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

14997 lines
508KB

  1. /*
  2. * Catch v2.7.1
  3. * Generated: 2019-04-05 18:22:37.720122
  4. * ----------------------------------------------------------
  5. * This file has been merged from multiple headers. Please don't edit it directly
  6. * Copyright (c) 2019 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 7
  16. #define CATCH_VERSION_PATCH 1
  17. #ifdef __clang__
  18. # pragma clang system_header
  19. #elif defined __GNUC__
  20. # pragma GCC system_header
  21. #endif
  22. // start catch_suppress_warnings.h
  23. #ifdef __clang__
  24. # ifdef __ICC // icpc defines the __clang__ macro
  25. # pragma warning(push)
  26. # pragma warning(disable: 161 1682)
  27. # else // __ICC
  28. # pragma clang diagnostic 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. // Because REQUIREs trigger GCC's -Wparentheses, and because still
  35. // supported version of g++ have only buggy support for _Pragmas,
  36. // Wparentheses have to be suppressed globally.
  37. # pragma GCC diagnostic ignored "-Wparentheses" // See #674 for details
  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. // MSVC traditional preprocessor needs some workaround for __VA_ARGS__
  187. // _MSVC_TRADITIONAL == 0 means new conformant preprocessor
  188. // _MSVC_TRADITIONAL == 1 means old traditional non-conformant preprocessor
  189. # if !defined(_MSVC_TRADITIONAL) || (defined(_MSVC_TRADITIONAL) && _MSVC_TRADITIONAL)
  190. # define CATCH_INTERNAL_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
  191. # endif
  192. #endif // _MSC_VER
  193. ////////////////////////////////////////////////////////////////////////////////
  194. // Check if we are compiled with -fno-exceptions or equivalent
  195. #if defined(__EXCEPTIONS) || defined(__cpp_exceptions) || defined(_CPPUNWIND)
  196. # define CATCH_INTERNAL_CONFIG_EXCEPTIONS_ENABLED
  197. #endif
  198. ////////////////////////////////////////////////////////////////////////////////
  199. // DJGPP
  200. #ifdef __DJGPP__
  201. # define CATCH_INTERNAL_CONFIG_NO_WCHAR
  202. #endif // __DJGPP__
  203. ////////////////////////////////////////////////////////////////////////////////
  204. // Embarcadero C++Build
  205. #if defined(__BORLANDC__)
  206. #define CATCH_INTERNAL_CONFIG_POLYFILL_ISNAN
  207. #endif
  208. ////////////////////////////////////////////////////////////////////////////////
  209. // Use of __COUNTER__ is suppressed during code analysis in
  210. // CLion/AppCode 2017.2.x and former, because __COUNTER__ is not properly
  211. // handled by it.
  212. // Otherwise all supported compilers support COUNTER macro,
  213. // but user still might want to turn it off
  214. #if ( !defined(__JETBRAINS_IDE__) || __JETBRAINS_IDE__ >= 20170300L )
  215. #define CATCH_INTERNAL_CONFIG_COUNTER
  216. #endif
  217. ////////////////////////////////////////////////////////////////////////////////
  218. // Check if string_view is available and usable
  219. // The check is split apart to work around v140 (VS2015) preprocessor issue...
  220. #if defined(__has_include)
  221. #if __has_include(<string_view>) && defined(CATCH_CPP17_OR_GREATER)
  222. # define CATCH_INTERNAL_CONFIG_CPP17_STRING_VIEW
  223. #endif
  224. #endif
  225. ////////////////////////////////////////////////////////////////////////////////
  226. // Check if optional is available and usable
  227. #if defined(__has_include)
  228. # if __has_include(<optional>) && defined(CATCH_CPP17_OR_GREATER)
  229. # define CATCH_INTERNAL_CONFIG_CPP17_OPTIONAL
  230. # endif // __has_include(<optional>) && defined(CATCH_CPP17_OR_GREATER)
  231. #endif // __has_include
  232. ////////////////////////////////////////////////////////////////////////////////
  233. // Check if variant is available and usable
  234. #if defined(__has_include)
  235. # if __has_include(<variant>) && defined(CATCH_CPP17_OR_GREATER)
  236. # if defined(__clang__) && (__clang_major__ < 8)
  237. // work around clang bug with libstdc++ https://bugs.llvm.org/show_bug.cgi?id=31852
  238. // fix should be in clang 8, workaround in libstdc++ 8.2
  239. # include <ciso646>
  240. # if defined(__GLIBCXX__) && defined(_GLIBCXX_RELEASE) && (_GLIBCXX_RELEASE < 9)
  241. # define CATCH_CONFIG_NO_CPP17_VARIANT
  242. # else
  243. # define CATCH_INTERNAL_CONFIG_CPP17_VARIANT
  244. # endif // defined(__GLIBCXX__) && defined(_GLIBCXX_RELEASE) && (_GLIBCXX_RELEASE < 9)
  245. # else
  246. # define CATCH_INTERNAL_CONFIG_CPP17_VARIANT
  247. # endif // defined(__clang__) && (__clang_major__ < 8)
  248. # endif // __has_include(<variant>) && defined(CATCH_CPP17_OR_GREATER)
  249. #endif // __has_include
  250. #if defined(CATCH_INTERNAL_CONFIG_COUNTER) && !defined(CATCH_CONFIG_NO_COUNTER) && !defined(CATCH_CONFIG_COUNTER)
  251. # define CATCH_CONFIG_COUNTER
  252. #endif
  253. #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)
  254. # define CATCH_CONFIG_WINDOWS_SEH
  255. #endif
  256. // This is set by default, because we assume that unix compilers are posix-signal-compatible by default.
  257. #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)
  258. # define CATCH_CONFIG_POSIX_SIGNALS
  259. #endif
  260. // This is set by default, because we assume that compilers with no wchar_t support are just rare exceptions.
  261. #if !defined(CATCH_INTERNAL_CONFIG_NO_WCHAR) && !defined(CATCH_CONFIG_NO_WCHAR) && !defined(CATCH_CONFIG_WCHAR)
  262. # define CATCH_CONFIG_WCHAR
  263. #endif
  264. #if !defined(CATCH_INTERNAL_CONFIG_NO_CPP11_TO_STRING) && !defined(CATCH_CONFIG_NO_CPP11_TO_STRING) && !defined(CATCH_CONFIG_CPP11_TO_STRING)
  265. # define CATCH_CONFIG_CPP11_TO_STRING
  266. #endif
  267. #if defined(CATCH_INTERNAL_CONFIG_CPP17_OPTIONAL) && !defined(CATCH_CONFIG_NO_CPP17_OPTIONAL) && !defined(CATCH_CONFIG_CPP17_OPTIONAL)
  268. # define CATCH_CONFIG_CPP17_OPTIONAL
  269. #endif
  270. #if defined(CATCH_INTERNAL_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS) && !defined(CATCH_CONFIG_NO_CPP17_UNCAUGHT_EXCEPTIONS) && !defined(CATCH_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS)
  271. # define CATCH_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS
  272. #endif
  273. #if defined(CATCH_INTERNAL_CONFIG_CPP17_STRING_VIEW) && !defined(CATCH_CONFIG_NO_CPP17_STRING_VIEW) && !defined(CATCH_CONFIG_CPP17_STRING_VIEW)
  274. # define CATCH_CONFIG_CPP17_STRING_VIEW
  275. #endif
  276. #if defined(CATCH_INTERNAL_CONFIG_CPP17_VARIANT) && !defined(CATCH_CONFIG_NO_CPP17_VARIANT) && !defined(CATCH_CONFIG_CPP17_VARIANT)
  277. # define CATCH_CONFIG_CPP17_VARIANT
  278. #endif
  279. #if defined(CATCH_CONFIG_EXPERIMENTAL_REDIRECT)
  280. # define CATCH_INTERNAL_CONFIG_NEW_CAPTURE
  281. #endif
  282. #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)
  283. # define CATCH_CONFIG_NEW_CAPTURE
  284. #endif
  285. #if !defined(CATCH_INTERNAL_CONFIG_EXCEPTIONS_ENABLED) && !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
  286. # define CATCH_CONFIG_DISABLE_EXCEPTIONS
  287. #endif
  288. #if defined(CATCH_INTERNAL_CONFIG_POLYFILL_ISNAN) && !defined(CATCH_CONFIG_NO_POLYFILL_ISNAN) && !defined(CATCH_CONFIG_POLYFILL_ISNAN)
  289. # define CATCH_CONFIG_POLYFILL_ISNAN
  290. #endif
  291. #if !defined(CATCH_INTERNAL_SUPPRESS_PARENTHESES_WARNINGS)
  292. # define CATCH_INTERNAL_SUPPRESS_PARENTHESES_WARNINGS
  293. # define CATCH_INTERNAL_UNSUPPRESS_PARENTHESES_WARNINGS
  294. #endif
  295. #if !defined(CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS)
  296. # define CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS
  297. # define CATCH_INTERNAL_UNSUPPRESS_GLOBALS_WARNINGS
  298. #endif
  299. #if !defined(CATCH_INTERNAL_SUPPRESS_UNUSED_WARNINGS)
  300. # define CATCH_INTERNAL_SUPPRESS_UNUSED_WARNINGS
  301. # define CATCH_INTERNAL_UNSUPPRESS_UNUSED_WARNINGS
  302. #endif
  303. #if defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
  304. #define CATCH_TRY if ((true))
  305. #define CATCH_CATCH_ALL if ((false))
  306. #define CATCH_CATCH_ANON(type) if ((false))
  307. #else
  308. #define CATCH_TRY try
  309. #define CATCH_CATCH_ALL catch (...)
  310. #define CATCH_CATCH_ANON(type) catch (type)
  311. #endif
  312. #if defined(CATCH_INTERNAL_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR) && !defined(CATCH_CONFIG_NO_TRADITIONAL_MSVC_PREPROCESSOR) && !defined(CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR)
  313. #define CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
  314. #endif
  315. // end catch_compiler_capabilities.h
  316. #define INTERNAL_CATCH_UNIQUE_NAME_LINE2( name, line ) name##line
  317. #define INTERNAL_CATCH_UNIQUE_NAME_LINE( name, line ) INTERNAL_CATCH_UNIQUE_NAME_LINE2( name, line )
  318. #ifdef CATCH_CONFIG_COUNTER
  319. # define INTERNAL_CATCH_UNIQUE_NAME( name ) INTERNAL_CATCH_UNIQUE_NAME_LINE( name, __COUNTER__ )
  320. #else
  321. # define INTERNAL_CATCH_UNIQUE_NAME( name ) INTERNAL_CATCH_UNIQUE_NAME_LINE( name, __LINE__ )
  322. #endif
  323. #include <iosfwd>
  324. #include <string>
  325. #include <cstdint>
  326. // We need a dummy global operator<< so we can bring it into Catch namespace later
  327. struct Catch_global_namespace_dummy {};
  328. std::ostream& operator<<(std::ostream&, Catch_global_namespace_dummy);
  329. namespace Catch {
  330. struct CaseSensitive { enum Choice {
  331. Yes,
  332. No
  333. }; };
  334. class NonCopyable {
  335. NonCopyable( NonCopyable const& ) = delete;
  336. NonCopyable( NonCopyable && ) = delete;
  337. NonCopyable& operator = ( NonCopyable const& ) = delete;
  338. NonCopyable& operator = ( NonCopyable && ) = delete;
  339. protected:
  340. NonCopyable();
  341. virtual ~NonCopyable();
  342. };
  343. struct SourceLineInfo {
  344. SourceLineInfo() = delete;
  345. SourceLineInfo( char const* _file, std::size_t _line ) noexcept
  346. : file( _file ),
  347. line( _line )
  348. {}
  349. SourceLineInfo( SourceLineInfo const& other ) = default;
  350. SourceLineInfo& operator = ( SourceLineInfo const& ) = default;
  351. SourceLineInfo( SourceLineInfo&& ) noexcept = default;
  352. SourceLineInfo& operator = ( SourceLineInfo&& ) noexcept = default;
  353. bool empty() const noexcept;
  354. bool operator == ( SourceLineInfo const& other ) const noexcept;
  355. bool operator < ( SourceLineInfo const& other ) const noexcept;
  356. char const* file;
  357. std::size_t line;
  358. };
  359. std::ostream& operator << ( std::ostream& os, SourceLineInfo const& info );
  360. // Bring in operator<< from global namespace into Catch namespace
  361. // This is necessary because the overload of operator<< above makes
  362. // lookup stop at namespace Catch
  363. using ::operator<<;
  364. // Use this in variadic streaming macros to allow
  365. // >> +StreamEndStop
  366. // as well as
  367. // >> stuff +StreamEndStop
  368. struct StreamEndStop {
  369. std::string operator+() const;
  370. };
  371. template<typename T>
  372. T const& operator + ( T const& value, StreamEndStop ) {
  373. return value;
  374. }
  375. }
  376. #define CATCH_INTERNAL_LINEINFO \
  377. ::Catch::SourceLineInfo( __FILE__, static_cast<std::size_t>( __LINE__ ) )
  378. // end catch_common.h
  379. namespace Catch {
  380. struct RegistrarForTagAliases {
  381. RegistrarForTagAliases( char const* alias, char const* tag, SourceLineInfo const& lineInfo );
  382. };
  383. } // end namespace Catch
  384. #define CATCH_REGISTER_TAG_ALIAS( alias, spec ) \
  385. CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
  386. namespace{ Catch::RegistrarForTagAliases INTERNAL_CATCH_UNIQUE_NAME( AutoRegisterTagAlias )( alias, spec, CATCH_INTERNAL_LINEINFO ); } \
  387. CATCH_INTERNAL_UNSUPPRESS_GLOBALS_WARNINGS
  388. // end catch_tag_alias_autoregistrar.h
  389. // start catch_test_registry.h
  390. // start catch_interfaces_testcase.h
  391. #include <vector>
  392. namespace Catch {
  393. class TestSpec;
  394. struct ITestInvoker {
  395. virtual void invoke () const = 0;
  396. virtual ~ITestInvoker();
  397. };
  398. class TestCase;
  399. struct IConfig;
  400. struct ITestCaseRegistry {
  401. virtual ~ITestCaseRegistry();
  402. virtual std::vector<TestCase> const& getAllTests() const = 0;
  403. virtual std::vector<TestCase> const& getAllTestsSorted( IConfig const& config ) const = 0;
  404. };
  405. bool matchTest( TestCase const& testCase, TestSpec const& testSpec, IConfig const& config );
  406. std::vector<TestCase> filterTests( std::vector<TestCase> const& testCases, TestSpec const& testSpec, IConfig const& config );
  407. std::vector<TestCase> const& getAllTestCasesSorted( IConfig const& config );
  408. }
  409. // end catch_interfaces_testcase.h
  410. // start catch_stringref.h
  411. #include <cstddef>
  412. #include <string>
  413. #include <iosfwd>
  414. namespace Catch {
  415. /// A non-owning string class (similar to the forthcoming std::string_view)
  416. /// Note that, because a StringRef may be a substring of another string,
  417. /// it may not be null terminated. c_str() must return a null terminated
  418. /// string, however, and so the StringRef will internally take ownership
  419. /// (taking a copy), if necessary. In theory this ownership is not externally
  420. /// visible - but it does mean (substring) StringRefs should not be shared between
  421. /// threads.
  422. class StringRef {
  423. public:
  424. using size_type = std::size_t;
  425. private:
  426. friend struct StringRefTestAccess;
  427. char const* m_start;
  428. size_type m_size;
  429. char* m_data = nullptr;
  430. void takeOwnership();
  431. static constexpr char const* const s_empty = "";
  432. public: // construction/ assignment
  433. StringRef() noexcept
  434. : StringRef( s_empty, 0 )
  435. {}
  436. StringRef( StringRef const& other ) noexcept
  437. : m_start( other.m_start ),
  438. m_size( other.m_size )
  439. {}
  440. StringRef( StringRef&& other ) noexcept
  441. : m_start( other.m_start ),
  442. m_size( other.m_size ),
  443. m_data( other.m_data )
  444. {
  445. other.m_data = nullptr;
  446. }
  447. StringRef( char const* rawChars ) noexcept;
  448. StringRef( char const* rawChars, size_type size ) noexcept
  449. : m_start( rawChars ),
  450. m_size( size )
  451. {}
  452. StringRef( std::string const& stdString ) noexcept
  453. : m_start( stdString.c_str() ),
  454. m_size( stdString.size() )
  455. {}
  456. ~StringRef() noexcept {
  457. delete[] m_data;
  458. }
  459. auto operator = ( StringRef const &other ) noexcept -> StringRef& {
  460. delete[] m_data;
  461. m_data = nullptr;
  462. m_start = other.m_start;
  463. m_size = other.m_size;
  464. return *this;
  465. }
  466. operator std::string() const;
  467. void swap( StringRef& other ) noexcept;
  468. public: // operators
  469. auto operator == ( StringRef const& other ) const noexcept -> bool;
  470. auto operator != ( StringRef const& other ) const noexcept -> bool;
  471. auto operator[] ( size_type index ) const noexcept -> char;
  472. public: // named queries
  473. auto empty() const noexcept -> bool {
  474. return m_size == 0;
  475. }
  476. auto size() const noexcept -> size_type {
  477. return m_size;
  478. }
  479. auto numberOfCharacters() const noexcept -> size_type;
  480. auto c_str() const -> char const*;
  481. public: // substrings and searches
  482. auto substr( size_type start, size_type size ) const noexcept -> StringRef;
  483. // Returns the current start pointer.
  484. // Note that the pointer can change when if the StringRef is a substring
  485. auto currentData() const noexcept -> char const*;
  486. private: // ownership queries - may not be consistent between calls
  487. auto isOwned() const noexcept -> bool;
  488. auto isSubstring() const noexcept -> bool;
  489. };
  490. auto operator + ( StringRef const& lhs, StringRef const& rhs ) -> std::string;
  491. auto operator + ( StringRef const& lhs, char const* rhs ) -> std::string;
  492. auto operator + ( char const* lhs, StringRef const& rhs ) -> std::string;
  493. auto operator += ( std::string& lhs, StringRef const& sr ) -> std::string&;
  494. auto operator << ( std::ostream& os, StringRef const& sr ) -> std::ostream&;
  495. inline auto operator "" _sr( char const* rawChars, std::size_t size ) noexcept -> StringRef {
  496. return StringRef( rawChars, size );
  497. }
  498. } // namespace Catch
  499. inline auto operator "" _catch_sr( char const* rawChars, std::size_t size ) noexcept -> Catch::StringRef {
  500. return Catch::StringRef( rawChars, size );
  501. }
  502. // end catch_stringref.h
  503. // start catch_type_traits.hpp
  504. #include <type_traits>
  505. namespace Catch{
  506. #ifdef CATCH_CPP17_OR_GREATER
  507. template <typename...>
  508. inline constexpr auto is_unique = std::true_type{};
  509. template <typename T, typename... Rest>
  510. inline constexpr auto is_unique<T, Rest...> = std::bool_constant<
  511. (!std::is_same_v<T, Rest> && ...) && is_unique<Rest...>
  512. >{};
  513. #else
  514. template <typename...>
  515. struct is_unique : std::true_type{};
  516. template <typename T0, typename T1, typename... Rest>
  517. struct is_unique<T0, T1, Rest...> : std::integral_constant
  518. <bool,
  519. !std::is_same<T0, T1>::value
  520. && is_unique<T0, Rest...>::value
  521. && is_unique<T1, Rest...>::value
  522. >{};
  523. #endif
  524. }
  525. // end catch_type_traits.hpp
  526. // start catch_preprocessor.hpp
  527. #define CATCH_RECURSION_LEVEL0(...) __VA_ARGS__
  528. #define CATCH_RECURSION_LEVEL1(...) CATCH_RECURSION_LEVEL0(CATCH_RECURSION_LEVEL0(CATCH_RECURSION_LEVEL0(__VA_ARGS__)))
  529. #define CATCH_RECURSION_LEVEL2(...) CATCH_RECURSION_LEVEL1(CATCH_RECURSION_LEVEL1(CATCH_RECURSION_LEVEL1(__VA_ARGS__)))
  530. #define CATCH_RECURSION_LEVEL3(...) CATCH_RECURSION_LEVEL2(CATCH_RECURSION_LEVEL2(CATCH_RECURSION_LEVEL2(__VA_ARGS__)))
  531. #define CATCH_RECURSION_LEVEL4(...) CATCH_RECURSION_LEVEL3(CATCH_RECURSION_LEVEL3(CATCH_RECURSION_LEVEL3(__VA_ARGS__)))
  532. #define CATCH_RECURSION_LEVEL5(...) CATCH_RECURSION_LEVEL4(CATCH_RECURSION_LEVEL4(CATCH_RECURSION_LEVEL4(__VA_ARGS__)))
  533. #ifdef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
  534. #define INTERNAL_CATCH_EXPAND_VARGS(...) __VA_ARGS__
  535. // MSVC needs more evaluations
  536. #define CATCH_RECURSION_LEVEL6(...) CATCH_RECURSION_LEVEL5(CATCH_RECURSION_LEVEL5(CATCH_RECURSION_LEVEL5(__VA_ARGS__)))
  537. #define CATCH_RECURSE(...) CATCH_RECURSION_LEVEL6(CATCH_RECURSION_LEVEL6(__VA_ARGS__))
  538. #else
  539. #define CATCH_RECURSE(...) CATCH_RECURSION_LEVEL5(__VA_ARGS__)
  540. #endif
  541. #define CATCH_REC_END(...)
  542. #define CATCH_REC_OUT
  543. #define CATCH_EMPTY()
  544. #define CATCH_DEFER(id) id CATCH_EMPTY()
  545. #define CATCH_REC_GET_END2() 0, CATCH_REC_END
  546. #define CATCH_REC_GET_END1(...) CATCH_REC_GET_END2
  547. #define CATCH_REC_GET_END(...) CATCH_REC_GET_END1
  548. #define CATCH_REC_NEXT0(test, next, ...) next CATCH_REC_OUT
  549. #define CATCH_REC_NEXT1(test, next) CATCH_DEFER ( CATCH_REC_NEXT0 ) ( test, next, 0)
  550. #define CATCH_REC_NEXT(test, next) CATCH_REC_NEXT1(CATCH_REC_GET_END test, next)
  551. #define CATCH_REC_LIST0(f, x, peek, ...) , f(x) CATCH_DEFER ( CATCH_REC_NEXT(peek, CATCH_REC_LIST1) ) ( f, peek, __VA_ARGS__ )
  552. #define CATCH_REC_LIST1(f, x, peek, ...) , f(x) CATCH_DEFER ( CATCH_REC_NEXT(peek, CATCH_REC_LIST0) ) ( f, peek, __VA_ARGS__ )
  553. #define CATCH_REC_LIST2(f, x, peek, ...) f(x) CATCH_DEFER ( CATCH_REC_NEXT(peek, CATCH_REC_LIST1) ) ( f, peek, __VA_ARGS__ )
  554. #define CATCH_REC_LIST0_UD(f, userdata, x, peek, ...) , f(userdata, x) CATCH_DEFER ( CATCH_REC_NEXT(peek, CATCH_REC_LIST1_UD) ) ( f, userdata, peek, __VA_ARGS__ )
  555. #define CATCH_REC_LIST1_UD(f, userdata, x, peek, ...) , f(userdata, x) CATCH_DEFER ( CATCH_REC_NEXT(peek, CATCH_REC_LIST0_UD) ) ( f, userdata, peek, __VA_ARGS__ )
  556. #define CATCH_REC_LIST2_UD(f, userdata, x, peek, ...) f(userdata, x) CATCH_DEFER ( CATCH_REC_NEXT(peek, CATCH_REC_LIST1_UD) ) ( f, userdata, peek, __VA_ARGS__ )
  557. // Applies the function macro `f` to each of the remaining parameters, inserts commas between the results,
  558. // and passes userdata as the first parameter to each invocation,
  559. // e.g. CATCH_REC_LIST_UD(f, x, a, b, c) evaluates to f(x, a), f(x, b), f(x, c)
  560. #define CATCH_REC_LIST_UD(f, userdata, ...) CATCH_RECURSE(CATCH_REC_LIST2_UD(f, userdata, __VA_ARGS__, ()()(), ()()(), ()()(), 0))
  561. #define CATCH_REC_LIST(f, ...) CATCH_RECURSE(CATCH_REC_LIST2(f, __VA_ARGS__, ()()(), ()()(), ()()(), 0))
  562. #define INTERNAL_CATCH_EXPAND1(param) INTERNAL_CATCH_EXPAND2(param)
  563. #define INTERNAL_CATCH_EXPAND2(...) INTERNAL_CATCH_NO## __VA_ARGS__
  564. #define INTERNAL_CATCH_DEF(...) INTERNAL_CATCH_DEF __VA_ARGS__
  565. #define INTERNAL_CATCH_NOINTERNAL_CATCH_DEF
  566. #define INTERNAL_CATCH_STRINGIZE(...) INTERNAL_CATCH_STRINGIZE2(__VA_ARGS__)
  567. #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
  568. #define INTERNAL_CATCH_STRINGIZE2(...) #__VA_ARGS__
  569. #define INTERNAL_CATCH_STRINGIZE_WITHOUT_PARENS(param) INTERNAL_CATCH_STRINGIZE(INTERNAL_CATCH_REMOVE_PARENS(param))
  570. #else
  571. // MSVC is adding extra space and needs another indirection to expand INTERNAL_CATCH_NOINTERNAL_CATCH_DEF
  572. #define INTERNAL_CATCH_STRINGIZE2(...) INTERNAL_CATCH_STRINGIZE3(__VA_ARGS__)
  573. #define INTERNAL_CATCH_STRINGIZE3(...) #__VA_ARGS__
  574. #define INTERNAL_CATCH_STRINGIZE_WITHOUT_PARENS(param) (INTERNAL_CATCH_STRINGIZE(INTERNAL_CATCH_REMOVE_PARENS(param)) + 1)
  575. #endif
  576. #define INTERNAL_CATCH_REMOVE_PARENS(...) INTERNAL_CATCH_EXPAND1(INTERNAL_CATCH_DEF __VA_ARGS__)
  577. #define INTERNAL_CATCH_TEMPLATE_UNIQUE_NAME2(Name, ...) INTERNAL_CATCH_TEMPLATE_UNIQUE_NAME3(Name, __VA_ARGS__)
  578. #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
  579. #define INTERNAL_CATCH_TEMPLATE_UNIQUE_NAME3(Name,...) Name " - " #__VA_ARGS__
  580. #define INTERNAL_CATCH_TEMPLATE_UNIQUE_NAME(Name,...) INTERNAL_CATCH_TEMPLATE_UNIQUE_NAME2(Name, INTERNAL_CATCH_REMOVE_PARENS(__VA_ARGS__))
  581. #else
  582. // MSVC is adding extra space and needs more calls to properly remove ()
  583. #define INTERNAL_CATCH_TEMPLATE_UNIQUE_NAME3(Name,...) Name " -" #__VA_ARGS__
  584. #define INTERNAL_CATCH_TEMPLATE_UNIQUE_NAME1(Name, ...) INTERNAL_CATCH_TEMPLATE_UNIQUE_NAME2(Name, __VA_ARGS__)
  585. #define INTERNAL_CATCH_TEMPLATE_UNIQUE_NAME(Name, ...) INTERNAL_CATCH_TEMPLATE_UNIQUE_NAME1(Name, INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_REMOVE_PARENS(__VA_ARGS__)))
  586. #endif
  587. #define INTERNAL_CATCH_MAKE_TYPE_LIST(types) Catch::TypeList<INTERNAL_CATCH_REMOVE_PARENS(types)>
  588. #define INTERNAL_CATCH_MAKE_TYPE_LISTS_FROM_TYPES(types)\
  589. CATCH_REC_LIST(INTERNAL_CATCH_MAKE_TYPE_LIST,INTERNAL_CATCH_REMOVE_PARENS(types))
  590. // end catch_preprocessor.hpp
  591. // start catch_meta.hpp
  592. #include <type_traits>
  593. namespace Catch {
  594. template< typename... >
  595. struct TypeList {};
  596. template< typename... >
  597. struct append;
  598. template< template<typename...> class L1
  599. , typename...E1
  600. , template<typename...> class L2
  601. , typename...E2
  602. >
  603. struct append< L1<E1...>, L2<E2...> > {
  604. using type = L1<E1..., E2...>;
  605. };
  606. template< template<typename...> class L1
  607. , typename...E1
  608. , template<typename...> class L2
  609. , typename...E2
  610. , typename...Rest
  611. >
  612. struct append< L1<E1...>, L2<E2...>, Rest...> {
  613. using type = typename append< L1<E1..., E2...>, Rest... >::type;
  614. };
  615. template< template<typename...> class
  616. , typename...
  617. >
  618. struct rewrap;
  619. template< template<typename...> class Container
  620. , template<typename...> class List
  621. , typename...elems
  622. >
  623. struct rewrap<Container, List<elems...>> {
  624. using type = TypeList< Container< elems... > >;
  625. };
  626. template< template<typename...> class Container
  627. , template<typename...> class List
  628. , class...Elems
  629. , typename...Elements>
  630. struct rewrap<Container, List<Elems...>, Elements...> {
  631. using type = typename append<TypeList<Container<Elems...>>, typename rewrap<Container, Elements...>::type>::type;
  632. };
  633. template< template<typename...> class...Containers >
  634. struct combine {
  635. template< typename...Types >
  636. struct with_types {
  637. template< template <typename...> class Final >
  638. struct into {
  639. using type = typename append<Final<>, typename rewrap<Containers, Types...>::type...>::type;
  640. };
  641. };
  642. };
  643. template<typename T>
  644. struct always_false : std::false_type {};
  645. } // namespace Catch
  646. // end catch_meta.hpp
  647. namespace Catch {
  648. template<typename C>
  649. class TestInvokerAsMethod : public ITestInvoker {
  650. void (C::*m_testAsMethod)();
  651. public:
  652. TestInvokerAsMethod( void (C::*testAsMethod)() ) noexcept : m_testAsMethod( testAsMethod ) {}
  653. void invoke() const override {
  654. C obj;
  655. (obj.*m_testAsMethod)();
  656. }
  657. };
  658. auto makeTestInvoker( void(*testAsFunction)() ) noexcept -> ITestInvoker*;
  659. template<typename C>
  660. auto makeTestInvoker( void (C::*testAsMethod)() ) noexcept -> ITestInvoker* {
  661. return new(std::nothrow) TestInvokerAsMethod<C>( testAsMethod );
  662. }
  663. struct NameAndTags {
  664. NameAndTags( StringRef const& name_ = StringRef(), StringRef const& tags_ = StringRef() ) noexcept;
  665. StringRef name;
  666. StringRef tags;
  667. };
  668. struct AutoReg : NonCopyable {
  669. AutoReg( ITestInvoker* invoker, SourceLineInfo const& lineInfo, StringRef const& classOrMethod, NameAndTags const& nameAndTags ) noexcept;
  670. ~AutoReg();
  671. };
  672. } // end namespace Catch
  673. #if defined(CATCH_CONFIG_DISABLE)
  674. #define INTERNAL_CATCH_TESTCASE_NO_REGISTRATION( TestName, ... ) \
  675. static void TestName()
  676. #define INTERNAL_CATCH_TESTCASE_METHOD_NO_REGISTRATION( TestName, ClassName, ... ) \
  677. namespace{ \
  678. struct TestName : INTERNAL_CATCH_REMOVE_PARENS(ClassName) { \
  679. void test(); \
  680. }; \
  681. } \
  682. void TestName::test()
  683. #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION( TestName, ... ) \
  684. template<typename TestType> \
  685. static void TestName()
  686. #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION( TestName, ClassName, ... ) \
  687. namespace{ \
  688. template<typename TestType> \
  689. struct TestName : INTERNAL_CATCH_REMOVE_PARENS(ClassName <TestType>) { \
  690. void test(); \
  691. }; \
  692. } \
  693. template<typename TestType> \
  694. void TestName::test()
  695. #endif
  696. ///////////////////////////////////////////////////////////////////////////////
  697. #define INTERNAL_CATCH_TESTCASE2( TestName, ... ) \
  698. static void TestName(); \
  699. CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
  700. namespace{ Catch::AutoReg INTERNAL_CATCH_UNIQUE_NAME( autoRegistrar )( Catch::makeTestInvoker( &TestName ), CATCH_INTERNAL_LINEINFO, Catch::StringRef(), Catch::NameAndTags{ __VA_ARGS__ } ); } /* NOLINT */ \
  701. CATCH_INTERNAL_UNSUPPRESS_GLOBALS_WARNINGS \
  702. static void TestName()
  703. #define INTERNAL_CATCH_TESTCASE( ... ) \
  704. INTERNAL_CATCH_TESTCASE2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ), __VA_ARGS__ )
  705. ///////////////////////////////////////////////////////////////////////////////
  706. #define INTERNAL_CATCH_METHOD_AS_TEST_CASE( QualifiedMethod, ... ) \
  707. CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
  708. namespace{ Catch::AutoReg INTERNAL_CATCH_UNIQUE_NAME( autoRegistrar )( Catch::makeTestInvoker( &QualifiedMethod ), CATCH_INTERNAL_LINEINFO, "&" #QualifiedMethod, Catch::NameAndTags{ __VA_ARGS__ } ); } /* NOLINT */ \
  709. CATCH_INTERNAL_UNSUPPRESS_GLOBALS_WARNINGS
  710. ///////////////////////////////////////////////////////////////////////////////
  711. #define INTERNAL_CATCH_TEST_CASE_METHOD2( TestName, ClassName, ... )\
  712. CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
  713. namespace{ \
  714. struct TestName : INTERNAL_CATCH_REMOVE_PARENS(ClassName) { \
  715. void test(); \
  716. }; \
  717. Catch::AutoReg INTERNAL_CATCH_UNIQUE_NAME( autoRegistrar ) ( Catch::makeTestInvoker( &TestName::test ), CATCH_INTERNAL_LINEINFO, #ClassName, Catch::NameAndTags{ __VA_ARGS__ } ); /* NOLINT */ \
  718. } \
  719. CATCH_INTERNAL_UNSUPPRESS_GLOBALS_WARNINGS \
  720. void TestName::test()
  721. #define INTERNAL_CATCH_TEST_CASE_METHOD( ClassName, ... ) \
  722. INTERNAL_CATCH_TEST_CASE_METHOD2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ), ClassName, __VA_ARGS__ )
  723. ///////////////////////////////////////////////////////////////////////////////
  724. #define INTERNAL_CATCH_REGISTER_TESTCASE( Function, ... ) \
  725. CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
  726. Catch::AutoReg INTERNAL_CATCH_UNIQUE_NAME( autoRegistrar )( Catch::makeTestInvoker( Function ), CATCH_INTERNAL_LINEINFO, Catch::StringRef(), Catch::NameAndTags{ __VA_ARGS__ } ); /* NOLINT */ \
  727. CATCH_INTERNAL_UNSUPPRESS_GLOBALS_WARNINGS
  728. ///////////////////////////////////////////////////////////////////////////////
  729. #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_2(TestName, TestFunc, Name, Tags, ... )\
  730. CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
  731. template<typename TestType> \
  732. static void TestFunc();\
  733. namespace {\
  734. template<typename...Types> \
  735. struct TestName{\
  736. template<typename...Ts> \
  737. TestName(Ts...names){\
  738. CATCH_INTERNAL_CHECK_UNIQUE_TYPES(CATCH_REC_LIST(INTERNAL_CATCH_REMOVE_PARENS, __VA_ARGS__)) \
  739. using expander = int[];\
  740. (void)expander{(Catch::AutoReg( Catch::makeTestInvoker( &TestFunc<Types> ), CATCH_INTERNAL_LINEINFO, Catch::StringRef(), Catch::NameAndTags{ names, Tags } ), 0)... };/* NOLINT */ \
  741. }\
  742. };\
  743. INTERNAL_CATCH_TEMPLATE_REGISTRY_INITIATE(TestName, Name, __VA_ARGS__) \
  744. }\
  745. CATCH_INTERNAL_UNSUPPRESS_GLOBALS_WARNINGS \
  746. template<typename TestType> \
  747. static void TestFunc()
  748. #if defined(CATCH_CPP17_OR_GREATER)
  749. #define CATCH_INTERNAL_CHECK_UNIQUE_TYPES(...) static_assert(Catch::is_unique<__VA_ARGS__>,"Duplicate type detected in declaration of template test case");
  750. #else
  751. #define CATCH_INTERNAL_CHECK_UNIQUE_TYPES(...) static_assert(Catch::is_unique<__VA_ARGS__>::value,"Duplicate type detected in declaration of template test case");
  752. #endif
  753. #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
  754. #define INTERNAL_CATCH_TEMPLATE_TEST_CASE(Name, Tags, ...) \
  755. INTERNAL_CATCH_TEMPLATE_TEST_CASE_2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____F_U_N_C____ ), Name, Tags, __VA_ARGS__ )
  756. #else
  757. #define INTERNAL_CATCH_TEMPLATE_TEST_CASE(Name, Tags, ...) \
  758. INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____F_U_N_C____ ), Name, Tags, __VA_ARGS__ ) )
  759. #endif
  760. #define INTERNAL_CATCH_TEMPLATE_REGISTRY_INITIATE(TestName, Name, ...)\
  761. static int INTERNAL_CATCH_UNIQUE_NAME( globalRegistrar ) = [](){\
  762. TestName<CATCH_REC_LIST(INTERNAL_CATCH_REMOVE_PARENS, __VA_ARGS__)>(CATCH_REC_LIST_UD(INTERNAL_CATCH_TEMPLATE_UNIQUE_NAME,Name, __VA_ARGS__));\
  763. return 0;\
  764. }();
  765. #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE2(TestName, TestFuncName, Name, Tags, TmplTypes, TypesList) \
  766. CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
  767. template<typename TestType> static void TestFuncName(); \
  768. namespace { \
  769. template<typename... Types> \
  770. struct TestName { \
  771. TestName() { \
  772. CATCH_INTERNAL_CHECK_UNIQUE_TYPES(Types...) \
  773. int index = 0; \
  774. using expander = int[]; \
  775. constexpr char const* tmpl_types[] = {CATCH_REC_LIST(INTERNAL_CATCH_STRINGIZE_WITHOUT_PARENS, INTERNAL_CATCH_REMOVE_PARENS(TmplTypes))};\
  776. constexpr char const* types_list[] = {CATCH_REC_LIST(INTERNAL_CATCH_STRINGIZE_WITHOUT_PARENS, INTERNAL_CATCH_REMOVE_PARENS(TypesList))};\
  777. constexpr auto num_types = sizeof(types_list) / sizeof(types_list[0]);\
  778. (void)expander{(Catch::AutoReg( Catch::makeTestInvoker( &TestFuncName<Types> ), CATCH_INTERNAL_LINEINFO, Catch::StringRef(), Catch::NameAndTags{ Name " - " + std::string(tmpl_types[index / num_types]) + "<" + std::string(types_list[index % num_types]) + ">", Tags } ), index++, 0)... };/* NOLINT */\
  779. } \
  780. }; \
  781. static int INTERNAL_CATCH_UNIQUE_NAME( globalRegistrar ) = [](){ \
  782. using TestInit = Catch::combine<INTERNAL_CATCH_REMOVE_PARENS(TmplTypes)> \
  783. ::with_types<INTERNAL_CATCH_MAKE_TYPE_LISTS_FROM_TYPES(TypesList)>::into<TestName>::type; \
  784. TestInit(); \
  785. return 0; \
  786. }(); \
  787. } \
  788. CATCH_INTERNAL_UNSUPPRESS_GLOBALS_WARNINGS \
  789. template<typename TestType> \
  790. static void TestFuncName()
  791. #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
  792. #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE(Name, Tags, ...)\
  793. INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE2(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____F_U_N_C____ ),Name,Tags,__VA_ARGS__)
  794. #else
  795. #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE(Name, Tags, ...)\
  796. INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____F_U_N_C____ ), Name, Tags, __VA_ARGS__ ) )
  797. #endif
  798. #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_2( TestNameClass, TestName, ClassName, Name, Tags, ... ) \
  799. CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
  800. namespace{ \
  801. template<typename TestType> \
  802. struct TestName : INTERNAL_CATCH_REMOVE_PARENS(ClassName <TestType>) { \
  803. void test();\
  804. };\
  805. template<typename...Types> \
  806. struct TestNameClass{\
  807. template<typename...Ts> \
  808. TestNameClass(Ts...names){\
  809. CATCH_INTERNAL_CHECK_UNIQUE_TYPES(CATCH_REC_LIST(INTERNAL_CATCH_REMOVE_PARENS, __VA_ARGS__)) \
  810. using expander = int[];\
  811. (void)expander{(Catch::AutoReg( Catch::makeTestInvoker( &TestName<Types>::test ), CATCH_INTERNAL_LINEINFO, #ClassName, Catch::NameAndTags{ names, Tags } ), 0)... };/* NOLINT */ \
  812. }\
  813. };\
  814. INTERNAL_CATCH_TEMPLATE_REGISTRY_INITIATE(TestNameClass, Name, __VA_ARGS__)\
  815. }\
  816. CATCH_INTERNAL_UNSUPPRESS_GLOBALS_WARNINGS\
  817. template<typename TestType> \
  818. void TestName<TestType>::test()
  819. #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
  820. #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD( ClassName, Name, Tags,... ) \
  821. INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____C_L_A_S_S____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ) , ClassName, Name, Tags, __VA_ARGS__ )
  822. #else
  823. #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD( ClassName, Name, Tags,... ) \
  824. INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____C_L_A_S_S____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ) , ClassName, Name, Tags, __VA_ARGS__ ) )
  825. #endif
  826. #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_2(TestNameClass, TestName, ClassName, Name, Tags, TmplTypes, TypesList)\
  827. CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
  828. template<typename TestType> \
  829. struct TestName : INTERNAL_CATCH_REMOVE_PARENS(ClassName <TestType>) { \
  830. void test();\
  831. };\
  832. namespace {\
  833. template<typename...Types>\
  834. struct TestNameClass{\
  835. TestNameClass(){\
  836. CATCH_INTERNAL_CHECK_UNIQUE_TYPES(Types...)\
  837. int index = 0;\
  838. using expander = int[];\
  839. constexpr char const* tmpl_types[] = {CATCH_REC_LIST(INTERNAL_CATCH_STRINGIZE_WITHOUT_PARENS, INTERNAL_CATCH_REMOVE_PARENS(TmplTypes))};\
  840. constexpr char const* types_list[] = {CATCH_REC_LIST(INTERNAL_CATCH_STRINGIZE_WITHOUT_PARENS, INTERNAL_CATCH_REMOVE_PARENS(TypesList))};\
  841. constexpr auto num_types = sizeof(types_list) / sizeof(types_list[0]);\
  842. (void)expander{(Catch::AutoReg( Catch::makeTestInvoker( &TestName<Types>::test ), CATCH_INTERNAL_LINEINFO, #ClassName, Catch::NameAndTags{ Name " - " + std::string(tmpl_types[index / num_types]) + "<" + std::string(types_list[index % num_types]) + ">", Tags } ), index++, 0)... };/* NOLINT */ \
  843. }\
  844. };\
  845. static int INTERNAL_CATCH_UNIQUE_NAME( globalRegistrar ) = [](){\
  846. using TestInit = Catch::combine<INTERNAL_CATCH_REMOVE_PARENS(TmplTypes)>\
  847. ::with_types<INTERNAL_CATCH_MAKE_TYPE_LISTS_FROM_TYPES(TypesList)>::into<TestNameClass>::type;\
  848. TestInit();\
  849. return 0;\
  850. }(); \
  851. }\
  852. CATCH_INTERNAL_UNSUPPRESS_GLOBALS_WARNINGS \
  853. template<typename TestType> \
  854. void TestName<TestType>::test()
  855. #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
  856. #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( ClassName, Name, Tags, ... )\
  857. INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____F_U_N_C____ ), ClassName, Name, Tags, __VA_ARGS__ )
  858. #else
  859. #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( ClassName, Name, Tags, ... )\
  860. INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____F_U_N_C____ ), ClassName, Name, Tags, __VA_ARGS__ ) )
  861. #endif
  862. // end catch_test_registry.h
  863. // start catch_capture.hpp
  864. // start catch_assertionhandler.h
  865. // start catch_assertioninfo.h
  866. // start catch_result_type.h
  867. namespace Catch {
  868. // ResultWas::OfType enum
  869. struct ResultWas { enum OfType {
  870. Unknown = -1,
  871. Ok = 0,
  872. Info = 1,
  873. Warning = 2,
  874. FailureBit = 0x10,
  875. ExpressionFailed = FailureBit | 1,
  876. ExplicitFailure = FailureBit | 2,
  877. Exception = 0x100 | FailureBit,
  878. ThrewException = Exception | 1,
  879. DidntThrowException = Exception | 2,
  880. FatalErrorCondition = 0x200 | FailureBit
  881. }; };
  882. bool isOk( ResultWas::OfType resultType );
  883. bool isJustInfo( int flags );
  884. // ResultDisposition::Flags enum
  885. struct ResultDisposition { enum Flags {
  886. Normal = 0x01,
  887. ContinueOnFailure = 0x02, // Failures fail test, but execution continues
  888. FalseTest = 0x04, // Prefix expression with !
  889. SuppressFail = 0x08 // Failures are reported but do not fail the test
  890. }; };
  891. ResultDisposition::Flags operator | ( ResultDisposition::Flags lhs, ResultDisposition::Flags rhs );
  892. bool shouldContinueOnFailure( int flags );
  893. inline bool isFalseTest( int flags ) { return ( flags & ResultDisposition::FalseTest ) != 0; }
  894. bool shouldSuppressFailure( int flags );
  895. } // end namespace Catch
  896. // end catch_result_type.h
  897. namespace Catch {
  898. struct AssertionInfo
  899. {
  900. StringRef macroName;
  901. SourceLineInfo lineInfo;
  902. StringRef capturedExpression;
  903. ResultDisposition::Flags resultDisposition;
  904. // We want to delete this constructor but a compiler bug in 4.8 means
  905. // the struct is then treated as non-aggregate
  906. //AssertionInfo() = delete;
  907. };
  908. } // end namespace Catch
  909. // end catch_assertioninfo.h
  910. // start catch_decomposer.h
  911. // start catch_tostring.h
  912. #include <vector>
  913. #include <cstddef>
  914. #include <type_traits>
  915. #include <string>
  916. // start catch_stream.h
  917. #include <iosfwd>
  918. #include <cstddef>
  919. #include <ostream>
  920. namespace Catch {
  921. std::ostream& cout();
  922. std::ostream& cerr();
  923. std::ostream& clog();
  924. class StringRef;
  925. struct IStream {
  926. virtual ~IStream();
  927. virtual std::ostream& stream() const = 0;
  928. };
  929. auto makeStream( StringRef const &filename ) -> IStream const*;
  930. class ReusableStringStream {
  931. std::size_t m_index;
  932. std::ostream* m_oss;
  933. public:
  934. ReusableStringStream();
  935. ~ReusableStringStream();
  936. auto str() const -> std::string;
  937. template<typename T>
  938. auto operator << ( T const& value ) -> ReusableStringStream& {
  939. *m_oss << value;
  940. return *this;
  941. }
  942. auto get() -> std::ostream& { return *m_oss; }
  943. };
  944. }
  945. // end catch_stream.h
  946. #ifdef CATCH_CONFIG_CPP17_STRING_VIEW
  947. #include <string_view>
  948. #endif
  949. #ifdef __OBJC__
  950. // start catch_objc_arc.hpp
  951. #import <Foundation/Foundation.h>
  952. #ifdef __has_feature
  953. #define CATCH_ARC_ENABLED __has_feature(objc_arc)
  954. #else
  955. #define CATCH_ARC_ENABLED 0
  956. #endif
  957. void arcSafeRelease( NSObject* obj );
  958. id performOptionalSelector( id obj, SEL sel );
  959. #if !CATCH_ARC_ENABLED
  960. inline void arcSafeRelease( NSObject* obj ) {
  961. [obj release];
  962. }
  963. inline id performOptionalSelector( id obj, SEL sel ) {
  964. if( [obj respondsToSelector: sel] )
  965. return [obj performSelector: sel];
  966. return nil;
  967. }
  968. #define CATCH_UNSAFE_UNRETAINED
  969. #define CATCH_ARC_STRONG
  970. #else
  971. inline void arcSafeRelease( NSObject* ){}
  972. inline id performOptionalSelector( id obj, SEL sel ) {
  973. #ifdef __clang__
  974. #pragma clang diagnostic push
  975. #pragma clang diagnostic ignored "-Warc-performSelector-leaks"
  976. #endif
  977. if( [obj respondsToSelector: sel] )
  978. return [obj performSelector: sel];
  979. #ifdef __clang__
  980. #pragma clang diagnostic pop
  981. #endif
  982. return nil;
  983. }
  984. #define CATCH_UNSAFE_UNRETAINED __unsafe_unretained
  985. #define CATCH_ARC_STRONG __strong
  986. #endif
  987. // end catch_objc_arc.hpp
  988. #endif
  989. #ifdef _MSC_VER
  990. #pragma warning(push)
  991. #pragma warning(disable:4180) // We attempt to stream a function (address) by const&, which MSVC complains about but is harmless
  992. #endif
  993. namespace Catch {
  994. namespace Detail {
  995. extern const std::string unprintableString;
  996. std::string rawMemoryToString( const void *object, std::size_t size );
  997. template<typename T>
  998. std::string rawMemoryToString( const T& object ) {
  999. return rawMemoryToString( &object, sizeof(object) );
  1000. }
  1001. template<typename T>
  1002. class IsStreamInsertable {
  1003. template<typename SS, typename TT>
  1004. static auto test(int)
  1005. -> decltype(std::declval<SS&>() << std::declval<TT>(), std::true_type());
  1006. template<typename, typename>
  1007. static auto test(...)->std::false_type;
  1008. public:
  1009. static const bool value = decltype(test<std::ostream, const T&>(0))::value;
  1010. };
  1011. template<typename E>
  1012. std::string convertUnknownEnumToString( E e );
  1013. template<typename T>
  1014. typename std::enable_if<
  1015. !std::is_enum<T>::value && !std::is_base_of<std::exception, T>::value,
  1016. std::string>::type convertUnstreamable( T const& ) {
  1017. return Detail::unprintableString;
  1018. }
  1019. template<typename T>
  1020. typename std::enable_if<
  1021. !std::is_enum<T>::value && std::is_base_of<std::exception, T>::value,
  1022. std::string>::type convertUnstreamable(T const& ex) {
  1023. return ex.what();
  1024. }
  1025. template<typename T>
  1026. typename std::enable_if<
  1027. std::is_enum<T>::value
  1028. , std::string>::type convertUnstreamable( T const& value ) {
  1029. return convertUnknownEnumToString( value );
  1030. }
  1031. #if defined(_MANAGED)
  1032. //! Convert a CLR string to a utf8 std::string
  1033. template<typename T>
  1034. std::string clrReferenceToString( T^ ref ) {
  1035. if (ref == nullptr)
  1036. return std::string("null");
  1037. auto bytes = System::Text::Encoding::UTF8->GetBytes(ref->ToString());
  1038. cli::pin_ptr<System::Byte> p = &bytes[0];
  1039. return std::string(reinterpret_cast<char const *>(p), bytes->Length);
  1040. }
  1041. #endif
  1042. } // namespace Detail
  1043. // If we decide for C++14, change these to enable_if_ts
  1044. template <typename T, typename = void>
  1045. struct StringMaker {
  1046. template <typename Fake = T>
  1047. static
  1048. typename std::enable_if<::Catch::Detail::IsStreamInsertable<Fake>::value, std::string>::type
  1049. convert(const Fake& value) {
  1050. ReusableStringStream rss;
  1051. // NB: call using the function-like syntax to avoid ambiguity with
  1052. // user-defined templated operator<< under clang.
  1053. rss.operator<<(value);
  1054. return rss.str();
  1055. }
  1056. template <typename Fake = T>
  1057. static
  1058. typename std::enable_if<!::Catch::Detail::IsStreamInsertable<Fake>::value, std::string>::type
  1059. convert( const Fake& value ) {
  1060. #if !defined(CATCH_CONFIG_FALLBACK_STRINGIFIER)
  1061. return Detail::convertUnstreamable(value);
  1062. #else
  1063. return CATCH_CONFIG_FALLBACK_STRINGIFIER(value);
  1064. #endif
  1065. }
  1066. };
  1067. namespace Detail {
  1068. // This function dispatches all stringification requests inside of Catch.
  1069. // Should be preferably called fully qualified, like ::Catch::Detail::stringify
  1070. template <typename T>
  1071. std::string stringify(const T& e) {
  1072. return ::Catch::StringMaker<typename std::remove_cv<typename std::remove_reference<T>::type>::type>::convert(e);
  1073. }
  1074. template<typename E>
  1075. std::string convertUnknownEnumToString( E e ) {
  1076. return ::Catch::Detail::stringify(static_cast<typename std::underlying_type<E>::type>(e));
  1077. }
  1078. #if defined(_MANAGED)
  1079. template <typename T>
  1080. std::string stringify( T^ e ) {
  1081. return ::Catch::StringMaker<T^>::convert(e);
  1082. }
  1083. #endif
  1084. } // namespace Detail
  1085. // Some predefined specializations
  1086. template<>
  1087. struct StringMaker<std::string> {
  1088. static std::string convert(const std::string& str);
  1089. };
  1090. #ifdef CATCH_CONFIG_CPP17_STRING_VIEW
  1091. template<>
  1092. struct StringMaker<std::string_view> {
  1093. static std::string convert(std::string_view str);
  1094. };
  1095. #endif
  1096. template<>
  1097. struct StringMaker<char const *> {
  1098. static std::string convert(char const * str);
  1099. };
  1100. template<>
  1101. struct StringMaker<char *> {
  1102. static std::string convert(char * str);
  1103. };
  1104. #ifdef CATCH_CONFIG_WCHAR
  1105. template<>
  1106. struct StringMaker<std::wstring> {
  1107. static std::string convert(const std::wstring& wstr);
  1108. };
  1109. # ifdef CATCH_CONFIG_CPP17_STRING_VIEW
  1110. template<>
  1111. struct StringMaker<std::wstring_view> {
  1112. static std::string convert(std::wstring_view str);
  1113. };
  1114. # endif
  1115. template<>
  1116. struct StringMaker<wchar_t const *> {
  1117. static std::string convert(wchar_t const * str);
  1118. };
  1119. template<>
  1120. struct StringMaker<wchar_t *> {
  1121. static std::string convert(wchar_t * str);
  1122. };
  1123. #endif
  1124. // TBD: Should we use `strnlen` to ensure that we don't go out of the buffer,
  1125. // while keeping string semantics?
  1126. template<int SZ>
  1127. struct StringMaker<char[SZ]> {
  1128. static std::string convert(char const* str) {
  1129. return ::Catch::Detail::stringify(std::string{ str });
  1130. }
  1131. };
  1132. template<int SZ>
  1133. struct StringMaker<signed char[SZ]> {
  1134. static std::string convert(signed char const* str) {
  1135. return ::Catch::Detail::stringify(std::string{ reinterpret_cast<char const *>(str) });
  1136. }
  1137. };
  1138. template<int SZ>
  1139. struct StringMaker<unsigned char[SZ]> {
  1140. static std::string convert(unsigned char const* str) {
  1141. return ::Catch::Detail::stringify(std::string{ reinterpret_cast<char const *>(str) });
  1142. }
  1143. };
  1144. template<>
  1145. struct StringMaker<int> {
  1146. static std::string convert(int value);
  1147. };
  1148. template<>
  1149. struct StringMaker<long> {
  1150. static std::string convert(long value);
  1151. };
  1152. template<>
  1153. struct StringMaker<long long> {
  1154. static std::string convert(long long value);
  1155. };
  1156. template<>
  1157. struct StringMaker<unsigned int> {
  1158. static std::string convert(unsigned int value);
  1159. };
  1160. template<>
  1161. struct StringMaker<unsigned long> {
  1162. static std::string convert(unsigned long value);
  1163. };
  1164. template<>
  1165. struct StringMaker<unsigned long long> {
  1166. static std::string convert(unsigned long long value);
  1167. };
  1168. template<>
  1169. struct StringMaker<bool> {
  1170. static std::string convert(bool b);
  1171. };
  1172. template<>
  1173. struct StringMaker<char> {
  1174. static std::string convert(char c);
  1175. };
  1176. template<>
  1177. struct StringMaker<signed char> {
  1178. static std::string convert(signed char c);
  1179. };
  1180. template<>
  1181. struct StringMaker<unsigned char> {
  1182. static std::string convert(unsigned char c);
  1183. };
  1184. template<>
  1185. struct StringMaker<std::nullptr_t> {
  1186. static std::string convert(std::nullptr_t);
  1187. };
  1188. template<>
  1189. struct StringMaker<float> {
  1190. static std::string convert(float value);
  1191. };
  1192. template<>
  1193. struct StringMaker<double> {
  1194. static std::string convert(double value);
  1195. };
  1196. template <typename T>
  1197. struct StringMaker<T*> {
  1198. template <typename U>
  1199. static std::string convert(U* p) {
  1200. if (p) {
  1201. return ::Catch::Detail::rawMemoryToString(p);
  1202. } else {
  1203. return "nullptr";
  1204. }
  1205. }
  1206. };
  1207. template <typename R, typename C>
  1208. struct StringMaker<R C::*> {
  1209. static std::string convert(R C::* p) {
  1210. if (p) {
  1211. return ::Catch::Detail::rawMemoryToString(p);
  1212. } else {
  1213. return "nullptr";
  1214. }
  1215. }
  1216. };
  1217. #if defined(_MANAGED)
  1218. template <typename T>
  1219. struct StringMaker<T^> {
  1220. static std::string convert( T^ ref ) {
  1221. return ::Catch::Detail::clrReferenceToString(ref);
  1222. }
  1223. };
  1224. #endif
  1225. namespace Detail {
  1226. template<typename InputIterator>
  1227. std::string rangeToString(InputIterator first, InputIterator last) {
  1228. ReusableStringStream rss;
  1229. rss << "{ ";
  1230. if (first != last) {
  1231. rss << ::Catch::Detail::stringify(*first);
  1232. for (++first; first != last; ++first)
  1233. rss << ", " << ::Catch::Detail::stringify(*first);
  1234. }
  1235. rss << " }";
  1236. return rss.str();
  1237. }
  1238. }
  1239. #ifdef __OBJC__
  1240. template<>
  1241. struct StringMaker<NSString*> {
  1242. static std::string convert(NSString * nsstring) {
  1243. if (!nsstring)
  1244. return "nil";
  1245. return std::string("@") + [nsstring UTF8String];
  1246. }
  1247. };
  1248. template<>
  1249. struct StringMaker<NSObject*> {
  1250. static std::string convert(NSObject* nsObject) {
  1251. return ::Catch::Detail::stringify([nsObject description]);
  1252. }
  1253. };
  1254. namespace Detail {
  1255. inline std::string stringify( NSString* nsstring ) {
  1256. return StringMaker<NSString*>::convert( nsstring );
  1257. }
  1258. } // namespace Detail
  1259. #endif // __OBJC__
  1260. } // namespace Catch
  1261. //////////////////////////////////////////////////////
  1262. // Separate std-lib types stringification, so it can be selectively enabled
  1263. // This means that we do not bring in
  1264. #if defined(CATCH_CONFIG_ENABLE_ALL_STRINGMAKERS)
  1265. # define CATCH_CONFIG_ENABLE_PAIR_STRINGMAKER
  1266. # define CATCH_CONFIG_ENABLE_TUPLE_STRINGMAKER
  1267. # define CATCH_CONFIG_ENABLE_VARIANT_STRINGMAKER
  1268. # define CATCH_CONFIG_ENABLE_CHRONO_STRINGMAKER
  1269. # define CATCH_CONFIG_ENABLE_OPTIONAL_STRINGMAKER
  1270. #endif
  1271. // Separate std::pair specialization
  1272. #if defined(CATCH_CONFIG_ENABLE_PAIR_STRINGMAKER)
  1273. #include <utility>
  1274. namespace Catch {
  1275. template<typename T1, typename T2>
  1276. struct StringMaker<std::pair<T1, T2> > {
  1277. static std::string convert(const std::pair<T1, T2>& pair) {
  1278. ReusableStringStream rss;
  1279. rss << "{ "
  1280. << ::Catch::Detail::stringify(pair.first)
  1281. << ", "
  1282. << ::Catch::Detail::stringify(pair.second)
  1283. << " }";
  1284. return rss.str();
  1285. }
  1286. };
  1287. }
  1288. #endif // CATCH_CONFIG_ENABLE_PAIR_STRINGMAKER
  1289. #if defined(CATCH_CONFIG_ENABLE_OPTIONAL_STRINGMAKER) && defined(CATCH_CONFIG_CPP17_OPTIONAL)
  1290. #include <optional>
  1291. namespace Catch {
  1292. template<typename T>
  1293. struct StringMaker<std::optional<T> > {
  1294. static std::string convert(const std::optional<T>& optional) {
  1295. ReusableStringStream rss;
  1296. if (optional.has_value()) {
  1297. rss << ::Catch::Detail::stringify(*optional);
  1298. } else {
  1299. rss << "{ }";
  1300. }
  1301. return rss.str();
  1302. }
  1303. };
  1304. }
  1305. #endif // CATCH_CONFIG_ENABLE_OPTIONAL_STRINGMAKER
  1306. // Separate std::tuple specialization
  1307. #if defined(CATCH_CONFIG_ENABLE_TUPLE_STRINGMAKER)
  1308. #include <tuple>
  1309. namespace Catch {
  1310. namespace Detail {
  1311. template<
  1312. typename Tuple,
  1313. std::size_t N = 0,
  1314. bool = (N < std::tuple_size<Tuple>::value)
  1315. >
  1316. struct TupleElementPrinter {
  1317. static void print(const Tuple& tuple, std::ostream& os) {
  1318. os << (N ? ", " : " ")
  1319. << ::Catch::Detail::stringify(std::get<N>(tuple));
  1320. TupleElementPrinter<Tuple, N + 1>::print(tuple, os);
  1321. }
  1322. };
  1323. template<
  1324. typename Tuple,
  1325. std::size_t N
  1326. >
  1327. struct TupleElementPrinter<Tuple, N, false> {
  1328. static void print(const Tuple&, std::ostream&) {}
  1329. };
  1330. }
  1331. template<typename ...Types>
  1332. struct StringMaker<std::tuple<Types...>> {
  1333. static std::string convert(const std::tuple<Types...>& tuple) {
  1334. ReusableStringStream rss;
  1335. rss << '{';
  1336. Detail::TupleElementPrinter<std::tuple<Types...>>::print(tuple, rss.get());
  1337. rss << " }";
  1338. return rss.str();
  1339. }
  1340. };
  1341. }
  1342. #endif // CATCH_CONFIG_ENABLE_TUPLE_STRINGMAKER
  1343. #if defined(CATCH_CONFIG_ENABLE_VARIANT_STRINGMAKER) && defined(CATCH_CONFIG_CPP17_VARIANT)
  1344. #include <variant>
  1345. namespace Catch {
  1346. template<>
  1347. struct StringMaker<std::monostate> {
  1348. static std::string convert(const std::monostate&) {
  1349. return "{ }";
  1350. }
  1351. };
  1352. template<typename... Elements>
  1353. struct StringMaker<std::variant<Elements...>> {
  1354. static std::string convert(const std::variant<Elements...>& variant) {
  1355. if (variant.valueless_by_exception()) {
  1356. return "{valueless variant}";
  1357. } else {
  1358. return std::visit(
  1359. [](const auto& value) {
  1360. return ::Catch::Detail::stringify(value);
  1361. },
  1362. variant
  1363. );
  1364. }
  1365. }
  1366. };
  1367. }
  1368. #endif // CATCH_CONFIG_ENABLE_VARIANT_STRINGMAKER
  1369. namespace Catch {
  1370. struct not_this_one {}; // Tag type for detecting which begin/ end are being selected
  1371. // Import begin/ end from std here so they are considered alongside the fallback (...) overloads in this namespace
  1372. using std::begin;
  1373. using std::end;
  1374. not_this_one begin( ... );
  1375. not_this_one end( ... );
  1376. template <typename T>
  1377. struct is_range {
  1378. static const bool value =
  1379. !std::is_same<decltype(begin(std::declval<T>())), not_this_one>::value &&
  1380. !std::is_same<decltype(end(std::declval<T>())), not_this_one>::value;
  1381. };
  1382. #if defined(_MANAGED) // Managed types are never ranges
  1383. template <typename T>
  1384. struct is_range<T^> {
  1385. static const bool value = false;
  1386. };
  1387. #endif
  1388. template<typename Range>
  1389. std::string rangeToString( Range const& range ) {
  1390. return ::Catch::Detail::rangeToString( begin( range ), end( range ) );
  1391. }
  1392. // Handle vector<bool> specially
  1393. template<typename Allocator>
  1394. std::string rangeToString( std::vector<bool, Allocator> const& v ) {
  1395. ReusableStringStream rss;
  1396. rss << "{ ";
  1397. bool first = true;
  1398. for( bool b : v ) {
  1399. if( first )
  1400. first = false;
  1401. else
  1402. rss << ", ";
  1403. rss << ::Catch::Detail::stringify( b );
  1404. }
  1405. rss << " }";
  1406. return rss.str();
  1407. }
  1408. template<typename R>
  1409. struct StringMaker<R, typename std::enable_if<is_range<R>::value && !::Catch::Detail::IsStreamInsertable<R>::value>::type> {
  1410. static std::string convert( R const& range ) {
  1411. return rangeToString( range );
  1412. }
  1413. };
  1414. template <typename T, int SZ>
  1415. struct StringMaker<T[SZ]> {
  1416. static std::string convert(T const(&arr)[SZ]) {
  1417. return rangeToString(arr);
  1418. }
  1419. };
  1420. } // namespace Catch
  1421. // Separate std::chrono::duration specialization
  1422. #if defined(CATCH_CONFIG_ENABLE_CHRONO_STRINGMAKER)
  1423. #include <ctime>
  1424. #include <ratio>
  1425. #include <chrono>
  1426. namespace Catch {
  1427. template <class Ratio>
  1428. struct ratio_string {
  1429. static std::string symbol();
  1430. };
  1431. template <class Ratio>
  1432. std::string ratio_string<Ratio>::symbol() {
  1433. Catch::ReusableStringStream rss;
  1434. rss << '[' << Ratio::num << '/'
  1435. << Ratio::den << ']';
  1436. return rss.str();
  1437. }
  1438. template <>
  1439. struct ratio_string<std::atto> {
  1440. static std::string symbol();
  1441. };
  1442. template <>
  1443. struct ratio_string<std::femto> {
  1444. static std::string symbol();
  1445. };
  1446. template <>
  1447. struct ratio_string<std::pico> {
  1448. static std::string symbol();
  1449. };
  1450. template <>
  1451. struct ratio_string<std::nano> {
  1452. static std::string symbol();
  1453. };
  1454. template <>
  1455. struct ratio_string<std::micro> {
  1456. static std::string symbol();
  1457. };
  1458. template <>
  1459. struct ratio_string<std::milli> {
  1460. static std::string symbol();
  1461. };
  1462. ////////////
  1463. // std::chrono::duration specializations
  1464. template<typename Value, typename Ratio>
  1465. struct StringMaker<std::chrono::duration<Value, Ratio>> {
  1466. static std::string convert(std::chrono::duration<Value, Ratio> const& duration) {
  1467. ReusableStringStream rss;
  1468. rss << duration.count() << ' ' << ratio_string<Ratio>::symbol() << 's';
  1469. return rss.str();
  1470. }
  1471. };
  1472. template<typename Value>
  1473. struct StringMaker<std::chrono::duration<Value, std::ratio<1>>> {
  1474. static std::string convert(std::chrono::duration<Value, std::ratio<1>> const& duration) {
  1475. ReusableStringStream rss;
  1476. rss << duration.count() << " s";
  1477. return rss.str();
  1478. }
  1479. };
  1480. template<typename Value>
  1481. struct StringMaker<std::chrono::duration<Value, std::ratio<60>>> {
  1482. static std::string convert(std::chrono::duration<Value, std::ratio<60>> const& duration) {
  1483. ReusableStringStream rss;
  1484. rss << duration.count() << " m";
  1485. return rss.str();
  1486. }
  1487. };
  1488. template<typename Value>
  1489. struct StringMaker<std::chrono::duration<Value, std::ratio<3600>>> {
  1490. static std::string convert(std::chrono::duration<Value, std::ratio<3600>> const& duration) {
  1491. ReusableStringStream rss;
  1492. rss << duration.count() << " h";
  1493. return rss.str();
  1494. }
  1495. };
  1496. ////////////
  1497. // std::chrono::time_point specialization
  1498. // Generic time_point cannot be specialized, only std::chrono::time_point<system_clock>
  1499. template<typename Clock, typename Duration>
  1500. struct StringMaker<std::chrono::time_point<Clock, Duration>> {
  1501. static std::string convert(std::chrono::time_point<Clock, Duration> const& time_point) {
  1502. return ::Catch::Detail::stringify(time_point.time_since_epoch()) + " since epoch";
  1503. }
  1504. };
  1505. // std::chrono::time_point<system_clock> specialization
  1506. template<typename Duration>
  1507. struct StringMaker<std::chrono::time_point<std::chrono::system_clock, Duration>> {
  1508. static std::string convert(std::chrono::time_point<std::chrono::system_clock, Duration> const& time_point) {
  1509. auto converted = std::chrono::system_clock::to_time_t(time_point);
  1510. #ifdef _MSC_VER
  1511. std::tm timeInfo = {};
  1512. gmtime_s(&timeInfo, &converted);
  1513. #else
  1514. std::tm* timeInfo = std::gmtime(&converted);
  1515. #endif
  1516. auto const timeStampSize = sizeof("2017-01-16T17:06:45Z");
  1517. char timeStamp[timeStampSize];
  1518. const char * const fmt = "%Y-%m-%dT%H:%M:%SZ";
  1519. #ifdef _MSC_VER
  1520. std::strftime(timeStamp, timeStampSize, fmt, &timeInfo);
  1521. #else
  1522. std::strftime(timeStamp, timeStampSize, fmt, timeInfo);
  1523. #endif
  1524. return std::string(timeStamp);
  1525. }
  1526. };
  1527. }
  1528. #endif // CATCH_CONFIG_ENABLE_CHRONO_STRINGMAKER
  1529. #ifdef _MSC_VER
  1530. #pragma warning(pop)
  1531. #endif
  1532. // end catch_tostring.h
  1533. #include <iosfwd>
  1534. #ifdef _MSC_VER
  1535. #pragma warning(push)
  1536. #pragma warning(disable:4389) // '==' : signed/unsigned mismatch
  1537. #pragma warning(disable:4018) // more "signed/unsigned mismatch"
  1538. #pragma warning(disable:4312) // Converting int to T* using reinterpret_cast (issue on x64 platform)
  1539. #pragma warning(disable:4180) // qualifier applied to function type has no meaning
  1540. #pragma warning(disable:4800) // Forcing result to true or false
  1541. #endif
  1542. namespace Catch {
  1543. struct ITransientExpression {
  1544. auto isBinaryExpression() const -> bool { return m_isBinaryExpression; }
  1545. auto getResult() const -> bool { return m_result; }
  1546. virtual void streamReconstructedExpression( std::ostream &os ) const = 0;
  1547. ITransientExpression( bool isBinaryExpression, bool result )
  1548. : m_isBinaryExpression( isBinaryExpression ),
  1549. m_result( result )
  1550. {}
  1551. // We don't actually need a virtual destructor, but many static analysers
  1552. // complain if it's not here :-(
  1553. virtual ~ITransientExpression();
  1554. bool m_isBinaryExpression;
  1555. bool m_result;
  1556. };
  1557. void formatReconstructedExpression( std::ostream &os, std::string const& lhs, StringRef op, std::string const& rhs );
  1558. template<typename LhsT, typename RhsT>
  1559. class BinaryExpr : public ITransientExpression {
  1560. LhsT m_lhs;
  1561. StringRef m_op;
  1562. RhsT m_rhs;
  1563. void streamReconstructedExpression( std::ostream &os ) const override {
  1564. formatReconstructedExpression
  1565. ( os, Catch::Detail::stringify( m_lhs ), m_op, Catch::Detail::stringify( m_rhs ) );
  1566. }
  1567. public:
  1568. BinaryExpr( bool comparisonResult, LhsT lhs, StringRef op, RhsT rhs )
  1569. : ITransientExpression{ true, comparisonResult },
  1570. m_lhs( lhs ),
  1571. m_op( op ),
  1572. m_rhs( rhs )
  1573. {}
  1574. template<typename T>
  1575. auto operator && ( T ) const -> BinaryExpr<LhsT, RhsT const&> const {
  1576. static_assert(always_false<T>::value,
  1577. "chained comparisons are not supported inside assertions, "
  1578. "wrap the expression inside parentheses, or decompose it");
  1579. }
  1580. template<typename T>
  1581. auto operator || ( T ) const -> BinaryExpr<LhsT, RhsT const&> const {
  1582. static_assert(always_false<T>::value,
  1583. "chained comparisons are not supported inside assertions, "
  1584. "wrap the expression inside parentheses, or decompose it");
  1585. }
  1586. template<typename T>
  1587. auto operator == ( T ) const -> BinaryExpr<LhsT, RhsT const&> const {
  1588. static_assert(always_false<T>::value,
  1589. "chained comparisons are not supported inside assertions, "
  1590. "wrap the expression inside parentheses, or decompose it");
  1591. }
  1592. template<typename T>
  1593. auto operator != ( T ) const -> BinaryExpr<LhsT, RhsT const&> const {
  1594. static_assert(always_false<T>::value,
  1595. "chained comparisons are not supported inside assertions, "
  1596. "wrap the expression inside parentheses, or decompose it");
  1597. }
  1598. template<typename T>
  1599. auto operator > ( T ) const -> BinaryExpr<LhsT, RhsT const&> const {
  1600. static_assert(always_false<T>::value,
  1601. "chained comparisons are not supported inside assertions, "
  1602. "wrap the expression inside parentheses, or decompose it");
  1603. }
  1604. template<typename T>
  1605. auto operator < ( T ) const -> BinaryExpr<LhsT, RhsT const&> const {
  1606. static_assert(always_false<T>::value,
  1607. "chained comparisons are not supported inside assertions, "
  1608. "wrap the expression inside parentheses, or decompose it");
  1609. }
  1610. template<typename T>
  1611. auto operator >= ( T ) const -> BinaryExpr<LhsT, RhsT const&> const {
  1612. static_assert(always_false<T>::value,
  1613. "chained comparisons are not supported inside assertions, "
  1614. "wrap the expression inside parentheses, or decompose it");
  1615. }
  1616. template<typename T>
  1617. auto operator <= ( T ) const -> BinaryExpr<LhsT, RhsT const&> const {
  1618. static_assert(always_false<T>::value,
  1619. "chained comparisons are not supported inside assertions, "
  1620. "wrap the expression inside parentheses, or decompose it");
  1621. }
  1622. };
  1623. template<typename LhsT>
  1624. class UnaryExpr : public ITransientExpression {
  1625. LhsT m_lhs;
  1626. void streamReconstructedExpression( std::ostream &os ) const override {
  1627. os << Catch::Detail::stringify( m_lhs );
  1628. }
  1629. public:
  1630. explicit UnaryExpr( LhsT lhs )
  1631. : ITransientExpression{ false, static_cast<bool>(lhs) },
  1632. m_lhs( lhs )
  1633. {}
  1634. };
  1635. // Specialised comparison functions to handle equality comparisons between ints and pointers (NULL deduces as an int)
  1636. template<typename LhsT, typename RhsT>
  1637. auto compareEqual( LhsT const& lhs, RhsT const& rhs ) -> bool { return static_cast<bool>(lhs == rhs); }
  1638. template<typename T>
  1639. auto compareEqual( T* const& lhs, int rhs ) -> bool { return lhs == reinterpret_cast<void const*>( rhs ); }
  1640. template<typename T>
  1641. auto compareEqual( T* const& lhs, long rhs ) -> bool { return lhs == reinterpret_cast<void const*>( rhs ); }
  1642. template<typename T>
  1643. auto compareEqual( int lhs, T* const& rhs ) -> bool { return reinterpret_cast<void const*>( lhs ) == rhs; }
  1644. template<typename T>
  1645. auto compareEqual( long lhs, T* const& rhs ) -> bool { return reinterpret_cast<void const*>( lhs ) == rhs; }
  1646. template<typename LhsT, typename RhsT>
  1647. auto compareNotEqual( LhsT const& lhs, RhsT&& rhs ) -> bool { return static_cast<bool>(lhs != rhs); }
  1648. template<typename T>
  1649. auto compareNotEqual( T* const& lhs, int rhs ) -> bool { return lhs != reinterpret_cast<void const*>( rhs ); }
  1650. template<typename T>
  1651. auto compareNotEqual( T* const& lhs, long rhs ) -> bool { return lhs != reinterpret_cast<void const*>( rhs ); }
  1652. template<typename T>
  1653. auto compareNotEqual( int lhs, T* const& rhs ) -> bool { return reinterpret_cast<void const*>( lhs ) != rhs; }
  1654. template<typename T>
  1655. auto compareNotEqual( long lhs, T* const& rhs ) -> bool { return reinterpret_cast<void const*>( lhs ) != rhs; }
  1656. template<typename LhsT>
  1657. class ExprLhs {
  1658. LhsT m_lhs;
  1659. public:
  1660. explicit ExprLhs( LhsT lhs ) : m_lhs( lhs ) {}
  1661. template<typename RhsT>
  1662. auto operator == ( RhsT const& rhs ) -> BinaryExpr<LhsT, RhsT const&> const {
  1663. return { compareEqual( m_lhs, rhs ), m_lhs, "==", rhs };
  1664. }
  1665. auto operator == ( bool rhs ) -> BinaryExpr<LhsT, bool> const {
  1666. return { m_lhs == rhs, m_lhs, "==", rhs };
  1667. }
  1668. template<typename RhsT>
  1669. auto operator != ( RhsT const& rhs ) -> BinaryExpr<LhsT, RhsT const&> const {
  1670. return { compareNotEqual( m_lhs, rhs ), m_lhs, "!=", rhs };
  1671. }
  1672. auto operator != ( bool rhs ) -> BinaryExpr<LhsT, bool> const {
  1673. return { m_lhs != rhs, m_lhs, "!=", rhs };
  1674. }
  1675. template<typename RhsT>
  1676. auto operator > ( RhsT const& rhs ) -> BinaryExpr<LhsT, RhsT const&> const {
  1677. return { static_cast<bool>(m_lhs > rhs), m_lhs, ">", rhs };
  1678. }
  1679. template<typename RhsT>
  1680. auto operator < ( RhsT const& rhs ) -> BinaryExpr<LhsT, RhsT const&> const {
  1681. return { static_cast<bool>(m_lhs < rhs), m_lhs, "<", rhs };
  1682. }
  1683. template<typename RhsT>
  1684. auto operator >= ( RhsT const& rhs ) -> BinaryExpr<LhsT, RhsT const&> const {
  1685. return { static_cast<bool>(m_lhs >= rhs), m_lhs, ">=", rhs };
  1686. }
  1687. template<typename RhsT>
  1688. auto operator <= ( RhsT const& rhs ) -> BinaryExpr<LhsT, RhsT const&> const {
  1689. return { static_cast<bool>(m_lhs <= rhs), m_lhs, "<=", rhs };
  1690. }
  1691. template<typename RhsT>
  1692. auto operator && ( RhsT const& ) -> BinaryExpr<LhsT, RhsT const&> const {
  1693. static_assert(always_false<RhsT>::value,
  1694. "operator&& is not supported inside assertions, "
  1695. "wrap the expression inside parentheses, or decompose it");
  1696. }
  1697. template<typename RhsT>
  1698. auto operator || ( RhsT const& ) -> BinaryExpr<LhsT, RhsT const&> const {
  1699. static_assert(always_false<RhsT>::value,
  1700. "operator|| is not supported inside assertions, "
  1701. "wrap the expression inside parentheses, or decompose it");
  1702. }
  1703. auto makeUnaryExpr() const -> UnaryExpr<LhsT> {
  1704. return UnaryExpr<LhsT>{ m_lhs };
  1705. }
  1706. };
  1707. void handleExpression( ITransientExpression const& expr );
  1708. template<typename T>
  1709. void handleExpression( ExprLhs<T> const& expr ) {
  1710. handleExpression( expr.makeUnaryExpr() );
  1711. }
  1712. struct Decomposer {
  1713. template<typename T>
  1714. auto operator <= ( T const& lhs ) -> ExprLhs<T const&> {
  1715. return ExprLhs<T const&>{ lhs };
  1716. }
  1717. auto operator <=( bool value ) -> ExprLhs<bool> {
  1718. return ExprLhs<bool>{ value };
  1719. }
  1720. };
  1721. } // end namespace Catch
  1722. #ifdef _MSC_VER
  1723. #pragma warning(pop)
  1724. #endif
  1725. // end catch_decomposer.h
  1726. // start catch_interfaces_capture.h
  1727. #include <string>
  1728. namespace Catch {
  1729. class AssertionResult;
  1730. struct AssertionInfo;
  1731. struct SectionInfo;
  1732. struct SectionEndInfo;
  1733. struct MessageInfo;
  1734. struct MessageBuilder;
  1735. struct Counts;
  1736. struct BenchmarkInfo;
  1737. struct BenchmarkStats;
  1738. struct AssertionReaction;
  1739. struct SourceLineInfo;
  1740. struct ITransientExpression;
  1741. struct IGeneratorTracker;
  1742. struct IResultCapture {
  1743. virtual ~IResultCapture();
  1744. virtual bool sectionStarted( SectionInfo const& sectionInfo,
  1745. Counts& assertions ) = 0;
  1746. virtual void sectionEnded( SectionEndInfo const& endInfo ) = 0;
  1747. virtual void sectionEndedEarly( SectionEndInfo const& endInfo ) = 0;
  1748. virtual auto acquireGeneratorTracker( SourceLineInfo const& lineInfo ) -> IGeneratorTracker& = 0;
  1749. virtual void benchmarkStarting( BenchmarkInfo const& info ) = 0;
  1750. virtual void benchmarkEnded( BenchmarkStats const& stats ) = 0;
  1751. virtual void pushScopedMessage( MessageInfo const& message ) = 0;
  1752. virtual void popScopedMessage( MessageInfo const& message ) = 0;
  1753. virtual void emplaceUnscopedMessage( MessageBuilder const& builder ) = 0;
  1754. virtual void handleFatalErrorCondition( StringRef message ) = 0;
  1755. virtual void handleExpr
  1756. ( AssertionInfo const& info,
  1757. ITransientExpression const& expr,
  1758. AssertionReaction& reaction ) = 0;
  1759. virtual void handleMessage
  1760. ( AssertionInfo const& info,
  1761. ResultWas::OfType resultType,
  1762. StringRef const& message,
  1763. AssertionReaction& reaction ) = 0;
  1764. virtual void handleUnexpectedExceptionNotThrown
  1765. ( AssertionInfo const& info,
  1766. AssertionReaction& reaction ) = 0;
  1767. virtual void handleUnexpectedInflightException
  1768. ( AssertionInfo const& info,
  1769. std::string const& message,
  1770. AssertionReaction& reaction ) = 0;
  1771. virtual void handleIncomplete
  1772. ( AssertionInfo const& info ) = 0;
  1773. virtual void handleNonExpr
  1774. ( AssertionInfo const &info,
  1775. ResultWas::OfType resultType,
  1776. AssertionReaction &reaction ) = 0;
  1777. virtual bool lastAssertionPassed() = 0;
  1778. virtual void assertionPassed() = 0;
  1779. // Deprecated, do not use:
  1780. virtual std::string getCurrentTestName() const = 0;
  1781. virtual const AssertionResult* getLastResult() const = 0;
  1782. virtual void exceptionEarlyReported() = 0;
  1783. };
  1784. IResultCapture& getResultCapture();
  1785. }
  1786. // end catch_interfaces_capture.h
  1787. namespace Catch {
  1788. struct TestFailureException{};
  1789. struct AssertionResultData;
  1790. struct IResultCapture;
  1791. class RunContext;
  1792. class LazyExpression {
  1793. friend class AssertionHandler;
  1794. friend struct AssertionStats;
  1795. friend class RunContext;
  1796. ITransientExpression const* m_transientExpression = nullptr;
  1797. bool m_isNegated;
  1798. public:
  1799. LazyExpression( bool isNegated );
  1800. LazyExpression( LazyExpression const& other );
  1801. LazyExpression& operator = ( LazyExpression const& ) = delete;
  1802. explicit operator bool() const;
  1803. friend auto operator << ( std::ostream& os, LazyExpression const& lazyExpr ) -> std::ostream&;
  1804. };
  1805. struct AssertionReaction {
  1806. bool shouldDebugBreak = false;
  1807. bool shouldThrow = false;
  1808. };
  1809. class AssertionHandler {
  1810. AssertionInfo m_assertionInfo;
  1811. AssertionReaction m_reaction;
  1812. bool m_completed = false;
  1813. IResultCapture& m_resultCapture;
  1814. public:
  1815. AssertionHandler
  1816. ( StringRef const& macroName,
  1817. SourceLineInfo const& lineInfo,
  1818. StringRef capturedExpression,
  1819. ResultDisposition::Flags resultDisposition );
  1820. ~AssertionHandler() {
  1821. if ( !m_completed ) {
  1822. m_resultCapture.handleIncomplete( m_assertionInfo );
  1823. }
  1824. }
  1825. template<typename T>
  1826. void handleExpr( ExprLhs<T> const& expr ) {
  1827. handleExpr( expr.makeUnaryExpr() );
  1828. }
  1829. void handleExpr( ITransientExpression const& expr );
  1830. void handleMessage(ResultWas::OfType resultType, StringRef const& message);
  1831. void handleExceptionThrownAsExpected();
  1832. void handleUnexpectedExceptionNotThrown();
  1833. void handleExceptionNotThrownAsExpected();
  1834. void handleThrowingCallSkipped();
  1835. void handleUnexpectedInflightException();
  1836. void complete();
  1837. void setCompleted();
  1838. // query
  1839. auto allowThrows() const -> bool;
  1840. };
  1841. void handleExceptionMatchExpr( AssertionHandler& handler, std::string const& str, StringRef const& matcherString );
  1842. } // namespace Catch
  1843. // end catch_assertionhandler.h
  1844. // start catch_message.h
  1845. #include <string>
  1846. #include <vector>
  1847. namespace Catch {
  1848. struct MessageInfo {
  1849. MessageInfo( StringRef const& _macroName,
  1850. SourceLineInfo const& _lineInfo,
  1851. ResultWas::OfType _type );
  1852. StringRef macroName;
  1853. std::string message;
  1854. SourceLineInfo lineInfo;
  1855. ResultWas::OfType type;
  1856. unsigned int sequence;
  1857. bool operator == ( MessageInfo const& other ) const;
  1858. bool operator < ( MessageInfo const& other ) const;
  1859. private:
  1860. static unsigned int globalCount;
  1861. };
  1862. struct MessageStream {
  1863. template<typename T>
  1864. MessageStream& operator << ( T const& value ) {
  1865. m_stream << value;
  1866. return *this;
  1867. }
  1868. ReusableStringStream m_stream;
  1869. };
  1870. struct MessageBuilder : MessageStream {
  1871. MessageBuilder( StringRef const& macroName,
  1872. SourceLineInfo const& lineInfo,
  1873. ResultWas::OfType type );
  1874. template<typename T>
  1875. MessageBuilder& operator << ( T const& value ) {
  1876. m_stream << value;
  1877. return *this;
  1878. }
  1879. MessageInfo m_info;
  1880. };
  1881. class ScopedMessage {
  1882. public:
  1883. explicit ScopedMessage( MessageBuilder const& builder );
  1884. ScopedMessage( ScopedMessage& duplicate ) = delete;
  1885. ScopedMessage( ScopedMessage&& old );
  1886. ~ScopedMessage();
  1887. MessageInfo m_info;
  1888. bool m_moved;
  1889. };
  1890. class Capturer {
  1891. std::vector<MessageInfo> m_messages;
  1892. IResultCapture& m_resultCapture = getResultCapture();
  1893. size_t m_captured = 0;
  1894. public:
  1895. Capturer( StringRef macroName, SourceLineInfo const& lineInfo, ResultWas::OfType resultType, StringRef names );
  1896. ~Capturer();
  1897. void captureValue( size_t index, std::string const& value );
  1898. template<typename T>
  1899. void captureValues( size_t index, T const& value ) {
  1900. captureValue( index, Catch::Detail::stringify( value ) );
  1901. }
  1902. template<typename T, typename... Ts>
  1903. void captureValues( size_t index, T const& value, Ts const&... values ) {
  1904. captureValue( index, Catch::Detail::stringify(value) );
  1905. captureValues( index+1, values... );
  1906. }
  1907. };
  1908. } // end namespace Catch
  1909. // end catch_message.h
  1910. #if !defined(CATCH_CONFIG_DISABLE)
  1911. #if !defined(CATCH_CONFIG_DISABLE_STRINGIFICATION)
  1912. #define CATCH_INTERNAL_STRINGIFY(...) #__VA_ARGS__
  1913. #else
  1914. #define CATCH_INTERNAL_STRINGIFY(...) "Disabled by CATCH_CONFIG_DISABLE_STRINGIFICATION"
  1915. #endif
  1916. #if defined(CATCH_CONFIG_FAST_COMPILE) || defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
  1917. ///////////////////////////////////////////////////////////////////////////////
  1918. // Another way to speed-up compilation is to omit local try-catch for REQUIRE*
  1919. // macros.
  1920. #define INTERNAL_CATCH_TRY
  1921. #define INTERNAL_CATCH_CATCH( capturer )
  1922. #else // CATCH_CONFIG_FAST_COMPILE
  1923. #define INTERNAL_CATCH_TRY try
  1924. #define INTERNAL_CATCH_CATCH( handler ) catch(...) { handler.handleUnexpectedInflightException(); }
  1925. #endif
  1926. #define INTERNAL_CATCH_REACT( handler ) handler.complete();
  1927. ///////////////////////////////////////////////////////////////////////////////
  1928. #define INTERNAL_CATCH_TEST( macroName, resultDisposition, ... ) \
  1929. do { \
  1930. Catch::AssertionHandler catchAssertionHandler( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(__VA_ARGS__), resultDisposition ); \
  1931. INTERNAL_CATCH_TRY { \
  1932. CATCH_INTERNAL_SUPPRESS_PARENTHESES_WARNINGS \
  1933. catchAssertionHandler.handleExpr( Catch::Decomposer() <= __VA_ARGS__ ); \
  1934. CATCH_INTERNAL_UNSUPPRESS_PARENTHESES_WARNINGS \
  1935. } INTERNAL_CATCH_CATCH( catchAssertionHandler ) \
  1936. INTERNAL_CATCH_REACT( catchAssertionHandler ) \
  1937. } 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
  1938. // The double negation silences MSVC's C4800 warning, the static_cast forces short-circuit evaluation if the type has overloaded &&.
  1939. ///////////////////////////////////////////////////////////////////////////////
  1940. #define INTERNAL_CATCH_IF( macroName, resultDisposition, ... ) \
  1941. INTERNAL_CATCH_TEST( macroName, resultDisposition, __VA_ARGS__ ); \
  1942. if( Catch::getResultCapture().lastAssertionPassed() )
  1943. ///////////////////////////////////////////////////////////////////////////////
  1944. #define INTERNAL_CATCH_ELSE( macroName, resultDisposition, ... ) \
  1945. INTERNAL_CATCH_TEST( macroName, resultDisposition, __VA_ARGS__ ); \
  1946. if( !Catch::getResultCapture().lastAssertionPassed() )
  1947. ///////////////////////////////////////////////////////////////////////////////
  1948. #define INTERNAL_CATCH_NO_THROW( macroName, resultDisposition, ... ) \
  1949. do { \
  1950. Catch::AssertionHandler catchAssertionHandler( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(__VA_ARGS__), resultDisposition ); \
  1951. try { \
  1952. static_cast<void>(__VA_ARGS__); \
  1953. catchAssertionHandler.handleExceptionNotThrownAsExpected(); \
  1954. } \
  1955. catch( ... ) { \
  1956. catchAssertionHandler.handleUnexpectedInflightException(); \
  1957. } \
  1958. INTERNAL_CATCH_REACT( catchAssertionHandler ) \
  1959. } while( false )
  1960. ///////////////////////////////////////////////////////////////////////////////
  1961. #define INTERNAL_CATCH_THROWS( macroName, resultDisposition, ... ) \
  1962. do { \
  1963. Catch::AssertionHandler catchAssertionHandler( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(__VA_ARGS__), resultDisposition); \
  1964. if( catchAssertionHandler.allowThrows() ) \
  1965. try { \
  1966. static_cast<void>(__VA_ARGS__); \
  1967. catchAssertionHandler.handleUnexpectedExceptionNotThrown(); \
  1968. } \
  1969. catch( ... ) { \
  1970. catchAssertionHandler.handleExceptionThrownAsExpected(); \
  1971. } \
  1972. else \
  1973. catchAssertionHandler.handleThrowingCallSkipped(); \
  1974. INTERNAL_CATCH_REACT( catchAssertionHandler ) \
  1975. } while( false )
  1976. ///////////////////////////////////////////////////////////////////////////////
  1977. #define INTERNAL_CATCH_THROWS_AS( macroName, exceptionType, resultDisposition, expr ) \
  1978. do { \
  1979. Catch::AssertionHandler catchAssertionHandler( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(expr) ", " CATCH_INTERNAL_STRINGIFY(exceptionType), resultDisposition ); \
  1980. if( catchAssertionHandler.allowThrows() ) \
  1981. try { \
  1982. static_cast<void>(expr); \
  1983. catchAssertionHandler.handleUnexpectedExceptionNotThrown(); \
  1984. } \
  1985. catch( exceptionType const& ) { \
  1986. catchAssertionHandler.handleExceptionThrownAsExpected(); \
  1987. } \
  1988. catch( ... ) { \
  1989. catchAssertionHandler.handleUnexpectedInflightException(); \
  1990. } \
  1991. else \
  1992. catchAssertionHandler.handleThrowingCallSkipped(); \
  1993. INTERNAL_CATCH_REACT( catchAssertionHandler ) \
  1994. } while( false )
  1995. ///////////////////////////////////////////////////////////////////////////////
  1996. #define INTERNAL_CATCH_MSG( macroName, messageType, resultDisposition, ... ) \
  1997. do { \
  1998. Catch::AssertionHandler catchAssertionHandler( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, Catch::StringRef(), resultDisposition ); \
  1999. catchAssertionHandler.handleMessage( messageType, ( Catch::MessageStream() << __VA_ARGS__ + ::Catch::StreamEndStop() ).m_stream.str() ); \
  2000. INTERNAL_CATCH_REACT( catchAssertionHandler ) \
  2001. } while( false )
  2002. ///////////////////////////////////////////////////////////////////////////////
  2003. #define INTERNAL_CATCH_CAPTURE( varName, macroName, ... ) \
  2004. auto varName = Catch::Capturer( macroName, CATCH_INTERNAL_LINEINFO, Catch::ResultWas::Info, #__VA_ARGS__ ); \
  2005. varName.captureValues( 0, __VA_ARGS__ )
  2006. ///////////////////////////////////////////////////////////////////////////////
  2007. #define INTERNAL_CATCH_INFO( macroName, log ) \
  2008. Catch::ScopedMessage INTERNAL_CATCH_UNIQUE_NAME( scopedMessage )( Catch::MessageBuilder( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, Catch::ResultWas::Info ) << log );
  2009. ///////////////////////////////////////////////////////////////////////////////
  2010. #define INTERNAL_CATCH_UNSCOPED_INFO( macroName, log ) \
  2011. Catch::getResultCapture().emplaceUnscopedMessage( Catch::MessageBuilder( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, Catch::ResultWas::Info ) << log )
  2012. ///////////////////////////////////////////////////////////////////////////////
  2013. // Although this is matcher-based, it can be used with just a string
  2014. #define INTERNAL_CATCH_THROWS_STR_MATCHES( macroName, resultDisposition, matcher, ... ) \
  2015. do { \
  2016. Catch::AssertionHandler catchAssertionHandler( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(__VA_ARGS__) ", " CATCH_INTERNAL_STRINGIFY(matcher), resultDisposition ); \
  2017. if( catchAssertionHandler.allowThrows() ) \
  2018. try { \
  2019. static_cast<void>(__VA_ARGS__); \
  2020. catchAssertionHandler.handleUnexpectedExceptionNotThrown(); \
  2021. } \
  2022. catch( ... ) { \
  2023. Catch::handleExceptionMatchExpr( catchAssertionHandler, matcher, #matcher##_catch_sr ); \
  2024. } \
  2025. else \
  2026. catchAssertionHandler.handleThrowingCallSkipped(); \
  2027. INTERNAL_CATCH_REACT( catchAssertionHandler ) \
  2028. } while( false )
  2029. #endif // CATCH_CONFIG_DISABLE
  2030. // end catch_capture.hpp
  2031. // start catch_section.h
  2032. // start catch_section_info.h
  2033. // start catch_totals.h
  2034. #include <cstddef>
  2035. namespace Catch {
  2036. struct Counts {
  2037. Counts operator - ( Counts const& other ) const;
  2038. Counts& operator += ( Counts const& other );
  2039. std::size_t total() const;
  2040. bool allPassed() const;
  2041. bool allOk() const;
  2042. std::size_t passed = 0;
  2043. std::size_t failed = 0;
  2044. std::size_t failedButOk = 0;
  2045. };
  2046. struct Totals {
  2047. Totals operator - ( Totals const& other ) const;
  2048. Totals& operator += ( Totals const& other );
  2049. Totals delta( Totals const& prevTotals ) const;
  2050. int error = 0;
  2051. Counts assertions;
  2052. Counts testCases;
  2053. };
  2054. }
  2055. // end catch_totals.h
  2056. #include <string>
  2057. namespace Catch {
  2058. struct SectionInfo {
  2059. SectionInfo
  2060. ( SourceLineInfo const& _lineInfo,
  2061. std::string const& _name );
  2062. // Deprecated
  2063. SectionInfo
  2064. ( SourceLineInfo const& _lineInfo,
  2065. std::string const& _name,
  2066. std::string const& ) : SectionInfo( _lineInfo, _name ) {}
  2067. std::string name;
  2068. std::string description; // !Deprecated: this will always be empty
  2069. SourceLineInfo lineInfo;
  2070. };
  2071. struct SectionEndInfo {
  2072. SectionInfo sectionInfo;
  2073. Counts prevAssertions;
  2074. double durationInSeconds;
  2075. };
  2076. } // end namespace Catch
  2077. // end catch_section_info.h
  2078. // start catch_timer.h
  2079. #include <cstdint>
  2080. namespace Catch {
  2081. auto getCurrentNanosecondsSinceEpoch() -> uint64_t;
  2082. auto getEstimatedClockResolution() -> uint64_t;
  2083. class Timer {
  2084. uint64_t m_nanoseconds = 0;
  2085. public:
  2086. void start();
  2087. auto getElapsedNanoseconds() const -> uint64_t;
  2088. auto getElapsedMicroseconds() const -> uint64_t;
  2089. auto getElapsedMilliseconds() const -> unsigned int;
  2090. auto getElapsedSeconds() const -> double;
  2091. };
  2092. } // namespace Catch
  2093. // end catch_timer.h
  2094. #include <string>
  2095. namespace Catch {
  2096. class Section : NonCopyable {
  2097. public:
  2098. Section( SectionInfo const& info );
  2099. ~Section();
  2100. // This indicates whether the section should be executed or not
  2101. explicit operator bool() const;
  2102. private:
  2103. SectionInfo m_info;
  2104. std::string m_name;
  2105. Counts m_assertions;
  2106. bool m_sectionIncluded;
  2107. Timer m_timer;
  2108. };
  2109. } // end namespace Catch
  2110. #define INTERNAL_CATCH_SECTION( ... ) \
  2111. CATCH_INTERNAL_SUPPRESS_UNUSED_WARNINGS \
  2112. if( Catch::Section const& INTERNAL_CATCH_UNIQUE_NAME( catch_internal_Section ) = Catch::SectionInfo( CATCH_INTERNAL_LINEINFO, __VA_ARGS__ ) ) \
  2113. CATCH_INTERNAL_UNSUPPRESS_UNUSED_WARNINGS
  2114. #define INTERNAL_CATCH_DYNAMIC_SECTION( ... ) \
  2115. CATCH_INTERNAL_SUPPRESS_UNUSED_WARNINGS \
  2116. if( Catch::Section const& INTERNAL_CATCH_UNIQUE_NAME( catch_internal_Section ) = Catch::SectionInfo( CATCH_INTERNAL_LINEINFO, (Catch::ReusableStringStream() << __VA_ARGS__).str() ) ) \
  2117. CATCH_INTERNAL_UNSUPPRESS_UNUSED_WARNINGS
  2118. // end catch_section.h
  2119. // start catch_benchmark.h
  2120. #include <cstdint>
  2121. #include <string>
  2122. namespace Catch {
  2123. class BenchmarkLooper {
  2124. std::string m_name;
  2125. std::size_t m_count = 0;
  2126. std::size_t m_iterationsToRun = 1;
  2127. uint64_t m_resolution;
  2128. Timer m_timer;
  2129. static auto getResolution() -> uint64_t;
  2130. public:
  2131. // Keep most of this inline as it's on the code path that is being timed
  2132. BenchmarkLooper( StringRef name )
  2133. : m_name( name ),
  2134. m_resolution( getResolution() )
  2135. {
  2136. reportStart();
  2137. m_timer.start();
  2138. }
  2139. explicit operator bool() {
  2140. if( m_count < m_iterationsToRun )
  2141. return true;
  2142. return needsMoreIterations();
  2143. }
  2144. void increment() {
  2145. ++m_count;
  2146. }
  2147. void reportStart();
  2148. auto needsMoreIterations() -> bool;
  2149. };
  2150. } // end namespace Catch
  2151. #define BENCHMARK( name ) \
  2152. for( Catch::BenchmarkLooper looper( name ); looper; looper.increment() )
  2153. // end catch_benchmark.h
  2154. // start catch_interfaces_exception.h
  2155. // start catch_interfaces_registry_hub.h
  2156. #include <string>
  2157. #include <memory>
  2158. namespace Catch {
  2159. class TestCase;
  2160. struct ITestCaseRegistry;
  2161. struct IExceptionTranslatorRegistry;
  2162. struct IExceptionTranslator;
  2163. struct IReporterRegistry;
  2164. struct IReporterFactory;
  2165. struct ITagAliasRegistry;
  2166. class StartupExceptionRegistry;
  2167. using IReporterFactoryPtr = std::shared_ptr<IReporterFactory>;
  2168. struct IRegistryHub {
  2169. virtual ~IRegistryHub();
  2170. virtual IReporterRegistry const& getReporterRegistry() const = 0;
  2171. virtual ITestCaseRegistry const& getTestCaseRegistry() const = 0;
  2172. virtual ITagAliasRegistry const& getTagAliasRegistry() const = 0;
  2173. virtual IExceptionTranslatorRegistry const& getExceptionTranslatorRegistry() const = 0;
  2174. virtual StartupExceptionRegistry const& getStartupExceptionRegistry() const = 0;
  2175. };
  2176. struct IMutableRegistryHub {
  2177. virtual ~IMutableRegistryHub();
  2178. virtual void registerReporter( std::string const& name, IReporterFactoryPtr const& factory ) = 0;
  2179. virtual void registerListener( IReporterFactoryPtr const& factory ) = 0;
  2180. virtual void registerTest( TestCase const& testInfo ) = 0;
  2181. virtual void registerTranslator( const IExceptionTranslator* translator ) = 0;
  2182. virtual void registerTagAlias( std::string const& alias, std::string const& tag, SourceLineInfo const& lineInfo ) = 0;
  2183. virtual void registerStartupException() noexcept = 0;
  2184. };
  2185. IRegistryHub const& getRegistryHub();
  2186. IMutableRegistryHub& getMutableRegistryHub();
  2187. void cleanUp();
  2188. std::string translateActiveException();
  2189. }
  2190. // end catch_interfaces_registry_hub.h
  2191. #if defined(CATCH_CONFIG_DISABLE)
  2192. #define INTERNAL_CATCH_TRANSLATE_EXCEPTION_NO_REG( translatorName, signature) \
  2193. static std::string translatorName( signature )
  2194. #endif
  2195. #include <exception>
  2196. #include <string>
  2197. #include <vector>
  2198. namespace Catch {
  2199. using exceptionTranslateFunction = std::string(*)();
  2200. struct IExceptionTranslator;
  2201. using ExceptionTranslators = std::vector<std::unique_ptr<IExceptionTranslator const>>;
  2202. struct IExceptionTranslator {
  2203. virtual ~IExceptionTranslator();
  2204. virtual std::string translate( ExceptionTranslators::const_iterator it, ExceptionTranslators::const_iterator itEnd ) const = 0;
  2205. };
  2206. struct IExceptionTranslatorRegistry {
  2207. virtual ~IExceptionTranslatorRegistry();
  2208. virtual std::string translateActiveException() const = 0;
  2209. };
  2210. class ExceptionTranslatorRegistrar {
  2211. template<typename T>
  2212. class ExceptionTranslator : public IExceptionTranslator {
  2213. public:
  2214. ExceptionTranslator( std::string(*translateFunction)( T& ) )
  2215. : m_translateFunction( translateFunction )
  2216. {}
  2217. std::string translate( ExceptionTranslators::const_iterator it, ExceptionTranslators::const_iterator itEnd ) const override {
  2218. try {
  2219. if( it == itEnd )
  2220. std::rethrow_exception(std::current_exception());
  2221. else
  2222. return (*it)->translate( it+1, itEnd );
  2223. }
  2224. catch( T& ex ) {
  2225. return m_translateFunction( ex );
  2226. }
  2227. }
  2228. protected:
  2229. std::string(*m_translateFunction)( T& );
  2230. };
  2231. public:
  2232. template<typename T>
  2233. ExceptionTranslatorRegistrar( std::string(*translateFunction)( T& ) ) {
  2234. getMutableRegistryHub().registerTranslator
  2235. ( new ExceptionTranslator<T>( translateFunction ) );
  2236. }
  2237. };
  2238. }
  2239. ///////////////////////////////////////////////////////////////////////////////
  2240. #define INTERNAL_CATCH_TRANSLATE_EXCEPTION2( translatorName, signature ) \
  2241. static std::string translatorName( signature ); \
  2242. CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
  2243. namespace{ Catch::ExceptionTranslatorRegistrar INTERNAL_CATCH_UNIQUE_NAME( catch_internal_ExceptionRegistrar )( &translatorName ); } \
  2244. CATCH_INTERNAL_UNSUPPRESS_GLOBALS_WARNINGS \
  2245. static std::string translatorName( signature )
  2246. #define INTERNAL_CATCH_TRANSLATE_EXCEPTION( signature ) INTERNAL_CATCH_TRANSLATE_EXCEPTION2( INTERNAL_CATCH_UNIQUE_NAME( catch_internal_ExceptionTranslator ), signature )
  2247. // end catch_interfaces_exception.h
  2248. // start catch_approx.h
  2249. #include <type_traits>
  2250. namespace Catch {
  2251. namespace Detail {
  2252. class Approx {
  2253. private:
  2254. bool equalityComparisonImpl(double other) const;
  2255. // Validates the new margin (margin >= 0)
  2256. // out-of-line to avoid including stdexcept in the header
  2257. void setMargin(double margin);
  2258. // Validates the new epsilon (0 < epsilon < 1)
  2259. // out-of-line to avoid including stdexcept in the header
  2260. void setEpsilon(double epsilon);
  2261. public:
  2262. explicit Approx ( double value );
  2263. static Approx custom();
  2264. Approx operator-() const;
  2265. template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
  2266. Approx operator()( T const& value ) {
  2267. Approx approx( static_cast<double>(value) );
  2268. approx.m_epsilon = m_epsilon;
  2269. approx.m_margin = m_margin;
  2270. approx.m_scale = m_scale;
  2271. return approx;
  2272. }
  2273. template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
  2274. explicit Approx( T const& value ): Approx(static_cast<double>(value))
  2275. {}
  2276. template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
  2277. friend bool operator == ( const T& lhs, Approx const& rhs ) {
  2278. auto lhs_v = static_cast<double>(lhs);
  2279. return rhs.equalityComparisonImpl(lhs_v);
  2280. }
  2281. template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
  2282. friend bool operator == ( Approx const& lhs, const T& rhs ) {
  2283. return operator==( rhs, lhs );
  2284. }
  2285. template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
  2286. friend bool operator != ( T const& lhs, Approx const& rhs ) {
  2287. return !operator==( lhs, rhs );
  2288. }
  2289. template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
  2290. friend bool operator != ( Approx const& lhs, T const& rhs ) {
  2291. return !operator==( rhs, lhs );
  2292. }
  2293. template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
  2294. friend bool operator <= ( T const& lhs, Approx const& rhs ) {
  2295. return static_cast<double>(lhs) < rhs.m_value || lhs == rhs;
  2296. }
  2297. template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
  2298. friend bool operator <= ( Approx const& lhs, T const& rhs ) {
  2299. return lhs.m_value < static_cast<double>(rhs) || lhs == rhs;
  2300. }
  2301. template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
  2302. friend bool operator >= ( T const& lhs, Approx const& rhs ) {
  2303. return static_cast<double>(lhs) > rhs.m_value || lhs == rhs;
  2304. }
  2305. template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
  2306. friend bool operator >= ( Approx const& lhs, T const& rhs ) {
  2307. return lhs.m_value > static_cast<double>(rhs) || lhs == rhs;
  2308. }
  2309. template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
  2310. Approx& epsilon( T const& newEpsilon ) {
  2311. double epsilonAsDouble = static_cast<double>(newEpsilon);
  2312. setEpsilon(epsilonAsDouble);
  2313. return *this;
  2314. }
  2315. template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
  2316. Approx& margin( T const& newMargin ) {
  2317. double marginAsDouble = static_cast<double>(newMargin);
  2318. setMargin(marginAsDouble);
  2319. return *this;
  2320. }
  2321. template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
  2322. Approx& scale( T const& newScale ) {
  2323. m_scale = static_cast<double>(newScale);
  2324. return *this;
  2325. }
  2326. std::string toString() const;
  2327. private:
  2328. double m_epsilon;
  2329. double m_margin;
  2330. double m_scale;
  2331. double m_value;
  2332. };
  2333. } // end namespace Detail
  2334. namespace literals {
  2335. Detail::Approx operator "" _a(long double val);
  2336. Detail::Approx operator "" _a(unsigned long long val);
  2337. } // end namespace literals
  2338. template<>
  2339. struct StringMaker<Catch::Detail::Approx> {
  2340. static std::string convert(Catch::Detail::Approx const& value);
  2341. };
  2342. } // end namespace Catch
  2343. // end catch_approx.h
  2344. // start catch_string_manip.h
  2345. #include <string>
  2346. #include <iosfwd>
  2347. namespace Catch {
  2348. bool startsWith( std::string const& s, std::string const& prefix );
  2349. bool startsWith( std::string const& s, char prefix );
  2350. bool endsWith( std::string const& s, std::string const& suffix );
  2351. bool endsWith( std::string const& s, char suffix );
  2352. bool contains( std::string const& s, std::string const& infix );
  2353. void toLowerInPlace( std::string& s );
  2354. std::string toLower( std::string const& s );
  2355. std::string trim( std::string const& str );
  2356. bool replaceInPlace( std::string& str, std::string const& replaceThis, std::string const& withThis );
  2357. struct pluralise {
  2358. pluralise( std::size_t count, std::string const& label );
  2359. friend std::ostream& operator << ( std::ostream& os, pluralise const& pluraliser );
  2360. std::size_t m_count;
  2361. std::string m_label;
  2362. };
  2363. }
  2364. // end catch_string_manip.h
  2365. #ifndef CATCH_CONFIG_DISABLE_MATCHERS
  2366. // start catch_capture_matchers.h
  2367. // start catch_matchers.h
  2368. #include <string>
  2369. #include <vector>
  2370. namespace Catch {
  2371. namespace Matchers {
  2372. namespace Impl {
  2373. template<typename ArgT> struct MatchAllOf;
  2374. template<typename ArgT> struct MatchAnyOf;
  2375. template<typename ArgT> struct MatchNotOf;
  2376. class MatcherUntypedBase {
  2377. public:
  2378. MatcherUntypedBase() = default;
  2379. MatcherUntypedBase ( MatcherUntypedBase const& ) = default;
  2380. MatcherUntypedBase& operator = ( MatcherUntypedBase const& ) = delete;
  2381. std::string toString() const;
  2382. protected:
  2383. virtual ~MatcherUntypedBase();
  2384. virtual std::string describe() const = 0;
  2385. mutable std::string m_cachedToString;
  2386. };
  2387. #ifdef __clang__
  2388. # pragma clang diagnostic push
  2389. # pragma clang diagnostic ignored "-Wnon-virtual-dtor"
  2390. #endif
  2391. template<typename ObjectT>
  2392. struct MatcherMethod {
  2393. virtual bool match( ObjectT const& arg ) const = 0;
  2394. };
  2395. #ifdef __clang__
  2396. # pragma clang diagnostic pop
  2397. #endif
  2398. template<typename T>
  2399. struct MatcherBase : MatcherUntypedBase, MatcherMethod<T> {
  2400. MatchAllOf<T> operator && ( MatcherBase const& other ) const;
  2401. MatchAnyOf<T> operator || ( MatcherBase const& other ) const;
  2402. MatchNotOf<T> operator ! () const;
  2403. };
  2404. template<typename ArgT>
  2405. struct MatchAllOf : MatcherBase<ArgT> {
  2406. bool match( ArgT const& arg ) const override {
  2407. for( auto matcher : m_matchers ) {
  2408. if (!matcher->match(arg))
  2409. return false;
  2410. }
  2411. return true;
  2412. }
  2413. std::string describe() const override {
  2414. std::string description;
  2415. description.reserve( 4 + m_matchers.size()*32 );
  2416. description += "( ";
  2417. bool first = true;
  2418. for( auto matcher : m_matchers ) {
  2419. if( first )
  2420. first = false;
  2421. else
  2422. description += " and ";
  2423. description += matcher->toString();
  2424. }
  2425. description += " )";
  2426. return description;
  2427. }
  2428. MatchAllOf<ArgT>& operator && ( MatcherBase<ArgT> const& other ) {
  2429. m_matchers.push_back( &other );
  2430. return *this;
  2431. }
  2432. std::vector<MatcherBase<ArgT> const*> m_matchers;
  2433. };
  2434. template<typename ArgT>
  2435. struct MatchAnyOf : MatcherBase<ArgT> {
  2436. bool match( ArgT const& arg ) const override {
  2437. for( auto matcher : m_matchers ) {
  2438. if (matcher->match(arg))
  2439. return true;
  2440. }
  2441. return false;
  2442. }
  2443. std::string describe() const override {
  2444. std::string description;
  2445. description.reserve( 4 + m_matchers.size()*32 );
  2446. description += "( ";
  2447. bool first = true;
  2448. for( auto matcher : m_matchers ) {
  2449. if( first )
  2450. first = false;
  2451. else
  2452. description += " or ";
  2453. description += matcher->toString();
  2454. }
  2455. description += " )";
  2456. return description;
  2457. }
  2458. MatchAnyOf<ArgT>& operator || ( MatcherBase<ArgT> const& other ) {
  2459. m_matchers.push_back( &other );
  2460. return *this;
  2461. }
  2462. std::vector<MatcherBase<ArgT> const*> m_matchers;
  2463. };
  2464. template<typename ArgT>
  2465. struct MatchNotOf : MatcherBase<ArgT> {
  2466. MatchNotOf( MatcherBase<ArgT> const& underlyingMatcher ) : m_underlyingMatcher( underlyingMatcher ) {}
  2467. bool match( ArgT const& arg ) const override {
  2468. return !m_underlyingMatcher.match( arg );
  2469. }
  2470. std::string describe() const override {
  2471. return "not " + m_underlyingMatcher.toString();
  2472. }
  2473. MatcherBase<ArgT> const& m_underlyingMatcher;
  2474. };
  2475. template<typename T>
  2476. MatchAllOf<T> MatcherBase<T>::operator && ( MatcherBase const& other ) const {
  2477. return MatchAllOf<T>() && *this && other;
  2478. }
  2479. template<typename T>
  2480. MatchAnyOf<T> MatcherBase<T>::operator || ( MatcherBase const& other ) const {
  2481. return MatchAnyOf<T>() || *this || other;
  2482. }
  2483. template<typename T>
  2484. MatchNotOf<T> MatcherBase<T>::operator ! () const {
  2485. return MatchNotOf<T>( *this );
  2486. }
  2487. } // namespace Impl
  2488. } // namespace Matchers
  2489. using namespace Matchers;
  2490. using Matchers::Impl::MatcherBase;
  2491. } // namespace Catch
  2492. // end catch_matchers.h
  2493. // start catch_matchers_floating.h
  2494. #include <type_traits>
  2495. #include <cmath>
  2496. namespace Catch {
  2497. namespace Matchers {
  2498. namespace Floating {
  2499. enum class FloatingPointKind : uint8_t;
  2500. struct WithinAbsMatcher : MatcherBase<double> {
  2501. WithinAbsMatcher(double target, double margin);
  2502. bool match(double const& matchee) const override;
  2503. std::string describe() const override;
  2504. private:
  2505. double m_target;
  2506. double m_margin;
  2507. };
  2508. struct WithinUlpsMatcher : MatcherBase<double> {
  2509. WithinUlpsMatcher(double target, int ulps, FloatingPointKind baseType);
  2510. bool match(double const& matchee) const override;
  2511. std::string describe() const override;
  2512. private:
  2513. double m_target;
  2514. int m_ulps;
  2515. FloatingPointKind m_type;
  2516. };
  2517. } // namespace Floating
  2518. // The following functions create the actual matcher objects.
  2519. // This allows the types to be inferred
  2520. Floating::WithinUlpsMatcher WithinULP(double target, int maxUlpDiff);
  2521. Floating::WithinUlpsMatcher WithinULP(float target, int maxUlpDiff);
  2522. Floating::WithinAbsMatcher WithinAbs(double target, double margin);
  2523. } // namespace Matchers
  2524. } // namespace Catch
  2525. // end catch_matchers_floating.h
  2526. // start catch_matchers_generic.hpp
  2527. #include <functional>
  2528. #include <string>
  2529. namespace Catch {
  2530. namespace Matchers {
  2531. namespace Generic {
  2532. namespace Detail {
  2533. std::string finalizeDescription(const std::string& desc);
  2534. }
  2535. template <typename T>
  2536. class PredicateMatcher : public MatcherBase<T> {
  2537. std::function<bool(T const&)> m_predicate;
  2538. std::string m_description;
  2539. public:
  2540. PredicateMatcher(std::function<bool(T const&)> const& elem, std::string const& descr)
  2541. :m_predicate(std::move(elem)),
  2542. m_description(Detail::finalizeDescription(descr))
  2543. {}
  2544. bool match( T const& item ) const override {
  2545. return m_predicate(item);
  2546. }
  2547. std::string describe() const override {
  2548. return m_description;
  2549. }
  2550. };
  2551. } // namespace Generic
  2552. // The following functions create the actual matcher objects.
  2553. // The user has to explicitly specify type to the function, because
  2554. // infering std::function<bool(T const&)> is hard (but possible) and
  2555. // requires a lot of TMP.
  2556. template<typename T>
  2557. Generic::PredicateMatcher<T> Predicate(std::function<bool(T const&)> const& predicate, std::string const& description = "") {
  2558. return Generic::PredicateMatcher<T>(predicate, description);
  2559. }
  2560. } // namespace Matchers
  2561. } // namespace Catch
  2562. // end catch_matchers_generic.hpp
  2563. // start catch_matchers_string.h
  2564. #include <string>
  2565. namespace Catch {
  2566. namespace Matchers {
  2567. namespace StdString {
  2568. struct CasedString
  2569. {
  2570. CasedString( std::string const& str, CaseSensitive::Choice caseSensitivity );
  2571. std::string adjustString( std::string const& str ) const;
  2572. std::string caseSensitivitySuffix() const;
  2573. CaseSensitive::Choice m_caseSensitivity;
  2574. std::string m_str;
  2575. };
  2576. struct StringMatcherBase : MatcherBase<std::string> {
  2577. StringMatcherBase( std::string const& operation, CasedString const& comparator );
  2578. std::string describe() const override;
  2579. CasedString m_comparator;
  2580. std::string m_operation;
  2581. };
  2582. struct EqualsMatcher : StringMatcherBase {
  2583. EqualsMatcher( CasedString const& comparator );
  2584. bool match( std::string const& source ) const override;
  2585. };
  2586. struct ContainsMatcher : StringMatcherBase {
  2587. ContainsMatcher( CasedString const& comparator );
  2588. bool match( std::string const& source ) const override;
  2589. };
  2590. struct StartsWithMatcher : StringMatcherBase {
  2591. StartsWithMatcher( CasedString const& comparator );
  2592. bool match( std::string const& source ) const override;
  2593. };
  2594. struct EndsWithMatcher : StringMatcherBase {
  2595. EndsWithMatcher( CasedString const& comparator );
  2596. bool match( std::string const& source ) const override;
  2597. };
  2598. struct RegexMatcher : MatcherBase<std::string> {
  2599. RegexMatcher( std::string regex, CaseSensitive::Choice caseSensitivity );
  2600. bool match( std::string const& matchee ) const override;
  2601. std::string describe() const override;
  2602. private:
  2603. std::string m_regex;
  2604. CaseSensitive::Choice m_caseSensitivity;
  2605. };
  2606. } // namespace StdString
  2607. // The following functions create the actual matcher objects.
  2608. // This allows the types to be inferred
  2609. StdString::EqualsMatcher Equals( std::string const& str, CaseSensitive::Choice caseSensitivity = CaseSensitive::Yes );
  2610. StdString::ContainsMatcher Contains( std::string const& str, CaseSensitive::Choice caseSensitivity = CaseSensitive::Yes );
  2611. StdString::EndsWithMatcher EndsWith( std::string const& str, CaseSensitive::Choice caseSensitivity = CaseSensitive::Yes );
  2612. StdString::StartsWithMatcher StartsWith( std::string const& str, CaseSensitive::Choice caseSensitivity = CaseSensitive::Yes );
  2613. StdString::RegexMatcher Matches( std::string const& regex, CaseSensitive::Choice caseSensitivity = CaseSensitive::Yes );
  2614. } // namespace Matchers
  2615. } // namespace Catch
  2616. // end catch_matchers_string.h
  2617. // start catch_matchers_vector.h
  2618. #include <algorithm>
  2619. namespace Catch {
  2620. namespace Matchers {
  2621. namespace Vector {
  2622. namespace Detail {
  2623. template <typename InputIterator, typename T>
  2624. size_t count(InputIterator first, InputIterator last, T const& item) {
  2625. size_t cnt = 0;
  2626. for (; first != last; ++first) {
  2627. if (*first == item) {
  2628. ++cnt;
  2629. }
  2630. }
  2631. return cnt;
  2632. }
  2633. template <typename InputIterator, typename T>
  2634. bool contains(InputIterator first, InputIterator last, T const& item) {
  2635. for (; first != last; ++first) {
  2636. if (*first == item) {
  2637. return true;
  2638. }
  2639. }
  2640. return false;
  2641. }
  2642. }
  2643. template<typename T>
  2644. struct ContainsElementMatcher : MatcherBase<std::vector<T>> {
  2645. ContainsElementMatcher(T const &comparator) : m_comparator( comparator) {}
  2646. bool match(std::vector<T> const &v) const override {
  2647. for (auto const& el : v) {
  2648. if (el == m_comparator) {
  2649. return true;
  2650. }
  2651. }
  2652. return false;
  2653. }
  2654. std::string describe() const override {
  2655. return "Contains: " + ::Catch::Detail::stringify( m_comparator );
  2656. }
  2657. T const& m_comparator;
  2658. };
  2659. template<typename T>
  2660. struct ContainsMatcher : MatcherBase<std::vector<T>> {
  2661. ContainsMatcher(std::vector<T> const &comparator) : m_comparator( comparator ) {}
  2662. bool match(std::vector<T> const &v) const override {
  2663. // !TBD: see note in EqualsMatcher
  2664. if (m_comparator.size() > v.size())
  2665. return false;
  2666. for (auto const& comparator : m_comparator) {
  2667. auto present = false;
  2668. for (const auto& el : v) {
  2669. if (el == comparator) {
  2670. present = true;
  2671. break;
  2672. }
  2673. }
  2674. if (!present) {
  2675. return false;
  2676. }
  2677. }
  2678. return true;
  2679. }
  2680. std::string describe() const override {
  2681. return "Contains: " + ::Catch::Detail::stringify( m_comparator );
  2682. }
  2683. std::vector<T> const& m_comparator;
  2684. };
  2685. template<typename T>
  2686. struct EqualsMatcher : MatcherBase<std::vector<T>> {
  2687. EqualsMatcher(std::vector<T> const &comparator) : m_comparator( comparator ) {}
  2688. bool match(std::vector<T> const &v) const override {
  2689. // !TBD: This currently works if all elements can be compared using !=
  2690. // - a more general approach would be via a compare template that defaults
  2691. // to using !=. but could be specialised for, e.g. std::vector<T> etc
  2692. // - then just call that directly
  2693. if (m_comparator.size() != v.size())
  2694. return false;
  2695. for (std::size_t i = 0; i < v.size(); ++i)
  2696. if (m_comparator[i] != v[i])
  2697. return false;
  2698. return true;
  2699. }
  2700. std::string describe() const override {
  2701. return "Equals: " + ::Catch::Detail::stringify( m_comparator );
  2702. }
  2703. std::vector<T> const& m_comparator;
  2704. };
  2705. template<typename T>
  2706. struct UnorderedEqualsMatcher : MatcherBase<std::vector<T>> {
  2707. UnorderedEqualsMatcher(std::vector<T> const& target) : m_target(target) {}
  2708. bool match(std::vector<T> const& vec) const override {
  2709. // Note: This is a reimplementation of std::is_permutation,
  2710. // because I don't want to include <algorithm> inside the common path
  2711. if (m_target.size() != vec.size()) {
  2712. return false;
  2713. }
  2714. auto lfirst = m_target.begin(), llast = m_target.end();
  2715. auto rfirst = vec.begin(), rlast = vec.end();
  2716. // Cut common prefix to optimize checking of permuted parts
  2717. while (lfirst != llast && *lfirst == *rfirst) {
  2718. ++lfirst; ++rfirst;
  2719. }
  2720. if (lfirst == llast) {
  2721. return true;
  2722. }
  2723. for (auto mid = lfirst; mid != llast; ++mid) {
  2724. // Skip already counted items
  2725. if (Detail::contains(lfirst, mid, *mid)) {
  2726. continue;
  2727. }
  2728. size_t num_vec = Detail::count(rfirst, rlast, *mid);
  2729. if (num_vec == 0 || Detail::count(lfirst, llast, *mid) != num_vec) {
  2730. return false;
  2731. }
  2732. }
  2733. return true;
  2734. }
  2735. std::string describe() const override {
  2736. return "UnorderedEquals: " + ::Catch::Detail::stringify(m_target);
  2737. }
  2738. private:
  2739. std::vector<T> const& m_target;
  2740. };
  2741. } // namespace Vector
  2742. // The following functions create the actual matcher objects.
  2743. // This allows the types to be inferred
  2744. template<typename T>
  2745. Vector::ContainsMatcher<T> Contains( std::vector<T> const& comparator ) {
  2746. return Vector::ContainsMatcher<T>( comparator );
  2747. }
  2748. template<typename T>
  2749. Vector::ContainsElementMatcher<T> VectorContains( T const& comparator ) {
  2750. return Vector::ContainsElementMatcher<T>( comparator );
  2751. }
  2752. template<typename T>
  2753. Vector::EqualsMatcher<T> Equals( std::vector<T> const& comparator ) {
  2754. return Vector::EqualsMatcher<T>( comparator );
  2755. }
  2756. template<typename T>
  2757. Vector::UnorderedEqualsMatcher<T> UnorderedEquals(std::vector<T> const& target) {
  2758. return Vector::UnorderedEqualsMatcher<T>(target);
  2759. }
  2760. } // namespace Matchers
  2761. } // namespace Catch
  2762. // end catch_matchers_vector.h
  2763. namespace Catch {
  2764. template<typename ArgT, typename MatcherT>
  2765. class MatchExpr : public ITransientExpression {
  2766. ArgT const& m_arg;
  2767. MatcherT m_matcher;
  2768. StringRef m_matcherString;
  2769. public:
  2770. MatchExpr( ArgT const& arg, MatcherT const& matcher, StringRef const& matcherString )
  2771. : ITransientExpression{ true, matcher.match( arg ) },
  2772. m_arg( arg ),
  2773. m_matcher( matcher ),
  2774. m_matcherString( matcherString )
  2775. {}
  2776. void streamReconstructedExpression( std::ostream &os ) const override {
  2777. auto matcherAsString = m_matcher.toString();
  2778. os << Catch::Detail::stringify( m_arg ) << ' ';
  2779. if( matcherAsString == Detail::unprintableString )
  2780. os << m_matcherString;
  2781. else
  2782. os << matcherAsString;
  2783. }
  2784. };
  2785. using StringMatcher = Matchers::Impl::MatcherBase<std::string>;
  2786. void handleExceptionMatchExpr( AssertionHandler& handler, StringMatcher const& matcher, StringRef const& matcherString );
  2787. template<typename ArgT, typename MatcherT>
  2788. auto makeMatchExpr( ArgT const& arg, MatcherT const& matcher, StringRef const& matcherString ) -> MatchExpr<ArgT, MatcherT> {
  2789. return MatchExpr<ArgT, MatcherT>( arg, matcher, matcherString );
  2790. }
  2791. } // namespace Catch
  2792. ///////////////////////////////////////////////////////////////////////////////
  2793. #define INTERNAL_CHECK_THAT( macroName, matcher, resultDisposition, arg ) \
  2794. do { \
  2795. Catch::AssertionHandler catchAssertionHandler( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(arg) ", " CATCH_INTERNAL_STRINGIFY(matcher), resultDisposition ); \
  2796. INTERNAL_CATCH_TRY { \
  2797. catchAssertionHandler.handleExpr( Catch::makeMatchExpr( arg, matcher, #matcher##_catch_sr ) ); \
  2798. } INTERNAL_CATCH_CATCH( catchAssertionHandler ) \
  2799. INTERNAL_CATCH_REACT( catchAssertionHandler ) \
  2800. } while( false )
  2801. ///////////////////////////////////////////////////////////////////////////////
  2802. #define INTERNAL_CATCH_THROWS_MATCHES( macroName, exceptionType, resultDisposition, matcher, ... ) \
  2803. do { \
  2804. Catch::AssertionHandler catchAssertionHandler( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(__VA_ARGS__) ", " CATCH_INTERNAL_STRINGIFY(exceptionType) ", " CATCH_INTERNAL_STRINGIFY(matcher), resultDisposition ); \
  2805. if( catchAssertionHandler.allowThrows() ) \
  2806. try { \
  2807. static_cast<void>(__VA_ARGS__ ); \
  2808. catchAssertionHandler.handleUnexpectedExceptionNotThrown(); \
  2809. } \
  2810. catch( exceptionType const& ex ) { \
  2811. catchAssertionHandler.handleExpr( Catch::makeMatchExpr( ex, matcher, #matcher##_catch_sr ) ); \
  2812. } \
  2813. catch( ... ) { \
  2814. catchAssertionHandler.handleUnexpectedInflightException(); \
  2815. } \
  2816. else \
  2817. catchAssertionHandler.handleThrowingCallSkipped(); \
  2818. INTERNAL_CATCH_REACT( catchAssertionHandler ) \
  2819. } while( false )
  2820. // end catch_capture_matchers.h
  2821. #endif
  2822. // start catch_generators.hpp
  2823. // start catch_interfaces_generatortracker.h
  2824. #include <memory>
  2825. namespace Catch {
  2826. namespace Generators {
  2827. class GeneratorUntypedBase {
  2828. public:
  2829. GeneratorUntypedBase() = default;
  2830. virtual ~GeneratorUntypedBase();
  2831. // Attempts to move the generator to the next element
  2832. //
  2833. // Returns true iff the move succeeded (and a valid element
  2834. // can be retrieved).
  2835. virtual bool next() = 0;
  2836. };
  2837. using GeneratorBasePtr = std::unique_ptr<GeneratorUntypedBase>;
  2838. } // namespace Generators
  2839. struct IGeneratorTracker {
  2840. virtual ~IGeneratorTracker();
  2841. virtual auto hasGenerator() const -> bool = 0;
  2842. virtual auto getGenerator() const -> Generators::GeneratorBasePtr const& = 0;
  2843. virtual void setGenerator( Generators::GeneratorBasePtr&& generator ) = 0;
  2844. };
  2845. } // namespace Catch
  2846. // end catch_interfaces_generatortracker.h
  2847. // start catch_enforce.h
  2848. #include <stdexcept>
  2849. namespace Catch {
  2850. #if !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
  2851. template <typename Ex>
  2852. [[noreturn]]
  2853. void throw_exception(Ex const& e) {
  2854. throw e;
  2855. }
  2856. #else // ^^ Exceptions are enabled // Exceptions are disabled vv
  2857. [[noreturn]]
  2858. void throw_exception(std::exception const& e);
  2859. #endif
  2860. } // namespace Catch;
  2861. #define CATCH_PREPARE_EXCEPTION( type, msg ) \
  2862. type( ( Catch::ReusableStringStream() << msg ).str() )
  2863. #define CATCH_INTERNAL_ERROR( msg ) \
  2864. Catch::throw_exception(CATCH_PREPARE_EXCEPTION( std::logic_error, CATCH_INTERNAL_LINEINFO << ": Internal Catch error: " << msg))
  2865. #define CATCH_ERROR( msg ) \
  2866. Catch::throw_exception(CATCH_PREPARE_EXCEPTION( std::domain_error, msg ))
  2867. #define CATCH_RUNTIME_ERROR( msg ) \
  2868. Catch::throw_exception(CATCH_PREPARE_EXCEPTION( std::runtime_error, msg ))
  2869. #define CATCH_ENFORCE( condition, msg ) \
  2870. do{ if( !(condition) ) CATCH_ERROR( msg ); } while(false)
  2871. // end catch_enforce.h
  2872. #include <memory>
  2873. #include <vector>
  2874. #include <cassert>
  2875. #include <utility>
  2876. #include <exception>
  2877. namespace Catch {
  2878. class GeneratorException : public std::exception {
  2879. const char* const m_msg = "";
  2880. public:
  2881. GeneratorException(const char* msg):
  2882. m_msg(msg)
  2883. {}
  2884. const char* what() const noexcept override final;
  2885. };
  2886. namespace Generators {
  2887. // !TBD move this into its own location?
  2888. namespace pf{
  2889. template<typename T, typename... Args>
  2890. std::unique_ptr<T> make_unique( Args&&... args ) {
  2891. return std::unique_ptr<T>(new T(std::forward<Args>(args)...));
  2892. }
  2893. }
  2894. template<typename T>
  2895. struct IGenerator : GeneratorUntypedBase {
  2896. virtual ~IGenerator() = default;
  2897. // Returns the current element of the generator
  2898. //
  2899. // \Precondition The generator is either freshly constructed,
  2900. // or the last call to `next()` returned true
  2901. virtual T const& get() const = 0;
  2902. using type = T;
  2903. };
  2904. template<typename T>
  2905. class SingleValueGenerator final : public IGenerator<T> {
  2906. T m_value;
  2907. public:
  2908. SingleValueGenerator(T const& value) : m_value( value ) {}
  2909. SingleValueGenerator(T&& value) : m_value(std::move(value)) {}
  2910. T const& get() const override {
  2911. return m_value;
  2912. }
  2913. bool next() override {
  2914. return false;
  2915. }
  2916. };
  2917. template<typename T>
  2918. class FixedValuesGenerator final : public IGenerator<T> {
  2919. std::vector<T> m_values;
  2920. size_t m_idx = 0;
  2921. public:
  2922. FixedValuesGenerator( std::initializer_list<T> values ) : m_values( values ) {}
  2923. T const& get() const override {
  2924. return m_values[m_idx];
  2925. }
  2926. bool next() override {
  2927. ++m_idx;
  2928. return m_idx < m_values.size();
  2929. }
  2930. };
  2931. template <typename T>
  2932. class GeneratorWrapper final {
  2933. std::unique_ptr<IGenerator<T>> m_generator;
  2934. public:
  2935. GeneratorWrapper(std::unique_ptr<IGenerator<T>> generator):
  2936. m_generator(std::move(generator))
  2937. {}
  2938. T const& get() const {
  2939. return m_generator->get();
  2940. }
  2941. bool next() {
  2942. return m_generator->next();
  2943. }
  2944. };
  2945. template <typename T>
  2946. GeneratorWrapper<T> value(T&& value) {
  2947. return GeneratorWrapper<T>(pf::make_unique<SingleValueGenerator<T>>(std::forward<T>(value)));
  2948. }
  2949. template <typename T>
  2950. GeneratorWrapper<T> values(std::initializer_list<T> values) {
  2951. return GeneratorWrapper<T>(pf::make_unique<FixedValuesGenerator<T>>(values));
  2952. }
  2953. template<typename T>
  2954. class Generators : public IGenerator<T> {
  2955. std::vector<GeneratorWrapper<T>> m_generators;
  2956. size_t m_current = 0;
  2957. void populate(GeneratorWrapper<T>&& generator) {
  2958. m_generators.emplace_back(std::move(generator));
  2959. }
  2960. void populate(T&& val) {
  2961. m_generators.emplace_back(value(std::move(val)));
  2962. }
  2963. template<typename U>
  2964. void populate(U&& val) {
  2965. populate(T(std::move(val)));
  2966. }
  2967. template<typename U, typename... Gs>
  2968. void populate(U&& valueOrGenerator, Gs... moreGenerators) {
  2969. populate(std::forward<U>(valueOrGenerator));
  2970. populate(std::forward<Gs>(moreGenerators)...);
  2971. }
  2972. public:
  2973. template <typename... Gs>
  2974. Generators(Gs... moreGenerators) {
  2975. m_generators.reserve(sizeof...(Gs));
  2976. populate(std::forward<Gs>(moreGenerators)...);
  2977. }
  2978. T const& get() const override {
  2979. return m_generators[m_current].get();
  2980. }
  2981. bool next() override {
  2982. if (m_current >= m_generators.size()) {
  2983. return false;
  2984. }
  2985. const bool current_status = m_generators[m_current].next();
  2986. if (!current_status) {
  2987. ++m_current;
  2988. }
  2989. return m_current < m_generators.size();
  2990. }
  2991. };
  2992. template<typename... Ts>
  2993. GeneratorWrapper<std::tuple<Ts...>> table( std::initializer_list<std::tuple<typename std::decay<Ts>::type...>> tuples ) {
  2994. return values<std::tuple<Ts...>>( tuples );
  2995. }
  2996. // Tag type to signal that a generator sequence should convert arguments to a specific type
  2997. template <typename T>
  2998. struct as {};
  2999. template<typename T, typename... Gs>
  3000. auto makeGenerators( GeneratorWrapper<T>&& generator, Gs... moreGenerators ) -> Generators<T> {
  3001. return Generators<T>(std::move(generator), std::forward<Gs>(moreGenerators)...);
  3002. }
  3003. template<typename T>
  3004. auto makeGenerators( GeneratorWrapper<T>&& generator ) -> Generators<T> {
  3005. return Generators<T>(std::move(generator));
  3006. }
  3007. template<typename T, typename... Gs>
  3008. auto makeGenerators( T&& val, Gs... moreGenerators ) -> Generators<T> {
  3009. return makeGenerators( value( std::forward<T>( val ) ), std::forward<Gs>( moreGenerators )... );
  3010. }
  3011. template<typename T, typename U, typename... Gs>
  3012. auto makeGenerators( as<T>, U&& val, Gs... moreGenerators ) -> Generators<T> {
  3013. return makeGenerators( value( T( std::forward<U>( val ) ) ), std::forward<Gs>( moreGenerators )... );
  3014. }
  3015. auto acquireGeneratorTracker( SourceLineInfo const& lineInfo ) -> IGeneratorTracker&;
  3016. template<typename L>
  3017. // Note: The type after -> is weird, because VS2015 cannot parse
  3018. // the expression used in the typedef inside, when it is in
  3019. // return type. Yeah.
  3020. auto generate( SourceLineInfo const& lineInfo, L const& generatorExpression ) -> decltype(std::declval<decltype(generatorExpression())>().get()) {
  3021. using UnderlyingType = typename decltype(generatorExpression())::type;
  3022. IGeneratorTracker& tracker = acquireGeneratorTracker( lineInfo );
  3023. if (!tracker.hasGenerator()) {
  3024. tracker.setGenerator(pf::make_unique<Generators<UnderlyingType>>(generatorExpression()));
  3025. }
  3026. auto const& generator = static_cast<IGenerator<UnderlyingType> const&>( *tracker.getGenerator() );
  3027. return generator.get();
  3028. }
  3029. } // namespace Generators
  3030. } // namespace Catch
  3031. #define GENERATE( ... ) \
  3032. Catch::Generators::generate( CATCH_INTERNAL_LINEINFO, [ ]{ using namespace Catch::Generators; return makeGenerators( __VA_ARGS__ ); } )
  3033. #define GENERATE_COPY( ... ) \
  3034. Catch::Generators::generate( CATCH_INTERNAL_LINEINFO, [=]{ using namespace Catch::Generators; return makeGenerators( __VA_ARGS__ ); } )
  3035. #define GENERATE_REF( ... ) \
  3036. Catch::Generators::generate( CATCH_INTERNAL_LINEINFO, [&]{ using namespace Catch::Generators; return makeGenerators( __VA_ARGS__ ); } )
  3037. // end catch_generators.hpp
  3038. // start catch_generators_generic.hpp
  3039. namespace Catch {
  3040. namespace Generators {
  3041. template <typename T>
  3042. class TakeGenerator : public IGenerator<T> {
  3043. GeneratorWrapper<T> m_generator;
  3044. size_t m_returned = 0;
  3045. size_t m_target;
  3046. public:
  3047. TakeGenerator(size_t target, GeneratorWrapper<T>&& generator):
  3048. m_generator(std::move(generator)),
  3049. m_target(target)
  3050. {
  3051. assert(target != 0 && "Empty generators are not allowed");
  3052. }
  3053. T const& get() const override {
  3054. return m_generator.get();
  3055. }
  3056. bool next() override {
  3057. ++m_returned;
  3058. if (m_returned >= m_target) {
  3059. return false;
  3060. }
  3061. const auto success = m_generator.next();
  3062. // If the underlying generator does not contain enough values
  3063. // then we cut short as well
  3064. if (!success) {
  3065. m_returned = m_target;
  3066. }
  3067. return success;
  3068. }
  3069. };
  3070. template <typename T>
  3071. GeneratorWrapper<T> take(size_t target, GeneratorWrapper<T>&& generator) {
  3072. return GeneratorWrapper<T>(pf::make_unique<TakeGenerator<T>>(target, std::move(generator)));
  3073. }
  3074. template <typename T, typename Predicate>
  3075. class FilterGenerator : public IGenerator<T> {
  3076. GeneratorWrapper<T> m_generator;
  3077. Predicate m_predicate;
  3078. public:
  3079. template <typename P = Predicate>
  3080. FilterGenerator(P&& pred, GeneratorWrapper<T>&& generator):
  3081. m_generator(std::move(generator)),
  3082. m_predicate(std::forward<P>(pred))
  3083. {
  3084. if (!m_predicate(m_generator.get())) {
  3085. // It might happen that there are no values that pass the
  3086. // filter. In that case we throw an exception.
  3087. auto has_initial_value = next();
  3088. if (!has_initial_value) {
  3089. Catch::throw_exception(GeneratorException("No valid value found in filtered generator"));
  3090. }
  3091. }
  3092. }
  3093. T const& get() const override {
  3094. return m_generator.get();
  3095. }
  3096. bool next() override {
  3097. bool success = m_generator.next();
  3098. if (!success) {
  3099. return false;
  3100. }
  3101. while (!m_predicate(m_generator.get()) && (success = m_generator.next()) == true);
  3102. return success;
  3103. }
  3104. };
  3105. template <typename T, typename Predicate>
  3106. GeneratorWrapper<T> filter(Predicate&& pred, GeneratorWrapper<T>&& generator) {
  3107. return GeneratorWrapper<T>(std::unique_ptr<IGenerator<T>>(pf::make_unique<FilterGenerator<T, Predicate>>(std::forward<Predicate>(pred), std::move(generator))));
  3108. }
  3109. template <typename T>
  3110. class RepeatGenerator : public IGenerator<T> {
  3111. GeneratorWrapper<T> m_generator;
  3112. mutable std::vector<T> m_returned;
  3113. size_t m_target_repeats;
  3114. size_t m_current_repeat = 0;
  3115. size_t m_repeat_index = 0;
  3116. public:
  3117. RepeatGenerator(size_t repeats, GeneratorWrapper<T>&& generator):
  3118. m_generator(std::move(generator)),
  3119. m_target_repeats(repeats)
  3120. {
  3121. assert(m_target_repeats > 0 && "Repeat generator must repeat at least once");
  3122. }
  3123. T const& get() const override {
  3124. if (m_current_repeat == 0) {
  3125. m_returned.push_back(m_generator.get());
  3126. return m_returned.back();
  3127. }
  3128. return m_returned[m_repeat_index];
  3129. }
  3130. bool next() override {
  3131. // There are 2 basic cases:
  3132. // 1) We are still reading the generator
  3133. // 2) We are reading our own cache
  3134. // In the first case, we need to poke the underlying generator.
  3135. // If it happily moves, we are left in that state, otherwise it is time to start reading from our cache
  3136. if (m_current_repeat == 0) {
  3137. const auto success = m_generator.next();
  3138. if (!success) {
  3139. ++m_current_repeat;
  3140. }
  3141. return m_current_repeat < m_target_repeats;
  3142. }
  3143. // In the second case, we need to move indices forward and check that we haven't run up against the end
  3144. ++m_repeat_index;
  3145. if (m_repeat_index == m_returned.size()) {
  3146. m_repeat_index = 0;
  3147. ++m_current_repeat;
  3148. }
  3149. return m_current_repeat < m_target_repeats;
  3150. }
  3151. };
  3152. template <typename T>
  3153. GeneratorWrapper<T> repeat(size_t repeats, GeneratorWrapper<T>&& generator) {
  3154. return GeneratorWrapper<T>(pf::make_unique<RepeatGenerator<T>>(repeats, std::move(generator)));
  3155. }
  3156. template <typename T, typename U, typename Func>
  3157. class MapGenerator : public IGenerator<T> {
  3158. // TBD: provide static assert for mapping function, for friendly error message
  3159. GeneratorWrapper<U> m_generator;
  3160. Func m_function;
  3161. // To avoid returning dangling reference, we have to save the values
  3162. T m_cache;
  3163. public:
  3164. template <typename F2 = Func>
  3165. MapGenerator(F2&& function, GeneratorWrapper<U>&& generator) :
  3166. m_generator(std::move(generator)),
  3167. m_function(std::forward<F2>(function)),
  3168. m_cache(m_function(m_generator.get()))
  3169. {}
  3170. T const& get() const override {
  3171. return m_cache;
  3172. }
  3173. bool next() override {
  3174. const auto success = m_generator.next();
  3175. if (success) {
  3176. m_cache = m_function(m_generator.get());
  3177. }
  3178. return success;
  3179. }
  3180. };
  3181. #if defined(__cpp_lib_is_invocable) && __cpp_lib_is_invocable >= 201703
  3182. // std::result_of is deprecated in C++17 and removed in C++20. Hence, it is
  3183. // replaced with std::invoke_result here. Also *_t format is preferred over
  3184. // typename *::type format.
  3185. template <typename Func, typename U>
  3186. using MapFunctionReturnType = std::remove_reference_t<std::remove_cv_t<std::invoke_result_t<Func, U>>>;
  3187. #else
  3188. template <typename Func, typename U>
  3189. using MapFunctionReturnType = typename std::remove_reference<typename std::remove_cv<typename std::result_of<Func(U)>::type>::type>::type;
  3190. #endif
  3191. template <typename Func, typename U, typename T = MapFunctionReturnType<Func, U>>
  3192. GeneratorWrapper<T> map(Func&& function, GeneratorWrapper<U>&& generator) {
  3193. return GeneratorWrapper<T>(
  3194. pf::make_unique<MapGenerator<T, U, Func>>(std::forward<Func>(function), std::move(generator))
  3195. );
  3196. }
  3197. template <typename T, typename U, typename Func>
  3198. GeneratorWrapper<T> map(Func&& function, GeneratorWrapper<U>&& generator) {
  3199. return GeneratorWrapper<T>(
  3200. pf::make_unique<MapGenerator<T, U, Func>>(std::forward<Func>(function), std::move(generator))
  3201. );
  3202. }
  3203. template <typename T>
  3204. class ChunkGenerator final : public IGenerator<std::vector<T>> {
  3205. std::vector<T> m_chunk;
  3206. size_t m_chunk_size;
  3207. GeneratorWrapper<T> m_generator;
  3208. bool m_used_up = false;
  3209. public:
  3210. ChunkGenerator(size_t size, GeneratorWrapper<T> generator) :
  3211. m_chunk_size(size), m_generator(std::move(generator))
  3212. {
  3213. m_chunk.reserve(m_chunk_size);
  3214. m_chunk.push_back(m_generator.get());
  3215. for (size_t i = 1; i < m_chunk_size; ++i) {
  3216. if (!m_generator.next()) {
  3217. Catch::throw_exception(GeneratorException("Not enough values to initialize the first chunk"));
  3218. }
  3219. m_chunk.push_back(m_generator.get());
  3220. }
  3221. }
  3222. std::vector<T> const& get() const override {
  3223. return m_chunk;
  3224. }
  3225. bool next() override {
  3226. m_chunk.clear();
  3227. for (size_t idx = 0; idx < m_chunk_size; ++idx) {
  3228. if (!m_generator.next()) {
  3229. return false;
  3230. }
  3231. m_chunk.push_back(m_generator.get());
  3232. }
  3233. return true;
  3234. }
  3235. };
  3236. template <typename T>
  3237. GeneratorWrapper<std::vector<T>> chunk(size_t size, GeneratorWrapper<T>&& generator) {
  3238. return GeneratorWrapper<std::vector<T>>(
  3239. pf::make_unique<ChunkGenerator<T>>(size, std::move(generator))
  3240. );
  3241. }
  3242. } // namespace Generators
  3243. } // namespace Catch
  3244. // end catch_generators_generic.hpp
  3245. // start catch_generators_specific.hpp
  3246. // start catch_context.h
  3247. #include <memory>
  3248. namespace Catch {
  3249. struct IResultCapture;
  3250. struct IRunner;
  3251. struct IConfig;
  3252. struct IMutableContext;
  3253. using IConfigPtr = std::shared_ptr<IConfig const>;
  3254. struct IContext
  3255. {
  3256. virtual ~IContext();
  3257. virtual IResultCapture* getResultCapture() = 0;
  3258. virtual IRunner* getRunner() = 0;
  3259. virtual IConfigPtr const& getConfig() const = 0;
  3260. };
  3261. struct IMutableContext : IContext
  3262. {
  3263. virtual ~IMutableContext();
  3264. virtual void setResultCapture( IResultCapture* resultCapture ) = 0;
  3265. virtual void setRunner( IRunner* runner ) = 0;
  3266. virtual void setConfig( IConfigPtr const& config ) = 0;
  3267. private:
  3268. static IMutableContext *currentContext;
  3269. friend IMutableContext& getCurrentMutableContext();
  3270. friend void cleanUpContext();
  3271. static void createContext();
  3272. };
  3273. inline IMutableContext& getCurrentMutableContext()
  3274. {
  3275. if( !IMutableContext::currentContext )
  3276. IMutableContext::createContext();
  3277. return *IMutableContext::currentContext;
  3278. }
  3279. inline IContext& getCurrentContext()
  3280. {
  3281. return getCurrentMutableContext();
  3282. }
  3283. void cleanUpContext();
  3284. }
  3285. // end catch_context.h
  3286. // start catch_interfaces_config.h
  3287. #include <iosfwd>
  3288. #include <string>
  3289. #include <vector>
  3290. #include <memory>
  3291. namespace Catch {
  3292. enum class Verbosity {
  3293. Quiet = 0,
  3294. Normal,
  3295. High
  3296. };
  3297. struct WarnAbout { enum What {
  3298. Nothing = 0x00,
  3299. NoAssertions = 0x01,
  3300. NoTests = 0x02
  3301. }; };
  3302. struct ShowDurations { enum OrNot {
  3303. DefaultForReporter,
  3304. Always,
  3305. Never
  3306. }; };
  3307. struct RunTests { enum InWhatOrder {
  3308. InDeclarationOrder,
  3309. InLexicographicalOrder,
  3310. InRandomOrder
  3311. }; };
  3312. struct UseColour { enum YesOrNo {
  3313. Auto,
  3314. Yes,
  3315. No
  3316. }; };
  3317. struct WaitForKeypress { enum When {
  3318. Never,
  3319. BeforeStart = 1,
  3320. BeforeExit = 2,
  3321. BeforeStartAndExit = BeforeStart | BeforeExit
  3322. }; };
  3323. class TestSpec;
  3324. struct IConfig : NonCopyable {
  3325. virtual ~IConfig();
  3326. virtual bool allowThrows() const = 0;
  3327. virtual std::ostream& stream() const = 0;
  3328. virtual std::string name() const = 0;
  3329. virtual bool includeSuccessfulResults() const = 0;
  3330. virtual bool shouldDebugBreak() const = 0;
  3331. virtual bool warnAboutMissingAssertions() const = 0;
  3332. virtual bool warnAboutNoTests() const = 0;
  3333. virtual int abortAfter() const = 0;
  3334. virtual bool showInvisibles() const = 0;
  3335. virtual ShowDurations::OrNot showDurations() const = 0;
  3336. virtual TestSpec const& testSpec() const = 0;
  3337. virtual bool hasTestFilters() const = 0;
  3338. virtual std::vector<std::string> const& getTestsOrTags() const = 0;
  3339. virtual RunTests::InWhatOrder runOrder() const = 0;
  3340. virtual unsigned int rngSeed() const = 0;
  3341. virtual int benchmarkResolutionMultiple() const = 0;
  3342. virtual UseColour::YesOrNo useColour() const = 0;
  3343. virtual std::vector<std::string> const& getSectionsToRun() const = 0;
  3344. virtual Verbosity verbosity() const = 0;
  3345. };
  3346. using IConfigPtr = std::shared_ptr<IConfig const>;
  3347. }
  3348. // end catch_interfaces_config.h
  3349. #include <random>
  3350. namespace Catch {
  3351. namespace Generators {
  3352. template <typename Float>
  3353. class RandomFloatingGenerator final : public IGenerator<Float> {
  3354. // FIXME: What is the right seed?
  3355. std::minstd_rand m_rand;
  3356. std::uniform_real_distribution<Float> m_dist;
  3357. Float m_current_number;
  3358. public:
  3359. RandomFloatingGenerator(Float a, Float b):
  3360. m_rand(getCurrentContext().getConfig()->rngSeed()),
  3361. m_dist(a, b) {
  3362. static_cast<void>(next());
  3363. }
  3364. Float const& get() const override {
  3365. return m_current_number;
  3366. }
  3367. bool next() override {
  3368. m_current_number = m_dist(m_rand);
  3369. return true;
  3370. }
  3371. };
  3372. template <typename Integer>
  3373. class RandomIntegerGenerator final : public IGenerator<Integer> {
  3374. std::minstd_rand m_rand;
  3375. std::uniform_int_distribution<Integer> m_dist;
  3376. Integer m_current_number;
  3377. public:
  3378. RandomIntegerGenerator(Integer a, Integer b):
  3379. m_rand(getCurrentContext().getConfig()->rngSeed()),
  3380. m_dist(a, b) {
  3381. static_cast<void>(next());
  3382. }
  3383. Integer const& get() const override {
  3384. return m_current_number;
  3385. }
  3386. bool next() override {
  3387. m_current_number = m_dist(m_rand);
  3388. return true;
  3389. }
  3390. };
  3391. // TODO: Ideally this would be also constrained against the various char types,
  3392. // but I don't expect users to run into that in practice.
  3393. template <typename T>
  3394. typename std::enable_if<std::is_integral<T>::value && !std::is_same<T, bool>::value,
  3395. GeneratorWrapper<T>>::type
  3396. random(T a, T b) {
  3397. return GeneratorWrapper<T>(
  3398. pf::make_unique<RandomIntegerGenerator<T>>(a, b)
  3399. );
  3400. }
  3401. template <typename T>
  3402. typename std::enable_if<std::is_floating_point<T>::value,
  3403. GeneratorWrapper<T>>::type
  3404. random(T a, T b) {
  3405. return GeneratorWrapper<T>(
  3406. pf::make_unique<RandomFloatingGenerator<T>>(a, b)
  3407. );
  3408. }
  3409. template <typename T>
  3410. class RangeGenerator final : public IGenerator<T> {
  3411. T m_current;
  3412. T m_end;
  3413. T m_step;
  3414. bool m_positive;
  3415. public:
  3416. RangeGenerator(T const& start, T const& end, T const& step):
  3417. m_current(start),
  3418. m_end(end),
  3419. m_step(step),
  3420. m_positive(m_step > T(0))
  3421. {
  3422. assert(m_current != m_end && "Range start and end cannot be equal");
  3423. assert(m_step != T(0) && "Step size cannot be zero");
  3424. assert(((m_positive && m_current <= m_end) || (!m_positive && m_current >= m_end)) && "Step moves away from end");
  3425. }
  3426. RangeGenerator(T const& start, T const& end):
  3427. RangeGenerator(start, end, (start < end) ? T(1) : T(-1))
  3428. {}
  3429. T const& get() const override {
  3430. return m_current;
  3431. }
  3432. bool next() override {
  3433. m_current += m_step;
  3434. return (m_positive) ? (m_current < m_end) : (m_current > m_end);
  3435. }
  3436. };
  3437. template <typename T>
  3438. GeneratorWrapper<T> range(T const& start, T const& end, T const& step) {
  3439. static_assert(std::is_integral<T>::value && !std::is_same<T, bool>::value, "Type must be an integer");
  3440. return GeneratorWrapper<T>(pf::make_unique<RangeGenerator<T>>(start, end, step));
  3441. }
  3442. template <typename T>
  3443. GeneratorWrapper<T> range(T const& start, T const& end) {
  3444. static_assert(std::is_integral<T>::value && !std::is_same<T, bool>::value, "Type must be an integer");
  3445. return GeneratorWrapper<T>(pf::make_unique<RangeGenerator<T>>(start, end));
  3446. }
  3447. } // namespace Generators
  3448. } // namespace Catch
  3449. // end catch_generators_specific.hpp
  3450. // These files are included here so the single_include script doesn't put them
  3451. // in the conditionally compiled sections
  3452. // start catch_test_case_info.h
  3453. #include <string>
  3454. #include <vector>
  3455. #include <memory>
  3456. #ifdef __clang__
  3457. #pragma clang diagnostic push
  3458. #pragma clang diagnostic ignored "-Wpadded"
  3459. #endif
  3460. namespace Catch {
  3461. struct ITestInvoker;
  3462. struct TestCaseInfo {
  3463. enum SpecialProperties{
  3464. None = 0,
  3465. IsHidden = 1 << 1,
  3466. ShouldFail = 1 << 2,
  3467. MayFail = 1 << 3,
  3468. Throws = 1 << 4,
  3469. NonPortable = 1 << 5,
  3470. Benchmark = 1 << 6
  3471. };
  3472. TestCaseInfo( std::string const& _name,
  3473. std::string const& _className,
  3474. std::string const& _description,
  3475. std::vector<std::string> const& _tags,
  3476. SourceLineInfo const& _lineInfo );
  3477. friend void setTags( TestCaseInfo& testCaseInfo, std::vector<std::string> tags );
  3478. bool isHidden() const;
  3479. bool throws() const;
  3480. bool okToFail() const;
  3481. bool expectedToFail() const;
  3482. std::string tagsAsString() const;
  3483. std::string name;
  3484. std::string className;
  3485. std::string description;
  3486. std::vector<std::string> tags;
  3487. std::vector<std::string> lcaseTags;
  3488. SourceLineInfo lineInfo;
  3489. SpecialProperties properties;
  3490. };
  3491. class TestCase : public TestCaseInfo {
  3492. public:
  3493. TestCase( ITestInvoker* testCase, TestCaseInfo&& info );
  3494. TestCase withName( std::string const& _newName ) const;
  3495. void invoke() const;
  3496. TestCaseInfo const& getTestCaseInfo() const;
  3497. bool operator == ( TestCase const& other ) const;
  3498. bool operator < ( TestCase const& other ) const;
  3499. private:
  3500. std::shared_ptr<ITestInvoker> test;
  3501. };
  3502. TestCase makeTestCase( ITestInvoker* testCase,
  3503. std::string const& className,
  3504. NameAndTags const& nameAndTags,
  3505. SourceLineInfo const& lineInfo );
  3506. }
  3507. #ifdef __clang__
  3508. #pragma clang diagnostic pop
  3509. #endif
  3510. // end catch_test_case_info.h
  3511. // start catch_interfaces_runner.h
  3512. namespace Catch {
  3513. struct IRunner {
  3514. virtual ~IRunner();
  3515. virtual bool aborting() const = 0;
  3516. };
  3517. }
  3518. // end catch_interfaces_runner.h
  3519. #ifdef __OBJC__
  3520. // start catch_objc.hpp
  3521. #import <objc/runtime.h>
  3522. #include <string>
  3523. // NB. Any general catch headers included here must be included
  3524. // in catch.hpp first to make sure they are included by the single
  3525. // header for non obj-usage
  3526. ///////////////////////////////////////////////////////////////////////////////
  3527. // This protocol is really only here for (self) documenting purposes, since
  3528. // all its methods are optional.
  3529. @protocol OcFixture
  3530. @optional
  3531. -(void) setUp;
  3532. -(void) tearDown;
  3533. @end
  3534. namespace Catch {
  3535. class OcMethod : public ITestInvoker {
  3536. public:
  3537. OcMethod( Class cls, SEL sel ) : m_cls( cls ), m_sel( sel ) {}
  3538. virtual void invoke() const {
  3539. id obj = [[m_cls alloc] init];
  3540. performOptionalSelector( obj, @selector(setUp) );
  3541. performOptionalSelector( obj, m_sel );
  3542. performOptionalSelector( obj, @selector(tearDown) );
  3543. arcSafeRelease( obj );
  3544. }
  3545. private:
  3546. virtual ~OcMethod() {}
  3547. Class m_cls;
  3548. SEL m_sel;
  3549. };
  3550. namespace Detail{
  3551. inline std::string getAnnotation( Class cls,
  3552. std::string const& annotationName,
  3553. std::string const& testCaseName ) {
  3554. NSString* selStr = [[NSString alloc] initWithFormat:@"Catch_%s_%s", annotationName.c_str(), testCaseName.c_str()];
  3555. SEL sel = NSSelectorFromString( selStr );
  3556. arcSafeRelease( selStr );
  3557. id value = performOptionalSelector( cls, sel );
  3558. if( value )
  3559. return [(NSString*)value UTF8String];
  3560. return "";
  3561. }
  3562. }
  3563. inline std::size_t registerTestMethods() {
  3564. std::size_t noTestMethods = 0;
  3565. int noClasses = objc_getClassList( nullptr, 0 );
  3566. Class* classes = (CATCH_UNSAFE_UNRETAINED Class *)malloc( sizeof(Class) * noClasses);
  3567. objc_getClassList( classes, noClasses );
  3568. for( int c = 0; c < noClasses; c++ ) {
  3569. Class cls = classes[c];
  3570. {
  3571. u_int count;
  3572. Method* methods = class_copyMethodList( cls, &count );
  3573. for( u_int m = 0; m < count ; m++ ) {
  3574. SEL selector = method_getName(methods[m]);
  3575. std::string methodName = sel_getName(selector);
  3576. if( startsWith( methodName, "Catch_TestCase_" ) ) {
  3577. std::string testCaseName = methodName.substr( 15 );
  3578. std::string name = Detail::getAnnotation( cls, "Name", testCaseName );
  3579. std::string desc = Detail::getAnnotation( cls, "Description", testCaseName );
  3580. const char* className = class_getName( cls );
  3581. getMutableRegistryHub().registerTest( makeTestCase( new OcMethod( cls, selector ), className, NameAndTags( name.c_str(), desc.c_str() ), SourceLineInfo("",0) ) );
  3582. noTestMethods++;
  3583. }
  3584. }
  3585. free(methods);
  3586. }
  3587. }
  3588. return noTestMethods;
  3589. }
  3590. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  3591. namespace Matchers {
  3592. namespace Impl {
  3593. namespace NSStringMatchers {
  3594. struct StringHolder : MatcherBase<NSString*>{
  3595. StringHolder( NSString* substr ) : m_substr( [substr copy] ){}
  3596. StringHolder( StringHolder const& other ) : m_substr( [other.m_substr copy] ){}
  3597. StringHolder() {
  3598. arcSafeRelease( m_substr );
  3599. }
  3600. bool match( NSString* const& str ) const override {
  3601. return false;
  3602. }
  3603. NSString* CATCH_ARC_STRONG m_substr;
  3604. };
  3605. struct Equals : StringHolder {
  3606. Equals( NSString* substr ) : StringHolder( substr ){}
  3607. bool match( NSString* const& str ) const override {
  3608. return (str != nil || m_substr == nil ) &&
  3609. [str isEqualToString:m_substr];
  3610. }
  3611. std::string describe() const override {
  3612. return "equals string: " + Catch::Detail::stringify( m_substr );
  3613. }
  3614. };
  3615. struct Contains : StringHolder {
  3616. Contains( NSString* substr ) : StringHolder( substr ){}
  3617. bool match( NSString* const& str ) const override {
  3618. return (str != nil || m_substr == nil ) &&
  3619. [str rangeOfString:m_substr].location != NSNotFound;
  3620. }
  3621. std::string describe() const override {
  3622. return "contains string: " + Catch::Detail::stringify( m_substr );
  3623. }
  3624. };
  3625. struct StartsWith : StringHolder {
  3626. StartsWith( NSString* substr ) : StringHolder( substr ){}
  3627. bool match( NSString* const& str ) const override {
  3628. return (str != nil || m_substr == nil ) &&
  3629. [str rangeOfString:m_substr].location == 0;
  3630. }
  3631. std::string describe() const override {
  3632. return "starts with: " + Catch::Detail::stringify( m_substr );
  3633. }
  3634. };
  3635. struct EndsWith : StringHolder {
  3636. EndsWith( NSString* substr ) : StringHolder( substr ){}
  3637. bool match( NSString* const& str ) const override {
  3638. return (str != nil || m_substr == nil ) &&
  3639. [str rangeOfString:m_substr].location == [str length] - [m_substr length];
  3640. }
  3641. std::string describe() const override {
  3642. return "ends with: " + Catch::Detail::stringify( m_substr );
  3643. }
  3644. };
  3645. } // namespace NSStringMatchers
  3646. } // namespace Impl
  3647. inline Impl::NSStringMatchers::Equals
  3648. Equals( NSString* substr ){ return Impl::NSStringMatchers::Equals( substr ); }
  3649. inline Impl::NSStringMatchers::Contains
  3650. Contains( NSString* substr ){ return Impl::NSStringMatchers::Contains( substr ); }
  3651. inline Impl::NSStringMatchers::StartsWith
  3652. StartsWith( NSString* substr ){ return Impl::NSStringMatchers::StartsWith( substr ); }
  3653. inline Impl::NSStringMatchers::EndsWith
  3654. EndsWith( NSString* substr ){ return Impl::NSStringMatchers::EndsWith( substr ); }
  3655. } // namespace Matchers
  3656. using namespace Matchers;
  3657. #endif // CATCH_CONFIG_DISABLE_MATCHERS
  3658. } // namespace Catch
  3659. ///////////////////////////////////////////////////////////////////////////////
  3660. #define OC_MAKE_UNIQUE_NAME( root, uniqueSuffix ) root##uniqueSuffix
  3661. #define OC_TEST_CASE2( name, desc, uniqueSuffix ) \
  3662. +(NSString*) OC_MAKE_UNIQUE_NAME( Catch_Name_test_, uniqueSuffix ) \
  3663. { \
  3664. return @ name; \
  3665. } \
  3666. +(NSString*) OC_MAKE_UNIQUE_NAME( Catch_Description_test_, uniqueSuffix ) \
  3667. { \
  3668. return @ desc; \
  3669. } \
  3670. -(void) OC_MAKE_UNIQUE_NAME( Catch_TestCase_test_, uniqueSuffix )
  3671. #define OC_TEST_CASE( name, desc ) OC_TEST_CASE2( name, desc, __LINE__ )
  3672. // end catch_objc.hpp
  3673. #endif
  3674. #ifdef CATCH_CONFIG_EXTERNAL_INTERFACES
  3675. // start catch_external_interfaces.h
  3676. // start catch_reporter_bases.hpp
  3677. // start catch_interfaces_reporter.h
  3678. // start catch_config.hpp
  3679. // start catch_test_spec_parser.h
  3680. #ifdef __clang__
  3681. #pragma clang diagnostic push
  3682. #pragma clang diagnostic ignored "-Wpadded"
  3683. #endif
  3684. // start catch_test_spec.h
  3685. #ifdef __clang__
  3686. #pragma clang diagnostic push
  3687. #pragma clang diagnostic ignored "-Wpadded"
  3688. #endif
  3689. // start catch_wildcard_pattern.h
  3690. namespace Catch
  3691. {
  3692. class WildcardPattern {
  3693. enum WildcardPosition {
  3694. NoWildcard = 0,
  3695. WildcardAtStart = 1,
  3696. WildcardAtEnd = 2,
  3697. WildcardAtBothEnds = WildcardAtStart | WildcardAtEnd
  3698. };
  3699. public:
  3700. WildcardPattern( std::string const& pattern, CaseSensitive::Choice caseSensitivity );
  3701. virtual ~WildcardPattern() = default;
  3702. virtual bool matches( std::string const& str ) const;
  3703. private:
  3704. std::string adjustCase( std::string const& str ) const;
  3705. CaseSensitive::Choice m_caseSensitivity;
  3706. WildcardPosition m_wildcard = NoWildcard;
  3707. std::string m_pattern;
  3708. };
  3709. }
  3710. // end catch_wildcard_pattern.h
  3711. #include <string>
  3712. #include <vector>
  3713. #include <memory>
  3714. namespace Catch {
  3715. class TestSpec {
  3716. struct Pattern {
  3717. virtual ~Pattern();
  3718. virtual bool matches( TestCaseInfo const& testCase ) const = 0;
  3719. };
  3720. using PatternPtr = std::shared_ptr<Pattern>;
  3721. class NamePattern : public Pattern {
  3722. public:
  3723. NamePattern( std::string const& name );
  3724. virtual ~NamePattern();
  3725. virtual bool matches( TestCaseInfo const& testCase ) const override;
  3726. private:
  3727. WildcardPattern m_wildcardPattern;
  3728. };
  3729. class TagPattern : public Pattern {
  3730. public:
  3731. TagPattern( std::string const& tag );
  3732. virtual ~TagPattern();
  3733. virtual bool matches( TestCaseInfo const& testCase ) const override;
  3734. private:
  3735. std::string m_tag;
  3736. };
  3737. class ExcludedPattern : public Pattern {
  3738. public:
  3739. ExcludedPattern( PatternPtr const& underlyingPattern );
  3740. virtual ~ExcludedPattern();
  3741. virtual bool matches( TestCaseInfo const& testCase ) const override;
  3742. private:
  3743. PatternPtr m_underlyingPattern;
  3744. };
  3745. struct Filter {
  3746. std::vector<PatternPtr> m_patterns;
  3747. bool matches( TestCaseInfo const& testCase ) const;
  3748. };
  3749. public:
  3750. bool hasFilters() const;
  3751. bool matches( TestCaseInfo const& testCase ) const;
  3752. private:
  3753. std::vector<Filter> m_filters;
  3754. friend class TestSpecParser;
  3755. };
  3756. }
  3757. #ifdef __clang__
  3758. #pragma clang diagnostic pop
  3759. #endif
  3760. // end catch_test_spec.h
  3761. // start catch_interfaces_tag_alias_registry.h
  3762. #include <string>
  3763. namespace Catch {
  3764. struct TagAlias;
  3765. struct ITagAliasRegistry {
  3766. virtual ~ITagAliasRegistry();
  3767. // Nullptr if not present
  3768. virtual TagAlias const* find( std::string const& alias ) const = 0;
  3769. virtual std::string expandAliases( std::string const& unexpandedTestSpec ) const = 0;
  3770. static ITagAliasRegistry const& get();
  3771. };
  3772. } // end namespace Catch
  3773. // end catch_interfaces_tag_alias_registry.h
  3774. namespace Catch {
  3775. class TestSpecParser {
  3776. enum Mode{ None, Name, QuotedName, Tag, EscapedName };
  3777. Mode m_mode = None;
  3778. bool m_exclusion = false;
  3779. std::size_t m_start = std::string::npos, m_pos = 0;
  3780. std::string m_arg;
  3781. std::vector<std::size_t> m_escapeChars;
  3782. TestSpec::Filter m_currentFilter;
  3783. TestSpec m_testSpec;
  3784. ITagAliasRegistry const* m_tagAliases = nullptr;
  3785. public:
  3786. TestSpecParser( ITagAliasRegistry const& tagAliases );
  3787. TestSpecParser& parse( std::string const& arg );
  3788. TestSpec testSpec();
  3789. private:
  3790. void visitChar( char c );
  3791. void startNewMode( Mode mode, std::size_t start );
  3792. void escape();
  3793. std::string subString() const;
  3794. template<typename T>
  3795. void addPattern() {
  3796. std::string token = subString();
  3797. for( std::size_t i = 0; i < m_escapeChars.size(); ++i )
  3798. token = token.substr( 0, m_escapeChars[i]-m_start-i ) + token.substr( m_escapeChars[i]-m_start-i+1 );
  3799. m_escapeChars.clear();
  3800. if( startsWith( token, "exclude:" ) ) {
  3801. m_exclusion = true;
  3802. token = token.substr( 8 );
  3803. }
  3804. if( !token.empty() ) {
  3805. TestSpec::PatternPtr pattern = std::make_shared<T>( token );
  3806. if( m_exclusion )
  3807. pattern = std::make_shared<TestSpec::ExcludedPattern>( pattern );
  3808. m_currentFilter.m_patterns.push_back( pattern );
  3809. }
  3810. m_exclusion = false;
  3811. m_mode = None;
  3812. }
  3813. void addFilter();
  3814. };
  3815. TestSpec parseTestSpec( std::string const& arg );
  3816. } // namespace Catch
  3817. #ifdef __clang__
  3818. #pragma clang diagnostic pop
  3819. #endif
  3820. // end catch_test_spec_parser.h
  3821. // Libstdc++ doesn't like incomplete classes for unique_ptr
  3822. #include <memory>
  3823. #include <vector>
  3824. #include <string>
  3825. #ifndef CATCH_CONFIG_CONSOLE_WIDTH
  3826. #define CATCH_CONFIG_CONSOLE_WIDTH 80
  3827. #endif
  3828. namespace Catch {
  3829. struct IStream;
  3830. struct ConfigData {
  3831. bool listTests = false;
  3832. bool listTags = false;
  3833. bool listReporters = false;
  3834. bool listTestNamesOnly = false;
  3835. bool showSuccessfulTests = false;
  3836. bool shouldDebugBreak = false;
  3837. bool noThrow = false;
  3838. bool showHelp = false;
  3839. bool showInvisibles = false;
  3840. bool filenamesAsTags = false;
  3841. bool libIdentify = false;
  3842. int abortAfter = -1;
  3843. unsigned int rngSeed = 0;
  3844. int benchmarkResolutionMultiple = 100;
  3845. Verbosity verbosity = Verbosity::Normal;
  3846. WarnAbout::What warnings = WarnAbout::Nothing;
  3847. ShowDurations::OrNot showDurations = ShowDurations::DefaultForReporter;
  3848. RunTests::InWhatOrder runOrder = RunTests::InDeclarationOrder;
  3849. UseColour::YesOrNo useColour = UseColour::Auto;
  3850. WaitForKeypress::When waitForKeypress = WaitForKeypress::Never;
  3851. std::string outputFilename;
  3852. std::string name;
  3853. std::string processName;
  3854. #ifndef CATCH_CONFIG_DEFAULT_REPORTER
  3855. #define CATCH_CONFIG_DEFAULT_REPORTER "console"
  3856. #endif
  3857. std::string reporterName = CATCH_CONFIG_DEFAULT_REPORTER;
  3858. #undef CATCH_CONFIG_DEFAULT_REPORTER
  3859. std::vector<std::string> testsOrTags;
  3860. std::vector<std::string> sectionsToRun;
  3861. };
  3862. class Config : public IConfig {
  3863. public:
  3864. Config() = default;
  3865. Config( ConfigData const& data );
  3866. virtual ~Config() = default;
  3867. std::string const& getFilename() const;
  3868. bool listTests() const;
  3869. bool listTestNamesOnly() const;
  3870. bool listTags() const;
  3871. bool listReporters() const;
  3872. std::string getProcessName() const;
  3873. std::string const& getReporterName() const;
  3874. std::vector<std::string> const& getTestsOrTags() const override;
  3875. std::vector<std::string> const& getSectionsToRun() const override;
  3876. virtual TestSpec const& testSpec() const override;
  3877. bool hasTestFilters() const override;
  3878. bool showHelp() const;
  3879. // IConfig interface
  3880. bool allowThrows() const override;
  3881. std::ostream& stream() const override;
  3882. std::string name() const override;
  3883. bool includeSuccessfulResults() const override;
  3884. bool warnAboutMissingAssertions() const override;
  3885. bool warnAboutNoTests() const override;
  3886. ShowDurations::OrNot showDurations() const override;
  3887. RunTests::InWhatOrder runOrder() const override;
  3888. unsigned int rngSeed() const override;
  3889. int benchmarkResolutionMultiple() const override;
  3890. UseColour::YesOrNo useColour() const override;
  3891. bool shouldDebugBreak() const override;
  3892. int abortAfter() const override;
  3893. bool showInvisibles() const override;
  3894. Verbosity verbosity() const override;
  3895. private:
  3896. IStream const* openStream();
  3897. ConfigData m_data;
  3898. std::unique_ptr<IStream const> m_stream;
  3899. TestSpec m_testSpec;
  3900. bool m_hasTestFilters = false;
  3901. };
  3902. } // end namespace Catch
  3903. // end catch_config.hpp
  3904. // start catch_assertionresult.h
  3905. #include <string>
  3906. namespace Catch {
  3907. struct AssertionResultData
  3908. {
  3909. AssertionResultData() = delete;
  3910. AssertionResultData( ResultWas::OfType _resultType, LazyExpression const& _lazyExpression );
  3911. std::string message;
  3912. mutable std::string reconstructedExpression;
  3913. LazyExpression lazyExpression;
  3914. ResultWas::OfType resultType;
  3915. std::string reconstructExpression() const;
  3916. };
  3917. class AssertionResult {
  3918. public:
  3919. AssertionResult() = delete;
  3920. AssertionResult( AssertionInfo const& info, AssertionResultData const& data );
  3921. bool isOk() const;
  3922. bool succeeded() const;
  3923. ResultWas::OfType getResultType() const;
  3924. bool hasExpression() const;
  3925. bool hasMessage() const;
  3926. std::string getExpression() const;
  3927. std::string getExpressionInMacro() const;
  3928. bool hasExpandedExpression() const;
  3929. std::string getExpandedExpression() const;
  3930. std::string getMessage() const;
  3931. SourceLineInfo getSourceInfo() const;
  3932. StringRef getTestMacroName() const;
  3933. //protected:
  3934. AssertionInfo m_info;
  3935. AssertionResultData m_resultData;
  3936. };
  3937. } // end namespace Catch
  3938. // end catch_assertionresult.h
  3939. // start catch_option.hpp
  3940. namespace Catch {
  3941. // An optional type
  3942. template<typename T>
  3943. class Option {
  3944. public:
  3945. Option() : nullableValue( nullptr ) {}
  3946. Option( T const& _value )
  3947. : nullableValue( new( storage ) T( _value ) )
  3948. {}
  3949. Option( Option const& _other )
  3950. : nullableValue( _other ? new( storage ) T( *_other ) : nullptr )
  3951. {}
  3952. ~Option() {
  3953. reset();
  3954. }
  3955. Option& operator= ( Option const& _other ) {
  3956. if( &_other != this ) {
  3957. reset();
  3958. if( _other )
  3959. nullableValue = new( storage ) T( *_other );
  3960. }
  3961. return *this;
  3962. }
  3963. Option& operator = ( T const& _value ) {
  3964. reset();
  3965. nullableValue = new( storage ) T( _value );
  3966. return *this;
  3967. }
  3968. void reset() {
  3969. if( nullableValue )
  3970. nullableValue->~T();
  3971. nullableValue = nullptr;
  3972. }
  3973. T& operator*() { return *nullableValue; }
  3974. T const& operator*() const { return *nullableValue; }
  3975. T* operator->() { return nullableValue; }
  3976. const T* operator->() const { return nullableValue; }
  3977. T valueOr( T const& defaultValue ) const {
  3978. return nullableValue ? *nullableValue : defaultValue;
  3979. }
  3980. bool some() const { return nullableValue != nullptr; }
  3981. bool none() const { return nullableValue == nullptr; }
  3982. bool operator !() const { return nullableValue == nullptr; }
  3983. explicit operator bool() const {
  3984. return some();
  3985. }
  3986. private:
  3987. T *nullableValue;
  3988. alignas(alignof(T)) char storage[sizeof(T)];
  3989. };
  3990. } // end namespace Catch
  3991. // end catch_option.hpp
  3992. #include <string>
  3993. #include <iosfwd>
  3994. #include <map>
  3995. #include <set>
  3996. #include <memory>
  3997. namespace Catch {
  3998. struct ReporterConfig {
  3999. explicit ReporterConfig( IConfigPtr const& _fullConfig );
  4000. ReporterConfig( IConfigPtr const& _fullConfig, std::ostream& _stream );
  4001. std::ostream& stream() const;
  4002. IConfigPtr fullConfig() const;
  4003. private:
  4004. std::ostream* m_stream;
  4005. IConfigPtr m_fullConfig;
  4006. };
  4007. struct ReporterPreferences {
  4008. bool shouldRedirectStdOut = false;
  4009. bool shouldReportAllAssertions = false;
  4010. };
  4011. template<typename T>
  4012. struct LazyStat : Option<T> {
  4013. LazyStat& operator=( T const& _value ) {
  4014. Option<T>::operator=( _value );
  4015. used = false;
  4016. return *this;
  4017. }
  4018. void reset() {
  4019. Option<T>::reset();
  4020. used = false;
  4021. }
  4022. bool used = false;
  4023. };
  4024. struct TestRunInfo {
  4025. TestRunInfo( std::string const& _name );
  4026. std::string name;
  4027. };
  4028. struct GroupInfo {
  4029. GroupInfo( std::string const& _name,
  4030. std::size_t _groupIndex,
  4031. std::size_t _groupsCount );
  4032. std::string name;
  4033. std::size_t groupIndex;
  4034. std::size_t groupsCounts;
  4035. };
  4036. struct AssertionStats {
  4037. AssertionStats( AssertionResult const& _assertionResult,
  4038. std::vector<MessageInfo> const& _infoMessages,
  4039. Totals const& _totals );
  4040. AssertionStats( AssertionStats const& ) = default;
  4041. AssertionStats( AssertionStats && ) = default;
  4042. AssertionStats& operator = ( AssertionStats const& ) = delete;
  4043. AssertionStats& operator = ( AssertionStats && ) = delete;
  4044. virtual ~AssertionStats();
  4045. AssertionResult assertionResult;
  4046. std::vector<MessageInfo> infoMessages;
  4047. Totals totals;
  4048. };
  4049. struct SectionStats {
  4050. SectionStats( SectionInfo const& _sectionInfo,
  4051. Counts const& _assertions,
  4052. double _durationInSeconds,
  4053. bool _missingAssertions );
  4054. SectionStats( SectionStats const& ) = default;
  4055. SectionStats( SectionStats && ) = default;
  4056. SectionStats& operator = ( SectionStats const& ) = default;
  4057. SectionStats& operator = ( SectionStats && ) = default;
  4058. virtual ~SectionStats();
  4059. SectionInfo sectionInfo;
  4060. Counts assertions;
  4061. double durationInSeconds;
  4062. bool missingAssertions;
  4063. };
  4064. struct TestCaseStats {
  4065. TestCaseStats( TestCaseInfo const& _testInfo,
  4066. Totals const& _totals,
  4067. std::string const& _stdOut,
  4068. std::string const& _stdErr,
  4069. bool _aborting );
  4070. TestCaseStats( TestCaseStats const& ) = default;
  4071. TestCaseStats( TestCaseStats && ) = default;
  4072. TestCaseStats& operator = ( TestCaseStats const& ) = default;
  4073. TestCaseStats& operator = ( TestCaseStats && ) = default;
  4074. virtual ~TestCaseStats();
  4075. TestCaseInfo testInfo;
  4076. Totals totals;
  4077. std::string stdOut;
  4078. std::string stdErr;
  4079. bool aborting;
  4080. };
  4081. struct TestGroupStats {
  4082. TestGroupStats( GroupInfo const& _groupInfo,
  4083. Totals const& _totals,
  4084. bool _aborting );
  4085. TestGroupStats( GroupInfo const& _groupInfo );
  4086. TestGroupStats( TestGroupStats const& ) = default;
  4087. TestGroupStats( TestGroupStats && ) = default;
  4088. TestGroupStats& operator = ( TestGroupStats const& ) = default;
  4089. TestGroupStats& operator = ( TestGroupStats && ) = default;
  4090. virtual ~TestGroupStats();
  4091. GroupInfo groupInfo;
  4092. Totals totals;
  4093. bool aborting;
  4094. };
  4095. struct TestRunStats {
  4096. TestRunStats( TestRunInfo const& _runInfo,
  4097. Totals const& _totals,
  4098. bool _aborting );
  4099. TestRunStats( TestRunStats const& ) = default;
  4100. TestRunStats( TestRunStats && ) = default;
  4101. TestRunStats& operator = ( TestRunStats const& ) = default;
  4102. TestRunStats& operator = ( TestRunStats && ) = default;
  4103. virtual ~TestRunStats();
  4104. TestRunInfo runInfo;
  4105. Totals totals;
  4106. bool aborting;
  4107. };
  4108. struct BenchmarkInfo {
  4109. std::string name;
  4110. };
  4111. struct BenchmarkStats {
  4112. BenchmarkInfo info;
  4113. std::size_t iterations;
  4114. uint64_t elapsedTimeInNanoseconds;
  4115. };
  4116. struct IStreamingReporter {
  4117. virtual ~IStreamingReporter() = default;
  4118. // Implementing class must also provide the following static methods:
  4119. // static std::string getDescription();
  4120. // static std::set<Verbosity> getSupportedVerbosities()
  4121. virtual ReporterPreferences getPreferences() const = 0;
  4122. virtual void noMatchingTestCases( std::string const& spec ) = 0;
  4123. virtual void testRunStarting( TestRunInfo const& testRunInfo ) = 0;
  4124. virtual void testGroupStarting( GroupInfo const& groupInfo ) = 0;
  4125. virtual void testCaseStarting( TestCaseInfo const& testInfo ) = 0;
  4126. virtual void sectionStarting( SectionInfo const& sectionInfo ) = 0;
  4127. // *** experimental ***
  4128. virtual void benchmarkStarting( BenchmarkInfo const& ) {}
  4129. virtual void assertionStarting( AssertionInfo const& assertionInfo ) = 0;
  4130. // The return value indicates if the messages buffer should be cleared:
  4131. virtual bool assertionEnded( AssertionStats const& assertionStats ) = 0;
  4132. // *** experimental ***
  4133. virtual void benchmarkEnded( BenchmarkStats const& ) {}
  4134. virtual void sectionEnded( SectionStats const& sectionStats ) = 0;
  4135. virtual void testCaseEnded( TestCaseStats const& testCaseStats ) = 0;
  4136. virtual void testGroupEnded( TestGroupStats const& testGroupStats ) = 0;
  4137. virtual void testRunEnded( TestRunStats const& testRunStats ) = 0;
  4138. virtual void skipTest( TestCaseInfo const& testInfo ) = 0;
  4139. // Default empty implementation provided
  4140. virtual void fatalErrorEncountered( StringRef name );
  4141. virtual bool isMulti() const;
  4142. };
  4143. using IStreamingReporterPtr = std::unique_ptr<IStreamingReporter>;
  4144. struct IReporterFactory {
  4145. virtual ~IReporterFactory();
  4146. virtual IStreamingReporterPtr create( ReporterConfig const& config ) const = 0;
  4147. virtual std::string getDescription() const = 0;
  4148. };
  4149. using IReporterFactoryPtr = std::shared_ptr<IReporterFactory>;
  4150. struct IReporterRegistry {
  4151. using FactoryMap = std::map<std::string, IReporterFactoryPtr>;
  4152. using Listeners = std::vector<IReporterFactoryPtr>;
  4153. virtual ~IReporterRegistry();
  4154. virtual IStreamingReporterPtr create( std::string const& name, IConfigPtr const& config ) const = 0;
  4155. virtual FactoryMap const& getFactories() const = 0;
  4156. virtual Listeners const& getListeners() const = 0;
  4157. };
  4158. } // end namespace Catch
  4159. // end catch_interfaces_reporter.h
  4160. #include <algorithm>
  4161. #include <cstring>
  4162. #include <cfloat>
  4163. #include <cstdio>
  4164. #include <cassert>
  4165. #include <memory>
  4166. #include <ostream>
  4167. namespace Catch {
  4168. void prepareExpandedExpression(AssertionResult& result);
  4169. // Returns double formatted as %.3f (format expected on output)
  4170. std::string getFormattedDuration( double duration );
  4171. std::string serializeFilters( std::vector<std::string> const& container );
  4172. template<typename DerivedT>
  4173. struct StreamingReporterBase : IStreamingReporter {
  4174. StreamingReporterBase( ReporterConfig const& _config )
  4175. : m_config( _config.fullConfig() ),
  4176. stream( _config.stream() )
  4177. {
  4178. m_reporterPrefs.shouldRedirectStdOut = false;
  4179. if( !DerivedT::getSupportedVerbosities().count( m_config->verbosity() ) )
  4180. CATCH_ERROR( "Verbosity level not supported by this reporter" );
  4181. }
  4182. ReporterPreferences getPreferences() const override {
  4183. return m_reporterPrefs;
  4184. }
  4185. static std::set<Verbosity> getSupportedVerbosities() {
  4186. return { Verbosity::Normal };
  4187. }
  4188. ~StreamingReporterBase() override = default;
  4189. void noMatchingTestCases(std::string const&) override {}
  4190. void testRunStarting(TestRunInfo const& _testRunInfo) override {
  4191. currentTestRunInfo = _testRunInfo;
  4192. }
  4193. void testGroupStarting(GroupInfo const& _groupInfo) override {
  4194. currentGroupInfo = _groupInfo;
  4195. }
  4196. void testCaseStarting(TestCaseInfo const& _testInfo) override {
  4197. currentTestCaseInfo = _testInfo;
  4198. }
  4199. void sectionStarting(SectionInfo const& _sectionInfo) override {
  4200. m_sectionStack.push_back(_sectionInfo);
  4201. }
  4202. void sectionEnded(SectionStats const& /* _sectionStats */) override {
  4203. m_sectionStack.pop_back();
  4204. }
  4205. void testCaseEnded(TestCaseStats const& /* _testCaseStats */) override {
  4206. currentTestCaseInfo.reset();
  4207. }
  4208. void testGroupEnded(TestGroupStats const& /* _testGroupStats */) override {
  4209. currentGroupInfo.reset();
  4210. }
  4211. void testRunEnded(TestRunStats const& /* _testRunStats */) override {
  4212. currentTestCaseInfo.reset();
  4213. currentGroupInfo.reset();
  4214. currentTestRunInfo.reset();
  4215. }
  4216. void skipTest(TestCaseInfo const&) override {
  4217. // Don't do anything with this by default.
  4218. // It can optionally be overridden in the derived class.
  4219. }
  4220. IConfigPtr m_config;
  4221. std::ostream& stream;
  4222. LazyStat<TestRunInfo> currentTestRunInfo;
  4223. LazyStat<GroupInfo> currentGroupInfo;
  4224. LazyStat<TestCaseInfo> currentTestCaseInfo;
  4225. std::vector<SectionInfo> m_sectionStack;
  4226. ReporterPreferences m_reporterPrefs;
  4227. };
  4228. template<typename DerivedT>
  4229. struct CumulativeReporterBase : IStreamingReporter {
  4230. template<typename T, typename ChildNodeT>
  4231. struct Node {
  4232. explicit Node( T const& _value ) : value( _value ) {}
  4233. virtual ~Node() {}
  4234. using ChildNodes = std::vector<std::shared_ptr<ChildNodeT>>;
  4235. T value;
  4236. ChildNodes children;
  4237. };
  4238. struct SectionNode {
  4239. explicit SectionNode(SectionStats const& _stats) : stats(_stats) {}
  4240. virtual ~SectionNode() = default;
  4241. bool operator == (SectionNode const& other) const {
  4242. return stats.sectionInfo.lineInfo == other.stats.sectionInfo.lineInfo;
  4243. }
  4244. bool operator == (std::shared_ptr<SectionNode> const& other) const {
  4245. return operator==(*other);
  4246. }
  4247. SectionStats stats;
  4248. using ChildSections = std::vector<std::shared_ptr<SectionNode>>;
  4249. using Assertions = std::vector<AssertionStats>;
  4250. ChildSections childSections;
  4251. Assertions assertions;
  4252. std::string stdOut;
  4253. std::string stdErr;
  4254. };
  4255. struct BySectionInfo {
  4256. BySectionInfo( SectionInfo const& other ) : m_other( other ) {}
  4257. BySectionInfo( BySectionInfo const& other ) : m_other( other.m_other ) {}
  4258. bool operator() (std::shared_ptr<SectionNode> const& node) const {
  4259. return ((node->stats.sectionInfo.name == m_other.name) &&
  4260. (node->stats.sectionInfo.lineInfo == m_other.lineInfo));
  4261. }
  4262. void operator=(BySectionInfo const&) = delete;
  4263. private:
  4264. SectionInfo const& m_other;
  4265. };
  4266. using TestCaseNode = Node<TestCaseStats, SectionNode>;
  4267. using TestGroupNode = Node<TestGroupStats, TestCaseNode>;
  4268. using TestRunNode = Node<TestRunStats, TestGroupNode>;
  4269. CumulativeReporterBase( ReporterConfig const& _config )
  4270. : m_config( _config.fullConfig() ),
  4271. stream( _config.stream() )
  4272. {
  4273. m_reporterPrefs.shouldRedirectStdOut = false;
  4274. if( !DerivedT::getSupportedVerbosities().count( m_config->verbosity() ) )
  4275. CATCH_ERROR( "Verbosity level not supported by this reporter" );
  4276. }
  4277. ~CumulativeReporterBase() override = default;
  4278. ReporterPreferences getPreferences() const override {
  4279. return m_reporterPrefs;
  4280. }
  4281. static std::set<Verbosity> getSupportedVerbosities() {
  4282. return { Verbosity::Normal };
  4283. }
  4284. void testRunStarting( TestRunInfo const& ) override {}
  4285. void testGroupStarting( GroupInfo const& ) override {}
  4286. void testCaseStarting( TestCaseInfo const& ) override {}
  4287. void sectionStarting( SectionInfo const& sectionInfo ) override {
  4288. SectionStats incompleteStats( sectionInfo, Counts(), 0, false );
  4289. std::shared_ptr<SectionNode> node;
  4290. if( m_sectionStack.empty() ) {
  4291. if( !m_rootSection )
  4292. m_rootSection = std::make_shared<SectionNode>( incompleteStats );
  4293. node = m_rootSection;
  4294. }
  4295. else {
  4296. SectionNode& parentNode = *m_sectionStack.back();
  4297. auto it =
  4298. std::find_if( parentNode.childSections.begin(),
  4299. parentNode.childSections.end(),
  4300. BySectionInfo( sectionInfo ) );
  4301. if( it == parentNode.childSections.end() ) {
  4302. node = std::make_shared<SectionNode>( incompleteStats );
  4303. parentNode.childSections.push_back( node );
  4304. }
  4305. else
  4306. node = *it;
  4307. }
  4308. m_sectionStack.push_back( node );
  4309. m_deepestSection = std::move(node);
  4310. }
  4311. void assertionStarting(AssertionInfo const&) override {}
  4312. bool assertionEnded(AssertionStats const& assertionStats) override {
  4313. assert(!m_sectionStack.empty());
  4314. // AssertionResult holds a pointer to a temporary DecomposedExpression,
  4315. // which getExpandedExpression() calls to build the expression string.
  4316. // Our section stack copy of the assertionResult will likely outlive the
  4317. // temporary, so it must be expanded or discarded now to avoid calling
  4318. // a destroyed object later.
  4319. prepareExpandedExpression(const_cast<AssertionResult&>( assertionStats.assertionResult ) );
  4320. SectionNode& sectionNode = *m_sectionStack.back();
  4321. sectionNode.assertions.push_back(assertionStats);
  4322. return true;
  4323. }
  4324. void sectionEnded(SectionStats const& sectionStats) override {
  4325. assert(!m_sectionStack.empty());
  4326. SectionNode& node = *m_sectionStack.back();
  4327. node.stats = sectionStats;
  4328. m_sectionStack.pop_back();
  4329. }
  4330. void testCaseEnded(TestCaseStats const& testCaseStats) override {
  4331. auto node = std::make_shared<TestCaseNode>(testCaseStats);
  4332. assert(m_sectionStack.size() == 0);
  4333. node->children.push_back(m_rootSection);
  4334. m_testCases.push_back(node);
  4335. m_rootSection.reset();
  4336. assert(m_deepestSection);
  4337. m_deepestSection->stdOut = testCaseStats.stdOut;
  4338. m_deepestSection->stdErr = testCaseStats.stdErr;
  4339. }
  4340. void testGroupEnded(TestGroupStats const& testGroupStats) override {
  4341. auto node = std::make_shared<TestGroupNode>(testGroupStats);
  4342. node->children.swap(m_testCases);
  4343. m_testGroups.push_back(node);
  4344. }
  4345. void testRunEnded(TestRunStats const& testRunStats) override {
  4346. auto node = std::make_shared<TestRunNode>(testRunStats);
  4347. node->children.swap(m_testGroups);
  4348. m_testRuns.push_back(node);
  4349. testRunEndedCumulative();
  4350. }
  4351. virtual void testRunEndedCumulative() = 0;
  4352. void skipTest(TestCaseInfo const&) override {}
  4353. IConfigPtr m_config;
  4354. std::ostream& stream;
  4355. std::vector<AssertionStats> m_assertions;
  4356. std::vector<std::vector<std::shared_ptr<SectionNode>>> m_sections;
  4357. std::vector<std::shared_ptr<TestCaseNode>> m_testCases;
  4358. std::vector<std::shared_ptr<TestGroupNode>> m_testGroups;
  4359. std::vector<std::shared_ptr<TestRunNode>> m_testRuns;
  4360. std::shared_ptr<SectionNode> m_rootSection;
  4361. std::shared_ptr<SectionNode> m_deepestSection;
  4362. std::vector<std::shared_ptr<SectionNode>> m_sectionStack;
  4363. ReporterPreferences m_reporterPrefs;
  4364. };
  4365. template<char C>
  4366. char const* getLineOfChars() {
  4367. static char line[CATCH_CONFIG_CONSOLE_WIDTH] = {0};
  4368. if( !*line ) {
  4369. std::memset( line, C, CATCH_CONFIG_CONSOLE_WIDTH-1 );
  4370. line[CATCH_CONFIG_CONSOLE_WIDTH-1] = 0;
  4371. }
  4372. return line;
  4373. }
  4374. struct TestEventListenerBase : StreamingReporterBase<TestEventListenerBase> {
  4375. TestEventListenerBase( ReporterConfig const& _config );
  4376. static std::set<Verbosity> getSupportedVerbosities();
  4377. void assertionStarting(AssertionInfo const&) override;
  4378. bool assertionEnded(AssertionStats const&) override;
  4379. };
  4380. } // end namespace Catch
  4381. // end catch_reporter_bases.hpp
  4382. // start catch_console_colour.h
  4383. namespace Catch {
  4384. struct Colour {
  4385. enum Code {
  4386. None = 0,
  4387. White,
  4388. Red,
  4389. Green,
  4390. Blue,
  4391. Cyan,
  4392. Yellow,
  4393. Grey,
  4394. Bright = 0x10,
  4395. BrightRed = Bright | Red,
  4396. BrightGreen = Bright | Green,
  4397. LightGrey = Bright | Grey,
  4398. BrightWhite = Bright | White,
  4399. BrightYellow = Bright | Yellow,
  4400. // By intention
  4401. FileName = LightGrey,
  4402. Warning = BrightYellow,
  4403. ResultError = BrightRed,
  4404. ResultSuccess = BrightGreen,
  4405. ResultExpectedFailure = Warning,
  4406. Error = BrightRed,
  4407. Success = Green,
  4408. OriginalExpression = Cyan,
  4409. ReconstructedExpression = BrightYellow,
  4410. SecondaryText = LightGrey,
  4411. Headers = White
  4412. };
  4413. // Use constructed object for RAII guard
  4414. Colour( Code _colourCode );
  4415. Colour( Colour&& other ) noexcept;
  4416. Colour& operator=( Colour&& other ) noexcept;
  4417. ~Colour();
  4418. // Use static method for one-shot changes
  4419. static void use( Code _colourCode );
  4420. private:
  4421. bool m_moved = false;
  4422. };
  4423. std::ostream& operator << ( std::ostream& os, Colour const& );
  4424. } // end namespace Catch
  4425. // end catch_console_colour.h
  4426. // start catch_reporter_registrars.hpp
  4427. namespace Catch {
  4428. template<typename T>
  4429. class ReporterRegistrar {
  4430. class ReporterFactory : public IReporterFactory {
  4431. virtual IStreamingReporterPtr create( ReporterConfig const& config ) const override {
  4432. return std::unique_ptr<T>( new T( config ) );
  4433. }
  4434. virtual std::string getDescription() const override {
  4435. return T::getDescription();
  4436. }
  4437. };
  4438. public:
  4439. explicit ReporterRegistrar( std::string const& name ) {
  4440. getMutableRegistryHub().registerReporter( name, std::make_shared<ReporterFactory>() );
  4441. }
  4442. };
  4443. template<typename T>
  4444. class ListenerRegistrar {
  4445. class ListenerFactory : public IReporterFactory {
  4446. virtual IStreamingReporterPtr create( ReporterConfig const& config ) const override {
  4447. return std::unique_ptr<T>( new T( config ) );
  4448. }
  4449. virtual std::string getDescription() const override {
  4450. return std::string();
  4451. }
  4452. };
  4453. public:
  4454. ListenerRegistrar() {
  4455. getMutableRegistryHub().registerListener( std::make_shared<ListenerFactory>() );
  4456. }
  4457. };
  4458. }
  4459. #if !defined(CATCH_CONFIG_DISABLE)
  4460. #define CATCH_REGISTER_REPORTER( name, reporterType ) \
  4461. CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
  4462. namespace{ Catch::ReporterRegistrar<reporterType> catch_internal_RegistrarFor##reporterType( name ); } \
  4463. CATCH_INTERNAL_UNSUPPRESS_GLOBALS_WARNINGS
  4464. #define CATCH_REGISTER_LISTENER( listenerType ) \
  4465. CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
  4466. namespace{ Catch::ListenerRegistrar<listenerType> catch_internal_RegistrarFor##listenerType; } \
  4467. CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS
  4468. #else // CATCH_CONFIG_DISABLE
  4469. #define CATCH_REGISTER_REPORTER(name, reporterType)
  4470. #define CATCH_REGISTER_LISTENER(listenerType)
  4471. #endif // CATCH_CONFIG_DISABLE
  4472. // end catch_reporter_registrars.hpp
  4473. // Allow users to base their work off existing reporters
  4474. // start catch_reporter_compact.h
  4475. namespace Catch {
  4476. struct CompactReporter : StreamingReporterBase<CompactReporter> {
  4477. using StreamingReporterBase::StreamingReporterBase;
  4478. ~CompactReporter() override;
  4479. static std::string getDescription();
  4480. ReporterPreferences getPreferences() const override;
  4481. void noMatchingTestCases(std::string const& spec) override;
  4482. void assertionStarting(AssertionInfo const&) override;
  4483. bool assertionEnded(AssertionStats const& _assertionStats) override;
  4484. void sectionEnded(SectionStats const& _sectionStats) override;
  4485. void testRunEnded(TestRunStats const& _testRunStats) override;
  4486. };
  4487. } // end namespace Catch
  4488. // end catch_reporter_compact.h
  4489. // start catch_reporter_console.h
  4490. #if defined(_MSC_VER)
  4491. #pragma warning(push)
  4492. #pragma warning(disable:4061) // Not all labels are EXPLICITLY handled in switch
  4493. // Note that 4062 (not all labels are handled
  4494. // and default is missing) is enabled
  4495. #endif
  4496. namespace Catch {
  4497. // Fwd decls
  4498. struct SummaryColumn;
  4499. class TablePrinter;
  4500. struct ConsoleReporter : StreamingReporterBase<ConsoleReporter> {
  4501. std::unique_ptr<TablePrinter> m_tablePrinter;
  4502. ConsoleReporter(ReporterConfig const& config);
  4503. ~ConsoleReporter() override;
  4504. static std::string getDescription();
  4505. void noMatchingTestCases(std::string const& spec) override;
  4506. void assertionStarting(AssertionInfo const&) override;
  4507. bool assertionEnded(AssertionStats const& _assertionStats) override;
  4508. void sectionStarting(SectionInfo const& _sectionInfo) override;
  4509. void sectionEnded(SectionStats const& _sectionStats) override;
  4510. void benchmarkStarting(BenchmarkInfo const& info) override;
  4511. void benchmarkEnded(BenchmarkStats const& stats) override;
  4512. void testCaseEnded(TestCaseStats const& _testCaseStats) override;
  4513. void testGroupEnded(TestGroupStats const& _testGroupStats) override;
  4514. void testRunEnded(TestRunStats const& _testRunStats) override;
  4515. void testRunStarting(TestRunInfo const& _testRunInfo) override;
  4516. private:
  4517. void lazyPrint();
  4518. void lazyPrintWithoutClosingBenchmarkTable();
  4519. void lazyPrintRunInfo();
  4520. void lazyPrintGroupInfo();
  4521. void printTestCaseAndSectionHeader();
  4522. void printClosedHeader(std::string const& _name);
  4523. void printOpenHeader(std::string const& _name);
  4524. // if string has a : in first line will set indent to follow it on
  4525. // subsequent lines
  4526. void printHeaderString(std::string const& _string, std::size_t indent = 0);
  4527. void printTotals(Totals const& totals);
  4528. void printSummaryRow(std::string const& label, std::vector<SummaryColumn> const& cols, std::size_t row);
  4529. void printTotalsDivider(Totals const& totals);
  4530. void printSummaryDivider();
  4531. void printTestFilters();
  4532. private:
  4533. bool m_headerPrinted = false;
  4534. };
  4535. } // end namespace Catch
  4536. #if defined(_MSC_VER)
  4537. #pragma warning(pop)
  4538. #endif
  4539. // end catch_reporter_console.h
  4540. // start catch_reporter_junit.h
  4541. // start catch_xmlwriter.h
  4542. #include <vector>
  4543. namespace Catch {
  4544. class XmlEncode {
  4545. public:
  4546. enum ForWhat { ForTextNodes, ForAttributes };
  4547. XmlEncode( std::string const& str, ForWhat forWhat = ForTextNodes );
  4548. void encodeTo( std::ostream& os ) const;
  4549. friend std::ostream& operator << ( std::ostream& os, XmlEncode const& xmlEncode );
  4550. private:
  4551. std::string m_str;
  4552. ForWhat m_forWhat;
  4553. };
  4554. class XmlWriter {
  4555. public:
  4556. class ScopedElement {
  4557. public:
  4558. ScopedElement( XmlWriter* writer );
  4559. ScopedElement( ScopedElement&& other ) noexcept;
  4560. ScopedElement& operator=( ScopedElement&& other ) noexcept;
  4561. ~ScopedElement();
  4562. ScopedElement& writeText( std::string const& text, bool indent = true );
  4563. template<typename T>
  4564. ScopedElement& writeAttribute( std::string const& name, T const& attribute ) {
  4565. m_writer->writeAttribute( name, attribute );
  4566. return *this;
  4567. }
  4568. private:
  4569. mutable XmlWriter* m_writer = nullptr;
  4570. };
  4571. XmlWriter( std::ostream& os = Catch::cout() );
  4572. ~XmlWriter();
  4573. XmlWriter( XmlWriter const& ) = delete;
  4574. XmlWriter& operator=( XmlWriter const& ) = delete;
  4575. XmlWriter& startElement( std::string const& name );
  4576. ScopedElement scopedElement( std::string const& name );
  4577. XmlWriter& endElement();
  4578. XmlWriter& writeAttribute( std::string const& name, std::string const& attribute );
  4579. XmlWriter& writeAttribute( std::string const& name, bool attribute );
  4580. template<typename T>
  4581. XmlWriter& writeAttribute( std::string const& name, T const& attribute ) {
  4582. ReusableStringStream rss;
  4583. rss << attribute;
  4584. return writeAttribute( name, rss.str() );
  4585. }
  4586. XmlWriter& writeText( std::string const& text, bool indent = true );
  4587. XmlWriter& writeComment( std::string const& text );
  4588. void writeStylesheetRef( std::string const& url );
  4589. XmlWriter& writeBlankLine();
  4590. void ensureTagClosed();
  4591. private:
  4592. void writeDeclaration();
  4593. void newlineIfNecessary();
  4594. bool m_tagIsOpen = false;
  4595. bool m_needsNewline = false;
  4596. std::vector<std::string> m_tags;
  4597. std::string m_indent;
  4598. std::ostream& m_os;
  4599. };
  4600. }
  4601. // end catch_xmlwriter.h
  4602. namespace Catch {
  4603. class JunitReporter : public CumulativeReporterBase<JunitReporter> {
  4604. public:
  4605. JunitReporter(ReporterConfig const& _config);
  4606. ~JunitReporter() override;
  4607. static std::string getDescription();
  4608. void noMatchingTestCases(std::string const& /*spec*/) override;
  4609. void testRunStarting(TestRunInfo const& runInfo) override;
  4610. void testGroupStarting(GroupInfo const& groupInfo) override;
  4611. void testCaseStarting(TestCaseInfo const& testCaseInfo) override;
  4612. bool assertionEnded(AssertionStats const& assertionStats) override;
  4613. void testCaseEnded(TestCaseStats const& testCaseStats) override;
  4614. void testGroupEnded(TestGroupStats const& testGroupStats) override;
  4615. void testRunEndedCumulative() override;
  4616. void writeGroup(TestGroupNode const& groupNode, double suiteTime);
  4617. void writeTestCase(TestCaseNode const& testCaseNode);
  4618. void writeSection(std::string const& className,
  4619. std::string const& rootName,
  4620. SectionNode const& sectionNode);
  4621. void writeAssertions(SectionNode const& sectionNode);
  4622. void writeAssertion(AssertionStats const& stats);
  4623. XmlWriter xml;
  4624. Timer suiteTimer;
  4625. std::string stdOutForSuite;
  4626. std::string stdErrForSuite;
  4627. unsigned int unexpectedExceptions = 0;
  4628. bool m_okToFail = false;
  4629. };
  4630. } // end namespace Catch
  4631. // end catch_reporter_junit.h
  4632. // start catch_reporter_xml.h
  4633. namespace Catch {
  4634. class XmlReporter : public StreamingReporterBase<XmlReporter> {
  4635. public:
  4636. XmlReporter(ReporterConfig const& _config);
  4637. ~XmlReporter() override;
  4638. static std::string getDescription();
  4639. virtual std::string getStylesheetRef() const;
  4640. void writeSourceInfo(SourceLineInfo const& sourceInfo);
  4641. public: // StreamingReporterBase
  4642. void noMatchingTestCases(std::string const& s) override;
  4643. void testRunStarting(TestRunInfo const& testInfo) override;
  4644. void testGroupStarting(GroupInfo const& groupInfo) override;
  4645. void testCaseStarting(TestCaseInfo const& testInfo) override;
  4646. void sectionStarting(SectionInfo const& sectionInfo) override;
  4647. void assertionStarting(AssertionInfo const&) override;
  4648. bool assertionEnded(AssertionStats const& assertionStats) override;
  4649. void sectionEnded(SectionStats const& sectionStats) override;
  4650. void testCaseEnded(TestCaseStats const& testCaseStats) override;
  4651. void testGroupEnded(TestGroupStats const& testGroupStats) override;
  4652. void testRunEnded(TestRunStats const& testRunStats) override;
  4653. private:
  4654. Timer m_testCaseTimer;
  4655. XmlWriter m_xml;
  4656. int m_sectionDepth = 0;
  4657. };
  4658. } // end namespace Catch
  4659. // end catch_reporter_xml.h
  4660. // end catch_external_interfaces.h
  4661. #endif
  4662. #endif // ! CATCH_CONFIG_IMPL_ONLY
  4663. #ifdef CATCH_IMPL
  4664. // start catch_impl.hpp
  4665. #ifdef __clang__
  4666. #pragma clang diagnostic push
  4667. #pragma clang diagnostic ignored "-Wweak-vtables"
  4668. #endif
  4669. // Keep these here for external reporters
  4670. // start catch_test_case_tracker.h
  4671. #include <string>
  4672. #include <vector>
  4673. #include <memory>
  4674. namespace Catch {
  4675. namespace TestCaseTracking {
  4676. struct NameAndLocation {
  4677. std::string name;
  4678. SourceLineInfo location;
  4679. NameAndLocation( std::string const& _name, SourceLineInfo const& _location );
  4680. };
  4681. struct ITracker;
  4682. using ITrackerPtr = std::shared_ptr<ITracker>;
  4683. struct ITracker {
  4684. virtual ~ITracker();
  4685. // static queries
  4686. virtual NameAndLocation const& nameAndLocation() const = 0;
  4687. // dynamic queries
  4688. virtual bool isComplete() const = 0; // Successfully completed or failed
  4689. virtual bool isSuccessfullyCompleted() const = 0;
  4690. virtual bool isOpen() const = 0; // Started but not complete
  4691. virtual bool hasChildren() const = 0;
  4692. virtual ITracker& parent() = 0;
  4693. // actions
  4694. virtual void close() = 0; // Successfully complete
  4695. virtual void fail() = 0;
  4696. virtual void markAsNeedingAnotherRun() = 0;
  4697. virtual void addChild( ITrackerPtr const& child ) = 0;
  4698. virtual ITrackerPtr findChild( NameAndLocation const& nameAndLocation ) = 0;
  4699. virtual void openChild() = 0;
  4700. // Debug/ checking
  4701. virtual bool isSectionTracker() const = 0;
  4702. virtual bool isGeneratorTracker() const = 0;
  4703. };
  4704. class TrackerContext {
  4705. enum RunState {
  4706. NotStarted,
  4707. Executing,
  4708. CompletedCycle
  4709. };
  4710. ITrackerPtr m_rootTracker;
  4711. ITracker* m_currentTracker = nullptr;
  4712. RunState m_runState = NotStarted;
  4713. public:
  4714. static TrackerContext& instance();
  4715. ITracker& startRun();
  4716. void endRun();
  4717. void startCycle();
  4718. void completeCycle();
  4719. bool completedCycle() const;
  4720. ITracker& currentTracker();
  4721. void setCurrentTracker( ITracker* tracker );
  4722. };
  4723. class TrackerBase : public ITracker {
  4724. protected:
  4725. enum CycleState {
  4726. NotStarted,
  4727. Executing,
  4728. ExecutingChildren,
  4729. NeedsAnotherRun,
  4730. CompletedSuccessfully,
  4731. Failed
  4732. };
  4733. using Children = std::vector<ITrackerPtr>;
  4734. NameAndLocation m_nameAndLocation;
  4735. TrackerContext& m_ctx;
  4736. ITracker* m_parent;
  4737. Children m_children;
  4738. CycleState m_runState = NotStarted;
  4739. public:
  4740. TrackerBase( NameAndLocation const& nameAndLocation, TrackerContext& ctx, ITracker* parent );
  4741. NameAndLocation const& nameAndLocation() const override;
  4742. bool isComplete() const override;
  4743. bool isSuccessfullyCompleted() const override;
  4744. bool isOpen() const override;
  4745. bool hasChildren() const override;
  4746. void addChild( ITrackerPtr const& child ) override;
  4747. ITrackerPtr findChild( NameAndLocation const& nameAndLocation ) override;
  4748. ITracker& parent() override;
  4749. void openChild() override;
  4750. bool isSectionTracker() const override;
  4751. bool isGeneratorTracker() const override;
  4752. void open();
  4753. void close() override;
  4754. void fail() override;
  4755. void markAsNeedingAnotherRun() override;
  4756. private:
  4757. void moveToParent();
  4758. void moveToThis();
  4759. };
  4760. class SectionTracker : public TrackerBase {
  4761. std::vector<std::string> m_filters;
  4762. public:
  4763. SectionTracker( NameAndLocation const& nameAndLocation, TrackerContext& ctx, ITracker* parent );
  4764. bool isSectionTracker() const override;
  4765. bool isComplete() const override;
  4766. static SectionTracker& acquire( TrackerContext& ctx, NameAndLocation const& nameAndLocation );
  4767. void tryOpen();
  4768. void addInitialFilters( std::vector<std::string> const& filters );
  4769. void addNextFilters( std::vector<std::string> const& filters );
  4770. };
  4771. } // namespace TestCaseTracking
  4772. using TestCaseTracking::ITracker;
  4773. using TestCaseTracking::TrackerContext;
  4774. using TestCaseTracking::SectionTracker;
  4775. } // namespace Catch
  4776. // end catch_test_case_tracker.h
  4777. // start catch_leak_detector.h
  4778. namespace Catch {
  4779. struct LeakDetector {
  4780. LeakDetector();
  4781. ~LeakDetector();
  4782. };
  4783. }
  4784. // end catch_leak_detector.h
  4785. // Cpp files will be included in the single-header file here
  4786. // start catch_approx.cpp
  4787. #include <cmath>
  4788. #include <limits>
  4789. namespace {
  4790. // Performs equivalent check of std::fabs(lhs - rhs) <= margin
  4791. // But without the subtraction to allow for INFINITY in comparison
  4792. bool marginComparison(double lhs, double rhs, double margin) {
  4793. return (lhs + margin >= rhs) && (rhs + margin >= lhs);
  4794. }
  4795. }
  4796. namespace Catch {
  4797. namespace Detail {
  4798. Approx::Approx ( double value )
  4799. : m_epsilon( std::numeric_limits<float>::epsilon()*100 ),
  4800. m_margin( 0.0 ),
  4801. m_scale( 0.0 ),
  4802. m_value( value )
  4803. {}
  4804. Approx Approx::custom() {
  4805. return Approx( 0 );
  4806. }
  4807. Approx Approx::operator-() const {
  4808. auto temp(*this);
  4809. temp.m_value = -temp.m_value;
  4810. return temp;
  4811. }
  4812. std::string Approx::toString() const {
  4813. ReusableStringStream rss;
  4814. rss << "Approx( " << ::Catch::Detail::stringify( m_value ) << " )";
  4815. return rss.str();
  4816. }
  4817. bool Approx::equalityComparisonImpl(const double other) const {
  4818. // First try with fixed margin, then compute margin based on epsilon, scale and Approx's value
  4819. // Thanks to Richard Harris for his help refining the scaled margin value
  4820. return marginComparison(m_value, other, m_margin) || marginComparison(m_value, other, m_epsilon * (m_scale + std::fabs(m_value)));
  4821. }
  4822. void Approx::setMargin(double margin) {
  4823. CATCH_ENFORCE(margin >= 0,
  4824. "Invalid Approx::margin: " << margin << '.'
  4825. << " Approx::Margin has to be non-negative.");
  4826. m_margin = margin;
  4827. }
  4828. void Approx::setEpsilon(double epsilon) {
  4829. CATCH_ENFORCE(epsilon >= 0 && epsilon <= 1.0,
  4830. "Invalid Approx::epsilon: " << epsilon << '.'
  4831. << " Approx::epsilon has to be in [0, 1]");
  4832. m_epsilon = epsilon;
  4833. }
  4834. } // end namespace Detail
  4835. namespace literals {
  4836. Detail::Approx operator "" _a(long double val) {
  4837. return Detail::Approx(val);
  4838. }
  4839. Detail::Approx operator "" _a(unsigned long long val) {
  4840. return Detail::Approx(val);
  4841. }
  4842. } // end namespace literals
  4843. std::string StringMaker<Catch::Detail::Approx>::convert(Catch::Detail::Approx const& value) {
  4844. return value.toString();
  4845. }
  4846. } // end namespace Catch
  4847. // end catch_approx.cpp
  4848. // start catch_assertionhandler.cpp
  4849. // start catch_debugger.h
  4850. namespace Catch {
  4851. bool isDebuggerActive();
  4852. }
  4853. #ifdef CATCH_PLATFORM_MAC
  4854. #define CATCH_TRAP() __asm__("int $3\n" : : ) /* NOLINT */
  4855. #elif defined(CATCH_PLATFORM_LINUX)
  4856. // If we can use inline assembler, do it because this allows us to break
  4857. // directly at the location of the failing check instead of breaking inside
  4858. // raise() called from it, i.e. one stack frame below.
  4859. #if defined(__GNUC__) && (defined(__i386) || defined(__x86_64))
  4860. #define CATCH_TRAP() asm volatile ("int $3") /* NOLINT */
  4861. #else // Fall back to the generic way.
  4862. #include <signal.h>
  4863. #define CATCH_TRAP() raise(SIGTRAP)
  4864. #endif
  4865. #elif defined(_MSC_VER)
  4866. #define CATCH_TRAP() __debugbreak()
  4867. #elif defined(__MINGW32__)
  4868. extern "C" __declspec(dllimport) void __stdcall DebugBreak();
  4869. #define CATCH_TRAP() DebugBreak()
  4870. #endif
  4871. #ifdef CATCH_TRAP
  4872. #define CATCH_BREAK_INTO_DEBUGGER() []{ if( Catch::isDebuggerActive() ) { CATCH_TRAP(); } }()
  4873. #else
  4874. #define CATCH_BREAK_INTO_DEBUGGER() []{}()
  4875. #endif
  4876. // end catch_debugger.h
  4877. // start catch_run_context.h
  4878. // start catch_fatal_condition.h
  4879. // start catch_windows_h_proxy.h
  4880. #if defined(CATCH_PLATFORM_WINDOWS)
  4881. #if !defined(NOMINMAX) && !defined(CATCH_CONFIG_NO_NOMINMAX)
  4882. # define CATCH_DEFINED_NOMINMAX
  4883. # define NOMINMAX
  4884. #endif
  4885. #if !defined(WIN32_LEAN_AND_MEAN) && !defined(CATCH_CONFIG_NO_WIN32_LEAN_AND_MEAN)
  4886. # define CATCH_DEFINED_WIN32_LEAN_AND_MEAN
  4887. # define WIN32_LEAN_AND_MEAN
  4888. #endif
  4889. #ifdef __AFXDLL
  4890. #include <AfxWin.h>
  4891. #else
  4892. #include <windows.h>
  4893. #endif
  4894. #ifdef CATCH_DEFINED_NOMINMAX
  4895. # undef NOMINMAX
  4896. #endif
  4897. #ifdef CATCH_DEFINED_WIN32_LEAN_AND_MEAN
  4898. # undef WIN32_LEAN_AND_MEAN
  4899. #endif
  4900. #endif // defined(CATCH_PLATFORM_WINDOWS)
  4901. // end catch_windows_h_proxy.h
  4902. #if defined( CATCH_CONFIG_WINDOWS_SEH )
  4903. namespace Catch {
  4904. struct FatalConditionHandler {
  4905. static LONG CALLBACK handleVectoredException(PEXCEPTION_POINTERS ExceptionInfo);
  4906. FatalConditionHandler();
  4907. static void reset();
  4908. ~FatalConditionHandler();
  4909. private:
  4910. static bool isSet;
  4911. static ULONG guaranteeSize;
  4912. static PVOID exceptionHandlerHandle;
  4913. };
  4914. } // namespace Catch
  4915. #elif defined ( CATCH_CONFIG_POSIX_SIGNALS )
  4916. #include <signal.h>
  4917. namespace Catch {
  4918. struct FatalConditionHandler {
  4919. static bool isSet;
  4920. static struct sigaction oldSigActions[];
  4921. static stack_t oldSigStack;
  4922. static char altStackMem[];
  4923. static void handleSignal( int sig );
  4924. FatalConditionHandler();
  4925. ~FatalConditionHandler();
  4926. static void reset();
  4927. };
  4928. } // namespace Catch
  4929. #else
  4930. namespace Catch {
  4931. struct FatalConditionHandler {
  4932. void reset();
  4933. };
  4934. }
  4935. #endif
  4936. // end catch_fatal_condition.h
  4937. #include <string>
  4938. namespace Catch {
  4939. struct IMutableContext;
  4940. ///////////////////////////////////////////////////////////////////////////
  4941. class RunContext : public IResultCapture, public IRunner {
  4942. public:
  4943. RunContext( RunContext const& ) = delete;
  4944. RunContext& operator =( RunContext const& ) = delete;
  4945. explicit RunContext( IConfigPtr const& _config, IStreamingReporterPtr&& reporter );
  4946. ~RunContext() override;
  4947. void testGroupStarting( std::string const& testSpec, std::size_t groupIndex, std::size_t groupsCount );
  4948. void testGroupEnded( std::string const& testSpec, Totals const& totals, std::size_t groupIndex, std::size_t groupsCount );
  4949. Totals runTest(TestCase const& testCase);
  4950. IConfigPtr config() const;
  4951. IStreamingReporter& reporter() const;
  4952. public: // IResultCapture
  4953. // Assertion handlers
  4954. void handleExpr
  4955. ( AssertionInfo const& info,
  4956. ITransientExpression const& expr,
  4957. AssertionReaction& reaction ) override;
  4958. void handleMessage
  4959. ( AssertionInfo const& info,
  4960. ResultWas::OfType resultType,
  4961. StringRef const& message,
  4962. AssertionReaction& reaction ) override;
  4963. void handleUnexpectedExceptionNotThrown
  4964. ( AssertionInfo const& info,
  4965. AssertionReaction& reaction ) override;
  4966. void handleUnexpectedInflightException
  4967. ( AssertionInfo const& info,
  4968. std::string const& message,
  4969. AssertionReaction& reaction ) override;
  4970. void handleIncomplete
  4971. ( AssertionInfo const& info ) override;
  4972. void handleNonExpr
  4973. ( AssertionInfo const &info,
  4974. ResultWas::OfType resultType,
  4975. AssertionReaction &reaction ) override;
  4976. bool sectionStarted( SectionInfo const& sectionInfo, Counts& assertions ) override;
  4977. void sectionEnded( SectionEndInfo const& endInfo ) override;
  4978. void sectionEndedEarly( SectionEndInfo const& endInfo ) override;
  4979. auto acquireGeneratorTracker( SourceLineInfo const& lineInfo ) -> IGeneratorTracker& override;
  4980. void benchmarkStarting( BenchmarkInfo const& info ) override;
  4981. void benchmarkEnded( BenchmarkStats const& stats ) override;
  4982. void pushScopedMessage( MessageInfo const& message ) override;
  4983. void popScopedMessage( MessageInfo const& message ) override;
  4984. void emplaceUnscopedMessage( MessageBuilder const& builder ) override;
  4985. std::string getCurrentTestName() const override;
  4986. const AssertionResult* getLastResult() const override;
  4987. void exceptionEarlyReported() override;
  4988. void handleFatalErrorCondition( StringRef message ) override;
  4989. bool lastAssertionPassed() override;
  4990. void assertionPassed() override;
  4991. public:
  4992. // !TBD We need to do this another way!
  4993. bool aborting() const final;
  4994. private:
  4995. void runCurrentTest( std::string& redirectedCout, std::string& redirectedCerr );
  4996. void invokeActiveTestCase();
  4997. void resetAssertionInfo();
  4998. bool testForMissingAssertions( Counts& assertions );
  4999. void assertionEnded( AssertionResult const& result );
  5000. void reportExpr
  5001. ( AssertionInfo const &info,
  5002. ResultWas::OfType resultType,
  5003. ITransientExpression const *expr,
  5004. bool negated );
  5005. void populateReaction( AssertionReaction& reaction );
  5006. private:
  5007. void handleUnfinishedSections();
  5008. TestRunInfo m_runInfo;
  5009. IMutableContext& m_context;
  5010. TestCase const* m_activeTestCase = nullptr;
  5011. ITracker* m_testCaseTracker = nullptr;
  5012. Option<AssertionResult> m_lastResult;
  5013. IConfigPtr m_config;
  5014. Totals m_totals;
  5015. IStreamingReporterPtr m_reporter;
  5016. std::vector<MessageInfo> m_messages;
  5017. std::vector<ScopedMessage> m_messageScopes; /* Keeps owners of so-called unscoped messages. */
  5018. AssertionInfo m_lastAssertionInfo;
  5019. std::vector<SectionEndInfo> m_unfinishedSections;
  5020. std::vector<ITracker*> m_activeSections;
  5021. TrackerContext m_trackerContext;
  5022. bool m_lastAssertionPassed = false;
  5023. bool m_shouldReportUnexpected = true;
  5024. bool m_includeSuccessfulResults;
  5025. };
  5026. } // end namespace Catch
  5027. // end catch_run_context.h
  5028. namespace Catch {
  5029. namespace {
  5030. auto operator <<( std::ostream& os, ITransientExpression const& expr ) -> std::ostream& {
  5031. expr.streamReconstructedExpression( os );
  5032. return os;
  5033. }
  5034. }
  5035. LazyExpression::LazyExpression( bool isNegated )
  5036. : m_isNegated( isNegated )
  5037. {}
  5038. LazyExpression::LazyExpression( LazyExpression const& other ) : m_isNegated( other.m_isNegated ) {}
  5039. LazyExpression::operator bool() const {
  5040. return m_transientExpression != nullptr;
  5041. }
  5042. auto operator << ( std::ostream& os, LazyExpression const& lazyExpr ) -> std::ostream& {
  5043. if( lazyExpr.m_isNegated )
  5044. os << "!";
  5045. if( lazyExpr ) {
  5046. if( lazyExpr.m_isNegated && lazyExpr.m_transientExpression->isBinaryExpression() )
  5047. os << "(" << *lazyExpr.m_transientExpression << ")";
  5048. else
  5049. os << *lazyExpr.m_transientExpression;
  5050. }
  5051. else {
  5052. os << "{** error - unchecked empty expression requested **}";
  5053. }
  5054. return os;
  5055. }
  5056. AssertionHandler::AssertionHandler
  5057. ( StringRef const& macroName,
  5058. SourceLineInfo const& lineInfo,
  5059. StringRef capturedExpression,
  5060. ResultDisposition::Flags resultDisposition )
  5061. : m_assertionInfo{ macroName, lineInfo, capturedExpression, resultDisposition },
  5062. m_resultCapture( getResultCapture() )
  5063. {}
  5064. void AssertionHandler::handleExpr( ITransientExpression const& expr ) {
  5065. m_resultCapture.handleExpr( m_assertionInfo, expr, m_reaction );
  5066. }
  5067. void AssertionHandler::handleMessage(ResultWas::OfType resultType, StringRef const& message) {
  5068. m_resultCapture.handleMessage( m_assertionInfo, resultType, message, m_reaction );
  5069. }
  5070. auto AssertionHandler::allowThrows() const -> bool {
  5071. return getCurrentContext().getConfig()->allowThrows();
  5072. }
  5073. void AssertionHandler::complete() {
  5074. setCompleted();
  5075. if( m_reaction.shouldDebugBreak ) {
  5076. // If you find your debugger stopping you here then go one level up on the
  5077. // call-stack for the code that caused it (typically a failed assertion)
  5078. // (To go back to the test and change execution, jump over the throw, next)
  5079. CATCH_BREAK_INTO_DEBUGGER();
  5080. }
  5081. if (m_reaction.shouldThrow) {
  5082. #if !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
  5083. throw Catch::TestFailureException();
  5084. #else
  5085. CATCH_ERROR( "Test failure requires aborting test!" );
  5086. #endif
  5087. }
  5088. }
  5089. void AssertionHandler::setCompleted() {
  5090. m_completed = true;
  5091. }
  5092. void AssertionHandler::handleUnexpectedInflightException() {
  5093. m_resultCapture.handleUnexpectedInflightException( m_assertionInfo, Catch::translateActiveException(), m_reaction );
  5094. }
  5095. void AssertionHandler::handleExceptionThrownAsExpected() {
  5096. m_resultCapture.handleNonExpr(m_assertionInfo, ResultWas::Ok, m_reaction);
  5097. }
  5098. void AssertionHandler::handleExceptionNotThrownAsExpected() {
  5099. m_resultCapture.handleNonExpr(m_assertionInfo, ResultWas::Ok, m_reaction);
  5100. }
  5101. void AssertionHandler::handleUnexpectedExceptionNotThrown() {
  5102. m_resultCapture.handleUnexpectedExceptionNotThrown( m_assertionInfo, m_reaction );
  5103. }
  5104. void AssertionHandler::handleThrowingCallSkipped() {
  5105. m_resultCapture.handleNonExpr(m_assertionInfo, ResultWas::Ok, m_reaction);
  5106. }
  5107. // This is the overload that takes a string and infers the Equals matcher from it
  5108. // The more general overload, that takes any string matcher, is in catch_capture_matchers.cpp
  5109. void handleExceptionMatchExpr( AssertionHandler& handler, std::string const& str, StringRef const& matcherString ) {
  5110. handleExceptionMatchExpr( handler, Matchers::Equals( str ), matcherString );
  5111. }
  5112. } // namespace Catch
  5113. // end catch_assertionhandler.cpp
  5114. // start catch_assertionresult.cpp
  5115. namespace Catch {
  5116. AssertionResultData::AssertionResultData(ResultWas::OfType _resultType, LazyExpression const & _lazyExpression):
  5117. lazyExpression(_lazyExpression),
  5118. resultType(_resultType) {}
  5119. std::string AssertionResultData::reconstructExpression() const {
  5120. if( reconstructedExpression.empty() ) {
  5121. if( lazyExpression ) {
  5122. ReusableStringStream rss;
  5123. rss << lazyExpression;
  5124. reconstructedExpression = rss.str();
  5125. }
  5126. }
  5127. return reconstructedExpression;
  5128. }
  5129. AssertionResult::AssertionResult( AssertionInfo const& info, AssertionResultData const& data )
  5130. : m_info( info ),
  5131. m_resultData( data )
  5132. {}
  5133. // Result was a success
  5134. bool AssertionResult::succeeded() const {
  5135. return Catch::isOk( m_resultData.resultType );
  5136. }
  5137. // Result was a success, or failure is suppressed
  5138. bool AssertionResult::isOk() const {
  5139. return Catch::isOk( m_resultData.resultType ) || shouldSuppressFailure( m_info.resultDisposition );
  5140. }
  5141. ResultWas::OfType AssertionResult::getResultType() const {
  5142. return m_resultData.resultType;
  5143. }
  5144. bool AssertionResult::hasExpression() const {
  5145. return m_info.capturedExpression[0] != 0;
  5146. }
  5147. bool AssertionResult::hasMessage() const {
  5148. return !m_resultData.message.empty();
  5149. }
  5150. std::string AssertionResult::getExpression() const {
  5151. if( isFalseTest( m_info.resultDisposition ) )
  5152. return "!(" + m_info.capturedExpression + ")";
  5153. else
  5154. return m_info.capturedExpression;
  5155. }
  5156. std::string AssertionResult::getExpressionInMacro() const {
  5157. std::string expr;
  5158. if( m_info.macroName[0] == 0 )
  5159. expr = m_info.capturedExpression;
  5160. else {
  5161. expr.reserve( m_info.macroName.size() + m_info.capturedExpression.size() + 4 );
  5162. expr += m_info.macroName;
  5163. expr += "( ";
  5164. expr += m_info.capturedExpression;
  5165. expr += " )";
  5166. }
  5167. return expr;
  5168. }
  5169. bool AssertionResult::hasExpandedExpression() const {
  5170. return hasExpression() && getExpandedExpression() != getExpression();
  5171. }
  5172. std::string AssertionResult::getExpandedExpression() const {
  5173. std::string expr = m_resultData.reconstructExpression();
  5174. return expr.empty()
  5175. ? getExpression()
  5176. : expr;
  5177. }
  5178. std::string AssertionResult::getMessage() const {
  5179. return m_resultData.message;
  5180. }
  5181. SourceLineInfo AssertionResult::getSourceInfo() const {
  5182. return m_info.lineInfo;
  5183. }
  5184. StringRef AssertionResult::getTestMacroName() const {
  5185. return m_info.macroName;
  5186. }
  5187. } // end namespace Catch
  5188. // end catch_assertionresult.cpp
  5189. // start catch_benchmark.cpp
  5190. namespace Catch {
  5191. auto BenchmarkLooper::getResolution() -> uint64_t {
  5192. return getEstimatedClockResolution() * getCurrentContext().getConfig()->benchmarkResolutionMultiple();
  5193. }
  5194. void BenchmarkLooper::reportStart() {
  5195. getResultCapture().benchmarkStarting( { m_name } );
  5196. }
  5197. auto BenchmarkLooper::needsMoreIterations() -> bool {
  5198. auto elapsed = m_timer.getElapsedNanoseconds();
  5199. // Exponentially increasing iterations until we're confident in our timer resolution
  5200. if( elapsed < m_resolution ) {
  5201. m_iterationsToRun *= 10;
  5202. return true;
  5203. }
  5204. getResultCapture().benchmarkEnded( { { m_name }, m_count, elapsed } );
  5205. return false;
  5206. }
  5207. } // end namespace Catch
  5208. // end catch_benchmark.cpp
  5209. // start catch_capture_matchers.cpp
  5210. namespace Catch {
  5211. using StringMatcher = Matchers::Impl::MatcherBase<std::string>;
  5212. // This is the general overload that takes a any string matcher
  5213. // There is another overload, in catch_assertionhandler.h/.cpp, that only takes a string and infers
  5214. // the Equals matcher (so the header does not mention matchers)
  5215. void handleExceptionMatchExpr( AssertionHandler& handler, StringMatcher const& matcher, StringRef const& matcherString ) {
  5216. std::string exceptionMessage = Catch::translateActiveException();
  5217. MatchExpr<std::string, StringMatcher const&> expr( exceptionMessage, matcher, matcherString );
  5218. handler.handleExpr( expr );
  5219. }
  5220. } // namespace Catch
  5221. // end catch_capture_matchers.cpp
  5222. // start catch_commandline.cpp
  5223. // start catch_commandline.h
  5224. // start catch_clara.h
  5225. // Use Catch's value for console width (store Clara's off to the side, if present)
  5226. #ifdef CLARA_CONFIG_CONSOLE_WIDTH
  5227. #define CATCH_TEMP_CLARA_CONFIG_CONSOLE_WIDTH CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH
  5228. #undef CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH
  5229. #endif
  5230. #define CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH CATCH_CONFIG_CONSOLE_WIDTH-1
  5231. #ifdef __clang__
  5232. #pragma clang diagnostic push
  5233. #pragma clang diagnostic ignored "-Wweak-vtables"
  5234. #pragma clang diagnostic ignored "-Wexit-time-destructors"
  5235. #pragma clang diagnostic ignored "-Wshadow"
  5236. #endif
  5237. // start clara.hpp
  5238. // Copyright 2017 Two Blue Cubes Ltd. All rights reserved.
  5239. //
  5240. // Distributed under the Boost Software License, Version 1.0. (See accompanying
  5241. // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
  5242. //
  5243. // See https://github.com/philsquared/Clara for more details
  5244. // Clara v1.1.5
  5245. #ifndef CATCH_CLARA_CONFIG_CONSOLE_WIDTH
  5246. #define CATCH_CLARA_CONFIG_CONSOLE_WIDTH 80
  5247. #endif
  5248. #ifndef CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH
  5249. #define CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH CATCH_CLARA_CONFIG_CONSOLE_WIDTH
  5250. #endif
  5251. #ifndef CLARA_CONFIG_OPTIONAL_TYPE
  5252. #ifdef __has_include
  5253. #if __has_include(<optional>) && __cplusplus >= 201703L
  5254. #include <optional>
  5255. #define CLARA_CONFIG_OPTIONAL_TYPE std::optional
  5256. #endif
  5257. #endif
  5258. #endif
  5259. // ----------- #included from clara_textflow.hpp -----------
  5260. // TextFlowCpp
  5261. //
  5262. // A single-header library for wrapping and laying out basic text, by Phil Nash
  5263. //
  5264. // Distributed under the Boost Software License, Version 1.0. (See accompanying
  5265. // file LICENSE.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
  5266. //
  5267. // This project is hosted at https://github.com/philsquared/textflowcpp
  5268. #include <cassert>
  5269. #include <ostream>
  5270. #include <sstream>
  5271. #include <vector>
  5272. #ifndef CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH
  5273. #define CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH 80
  5274. #endif
  5275. namespace Catch {
  5276. namespace clara {
  5277. namespace TextFlow {
  5278. inline auto isWhitespace(char c) -> bool {
  5279. static std::string chars = " \t\n\r";
  5280. return chars.find(c) != std::string::npos;
  5281. }
  5282. inline auto isBreakableBefore(char c) -> bool {
  5283. static std::string chars = "[({<|";
  5284. return chars.find(c) != std::string::npos;
  5285. }
  5286. inline auto isBreakableAfter(char c) -> bool {
  5287. static std::string chars = "])}>.,:;*+-=&/\\";
  5288. return chars.find(c) != std::string::npos;
  5289. }
  5290. class Columns;
  5291. class Column {
  5292. std::vector<std::string> m_strings;
  5293. size_t m_width = CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH;
  5294. size_t m_indent = 0;
  5295. size_t m_initialIndent = std::string::npos;
  5296. public:
  5297. class iterator {
  5298. friend Column;
  5299. Column const& m_column;
  5300. size_t m_stringIndex = 0;
  5301. size_t m_pos = 0;
  5302. size_t m_len = 0;
  5303. size_t m_end = 0;
  5304. bool m_suffix = false;
  5305. iterator(Column const& column, size_t stringIndex)
  5306. : m_column(column),
  5307. m_stringIndex(stringIndex) {}
  5308. auto line() const -> std::string const& { return m_column.m_strings[m_stringIndex]; }
  5309. auto isBoundary(size_t at) const -> bool {
  5310. assert(at > 0);
  5311. assert(at <= line().size());
  5312. return at == line().size() ||
  5313. (isWhitespace(line()[at]) && !isWhitespace(line()[at - 1])) ||
  5314. isBreakableBefore(line()[at]) ||
  5315. isBreakableAfter(line()[at - 1]);
  5316. }
  5317. void calcLength() {
  5318. assert(m_stringIndex < m_column.m_strings.size());
  5319. m_suffix = false;
  5320. auto width = m_column.m_width - indent();
  5321. m_end = m_pos;
  5322. while (m_end < line().size() && line()[m_end] != '\n')
  5323. ++m_end;
  5324. if (m_end < m_pos + width) {
  5325. m_len = m_end - m_pos;
  5326. } else {
  5327. size_t len = width;
  5328. while (len > 0 && !isBoundary(m_pos + len))
  5329. --len;
  5330. while (len > 0 && isWhitespace(line()[m_pos + len - 1]))
  5331. --len;
  5332. if (len > 0) {
  5333. m_len = len;
  5334. } else {
  5335. m_suffix = true;
  5336. m_len = width - 1;
  5337. }
  5338. }
  5339. }
  5340. auto indent() const -> size_t {
  5341. auto initial = m_pos == 0 && m_stringIndex == 0 ? m_column.m_initialIndent : std::string::npos;
  5342. return initial == std::string::npos ? m_column.m_indent : initial;
  5343. }
  5344. auto addIndentAndSuffix(std::string const &plain) const -> std::string {
  5345. return std::string(indent(), ' ') + (m_suffix ? plain + "-" : plain);
  5346. }
  5347. public:
  5348. using difference_type = std::ptrdiff_t;
  5349. using value_type = std::string;
  5350. using pointer = value_type * ;
  5351. using reference = value_type & ;
  5352. using iterator_category = std::forward_iterator_tag;
  5353. explicit iterator(Column const& column) : m_column(column) {
  5354. assert(m_column.m_width > m_column.m_indent);
  5355. assert(m_column.m_initialIndent == std::string::npos || m_column.m_width > m_column.m_initialIndent);
  5356. calcLength();
  5357. if (m_len == 0)
  5358. m_stringIndex++; // Empty string
  5359. }
  5360. auto operator *() const -> std::string {
  5361. assert(m_stringIndex < m_column.m_strings.size());
  5362. assert(m_pos <= m_end);
  5363. return addIndentAndSuffix(line().substr(m_pos, m_len));
  5364. }
  5365. auto operator ++() -> iterator& {
  5366. m_pos += m_len;
  5367. if (m_pos < line().size() && line()[m_pos] == '\n')
  5368. m_pos += 1;
  5369. else
  5370. while (m_pos < line().size() && isWhitespace(line()[m_pos]))
  5371. ++m_pos;
  5372. if (m_pos == line().size()) {
  5373. m_pos = 0;
  5374. ++m_stringIndex;
  5375. }
  5376. if (m_stringIndex < m_column.m_strings.size())
  5377. calcLength();
  5378. return *this;
  5379. }
  5380. auto operator ++(int) -> iterator {
  5381. iterator prev(*this);
  5382. operator++();
  5383. return prev;
  5384. }
  5385. auto operator ==(iterator const& other) const -> bool {
  5386. return
  5387. m_pos == other.m_pos &&
  5388. m_stringIndex == other.m_stringIndex &&
  5389. &m_column == &other.m_column;
  5390. }
  5391. auto operator !=(iterator const& other) const -> bool {
  5392. return !operator==(other);
  5393. }
  5394. };
  5395. using const_iterator = iterator;
  5396. explicit Column(std::string const& text) { m_strings.push_back(text); }
  5397. auto width(size_t newWidth) -> Column& {
  5398. assert(newWidth > 0);
  5399. m_width = newWidth;
  5400. return *this;
  5401. }
  5402. auto indent(size_t newIndent) -> Column& {
  5403. m_indent = newIndent;
  5404. return *this;
  5405. }
  5406. auto initialIndent(size_t newIndent) -> Column& {
  5407. m_initialIndent = newIndent;
  5408. return *this;
  5409. }
  5410. auto width() const -> size_t { return m_width; }
  5411. auto begin() const -> iterator { return iterator(*this); }
  5412. auto end() const -> iterator { return { *this, m_strings.size() }; }
  5413. inline friend std::ostream& operator << (std::ostream& os, Column const& col) {
  5414. bool first = true;
  5415. for (auto line : col) {
  5416. if (first)
  5417. first = false;
  5418. else
  5419. os << "\n";
  5420. os << line;
  5421. }
  5422. return os;
  5423. }
  5424. auto operator + (Column const& other)->Columns;
  5425. auto toString() const -> std::string {
  5426. std::ostringstream oss;
  5427. oss << *this;
  5428. return oss.str();
  5429. }
  5430. };
  5431. class Spacer : public Column {
  5432. public:
  5433. explicit Spacer(size_t spaceWidth) : Column("") {
  5434. width(spaceWidth);
  5435. }
  5436. };
  5437. class Columns {
  5438. std::vector<Column> m_columns;
  5439. public:
  5440. class iterator {
  5441. friend Columns;
  5442. struct EndTag {};
  5443. std::vector<Column> const& m_columns;
  5444. std::vector<Column::iterator> m_iterators;
  5445. size_t m_activeIterators;
  5446. iterator(Columns const& columns, EndTag)
  5447. : m_columns(columns.m_columns),
  5448. m_activeIterators(0) {
  5449. m_iterators.reserve(m_columns.size());
  5450. for (auto const& col : m_columns)
  5451. m_iterators.push_back(col.end());
  5452. }
  5453. public:
  5454. using difference_type = std::ptrdiff_t;
  5455. using value_type = std::string;
  5456. using pointer = value_type * ;
  5457. using reference = value_type & ;
  5458. using iterator_category = std::forward_iterator_tag;
  5459. explicit iterator(Columns const& columns)
  5460. : m_columns(columns.m_columns),
  5461. m_activeIterators(m_columns.size()) {
  5462. m_iterators.reserve(m_columns.size());
  5463. for (auto const& col : m_columns)
  5464. m_iterators.push_back(col.begin());
  5465. }
  5466. auto operator ==(iterator const& other) const -> bool {
  5467. return m_iterators == other.m_iterators;
  5468. }
  5469. auto operator !=(iterator const& other) const -> bool {
  5470. return m_iterators != other.m_iterators;
  5471. }
  5472. auto operator *() const -> std::string {
  5473. std::string row, padding;
  5474. for (size_t i = 0; i < m_columns.size(); ++i) {
  5475. auto width = m_columns[i].width();
  5476. if (m_iterators[i] != m_columns[i].end()) {
  5477. std::string col = *m_iterators[i];
  5478. row += padding + col;
  5479. if (col.size() < width)
  5480. padding = std::string(width - col.size(), ' ');
  5481. else
  5482. padding = "";
  5483. } else {
  5484. padding += std::string(width, ' ');
  5485. }
  5486. }
  5487. return row;
  5488. }
  5489. auto operator ++() -> iterator& {
  5490. for (size_t i = 0; i < m_columns.size(); ++i) {
  5491. if (m_iterators[i] != m_columns[i].end())
  5492. ++m_iterators[i];
  5493. }
  5494. return *this;
  5495. }
  5496. auto operator ++(int) -> iterator {
  5497. iterator prev(*this);
  5498. operator++();
  5499. return prev;
  5500. }
  5501. };
  5502. using const_iterator = iterator;
  5503. auto begin() const -> iterator { return iterator(*this); }
  5504. auto end() const -> iterator { return { *this, iterator::EndTag() }; }
  5505. auto operator += (Column const& col) -> Columns& {
  5506. m_columns.push_back(col);
  5507. return *this;
  5508. }
  5509. auto operator + (Column const& col) -> Columns {
  5510. Columns combined = *this;
  5511. combined += col;
  5512. return combined;
  5513. }
  5514. inline friend std::ostream& operator << (std::ostream& os, Columns const& cols) {
  5515. bool first = true;
  5516. for (auto line : cols) {
  5517. if (first)
  5518. first = false;
  5519. else
  5520. os << "\n";
  5521. os << line;
  5522. }
  5523. return os;
  5524. }
  5525. auto toString() const -> std::string {
  5526. std::ostringstream oss;
  5527. oss << *this;
  5528. return oss.str();
  5529. }
  5530. };
  5531. inline auto Column::operator + (Column const& other) -> Columns {
  5532. Columns cols;
  5533. cols += *this;
  5534. cols += other;
  5535. return cols;
  5536. }
  5537. }
  5538. }
  5539. }
  5540. // ----------- end of #include from clara_textflow.hpp -----------
  5541. // ........... back in clara.hpp
  5542. #include <cctype>
  5543. #include <string>
  5544. #include <memory>
  5545. #include <set>
  5546. #include <algorithm>
  5547. #if !defined(CATCH_PLATFORM_WINDOWS) && ( defined(WIN32) || defined(__WIN32__) || defined(_WIN32) || defined(_MSC_VER) )
  5548. #define CATCH_PLATFORM_WINDOWS
  5549. #endif
  5550. namespace Catch { namespace clara {
  5551. namespace detail {
  5552. // Traits for extracting arg and return type of lambdas (for single argument lambdas)
  5553. template<typename L>
  5554. struct UnaryLambdaTraits : UnaryLambdaTraits<decltype( &L::operator() )> {};
  5555. template<typename ClassT, typename ReturnT, typename... Args>
  5556. struct UnaryLambdaTraits<ReturnT( ClassT::* )( Args... ) const> {
  5557. static const bool isValid = false;
  5558. };
  5559. template<typename ClassT, typename ReturnT, typename ArgT>
  5560. struct UnaryLambdaTraits<ReturnT( ClassT::* )( ArgT ) const> {
  5561. static const bool isValid = true;
  5562. using ArgType = typename std::remove_const<typename std::remove_reference<ArgT>::type>::type;
  5563. using ReturnType = ReturnT;
  5564. };
  5565. class TokenStream;
  5566. // Transport for raw args (copied from main args, or supplied via init list for testing)
  5567. class Args {
  5568. friend TokenStream;
  5569. std::string m_exeName;
  5570. std::vector<std::string> m_args;
  5571. public:
  5572. Args( int argc, char const* const* argv )
  5573. : m_exeName(argv[0]),
  5574. m_args(argv + 1, argv + argc) {}
  5575. Args( std::initializer_list<std::string> args )
  5576. : m_exeName( *args.begin() ),
  5577. m_args( args.begin()+1, args.end() )
  5578. {}
  5579. auto exeName() const -> std::string {
  5580. return m_exeName;
  5581. }
  5582. };
  5583. // Wraps a token coming from a token stream. These may not directly correspond to strings as a single string
  5584. // may encode an option + its argument if the : or = form is used
  5585. enum class TokenType {
  5586. Option, Argument
  5587. };
  5588. struct Token {
  5589. TokenType type;
  5590. std::string token;
  5591. };
  5592. inline auto isOptPrefix( char c ) -> bool {
  5593. return c == '-'
  5594. #ifdef CATCH_PLATFORM_WINDOWS
  5595. || c == '/'
  5596. #endif
  5597. ;
  5598. }
  5599. // Abstracts iterators into args as a stream of tokens, with option arguments uniformly handled
  5600. class TokenStream {
  5601. using Iterator = std::vector<std::string>::const_iterator;
  5602. Iterator it;
  5603. Iterator itEnd;
  5604. std::vector<Token> m_tokenBuffer;
  5605. void loadBuffer() {
  5606. m_tokenBuffer.resize( 0 );
  5607. // Skip any empty strings
  5608. while( it != itEnd && it->empty() )
  5609. ++it;
  5610. if( it != itEnd ) {
  5611. auto const &next = *it;
  5612. if( isOptPrefix( next[0] ) ) {
  5613. auto delimiterPos = next.find_first_of( " :=" );
  5614. if( delimiterPos != std::string::npos ) {
  5615. m_tokenBuffer.push_back( { TokenType::Option, next.substr( 0, delimiterPos ) } );
  5616. m_tokenBuffer.push_back( { TokenType::Argument, next.substr( delimiterPos + 1 ) } );
  5617. } else {
  5618. if( next[1] != '-' && next.size() > 2 ) {
  5619. std::string opt = "- ";
  5620. for( size_t i = 1; i < next.size(); ++i ) {
  5621. opt[1] = next[i];
  5622. m_tokenBuffer.push_back( { TokenType::Option, opt } );
  5623. }
  5624. } else {
  5625. m_tokenBuffer.push_back( { TokenType::Option, next } );
  5626. }
  5627. }
  5628. } else {
  5629. m_tokenBuffer.push_back( { TokenType::Argument, next } );
  5630. }
  5631. }
  5632. }
  5633. public:
  5634. explicit TokenStream( Args const &args ) : TokenStream( args.m_args.begin(), args.m_args.end() ) {}
  5635. TokenStream( Iterator it, Iterator itEnd ) : it( it ), itEnd( itEnd ) {
  5636. loadBuffer();
  5637. }
  5638. explicit operator bool() const {
  5639. return !m_tokenBuffer.empty() || it != itEnd;
  5640. }
  5641. auto count() const -> size_t { return m_tokenBuffer.size() + (itEnd - it); }
  5642. auto operator*() const -> Token {
  5643. assert( !m_tokenBuffer.empty() );
  5644. return m_tokenBuffer.front();
  5645. }
  5646. auto operator->() const -> Token const * {
  5647. assert( !m_tokenBuffer.empty() );
  5648. return &m_tokenBuffer.front();
  5649. }
  5650. auto operator++() -> TokenStream & {
  5651. if( m_tokenBuffer.size() >= 2 ) {
  5652. m_tokenBuffer.erase( m_tokenBuffer.begin() );
  5653. } else {
  5654. if( it != itEnd )
  5655. ++it;
  5656. loadBuffer();
  5657. }
  5658. return *this;
  5659. }
  5660. };
  5661. class ResultBase {
  5662. public:
  5663. enum Type {
  5664. Ok, LogicError, RuntimeError
  5665. };
  5666. protected:
  5667. ResultBase( Type type ) : m_type( type ) {}
  5668. virtual ~ResultBase() = default;
  5669. virtual void enforceOk() const = 0;
  5670. Type m_type;
  5671. };
  5672. template<typename T>
  5673. class ResultValueBase : public ResultBase {
  5674. public:
  5675. auto value() const -> T const & {
  5676. enforceOk();
  5677. return m_value;
  5678. }
  5679. protected:
  5680. ResultValueBase( Type type ) : ResultBase( type ) {}
  5681. ResultValueBase( ResultValueBase const &other ) : ResultBase( other ) {
  5682. if( m_type == ResultBase::Ok )
  5683. new( &m_value ) T( other.m_value );
  5684. }
  5685. ResultValueBase( Type, T const &value ) : ResultBase( Ok ) {
  5686. new( &m_value ) T( value );
  5687. }
  5688. auto operator=( ResultValueBase const &other ) -> ResultValueBase & {
  5689. if( m_type == ResultBase::Ok )
  5690. m_value.~T();
  5691. ResultBase::operator=(other);
  5692. if( m_type == ResultBase::Ok )
  5693. new( &m_value ) T( other.m_value );
  5694. return *this;
  5695. }
  5696. ~ResultValueBase() override {
  5697. if( m_type == Ok )
  5698. m_value.~T();
  5699. }
  5700. union {
  5701. T m_value;
  5702. };
  5703. };
  5704. template<>
  5705. class ResultValueBase<void> : public ResultBase {
  5706. protected:
  5707. using ResultBase::ResultBase;
  5708. };
  5709. template<typename T = void>
  5710. class BasicResult : public ResultValueBase<T> {
  5711. public:
  5712. template<typename U>
  5713. explicit BasicResult( BasicResult<U> const &other )
  5714. : ResultValueBase<T>( other.type() ),
  5715. m_errorMessage( other.errorMessage() )
  5716. {
  5717. assert( type() != ResultBase::Ok );
  5718. }
  5719. template<typename U>
  5720. static auto ok( U const &value ) -> BasicResult { return { ResultBase::Ok, value }; }
  5721. static auto ok() -> BasicResult { return { ResultBase::Ok }; }
  5722. static auto logicError( std::string const &message ) -> BasicResult { return { ResultBase::LogicError, message }; }
  5723. static auto runtimeError( std::string const &message ) -> BasicResult { return { ResultBase::RuntimeError, message }; }
  5724. explicit operator bool() const { return m_type == ResultBase::Ok; }
  5725. auto type() const -> ResultBase::Type { return m_type; }
  5726. auto errorMessage() const -> std::string { return m_errorMessage; }
  5727. protected:
  5728. void enforceOk() const override {
  5729. // Errors shouldn't reach this point, but if they do
  5730. // the actual error message will be in m_errorMessage
  5731. assert( m_type != ResultBase::LogicError );
  5732. assert( m_type != ResultBase::RuntimeError );
  5733. if( m_type != ResultBase::Ok )
  5734. std::abort();
  5735. }
  5736. std::string m_errorMessage; // Only populated if resultType is an error
  5737. BasicResult( ResultBase::Type type, std::string const &message )
  5738. : ResultValueBase<T>(type),
  5739. m_errorMessage(message)
  5740. {
  5741. assert( m_type != ResultBase::Ok );
  5742. }
  5743. using ResultValueBase<T>::ResultValueBase;
  5744. using ResultBase::m_type;
  5745. };
  5746. enum class ParseResultType {
  5747. Matched, NoMatch, ShortCircuitAll, ShortCircuitSame
  5748. };
  5749. class ParseState {
  5750. public:
  5751. ParseState( ParseResultType type, TokenStream const &remainingTokens )
  5752. : m_type(type),
  5753. m_remainingTokens( remainingTokens )
  5754. {}
  5755. auto type() const -> ParseResultType { return m_type; }
  5756. auto remainingTokens() const -> TokenStream { return m_remainingTokens; }
  5757. private:
  5758. ParseResultType m_type;
  5759. TokenStream m_remainingTokens;
  5760. };
  5761. using Result = BasicResult<void>;
  5762. using ParserResult = BasicResult<ParseResultType>;
  5763. using InternalParseResult = BasicResult<ParseState>;
  5764. struct HelpColumns {
  5765. std::string left;
  5766. std::string right;
  5767. };
  5768. template<typename T>
  5769. inline auto convertInto( std::string const &source, T& target ) -> ParserResult {
  5770. std::stringstream ss;
  5771. ss << source;
  5772. ss >> target;
  5773. if( ss.fail() )
  5774. return ParserResult::runtimeError( "Unable to convert '" + source + "' to destination type" );
  5775. else
  5776. return ParserResult::ok( ParseResultType::Matched );
  5777. }
  5778. inline auto convertInto( std::string const &source, std::string& target ) -> ParserResult {
  5779. target = source;
  5780. return ParserResult::ok( ParseResultType::Matched );
  5781. }
  5782. inline auto convertInto( std::string const &source, bool &target ) -> ParserResult {
  5783. std::string srcLC = source;
  5784. std::transform( srcLC.begin(), srcLC.end(), srcLC.begin(), []( char c ) { return static_cast<char>( std::tolower(c) ); } );
  5785. if (srcLC == "y" || srcLC == "1" || srcLC == "true" || srcLC == "yes" || srcLC == "on")
  5786. target = true;
  5787. else if (srcLC == "n" || srcLC == "0" || srcLC == "false" || srcLC == "no" || srcLC == "off")
  5788. target = false;
  5789. else
  5790. return ParserResult::runtimeError( "Expected a boolean value but did not recognise: '" + source + "'" );
  5791. return ParserResult::ok( ParseResultType::Matched );
  5792. }
  5793. #ifdef CLARA_CONFIG_OPTIONAL_TYPE
  5794. template<typename T>
  5795. inline auto convertInto( std::string const &source, CLARA_CONFIG_OPTIONAL_TYPE<T>& target ) -> ParserResult {
  5796. T temp;
  5797. auto result = convertInto( source, temp );
  5798. if( result )
  5799. target = std::move(temp);
  5800. return result;
  5801. }
  5802. #endif // CLARA_CONFIG_OPTIONAL_TYPE
  5803. struct NonCopyable {
  5804. NonCopyable() = default;
  5805. NonCopyable( NonCopyable const & ) = delete;
  5806. NonCopyable( NonCopyable && ) = delete;
  5807. NonCopyable &operator=( NonCopyable const & ) = delete;
  5808. NonCopyable &operator=( NonCopyable && ) = delete;
  5809. };
  5810. struct BoundRef : NonCopyable {
  5811. virtual ~BoundRef() = default;
  5812. virtual auto isContainer() const -> bool { return false; }
  5813. virtual auto isFlag() const -> bool { return false; }
  5814. };
  5815. struct BoundValueRefBase : BoundRef {
  5816. virtual auto setValue( std::string const &arg ) -> ParserResult = 0;
  5817. };
  5818. struct BoundFlagRefBase : BoundRef {
  5819. virtual auto setFlag( bool flag ) -> ParserResult = 0;
  5820. virtual auto isFlag() const -> bool { return true; }
  5821. };
  5822. template<typename T>
  5823. struct BoundValueRef : BoundValueRefBase {
  5824. T &m_ref;
  5825. explicit BoundValueRef( T &ref ) : m_ref( ref ) {}
  5826. auto setValue( std::string const &arg ) -> ParserResult override {
  5827. return convertInto( arg, m_ref );
  5828. }
  5829. };
  5830. template<typename T>
  5831. struct BoundValueRef<std::vector<T>> : BoundValueRefBase {
  5832. std::vector<T> &m_ref;
  5833. explicit BoundValueRef( std::vector<T> &ref ) : m_ref( ref ) {}
  5834. auto isContainer() const -> bool override { return true; }
  5835. auto setValue( std::string const &arg ) -> ParserResult override {
  5836. T temp;
  5837. auto result = convertInto( arg, temp );
  5838. if( result )
  5839. m_ref.push_back( temp );
  5840. return result;
  5841. }
  5842. };
  5843. struct BoundFlagRef : BoundFlagRefBase {
  5844. bool &m_ref;
  5845. explicit BoundFlagRef( bool &ref ) : m_ref( ref ) {}
  5846. auto setFlag( bool flag ) -> ParserResult override {
  5847. m_ref = flag;
  5848. return ParserResult::ok( ParseResultType::Matched );
  5849. }
  5850. };
  5851. template<typename ReturnType>
  5852. struct LambdaInvoker {
  5853. static_assert( std::is_same<ReturnType, ParserResult>::value, "Lambda must return void or clara::ParserResult" );
  5854. template<typename L, typename ArgType>
  5855. static auto invoke( L const &lambda, ArgType const &arg ) -> ParserResult {
  5856. return lambda( arg );
  5857. }
  5858. };
  5859. template<>
  5860. struct LambdaInvoker<void> {
  5861. template<typename L, typename ArgType>
  5862. static auto invoke( L const &lambda, ArgType const &arg ) -> ParserResult {
  5863. lambda( arg );
  5864. return ParserResult::ok( ParseResultType::Matched );
  5865. }
  5866. };
  5867. template<typename ArgType, typename L>
  5868. inline auto invokeLambda( L const &lambda, std::string const &arg ) -> ParserResult {
  5869. ArgType temp{};
  5870. auto result = convertInto( arg, temp );
  5871. return !result
  5872. ? result
  5873. : LambdaInvoker<typename UnaryLambdaTraits<L>::ReturnType>::invoke( lambda, temp );
  5874. }
  5875. template<typename L>
  5876. struct BoundLambda : BoundValueRefBase {
  5877. L m_lambda;
  5878. static_assert( UnaryLambdaTraits<L>::isValid, "Supplied lambda must take exactly one argument" );
  5879. explicit BoundLambda( L const &lambda ) : m_lambda( lambda ) {}
  5880. auto setValue( std::string const &arg ) -> ParserResult override {
  5881. return invokeLambda<typename UnaryLambdaTraits<L>::ArgType>( m_lambda, arg );
  5882. }
  5883. };
  5884. template<typename L>
  5885. struct BoundFlagLambda : BoundFlagRefBase {
  5886. L m_lambda;
  5887. static_assert( UnaryLambdaTraits<L>::isValid, "Supplied lambda must take exactly one argument" );
  5888. static_assert( std::is_same<typename UnaryLambdaTraits<L>::ArgType, bool>::value, "flags must be boolean" );
  5889. explicit BoundFlagLambda( L const &lambda ) : m_lambda( lambda ) {}
  5890. auto setFlag( bool flag ) -> ParserResult override {
  5891. return LambdaInvoker<typename UnaryLambdaTraits<L>::ReturnType>::invoke( m_lambda, flag );
  5892. }
  5893. };
  5894. enum class Optionality { Optional, Required };
  5895. struct Parser;
  5896. class ParserBase {
  5897. public:
  5898. virtual ~ParserBase() = default;
  5899. virtual auto validate() const -> Result { return Result::ok(); }
  5900. virtual auto parse( std::string const& exeName, TokenStream const &tokens) const -> InternalParseResult = 0;
  5901. virtual auto cardinality() const -> size_t { return 1; }
  5902. auto parse( Args const &args ) const -> InternalParseResult {
  5903. return parse( args.exeName(), TokenStream( args ) );
  5904. }
  5905. };
  5906. template<typename DerivedT>
  5907. class ComposableParserImpl : public ParserBase {
  5908. public:
  5909. template<typename T>
  5910. auto operator|( T const &other ) const -> Parser;
  5911. template<typename T>
  5912. auto operator+( T const &other ) const -> Parser;
  5913. };
  5914. // Common code and state for Args and Opts
  5915. template<typename DerivedT>
  5916. class ParserRefImpl : public ComposableParserImpl<DerivedT> {
  5917. protected:
  5918. Optionality m_optionality = Optionality::Optional;
  5919. std::shared_ptr<BoundRef> m_ref;
  5920. std::string m_hint;
  5921. std::string m_description;
  5922. explicit ParserRefImpl( std::shared_ptr<BoundRef> const &ref ) : m_ref( ref ) {}
  5923. public:
  5924. template<typename T>
  5925. ParserRefImpl( T &ref, std::string const &hint )
  5926. : m_ref( std::make_shared<BoundValueRef<T>>( ref ) ),
  5927. m_hint( hint )
  5928. {}
  5929. template<typename LambdaT>
  5930. ParserRefImpl( LambdaT const &ref, std::string const &hint )
  5931. : m_ref( std::make_shared<BoundLambda<LambdaT>>( ref ) ),
  5932. m_hint(hint)
  5933. {}
  5934. auto operator()( std::string const &description ) -> DerivedT & {
  5935. m_description = description;
  5936. return static_cast<DerivedT &>( *this );
  5937. }
  5938. auto optional() -> DerivedT & {
  5939. m_optionality = Optionality::Optional;
  5940. return static_cast<DerivedT &>( *this );
  5941. };
  5942. auto required() -> DerivedT & {
  5943. m_optionality = Optionality::Required;
  5944. return static_cast<DerivedT &>( *this );
  5945. };
  5946. auto isOptional() const -> bool {
  5947. return m_optionality == Optionality::Optional;
  5948. }
  5949. auto cardinality() const -> size_t override {
  5950. if( m_ref->isContainer() )
  5951. return 0;
  5952. else
  5953. return 1;
  5954. }
  5955. auto hint() const -> std::string { return m_hint; }
  5956. };
  5957. class ExeName : public ComposableParserImpl<ExeName> {
  5958. std::shared_ptr<std::string> m_name;
  5959. std::shared_ptr<BoundValueRefBase> m_ref;
  5960. template<typename LambdaT>
  5961. static auto makeRef(LambdaT const &lambda) -> std::shared_ptr<BoundValueRefBase> {
  5962. return std::make_shared<BoundLambda<LambdaT>>( lambda) ;
  5963. }
  5964. public:
  5965. ExeName() : m_name( std::make_shared<std::string>( "<executable>" ) ) {}
  5966. explicit ExeName( std::string &ref ) : ExeName() {
  5967. m_ref = std::make_shared<BoundValueRef<std::string>>( ref );
  5968. }
  5969. template<typename LambdaT>
  5970. explicit ExeName( LambdaT const& lambda ) : ExeName() {
  5971. m_ref = std::make_shared<BoundLambda<LambdaT>>( lambda );
  5972. }
  5973. // The exe name is not parsed out of the normal tokens, but is handled specially
  5974. auto parse( std::string const&, TokenStream const &tokens ) const -> InternalParseResult override {
  5975. return InternalParseResult::ok( ParseState( ParseResultType::NoMatch, tokens ) );
  5976. }
  5977. auto name() const -> std::string { return *m_name; }
  5978. auto set( std::string const& newName ) -> ParserResult {
  5979. auto lastSlash = newName.find_last_of( "\\/" );
  5980. auto filename = ( lastSlash == std::string::npos )
  5981. ? newName
  5982. : newName.substr( lastSlash+1 );
  5983. *m_name = filename;
  5984. if( m_ref )
  5985. return m_ref->setValue( filename );
  5986. else
  5987. return ParserResult::ok( ParseResultType::Matched );
  5988. }
  5989. };
  5990. class Arg : public ParserRefImpl<Arg> {
  5991. public:
  5992. using ParserRefImpl::ParserRefImpl;
  5993. auto parse( std::string const &, TokenStream const &tokens ) const -> InternalParseResult override {
  5994. auto validationResult = validate();
  5995. if( !validationResult )
  5996. return InternalParseResult( validationResult );
  5997. auto remainingTokens = tokens;
  5998. auto const &token = *remainingTokens;
  5999. if( token.type != TokenType::Argument )
  6000. return InternalParseResult::ok( ParseState( ParseResultType::NoMatch, remainingTokens ) );
  6001. assert( !m_ref->isFlag() );
  6002. auto valueRef = static_cast<detail::BoundValueRefBase*>( m_ref.get() );
  6003. auto result = valueRef->setValue( remainingTokens->token );
  6004. if( !result )
  6005. return InternalParseResult( result );
  6006. else
  6007. return InternalParseResult::ok( ParseState( ParseResultType::Matched, ++remainingTokens ) );
  6008. }
  6009. };
  6010. inline auto normaliseOpt( std::string const &optName ) -> std::string {
  6011. #ifdef CATCH_PLATFORM_WINDOWS
  6012. if( optName[0] == '/' )
  6013. return "-" + optName.substr( 1 );
  6014. else
  6015. #endif
  6016. return optName;
  6017. }
  6018. class Opt : public ParserRefImpl<Opt> {
  6019. protected:
  6020. std::vector<std::string> m_optNames;
  6021. public:
  6022. template<typename LambdaT>
  6023. explicit Opt( LambdaT const &ref ) : ParserRefImpl( std::make_shared<BoundFlagLambda<LambdaT>>( ref ) ) {}
  6024. explicit Opt( bool &ref ) : ParserRefImpl( std::make_shared<BoundFlagRef>( ref ) ) {}
  6025. template<typename LambdaT>
  6026. Opt( LambdaT const &ref, std::string const &hint ) : ParserRefImpl( ref, hint ) {}
  6027. template<typename T>
  6028. Opt( T &ref, std::string const &hint ) : ParserRefImpl( ref, hint ) {}
  6029. auto operator[]( std::string const &optName ) -> Opt & {
  6030. m_optNames.push_back( optName );
  6031. return *this;
  6032. }
  6033. auto getHelpColumns() const -> std::vector<HelpColumns> {
  6034. std::ostringstream oss;
  6035. bool first = true;
  6036. for( auto const &opt : m_optNames ) {
  6037. if (first)
  6038. first = false;
  6039. else
  6040. oss << ", ";
  6041. oss << opt;
  6042. }
  6043. if( !m_hint.empty() )
  6044. oss << " <" << m_hint << ">";
  6045. return { { oss.str(), m_description } };
  6046. }
  6047. auto isMatch( std::string const &optToken ) const -> bool {
  6048. auto normalisedToken = normaliseOpt( optToken );
  6049. for( auto const &name : m_optNames ) {
  6050. if( normaliseOpt( name ) == normalisedToken )
  6051. return true;
  6052. }
  6053. return false;
  6054. }
  6055. using ParserBase::parse;
  6056. auto parse( std::string const&, TokenStream const &tokens ) const -> InternalParseResult override {
  6057. auto validationResult = validate();
  6058. if( !validationResult )
  6059. return InternalParseResult( validationResult );
  6060. auto remainingTokens = tokens;
  6061. if( remainingTokens && remainingTokens->type == TokenType::Option ) {
  6062. auto const &token = *remainingTokens;
  6063. if( isMatch(token.token ) ) {
  6064. if( m_ref->isFlag() ) {
  6065. auto flagRef = static_cast<detail::BoundFlagRefBase*>( m_ref.get() );
  6066. auto result = flagRef->setFlag( true );
  6067. if( !result )
  6068. return InternalParseResult( result );
  6069. if( result.value() == ParseResultType::ShortCircuitAll )
  6070. return InternalParseResult::ok( ParseState( result.value(), remainingTokens ) );
  6071. } else {
  6072. auto valueRef = static_cast<detail::BoundValueRefBase*>( m_ref.get() );
  6073. ++remainingTokens;
  6074. if( !remainingTokens )
  6075. return InternalParseResult::runtimeError( "Expected argument following " + token.token );
  6076. auto const &argToken = *remainingTokens;
  6077. if( argToken.type != TokenType::Argument )
  6078. return InternalParseResult::runtimeError( "Expected argument following " + token.token );
  6079. auto result = valueRef->setValue( argToken.token );
  6080. if( !result )
  6081. return InternalParseResult( result );
  6082. if( result.value() == ParseResultType::ShortCircuitAll )
  6083. return InternalParseResult::ok( ParseState( result.value(), remainingTokens ) );
  6084. }
  6085. return InternalParseResult::ok( ParseState( ParseResultType::Matched, ++remainingTokens ) );
  6086. }
  6087. }
  6088. return InternalParseResult::ok( ParseState( ParseResultType::NoMatch, remainingTokens ) );
  6089. }
  6090. auto validate() const -> Result override {
  6091. if( m_optNames.empty() )
  6092. return Result::logicError( "No options supplied to Opt" );
  6093. for( auto const &name : m_optNames ) {
  6094. if( name.empty() )
  6095. return Result::logicError( "Option name cannot be empty" );
  6096. #ifdef CATCH_PLATFORM_WINDOWS
  6097. if( name[0] != '-' && name[0] != '/' )
  6098. return Result::logicError( "Option name must begin with '-' or '/'" );
  6099. #else
  6100. if( name[0] != '-' )
  6101. return Result::logicError( "Option name must begin with '-'" );
  6102. #endif
  6103. }
  6104. return ParserRefImpl::validate();
  6105. }
  6106. };
  6107. struct Help : Opt {
  6108. Help( bool &showHelpFlag )
  6109. : Opt([&]( bool flag ) {
  6110. showHelpFlag = flag;
  6111. return ParserResult::ok( ParseResultType::ShortCircuitAll );
  6112. })
  6113. {
  6114. static_cast<Opt &>( *this )
  6115. ("display usage information")
  6116. ["-?"]["-h"]["--help"]
  6117. .optional();
  6118. }
  6119. };
  6120. struct Parser : ParserBase {
  6121. mutable ExeName m_exeName;
  6122. std::vector<Opt> m_options;
  6123. std::vector<Arg> m_args;
  6124. auto operator|=( ExeName const &exeName ) -> Parser & {
  6125. m_exeName = exeName;
  6126. return *this;
  6127. }
  6128. auto operator|=( Arg const &arg ) -> Parser & {
  6129. m_args.push_back(arg);
  6130. return *this;
  6131. }
  6132. auto operator|=( Opt const &opt ) -> Parser & {
  6133. m_options.push_back(opt);
  6134. return *this;
  6135. }
  6136. auto operator|=( Parser const &other ) -> Parser & {
  6137. m_options.insert(m_options.end(), other.m_options.begin(), other.m_options.end());
  6138. m_args.insert(m_args.end(), other.m_args.begin(), other.m_args.end());
  6139. return *this;
  6140. }
  6141. template<typename T>
  6142. auto operator|( T const &other ) const -> Parser {
  6143. return Parser( *this ) |= other;
  6144. }
  6145. // Forward deprecated interface with '+' instead of '|'
  6146. template<typename T>
  6147. auto operator+=( T const &other ) -> Parser & { return operator|=( other ); }
  6148. template<typename T>
  6149. auto operator+( T const &other ) const -> Parser { return operator|( other ); }
  6150. auto getHelpColumns() const -> std::vector<HelpColumns> {
  6151. std::vector<HelpColumns> cols;
  6152. for (auto const &o : m_options) {
  6153. auto childCols = o.getHelpColumns();
  6154. cols.insert( cols.end(), childCols.begin(), childCols.end() );
  6155. }
  6156. return cols;
  6157. }
  6158. void writeToStream( std::ostream &os ) const {
  6159. if (!m_exeName.name().empty()) {
  6160. os << "usage:\n" << " " << m_exeName.name() << " ";
  6161. bool required = true, first = true;
  6162. for( auto const &arg : m_args ) {
  6163. if (first)
  6164. first = false;
  6165. else
  6166. os << " ";
  6167. if( arg.isOptional() && required ) {
  6168. os << "[";
  6169. required = false;
  6170. }
  6171. os << "<" << arg.hint() << ">";
  6172. if( arg.cardinality() == 0 )
  6173. os << " ... ";
  6174. }
  6175. if( !required )
  6176. os << "]";
  6177. if( !m_options.empty() )
  6178. os << " options";
  6179. os << "\n\nwhere options are:" << std::endl;
  6180. }
  6181. auto rows = getHelpColumns();
  6182. size_t consoleWidth = CATCH_CLARA_CONFIG_CONSOLE_WIDTH;
  6183. size_t optWidth = 0;
  6184. for( auto const &cols : rows )
  6185. optWidth = (std::max)(optWidth, cols.left.size() + 2);
  6186. optWidth = (std::min)(optWidth, consoleWidth/2);
  6187. for( auto const &cols : rows ) {
  6188. auto row =
  6189. TextFlow::Column( cols.left ).width( optWidth ).indent( 2 ) +
  6190. TextFlow::Spacer(4) +
  6191. TextFlow::Column( cols.right ).width( consoleWidth - 7 - optWidth );
  6192. os << row << std::endl;
  6193. }
  6194. }
  6195. friend auto operator<<( std::ostream &os, Parser const &parser ) -> std::ostream& {
  6196. parser.writeToStream( os );
  6197. return os;
  6198. }
  6199. auto validate() const -> Result override {
  6200. for( auto const &opt : m_options ) {
  6201. auto result = opt.validate();
  6202. if( !result )
  6203. return result;
  6204. }
  6205. for( auto const &arg : m_args ) {
  6206. auto result = arg.validate();
  6207. if( !result )
  6208. return result;
  6209. }
  6210. return Result::ok();
  6211. }
  6212. using ParserBase::parse;
  6213. auto parse( std::string const& exeName, TokenStream const &tokens ) const -> InternalParseResult override {
  6214. struct ParserInfo {
  6215. ParserBase const* parser = nullptr;
  6216. size_t count = 0;
  6217. };
  6218. const size_t totalParsers = m_options.size() + m_args.size();
  6219. assert( totalParsers < 512 );
  6220. // ParserInfo parseInfos[totalParsers]; // <-- this is what we really want to do
  6221. ParserInfo parseInfos[512];
  6222. {
  6223. size_t i = 0;
  6224. for (auto const &opt : m_options) parseInfos[i++].parser = &opt;
  6225. for (auto const &arg : m_args) parseInfos[i++].parser = &arg;
  6226. }
  6227. m_exeName.set( exeName );
  6228. auto result = InternalParseResult::ok( ParseState( ParseResultType::NoMatch, tokens ) );
  6229. while( result.value().remainingTokens() ) {
  6230. bool tokenParsed = false;
  6231. for( size_t i = 0; i < totalParsers; ++i ) {
  6232. auto& parseInfo = parseInfos[i];
  6233. if( parseInfo.parser->cardinality() == 0 || parseInfo.count < parseInfo.parser->cardinality() ) {
  6234. result = parseInfo.parser->parse(exeName, result.value().remainingTokens());
  6235. if (!result)
  6236. return result;
  6237. if (result.value().type() != ParseResultType::NoMatch) {
  6238. tokenParsed = true;
  6239. ++parseInfo.count;
  6240. break;
  6241. }
  6242. }
  6243. }
  6244. if( result.value().type() == ParseResultType::ShortCircuitAll )
  6245. return result;
  6246. if( !tokenParsed )
  6247. return InternalParseResult::runtimeError( "Unrecognised token: " + result.value().remainingTokens()->token );
  6248. }
  6249. // !TBD Check missing required options
  6250. return result;
  6251. }
  6252. };
  6253. template<typename DerivedT>
  6254. template<typename T>
  6255. auto ComposableParserImpl<DerivedT>::operator|( T const &other ) const -> Parser {
  6256. return Parser() | static_cast<DerivedT const &>( *this ) | other;
  6257. }
  6258. } // namespace detail
  6259. // A Combined parser
  6260. using detail::Parser;
  6261. // A parser for options
  6262. using detail::Opt;
  6263. // A parser for arguments
  6264. using detail::Arg;
  6265. // Wrapper for argc, argv from main()
  6266. using detail::Args;
  6267. // Specifies the name of the executable
  6268. using detail::ExeName;
  6269. // Convenience wrapper for option parser that specifies the help option
  6270. using detail::Help;
  6271. // enum of result types from a parse
  6272. using detail::ParseResultType;
  6273. // Result type for parser operation
  6274. using detail::ParserResult;
  6275. }} // namespace Catch::clara
  6276. // end clara.hpp
  6277. #ifdef __clang__
  6278. #pragma clang diagnostic pop
  6279. #endif
  6280. // Restore Clara's value for console width, if present
  6281. #ifdef CATCH_TEMP_CLARA_CONFIG_CONSOLE_WIDTH
  6282. #define CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH CATCH_TEMP_CLARA_CONFIG_CONSOLE_WIDTH
  6283. #undef CATCH_TEMP_CLARA_CONFIG_CONSOLE_WIDTH
  6284. #endif
  6285. // end catch_clara.h
  6286. namespace Catch {
  6287. clara::Parser makeCommandLineParser( ConfigData& config );
  6288. } // end namespace Catch
  6289. // end catch_commandline.h
  6290. #include <fstream>
  6291. #include <ctime>
  6292. namespace Catch {
  6293. clara::Parser makeCommandLineParser( ConfigData& config ) {
  6294. using namespace clara;
  6295. auto const setWarning = [&]( std::string const& warning ) {
  6296. auto warningSet = [&]() {
  6297. if( warning == "NoAssertions" )
  6298. return WarnAbout::NoAssertions;
  6299. if ( warning == "NoTests" )
  6300. return WarnAbout::NoTests;
  6301. return WarnAbout::Nothing;
  6302. }();
  6303. if (warningSet == WarnAbout::Nothing)
  6304. return ParserResult::runtimeError( "Unrecognised warning: '" + warning + "'" );
  6305. config.warnings = static_cast<WarnAbout::What>( config.warnings | warningSet );
  6306. return ParserResult::ok( ParseResultType::Matched );
  6307. };
  6308. auto const loadTestNamesFromFile = [&]( std::string const& filename ) {
  6309. std::ifstream f( filename.c_str() );
  6310. if( !f.is_open() )
  6311. return ParserResult::runtimeError( "Unable to load input file: '" + filename + "'" );
  6312. std::string line;
  6313. while( std::getline( f, line ) ) {
  6314. line = trim(line);
  6315. if( !line.empty() && !startsWith( line, '#' ) ) {
  6316. if( !startsWith( line, '"' ) )
  6317. line = '"' + line + '"';
  6318. config.testsOrTags.push_back( line + ',' );
  6319. }
  6320. }
  6321. return ParserResult::ok( ParseResultType::Matched );
  6322. };
  6323. auto const setTestOrder = [&]( std::string const& order ) {
  6324. if( startsWith( "declared", order ) )
  6325. config.runOrder = RunTests::InDeclarationOrder;
  6326. else if( startsWith( "lexical", order ) )
  6327. config.runOrder = RunTests::InLexicographicalOrder;
  6328. else if( startsWith( "random", order ) )
  6329. config.runOrder = RunTests::InRandomOrder;
  6330. else
  6331. return clara::ParserResult::runtimeError( "Unrecognised ordering: '" + order + "'" );
  6332. return ParserResult::ok( ParseResultType::Matched );
  6333. };
  6334. auto const setRngSeed = [&]( std::string const& seed ) {
  6335. if( seed != "time" )
  6336. return clara::detail::convertInto( seed, config.rngSeed );
  6337. config.rngSeed = static_cast<unsigned int>( std::time(nullptr) );
  6338. return ParserResult::ok( ParseResultType::Matched );
  6339. };
  6340. auto const setColourUsage = [&]( std::string const& useColour ) {
  6341. auto mode = toLower( useColour );
  6342. if( mode == "yes" )
  6343. config.useColour = UseColour::Yes;
  6344. else if( mode == "no" )
  6345. config.useColour = UseColour::No;
  6346. else if( mode == "auto" )
  6347. config.useColour = UseColour::Auto;
  6348. else
  6349. return ParserResult::runtimeError( "colour mode must be one of: auto, yes or no. '" + useColour + "' not recognised" );
  6350. return ParserResult::ok( ParseResultType::Matched );
  6351. };
  6352. auto const setWaitForKeypress = [&]( std::string const& keypress ) {
  6353. auto keypressLc = toLower( keypress );
  6354. if( keypressLc == "start" )
  6355. config.waitForKeypress = WaitForKeypress::BeforeStart;
  6356. else if( keypressLc == "exit" )
  6357. config.waitForKeypress = WaitForKeypress::BeforeExit;
  6358. else if( keypressLc == "both" )
  6359. config.waitForKeypress = WaitForKeypress::BeforeStartAndExit;
  6360. else
  6361. return ParserResult::runtimeError( "keypress argument must be one of: start, exit or both. '" + keypress + "' not recognised" );
  6362. return ParserResult::ok( ParseResultType::Matched );
  6363. };
  6364. auto const setVerbosity = [&]( std::string const& verbosity ) {
  6365. auto lcVerbosity = toLower( verbosity );
  6366. if( lcVerbosity == "quiet" )
  6367. config.verbosity = Verbosity::Quiet;
  6368. else if( lcVerbosity == "normal" )
  6369. config.verbosity = Verbosity::Normal;
  6370. else if( lcVerbosity == "high" )
  6371. config.verbosity = Verbosity::High;
  6372. else
  6373. return ParserResult::runtimeError( "Unrecognised verbosity, '" + verbosity + "'" );
  6374. return ParserResult::ok( ParseResultType::Matched );
  6375. };
  6376. auto const setReporter = [&]( std::string const& reporter ) {
  6377. IReporterRegistry::FactoryMap const& factories = getRegistryHub().getReporterRegistry().getFactories();
  6378. auto lcReporter = toLower( reporter );
  6379. auto result = factories.find( lcReporter );
  6380. if( factories.end() != result )
  6381. config.reporterName = lcReporter;
  6382. else
  6383. return ParserResult::runtimeError( "Unrecognized reporter, '" + reporter + "'. Check available with --list-reporters" );
  6384. return ParserResult::ok( ParseResultType::Matched );
  6385. };
  6386. auto cli
  6387. = ExeName( config.processName )
  6388. | Help( config.showHelp )
  6389. | Opt( config.listTests )
  6390. ["-l"]["--list-tests"]
  6391. ( "list all/matching test cases" )
  6392. | Opt( config.listTags )
  6393. ["-t"]["--list-tags"]
  6394. ( "list all/matching tags" )
  6395. | Opt( config.showSuccessfulTests )
  6396. ["-s"]["--success"]
  6397. ( "include successful tests in output" )
  6398. | Opt( config.shouldDebugBreak )
  6399. ["-b"]["--break"]
  6400. ( "break into debugger on failure" )
  6401. | Opt( config.noThrow )
  6402. ["-e"]["--nothrow"]
  6403. ( "skip exception tests" )
  6404. | Opt( config.showInvisibles )
  6405. ["-i"]["--invisibles"]
  6406. ( "show invisibles (tabs, newlines)" )
  6407. | Opt( config.outputFilename, "filename" )
  6408. ["-o"]["--out"]
  6409. ( "output filename" )
  6410. | Opt( setReporter, "name" )
  6411. ["-r"]["--reporter"]
  6412. ( "reporter to use (defaults to console)" )
  6413. | Opt( config.name, "name" )
  6414. ["-n"]["--name"]
  6415. ( "suite name" )
  6416. | Opt( [&]( bool ){ config.abortAfter = 1; } )
  6417. ["-a"]["--abort"]
  6418. ( "abort at first failure" )
  6419. | Opt( [&]( int x ){ config.abortAfter = x; }, "no. failures" )
  6420. ["-x"]["--abortx"]
  6421. ( "abort after x failures" )
  6422. | Opt( setWarning, "warning name" )
  6423. ["-w"]["--warn"]
  6424. ( "enable warnings" )
  6425. | Opt( [&]( bool flag ) { config.showDurations = flag ? ShowDurations::Always : ShowDurations::Never; }, "yes|no" )
  6426. ["-d"]["--durations"]
  6427. ( "show test durations" )
  6428. | Opt( loadTestNamesFromFile, "filename" )
  6429. ["-f"]["--input-file"]
  6430. ( "load test names to run from a file" )
  6431. | Opt( config.filenamesAsTags )
  6432. ["-#"]["--filenames-as-tags"]
  6433. ( "adds a tag for the filename" )
  6434. | Opt( config.sectionsToRun, "section name" )
  6435. ["-c"]["--section"]
  6436. ( "specify section to run" )
  6437. | Opt( setVerbosity, "quiet|normal|high" )
  6438. ["-v"]["--verbosity"]
  6439. ( "set output verbosity" )
  6440. | Opt( config.listTestNamesOnly )
  6441. ["--list-test-names-only"]
  6442. ( "list all/matching test cases names only" )
  6443. | Opt( config.listReporters )
  6444. ["--list-reporters"]
  6445. ( "list all reporters" )
  6446. | Opt( setTestOrder, "decl|lex|rand" )
  6447. ["--order"]
  6448. ( "test case order (defaults to decl)" )
  6449. | Opt( setRngSeed, "'time'|number" )
  6450. ["--rng-seed"]
  6451. ( "set a specific seed for random numbers" )
  6452. | Opt( setColourUsage, "yes|no" )
  6453. ["--use-colour"]
  6454. ( "should output be colourised" )
  6455. | Opt( config.libIdentify )
  6456. ["--libidentify"]
  6457. ( "report name and version according to libidentify standard" )
  6458. | Opt( setWaitForKeypress, "start|exit|both" )
  6459. ["--wait-for-keypress"]
  6460. ( "waits for a keypress before exiting" )
  6461. | Opt( config.benchmarkResolutionMultiple, "multiplier" )
  6462. ["--benchmark-resolution-multiple"]
  6463. ( "multiple of clock resolution to run benchmarks" )
  6464. | Arg( config.testsOrTags, "test name|pattern|tags" )
  6465. ( "which test or tests to use" );
  6466. return cli;
  6467. }
  6468. } // end namespace Catch
  6469. // end catch_commandline.cpp
  6470. // start catch_common.cpp
  6471. #include <cstring>
  6472. #include <ostream>
  6473. namespace Catch {
  6474. bool SourceLineInfo::empty() const noexcept {
  6475. return file[0] == '\0';
  6476. }
  6477. bool SourceLineInfo::operator == ( SourceLineInfo const& other ) const noexcept {
  6478. return line == other.line && (file == other.file || std::strcmp(file, other.file) == 0);
  6479. }
  6480. bool SourceLineInfo::operator < ( SourceLineInfo const& other ) const noexcept {
  6481. // We can assume that the same file will usually have the same pointer.
  6482. // Thus, if the pointers are the same, there is no point in calling the strcmp
  6483. return line < other.line || ( line == other.line && file != other.file && (std::strcmp(file, other.file) < 0));
  6484. }
  6485. std::ostream& operator << ( std::ostream& os, SourceLineInfo const& info ) {
  6486. #ifndef __GNUG__
  6487. os << info.file << '(' << info.line << ')';
  6488. #else
  6489. os << info.file << ':' << info.line;
  6490. #endif
  6491. return os;
  6492. }
  6493. std::string StreamEndStop::operator+() const {
  6494. return std::string();
  6495. }
  6496. NonCopyable::NonCopyable() = default;
  6497. NonCopyable::~NonCopyable() = default;
  6498. }
  6499. // end catch_common.cpp
  6500. // start catch_config.cpp
  6501. namespace Catch {
  6502. Config::Config( ConfigData const& data )
  6503. : m_data( data ),
  6504. m_stream( openStream() )
  6505. {
  6506. TestSpecParser parser(ITagAliasRegistry::get());
  6507. if (data.testsOrTags.empty()) {
  6508. parser.parse("~[.]"); // All not hidden tests
  6509. }
  6510. else {
  6511. m_hasTestFilters = true;
  6512. for( auto const& testOrTags : data.testsOrTags )
  6513. parser.parse( testOrTags );
  6514. }
  6515. m_testSpec = parser.testSpec();
  6516. }
  6517. std::string const& Config::getFilename() const {
  6518. return m_data.outputFilename ;
  6519. }
  6520. bool Config::listTests() const { return m_data.listTests; }
  6521. bool Config::listTestNamesOnly() const { return m_data.listTestNamesOnly; }
  6522. bool Config::listTags() const { return m_data.listTags; }
  6523. bool Config::listReporters() const { return m_data.listReporters; }
  6524. std::string Config::getProcessName() const { return m_data.processName; }
  6525. std::string const& Config::getReporterName() const { return m_data.reporterName; }
  6526. std::vector<std::string> const& Config::getTestsOrTags() const { return m_data.testsOrTags; }
  6527. std::vector<std::string> const& Config::getSectionsToRun() const { return m_data.sectionsToRun; }
  6528. TestSpec const& Config::testSpec() const { return m_testSpec; }
  6529. bool Config::hasTestFilters() const { return m_hasTestFilters; }
  6530. bool Config::showHelp() const { return m_data.showHelp; }
  6531. // IConfig interface
  6532. bool Config::allowThrows() const { return !m_data.noThrow; }
  6533. std::ostream& Config::stream() const { return m_stream->stream(); }
  6534. std::string Config::name() const { return m_data.name.empty() ? m_data.processName : m_data.name; }
  6535. bool Config::includeSuccessfulResults() const { return m_data.showSuccessfulTests; }
  6536. bool Config::warnAboutMissingAssertions() const { return !!(m_data.warnings & WarnAbout::NoAssertions); }
  6537. bool Config::warnAboutNoTests() const { return !!(m_data.warnings & WarnAbout::NoTests); }
  6538. ShowDurations::OrNot Config::showDurations() const { return m_data.showDurations; }
  6539. RunTests::InWhatOrder Config::runOrder() const { return m_data.runOrder; }
  6540. unsigned int Config::rngSeed() const { return m_data.rngSeed; }
  6541. int Config::benchmarkResolutionMultiple() const { return m_data.benchmarkResolutionMultiple; }
  6542. UseColour::YesOrNo Config::useColour() const { return m_data.useColour; }
  6543. bool Config::shouldDebugBreak() const { return m_data.shouldDebugBreak; }
  6544. int Config::abortAfter() const { return m_data.abortAfter; }
  6545. bool Config::showInvisibles() const { return m_data.showInvisibles; }
  6546. Verbosity Config::verbosity() const { return m_data.verbosity; }
  6547. IStream const* Config::openStream() {
  6548. return Catch::makeStream(m_data.outputFilename);
  6549. }
  6550. } // end namespace Catch
  6551. // end catch_config.cpp
  6552. // start catch_console_colour.cpp
  6553. #if defined(__clang__)
  6554. # pragma clang diagnostic push
  6555. # pragma clang diagnostic ignored "-Wexit-time-destructors"
  6556. #endif
  6557. // start catch_errno_guard.h
  6558. namespace Catch {
  6559. class ErrnoGuard {
  6560. public:
  6561. ErrnoGuard();
  6562. ~ErrnoGuard();
  6563. private:
  6564. int m_oldErrno;
  6565. };
  6566. }
  6567. // end catch_errno_guard.h
  6568. #include <sstream>
  6569. namespace Catch {
  6570. namespace {
  6571. struct IColourImpl {
  6572. virtual ~IColourImpl() = default;
  6573. virtual void use( Colour::Code _colourCode ) = 0;
  6574. };
  6575. struct NoColourImpl : IColourImpl {
  6576. void use( Colour::Code ) {}
  6577. static IColourImpl* instance() {
  6578. static NoColourImpl s_instance;
  6579. return &s_instance;
  6580. }
  6581. };
  6582. } // anon namespace
  6583. } // namespace Catch
  6584. #if !defined( CATCH_CONFIG_COLOUR_NONE ) && !defined( CATCH_CONFIG_COLOUR_WINDOWS ) && !defined( CATCH_CONFIG_COLOUR_ANSI )
  6585. # ifdef CATCH_PLATFORM_WINDOWS
  6586. # define CATCH_CONFIG_COLOUR_WINDOWS
  6587. # else
  6588. # define CATCH_CONFIG_COLOUR_ANSI
  6589. # endif
  6590. #endif
  6591. #if defined ( CATCH_CONFIG_COLOUR_WINDOWS ) /////////////////////////////////////////
  6592. namespace Catch {
  6593. namespace {
  6594. class Win32ColourImpl : public IColourImpl {
  6595. public:
  6596. Win32ColourImpl() : stdoutHandle( GetStdHandle(STD_OUTPUT_HANDLE) )
  6597. {
  6598. CONSOLE_SCREEN_BUFFER_INFO csbiInfo;
  6599. GetConsoleScreenBufferInfo( stdoutHandle, &csbiInfo );
  6600. originalForegroundAttributes = csbiInfo.wAttributes & ~( BACKGROUND_GREEN | BACKGROUND_RED | BACKGROUND_BLUE | BACKGROUND_INTENSITY );
  6601. originalBackgroundAttributes = csbiInfo.wAttributes & ~( FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_BLUE | FOREGROUND_INTENSITY );
  6602. }
  6603. virtual void use( Colour::Code _colourCode ) override {
  6604. switch( _colourCode ) {
  6605. case Colour::None: return setTextAttribute( originalForegroundAttributes );
  6606. case Colour::White: return setTextAttribute( FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_BLUE );
  6607. case Colour::Red: return setTextAttribute( FOREGROUND_RED );
  6608. case Colour::Green: return setTextAttribute( FOREGROUND_GREEN );
  6609. case Colour::Blue: return setTextAttribute( FOREGROUND_BLUE );
  6610. case Colour::Cyan: return setTextAttribute( FOREGROUND_BLUE | FOREGROUND_GREEN );
  6611. case Colour::Yellow: return setTextAttribute( FOREGROUND_RED | FOREGROUND_GREEN );
  6612. case Colour::Grey: return setTextAttribute( 0 );
  6613. case Colour::LightGrey: return setTextAttribute( FOREGROUND_INTENSITY );
  6614. case Colour::BrightRed: return setTextAttribute( FOREGROUND_INTENSITY | FOREGROUND_RED );
  6615. case Colour::BrightGreen: return setTextAttribute( FOREGROUND_INTENSITY | FOREGROUND_GREEN );
  6616. case Colour::BrightWhite: return setTextAttribute( FOREGROUND_INTENSITY | FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_BLUE );
  6617. case Colour::BrightYellow: return setTextAttribute( FOREGROUND_INTENSITY | FOREGROUND_RED | FOREGROUND_GREEN );
  6618. case Colour::Bright: CATCH_INTERNAL_ERROR( "not a colour" );
  6619. default:
  6620. CATCH_ERROR( "Unknown colour requested" );
  6621. }
  6622. }
  6623. private:
  6624. void setTextAttribute( WORD _textAttribute ) {
  6625. SetConsoleTextAttribute( stdoutHandle, _textAttribute | originalBackgroundAttributes );
  6626. }
  6627. HANDLE stdoutHandle;
  6628. WORD originalForegroundAttributes;
  6629. WORD originalBackgroundAttributes;
  6630. };
  6631. IColourImpl* platformColourInstance() {
  6632. static Win32ColourImpl s_instance;
  6633. IConfigPtr config = getCurrentContext().getConfig();
  6634. UseColour::YesOrNo colourMode = config
  6635. ? config->useColour()
  6636. : UseColour::Auto;
  6637. if( colourMode == UseColour::Auto )
  6638. colourMode = UseColour::Yes;
  6639. return colourMode == UseColour::Yes
  6640. ? &s_instance
  6641. : NoColourImpl::instance();
  6642. }
  6643. } // end anon namespace
  6644. } // end namespace Catch
  6645. #elif defined( CATCH_CONFIG_COLOUR_ANSI ) //////////////////////////////////////
  6646. #include <unistd.h>
  6647. namespace Catch {
  6648. namespace {
  6649. // use POSIX/ ANSI console terminal codes
  6650. // Thanks to Adam Strzelecki for original contribution
  6651. // (http://github.com/nanoant)
  6652. // https://github.com/philsquared/Catch/pull/131
  6653. class PosixColourImpl : public IColourImpl {
  6654. public:
  6655. virtual void use( Colour::Code _colourCode ) override {
  6656. switch( _colourCode ) {
  6657. case Colour::None:
  6658. case Colour::White: return setColour( "[0m" );
  6659. case Colour::Red: return setColour( "[0;31m" );
  6660. case Colour::Green: return setColour( "[0;32m" );
  6661. case Colour::Blue: return setColour( "[0;34m" );
  6662. case Colour::Cyan: return setColour( "[0;36m" );
  6663. case Colour::Yellow: return setColour( "[0;33m" );
  6664. case Colour::Grey: return setColour( "[1;30m" );
  6665. case Colour::LightGrey: return setColour( "[0;37m" );
  6666. case Colour::BrightRed: return setColour( "[1;31m" );
  6667. case Colour::BrightGreen: return setColour( "[1;32m" );
  6668. case Colour::BrightWhite: return setColour( "[1;37m" );
  6669. case Colour::BrightYellow: return setColour( "[1;33m" );
  6670. case Colour::Bright: CATCH_INTERNAL_ERROR( "not a colour" );
  6671. default: CATCH_INTERNAL_ERROR( "Unknown colour requested" );
  6672. }
  6673. }
  6674. static IColourImpl* instance() {
  6675. static PosixColourImpl s_instance;
  6676. return &s_instance;
  6677. }
  6678. private:
  6679. void setColour( const char* _escapeCode ) {
  6680. getCurrentContext().getConfig()->stream()
  6681. << '\033' << _escapeCode;
  6682. }
  6683. };
  6684. bool useColourOnPlatform() {
  6685. return
  6686. #ifdef CATCH_PLATFORM_MAC
  6687. !isDebuggerActive() &&
  6688. #endif
  6689. #if !(defined(__DJGPP__) && defined(__STRICT_ANSI__))
  6690. isatty(STDOUT_FILENO)
  6691. #else
  6692. false
  6693. #endif
  6694. ;
  6695. }
  6696. IColourImpl* platformColourInstance() {
  6697. ErrnoGuard guard;
  6698. IConfigPtr config = getCurrentContext().getConfig();
  6699. UseColour::YesOrNo colourMode = config
  6700. ? config->useColour()
  6701. : UseColour::Auto;
  6702. if( colourMode == UseColour::Auto )
  6703. colourMode = useColourOnPlatform()
  6704. ? UseColour::Yes
  6705. : UseColour::No;
  6706. return colourMode == UseColour::Yes
  6707. ? PosixColourImpl::instance()
  6708. : NoColourImpl::instance();
  6709. }
  6710. } // end anon namespace
  6711. } // end namespace Catch
  6712. #else // not Windows or ANSI ///////////////////////////////////////////////
  6713. namespace Catch {
  6714. static IColourImpl* platformColourInstance() { return NoColourImpl::instance(); }
  6715. } // end namespace Catch
  6716. #endif // Windows/ ANSI/ None
  6717. namespace Catch {
  6718. Colour::Colour( Code _colourCode ) { use( _colourCode ); }
  6719. Colour::Colour( Colour&& rhs ) noexcept {
  6720. m_moved = rhs.m_moved;
  6721. rhs.m_moved = true;
  6722. }
  6723. Colour& Colour::operator=( Colour&& rhs ) noexcept {
  6724. m_moved = rhs.m_moved;
  6725. rhs.m_moved = true;
  6726. return *this;
  6727. }
  6728. Colour::~Colour(){ if( !m_moved ) use( None ); }
  6729. void Colour::use( Code _colourCode ) {
  6730. static IColourImpl* impl = platformColourInstance();
  6731. impl->use( _colourCode );
  6732. }
  6733. std::ostream& operator << ( std::ostream& os, Colour const& ) {
  6734. return os;
  6735. }
  6736. } // end namespace Catch
  6737. #if defined(__clang__)
  6738. # pragma clang diagnostic pop
  6739. #endif
  6740. // end catch_console_colour.cpp
  6741. // start catch_context.cpp
  6742. namespace Catch {
  6743. class Context : public IMutableContext, NonCopyable {
  6744. public: // IContext
  6745. virtual IResultCapture* getResultCapture() override {
  6746. return m_resultCapture;
  6747. }
  6748. virtual IRunner* getRunner() override {
  6749. return m_runner;
  6750. }
  6751. virtual IConfigPtr const& getConfig() const override {
  6752. return m_config;
  6753. }
  6754. virtual ~Context() override;
  6755. public: // IMutableContext
  6756. virtual void setResultCapture( IResultCapture* resultCapture ) override {
  6757. m_resultCapture = resultCapture;
  6758. }
  6759. virtual void setRunner( IRunner* runner ) override {
  6760. m_runner = runner;
  6761. }
  6762. virtual void setConfig( IConfigPtr const& config ) override {
  6763. m_config = config;
  6764. }
  6765. friend IMutableContext& getCurrentMutableContext();
  6766. private:
  6767. IConfigPtr m_config;
  6768. IRunner* m_runner = nullptr;
  6769. IResultCapture* m_resultCapture = nullptr;
  6770. };
  6771. IMutableContext *IMutableContext::currentContext = nullptr;
  6772. void IMutableContext::createContext()
  6773. {
  6774. currentContext = new Context();
  6775. }
  6776. void cleanUpContext() {
  6777. delete IMutableContext::currentContext;
  6778. IMutableContext::currentContext = nullptr;
  6779. }
  6780. IContext::~IContext() = default;
  6781. IMutableContext::~IMutableContext() = default;
  6782. Context::~Context() = default;
  6783. }
  6784. // end catch_context.cpp
  6785. // start catch_debug_console.cpp
  6786. // start catch_debug_console.h
  6787. #include <string>
  6788. namespace Catch {
  6789. void writeToDebugConsole( std::string const& text );
  6790. }
  6791. // end catch_debug_console.h
  6792. #ifdef CATCH_PLATFORM_WINDOWS
  6793. namespace Catch {
  6794. void writeToDebugConsole( std::string const& text ) {
  6795. ::OutputDebugStringA( text.c_str() );
  6796. }
  6797. }
  6798. #else
  6799. namespace Catch {
  6800. void writeToDebugConsole( std::string const& text ) {
  6801. // !TBD: Need a version for Mac/ XCode and other IDEs
  6802. Catch::cout() << text;
  6803. }
  6804. }
  6805. #endif // Platform
  6806. // end catch_debug_console.cpp
  6807. // start catch_debugger.cpp
  6808. #ifdef CATCH_PLATFORM_MAC
  6809. # include <assert.h>
  6810. # include <stdbool.h>
  6811. # include <sys/types.h>
  6812. # include <unistd.h>
  6813. # include <sys/sysctl.h>
  6814. # include <cstddef>
  6815. # include <ostream>
  6816. namespace Catch {
  6817. // The following function is taken directly from the following technical note:
  6818. // http://developer.apple.com/library/mac/#qa/qa2004/qa1361.html
  6819. // Returns true if the current process is being debugged (either
  6820. // running under the debugger or has a debugger attached post facto).
  6821. bool isDebuggerActive(){
  6822. int mib[4];
  6823. struct kinfo_proc info;
  6824. std::size_t size;
  6825. // Initialize the flags so that, if sysctl fails for some bizarre
  6826. // reason, we get a predictable result.
  6827. info.kp_proc.p_flag = 0;
  6828. // Initialize mib, which tells sysctl the info we want, in this case
  6829. // we're looking for information about a specific process ID.
  6830. mib[0] = CTL_KERN;
  6831. mib[1] = KERN_PROC;
  6832. mib[2] = KERN_PROC_PID;
  6833. mib[3] = getpid();
  6834. // Call sysctl.
  6835. size = sizeof(info);
  6836. if( sysctl(mib, sizeof(mib) / sizeof(*mib), &info, &size, nullptr, 0) != 0 ) {
  6837. Catch::cerr() << "\n** Call to sysctl failed - unable to determine if debugger is active **\n" << std::endl;
  6838. return false;
  6839. }
  6840. // We're being debugged if the P_TRACED flag is set.
  6841. return ( (info.kp_proc.p_flag & P_TRACED) != 0 );
  6842. }
  6843. } // namespace Catch
  6844. #elif defined(CATCH_PLATFORM_LINUX)
  6845. #include <fstream>
  6846. #include <string>
  6847. namespace Catch{
  6848. // The standard POSIX way of detecting a debugger is to attempt to
  6849. // ptrace() the process, but this needs to be done from a child and not
  6850. // this process itself to still allow attaching to this process later
  6851. // if wanted, so is rather heavy. Under Linux we have the PID of the
  6852. // "debugger" (which doesn't need to be gdb, of course, it could also
  6853. // be strace, for example) in /proc/$PID/status, so just get it from
  6854. // there instead.
  6855. bool isDebuggerActive(){
  6856. // Libstdc++ has a bug, where std::ifstream sets errno to 0
  6857. // This way our users can properly assert over errno values
  6858. ErrnoGuard guard;
  6859. std::ifstream in("/proc/self/status");
  6860. for( std::string line; std::getline(in, line); ) {
  6861. static const int PREFIX_LEN = 11;
  6862. if( line.compare(0, PREFIX_LEN, "TracerPid:\t") == 0 ) {
  6863. // We're traced if the PID is not 0 and no other PID starts
  6864. // with 0 digit, so it's enough to check for just a single
  6865. // character.
  6866. return line.length() > PREFIX_LEN && line[PREFIX_LEN] != '0';
  6867. }
  6868. }
  6869. return false;
  6870. }
  6871. } // namespace Catch
  6872. #elif defined(_MSC_VER)
  6873. extern "C" __declspec(dllimport) int __stdcall IsDebuggerPresent();
  6874. namespace Catch {
  6875. bool isDebuggerActive() {
  6876. return IsDebuggerPresent() != 0;
  6877. }
  6878. }
  6879. #elif defined(__MINGW32__)
  6880. extern "C" __declspec(dllimport) int __stdcall IsDebuggerPresent();
  6881. namespace Catch {
  6882. bool isDebuggerActive() {
  6883. return IsDebuggerPresent() != 0;
  6884. }
  6885. }
  6886. #else
  6887. namespace Catch {
  6888. bool isDebuggerActive() { return false; }
  6889. }
  6890. #endif // Platform
  6891. // end catch_debugger.cpp
  6892. // start catch_decomposer.cpp
  6893. namespace Catch {
  6894. ITransientExpression::~ITransientExpression() = default;
  6895. void formatReconstructedExpression( std::ostream &os, std::string const& lhs, StringRef op, std::string const& rhs ) {
  6896. if( lhs.size() + rhs.size() < 40 &&
  6897. lhs.find('\n') == std::string::npos &&
  6898. rhs.find('\n') == std::string::npos )
  6899. os << lhs << " " << op << " " << rhs;
  6900. else
  6901. os << lhs << "\n" << op << "\n" << rhs;
  6902. }
  6903. }
  6904. // end catch_decomposer.cpp
  6905. // start catch_enforce.cpp
  6906. namespace Catch {
  6907. #if defined(CATCH_CONFIG_DISABLE_EXCEPTIONS) && !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS_CUSTOM_HANDLER)
  6908. [[noreturn]]
  6909. void throw_exception(std::exception const& e) {
  6910. Catch::cerr() << "Catch will terminate because it needed to throw an exception.\n"
  6911. << "The message was: " << e.what() << '\n';
  6912. std::terminate();
  6913. }
  6914. #endif
  6915. } // namespace Catch;
  6916. // end catch_enforce.cpp
  6917. // start catch_errno_guard.cpp
  6918. #include <cerrno>
  6919. namespace Catch {
  6920. ErrnoGuard::ErrnoGuard():m_oldErrno(errno){}
  6921. ErrnoGuard::~ErrnoGuard() { errno = m_oldErrno; }
  6922. }
  6923. // end catch_errno_guard.cpp
  6924. // start catch_exception_translator_registry.cpp
  6925. // start catch_exception_translator_registry.h
  6926. #include <vector>
  6927. #include <string>
  6928. #include <memory>
  6929. namespace Catch {
  6930. class ExceptionTranslatorRegistry : public IExceptionTranslatorRegistry {
  6931. public:
  6932. ~ExceptionTranslatorRegistry();
  6933. virtual void registerTranslator( const IExceptionTranslator* translator );
  6934. virtual std::string translateActiveException() const override;
  6935. std::string tryTranslators() const;
  6936. private:
  6937. std::vector<std::unique_ptr<IExceptionTranslator const>> m_translators;
  6938. };
  6939. }
  6940. // end catch_exception_translator_registry.h
  6941. #ifdef __OBJC__
  6942. #import "Foundation/Foundation.h"
  6943. #endif
  6944. namespace Catch {
  6945. ExceptionTranslatorRegistry::~ExceptionTranslatorRegistry() {
  6946. }
  6947. void ExceptionTranslatorRegistry::registerTranslator( const IExceptionTranslator* translator ) {
  6948. m_translators.push_back( std::unique_ptr<const IExceptionTranslator>( translator ) );
  6949. }
  6950. #if !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
  6951. std::string ExceptionTranslatorRegistry::translateActiveException() const {
  6952. try {
  6953. #ifdef __OBJC__
  6954. // In Objective-C try objective-c exceptions first
  6955. @try {
  6956. return tryTranslators();
  6957. }
  6958. @catch (NSException *exception) {
  6959. return Catch::Detail::stringify( [exception description] );
  6960. }
  6961. #else
  6962. // Compiling a mixed mode project with MSVC means that CLR
  6963. // exceptions will be caught in (...) as well. However, these
  6964. // do not fill-in std::current_exception and thus lead to crash
  6965. // when attempting rethrow.
  6966. // /EHa switch also causes structured exceptions to be caught
  6967. // here, but they fill-in current_exception properly, so
  6968. // at worst the output should be a little weird, instead of
  6969. // causing a crash.
  6970. if (std::current_exception() == nullptr) {
  6971. return "Non C++ exception. Possibly a CLR exception.";
  6972. }
  6973. return tryTranslators();
  6974. #endif
  6975. }
  6976. catch( TestFailureException& ) {
  6977. std::rethrow_exception(std::current_exception());
  6978. }
  6979. catch( std::exception& ex ) {
  6980. return ex.what();
  6981. }
  6982. catch( std::string& msg ) {
  6983. return msg;
  6984. }
  6985. catch( const char* msg ) {
  6986. return msg;
  6987. }
  6988. catch(...) {
  6989. return "Unknown exception";
  6990. }
  6991. }
  6992. std::string ExceptionTranslatorRegistry::tryTranslators() const {
  6993. if (m_translators.empty()) {
  6994. std::rethrow_exception(std::current_exception());
  6995. } else {
  6996. return m_translators[0]->translate(m_translators.begin() + 1, m_translators.end());
  6997. }
  6998. }
  6999. #else // ^^ Exceptions are enabled // Exceptions are disabled vv
  7000. std::string ExceptionTranslatorRegistry::translateActiveException() const {
  7001. CATCH_INTERNAL_ERROR("Attempted to translate active exception under CATCH_CONFIG_DISABLE_EXCEPTIONS!");
  7002. }
  7003. std::string ExceptionTranslatorRegistry::tryTranslators() const {
  7004. CATCH_INTERNAL_ERROR("Attempted to use exception translators under CATCH_CONFIG_DISABLE_EXCEPTIONS!");
  7005. }
  7006. #endif
  7007. }
  7008. // end catch_exception_translator_registry.cpp
  7009. // start catch_fatal_condition.cpp
  7010. #if defined(__GNUC__)
  7011. # pragma GCC diagnostic push
  7012. # pragma GCC diagnostic ignored "-Wmissing-field-initializers"
  7013. #endif
  7014. #if defined( CATCH_CONFIG_WINDOWS_SEH ) || defined( CATCH_CONFIG_POSIX_SIGNALS )
  7015. namespace {
  7016. // Report the error condition
  7017. void reportFatal( char const * const message ) {
  7018. Catch::getCurrentContext().getResultCapture()->handleFatalErrorCondition( message );
  7019. }
  7020. }
  7021. #endif // signals/SEH handling
  7022. #if defined( CATCH_CONFIG_WINDOWS_SEH )
  7023. namespace Catch {
  7024. struct SignalDefs { DWORD id; const char* name; };
  7025. // There is no 1-1 mapping between signals and windows exceptions.
  7026. // Windows can easily distinguish between SO and SigSegV,
  7027. // but SigInt, SigTerm, etc are handled differently.
  7028. static SignalDefs signalDefs[] = {
  7029. { static_cast<DWORD>(EXCEPTION_ILLEGAL_INSTRUCTION), "SIGILL - Illegal instruction signal" },
  7030. { static_cast<DWORD>(EXCEPTION_STACK_OVERFLOW), "SIGSEGV - Stack overflow" },
  7031. { static_cast<DWORD>(EXCEPTION_ACCESS_VIOLATION), "SIGSEGV - Segmentation violation signal" },
  7032. { static_cast<DWORD>(EXCEPTION_INT_DIVIDE_BY_ZERO), "Divide by zero error" },
  7033. };
  7034. LONG CALLBACK FatalConditionHandler::handleVectoredException(PEXCEPTION_POINTERS ExceptionInfo) {
  7035. for (auto const& def : signalDefs) {
  7036. if (ExceptionInfo->ExceptionRecord->ExceptionCode == def.id) {
  7037. reportFatal(def.name);
  7038. }
  7039. }
  7040. // If its not an exception we care about, pass it along.
  7041. // This stops us from eating debugger breaks etc.
  7042. return EXCEPTION_CONTINUE_SEARCH;
  7043. }
  7044. FatalConditionHandler::FatalConditionHandler() {
  7045. isSet = true;
  7046. // 32k seems enough for Catch to handle stack overflow,
  7047. // but the value was found experimentally, so there is no strong guarantee
  7048. guaranteeSize = 32 * 1024;
  7049. exceptionHandlerHandle = nullptr;
  7050. // Register as first handler in current chain
  7051. exceptionHandlerHandle = AddVectoredExceptionHandler(1, handleVectoredException);
  7052. // Pass in guarantee size to be filled
  7053. SetThreadStackGuarantee(&guaranteeSize);
  7054. }
  7055. void FatalConditionHandler::reset() {
  7056. if (isSet) {
  7057. RemoveVectoredExceptionHandler(exceptionHandlerHandle);
  7058. SetThreadStackGuarantee(&guaranteeSize);
  7059. exceptionHandlerHandle = nullptr;
  7060. isSet = false;
  7061. }
  7062. }
  7063. FatalConditionHandler::~FatalConditionHandler() {
  7064. reset();
  7065. }
  7066. bool FatalConditionHandler::isSet = false;
  7067. ULONG FatalConditionHandler::guaranteeSize = 0;
  7068. PVOID FatalConditionHandler::exceptionHandlerHandle = nullptr;
  7069. } // namespace Catch
  7070. #elif defined( CATCH_CONFIG_POSIX_SIGNALS )
  7071. namespace Catch {
  7072. struct SignalDefs {
  7073. int id;
  7074. const char* name;
  7075. };
  7076. // 32kb for the alternate stack seems to be sufficient. However, this value
  7077. // is experimentally determined, so that's not guaranteed.
  7078. constexpr static std::size_t sigStackSize = 32768 >= MINSIGSTKSZ ? 32768 : MINSIGSTKSZ;
  7079. static SignalDefs signalDefs[] = {
  7080. { SIGINT, "SIGINT - Terminal interrupt signal" },
  7081. { SIGILL, "SIGILL - Illegal instruction signal" },
  7082. { SIGFPE, "SIGFPE - Floating point error signal" },
  7083. { SIGSEGV, "SIGSEGV - Segmentation violation signal" },
  7084. { SIGTERM, "SIGTERM - Termination request signal" },
  7085. { SIGABRT, "SIGABRT - Abort (abnormal termination) signal" }
  7086. };
  7087. void FatalConditionHandler::handleSignal( int sig ) {
  7088. char const * name = "<unknown signal>";
  7089. for (auto const& def : signalDefs) {
  7090. if (sig == def.id) {
  7091. name = def.name;
  7092. break;
  7093. }
  7094. }
  7095. reset();
  7096. reportFatal(name);
  7097. raise( sig );
  7098. }
  7099. FatalConditionHandler::FatalConditionHandler() {
  7100. isSet = true;
  7101. stack_t sigStack;
  7102. sigStack.ss_sp = altStackMem;
  7103. sigStack.ss_size = sigStackSize;
  7104. sigStack.ss_flags = 0;
  7105. sigaltstack(&sigStack, &oldSigStack);
  7106. struct sigaction sa = { };
  7107. sa.sa_handler = handleSignal;
  7108. sa.sa_flags = SA_ONSTACK;
  7109. for (std::size_t i = 0; i < sizeof(signalDefs)/sizeof(SignalDefs); ++i) {
  7110. sigaction(signalDefs[i].id, &sa, &oldSigActions[i]);
  7111. }
  7112. }
  7113. FatalConditionHandler::~FatalConditionHandler() {
  7114. reset();
  7115. }
  7116. void FatalConditionHandler::reset() {
  7117. if( isSet ) {
  7118. // Set signals back to previous values -- hopefully nobody overwrote them in the meantime
  7119. for( std::size_t i = 0; i < sizeof(signalDefs)/sizeof(SignalDefs); ++i ) {
  7120. sigaction(signalDefs[i].id, &oldSigActions[i], nullptr);
  7121. }
  7122. // Return the old stack
  7123. sigaltstack(&oldSigStack, nullptr);
  7124. isSet = false;
  7125. }
  7126. }
  7127. bool FatalConditionHandler::isSet = false;
  7128. struct sigaction FatalConditionHandler::oldSigActions[sizeof(signalDefs)/sizeof(SignalDefs)] = {};
  7129. stack_t FatalConditionHandler::oldSigStack = {};
  7130. char FatalConditionHandler::altStackMem[sigStackSize] = {};
  7131. } // namespace Catch
  7132. #else
  7133. namespace Catch {
  7134. void FatalConditionHandler::reset() {}
  7135. }
  7136. #endif // signals/SEH handling
  7137. #if defined(__GNUC__)
  7138. # pragma GCC diagnostic pop
  7139. #endif
  7140. // end catch_fatal_condition.cpp
  7141. // start catch_generators.cpp
  7142. // start catch_random_number_generator.h
  7143. #include <algorithm>
  7144. #include <random>
  7145. namespace Catch {
  7146. struct IConfig;
  7147. std::mt19937& rng();
  7148. void seedRng( IConfig const& config );
  7149. unsigned int rngSeed();
  7150. }
  7151. // end catch_random_number_generator.h
  7152. #include <limits>
  7153. #include <set>
  7154. namespace Catch {
  7155. IGeneratorTracker::~IGeneratorTracker() {}
  7156. const char* GeneratorException::what() const noexcept {
  7157. return m_msg;
  7158. }
  7159. namespace Generators {
  7160. GeneratorUntypedBase::~GeneratorUntypedBase() {}
  7161. auto acquireGeneratorTracker( SourceLineInfo const& lineInfo ) -> IGeneratorTracker& {
  7162. return getResultCapture().acquireGeneratorTracker( lineInfo );
  7163. }
  7164. } // namespace Generators
  7165. } // namespace Catch
  7166. // end catch_generators.cpp
  7167. // start catch_interfaces_capture.cpp
  7168. namespace Catch {
  7169. IResultCapture::~IResultCapture() = default;
  7170. }
  7171. // end catch_interfaces_capture.cpp
  7172. // start catch_interfaces_config.cpp
  7173. namespace Catch {
  7174. IConfig::~IConfig() = default;
  7175. }
  7176. // end catch_interfaces_config.cpp
  7177. // start catch_interfaces_exception.cpp
  7178. namespace Catch {
  7179. IExceptionTranslator::~IExceptionTranslator() = default;
  7180. IExceptionTranslatorRegistry::~IExceptionTranslatorRegistry() = default;
  7181. }
  7182. // end catch_interfaces_exception.cpp
  7183. // start catch_interfaces_registry_hub.cpp
  7184. namespace Catch {
  7185. IRegistryHub::~IRegistryHub() = default;
  7186. IMutableRegistryHub::~IMutableRegistryHub() = default;
  7187. }
  7188. // end catch_interfaces_registry_hub.cpp
  7189. // start catch_interfaces_reporter.cpp
  7190. // start catch_reporter_listening.h
  7191. namespace Catch {
  7192. class ListeningReporter : public IStreamingReporter {
  7193. using Reporters = std::vector<IStreamingReporterPtr>;
  7194. Reporters m_listeners;
  7195. IStreamingReporterPtr m_reporter = nullptr;
  7196. ReporterPreferences m_preferences;
  7197. public:
  7198. ListeningReporter();
  7199. void addListener( IStreamingReporterPtr&& listener );
  7200. void addReporter( IStreamingReporterPtr&& reporter );
  7201. public: // IStreamingReporter
  7202. ReporterPreferences getPreferences() const override;
  7203. void noMatchingTestCases( std::string const& spec ) override;
  7204. static std::set<Verbosity> getSupportedVerbosities();
  7205. void benchmarkStarting( BenchmarkInfo const& benchmarkInfo ) override;
  7206. void benchmarkEnded( BenchmarkStats const& benchmarkStats ) override;
  7207. void testRunStarting( TestRunInfo const& testRunInfo ) override;
  7208. void testGroupStarting( GroupInfo const& groupInfo ) override;
  7209. void testCaseStarting( TestCaseInfo const& testInfo ) override;
  7210. void sectionStarting( SectionInfo const& sectionInfo ) override;
  7211. void assertionStarting( AssertionInfo const& assertionInfo ) override;
  7212. // The return value indicates if the messages buffer should be cleared:
  7213. bool assertionEnded( AssertionStats const& assertionStats ) override;
  7214. void sectionEnded( SectionStats const& sectionStats ) override;
  7215. void testCaseEnded( TestCaseStats const& testCaseStats ) override;
  7216. void testGroupEnded( TestGroupStats const& testGroupStats ) override;
  7217. void testRunEnded( TestRunStats const& testRunStats ) override;
  7218. void skipTest( TestCaseInfo const& testInfo ) override;
  7219. bool isMulti() const override;
  7220. };
  7221. } // end namespace Catch
  7222. // end catch_reporter_listening.h
  7223. namespace Catch {
  7224. ReporterConfig::ReporterConfig( IConfigPtr const& _fullConfig )
  7225. : m_stream( &_fullConfig->stream() ), m_fullConfig( _fullConfig ) {}
  7226. ReporterConfig::ReporterConfig( IConfigPtr const& _fullConfig, std::ostream& _stream )
  7227. : m_stream( &_stream ), m_fullConfig( _fullConfig ) {}
  7228. std::ostream& ReporterConfig::stream() const { return *m_stream; }
  7229. IConfigPtr ReporterConfig::fullConfig() const { return m_fullConfig; }
  7230. TestRunInfo::TestRunInfo( std::string const& _name ) : name( _name ) {}
  7231. GroupInfo::GroupInfo( std::string const& _name,
  7232. std::size_t _groupIndex,
  7233. std::size_t _groupsCount )
  7234. : name( _name ),
  7235. groupIndex( _groupIndex ),
  7236. groupsCounts( _groupsCount )
  7237. {}
  7238. AssertionStats::AssertionStats( AssertionResult const& _assertionResult,
  7239. std::vector<MessageInfo> const& _infoMessages,
  7240. Totals const& _totals )
  7241. : assertionResult( _assertionResult ),
  7242. infoMessages( _infoMessages ),
  7243. totals( _totals )
  7244. {
  7245. assertionResult.m_resultData.lazyExpression.m_transientExpression = _assertionResult.m_resultData.lazyExpression.m_transientExpression;
  7246. if( assertionResult.hasMessage() ) {
  7247. // Copy message into messages list.
  7248. // !TBD This should have been done earlier, somewhere
  7249. MessageBuilder builder( assertionResult.getTestMacroName(), assertionResult.getSourceInfo(), assertionResult.getResultType() );
  7250. builder << assertionResult.getMessage();
  7251. builder.m_info.message = builder.m_stream.str();
  7252. infoMessages.push_back( builder.m_info );
  7253. }
  7254. }
  7255. AssertionStats::~AssertionStats() = default;
  7256. SectionStats::SectionStats( SectionInfo const& _sectionInfo,
  7257. Counts const& _assertions,
  7258. double _durationInSeconds,
  7259. bool _missingAssertions )
  7260. : sectionInfo( _sectionInfo ),
  7261. assertions( _assertions ),
  7262. durationInSeconds( _durationInSeconds ),
  7263. missingAssertions( _missingAssertions )
  7264. {}
  7265. SectionStats::~SectionStats() = default;
  7266. TestCaseStats::TestCaseStats( TestCaseInfo const& _testInfo,
  7267. Totals const& _totals,
  7268. std::string const& _stdOut,
  7269. std::string const& _stdErr,
  7270. bool _aborting )
  7271. : testInfo( _testInfo ),
  7272. totals( _totals ),
  7273. stdOut( _stdOut ),
  7274. stdErr( _stdErr ),
  7275. aborting( _aborting )
  7276. {}
  7277. TestCaseStats::~TestCaseStats() = default;
  7278. TestGroupStats::TestGroupStats( GroupInfo const& _groupInfo,
  7279. Totals const& _totals,
  7280. bool _aborting )
  7281. : groupInfo( _groupInfo ),
  7282. totals( _totals ),
  7283. aborting( _aborting )
  7284. {}
  7285. TestGroupStats::TestGroupStats( GroupInfo const& _groupInfo )
  7286. : groupInfo( _groupInfo ),
  7287. aborting( false )
  7288. {}
  7289. TestGroupStats::~TestGroupStats() = default;
  7290. TestRunStats::TestRunStats( TestRunInfo const& _runInfo,
  7291. Totals const& _totals,
  7292. bool _aborting )
  7293. : runInfo( _runInfo ),
  7294. totals( _totals ),
  7295. aborting( _aborting )
  7296. {}
  7297. TestRunStats::~TestRunStats() = default;
  7298. void IStreamingReporter::fatalErrorEncountered( StringRef ) {}
  7299. bool IStreamingReporter::isMulti() const { return false; }
  7300. IReporterFactory::~IReporterFactory() = default;
  7301. IReporterRegistry::~IReporterRegistry() = default;
  7302. } // end namespace Catch
  7303. // end catch_interfaces_reporter.cpp
  7304. // start catch_interfaces_runner.cpp
  7305. namespace Catch {
  7306. IRunner::~IRunner() = default;
  7307. }
  7308. // end catch_interfaces_runner.cpp
  7309. // start catch_interfaces_testcase.cpp
  7310. namespace Catch {
  7311. ITestInvoker::~ITestInvoker() = default;
  7312. ITestCaseRegistry::~ITestCaseRegistry() = default;
  7313. }
  7314. // end catch_interfaces_testcase.cpp
  7315. // start catch_leak_detector.cpp
  7316. #ifdef CATCH_CONFIG_WINDOWS_CRTDBG
  7317. #include <crtdbg.h>
  7318. namespace Catch {
  7319. LeakDetector::LeakDetector() {
  7320. int flag = _CrtSetDbgFlag(_CRTDBG_REPORT_FLAG);
  7321. flag |= _CRTDBG_LEAK_CHECK_DF;
  7322. flag |= _CRTDBG_ALLOC_MEM_DF;
  7323. _CrtSetDbgFlag(flag);
  7324. _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE | _CRTDBG_MODE_DEBUG);
  7325. _CrtSetReportFile(_CRT_WARN, _CRTDBG_FILE_STDERR);
  7326. // Change this to leaking allocation's number to break there
  7327. _CrtSetBreakAlloc(-1);
  7328. }
  7329. }
  7330. #else
  7331. Catch::LeakDetector::LeakDetector() {}
  7332. #endif
  7333. Catch::LeakDetector::~LeakDetector() {
  7334. Catch::cleanUp();
  7335. }
  7336. // end catch_leak_detector.cpp
  7337. // start catch_list.cpp
  7338. // start catch_list.h
  7339. #include <set>
  7340. namespace Catch {
  7341. std::size_t listTests( Config const& config );
  7342. std::size_t listTestsNamesOnly( Config const& config );
  7343. struct TagInfo {
  7344. void add( std::string const& spelling );
  7345. std::string all() const;
  7346. std::set<std::string> spellings;
  7347. std::size_t count = 0;
  7348. };
  7349. std::size_t listTags( Config const& config );
  7350. std::size_t listReporters();
  7351. Option<std::size_t> list( std::shared_ptr<Config> const& config );
  7352. } // end namespace Catch
  7353. // end catch_list.h
  7354. // start catch_text.h
  7355. namespace Catch {
  7356. using namespace clara::TextFlow;
  7357. }
  7358. // end catch_text.h
  7359. #include <limits>
  7360. #include <algorithm>
  7361. #include <iomanip>
  7362. namespace Catch {
  7363. std::size_t listTests( Config const& config ) {
  7364. TestSpec testSpec = config.testSpec();
  7365. if( config.hasTestFilters() )
  7366. Catch::cout() << "Matching test cases:\n";
  7367. else {
  7368. Catch::cout() << "All available test cases:\n";
  7369. }
  7370. auto matchedTestCases = filterTests( getAllTestCasesSorted( config ), testSpec, config );
  7371. for( auto const& testCaseInfo : matchedTestCases ) {
  7372. Colour::Code colour = testCaseInfo.isHidden()
  7373. ? Colour::SecondaryText
  7374. : Colour::None;
  7375. Colour colourGuard( colour );
  7376. Catch::cout() << Column( testCaseInfo.name ).initialIndent( 2 ).indent( 4 ) << "\n";
  7377. if( config.verbosity() >= Verbosity::High ) {
  7378. Catch::cout() << Column( Catch::Detail::stringify( testCaseInfo.lineInfo ) ).indent(4) << std::endl;
  7379. std::string description = testCaseInfo.description;
  7380. if( description.empty() )
  7381. description = "(NO DESCRIPTION)";
  7382. Catch::cout() << Column( description ).indent(4) << std::endl;
  7383. }
  7384. if( !testCaseInfo.tags.empty() )
  7385. Catch::cout() << Column( testCaseInfo.tagsAsString() ).indent( 6 ) << "\n";
  7386. }
  7387. if( !config.hasTestFilters() )
  7388. Catch::cout() << pluralise( matchedTestCases.size(), "test case" ) << '\n' << std::endl;
  7389. else
  7390. Catch::cout() << pluralise( matchedTestCases.size(), "matching test case" ) << '\n' << std::endl;
  7391. return matchedTestCases.size();
  7392. }
  7393. std::size_t listTestsNamesOnly( Config const& config ) {
  7394. TestSpec testSpec = config.testSpec();
  7395. std::size_t matchedTests = 0;
  7396. std::vector<TestCase> matchedTestCases = filterTests( getAllTestCasesSorted( config ), testSpec, config );
  7397. for( auto const& testCaseInfo : matchedTestCases ) {
  7398. matchedTests++;
  7399. if( startsWith( testCaseInfo.name, '#' ) )
  7400. Catch::cout() << '"' << testCaseInfo.name << '"';
  7401. else
  7402. Catch::cout() << testCaseInfo.name;
  7403. if ( config.verbosity() >= Verbosity::High )
  7404. Catch::cout() << "\t@" << testCaseInfo.lineInfo;
  7405. Catch::cout() << std::endl;
  7406. }
  7407. return matchedTests;
  7408. }
  7409. void TagInfo::add( std::string const& spelling ) {
  7410. ++count;
  7411. spellings.insert( spelling );
  7412. }
  7413. std::string TagInfo::all() const {
  7414. std::string out;
  7415. for( auto const& spelling : spellings )
  7416. out += "[" + spelling + "]";
  7417. return out;
  7418. }
  7419. std::size_t listTags( Config const& config ) {
  7420. TestSpec testSpec = config.testSpec();
  7421. if( config.hasTestFilters() )
  7422. Catch::cout() << "Tags for matching test cases:\n";
  7423. else {
  7424. Catch::cout() << "All available tags:\n";
  7425. }
  7426. std::map<std::string, TagInfo> tagCounts;
  7427. std::vector<TestCase> matchedTestCases = filterTests( getAllTestCasesSorted( config ), testSpec, config );
  7428. for( auto const& testCase : matchedTestCases ) {
  7429. for( auto const& tagName : testCase.getTestCaseInfo().tags ) {
  7430. std::string lcaseTagName = toLower( tagName );
  7431. auto countIt = tagCounts.find( lcaseTagName );
  7432. if( countIt == tagCounts.end() )
  7433. countIt = tagCounts.insert( std::make_pair( lcaseTagName, TagInfo() ) ).first;
  7434. countIt->second.add( tagName );
  7435. }
  7436. }
  7437. for( auto const& tagCount : tagCounts ) {
  7438. ReusableStringStream rss;
  7439. rss << " " << std::setw(2) << tagCount.second.count << " ";
  7440. auto str = rss.str();
  7441. auto wrapper = Column( tagCount.second.all() )
  7442. .initialIndent( 0 )
  7443. .indent( str.size() )
  7444. .width( CATCH_CONFIG_CONSOLE_WIDTH-10 );
  7445. Catch::cout() << str << wrapper << '\n';
  7446. }
  7447. Catch::cout() << pluralise( tagCounts.size(), "tag" ) << '\n' << std::endl;
  7448. return tagCounts.size();
  7449. }
  7450. std::size_t listReporters() {
  7451. Catch::cout() << "Available reporters:\n";
  7452. IReporterRegistry::FactoryMap const& factories = getRegistryHub().getReporterRegistry().getFactories();
  7453. std::size_t maxNameLen = 0;
  7454. for( auto const& factoryKvp : factories )
  7455. maxNameLen = (std::max)( maxNameLen, factoryKvp.first.size() );
  7456. for( auto const& factoryKvp : factories ) {
  7457. Catch::cout()
  7458. << Column( factoryKvp.first + ":" )
  7459. .indent(2)
  7460. .width( 5+maxNameLen )
  7461. + Column( factoryKvp.second->getDescription() )
  7462. .initialIndent(0)
  7463. .indent(2)
  7464. .width( CATCH_CONFIG_CONSOLE_WIDTH - maxNameLen-8 )
  7465. << "\n";
  7466. }
  7467. Catch::cout() << std::endl;
  7468. return factories.size();
  7469. }
  7470. Option<std::size_t> list( std::shared_ptr<Config> const& config ) {
  7471. Option<std::size_t> listedCount;
  7472. getCurrentMutableContext().setConfig( config );
  7473. if( config->listTests() )
  7474. listedCount = listedCount.valueOr(0) + listTests( *config );
  7475. if( config->listTestNamesOnly() )
  7476. listedCount = listedCount.valueOr(0) + listTestsNamesOnly( *config );
  7477. if( config->listTags() )
  7478. listedCount = listedCount.valueOr(0) + listTags( *config );
  7479. if( config->listReporters() )
  7480. listedCount = listedCount.valueOr(0) + listReporters();
  7481. return listedCount;
  7482. }
  7483. } // end namespace Catch
  7484. // end catch_list.cpp
  7485. // start catch_matchers.cpp
  7486. namespace Catch {
  7487. namespace Matchers {
  7488. namespace Impl {
  7489. std::string MatcherUntypedBase::toString() const {
  7490. if( m_cachedToString.empty() )
  7491. m_cachedToString = describe();
  7492. return m_cachedToString;
  7493. }
  7494. MatcherUntypedBase::~MatcherUntypedBase() = default;
  7495. } // namespace Impl
  7496. } // namespace Matchers
  7497. using namespace Matchers;
  7498. using Matchers::Impl::MatcherBase;
  7499. } // namespace Catch
  7500. // end catch_matchers.cpp
  7501. // start catch_matchers_floating.cpp
  7502. // start catch_polyfills.hpp
  7503. namespace Catch {
  7504. bool isnan(float f);
  7505. bool isnan(double d);
  7506. }
  7507. // end catch_polyfills.hpp
  7508. // start catch_to_string.hpp
  7509. #include <string>
  7510. namespace Catch {
  7511. template <typename T>
  7512. std::string to_string(T const& t) {
  7513. #if defined(CATCH_CONFIG_CPP11_TO_STRING)
  7514. return std::to_string(t);
  7515. #else
  7516. ReusableStringStream rss;
  7517. rss << t;
  7518. return rss.str();
  7519. #endif
  7520. }
  7521. } // end namespace Catch
  7522. // end catch_to_string.hpp
  7523. #include <cstdlib>
  7524. #include <cstdint>
  7525. #include <cstring>
  7526. namespace Catch {
  7527. namespace Matchers {
  7528. namespace Floating {
  7529. enum class FloatingPointKind : uint8_t {
  7530. Float,
  7531. Double
  7532. };
  7533. }
  7534. }
  7535. }
  7536. namespace {
  7537. template <typename T>
  7538. struct Converter;
  7539. template <>
  7540. struct Converter<float> {
  7541. static_assert(sizeof(float) == sizeof(int32_t), "Important ULP matcher assumption violated");
  7542. Converter(float f) {
  7543. std::memcpy(&i, &f, sizeof(f));
  7544. }
  7545. int32_t i;
  7546. };
  7547. template <>
  7548. struct Converter<double> {
  7549. static_assert(sizeof(double) == sizeof(int64_t), "Important ULP matcher assumption violated");
  7550. Converter(double d) {
  7551. std::memcpy(&i, &d, sizeof(d));
  7552. }
  7553. int64_t i;
  7554. };
  7555. template <typename T>
  7556. auto convert(T t) -> Converter<T> {
  7557. return Converter<T>(t);
  7558. }
  7559. template <typename FP>
  7560. bool almostEqualUlps(FP lhs, FP rhs, int maxUlpDiff) {
  7561. // Comparison with NaN should always be false.
  7562. // This way we can rule it out before getting into the ugly details
  7563. if (Catch::isnan(lhs) || Catch::isnan(rhs)) {
  7564. return false;
  7565. }
  7566. auto lc = convert(lhs);
  7567. auto rc = convert(rhs);
  7568. if ((lc.i < 0) != (rc.i < 0)) {
  7569. // Potentially we can have +0 and -0
  7570. return lhs == rhs;
  7571. }
  7572. auto ulpDiff = std::abs(lc.i - rc.i);
  7573. return ulpDiff <= maxUlpDiff;
  7574. }
  7575. }
  7576. namespace Catch {
  7577. namespace Matchers {
  7578. namespace Floating {
  7579. WithinAbsMatcher::WithinAbsMatcher(double target, double margin)
  7580. :m_target{ target }, m_margin{ margin } {
  7581. CATCH_ENFORCE(margin >= 0, "Invalid margin: " << margin << '.'
  7582. << " Margin has to be non-negative.");
  7583. }
  7584. // Performs equivalent check of std::fabs(lhs - rhs) <= margin
  7585. // But without the subtraction to allow for INFINITY in comparison
  7586. bool WithinAbsMatcher::match(double const& matchee) const {
  7587. return (matchee + m_margin >= m_target) && (m_target + m_margin >= matchee);
  7588. }
  7589. std::string WithinAbsMatcher::describe() const {
  7590. return "is within " + ::Catch::Detail::stringify(m_margin) + " of " + ::Catch::Detail::stringify(m_target);
  7591. }
  7592. WithinUlpsMatcher::WithinUlpsMatcher(double target, int ulps, FloatingPointKind baseType)
  7593. :m_target{ target }, m_ulps{ ulps }, m_type{ baseType } {
  7594. CATCH_ENFORCE(ulps >= 0, "Invalid ULP setting: " << ulps << '.'
  7595. << " ULPs have to be non-negative.");
  7596. }
  7597. #if defined(__clang__)
  7598. #pragma clang diagnostic push
  7599. // Clang <3.5 reports on the default branch in the switch below
  7600. #pragma clang diagnostic ignored "-Wunreachable-code"
  7601. #endif
  7602. bool WithinUlpsMatcher::match(double const& matchee) const {
  7603. switch (m_type) {
  7604. case FloatingPointKind::Float:
  7605. return almostEqualUlps<float>(static_cast<float>(matchee), static_cast<float>(m_target), m_ulps);
  7606. case FloatingPointKind::Double:
  7607. return almostEqualUlps<double>(matchee, m_target, m_ulps);
  7608. default:
  7609. CATCH_INTERNAL_ERROR( "Unknown FloatingPointKind value" );
  7610. }
  7611. }
  7612. #if defined(__clang__)
  7613. #pragma clang diagnostic pop
  7614. #endif
  7615. std::string WithinUlpsMatcher::describe() const {
  7616. return "is within " + Catch::to_string(m_ulps) + " ULPs of " + ::Catch::Detail::stringify(m_target) + ((m_type == FloatingPointKind::Float)? "f" : "");
  7617. }
  7618. }// namespace Floating
  7619. Floating::WithinUlpsMatcher WithinULP(double target, int maxUlpDiff) {
  7620. return Floating::WithinUlpsMatcher(target, maxUlpDiff, Floating::FloatingPointKind::Double);
  7621. }
  7622. Floating::WithinUlpsMatcher WithinULP(float target, int maxUlpDiff) {
  7623. return Floating::WithinUlpsMatcher(target, maxUlpDiff, Floating::FloatingPointKind::Float);
  7624. }
  7625. Floating::WithinAbsMatcher WithinAbs(double target, double margin) {
  7626. return Floating::WithinAbsMatcher(target, margin);
  7627. }
  7628. } // namespace Matchers
  7629. } // namespace Catch
  7630. // end catch_matchers_floating.cpp
  7631. // start catch_matchers_generic.cpp
  7632. std::string Catch::Matchers::Generic::Detail::finalizeDescription(const std::string& desc) {
  7633. if (desc.empty()) {
  7634. return "matches undescribed predicate";
  7635. } else {
  7636. return "matches predicate: \"" + desc + '"';
  7637. }
  7638. }
  7639. // end catch_matchers_generic.cpp
  7640. // start catch_matchers_string.cpp
  7641. #include <regex>
  7642. namespace Catch {
  7643. namespace Matchers {
  7644. namespace StdString {
  7645. CasedString::CasedString( std::string const& str, CaseSensitive::Choice caseSensitivity )
  7646. : m_caseSensitivity( caseSensitivity ),
  7647. m_str( adjustString( str ) )
  7648. {}
  7649. std::string CasedString::adjustString( std::string const& str ) const {
  7650. return m_caseSensitivity == CaseSensitive::No
  7651. ? toLower( str )
  7652. : str;
  7653. }
  7654. std::string CasedString::caseSensitivitySuffix() const {
  7655. return m_caseSensitivity == CaseSensitive::No
  7656. ? " (case insensitive)"
  7657. : std::string();
  7658. }
  7659. StringMatcherBase::StringMatcherBase( std::string const& operation, CasedString const& comparator )
  7660. : m_comparator( comparator ),
  7661. m_operation( operation ) {
  7662. }
  7663. std::string StringMatcherBase::describe() const {
  7664. std::string description;
  7665. description.reserve(5 + m_operation.size() + m_comparator.m_str.size() +
  7666. m_comparator.caseSensitivitySuffix().size());
  7667. description += m_operation;
  7668. description += ": \"";
  7669. description += m_comparator.m_str;
  7670. description += "\"";
  7671. description += m_comparator.caseSensitivitySuffix();
  7672. return description;
  7673. }
  7674. EqualsMatcher::EqualsMatcher( CasedString const& comparator ) : StringMatcherBase( "equals", comparator ) {}
  7675. bool EqualsMatcher::match( std::string const& source ) const {
  7676. return m_comparator.adjustString( source ) == m_comparator.m_str;
  7677. }
  7678. ContainsMatcher::ContainsMatcher( CasedString const& comparator ) : StringMatcherBase( "contains", comparator ) {}
  7679. bool ContainsMatcher::match( std::string const& source ) const {
  7680. return contains( m_comparator.adjustString( source ), m_comparator.m_str );
  7681. }
  7682. StartsWithMatcher::StartsWithMatcher( CasedString const& comparator ) : StringMatcherBase( "starts with", comparator ) {}
  7683. bool StartsWithMatcher::match( std::string const& source ) const {
  7684. return startsWith( m_comparator.adjustString( source ), m_comparator.m_str );
  7685. }
  7686. EndsWithMatcher::EndsWithMatcher( CasedString const& comparator ) : StringMatcherBase( "ends with", comparator ) {}
  7687. bool EndsWithMatcher::match( std::string const& source ) const {
  7688. return endsWith( m_comparator.adjustString( source ), m_comparator.m_str );
  7689. }
  7690. RegexMatcher::RegexMatcher(std::string regex, CaseSensitive::Choice caseSensitivity): m_regex(std::move(regex)), m_caseSensitivity(caseSensitivity) {}
  7691. bool RegexMatcher::match(std::string const& matchee) const {
  7692. auto flags = std::regex::ECMAScript; // ECMAScript is the default syntax option anyway
  7693. if (m_caseSensitivity == CaseSensitive::Choice::No) {
  7694. flags |= std::regex::icase;
  7695. }
  7696. auto reg = std::regex(m_regex, flags);
  7697. return std::regex_match(matchee, reg);
  7698. }
  7699. std::string RegexMatcher::describe() const {
  7700. return "matches " + ::Catch::Detail::stringify(m_regex) + ((m_caseSensitivity == CaseSensitive::Choice::Yes)? " case sensitively" : " case insensitively");
  7701. }
  7702. } // namespace StdString
  7703. StdString::EqualsMatcher Equals( std::string const& str, CaseSensitive::Choice caseSensitivity ) {
  7704. return StdString::EqualsMatcher( StdString::CasedString( str, caseSensitivity) );
  7705. }
  7706. StdString::ContainsMatcher Contains( std::string const& str, CaseSensitive::Choice caseSensitivity ) {
  7707. return StdString::ContainsMatcher( StdString::CasedString( str, caseSensitivity) );
  7708. }
  7709. StdString::EndsWithMatcher EndsWith( std::string const& str, CaseSensitive::Choice caseSensitivity ) {
  7710. return StdString::EndsWithMatcher( StdString::CasedString( str, caseSensitivity) );
  7711. }
  7712. StdString::StartsWithMatcher StartsWith( std::string const& str, CaseSensitive::Choice caseSensitivity ) {
  7713. return StdString::StartsWithMatcher( StdString::CasedString( str, caseSensitivity) );
  7714. }
  7715. StdString::RegexMatcher Matches(std::string const& regex, CaseSensitive::Choice caseSensitivity) {
  7716. return StdString::RegexMatcher(regex, caseSensitivity);
  7717. }
  7718. } // namespace Matchers
  7719. } // namespace Catch
  7720. // end catch_matchers_string.cpp
  7721. // start catch_message.cpp
  7722. // start catch_uncaught_exceptions.h
  7723. namespace Catch {
  7724. bool uncaught_exceptions();
  7725. } // end namespace Catch
  7726. // end catch_uncaught_exceptions.h
  7727. #include <cassert>
  7728. #include <stack>
  7729. namespace Catch {
  7730. MessageInfo::MessageInfo( StringRef const& _macroName,
  7731. SourceLineInfo const& _lineInfo,
  7732. ResultWas::OfType _type )
  7733. : macroName( _macroName ),
  7734. lineInfo( _lineInfo ),
  7735. type( _type ),
  7736. sequence( ++globalCount )
  7737. {}
  7738. bool MessageInfo::operator==( MessageInfo const& other ) const {
  7739. return sequence == other.sequence;
  7740. }
  7741. bool MessageInfo::operator<( MessageInfo const& other ) const {
  7742. return sequence < other.sequence;
  7743. }
  7744. // This may need protecting if threading support is added
  7745. unsigned int MessageInfo::globalCount = 0;
  7746. ////////////////////////////////////////////////////////////////////////////
  7747. Catch::MessageBuilder::MessageBuilder( StringRef const& macroName,
  7748. SourceLineInfo const& lineInfo,
  7749. ResultWas::OfType type )
  7750. :m_info(macroName, lineInfo, type) {}
  7751. ////////////////////////////////////////////////////////////////////////////
  7752. ScopedMessage::ScopedMessage( MessageBuilder const& builder )
  7753. : m_info( builder.m_info ), m_moved()
  7754. {
  7755. m_info.message = builder.m_stream.str();
  7756. getResultCapture().pushScopedMessage( m_info );
  7757. }
  7758. ScopedMessage::ScopedMessage( ScopedMessage&& old )
  7759. : m_info( old.m_info ), m_moved()
  7760. {
  7761. old.m_moved = true;
  7762. }
  7763. ScopedMessage::~ScopedMessage() {
  7764. if ( !uncaught_exceptions() && !m_moved ){
  7765. getResultCapture().popScopedMessage(m_info);
  7766. }
  7767. }
  7768. Capturer::Capturer( StringRef macroName, SourceLineInfo const& lineInfo, ResultWas::OfType resultType, StringRef names ) {
  7769. auto trimmed = [&] (size_t start, size_t end) {
  7770. while (names[start] == ',' || isspace(names[start])) {
  7771. ++start;
  7772. }
  7773. while (names[end] == ',' || isspace(names[end])) {
  7774. --end;
  7775. }
  7776. return names.substr(start, end - start + 1);
  7777. };
  7778. size_t start = 0;
  7779. std::stack<char> openings;
  7780. for (size_t pos = 0; pos < names.size(); ++pos) {
  7781. char c = names[pos];
  7782. switch (c) {
  7783. case '[':
  7784. case '{':
  7785. case '(':
  7786. // It is basically impossible to disambiguate between
  7787. // comparison and start of template args in this context
  7788. // case '<':
  7789. openings.push(c);
  7790. break;
  7791. case ']':
  7792. case '}':
  7793. case ')':
  7794. // case '>':
  7795. openings.pop();
  7796. break;
  7797. case ',':
  7798. if (start != pos && openings.size() == 0) {
  7799. m_messages.emplace_back(macroName, lineInfo, resultType);
  7800. m_messages.back().message = trimmed(start, pos);
  7801. m_messages.back().message += " := ";
  7802. start = pos;
  7803. }
  7804. }
  7805. }
  7806. assert(openings.size() == 0 && "Mismatched openings");
  7807. m_messages.emplace_back(macroName, lineInfo, resultType);
  7808. m_messages.back().message = trimmed(start, names.size() - 1);
  7809. m_messages.back().message += " := ";
  7810. }
  7811. Capturer::~Capturer() {
  7812. if ( !uncaught_exceptions() ){
  7813. assert( m_captured == m_messages.size() );
  7814. for( size_t i = 0; i < m_captured; ++i )
  7815. m_resultCapture.popScopedMessage( m_messages[i] );
  7816. }
  7817. }
  7818. void Capturer::captureValue( size_t index, std::string const& value ) {
  7819. assert( index < m_messages.size() );
  7820. m_messages[index].message += value;
  7821. m_resultCapture.pushScopedMessage( m_messages[index] );
  7822. m_captured++;
  7823. }
  7824. } // end namespace Catch
  7825. // end catch_message.cpp
  7826. // start catch_output_redirect.cpp
  7827. // start catch_output_redirect.h
  7828. #ifndef TWOBLUECUBES_CATCH_OUTPUT_REDIRECT_H
  7829. #define TWOBLUECUBES_CATCH_OUTPUT_REDIRECT_H
  7830. #include <cstdio>
  7831. #include <iosfwd>
  7832. #include <string>
  7833. namespace Catch {
  7834. class RedirectedStream {
  7835. std::ostream& m_originalStream;
  7836. std::ostream& m_redirectionStream;
  7837. std::streambuf* m_prevBuf;
  7838. public:
  7839. RedirectedStream( std::ostream& originalStream, std::ostream& redirectionStream );
  7840. ~RedirectedStream();
  7841. };
  7842. class RedirectedStdOut {
  7843. ReusableStringStream m_rss;
  7844. RedirectedStream m_cout;
  7845. public:
  7846. RedirectedStdOut();
  7847. auto str() const -> std::string;
  7848. };
  7849. // StdErr has two constituent streams in C++, std::cerr and std::clog
  7850. // This means that we need to redirect 2 streams into 1 to keep proper
  7851. // order of writes
  7852. class RedirectedStdErr {
  7853. ReusableStringStream m_rss;
  7854. RedirectedStream m_cerr;
  7855. RedirectedStream m_clog;
  7856. public:
  7857. RedirectedStdErr();
  7858. auto str() const -> std::string;
  7859. };
  7860. class RedirectedStreams {
  7861. public:
  7862. RedirectedStreams(RedirectedStreams const&) = delete;
  7863. RedirectedStreams& operator=(RedirectedStreams const&) = delete;
  7864. RedirectedStreams(RedirectedStreams&&) = delete;
  7865. RedirectedStreams& operator=(RedirectedStreams&&) = delete;
  7866. RedirectedStreams(std::string& redirectedCout, std::string& redirectedCerr);
  7867. ~RedirectedStreams();
  7868. private:
  7869. std::string& m_redirectedCout;
  7870. std::string& m_redirectedCerr;
  7871. RedirectedStdOut m_redirectedStdOut;
  7872. RedirectedStdErr m_redirectedStdErr;
  7873. };
  7874. #if defined(CATCH_CONFIG_NEW_CAPTURE)
  7875. // Windows's implementation of std::tmpfile is terrible (it tries
  7876. // to create a file inside system folder, thus requiring elevated
  7877. // privileges for the binary), so we have to use tmpnam(_s) and
  7878. // create the file ourselves there.
  7879. class TempFile {
  7880. public:
  7881. TempFile(TempFile const&) = delete;
  7882. TempFile& operator=(TempFile const&) = delete;
  7883. TempFile(TempFile&&) = delete;
  7884. TempFile& operator=(TempFile&&) = delete;
  7885. TempFile();
  7886. ~TempFile();
  7887. std::FILE* getFile();
  7888. std::string getContents();
  7889. private:
  7890. std::FILE* m_file = nullptr;
  7891. #if defined(_MSC_VER)
  7892. char m_buffer[L_tmpnam] = { 0 };
  7893. #endif
  7894. };
  7895. class OutputRedirect {
  7896. public:
  7897. OutputRedirect(OutputRedirect const&) = delete;
  7898. OutputRedirect& operator=(OutputRedirect const&) = delete;
  7899. OutputRedirect(OutputRedirect&&) = delete;
  7900. OutputRedirect& operator=(OutputRedirect&&) = delete;
  7901. OutputRedirect(std::string& stdout_dest, std::string& stderr_dest);
  7902. ~OutputRedirect();
  7903. private:
  7904. int m_originalStdout = -1;
  7905. int m_originalStderr = -1;
  7906. TempFile m_stdoutFile;
  7907. TempFile m_stderrFile;
  7908. std::string& m_stdoutDest;
  7909. std::string& m_stderrDest;
  7910. };
  7911. #endif
  7912. } // end namespace Catch
  7913. #endif // TWOBLUECUBES_CATCH_OUTPUT_REDIRECT_H
  7914. // end catch_output_redirect.h
  7915. #include <cstdio>
  7916. #include <cstring>
  7917. #include <fstream>
  7918. #include <sstream>
  7919. #include <stdexcept>
  7920. #if defined(CATCH_CONFIG_NEW_CAPTURE)
  7921. #if defined(_MSC_VER)
  7922. #include <io.h> //_dup and _dup2
  7923. #define dup _dup
  7924. #define dup2 _dup2
  7925. #define fileno _fileno
  7926. #else
  7927. #include <unistd.h> // dup and dup2
  7928. #endif
  7929. #endif
  7930. namespace Catch {
  7931. RedirectedStream::RedirectedStream( std::ostream& originalStream, std::ostream& redirectionStream )
  7932. : m_originalStream( originalStream ),
  7933. m_redirectionStream( redirectionStream ),
  7934. m_prevBuf( m_originalStream.rdbuf() )
  7935. {
  7936. m_originalStream.rdbuf( m_redirectionStream.rdbuf() );
  7937. }
  7938. RedirectedStream::~RedirectedStream() {
  7939. m_originalStream.rdbuf( m_prevBuf );
  7940. }
  7941. RedirectedStdOut::RedirectedStdOut() : m_cout( Catch::cout(), m_rss.get() ) {}
  7942. auto RedirectedStdOut::str() const -> std::string { return m_rss.str(); }
  7943. RedirectedStdErr::RedirectedStdErr()
  7944. : m_cerr( Catch::cerr(), m_rss.get() ),
  7945. m_clog( Catch::clog(), m_rss.get() )
  7946. {}
  7947. auto RedirectedStdErr::str() const -> std::string { return m_rss.str(); }
  7948. RedirectedStreams::RedirectedStreams(std::string& redirectedCout, std::string& redirectedCerr)
  7949. : m_redirectedCout(redirectedCout),
  7950. m_redirectedCerr(redirectedCerr)
  7951. {}
  7952. RedirectedStreams::~RedirectedStreams() {
  7953. m_redirectedCout += m_redirectedStdOut.str();
  7954. m_redirectedCerr += m_redirectedStdErr.str();
  7955. }
  7956. #if defined(CATCH_CONFIG_NEW_CAPTURE)
  7957. #if defined(_MSC_VER)
  7958. TempFile::TempFile() {
  7959. if (tmpnam_s(m_buffer)) {
  7960. CATCH_RUNTIME_ERROR("Could not get a temp filename");
  7961. }
  7962. if (fopen_s(&m_file, m_buffer, "w")) {
  7963. char buffer[100];
  7964. if (strerror_s(buffer, errno)) {
  7965. CATCH_RUNTIME_ERROR("Could not translate errno to a string");
  7966. }
  7967. CATCH_RUNTIME_ERROR("Coul dnot open the temp file: '" << m_buffer << "' because: " << buffer);
  7968. }
  7969. }
  7970. #else
  7971. TempFile::TempFile() {
  7972. m_file = std::tmpfile();
  7973. if (!m_file) {
  7974. CATCH_RUNTIME_ERROR("Could not create a temp file.");
  7975. }
  7976. }
  7977. #endif
  7978. TempFile::~TempFile() {
  7979. // TBD: What to do about errors here?
  7980. std::fclose(m_file);
  7981. // We manually create the file on Windows only, on Linux
  7982. // it will be autodeleted
  7983. #if defined(_MSC_VER)
  7984. std::remove(m_buffer);
  7985. #endif
  7986. }
  7987. FILE* TempFile::getFile() {
  7988. return m_file;
  7989. }
  7990. std::string TempFile::getContents() {
  7991. std::stringstream sstr;
  7992. char buffer[100] = {};
  7993. std::rewind(m_file);
  7994. while (std::fgets(buffer, sizeof(buffer), m_file)) {
  7995. sstr << buffer;
  7996. }
  7997. return sstr.str();
  7998. }
  7999. OutputRedirect::OutputRedirect(std::string& stdout_dest, std::string& stderr_dest) :
  8000. m_originalStdout(dup(1)),
  8001. m_originalStderr(dup(2)),
  8002. m_stdoutDest(stdout_dest),
  8003. m_stderrDest(stderr_dest) {
  8004. dup2(fileno(m_stdoutFile.getFile()), 1);
  8005. dup2(fileno(m_stderrFile.getFile()), 2);
  8006. }
  8007. OutputRedirect::~OutputRedirect() {
  8008. Catch::cout() << std::flush;
  8009. fflush(stdout);
  8010. // Since we support overriding these streams, we flush cerr
  8011. // even though std::cerr is unbuffered
  8012. Catch::cerr() << std::flush;
  8013. Catch::clog() << std::flush;
  8014. fflush(stderr);
  8015. dup2(m_originalStdout, 1);
  8016. dup2(m_originalStderr, 2);
  8017. m_stdoutDest += m_stdoutFile.getContents();
  8018. m_stderrDest += m_stderrFile.getContents();
  8019. }
  8020. #endif // CATCH_CONFIG_NEW_CAPTURE
  8021. } // namespace Catch
  8022. #if defined(CATCH_CONFIG_NEW_CAPTURE)
  8023. #if defined(_MSC_VER)
  8024. #undef dup
  8025. #undef dup2
  8026. #undef fileno
  8027. #endif
  8028. #endif
  8029. // end catch_output_redirect.cpp
  8030. // start catch_polyfills.cpp
  8031. #include <cmath>
  8032. namespace Catch {
  8033. #if !defined(CATCH_CONFIG_POLYFILL_ISNAN)
  8034. bool isnan(float f) {
  8035. return std::isnan(f);
  8036. }
  8037. bool isnan(double d) {
  8038. return std::isnan(d);
  8039. }
  8040. #else
  8041. // For now we only use this for embarcadero
  8042. bool isnan(float f) {
  8043. return std::_isnan(f);
  8044. }
  8045. bool isnan(double d) {
  8046. return std::_isnan(d);
  8047. }
  8048. #endif
  8049. } // end namespace Catch
  8050. // end catch_polyfills.cpp
  8051. // start catch_random_number_generator.cpp
  8052. namespace Catch {
  8053. std::mt19937& rng() {
  8054. static std::mt19937 s_rng;
  8055. return s_rng;
  8056. }
  8057. void seedRng( IConfig const& config ) {
  8058. if( config.rngSeed() != 0 ) {
  8059. std::srand( config.rngSeed() );
  8060. rng().seed( config.rngSeed() );
  8061. }
  8062. }
  8063. unsigned int rngSeed() {
  8064. return getCurrentContext().getConfig()->rngSeed();
  8065. }
  8066. }
  8067. // end catch_random_number_generator.cpp
  8068. // start catch_registry_hub.cpp
  8069. // start catch_test_case_registry_impl.h
  8070. #include <vector>
  8071. #include <set>
  8072. #include <algorithm>
  8073. #include <ios>
  8074. namespace Catch {
  8075. class TestCase;
  8076. struct IConfig;
  8077. std::vector<TestCase> sortTests( IConfig const& config, std::vector<TestCase> const& unsortedTestCases );
  8078. bool matchTest( TestCase const& testCase, TestSpec const& testSpec, IConfig const& config );
  8079. void enforceNoDuplicateTestCases( std::vector<TestCase> const& functions );
  8080. std::vector<TestCase> filterTests( std::vector<TestCase> const& testCases, TestSpec const& testSpec, IConfig const& config );
  8081. std::vector<TestCase> const& getAllTestCasesSorted( IConfig const& config );
  8082. class TestRegistry : public ITestCaseRegistry {
  8083. public:
  8084. virtual ~TestRegistry() = default;
  8085. virtual void registerTest( TestCase const& testCase );
  8086. std::vector<TestCase> const& getAllTests() const override;
  8087. std::vector<TestCase> const& getAllTestsSorted( IConfig const& config ) const override;
  8088. private:
  8089. std::vector<TestCase> m_functions;
  8090. mutable RunTests::InWhatOrder m_currentSortOrder = RunTests::InDeclarationOrder;
  8091. mutable std::vector<TestCase> m_sortedFunctions;
  8092. std::size_t m_unnamedCount = 0;
  8093. std::ios_base::Init m_ostreamInit; // Forces cout/ cerr to be initialised
  8094. };
  8095. ///////////////////////////////////////////////////////////////////////////
  8096. class TestInvokerAsFunction : public ITestInvoker {
  8097. void(*m_testAsFunction)();
  8098. public:
  8099. TestInvokerAsFunction( void(*testAsFunction)() ) noexcept;
  8100. void invoke() const override;
  8101. };
  8102. std::string extractClassName( StringRef const& classOrQualifiedMethodName );
  8103. ///////////////////////////////////////////////////////////////////////////
  8104. } // end namespace Catch
  8105. // end catch_test_case_registry_impl.h
  8106. // start catch_reporter_registry.h
  8107. #include <map>
  8108. namespace Catch {
  8109. class ReporterRegistry : public IReporterRegistry {
  8110. public:
  8111. ~ReporterRegistry() override;
  8112. IStreamingReporterPtr create( std::string const& name, IConfigPtr const& config ) const override;
  8113. void registerReporter( std::string const& name, IReporterFactoryPtr const& factory );
  8114. void registerListener( IReporterFactoryPtr const& factory );
  8115. FactoryMap const& getFactories() const override;
  8116. Listeners const& getListeners() const override;
  8117. private:
  8118. FactoryMap m_factories;
  8119. Listeners m_listeners;
  8120. };
  8121. }
  8122. // end catch_reporter_registry.h
  8123. // start catch_tag_alias_registry.h
  8124. // start catch_tag_alias.h
  8125. #include <string>
  8126. namespace Catch {
  8127. struct TagAlias {
  8128. TagAlias(std::string const& _tag, SourceLineInfo _lineInfo);
  8129. std::string tag;
  8130. SourceLineInfo lineInfo;
  8131. };
  8132. } // end namespace Catch
  8133. // end catch_tag_alias.h
  8134. #include <map>
  8135. namespace Catch {
  8136. class TagAliasRegistry : public ITagAliasRegistry {
  8137. public:
  8138. ~TagAliasRegistry() override;
  8139. TagAlias const* find( std::string const& alias ) const override;
  8140. std::string expandAliases( std::string const& unexpandedTestSpec ) const override;
  8141. void add( std::string const& alias, std::string const& tag, SourceLineInfo const& lineInfo );
  8142. private:
  8143. std::map<std::string, TagAlias> m_registry;
  8144. };
  8145. } // end namespace Catch
  8146. // end catch_tag_alias_registry.h
  8147. // start catch_startup_exception_registry.h
  8148. #include <vector>
  8149. #include <exception>
  8150. namespace Catch {
  8151. class StartupExceptionRegistry {
  8152. public:
  8153. void add(std::exception_ptr const& exception) noexcept;
  8154. std::vector<std::exception_ptr> const& getExceptions() const noexcept;
  8155. private:
  8156. std::vector<std::exception_ptr> m_exceptions;
  8157. };
  8158. } // end namespace Catch
  8159. // end catch_startup_exception_registry.h
  8160. // start catch_singletons.hpp
  8161. namespace Catch {
  8162. struct ISingleton {
  8163. virtual ~ISingleton();
  8164. };
  8165. void addSingleton( ISingleton* singleton );
  8166. void cleanupSingletons();
  8167. template<typename SingletonImplT, typename InterfaceT = SingletonImplT, typename MutableInterfaceT = InterfaceT>
  8168. class Singleton : SingletonImplT, public ISingleton {
  8169. static auto getInternal() -> Singleton* {
  8170. static Singleton* s_instance = nullptr;
  8171. if( !s_instance ) {
  8172. s_instance = new Singleton;
  8173. addSingleton( s_instance );
  8174. }
  8175. return s_instance;
  8176. }
  8177. public:
  8178. static auto get() -> InterfaceT const& {
  8179. return *getInternal();
  8180. }
  8181. static auto getMutable() -> MutableInterfaceT& {
  8182. return *getInternal();
  8183. }
  8184. };
  8185. } // namespace Catch
  8186. // end catch_singletons.hpp
  8187. namespace Catch {
  8188. namespace {
  8189. class RegistryHub : public IRegistryHub, public IMutableRegistryHub,
  8190. private NonCopyable {
  8191. public: // IRegistryHub
  8192. RegistryHub() = default;
  8193. IReporterRegistry const& getReporterRegistry() const override {
  8194. return m_reporterRegistry;
  8195. }
  8196. ITestCaseRegistry const& getTestCaseRegistry() const override {
  8197. return m_testCaseRegistry;
  8198. }
  8199. IExceptionTranslatorRegistry const& getExceptionTranslatorRegistry() const override {
  8200. return m_exceptionTranslatorRegistry;
  8201. }
  8202. ITagAliasRegistry const& getTagAliasRegistry() const override {
  8203. return m_tagAliasRegistry;
  8204. }
  8205. StartupExceptionRegistry const& getStartupExceptionRegistry() const override {
  8206. return m_exceptionRegistry;
  8207. }
  8208. public: // IMutableRegistryHub
  8209. void registerReporter( std::string const& name, IReporterFactoryPtr const& factory ) override {
  8210. m_reporterRegistry.registerReporter( name, factory );
  8211. }
  8212. void registerListener( IReporterFactoryPtr const& factory ) override {
  8213. m_reporterRegistry.registerListener( factory );
  8214. }
  8215. void registerTest( TestCase const& testInfo ) override {
  8216. m_testCaseRegistry.registerTest( testInfo );
  8217. }
  8218. void registerTranslator( const IExceptionTranslator* translator ) override {
  8219. m_exceptionTranslatorRegistry.registerTranslator( translator );
  8220. }
  8221. void registerTagAlias( std::string const& alias, std::string const& tag, SourceLineInfo const& lineInfo ) override {
  8222. m_tagAliasRegistry.add( alias, tag, lineInfo );
  8223. }
  8224. void registerStartupException() noexcept override {
  8225. m_exceptionRegistry.add(std::current_exception());
  8226. }
  8227. private:
  8228. TestRegistry m_testCaseRegistry;
  8229. ReporterRegistry m_reporterRegistry;
  8230. ExceptionTranslatorRegistry m_exceptionTranslatorRegistry;
  8231. TagAliasRegistry m_tagAliasRegistry;
  8232. StartupExceptionRegistry m_exceptionRegistry;
  8233. };
  8234. }
  8235. using RegistryHubSingleton = Singleton<RegistryHub, IRegistryHub, IMutableRegistryHub>;
  8236. IRegistryHub const& getRegistryHub() {
  8237. return RegistryHubSingleton::get();
  8238. }
  8239. IMutableRegistryHub& getMutableRegistryHub() {
  8240. return RegistryHubSingleton::getMutable();
  8241. }
  8242. void cleanUp() {
  8243. cleanupSingletons();
  8244. cleanUpContext();
  8245. }
  8246. std::string translateActiveException() {
  8247. return getRegistryHub().getExceptionTranslatorRegistry().translateActiveException();
  8248. }
  8249. } // end namespace Catch
  8250. // end catch_registry_hub.cpp
  8251. // start catch_reporter_registry.cpp
  8252. namespace Catch {
  8253. ReporterRegistry::~ReporterRegistry() = default;
  8254. IStreamingReporterPtr ReporterRegistry::create( std::string const& name, IConfigPtr const& config ) const {
  8255. auto it = m_factories.find( name );
  8256. if( it == m_factories.end() )
  8257. return nullptr;
  8258. return it->second->create( ReporterConfig( config ) );
  8259. }
  8260. void ReporterRegistry::registerReporter( std::string const& name, IReporterFactoryPtr const& factory ) {
  8261. m_factories.emplace(name, factory);
  8262. }
  8263. void ReporterRegistry::registerListener( IReporterFactoryPtr const& factory ) {
  8264. m_listeners.push_back( factory );
  8265. }
  8266. IReporterRegistry::FactoryMap const& ReporterRegistry::getFactories() const {
  8267. return m_factories;
  8268. }
  8269. IReporterRegistry::Listeners const& ReporterRegistry::getListeners() const {
  8270. return m_listeners;
  8271. }
  8272. }
  8273. // end catch_reporter_registry.cpp
  8274. // start catch_result_type.cpp
  8275. namespace Catch {
  8276. bool isOk( ResultWas::OfType resultType ) {
  8277. return ( resultType & ResultWas::FailureBit ) == 0;
  8278. }
  8279. bool isJustInfo( int flags ) {
  8280. return flags == ResultWas::Info;
  8281. }
  8282. ResultDisposition::Flags operator | ( ResultDisposition::Flags lhs, ResultDisposition::Flags rhs ) {
  8283. return static_cast<ResultDisposition::Flags>( static_cast<int>( lhs ) | static_cast<int>( rhs ) );
  8284. }
  8285. bool shouldContinueOnFailure( int flags ) { return ( flags & ResultDisposition::ContinueOnFailure ) != 0; }
  8286. bool shouldSuppressFailure( int flags ) { return ( flags & ResultDisposition::SuppressFail ) != 0; }
  8287. } // end namespace Catch
  8288. // end catch_result_type.cpp
  8289. // start catch_run_context.cpp
  8290. #include <cassert>
  8291. #include <algorithm>
  8292. #include <sstream>
  8293. namespace Catch {
  8294. namespace Generators {
  8295. struct GeneratorTracker : TestCaseTracking::TrackerBase, IGeneratorTracker {
  8296. GeneratorBasePtr m_generator;
  8297. GeneratorTracker( TestCaseTracking::NameAndLocation const& nameAndLocation, TrackerContext& ctx, ITracker* parent )
  8298. : TrackerBase( nameAndLocation, ctx, parent )
  8299. {}
  8300. ~GeneratorTracker();
  8301. static GeneratorTracker& acquire( TrackerContext& ctx, TestCaseTracking::NameAndLocation const& nameAndLocation ) {
  8302. std::shared_ptr<GeneratorTracker> tracker;
  8303. ITracker& currentTracker = ctx.currentTracker();
  8304. if( TestCaseTracking::ITrackerPtr childTracker = currentTracker.findChild( nameAndLocation ) ) {
  8305. assert( childTracker );
  8306. assert( childTracker->isGeneratorTracker() );
  8307. tracker = std::static_pointer_cast<GeneratorTracker>( childTracker );
  8308. }
  8309. else {
  8310. tracker = std::make_shared<GeneratorTracker>( nameAndLocation, ctx, &currentTracker );
  8311. currentTracker.addChild( tracker );
  8312. }
  8313. if( !ctx.completedCycle() && !tracker->isComplete() ) {
  8314. tracker->open();
  8315. }
  8316. return *tracker;
  8317. }
  8318. // TrackerBase interface
  8319. bool isGeneratorTracker() const override { return true; }
  8320. auto hasGenerator() const -> bool override {
  8321. return !!m_generator;
  8322. }
  8323. void close() override {
  8324. TrackerBase::close();
  8325. // Generator interface only finds out if it has another item on atual move
  8326. if (m_runState == CompletedSuccessfully && m_generator->next()) {
  8327. m_children.clear();
  8328. m_runState = Executing;
  8329. }
  8330. }
  8331. // IGeneratorTracker interface
  8332. auto getGenerator() const -> GeneratorBasePtr const& override {
  8333. return m_generator;
  8334. }
  8335. void setGenerator( GeneratorBasePtr&& generator ) override {
  8336. m_generator = std::move( generator );
  8337. }
  8338. };
  8339. GeneratorTracker::~GeneratorTracker() {}
  8340. }
  8341. RunContext::RunContext(IConfigPtr const& _config, IStreamingReporterPtr&& reporter)
  8342. : m_runInfo(_config->name()),
  8343. m_context(getCurrentMutableContext()),
  8344. m_config(_config),
  8345. m_reporter(std::move(reporter)),
  8346. m_lastAssertionInfo{ StringRef(), SourceLineInfo("",0), StringRef(), ResultDisposition::Normal },
  8347. m_includeSuccessfulResults( m_config->includeSuccessfulResults() || m_reporter->getPreferences().shouldReportAllAssertions )
  8348. {
  8349. m_context.setRunner(this);
  8350. m_context.setConfig(m_config);
  8351. m_context.setResultCapture(this);
  8352. m_reporter->testRunStarting(m_runInfo);
  8353. }
  8354. RunContext::~RunContext() {
  8355. m_reporter->testRunEnded(TestRunStats(m_runInfo, m_totals, aborting()));
  8356. }
  8357. void RunContext::testGroupStarting(std::string const& testSpec, std::size_t groupIndex, std::size_t groupsCount) {
  8358. m_reporter->testGroupStarting(GroupInfo(testSpec, groupIndex, groupsCount));
  8359. }
  8360. void RunContext::testGroupEnded(std::string const& testSpec, Totals const& totals, std::size_t groupIndex, std::size_t groupsCount) {
  8361. m_reporter->testGroupEnded(TestGroupStats(GroupInfo(testSpec, groupIndex, groupsCount), totals, aborting()));
  8362. }
  8363. Totals RunContext::runTest(TestCase const& testCase) {
  8364. Totals prevTotals = m_totals;
  8365. std::string redirectedCout;
  8366. std::string redirectedCerr;
  8367. auto const& testInfo = testCase.getTestCaseInfo();
  8368. m_reporter->testCaseStarting(testInfo);
  8369. m_activeTestCase = &testCase;
  8370. ITracker& rootTracker = m_trackerContext.startRun();
  8371. assert(rootTracker.isSectionTracker());
  8372. static_cast<SectionTracker&>(rootTracker).addInitialFilters(m_config->getSectionsToRun());
  8373. do {
  8374. m_trackerContext.startCycle();
  8375. m_testCaseTracker = &SectionTracker::acquire(m_trackerContext, TestCaseTracking::NameAndLocation(testInfo.name, testInfo.lineInfo));
  8376. runCurrentTest(redirectedCout, redirectedCerr);
  8377. } while (!m_testCaseTracker->isSuccessfullyCompleted() && !aborting());
  8378. Totals deltaTotals = m_totals.delta(prevTotals);
  8379. if (testInfo.expectedToFail() && deltaTotals.testCases.passed > 0) {
  8380. deltaTotals.assertions.failed++;
  8381. deltaTotals.testCases.passed--;
  8382. deltaTotals.testCases.failed++;
  8383. }
  8384. m_totals.testCases += deltaTotals.testCases;
  8385. m_reporter->testCaseEnded(TestCaseStats(testInfo,
  8386. deltaTotals,
  8387. redirectedCout,
  8388. redirectedCerr,
  8389. aborting()));
  8390. m_activeTestCase = nullptr;
  8391. m_testCaseTracker = nullptr;
  8392. return deltaTotals;
  8393. }
  8394. IConfigPtr RunContext::config() const {
  8395. return m_config;
  8396. }
  8397. IStreamingReporter& RunContext::reporter() const {
  8398. return *m_reporter;
  8399. }
  8400. void RunContext::assertionEnded(AssertionResult const & result) {
  8401. if (result.getResultType() == ResultWas::Ok) {
  8402. m_totals.assertions.passed++;
  8403. m_lastAssertionPassed = true;
  8404. } else if (!result.isOk()) {
  8405. m_lastAssertionPassed = false;
  8406. if( m_activeTestCase->getTestCaseInfo().okToFail() )
  8407. m_totals.assertions.failedButOk++;
  8408. else
  8409. m_totals.assertions.failed++;
  8410. }
  8411. else {
  8412. m_lastAssertionPassed = true;
  8413. }
  8414. // We have no use for the return value (whether messages should be cleared), because messages were made scoped
  8415. // and should be let to clear themselves out.
  8416. static_cast<void>(m_reporter->assertionEnded(AssertionStats(result, m_messages, m_totals)));
  8417. if (result.getResultType() != ResultWas::Warning)
  8418. m_messageScopes.clear();
  8419. // Reset working state
  8420. resetAssertionInfo();
  8421. m_lastResult = result;
  8422. }
  8423. void RunContext::resetAssertionInfo() {
  8424. m_lastAssertionInfo.macroName = StringRef();
  8425. m_lastAssertionInfo.capturedExpression = "{Unknown expression after the reported line}"_sr;
  8426. }
  8427. bool RunContext::sectionStarted(SectionInfo const & sectionInfo, Counts & assertions) {
  8428. ITracker& sectionTracker = SectionTracker::acquire(m_trackerContext, TestCaseTracking::NameAndLocation(sectionInfo.name, sectionInfo.lineInfo));
  8429. if (!sectionTracker.isOpen())
  8430. return false;
  8431. m_activeSections.push_back(&sectionTracker);
  8432. m_lastAssertionInfo.lineInfo = sectionInfo.lineInfo;
  8433. m_reporter->sectionStarting(sectionInfo);
  8434. assertions = m_totals.assertions;
  8435. return true;
  8436. }
  8437. auto RunContext::acquireGeneratorTracker( SourceLineInfo const& lineInfo ) -> IGeneratorTracker& {
  8438. using namespace Generators;
  8439. GeneratorTracker& tracker = GeneratorTracker::acquire( m_trackerContext, TestCaseTracking::NameAndLocation( "generator", lineInfo ) );
  8440. assert( tracker.isOpen() );
  8441. m_lastAssertionInfo.lineInfo = lineInfo;
  8442. return tracker;
  8443. }
  8444. bool RunContext::testForMissingAssertions(Counts& assertions) {
  8445. if (assertions.total() != 0)
  8446. return false;
  8447. if (!m_config->warnAboutMissingAssertions())
  8448. return false;
  8449. if (m_trackerContext.currentTracker().hasChildren())
  8450. return false;
  8451. m_totals.assertions.failed++;
  8452. assertions.failed++;
  8453. return true;
  8454. }
  8455. void RunContext::sectionEnded(SectionEndInfo const & endInfo) {
  8456. Counts assertions = m_totals.assertions - endInfo.prevAssertions;
  8457. bool missingAssertions = testForMissingAssertions(assertions);
  8458. if (!m_activeSections.empty()) {
  8459. m_activeSections.back()->close();
  8460. m_activeSections.pop_back();
  8461. }
  8462. m_reporter->sectionEnded(SectionStats(endInfo.sectionInfo, assertions, endInfo.durationInSeconds, missingAssertions));
  8463. m_messages.clear();
  8464. m_messageScopes.clear();
  8465. }
  8466. void RunContext::sectionEndedEarly(SectionEndInfo const & endInfo) {
  8467. if (m_unfinishedSections.empty())
  8468. m_activeSections.back()->fail();
  8469. else
  8470. m_activeSections.back()->close();
  8471. m_activeSections.pop_back();
  8472. m_unfinishedSections.push_back(endInfo);
  8473. }
  8474. void RunContext::benchmarkStarting( BenchmarkInfo const& info ) {
  8475. m_reporter->benchmarkStarting( info );
  8476. }
  8477. void RunContext::benchmarkEnded( BenchmarkStats const& stats ) {
  8478. m_reporter->benchmarkEnded( stats );
  8479. }
  8480. void RunContext::pushScopedMessage(MessageInfo const & message) {
  8481. m_messages.push_back(message);
  8482. }
  8483. void RunContext::popScopedMessage(MessageInfo const & message) {
  8484. m_messages.erase(std::remove(m_messages.begin(), m_messages.end(), message), m_messages.end());
  8485. }
  8486. void RunContext::emplaceUnscopedMessage( MessageBuilder const& builder ) {
  8487. m_messageScopes.emplace_back( builder );
  8488. }
  8489. std::string RunContext::getCurrentTestName() const {
  8490. return m_activeTestCase
  8491. ? m_activeTestCase->getTestCaseInfo().name
  8492. : std::string();
  8493. }
  8494. const AssertionResult * RunContext::getLastResult() const {
  8495. return &(*m_lastResult);
  8496. }
  8497. void RunContext::exceptionEarlyReported() {
  8498. m_shouldReportUnexpected = false;
  8499. }
  8500. void RunContext::handleFatalErrorCondition( StringRef message ) {
  8501. // First notify reporter that bad things happened
  8502. m_reporter->fatalErrorEncountered(message);
  8503. // Don't rebuild the result -- the stringification itself can cause more fatal errors
  8504. // Instead, fake a result data.
  8505. AssertionResultData tempResult( ResultWas::FatalErrorCondition, { false } );
  8506. tempResult.message = message;
  8507. AssertionResult result(m_lastAssertionInfo, tempResult);
  8508. assertionEnded(result);
  8509. handleUnfinishedSections();
  8510. // Recreate section for test case (as we will lose the one that was in scope)
  8511. auto const& testCaseInfo = m_activeTestCase->getTestCaseInfo();
  8512. SectionInfo testCaseSection(testCaseInfo.lineInfo, testCaseInfo.name);
  8513. Counts assertions;
  8514. assertions.failed = 1;
  8515. SectionStats testCaseSectionStats(testCaseSection, assertions, 0, false);
  8516. m_reporter->sectionEnded(testCaseSectionStats);
  8517. auto const& testInfo = m_activeTestCase->getTestCaseInfo();
  8518. Totals deltaTotals;
  8519. deltaTotals.testCases.failed = 1;
  8520. deltaTotals.assertions.failed = 1;
  8521. m_reporter->testCaseEnded(TestCaseStats(testInfo,
  8522. deltaTotals,
  8523. std::string(),
  8524. std::string(),
  8525. false));
  8526. m_totals.testCases.failed++;
  8527. testGroupEnded(std::string(), m_totals, 1, 1);
  8528. m_reporter->testRunEnded(TestRunStats(m_runInfo, m_totals, false));
  8529. }
  8530. bool RunContext::lastAssertionPassed() {
  8531. return m_lastAssertionPassed;
  8532. }
  8533. void RunContext::assertionPassed() {
  8534. m_lastAssertionPassed = true;
  8535. ++m_totals.assertions.passed;
  8536. resetAssertionInfo();
  8537. m_messageScopes.clear();
  8538. }
  8539. bool RunContext::aborting() const {
  8540. return m_totals.assertions.failed >= static_cast<std::size_t>(m_config->abortAfter());
  8541. }
  8542. void RunContext::runCurrentTest(std::string & redirectedCout, std::string & redirectedCerr) {
  8543. auto const& testCaseInfo = m_activeTestCase->getTestCaseInfo();
  8544. SectionInfo testCaseSection(testCaseInfo.lineInfo, testCaseInfo.name);
  8545. m_reporter->sectionStarting(testCaseSection);
  8546. Counts prevAssertions = m_totals.assertions;
  8547. double duration = 0;
  8548. m_shouldReportUnexpected = true;
  8549. m_lastAssertionInfo = { "TEST_CASE"_sr, testCaseInfo.lineInfo, StringRef(), ResultDisposition::Normal };
  8550. seedRng(*m_config);
  8551. Timer timer;
  8552. CATCH_TRY {
  8553. if (m_reporter->getPreferences().shouldRedirectStdOut) {
  8554. #if !defined(CATCH_CONFIG_EXPERIMENTAL_REDIRECT)
  8555. RedirectedStreams redirectedStreams(redirectedCout, redirectedCerr);
  8556. timer.start();
  8557. invokeActiveTestCase();
  8558. #else
  8559. OutputRedirect r(redirectedCout, redirectedCerr);
  8560. timer.start();
  8561. invokeActiveTestCase();
  8562. #endif
  8563. } else {
  8564. timer.start();
  8565. invokeActiveTestCase();
  8566. }
  8567. duration = timer.getElapsedSeconds();
  8568. } CATCH_CATCH_ANON (TestFailureException&) {
  8569. // This just means the test was aborted due to failure
  8570. } CATCH_CATCH_ALL {
  8571. // Under CATCH_CONFIG_FAST_COMPILE, unexpected exceptions under REQUIRE assertions
  8572. // are reported without translation at the point of origin.
  8573. if( m_shouldReportUnexpected ) {
  8574. AssertionReaction dummyReaction;
  8575. handleUnexpectedInflightException( m_lastAssertionInfo, translateActiveException(), dummyReaction );
  8576. }
  8577. }
  8578. Counts assertions = m_totals.assertions - prevAssertions;
  8579. bool missingAssertions = testForMissingAssertions(assertions);
  8580. m_testCaseTracker->close();
  8581. handleUnfinishedSections();
  8582. m_messages.clear();
  8583. m_messageScopes.clear();
  8584. SectionStats testCaseSectionStats(testCaseSection, assertions, duration, missingAssertions);
  8585. m_reporter->sectionEnded(testCaseSectionStats);
  8586. }
  8587. void RunContext::invokeActiveTestCase() {
  8588. FatalConditionHandler fatalConditionHandler; // Handle signals
  8589. m_activeTestCase->invoke();
  8590. fatalConditionHandler.reset();
  8591. }
  8592. void RunContext::handleUnfinishedSections() {
  8593. // If sections ended prematurely due to an exception we stored their
  8594. // infos here so we can tear them down outside the unwind process.
  8595. for (auto it = m_unfinishedSections.rbegin(),
  8596. itEnd = m_unfinishedSections.rend();
  8597. it != itEnd;
  8598. ++it)
  8599. sectionEnded(*it);
  8600. m_unfinishedSections.clear();
  8601. }
  8602. void RunContext::handleExpr(
  8603. AssertionInfo const& info,
  8604. ITransientExpression const& expr,
  8605. AssertionReaction& reaction
  8606. ) {
  8607. m_reporter->assertionStarting( info );
  8608. bool negated = isFalseTest( info.resultDisposition );
  8609. bool result = expr.getResult() != negated;
  8610. if( result ) {
  8611. if (!m_includeSuccessfulResults) {
  8612. assertionPassed();
  8613. }
  8614. else {
  8615. reportExpr(info, ResultWas::Ok, &expr, negated);
  8616. }
  8617. }
  8618. else {
  8619. reportExpr(info, ResultWas::ExpressionFailed, &expr, negated );
  8620. populateReaction( reaction );
  8621. }
  8622. }
  8623. void RunContext::reportExpr(
  8624. AssertionInfo const &info,
  8625. ResultWas::OfType resultType,
  8626. ITransientExpression const *expr,
  8627. bool negated ) {
  8628. m_lastAssertionInfo = info;
  8629. AssertionResultData data( resultType, LazyExpression( negated ) );
  8630. AssertionResult assertionResult{ info, data };
  8631. assertionResult.m_resultData.lazyExpression.m_transientExpression = expr;
  8632. assertionEnded( assertionResult );
  8633. }
  8634. void RunContext::handleMessage(
  8635. AssertionInfo const& info,
  8636. ResultWas::OfType resultType,
  8637. StringRef const& message,
  8638. AssertionReaction& reaction
  8639. ) {
  8640. m_reporter->assertionStarting( info );
  8641. m_lastAssertionInfo = info;
  8642. AssertionResultData data( resultType, LazyExpression( false ) );
  8643. data.message = message;
  8644. AssertionResult assertionResult{ m_lastAssertionInfo, data };
  8645. assertionEnded( assertionResult );
  8646. if( !assertionResult.isOk() )
  8647. populateReaction( reaction );
  8648. }
  8649. void RunContext::handleUnexpectedExceptionNotThrown(
  8650. AssertionInfo const& info,
  8651. AssertionReaction& reaction
  8652. ) {
  8653. handleNonExpr(info, Catch::ResultWas::DidntThrowException, reaction);
  8654. }
  8655. void RunContext::handleUnexpectedInflightException(
  8656. AssertionInfo const& info,
  8657. std::string const& message,
  8658. AssertionReaction& reaction
  8659. ) {
  8660. m_lastAssertionInfo = info;
  8661. AssertionResultData data( ResultWas::ThrewException, LazyExpression( false ) );
  8662. data.message = message;
  8663. AssertionResult assertionResult{ info, data };
  8664. assertionEnded( assertionResult );
  8665. populateReaction( reaction );
  8666. }
  8667. void RunContext::populateReaction( AssertionReaction& reaction ) {
  8668. reaction.shouldDebugBreak = m_config->shouldDebugBreak();
  8669. reaction.shouldThrow = aborting() || (m_lastAssertionInfo.resultDisposition & ResultDisposition::Normal);
  8670. }
  8671. void RunContext::handleIncomplete(
  8672. AssertionInfo const& info
  8673. ) {
  8674. m_lastAssertionInfo = info;
  8675. AssertionResultData data( ResultWas::ThrewException, LazyExpression( false ) );
  8676. data.message = "Exception translation was disabled by CATCH_CONFIG_FAST_COMPILE";
  8677. AssertionResult assertionResult{ info, data };
  8678. assertionEnded( assertionResult );
  8679. }
  8680. void RunContext::handleNonExpr(
  8681. AssertionInfo const &info,
  8682. ResultWas::OfType resultType,
  8683. AssertionReaction &reaction
  8684. ) {
  8685. m_lastAssertionInfo = info;
  8686. AssertionResultData data( resultType, LazyExpression( false ) );
  8687. AssertionResult assertionResult{ info, data };
  8688. assertionEnded( assertionResult );
  8689. if( !assertionResult.isOk() )
  8690. populateReaction( reaction );
  8691. }
  8692. IResultCapture& getResultCapture() {
  8693. if (auto* capture = getCurrentContext().getResultCapture())
  8694. return *capture;
  8695. else
  8696. CATCH_INTERNAL_ERROR("No result capture instance");
  8697. }
  8698. }
  8699. // end catch_run_context.cpp
  8700. // start catch_section.cpp
  8701. namespace Catch {
  8702. Section::Section( SectionInfo const& info )
  8703. : m_info( info ),
  8704. m_sectionIncluded( getResultCapture().sectionStarted( m_info, m_assertions ) )
  8705. {
  8706. m_timer.start();
  8707. }
  8708. Section::~Section() {
  8709. if( m_sectionIncluded ) {
  8710. SectionEndInfo endInfo{ m_info, m_assertions, m_timer.getElapsedSeconds() };
  8711. if( uncaught_exceptions() )
  8712. getResultCapture().sectionEndedEarly( endInfo );
  8713. else
  8714. getResultCapture().sectionEnded( endInfo );
  8715. }
  8716. }
  8717. // This indicates whether the section should be executed or not
  8718. Section::operator bool() const {
  8719. return m_sectionIncluded;
  8720. }
  8721. } // end namespace Catch
  8722. // end catch_section.cpp
  8723. // start catch_section_info.cpp
  8724. namespace Catch {
  8725. SectionInfo::SectionInfo
  8726. ( SourceLineInfo const& _lineInfo,
  8727. std::string const& _name )
  8728. : name( _name ),
  8729. lineInfo( _lineInfo )
  8730. {}
  8731. } // end namespace Catch
  8732. // end catch_section_info.cpp
  8733. // start catch_session.cpp
  8734. // start catch_session.h
  8735. #include <memory>
  8736. namespace Catch {
  8737. class Session : NonCopyable {
  8738. public:
  8739. Session();
  8740. ~Session() override;
  8741. void showHelp() const;
  8742. void libIdentify();
  8743. int applyCommandLine( int argc, char const * const * argv );
  8744. #if defined(CATCH_CONFIG_WCHAR) && defined(WIN32) && defined(UNICODE)
  8745. int applyCommandLine( int argc, wchar_t const * const * argv );
  8746. #endif
  8747. void useConfigData( ConfigData const& configData );
  8748. template<typename CharT>
  8749. int run(int argc, CharT const * const argv[]) {
  8750. if (m_startupExceptions)
  8751. return 1;
  8752. int returnCode = applyCommandLine(argc, argv);
  8753. if (returnCode == 0)
  8754. returnCode = run();
  8755. return returnCode;
  8756. }
  8757. int run();
  8758. clara::Parser const& cli() const;
  8759. void cli( clara::Parser const& newParser );
  8760. ConfigData& configData();
  8761. Config& config();
  8762. private:
  8763. int runInternal();
  8764. clara::Parser m_cli;
  8765. ConfigData m_configData;
  8766. std::shared_ptr<Config> m_config;
  8767. bool m_startupExceptions = false;
  8768. };
  8769. } // end namespace Catch
  8770. // end catch_session.h
  8771. // start catch_version.h
  8772. #include <iosfwd>
  8773. namespace Catch {
  8774. // Versioning information
  8775. struct Version {
  8776. Version( Version const& ) = delete;
  8777. Version& operator=( Version const& ) = delete;
  8778. Version( unsigned int _majorVersion,
  8779. unsigned int _minorVersion,
  8780. unsigned int _patchNumber,
  8781. char const * const _branchName,
  8782. unsigned int _buildNumber );
  8783. unsigned int const majorVersion;
  8784. unsigned int const minorVersion;
  8785. unsigned int const patchNumber;
  8786. // buildNumber is only used if branchName is not null
  8787. char const * const branchName;
  8788. unsigned int const buildNumber;
  8789. friend std::ostream& operator << ( std::ostream& os, Version const& version );
  8790. };
  8791. Version const& libraryVersion();
  8792. }
  8793. // end catch_version.h
  8794. #include <cstdlib>
  8795. #include <iomanip>
  8796. namespace Catch {
  8797. namespace {
  8798. const int MaxExitCode = 255;
  8799. IStreamingReporterPtr createReporter(std::string const& reporterName, IConfigPtr const& config) {
  8800. auto reporter = Catch::getRegistryHub().getReporterRegistry().create(reporterName, config);
  8801. CATCH_ENFORCE(reporter, "No reporter registered with name: '" << reporterName << "'");
  8802. return reporter;
  8803. }
  8804. IStreamingReporterPtr makeReporter(std::shared_ptr<Config> const& config) {
  8805. if (Catch::getRegistryHub().getReporterRegistry().getListeners().empty()) {
  8806. return createReporter(config->getReporterName(), config);
  8807. }
  8808. // On older platforms, returning std::unique_ptr<ListeningReporter>
  8809. // when the return type is std::unique_ptr<IStreamingReporter>
  8810. // doesn't compile without a std::move call. However, this causes
  8811. // a warning on newer platforms. Thus, we have to work around
  8812. // it a bit and downcast the pointer manually.
  8813. auto ret = std::unique_ptr<IStreamingReporter>(new ListeningReporter);
  8814. auto& multi = static_cast<ListeningReporter&>(*ret);
  8815. auto const& listeners = Catch::getRegistryHub().getReporterRegistry().getListeners();
  8816. for (auto const& listener : listeners) {
  8817. multi.addListener(listener->create(Catch::ReporterConfig(config)));
  8818. }
  8819. multi.addReporter(createReporter(config->getReporterName(), config));
  8820. return ret;
  8821. }
  8822. Catch::Totals runTests(std::shared_ptr<Config> const& config) {
  8823. auto reporter = makeReporter(config);
  8824. RunContext context(config, std::move(reporter));
  8825. Totals totals;
  8826. context.testGroupStarting(config->name(), 1, 1);
  8827. TestSpec testSpec = config->testSpec();
  8828. auto const& allTestCases = getAllTestCasesSorted(*config);
  8829. for (auto const& testCase : allTestCases) {
  8830. if (!context.aborting() && matchTest(testCase, testSpec, *config))
  8831. totals += context.runTest(testCase);
  8832. else
  8833. context.reporter().skipTest(testCase);
  8834. }
  8835. if (config->warnAboutNoTests() && totals.testCases.total() == 0) {
  8836. ReusableStringStream testConfig;
  8837. bool first = true;
  8838. for (const auto& input : config->getTestsOrTags()) {
  8839. if (!first) { testConfig << ' '; }
  8840. first = false;
  8841. testConfig << input;
  8842. }
  8843. context.reporter().noMatchingTestCases(testConfig.str());
  8844. totals.error = -1;
  8845. }
  8846. context.testGroupEnded(config->name(), totals, 1, 1);
  8847. return totals;
  8848. }
  8849. void applyFilenamesAsTags(Catch::IConfig const& config) {
  8850. auto& tests = const_cast<std::vector<TestCase>&>(getAllTestCasesSorted(config));
  8851. for (auto& testCase : tests) {
  8852. auto tags = testCase.tags;
  8853. std::string filename = testCase.lineInfo.file;
  8854. auto lastSlash = filename.find_last_of("\\/");
  8855. if (lastSlash != std::string::npos) {
  8856. filename.erase(0, lastSlash);
  8857. filename[0] = '#';
  8858. }
  8859. auto lastDot = filename.find_last_of('.');
  8860. if (lastDot != std::string::npos) {
  8861. filename.erase(lastDot);
  8862. }
  8863. tags.push_back(std::move(filename));
  8864. setTags(testCase, tags);
  8865. }
  8866. }
  8867. } // anon namespace
  8868. Session::Session() {
  8869. static bool alreadyInstantiated = false;
  8870. if( alreadyInstantiated ) {
  8871. CATCH_TRY { CATCH_INTERNAL_ERROR( "Only one instance of Catch::Session can ever be used" ); }
  8872. CATCH_CATCH_ALL { getMutableRegistryHub().registerStartupException(); }
  8873. }
  8874. // There cannot be exceptions at startup in no-exception mode.
  8875. #if !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
  8876. const auto& exceptions = getRegistryHub().getStartupExceptionRegistry().getExceptions();
  8877. if ( !exceptions.empty() ) {
  8878. m_startupExceptions = true;
  8879. Colour colourGuard( Colour::Red );
  8880. Catch::cerr() << "Errors occurred during startup!" << '\n';
  8881. // iterate over all exceptions and notify user
  8882. for ( const auto& ex_ptr : exceptions ) {
  8883. try {
  8884. std::rethrow_exception(ex_ptr);
  8885. } catch ( std::exception const& ex ) {
  8886. Catch::cerr() << Column( ex.what() ).indent(2) << '\n';
  8887. }
  8888. }
  8889. }
  8890. #endif
  8891. alreadyInstantiated = true;
  8892. m_cli = makeCommandLineParser( m_configData );
  8893. }
  8894. Session::~Session() {
  8895. Catch::cleanUp();
  8896. }
  8897. void Session::showHelp() const {
  8898. Catch::cout()
  8899. << "\nCatch v" << libraryVersion() << "\n"
  8900. << m_cli << std::endl
  8901. << "For more detailed usage please see the project docs\n" << std::endl;
  8902. }
  8903. void Session::libIdentify() {
  8904. Catch::cout()
  8905. << std::left << std::setw(16) << "description: " << "A Catch test executable\n"
  8906. << std::left << std::setw(16) << "category: " << "testframework\n"
  8907. << std::left << std::setw(16) << "framework: " << "Catch Test\n"
  8908. << std::left << std::setw(16) << "version: " << libraryVersion() << std::endl;
  8909. }
  8910. int Session::applyCommandLine( int argc, char const * const * argv ) {
  8911. if( m_startupExceptions )
  8912. return 1;
  8913. auto result = m_cli.parse( clara::Args( argc, argv ) );
  8914. if( !result ) {
  8915. config();
  8916. getCurrentMutableContext().setConfig(m_config);
  8917. Catch::cerr()
  8918. << Colour( Colour::Red )
  8919. << "\nError(s) in input:\n"
  8920. << Column( result.errorMessage() ).indent( 2 )
  8921. << "\n\n";
  8922. Catch::cerr() << "Run with -? for usage\n" << std::endl;
  8923. return MaxExitCode;
  8924. }
  8925. if( m_configData.showHelp )
  8926. showHelp();
  8927. if( m_configData.libIdentify )
  8928. libIdentify();
  8929. m_config.reset();
  8930. return 0;
  8931. }
  8932. #if defined(CATCH_CONFIG_WCHAR) && defined(WIN32) && defined(UNICODE)
  8933. int Session::applyCommandLine( int argc, wchar_t const * const * argv ) {
  8934. char **utf8Argv = new char *[ argc ];
  8935. for ( int i = 0; i < argc; ++i ) {
  8936. int bufSize = WideCharToMultiByte( CP_UTF8, 0, argv[i], -1, NULL, 0, NULL, NULL );
  8937. utf8Argv[ i ] = new char[ bufSize ];
  8938. WideCharToMultiByte( CP_UTF8, 0, argv[i], -1, utf8Argv[i], bufSize, NULL, NULL );
  8939. }
  8940. int returnCode = applyCommandLine( argc, utf8Argv );
  8941. for ( int i = 0; i < argc; ++i )
  8942. delete [] utf8Argv[ i ];
  8943. delete [] utf8Argv;
  8944. return returnCode;
  8945. }
  8946. #endif
  8947. void Session::useConfigData( ConfigData const& configData ) {
  8948. m_configData = configData;
  8949. m_config.reset();
  8950. }
  8951. int Session::run() {
  8952. if( ( m_configData.waitForKeypress & WaitForKeypress::BeforeStart ) != 0 ) {
  8953. Catch::cout() << "...waiting for enter/ return before starting" << std::endl;
  8954. static_cast<void>(std::getchar());
  8955. }
  8956. int exitCode = runInternal();
  8957. if( ( m_configData.waitForKeypress & WaitForKeypress::BeforeExit ) != 0 ) {
  8958. Catch::cout() << "...waiting for enter/ return before exiting, with code: " << exitCode << std::endl;
  8959. static_cast<void>(std::getchar());
  8960. }
  8961. return exitCode;
  8962. }
  8963. clara::Parser const& Session::cli() const {
  8964. return m_cli;
  8965. }
  8966. void Session::cli( clara::Parser const& newParser ) {
  8967. m_cli = newParser;
  8968. }
  8969. ConfigData& Session::configData() {
  8970. return m_configData;
  8971. }
  8972. Config& Session::config() {
  8973. if( !m_config )
  8974. m_config = std::make_shared<Config>( m_configData );
  8975. return *m_config;
  8976. }
  8977. int Session::runInternal() {
  8978. if( m_startupExceptions )
  8979. return 1;
  8980. if (m_configData.showHelp || m_configData.libIdentify) {
  8981. return 0;
  8982. }
  8983. CATCH_TRY {
  8984. config(); // Force config to be constructed
  8985. seedRng( *m_config );
  8986. if( m_configData.filenamesAsTags )
  8987. applyFilenamesAsTags( *m_config );
  8988. // Handle list request
  8989. if( Option<std::size_t> listed = list( m_config ) )
  8990. return static_cast<int>( *listed );
  8991. auto totals = runTests( m_config );
  8992. // Note that on unices only the lower 8 bits are usually used, clamping
  8993. // the return value to 255 prevents false negative when some multiple
  8994. // of 256 tests has failed
  8995. return (std::min) (MaxExitCode, (std::max) (totals.error, static_cast<int>(totals.assertions.failed)));
  8996. }
  8997. #if !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
  8998. catch( std::exception& ex ) {
  8999. Catch::cerr() << ex.what() << std::endl;
  9000. return MaxExitCode;
  9001. }
  9002. #endif
  9003. }
  9004. } // end namespace Catch
  9005. // end catch_session.cpp
  9006. // start catch_singletons.cpp
  9007. #include <vector>
  9008. namespace Catch {
  9009. namespace {
  9010. static auto getSingletons() -> std::vector<ISingleton*>*& {
  9011. static std::vector<ISingleton*>* g_singletons = nullptr;
  9012. if( !g_singletons )
  9013. g_singletons = new std::vector<ISingleton*>();
  9014. return g_singletons;
  9015. }
  9016. }
  9017. ISingleton::~ISingleton() {}
  9018. void addSingleton(ISingleton* singleton ) {
  9019. getSingletons()->push_back( singleton );
  9020. }
  9021. void cleanupSingletons() {
  9022. auto& singletons = getSingletons();
  9023. for( auto singleton : *singletons )
  9024. delete singleton;
  9025. delete singletons;
  9026. singletons = nullptr;
  9027. }
  9028. } // namespace Catch
  9029. // end catch_singletons.cpp
  9030. // start catch_startup_exception_registry.cpp
  9031. namespace Catch {
  9032. void StartupExceptionRegistry::add( std::exception_ptr const& exception ) noexcept {
  9033. CATCH_TRY {
  9034. m_exceptions.push_back(exception);
  9035. } CATCH_CATCH_ALL {
  9036. // If we run out of memory during start-up there's really not a lot more we can do about it
  9037. std::terminate();
  9038. }
  9039. }
  9040. std::vector<std::exception_ptr> const& StartupExceptionRegistry::getExceptions() const noexcept {
  9041. return m_exceptions;
  9042. }
  9043. } // end namespace Catch
  9044. // end catch_startup_exception_registry.cpp
  9045. // start catch_stream.cpp
  9046. #include <cstdio>
  9047. #include <iostream>
  9048. #include <fstream>
  9049. #include <sstream>
  9050. #include <vector>
  9051. #include <memory>
  9052. namespace Catch {
  9053. Catch::IStream::~IStream() = default;
  9054. namespace detail { namespace {
  9055. template<typename WriterF, std::size_t bufferSize=256>
  9056. class StreamBufImpl : public std::streambuf {
  9057. char data[bufferSize];
  9058. WriterF m_writer;
  9059. public:
  9060. StreamBufImpl() {
  9061. setp( data, data + sizeof(data) );
  9062. }
  9063. ~StreamBufImpl() noexcept {
  9064. StreamBufImpl::sync();
  9065. }
  9066. private:
  9067. int overflow( int c ) override {
  9068. sync();
  9069. if( c != EOF ) {
  9070. if( pbase() == epptr() )
  9071. m_writer( std::string( 1, static_cast<char>( c ) ) );
  9072. else
  9073. sputc( static_cast<char>( c ) );
  9074. }
  9075. return 0;
  9076. }
  9077. int sync() override {
  9078. if( pbase() != pptr() ) {
  9079. m_writer( std::string( pbase(), static_cast<std::string::size_type>( pptr() - pbase() ) ) );
  9080. setp( pbase(), epptr() );
  9081. }
  9082. return 0;
  9083. }
  9084. };
  9085. ///////////////////////////////////////////////////////////////////////////
  9086. struct OutputDebugWriter {
  9087. void operator()( std::string const&str ) {
  9088. writeToDebugConsole( str );
  9089. }
  9090. };
  9091. ///////////////////////////////////////////////////////////////////////////
  9092. class FileStream : public IStream {
  9093. mutable std::ofstream m_ofs;
  9094. public:
  9095. FileStream( StringRef filename ) {
  9096. m_ofs.open( filename.c_str() );
  9097. CATCH_ENFORCE( !m_ofs.fail(), "Unable to open file: '" << filename << "'" );
  9098. }
  9099. ~FileStream() override = default;
  9100. public: // IStream
  9101. std::ostream& stream() const override {
  9102. return m_ofs;
  9103. }
  9104. };
  9105. ///////////////////////////////////////////////////////////////////////////
  9106. class CoutStream : public IStream {
  9107. mutable std::ostream m_os;
  9108. public:
  9109. // Store the streambuf from cout up-front because
  9110. // cout may get redirected when running tests
  9111. CoutStream() : m_os( Catch::cout().rdbuf() ) {}
  9112. ~CoutStream() override = default;
  9113. public: // IStream
  9114. std::ostream& stream() const override { return m_os; }
  9115. };
  9116. ///////////////////////////////////////////////////////////////////////////
  9117. class DebugOutStream : public IStream {
  9118. std::unique_ptr<StreamBufImpl<OutputDebugWriter>> m_streamBuf;
  9119. mutable std::ostream m_os;
  9120. public:
  9121. DebugOutStream()
  9122. : m_streamBuf( new StreamBufImpl<OutputDebugWriter>() ),
  9123. m_os( m_streamBuf.get() )
  9124. {}
  9125. ~DebugOutStream() override = default;
  9126. public: // IStream
  9127. std::ostream& stream() const override { return m_os; }
  9128. };
  9129. }} // namespace anon::detail
  9130. ///////////////////////////////////////////////////////////////////////////
  9131. auto makeStream( StringRef const &filename ) -> IStream const* {
  9132. if( filename.empty() )
  9133. return new detail::CoutStream();
  9134. else if( filename[0] == '%' ) {
  9135. if( filename == "%debug" )
  9136. return new detail::DebugOutStream();
  9137. else
  9138. CATCH_ERROR( "Unrecognised stream: '" << filename << "'" );
  9139. }
  9140. else
  9141. return new detail::FileStream( filename );
  9142. }
  9143. // This class encapsulates the idea of a pool of ostringstreams that can be reused.
  9144. struct StringStreams {
  9145. std::vector<std::unique_ptr<std::ostringstream>> m_streams;
  9146. std::vector<std::size_t> m_unused;
  9147. std::ostringstream m_referenceStream; // Used for copy state/ flags from
  9148. auto add() -> std::size_t {
  9149. if( m_unused.empty() ) {
  9150. m_streams.push_back( std::unique_ptr<std::ostringstream>( new std::ostringstream ) );
  9151. return m_streams.size()-1;
  9152. }
  9153. else {
  9154. auto index = m_unused.back();
  9155. m_unused.pop_back();
  9156. return index;
  9157. }
  9158. }
  9159. void release( std::size_t index ) {
  9160. m_streams[index]->copyfmt( m_referenceStream ); // Restore initial flags and other state
  9161. m_unused.push_back(index);
  9162. }
  9163. };
  9164. ReusableStringStream::ReusableStringStream()
  9165. : m_index( Singleton<StringStreams>::getMutable().add() ),
  9166. m_oss( Singleton<StringStreams>::getMutable().m_streams[m_index].get() )
  9167. {}
  9168. ReusableStringStream::~ReusableStringStream() {
  9169. static_cast<std::ostringstream*>( m_oss )->str("");
  9170. m_oss->clear();
  9171. Singleton<StringStreams>::getMutable().release( m_index );
  9172. }
  9173. auto ReusableStringStream::str() const -> std::string {
  9174. return static_cast<std::ostringstream*>( m_oss )->str();
  9175. }
  9176. ///////////////////////////////////////////////////////////////////////////
  9177. #ifndef CATCH_CONFIG_NOSTDOUT // If you #define this you must implement these functions
  9178. std::ostream& cout() { return std::cout; }
  9179. std::ostream& cerr() { return std::cerr; }
  9180. std::ostream& clog() { return std::clog; }
  9181. #endif
  9182. }
  9183. // end catch_stream.cpp
  9184. // start catch_string_manip.cpp
  9185. #include <algorithm>
  9186. #include <ostream>
  9187. #include <cstring>
  9188. #include <cctype>
  9189. namespace Catch {
  9190. namespace {
  9191. char toLowerCh(char c) {
  9192. return static_cast<char>( std::tolower( c ) );
  9193. }
  9194. }
  9195. bool startsWith( std::string const& s, std::string const& prefix ) {
  9196. return s.size() >= prefix.size() && std::equal(prefix.begin(), prefix.end(), s.begin());
  9197. }
  9198. bool startsWith( std::string const& s, char prefix ) {
  9199. return !s.empty() && s[0] == prefix;
  9200. }
  9201. bool endsWith( std::string const& s, std::string const& suffix ) {
  9202. return s.size() >= suffix.size() && std::equal(suffix.rbegin(), suffix.rend(), s.rbegin());
  9203. }
  9204. bool endsWith( std::string const& s, char suffix ) {
  9205. return !s.empty() && s[s.size()-1] == suffix;
  9206. }
  9207. bool contains( std::string const& s, std::string const& infix ) {
  9208. return s.find( infix ) != std::string::npos;
  9209. }
  9210. void toLowerInPlace( std::string& s ) {
  9211. std::transform( s.begin(), s.end(), s.begin(), toLowerCh );
  9212. }
  9213. std::string toLower( std::string const& s ) {
  9214. std::string lc = s;
  9215. toLowerInPlace( lc );
  9216. return lc;
  9217. }
  9218. std::string trim( std::string const& str ) {
  9219. static char const* whitespaceChars = "\n\r\t ";
  9220. std::string::size_type start = str.find_first_not_of( whitespaceChars );
  9221. std::string::size_type end = str.find_last_not_of( whitespaceChars );
  9222. return start != std::string::npos ? str.substr( start, 1+end-start ) : std::string();
  9223. }
  9224. bool replaceInPlace( std::string& str, std::string const& replaceThis, std::string const& withThis ) {
  9225. bool replaced = false;
  9226. std::size_t i = str.find( replaceThis );
  9227. while( i != std::string::npos ) {
  9228. replaced = true;
  9229. str = str.substr( 0, i ) + withThis + str.substr( i+replaceThis.size() );
  9230. if( i < str.size()-withThis.size() )
  9231. i = str.find( replaceThis, i+withThis.size() );
  9232. else
  9233. i = std::string::npos;
  9234. }
  9235. return replaced;
  9236. }
  9237. pluralise::pluralise( std::size_t count, std::string const& label )
  9238. : m_count( count ),
  9239. m_label( label )
  9240. {}
  9241. std::ostream& operator << ( std::ostream& os, pluralise const& pluraliser ) {
  9242. os << pluraliser.m_count << ' ' << pluraliser.m_label;
  9243. if( pluraliser.m_count != 1 )
  9244. os << 's';
  9245. return os;
  9246. }
  9247. }
  9248. // end catch_string_manip.cpp
  9249. // start catch_stringref.cpp
  9250. #if defined(__clang__)
  9251. # pragma clang diagnostic push
  9252. # pragma clang diagnostic ignored "-Wexit-time-destructors"
  9253. #endif
  9254. #include <ostream>
  9255. #include <cstring>
  9256. #include <cstdint>
  9257. namespace {
  9258. const uint32_t byte_2_lead = 0xC0;
  9259. const uint32_t byte_3_lead = 0xE0;
  9260. const uint32_t byte_4_lead = 0xF0;
  9261. }
  9262. namespace Catch {
  9263. StringRef::StringRef( char const* rawChars ) noexcept
  9264. : StringRef( rawChars, static_cast<StringRef::size_type>(std::strlen(rawChars) ) )
  9265. {}
  9266. StringRef::operator std::string() const {
  9267. return std::string( m_start, m_size );
  9268. }
  9269. void StringRef::swap( StringRef& other ) noexcept {
  9270. std::swap( m_start, other.m_start );
  9271. std::swap( m_size, other.m_size );
  9272. std::swap( m_data, other.m_data );
  9273. }
  9274. auto StringRef::c_str() const -> char const* {
  9275. if( isSubstring() )
  9276. const_cast<StringRef*>( this )->takeOwnership();
  9277. return m_start;
  9278. }
  9279. auto StringRef::currentData() const noexcept -> char const* {
  9280. return m_start;
  9281. }
  9282. auto StringRef::isOwned() const noexcept -> bool {
  9283. return m_data != nullptr;
  9284. }
  9285. auto StringRef::isSubstring() const noexcept -> bool {
  9286. return m_start[m_size] != '\0';
  9287. }
  9288. void StringRef::takeOwnership() {
  9289. if( !isOwned() ) {
  9290. m_data = new char[m_size+1];
  9291. memcpy( m_data, m_start, m_size );
  9292. m_data[m_size] = '\0';
  9293. m_start = m_data;
  9294. }
  9295. }
  9296. auto StringRef::substr( size_type start, size_type size ) const noexcept -> StringRef {
  9297. if( start < m_size )
  9298. return StringRef( m_start+start, size );
  9299. else
  9300. return StringRef();
  9301. }
  9302. auto StringRef::operator == ( StringRef const& other ) const noexcept -> bool {
  9303. return
  9304. size() == other.size() &&
  9305. (std::strncmp( m_start, other.m_start, size() ) == 0);
  9306. }
  9307. auto StringRef::operator != ( StringRef const& other ) const noexcept -> bool {
  9308. return !operator==( other );
  9309. }
  9310. auto StringRef::operator[](size_type index) const noexcept -> char {
  9311. return m_start[index];
  9312. }
  9313. auto StringRef::numberOfCharacters() const noexcept -> size_type {
  9314. size_type noChars = m_size;
  9315. // Make adjustments for uft encodings
  9316. for( size_type i=0; i < m_size; ++i ) {
  9317. char c = m_start[i];
  9318. if( ( c & byte_2_lead ) == byte_2_lead ) {
  9319. noChars--;
  9320. if (( c & byte_3_lead ) == byte_3_lead )
  9321. noChars--;
  9322. if( ( c & byte_4_lead ) == byte_4_lead )
  9323. noChars--;
  9324. }
  9325. }
  9326. return noChars;
  9327. }
  9328. auto operator + ( StringRef const& lhs, StringRef const& rhs ) -> std::string {
  9329. std::string str;
  9330. str.reserve( lhs.size() + rhs.size() );
  9331. str += lhs;
  9332. str += rhs;
  9333. return str;
  9334. }
  9335. auto operator + ( StringRef const& lhs, const char* rhs ) -> std::string {
  9336. return std::string( lhs ) + std::string( rhs );
  9337. }
  9338. auto operator + ( char const* lhs, StringRef const& rhs ) -> std::string {
  9339. return std::string( lhs ) + std::string( rhs );
  9340. }
  9341. auto operator << ( std::ostream& os, StringRef const& str ) -> std::ostream& {
  9342. return os.write(str.currentData(), str.size());
  9343. }
  9344. auto operator+=( std::string& lhs, StringRef const& rhs ) -> std::string& {
  9345. lhs.append(rhs.currentData(), rhs.size());
  9346. return lhs;
  9347. }
  9348. } // namespace Catch
  9349. #if defined(__clang__)
  9350. # pragma clang diagnostic pop
  9351. #endif
  9352. // end catch_stringref.cpp
  9353. // start catch_tag_alias.cpp
  9354. namespace Catch {
  9355. TagAlias::TagAlias(std::string const & _tag, SourceLineInfo _lineInfo): tag(_tag), lineInfo(_lineInfo) {}
  9356. }
  9357. // end catch_tag_alias.cpp
  9358. // start catch_tag_alias_autoregistrar.cpp
  9359. namespace Catch {
  9360. RegistrarForTagAliases::RegistrarForTagAliases(char const* alias, char const* tag, SourceLineInfo const& lineInfo) {
  9361. CATCH_TRY {
  9362. getMutableRegistryHub().registerTagAlias(alias, tag, lineInfo);
  9363. } CATCH_CATCH_ALL {
  9364. // Do not throw when constructing global objects, instead register the exception to be processed later
  9365. getMutableRegistryHub().registerStartupException();
  9366. }
  9367. }
  9368. }
  9369. // end catch_tag_alias_autoregistrar.cpp
  9370. // start catch_tag_alias_registry.cpp
  9371. #include <sstream>
  9372. namespace Catch {
  9373. TagAliasRegistry::~TagAliasRegistry() {}
  9374. TagAlias const* TagAliasRegistry::find( std::string const& alias ) const {
  9375. auto it = m_registry.find( alias );
  9376. if( it != m_registry.end() )
  9377. return &(it->second);
  9378. else
  9379. return nullptr;
  9380. }
  9381. std::string TagAliasRegistry::expandAliases( std::string const& unexpandedTestSpec ) const {
  9382. std::string expandedTestSpec = unexpandedTestSpec;
  9383. for( auto const& registryKvp : m_registry ) {
  9384. std::size_t pos = expandedTestSpec.find( registryKvp.first );
  9385. if( pos != std::string::npos ) {
  9386. expandedTestSpec = expandedTestSpec.substr( 0, pos ) +
  9387. registryKvp.second.tag +
  9388. expandedTestSpec.substr( pos + registryKvp.first.size() );
  9389. }
  9390. }
  9391. return expandedTestSpec;
  9392. }
  9393. void TagAliasRegistry::add( std::string const& alias, std::string const& tag, SourceLineInfo const& lineInfo ) {
  9394. CATCH_ENFORCE( startsWith(alias, "[@") && endsWith(alias, ']'),
  9395. "error: tag alias, '" << alias << "' is not of the form [@alias name].\n" << lineInfo );
  9396. CATCH_ENFORCE( m_registry.insert(std::make_pair(alias, TagAlias(tag, lineInfo))).second,
  9397. "error: tag alias, '" << alias << "' already registered.\n"
  9398. << "\tFirst seen at: " << find(alias)->lineInfo << "\n"
  9399. << "\tRedefined at: " << lineInfo );
  9400. }
  9401. ITagAliasRegistry::~ITagAliasRegistry() {}
  9402. ITagAliasRegistry const& ITagAliasRegistry::get() {
  9403. return getRegistryHub().getTagAliasRegistry();
  9404. }
  9405. } // end namespace Catch
  9406. // end catch_tag_alias_registry.cpp
  9407. // start catch_test_case_info.cpp
  9408. #include <cctype>
  9409. #include <exception>
  9410. #include <algorithm>
  9411. #include <sstream>
  9412. namespace Catch {
  9413. namespace {
  9414. TestCaseInfo::SpecialProperties parseSpecialTag( std::string const& tag ) {
  9415. if( startsWith( tag, '.' ) ||
  9416. tag == "!hide" )
  9417. return TestCaseInfo::IsHidden;
  9418. else if( tag == "!throws" )
  9419. return TestCaseInfo::Throws;
  9420. else if( tag == "!shouldfail" )
  9421. return TestCaseInfo::ShouldFail;
  9422. else if( tag == "!mayfail" )
  9423. return TestCaseInfo::MayFail;
  9424. else if( tag == "!nonportable" )
  9425. return TestCaseInfo::NonPortable;
  9426. else if( tag == "!benchmark" )
  9427. return static_cast<TestCaseInfo::SpecialProperties>( TestCaseInfo::Benchmark | TestCaseInfo::IsHidden );
  9428. else
  9429. return TestCaseInfo::None;
  9430. }
  9431. bool isReservedTag( std::string const& tag ) {
  9432. return parseSpecialTag( tag ) == TestCaseInfo::None && tag.size() > 0 && !std::isalnum( static_cast<unsigned char>(tag[0]) );
  9433. }
  9434. void enforceNotReservedTag( std::string const& tag, SourceLineInfo const& _lineInfo ) {
  9435. CATCH_ENFORCE( !isReservedTag(tag),
  9436. "Tag name: [" << tag << "] is not allowed.\n"
  9437. << "Tag names starting with non alpha-numeric characters are reserved\n"
  9438. << _lineInfo );
  9439. }
  9440. }
  9441. TestCase makeTestCase( ITestInvoker* _testCase,
  9442. std::string const& _className,
  9443. NameAndTags const& nameAndTags,
  9444. SourceLineInfo const& _lineInfo )
  9445. {
  9446. bool isHidden = false;
  9447. // Parse out tags
  9448. std::vector<std::string> tags;
  9449. std::string desc, tag;
  9450. bool inTag = false;
  9451. std::string _descOrTags = nameAndTags.tags;
  9452. for (char c : _descOrTags) {
  9453. if( !inTag ) {
  9454. if( c == '[' )
  9455. inTag = true;
  9456. else
  9457. desc += c;
  9458. }
  9459. else {
  9460. if( c == ']' ) {
  9461. TestCaseInfo::SpecialProperties prop = parseSpecialTag( tag );
  9462. if( ( prop & TestCaseInfo::IsHidden ) != 0 )
  9463. isHidden = true;
  9464. else if( prop == TestCaseInfo::None )
  9465. enforceNotReservedTag( tag, _lineInfo );
  9466. // Merged hide tags like `[.approvals]` should be added as
  9467. // `[.][approvals]`. The `[.]` is added at later point, so
  9468. // we only strip the prefix
  9469. if (startsWith(tag, '.') && tag.size() > 1) {
  9470. tag.erase(0, 1);
  9471. }
  9472. tags.push_back( tag );
  9473. tag.clear();
  9474. inTag = false;
  9475. }
  9476. else
  9477. tag += c;
  9478. }
  9479. }
  9480. if( isHidden ) {
  9481. tags.push_back( "." );
  9482. }
  9483. TestCaseInfo info( nameAndTags.name, _className, desc, tags, _lineInfo );
  9484. return TestCase( _testCase, std::move(info) );
  9485. }
  9486. void setTags( TestCaseInfo& testCaseInfo, std::vector<std::string> tags ) {
  9487. std::sort(begin(tags), end(tags));
  9488. tags.erase(std::unique(begin(tags), end(tags)), end(tags));
  9489. testCaseInfo.lcaseTags.clear();
  9490. for( auto const& tag : tags ) {
  9491. std::string lcaseTag = toLower( tag );
  9492. testCaseInfo.properties = static_cast<TestCaseInfo::SpecialProperties>( testCaseInfo.properties | parseSpecialTag( lcaseTag ) );
  9493. testCaseInfo.lcaseTags.push_back( lcaseTag );
  9494. }
  9495. testCaseInfo.tags = std::move(tags);
  9496. }
  9497. TestCaseInfo::TestCaseInfo( std::string const& _name,
  9498. std::string const& _className,
  9499. std::string const& _description,
  9500. std::vector<std::string> const& _tags,
  9501. SourceLineInfo const& _lineInfo )
  9502. : name( _name ),
  9503. className( _className ),
  9504. description( _description ),
  9505. lineInfo( _lineInfo ),
  9506. properties( None )
  9507. {
  9508. setTags( *this, _tags );
  9509. }
  9510. bool TestCaseInfo::isHidden() const {
  9511. return ( properties & IsHidden ) != 0;
  9512. }
  9513. bool TestCaseInfo::throws() const {
  9514. return ( properties & Throws ) != 0;
  9515. }
  9516. bool TestCaseInfo::okToFail() const {
  9517. return ( properties & (ShouldFail | MayFail ) ) != 0;
  9518. }
  9519. bool TestCaseInfo::expectedToFail() const {
  9520. return ( properties & (ShouldFail ) ) != 0;
  9521. }
  9522. std::string TestCaseInfo::tagsAsString() const {
  9523. std::string ret;
  9524. // '[' and ']' per tag
  9525. std::size_t full_size = 2 * tags.size();
  9526. for (const auto& tag : tags) {
  9527. full_size += tag.size();
  9528. }
  9529. ret.reserve(full_size);
  9530. for (const auto& tag : tags) {
  9531. ret.push_back('[');
  9532. ret.append(tag);
  9533. ret.push_back(']');
  9534. }
  9535. return ret;
  9536. }
  9537. TestCase::TestCase( ITestInvoker* testCase, TestCaseInfo&& info ) : TestCaseInfo( std::move(info) ), test( testCase ) {}
  9538. TestCase TestCase::withName( std::string const& _newName ) const {
  9539. TestCase other( *this );
  9540. other.name = _newName;
  9541. return other;
  9542. }
  9543. void TestCase::invoke() const {
  9544. test->invoke();
  9545. }
  9546. bool TestCase::operator == ( TestCase const& other ) const {
  9547. return test.get() == other.test.get() &&
  9548. name == other.name &&
  9549. className == other.className;
  9550. }
  9551. bool TestCase::operator < ( TestCase const& other ) const {
  9552. return name < other.name;
  9553. }
  9554. TestCaseInfo const& TestCase::getTestCaseInfo() const
  9555. {
  9556. return *this;
  9557. }
  9558. } // end namespace Catch
  9559. // end catch_test_case_info.cpp
  9560. // start catch_test_case_registry_impl.cpp
  9561. #include <sstream>
  9562. namespace Catch {
  9563. std::vector<TestCase> sortTests( IConfig const& config, std::vector<TestCase> const& unsortedTestCases ) {
  9564. std::vector<TestCase> sorted = unsortedTestCases;
  9565. switch( config.runOrder() ) {
  9566. case RunTests::InLexicographicalOrder:
  9567. std::sort( sorted.begin(), sorted.end() );
  9568. break;
  9569. case RunTests::InRandomOrder:
  9570. seedRng( config );
  9571. std::shuffle( sorted.begin(), sorted.end(), rng() );
  9572. break;
  9573. case RunTests::InDeclarationOrder:
  9574. // already in declaration order
  9575. break;
  9576. }
  9577. return sorted;
  9578. }
  9579. bool matchTest( TestCase const& testCase, TestSpec const& testSpec, IConfig const& config ) {
  9580. return testSpec.matches( testCase ) && ( config.allowThrows() || !testCase.throws() );
  9581. }
  9582. void enforceNoDuplicateTestCases( std::vector<TestCase> const& functions ) {
  9583. std::set<TestCase> seenFunctions;
  9584. for( auto const& function : functions ) {
  9585. auto prev = seenFunctions.insert( function );
  9586. CATCH_ENFORCE( prev.second,
  9587. "error: TEST_CASE( \"" << function.name << "\" ) already defined.\n"
  9588. << "\tFirst seen at " << prev.first->getTestCaseInfo().lineInfo << "\n"
  9589. << "\tRedefined at " << function.getTestCaseInfo().lineInfo );
  9590. }
  9591. }
  9592. std::vector<TestCase> filterTests( std::vector<TestCase> const& testCases, TestSpec const& testSpec, IConfig const& config ) {
  9593. std::vector<TestCase> filtered;
  9594. filtered.reserve( testCases.size() );
  9595. for( auto const& testCase : testCases )
  9596. if( matchTest( testCase, testSpec, config ) )
  9597. filtered.push_back( testCase );
  9598. return filtered;
  9599. }
  9600. std::vector<TestCase> const& getAllTestCasesSorted( IConfig const& config ) {
  9601. return getRegistryHub().getTestCaseRegistry().getAllTestsSorted( config );
  9602. }
  9603. void TestRegistry::registerTest( TestCase const& testCase ) {
  9604. std::string name = testCase.getTestCaseInfo().name;
  9605. if( name.empty() ) {
  9606. ReusableStringStream rss;
  9607. rss << "Anonymous test case " << ++m_unnamedCount;
  9608. return registerTest( testCase.withName( rss.str() ) );
  9609. }
  9610. m_functions.push_back( testCase );
  9611. }
  9612. std::vector<TestCase> const& TestRegistry::getAllTests() const {
  9613. return m_functions;
  9614. }
  9615. std::vector<TestCase> const& TestRegistry::getAllTestsSorted( IConfig const& config ) const {
  9616. if( m_sortedFunctions.empty() )
  9617. enforceNoDuplicateTestCases( m_functions );
  9618. if( m_currentSortOrder != config.runOrder() || m_sortedFunctions.empty() ) {
  9619. m_sortedFunctions = sortTests( config, m_functions );
  9620. m_currentSortOrder = config.runOrder();
  9621. }
  9622. return m_sortedFunctions;
  9623. }
  9624. ///////////////////////////////////////////////////////////////////////////
  9625. TestInvokerAsFunction::TestInvokerAsFunction( void(*testAsFunction)() ) noexcept : m_testAsFunction( testAsFunction ) {}
  9626. void TestInvokerAsFunction::invoke() const {
  9627. m_testAsFunction();
  9628. }
  9629. std::string extractClassName( StringRef const& classOrQualifiedMethodName ) {
  9630. std::string className = classOrQualifiedMethodName;
  9631. if( startsWith( className, '&' ) )
  9632. {
  9633. std::size_t lastColons = className.rfind( "::" );
  9634. std::size_t penultimateColons = className.rfind( "::", lastColons-1 );
  9635. if( penultimateColons == std::string::npos )
  9636. penultimateColons = 1;
  9637. className = className.substr( penultimateColons, lastColons-penultimateColons );
  9638. }
  9639. return className;
  9640. }
  9641. } // end namespace Catch
  9642. // end catch_test_case_registry_impl.cpp
  9643. // start catch_test_case_tracker.cpp
  9644. #include <algorithm>
  9645. #include <cassert>
  9646. #include <stdexcept>
  9647. #include <memory>
  9648. #include <sstream>
  9649. #if defined(__clang__)
  9650. # pragma clang diagnostic push
  9651. # pragma clang diagnostic ignored "-Wexit-time-destructors"
  9652. #endif
  9653. namespace Catch {
  9654. namespace TestCaseTracking {
  9655. NameAndLocation::NameAndLocation( std::string const& _name, SourceLineInfo const& _location )
  9656. : name( _name ),
  9657. location( _location )
  9658. {}
  9659. ITracker::~ITracker() = default;
  9660. TrackerContext& TrackerContext::instance() {
  9661. static TrackerContext s_instance;
  9662. return s_instance;
  9663. }
  9664. ITracker& TrackerContext::startRun() {
  9665. m_rootTracker = std::make_shared<SectionTracker>( NameAndLocation( "{root}", CATCH_INTERNAL_LINEINFO ), *this, nullptr );
  9666. m_currentTracker = nullptr;
  9667. m_runState = Executing;
  9668. return *m_rootTracker;
  9669. }
  9670. void TrackerContext::endRun() {
  9671. m_rootTracker.reset();
  9672. m_currentTracker = nullptr;
  9673. m_runState = NotStarted;
  9674. }
  9675. void TrackerContext::startCycle() {
  9676. m_currentTracker = m_rootTracker.get();
  9677. m_runState = Executing;
  9678. }
  9679. void TrackerContext::completeCycle() {
  9680. m_runState = CompletedCycle;
  9681. }
  9682. bool TrackerContext::completedCycle() const {
  9683. return m_runState == CompletedCycle;
  9684. }
  9685. ITracker& TrackerContext::currentTracker() {
  9686. return *m_currentTracker;
  9687. }
  9688. void TrackerContext::setCurrentTracker( ITracker* tracker ) {
  9689. m_currentTracker = tracker;
  9690. }
  9691. TrackerBase::TrackerBase( NameAndLocation const& nameAndLocation, TrackerContext& ctx, ITracker* parent )
  9692. : m_nameAndLocation( nameAndLocation ),
  9693. m_ctx( ctx ),
  9694. m_parent( parent )
  9695. {}
  9696. NameAndLocation const& TrackerBase::nameAndLocation() const {
  9697. return m_nameAndLocation;
  9698. }
  9699. bool TrackerBase::isComplete() const {
  9700. return m_runState == CompletedSuccessfully || m_runState == Failed;
  9701. }
  9702. bool TrackerBase::isSuccessfullyCompleted() const {
  9703. return m_runState == CompletedSuccessfully;
  9704. }
  9705. bool TrackerBase::isOpen() const {
  9706. return m_runState != NotStarted && !isComplete();
  9707. }
  9708. bool TrackerBase::hasChildren() const {
  9709. return !m_children.empty();
  9710. }
  9711. void TrackerBase::addChild( ITrackerPtr const& child ) {
  9712. m_children.push_back( child );
  9713. }
  9714. ITrackerPtr TrackerBase::findChild( NameAndLocation const& nameAndLocation ) {
  9715. auto it = std::find_if( m_children.begin(), m_children.end(),
  9716. [&nameAndLocation]( ITrackerPtr const& tracker ){
  9717. return
  9718. tracker->nameAndLocation().location == nameAndLocation.location &&
  9719. tracker->nameAndLocation().name == nameAndLocation.name;
  9720. } );
  9721. return( it != m_children.end() )
  9722. ? *it
  9723. : nullptr;
  9724. }
  9725. ITracker& TrackerBase::parent() {
  9726. assert( m_parent ); // Should always be non-null except for root
  9727. return *m_parent;
  9728. }
  9729. void TrackerBase::openChild() {
  9730. if( m_runState != ExecutingChildren ) {
  9731. m_runState = ExecutingChildren;
  9732. if( m_parent )
  9733. m_parent->openChild();
  9734. }
  9735. }
  9736. bool TrackerBase::isSectionTracker() const { return false; }
  9737. bool TrackerBase::isGeneratorTracker() const { return false; }
  9738. void TrackerBase::open() {
  9739. m_runState = Executing;
  9740. moveToThis();
  9741. if( m_parent )
  9742. m_parent->openChild();
  9743. }
  9744. void TrackerBase::close() {
  9745. // Close any still open children (e.g. generators)
  9746. while( &m_ctx.currentTracker() != this )
  9747. m_ctx.currentTracker().close();
  9748. switch( m_runState ) {
  9749. case NeedsAnotherRun:
  9750. break;
  9751. case Executing:
  9752. m_runState = CompletedSuccessfully;
  9753. break;
  9754. case ExecutingChildren:
  9755. if( m_children.empty() || m_children.back()->isComplete() )
  9756. m_runState = CompletedSuccessfully;
  9757. break;
  9758. case NotStarted:
  9759. case CompletedSuccessfully:
  9760. case Failed:
  9761. CATCH_INTERNAL_ERROR( "Illogical state: " << m_runState );
  9762. default:
  9763. CATCH_INTERNAL_ERROR( "Unknown state: " << m_runState );
  9764. }
  9765. moveToParent();
  9766. m_ctx.completeCycle();
  9767. }
  9768. void TrackerBase::fail() {
  9769. m_runState = Failed;
  9770. if( m_parent )
  9771. m_parent->markAsNeedingAnotherRun();
  9772. moveToParent();
  9773. m_ctx.completeCycle();
  9774. }
  9775. void TrackerBase::markAsNeedingAnotherRun() {
  9776. m_runState = NeedsAnotherRun;
  9777. }
  9778. void TrackerBase::moveToParent() {
  9779. assert( m_parent );
  9780. m_ctx.setCurrentTracker( m_parent );
  9781. }
  9782. void TrackerBase::moveToThis() {
  9783. m_ctx.setCurrentTracker( this );
  9784. }
  9785. SectionTracker::SectionTracker( NameAndLocation const& nameAndLocation, TrackerContext& ctx, ITracker* parent )
  9786. : TrackerBase( nameAndLocation, ctx, parent )
  9787. {
  9788. if( parent ) {
  9789. while( !parent->isSectionTracker() )
  9790. parent = &parent->parent();
  9791. SectionTracker& parentSection = static_cast<SectionTracker&>( *parent );
  9792. addNextFilters( parentSection.m_filters );
  9793. }
  9794. }
  9795. bool SectionTracker::isComplete() const {
  9796. bool complete = true;
  9797. if ((m_filters.empty() || m_filters[0] == "") ||
  9798. std::find(m_filters.begin(), m_filters.end(),
  9799. m_nameAndLocation.name) != m_filters.end())
  9800. complete = TrackerBase::isComplete();
  9801. return complete;
  9802. }
  9803. bool SectionTracker::isSectionTracker() const { return true; }
  9804. SectionTracker& SectionTracker::acquire( TrackerContext& ctx, NameAndLocation const& nameAndLocation ) {
  9805. std::shared_ptr<SectionTracker> section;
  9806. ITracker& currentTracker = ctx.currentTracker();
  9807. if( ITrackerPtr childTracker = currentTracker.findChild( nameAndLocation ) ) {
  9808. assert( childTracker );
  9809. assert( childTracker->isSectionTracker() );
  9810. section = std::static_pointer_cast<SectionTracker>( childTracker );
  9811. }
  9812. else {
  9813. section = std::make_shared<SectionTracker>( nameAndLocation, ctx, &currentTracker );
  9814. currentTracker.addChild( section );
  9815. }
  9816. if( !ctx.completedCycle() )
  9817. section->tryOpen();
  9818. return *section;
  9819. }
  9820. void SectionTracker::tryOpen() {
  9821. if( !isComplete() && (m_filters.empty() || m_filters[0].empty() || m_filters[0] == m_nameAndLocation.name ) )
  9822. open();
  9823. }
  9824. void SectionTracker::addInitialFilters( std::vector<std::string> const& filters ) {
  9825. if( !filters.empty() ) {
  9826. m_filters.push_back(""); // Root - should never be consulted
  9827. m_filters.push_back(""); // Test Case - not a section filter
  9828. m_filters.insert( m_filters.end(), filters.begin(), filters.end() );
  9829. }
  9830. }
  9831. void SectionTracker::addNextFilters( std::vector<std::string> const& filters ) {
  9832. if( filters.size() > 1 )
  9833. m_filters.insert( m_filters.end(), ++filters.begin(), filters.end() );
  9834. }
  9835. } // namespace TestCaseTracking
  9836. using TestCaseTracking::ITracker;
  9837. using TestCaseTracking::TrackerContext;
  9838. using TestCaseTracking::SectionTracker;
  9839. } // namespace Catch
  9840. #if defined(__clang__)
  9841. # pragma clang diagnostic pop
  9842. #endif
  9843. // end catch_test_case_tracker.cpp
  9844. // start catch_test_registry.cpp
  9845. namespace Catch {
  9846. auto makeTestInvoker( void(*testAsFunction)() ) noexcept -> ITestInvoker* {
  9847. return new(std::nothrow) TestInvokerAsFunction( testAsFunction );
  9848. }
  9849. NameAndTags::NameAndTags( StringRef const& name_ , StringRef const& tags_ ) noexcept : name( name_ ), tags( tags_ ) {}
  9850. AutoReg::AutoReg( ITestInvoker* invoker, SourceLineInfo const& lineInfo, StringRef const& classOrMethod, NameAndTags const& nameAndTags ) noexcept {
  9851. CATCH_TRY {
  9852. getMutableRegistryHub()
  9853. .registerTest(
  9854. makeTestCase(
  9855. invoker,
  9856. extractClassName( classOrMethod ),
  9857. nameAndTags,
  9858. lineInfo));
  9859. } CATCH_CATCH_ALL {
  9860. // Do not throw when constructing global objects, instead register the exception to be processed later
  9861. getMutableRegistryHub().registerStartupException();
  9862. }
  9863. }
  9864. AutoReg::~AutoReg() = default;
  9865. }
  9866. // end catch_test_registry.cpp
  9867. // start catch_test_spec.cpp
  9868. #include <algorithm>
  9869. #include <string>
  9870. #include <vector>
  9871. #include <memory>
  9872. namespace Catch {
  9873. TestSpec::Pattern::~Pattern() = default;
  9874. TestSpec::NamePattern::~NamePattern() = default;
  9875. TestSpec::TagPattern::~TagPattern() = default;
  9876. TestSpec::ExcludedPattern::~ExcludedPattern() = default;
  9877. TestSpec::NamePattern::NamePattern( std::string const& name )
  9878. : m_wildcardPattern( toLower( name ), CaseSensitive::No )
  9879. {}
  9880. bool TestSpec::NamePattern::matches( TestCaseInfo const& testCase ) const {
  9881. return m_wildcardPattern.matches( toLower( testCase.name ) );
  9882. }
  9883. TestSpec::TagPattern::TagPattern( std::string const& tag ) : m_tag( toLower( tag ) ) {}
  9884. bool TestSpec::TagPattern::matches( TestCaseInfo const& testCase ) const {
  9885. return std::find(begin(testCase.lcaseTags),
  9886. end(testCase.lcaseTags),
  9887. m_tag) != end(testCase.lcaseTags);
  9888. }
  9889. TestSpec::ExcludedPattern::ExcludedPattern( PatternPtr const& underlyingPattern ) : m_underlyingPattern( underlyingPattern ) {}
  9890. bool TestSpec::ExcludedPattern::matches( TestCaseInfo const& testCase ) const { return !m_underlyingPattern->matches( testCase ); }
  9891. bool TestSpec::Filter::matches( TestCaseInfo const& testCase ) const {
  9892. // All patterns in a filter must match for the filter to be a match
  9893. for( auto const& pattern : m_patterns ) {
  9894. if( !pattern->matches( testCase ) )
  9895. return false;
  9896. }
  9897. return true;
  9898. }
  9899. bool TestSpec::hasFilters() const {
  9900. return !m_filters.empty();
  9901. }
  9902. bool TestSpec::matches( TestCaseInfo const& testCase ) const {
  9903. // A TestSpec matches if any filter matches
  9904. for( auto const& filter : m_filters )
  9905. if( filter.matches( testCase ) )
  9906. return true;
  9907. return false;
  9908. }
  9909. }
  9910. // end catch_test_spec.cpp
  9911. // start catch_test_spec_parser.cpp
  9912. namespace Catch {
  9913. TestSpecParser::TestSpecParser( ITagAliasRegistry const& tagAliases ) : m_tagAliases( &tagAliases ) {}
  9914. TestSpecParser& TestSpecParser::parse( std::string const& arg ) {
  9915. m_mode = None;
  9916. m_exclusion = false;
  9917. m_start = std::string::npos;
  9918. m_arg = m_tagAliases->expandAliases( arg );
  9919. m_escapeChars.clear();
  9920. for( m_pos = 0; m_pos < m_arg.size(); ++m_pos )
  9921. visitChar( m_arg[m_pos] );
  9922. if( m_mode == Name )
  9923. addPattern<TestSpec::NamePattern>();
  9924. return *this;
  9925. }
  9926. TestSpec TestSpecParser::testSpec() {
  9927. addFilter();
  9928. return m_testSpec;
  9929. }
  9930. void TestSpecParser::visitChar( char c ) {
  9931. if( m_mode == None ) {
  9932. switch( c ) {
  9933. case ' ': return;
  9934. case '~': m_exclusion = true; return;
  9935. case '[': return startNewMode( Tag, ++m_pos );
  9936. case '"': return startNewMode( QuotedName, ++m_pos );
  9937. case '\\': return escape();
  9938. default: startNewMode( Name, m_pos ); break;
  9939. }
  9940. }
  9941. if( m_mode == Name ) {
  9942. if( c == ',' ) {
  9943. addPattern<TestSpec::NamePattern>();
  9944. addFilter();
  9945. }
  9946. else if( c == '[' ) {
  9947. if( subString() == "exclude:" )
  9948. m_exclusion = true;
  9949. else
  9950. addPattern<TestSpec::NamePattern>();
  9951. startNewMode( Tag, ++m_pos );
  9952. }
  9953. else if( c == '\\' )
  9954. escape();
  9955. }
  9956. else if( m_mode == EscapedName )
  9957. m_mode = Name;
  9958. else if( m_mode == QuotedName && c == '"' )
  9959. addPattern<TestSpec::NamePattern>();
  9960. else if( m_mode == Tag && c == ']' )
  9961. addPattern<TestSpec::TagPattern>();
  9962. }
  9963. void TestSpecParser::startNewMode( Mode mode, std::size_t start ) {
  9964. m_mode = mode;
  9965. m_start = start;
  9966. }
  9967. void TestSpecParser::escape() {
  9968. if( m_mode == None )
  9969. m_start = m_pos;
  9970. m_mode = EscapedName;
  9971. m_escapeChars.push_back( m_pos );
  9972. }
  9973. std::string TestSpecParser::subString() const { return m_arg.substr( m_start, m_pos - m_start ); }
  9974. void TestSpecParser::addFilter() {
  9975. if( !m_currentFilter.m_patterns.empty() ) {
  9976. m_testSpec.m_filters.push_back( m_currentFilter );
  9977. m_currentFilter = TestSpec::Filter();
  9978. }
  9979. }
  9980. TestSpec parseTestSpec( std::string const& arg ) {
  9981. return TestSpecParser( ITagAliasRegistry::get() ).parse( arg ).testSpec();
  9982. }
  9983. } // namespace Catch
  9984. // end catch_test_spec_parser.cpp
  9985. // start catch_timer.cpp
  9986. #include <chrono>
  9987. static const uint64_t nanosecondsInSecond = 1000000000;
  9988. namespace Catch {
  9989. auto getCurrentNanosecondsSinceEpoch() -> uint64_t {
  9990. return std::chrono::duration_cast<std::chrono::nanoseconds>( std::chrono::high_resolution_clock::now().time_since_epoch() ).count();
  9991. }
  9992. namespace {
  9993. auto estimateClockResolution() -> uint64_t {
  9994. uint64_t sum = 0;
  9995. static const uint64_t iterations = 1000000;
  9996. auto startTime = getCurrentNanosecondsSinceEpoch();
  9997. for( std::size_t i = 0; i < iterations; ++i ) {
  9998. uint64_t ticks;
  9999. uint64_t baseTicks = getCurrentNanosecondsSinceEpoch();
  10000. do {
  10001. ticks = getCurrentNanosecondsSinceEpoch();
  10002. } while( ticks == baseTicks );
  10003. auto delta = ticks - baseTicks;
  10004. sum += delta;
  10005. // If we have been calibrating for over 3 seconds -- the clock
  10006. // is terrible and we should move on.
  10007. // TBD: How to signal that the measured resolution is probably wrong?
  10008. if (ticks > startTime + 3 * nanosecondsInSecond) {
  10009. return sum / ( i + 1u );
  10010. }
  10011. }
  10012. // We're just taking the mean, here. To do better we could take the std. dev and exclude outliers
  10013. // - and potentially do more iterations if there's a high variance.
  10014. return sum/iterations;
  10015. }
  10016. }
  10017. auto getEstimatedClockResolution() -> uint64_t {
  10018. static auto s_resolution = estimateClockResolution();
  10019. return s_resolution;
  10020. }
  10021. void Timer::start() {
  10022. m_nanoseconds = getCurrentNanosecondsSinceEpoch();
  10023. }
  10024. auto Timer::getElapsedNanoseconds() const -> uint64_t {
  10025. return getCurrentNanosecondsSinceEpoch() - m_nanoseconds;
  10026. }
  10027. auto Timer::getElapsedMicroseconds() const -> uint64_t {
  10028. return getElapsedNanoseconds()/1000;
  10029. }
  10030. auto Timer::getElapsedMilliseconds() const -> unsigned int {
  10031. return static_cast<unsigned int>(getElapsedMicroseconds()/1000);
  10032. }
  10033. auto Timer::getElapsedSeconds() const -> double {
  10034. return getElapsedMicroseconds()/1000000.0;
  10035. }
  10036. } // namespace Catch
  10037. // end catch_timer.cpp
  10038. // start catch_tostring.cpp
  10039. #if defined(__clang__)
  10040. # pragma clang diagnostic push
  10041. # pragma clang diagnostic ignored "-Wexit-time-destructors"
  10042. # pragma clang diagnostic ignored "-Wglobal-constructors"
  10043. #endif
  10044. // Enable specific decls locally
  10045. #if !defined(CATCH_CONFIG_ENABLE_CHRONO_STRINGMAKER)
  10046. #define CATCH_CONFIG_ENABLE_CHRONO_STRINGMAKER
  10047. #endif
  10048. #include <cmath>
  10049. #include <iomanip>
  10050. namespace Catch {
  10051. namespace Detail {
  10052. const std::string unprintableString = "{?}";
  10053. namespace {
  10054. const int hexThreshold = 255;
  10055. struct Endianness {
  10056. enum Arch { Big, Little };
  10057. static Arch which() {
  10058. union _{
  10059. int asInt;
  10060. char asChar[sizeof (int)];
  10061. } u;
  10062. u.asInt = 1;
  10063. return ( u.asChar[sizeof(int)-1] == 1 ) ? Big : Little;
  10064. }
  10065. };
  10066. }
  10067. std::string rawMemoryToString( const void *object, std::size_t size ) {
  10068. // Reverse order for little endian architectures
  10069. int i = 0, end = static_cast<int>( size ), inc = 1;
  10070. if( Endianness::which() == Endianness::Little ) {
  10071. i = end-1;
  10072. end = inc = -1;
  10073. }
  10074. unsigned char const *bytes = static_cast<unsigned char const *>(object);
  10075. ReusableStringStream rss;
  10076. rss << "0x" << std::setfill('0') << std::hex;
  10077. for( ; i != end; i += inc )
  10078. rss << std::setw(2) << static_cast<unsigned>(bytes[i]);
  10079. return rss.str();
  10080. }
  10081. }
  10082. template<typename T>
  10083. std::string fpToString( T value, int precision ) {
  10084. if (Catch::isnan(value)) {
  10085. return "nan";
  10086. }
  10087. ReusableStringStream rss;
  10088. rss << std::setprecision( precision )
  10089. << std::fixed
  10090. << value;
  10091. std::string d = rss.str();
  10092. std::size_t i = d.find_last_not_of( '0' );
  10093. if( i != std::string::npos && i != d.size()-1 ) {
  10094. if( d[i] == '.' )
  10095. i++;
  10096. d = d.substr( 0, i+1 );
  10097. }
  10098. return d;
  10099. }
  10100. //// ======================================================= ////
  10101. //
  10102. // Out-of-line defs for full specialization of StringMaker
  10103. //
  10104. //// ======================================================= ////
  10105. std::string StringMaker<std::string>::convert(const std::string& str) {
  10106. if (!getCurrentContext().getConfig()->showInvisibles()) {
  10107. return '"' + str + '"';
  10108. }
  10109. std::string s("\"");
  10110. for (char c : str) {
  10111. switch (c) {
  10112. case '\n':
  10113. s.append("\\n");
  10114. break;
  10115. case '\t':
  10116. s.append("\\t");
  10117. break;
  10118. default:
  10119. s.push_back(c);
  10120. break;
  10121. }
  10122. }
  10123. s.append("\"");
  10124. return s;
  10125. }
  10126. #ifdef CATCH_CONFIG_CPP17_STRING_VIEW
  10127. std::string StringMaker<std::string_view>::convert(std::string_view str) {
  10128. return ::Catch::Detail::stringify(std::string{ str });
  10129. }
  10130. #endif
  10131. std::string StringMaker<char const*>::convert(char const* str) {
  10132. if (str) {
  10133. return ::Catch::Detail::stringify(std::string{ str });
  10134. } else {
  10135. return{ "{null string}" };
  10136. }
  10137. }
  10138. std::string StringMaker<char*>::convert(char* str) {
  10139. if (str) {
  10140. return ::Catch::Detail::stringify(std::string{ str });
  10141. } else {
  10142. return{ "{null string}" };
  10143. }
  10144. }
  10145. #ifdef CATCH_CONFIG_WCHAR
  10146. std::string StringMaker<std::wstring>::convert(const std::wstring& wstr) {
  10147. std::string s;
  10148. s.reserve(wstr.size());
  10149. for (auto c : wstr) {
  10150. s += (c <= 0xff) ? static_cast<char>(c) : '?';
  10151. }
  10152. return ::Catch::Detail::stringify(s);
  10153. }
  10154. # ifdef CATCH_CONFIG_CPP17_STRING_VIEW
  10155. std::string StringMaker<std::wstring_view>::convert(std::wstring_view str) {
  10156. return StringMaker<std::wstring>::convert(std::wstring(str));
  10157. }
  10158. # endif
  10159. std::string StringMaker<wchar_t const*>::convert(wchar_t const * str) {
  10160. if (str) {
  10161. return ::Catch::Detail::stringify(std::wstring{ str });
  10162. } else {
  10163. return{ "{null string}" };
  10164. }
  10165. }
  10166. std::string StringMaker<wchar_t *>::convert(wchar_t * str) {
  10167. if (str) {
  10168. return ::Catch::Detail::stringify(std::wstring{ str });
  10169. } else {
  10170. return{ "{null string}" };
  10171. }
  10172. }
  10173. #endif
  10174. std::string StringMaker<int>::convert(int value) {
  10175. return ::Catch::Detail::stringify(static_cast<long long>(value));
  10176. }
  10177. std::string StringMaker<long>::convert(long value) {
  10178. return ::Catch::Detail::stringify(static_cast<long long>(value));
  10179. }
  10180. std::string StringMaker<long long>::convert(long long value) {
  10181. ReusableStringStream rss;
  10182. rss << value;
  10183. if (value > Detail::hexThreshold) {
  10184. rss << " (0x" << std::hex << value << ')';
  10185. }
  10186. return rss.str();
  10187. }
  10188. std::string StringMaker<unsigned int>::convert(unsigned int value) {
  10189. return ::Catch::Detail::stringify(static_cast<unsigned long long>(value));
  10190. }
  10191. std::string StringMaker<unsigned long>::convert(unsigned long value) {
  10192. return ::Catch::Detail::stringify(static_cast<unsigned long long>(value));
  10193. }
  10194. std::string StringMaker<unsigned long long>::convert(unsigned long long value) {
  10195. ReusableStringStream rss;
  10196. rss << value;
  10197. if (value > Detail::hexThreshold) {
  10198. rss << " (0x" << std::hex << value << ')';
  10199. }
  10200. return rss.str();
  10201. }
  10202. std::string StringMaker<bool>::convert(bool b) {
  10203. return b ? "true" : "false";
  10204. }
  10205. std::string StringMaker<signed char>::convert(signed char value) {
  10206. if (value == '\r') {
  10207. return "'\\r'";
  10208. } else if (value == '\f') {
  10209. return "'\\f'";
  10210. } else if (value == '\n') {
  10211. return "'\\n'";
  10212. } else if (value == '\t') {
  10213. return "'\\t'";
  10214. } else if ('\0' <= value && value < ' ') {
  10215. return ::Catch::Detail::stringify(static_cast<unsigned int>(value));
  10216. } else {
  10217. char chstr[] = "' '";
  10218. chstr[1] = value;
  10219. return chstr;
  10220. }
  10221. }
  10222. std::string StringMaker<char>::convert(char c) {
  10223. return ::Catch::Detail::stringify(static_cast<signed char>(c));
  10224. }
  10225. std::string StringMaker<unsigned char>::convert(unsigned char c) {
  10226. return ::Catch::Detail::stringify(static_cast<char>(c));
  10227. }
  10228. std::string StringMaker<std::nullptr_t>::convert(std::nullptr_t) {
  10229. return "nullptr";
  10230. }
  10231. std::string StringMaker<float>::convert(float value) {
  10232. return fpToString(value, 5) + 'f';
  10233. }
  10234. std::string StringMaker<double>::convert(double value) {
  10235. return fpToString(value, 10);
  10236. }
  10237. std::string ratio_string<std::atto>::symbol() { return "a"; }
  10238. std::string ratio_string<std::femto>::symbol() { return "f"; }
  10239. std::string ratio_string<std::pico>::symbol() { return "p"; }
  10240. std::string ratio_string<std::nano>::symbol() { return "n"; }
  10241. std::string ratio_string<std::micro>::symbol() { return "u"; }
  10242. std::string ratio_string<std::milli>::symbol() { return "m"; }
  10243. } // end namespace Catch
  10244. #if defined(__clang__)
  10245. # pragma clang diagnostic pop
  10246. #endif
  10247. // end catch_tostring.cpp
  10248. // start catch_totals.cpp
  10249. namespace Catch {
  10250. Counts Counts::operator - ( Counts const& other ) const {
  10251. Counts diff;
  10252. diff.passed = passed - other.passed;
  10253. diff.failed = failed - other.failed;
  10254. diff.failedButOk = failedButOk - other.failedButOk;
  10255. return diff;
  10256. }
  10257. Counts& Counts::operator += ( Counts const& other ) {
  10258. passed += other.passed;
  10259. failed += other.failed;
  10260. failedButOk += other.failedButOk;
  10261. return *this;
  10262. }
  10263. std::size_t Counts::total() const {
  10264. return passed + failed + failedButOk;
  10265. }
  10266. bool Counts::allPassed() const {
  10267. return failed == 0 && failedButOk == 0;
  10268. }
  10269. bool Counts::allOk() const {
  10270. return failed == 0;
  10271. }
  10272. Totals Totals::operator - ( Totals const& other ) const {
  10273. Totals diff;
  10274. diff.assertions = assertions - other.assertions;
  10275. diff.testCases = testCases - other.testCases;
  10276. return diff;
  10277. }
  10278. Totals& Totals::operator += ( Totals const& other ) {
  10279. assertions += other.assertions;
  10280. testCases += other.testCases;
  10281. return *this;
  10282. }
  10283. Totals Totals::delta( Totals const& prevTotals ) const {
  10284. Totals diff = *this - prevTotals;
  10285. if( diff.assertions.failed > 0 )
  10286. ++diff.testCases.failed;
  10287. else if( diff.assertions.failedButOk > 0 )
  10288. ++diff.testCases.failedButOk;
  10289. else
  10290. ++diff.testCases.passed;
  10291. return diff;
  10292. }
  10293. }
  10294. // end catch_totals.cpp
  10295. // start catch_uncaught_exceptions.cpp
  10296. #include <exception>
  10297. namespace Catch {
  10298. bool uncaught_exceptions() {
  10299. #if defined(CATCH_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS)
  10300. return std::uncaught_exceptions() > 0;
  10301. #else
  10302. return std::uncaught_exception();
  10303. #endif
  10304. }
  10305. } // end namespace Catch
  10306. // end catch_uncaught_exceptions.cpp
  10307. // start catch_version.cpp
  10308. #include <ostream>
  10309. namespace Catch {
  10310. Version::Version
  10311. ( unsigned int _majorVersion,
  10312. unsigned int _minorVersion,
  10313. unsigned int _patchNumber,
  10314. char const * const _branchName,
  10315. unsigned int _buildNumber )
  10316. : majorVersion( _majorVersion ),
  10317. minorVersion( _minorVersion ),
  10318. patchNumber( _patchNumber ),
  10319. branchName( _branchName ),
  10320. buildNumber( _buildNumber )
  10321. {}
  10322. std::ostream& operator << ( std::ostream& os, Version const& version ) {
  10323. os << version.majorVersion << '.'
  10324. << version.minorVersion << '.'
  10325. << version.patchNumber;
  10326. // branchName is never null -> 0th char is \0 if it is empty
  10327. if (version.branchName[0]) {
  10328. os << '-' << version.branchName
  10329. << '.' << version.buildNumber;
  10330. }
  10331. return os;
  10332. }
  10333. Version const& libraryVersion() {
  10334. static Version version( 2, 7, 1, "", 0 );
  10335. return version;
  10336. }
  10337. }
  10338. // end catch_version.cpp
  10339. // start catch_wildcard_pattern.cpp
  10340. #include <sstream>
  10341. namespace Catch {
  10342. WildcardPattern::WildcardPattern( std::string const& pattern,
  10343. CaseSensitive::Choice caseSensitivity )
  10344. : m_caseSensitivity( caseSensitivity ),
  10345. m_pattern( adjustCase( pattern ) )
  10346. {
  10347. if( startsWith( m_pattern, '*' ) ) {
  10348. m_pattern = m_pattern.substr( 1 );
  10349. m_wildcard = WildcardAtStart;
  10350. }
  10351. if( endsWith( m_pattern, '*' ) ) {
  10352. m_pattern = m_pattern.substr( 0, m_pattern.size()-1 );
  10353. m_wildcard = static_cast<WildcardPosition>( m_wildcard | WildcardAtEnd );
  10354. }
  10355. }
  10356. bool WildcardPattern::matches( std::string const& str ) const {
  10357. switch( m_wildcard ) {
  10358. case NoWildcard:
  10359. return m_pattern == adjustCase( str );
  10360. case WildcardAtStart:
  10361. return endsWith( adjustCase( str ), m_pattern );
  10362. case WildcardAtEnd:
  10363. return startsWith( adjustCase( str ), m_pattern );
  10364. case WildcardAtBothEnds:
  10365. return contains( adjustCase( str ), m_pattern );
  10366. default:
  10367. CATCH_INTERNAL_ERROR( "Unknown enum" );
  10368. }
  10369. }
  10370. std::string WildcardPattern::adjustCase( std::string const& str ) const {
  10371. return m_caseSensitivity == CaseSensitive::No ? toLower( str ) : str;
  10372. }
  10373. }
  10374. // end catch_wildcard_pattern.cpp
  10375. // start catch_xmlwriter.cpp
  10376. #include <iomanip>
  10377. using uchar = unsigned char;
  10378. namespace Catch {
  10379. namespace {
  10380. size_t trailingBytes(unsigned char c) {
  10381. if ((c & 0xE0) == 0xC0) {
  10382. return 2;
  10383. }
  10384. if ((c & 0xF0) == 0xE0) {
  10385. return 3;
  10386. }
  10387. if ((c & 0xF8) == 0xF0) {
  10388. return 4;
  10389. }
  10390. CATCH_INTERNAL_ERROR("Invalid multibyte utf-8 start byte encountered");
  10391. }
  10392. uint32_t headerValue(unsigned char c) {
  10393. if ((c & 0xE0) == 0xC0) {
  10394. return c & 0x1F;
  10395. }
  10396. if ((c & 0xF0) == 0xE0) {
  10397. return c & 0x0F;
  10398. }
  10399. if ((c & 0xF8) == 0xF0) {
  10400. return c & 0x07;
  10401. }
  10402. CATCH_INTERNAL_ERROR("Invalid multibyte utf-8 start byte encountered");
  10403. }
  10404. void hexEscapeChar(std::ostream& os, unsigned char c) {
  10405. std::ios_base::fmtflags f(os.flags());
  10406. os << "\\x"
  10407. << std::uppercase << std::hex << std::setfill('0') << std::setw(2)
  10408. << static_cast<int>(c);
  10409. os.flags(f);
  10410. }
  10411. } // anonymous namespace
  10412. XmlEncode::XmlEncode( std::string const& str, ForWhat forWhat )
  10413. : m_str( str ),
  10414. m_forWhat( forWhat )
  10415. {}
  10416. void XmlEncode::encodeTo( std::ostream& os ) const {
  10417. // Apostrophe escaping not necessary if we always use " to write attributes
  10418. // (see: http://www.w3.org/TR/xml/#syntax)
  10419. for( std::size_t idx = 0; idx < m_str.size(); ++ idx ) {
  10420. uchar c = m_str[idx];
  10421. switch (c) {
  10422. case '<': os << "&lt;"; break;
  10423. case '&': os << "&amp;"; break;
  10424. case '>':
  10425. // See: http://www.w3.org/TR/xml/#syntax
  10426. if (idx > 2 && m_str[idx - 1] == ']' && m_str[idx - 2] == ']')
  10427. os << "&gt;";
  10428. else
  10429. os << c;
  10430. break;
  10431. case '\"':
  10432. if (m_forWhat == ForAttributes)
  10433. os << "&quot;";
  10434. else
  10435. os << c;
  10436. break;
  10437. default:
  10438. // Check for control characters and invalid utf-8
  10439. // Escape control characters in standard ascii
  10440. // see http://stackoverflow.com/questions/404107/why-are-control-characters-illegal-in-xml-1-0
  10441. if (c < 0x09 || (c > 0x0D && c < 0x20) || c == 0x7F) {
  10442. hexEscapeChar(os, c);
  10443. break;
  10444. }
  10445. // Plain ASCII: Write it to stream
  10446. if (c < 0x7F) {
  10447. os << c;
  10448. break;
  10449. }
  10450. // UTF-8 territory
  10451. // Check if the encoding is valid and if it is not, hex escape bytes.
  10452. // Important: We do not check the exact decoded values for validity, only the encoding format
  10453. // First check that this bytes is a valid lead byte:
  10454. // This means that it is not encoded as 1111 1XXX
  10455. // Or as 10XX XXXX
  10456. if (c < 0xC0 ||
  10457. c >= 0xF8) {
  10458. hexEscapeChar(os, c);
  10459. break;
  10460. }
  10461. auto encBytes = trailingBytes(c);
  10462. // Are there enough bytes left to avoid accessing out-of-bounds memory?
  10463. if (idx + encBytes - 1 >= m_str.size()) {
  10464. hexEscapeChar(os, c);
  10465. break;
  10466. }
  10467. // The header is valid, check data
  10468. // The next encBytes bytes must together be a valid utf-8
  10469. // This means: bitpattern 10XX XXXX and the extracted value is sane (ish)
  10470. bool valid = true;
  10471. uint32_t value = headerValue(c);
  10472. for (std::size_t n = 1; n < encBytes; ++n) {
  10473. uchar nc = m_str[idx + n];
  10474. valid &= ((nc & 0xC0) == 0x80);
  10475. value = (value << 6) | (nc & 0x3F);
  10476. }
  10477. if (
  10478. // Wrong bit pattern of following bytes
  10479. (!valid) ||
  10480. // Overlong encodings
  10481. (value < 0x80) ||
  10482. (0x80 <= value && value < 0x800 && encBytes > 2) ||
  10483. (0x800 < value && value < 0x10000 && encBytes > 3) ||
  10484. // Encoded value out of range
  10485. (value >= 0x110000)
  10486. ) {
  10487. hexEscapeChar(os, c);
  10488. break;
  10489. }
  10490. // If we got here, this is in fact a valid(ish) utf-8 sequence
  10491. for (std::size_t n = 0; n < encBytes; ++n) {
  10492. os << m_str[idx + n];
  10493. }
  10494. idx += encBytes - 1;
  10495. break;
  10496. }
  10497. }
  10498. }
  10499. std::ostream& operator << ( std::ostream& os, XmlEncode const& xmlEncode ) {
  10500. xmlEncode.encodeTo( os );
  10501. return os;
  10502. }
  10503. XmlWriter::ScopedElement::ScopedElement( XmlWriter* writer )
  10504. : m_writer( writer )
  10505. {}
  10506. XmlWriter::ScopedElement::ScopedElement( ScopedElement&& other ) noexcept
  10507. : m_writer( other.m_writer ){
  10508. other.m_writer = nullptr;
  10509. }
  10510. XmlWriter::ScopedElement& XmlWriter::ScopedElement::operator=( ScopedElement&& other ) noexcept {
  10511. if ( m_writer ) {
  10512. m_writer->endElement();
  10513. }
  10514. m_writer = other.m_writer;
  10515. other.m_writer = nullptr;
  10516. return *this;
  10517. }
  10518. XmlWriter::ScopedElement::~ScopedElement() {
  10519. if( m_writer )
  10520. m_writer->endElement();
  10521. }
  10522. XmlWriter::ScopedElement& XmlWriter::ScopedElement::writeText( std::string const& text, bool indent ) {
  10523. m_writer->writeText( text, indent );
  10524. return *this;
  10525. }
  10526. XmlWriter::XmlWriter( std::ostream& os ) : m_os( os )
  10527. {
  10528. writeDeclaration();
  10529. }
  10530. XmlWriter::~XmlWriter() {
  10531. while( !m_tags.empty() )
  10532. endElement();
  10533. }
  10534. XmlWriter& XmlWriter::startElement( std::string const& name ) {
  10535. ensureTagClosed();
  10536. newlineIfNecessary();
  10537. m_os << m_indent << '<' << name;
  10538. m_tags.push_back( name );
  10539. m_indent += " ";
  10540. m_tagIsOpen = true;
  10541. return *this;
  10542. }
  10543. XmlWriter::ScopedElement XmlWriter::scopedElement( std::string const& name ) {
  10544. ScopedElement scoped( this );
  10545. startElement( name );
  10546. return scoped;
  10547. }
  10548. XmlWriter& XmlWriter::endElement() {
  10549. newlineIfNecessary();
  10550. m_indent = m_indent.substr( 0, m_indent.size()-2 );
  10551. if( m_tagIsOpen ) {
  10552. m_os << "/>";
  10553. m_tagIsOpen = false;
  10554. }
  10555. else {
  10556. m_os << m_indent << "</" << m_tags.back() << ">";
  10557. }
  10558. m_os << std::endl;
  10559. m_tags.pop_back();
  10560. return *this;
  10561. }
  10562. XmlWriter& XmlWriter::writeAttribute( std::string const& name, std::string const& attribute ) {
  10563. if( !name.empty() && !attribute.empty() )
  10564. m_os << ' ' << name << "=\"" << XmlEncode( attribute, XmlEncode::ForAttributes ) << '"';
  10565. return *this;
  10566. }
  10567. XmlWriter& XmlWriter::writeAttribute( std::string const& name, bool attribute ) {
  10568. m_os << ' ' << name << "=\"" << ( attribute ? "true" : "false" ) << '"';
  10569. return *this;
  10570. }
  10571. XmlWriter& XmlWriter::writeText( std::string const& text, bool indent ) {
  10572. if( !text.empty() ){
  10573. bool tagWasOpen = m_tagIsOpen;
  10574. ensureTagClosed();
  10575. if( tagWasOpen && indent )
  10576. m_os << m_indent;
  10577. m_os << XmlEncode( text );
  10578. m_needsNewline = true;
  10579. }
  10580. return *this;
  10581. }
  10582. XmlWriter& XmlWriter::writeComment( std::string const& text ) {
  10583. ensureTagClosed();
  10584. m_os << m_indent << "<!--" << text << "-->";
  10585. m_needsNewline = true;
  10586. return *this;
  10587. }
  10588. void XmlWriter::writeStylesheetRef( std::string const& url ) {
  10589. m_os << "<?xml-stylesheet type=\"text/xsl\" href=\"" << url << "\"?>\n";
  10590. }
  10591. XmlWriter& XmlWriter::writeBlankLine() {
  10592. ensureTagClosed();
  10593. m_os << '\n';
  10594. return *this;
  10595. }
  10596. void XmlWriter::ensureTagClosed() {
  10597. if( m_tagIsOpen ) {
  10598. m_os << ">" << std::endl;
  10599. m_tagIsOpen = false;
  10600. }
  10601. }
  10602. void XmlWriter::writeDeclaration() {
  10603. m_os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
  10604. }
  10605. void XmlWriter::newlineIfNecessary() {
  10606. if( m_needsNewline ) {
  10607. m_os << std::endl;
  10608. m_needsNewline = false;
  10609. }
  10610. }
  10611. }
  10612. // end catch_xmlwriter.cpp
  10613. // start catch_reporter_bases.cpp
  10614. #include <cstring>
  10615. #include <cfloat>
  10616. #include <cstdio>
  10617. #include <cassert>
  10618. #include <memory>
  10619. namespace Catch {
  10620. void prepareExpandedExpression(AssertionResult& result) {
  10621. result.getExpandedExpression();
  10622. }
  10623. // Because formatting using c++ streams is stateful, drop down to C is required
  10624. // Alternatively we could use stringstream, but its performance is... not good.
  10625. std::string getFormattedDuration( double duration ) {
  10626. // Max exponent + 1 is required to represent the whole part
  10627. // + 1 for decimal point
  10628. // + 3 for the 3 decimal places
  10629. // + 1 for null terminator
  10630. const std::size_t maxDoubleSize = DBL_MAX_10_EXP + 1 + 1 + 3 + 1;
  10631. char buffer[maxDoubleSize];
  10632. // Save previous errno, to prevent sprintf from overwriting it
  10633. ErrnoGuard guard;
  10634. #ifdef _MSC_VER
  10635. sprintf_s(buffer, "%.3f", duration);
  10636. #else
  10637. std::sprintf(buffer, "%.3f", duration);
  10638. #endif
  10639. return std::string(buffer);
  10640. }
  10641. std::string serializeFilters( std::vector<std::string> const& container ) {
  10642. ReusableStringStream oss;
  10643. bool first = true;
  10644. for (auto&& filter : container)
  10645. {
  10646. if (!first)
  10647. oss << ' ';
  10648. else
  10649. first = false;
  10650. oss << filter;
  10651. }
  10652. return oss.str();
  10653. }
  10654. TestEventListenerBase::TestEventListenerBase(ReporterConfig const & _config)
  10655. :StreamingReporterBase(_config) {}
  10656. std::set<Verbosity> TestEventListenerBase::getSupportedVerbosities() {
  10657. return { Verbosity::Quiet, Verbosity::Normal, Verbosity::High };
  10658. }
  10659. void TestEventListenerBase::assertionStarting(AssertionInfo const &) {}
  10660. bool TestEventListenerBase::assertionEnded(AssertionStats const &) {
  10661. return false;
  10662. }
  10663. } // end namespace Catch
  10664. // end catch_reporter_bases.cpp
  10665. // start catch_reporter_compact.cpp
  10666. namespace {
  10667. #ifdef CATCH_PLATFORM_MAC
  10668. const char* failedString() { return "FAILED"; }
  10669. const char* passedString() { return "PASSED"; }
  10670. #else
  10671. const char* failedString() { return "failed"; }
  10672. const char* passedString() { return "passed"; }
  10673. #endif
  10674. // Colour::LightGrey
  10675. Catch::Colour::Code dimColour() { return Catch::Colour::FileName; }
  10676. std::string bothOrAll( std::size_t count ) {
  10677. return count == 1 ? std::string() :
  10678. count == 2 ? "both " : "all " ;
  10679. }
  10680. } // anon namespace
  10681. namespace Catch {
  10682. namespace {
  10683. // Colour, message variants:
  10684. // - white: No tests ran.
  10685. // - red: Failed [both/all] N test cases, failed [both/all] M assertions.
  10686. // - white: Passed [both/all] N test cases (no assertions).
  10687. // - red: Failed N tests cases, failed M assertions.
  10688. // - green: Passed [both/all] N tests cases with M assertions.
  10689. void printTotals(std::ostream& out, const Totals& totals) {
  10690. if (totals.testCases.total() == 0) {
  10691. out << "No tests ran.";
  10692. } else if (totals.testCases.failed == totals.testCases.total()) {
  10693. Colour colour(Colour::ResultError);
  10694. const std::string qualify_assertions_failed =
  10695. totals.assertions.failed == totals.assertions.total() ?
  10696. bothOrAll(totals.assertions.failed) : std::string();
  10697. out <<
  10698. "Failed " << bothOrAll(totals.testCases.failed)
  10699. << pluralise(totals.testCases.failed, "test case") << ", "
  10700. "failed " << qualify_assertions_failed <<
  10701. pluralise(totals.assertions.failed, "assertion") << '.';
  10702. } else if (totals.assertions.total() == 0) {
  10703. out <<
  10704. "Passed " << bothOrAll(totals.testCases.total())
  10705. << pluralise(totals.testCases.total(), "test case")
  10706. << " (no assertions).";
  10707. } else if (totals.assertions.failed) {
  10708. Colour colour(Colour::ResultError);
  10709. out <<
  10710. "Failed " << pluralise(totals.testCases.failed, "test case") << ", "
  10711. "failed " << pluralise(totals.assertions.failed, "assertion") << '.';
  10712. } else {
  10713. Colour colour(Colour::ResultSuccess);
  10714. out <<
  10715. "Passed " << bothOrAll(totals.testCases.passed)
  10716. << pluralise(totals.testCases.passed, "test case") <<
  10717. " with " << pluralise(totals.assertions.passed, "assertion") << '.';
  10718. }
  10719. }
  10720. // Implementation of CompactReporter formatting
  10721. class AssertionPrinter {
  10722. public:
  10723. AssertionPrinter& operator= (AssertionPrinter const&) = delete;
  10724. AssertionPrinter(AssertionPrinter const&) = delete;
  10725. AssertionPrinter(std::ostream& _stream, AssertionStats const& _stats, bool _printInfoMessages)
  10726. : stream(_stream)
  10727. , result(_stats.assertionResult)
  10728. , messages(_stats.infoMessages)
  10729. , itMessage(_stats.infoMessages.begin())
  10730. , printInfoMessages(_printInfoMessages) {}
  10731. void print() {
  10732. printSourceInfo();
  10733. itMessage = messages.begin();
  10734. switch (result.getResultType()) {
  10735. case ResultWas::Ok:
  10736. printResultType(Colour::ResultSuccess, passedString());
  10737. printOriginalExpression();
  10738. printReconstructedExpression();
  10739. if (!result.hasExpression())
  10740. printRemainingMessages(Colour::None);
  10741. else
  10742. printRemainingMessages();
  10743. break;
  10744. case ResultWas::ExpressionFailed:
  10745. if (result.isOk())
  10746. printResultType(Colour::ResultSuccess, failedString() + std::string(" - but was ok"));
  10747. else
  10748. printResultType(Colour::Error, failedString());
  10749. printOriginalExpression();
  10750. printReconstructedExpression();
  10751. printRemainingMessages();
  10752. break;
  10753. case ResultWas::ThrewException:
  10754. printResultType(Colour::Error, failedString());
  10755. printIssue("unexpected exception with message:");
  10756. printMessage();
  10757. printExpressionWas();
  10758. printRemainingMessages();
  10759. break;
  10760. case ResultWas::FatalErrorCondition:
  10761. printResultType(Colour::Error, failedString());
  10762. printIssue("fatal error condition with message:");
  10763. printMessage();
  10764. printExpressionWas();
  10765. printRemainingMessages();
  10766. break;
  10767. case ResultWas::DidntThrowException:
  10768. printResultType(Colour::Error, failedString());
  10769. printIssue("expected exception, got none");
  10770. printExpressionWas();
  10771. printRemainingMessages();
  10772. break;
  10773. case ResultWas::Info:
  10774. printResultType(Colour::None, "info");
  10775. printMessage();
  10776. printRemainingMessages();
  10777. break;
  10778. case ResultWas::Warning:
  10779. printResultType(Colour::None, "warning");
  10780. printMessage();
  10781. printRemainingMessages();
  10782. break;
  10783. case ResultWas::ExplicitFailure:
  10784. printResultType(Colour::Error, failedString());
  10785. printIssue("explicitly");
  10786. printRemainingMessages(Colour::None);
  10787. break;
  10788. // These cases are here to prevent compiler warnings
  10789. case ResultWas::Unknown:
  10790. case ResultWas::FailureBit:
  10791. case ResultWas::Exception:
  10792. printResultType(Colour::Error, "** internal error **");
  10793. break;
  10794. }
  10795. }
  10796. private:
  10797. void printSourceInfo() const {
  10798. Colour colourGuard(Colour::FileName);
  10799. stream << result.getSourceInfo() << ':';
  10800. }
  10801. void printResultType(Colour::Code colour, std::string const& passOrFail) const {
  10802. if (!passOrFail.empty()) {
  10803. {
  10804. Colour colourGuard(colour);
  10805. stream << ' ' << passOrFail;
  10806. }
  10807. stream << ':';
  10808. }
  10809. }
  10810. void printIssue(std::string const& issue) const {
  10811. stream << ' ' << issue;
  10812. }
  10813. void printExpressionWas() {
  10814. if (result.hasExpression()) {
  10815. stream << ';';
  10816. {
  10817. Colour colour(dimColour());
  10818. stream << " expression was:";
  10819. }
  10820. printOriginalExpression();
  10821. }
  10822. }
  10823. void printOriginalExpression() const {
  10824. if (result.hasExpression()) {
  10825. stream << ' ' << result.getExpression();
  10826. }
  10827. }
  10828. void printReconstructedExpression() const {
  10829. if (result.hasExpandedExpression()) {
  10830. {
  10831. Colour colour(dimColour());
  10832. stream << " for: ";
  10833. }
  10834. stream << result.getExpandedExpression();
  10835. }
  10836. }
  10837. void printMessage() {
  10838. if (itMessage != messages.end()) {
  10839. stream << " '" << itMessage->message << '\'';
  10840. ++itMessage;
  10841. }
  10842. }
  10843. void printRemainingMessages(Colour::Code colour = dimColour()) {
  10844. if (itMessage == messages.end())
  10845. return;
  10846. // using messages.end() directly yields (or auto) compilation error:
  10847. std::vector<MessageInfo>::const_iterator itEnd = messages.end();
  10848. const std::size_t N = static_cast<std::size_t>(std::distance(itMessage, itEnd));
  10849. {
  10850. Colour colourGuard(colour);
  10851. stream << " with " << pluralise(N, "message") << ':';
  10852. }
  10853. for (; itMessage != itEnd; ) {
  10854. // If this assertion is a warning ignore any INFO messages
  10855. if (printInfoMessages || itMessage->type != ResultWas::Info) {
  10856. stream << " '" << itMessage->message << '\'';
  10857. if (++itMessage != itEnd) {
  10858. Colour colourGuard(dimColour());
  10859. stream << " and";
  10860. }
  10861. }
  10862. }
  10863. }
  10864. private:
  10865. std::ostream& stream;
  10866. AssertionResult const& result;
  10867. std::vector<MessageInfo> messages;
  10868. std::vector<MessageInfo>::const_iterator itMessage;
  10869. bool printInfoMessages;
  10870. };
  10871. } // anon namespace
  10872. std::string CompactReporter::getDescription() {
  10873. return "Reports test results on a single line, suitable for IDEs";
  10874. }
  10875. ReporterPreferences CompactReporter::getPreferences() const {
  10876. return m_reporterPrefs;
  10877. }
  10878. void CompactReporter::noMatchingTestCases( std::string const& spec ) {
  10879. stream << "No test cases matched '" << spec << '\'' << std::endl;
  10880. }
  10881. void CompactReporter::assertionStarting( AssertionInfo const& ) {}
  10882. bool CompactReporter::assertionEnded( AssertionStats const& _assertionStats ) {
  10883. AssertionResult const& result = _assertionStats.assertionResult;
  10884. bool printInfoMessages = true;
  10885. // Drop out if result was successful and we're not printing those
  10886. if( !m_config->includeSuccessfulResults() && result.isOk() ) {
  10887. if( result.getResultType() != ResultWas::Warning )
  10888. return false;
  10889. printInfoMessages = false;
  10890. }
  10891. AssertionPrinter printer( stream, _assertionStats, printInfoMessages );
  10892. printer.print();
  10893. stream << std::endl;
  10894. return true;
  10895. }
  10896. void CompactReporter::sectionEnded(SectionStats const& _sectionStats) {
  10897. if (m_config->showDurations() == ShowDurations::Always) {
  10898. stream << getFormattedDuration(_sectionStats.durationInSeconds) << " s: " << _sectionStats.sectionInfo.name << std::endl;
  10899. }
  10900. }
  10901. void CompactReporter::testRunEnded( TestRunStats const& _testRunStats ) {
  10902. printTotals( stream, _testRunStats.totals );
  10903. stream << '\n' << std::endl;
  10904. StreamingReporterBase::testRunEnded( _testRunStats );
  10905. }
  10906. CompactReporter::~CompactReporter() {}
  10907. CATCH_REGISTER_REPORTER( "compact", CompactReporter )
  10908. } // end namespace Catch
  10909. // end catch_reporter_compact.cpp
  10910. // start catch_reporter_console.cpp
  10911. #include <cfloat>
  10912. #include <cstdio>
  10913. #if defined(_MSC_VER)
  10914. #pragma warning(push)
  10915. #pragma warning(disable:4061) // Not all labels are EXPLICITLY handled in switch
  10916. // Note that 4062 (not all labels are handled
  10917. // and default is missing) is enabled
  10918. #endif
  10919. namespace Catch {
  10920. namespace {
  10921. // Formatter impl for ConsoleReporter
  10922. class ConsoleAssertionPrinter {
  10923. public:
  10924. ConsoleAssertionPrinter& operator= (ConsoleAssertionPrinter const&) = delete;
  10925. ConsoleAssertionPrinter(ConsoleAssertionPrinter const&) = delete;
  10926. ConsoleAssertionPrinter(std::ostream& _stream, AssertionStats const& _stats, bool _printInfoMessages)
  10927. : stream(_stream),
  10928. stats(_stats),
  10929. result(_stats.assertionResult),
  10930. colour(Colour::None),
  10931. message(result.getMessage()),
  10932. messages(_stats.infoMessages),
  10933. printInfoMessages(_printInfoMessages) {
  10934. switch (result.getResultType()) {
  10935. case ResultWas::Ok:
  10936. colour = Colour::Success;
  10937. passOrFail = "PASSED";
  10938. //if( result.hasMessage() )
  10939. if (_stats.infoMessages.size() == 1)
  10940. messageLabel = "with message";
  10941. if (_stats.infoMessages.size() > 1)
  10942. messageLabel = "with messages";
  10943. break;
  10944. case ResultWas::ExpressionFailed:
  10945. if (result.isOk()) {
  10946. colour = Colour::Success;
  10947. passOrFail = "FAILED - but was ok";
  10948. } else {
  10949. colour = Colour::Error;
  10950. passOrFail = "FAILED";
  10951. }
  10952. if (_stats.infoMessages.size() == 1)
  10953. messageLabel = "with message";
  10954. if (_stats.infoMessages.size() > 1)
  10955. messageLabel = "with messages";
  10956. break;
  10957. case ResultWas::ThrewException:
  10958. colour = Colour::Error;
  10959. passOrFail = "FAILED";
  10960. messageLabel = "due to unexpected exception with ";
  10961. if (_stats.infoMessages.size() == 1)
  10962. messageLabel += "message";
  10963. if (_stats.infoMessages.size() > 1)
  10964. messageLabel += "messages";
  10965. break;
  10966. case ResultWas::FatalErrorCondition:
  10967. colour = Colour::Error;
  10968. passOrFail = "FAILED";
  10969. messageLabel = "due to a fatal error condition";
  10970. break;
  10971. case ResultWas::DidntThrowException:
  10972. colour = Colour::Error;
  10973. passOrFail = "FAILED";
  10974. messageLabel = "because no exception was thrown where one was expected";
  10975. break;
  10976. case ResultWas::Info:
  10977. messageLabel = "info";
  10978. break;
  10979. case ResultWas::Warning:
  10980. messageLabel = "warning";
  10981. break;
  10982. case ResultWas::ExplicitFailure:
  10983. passOrFail = "FAILED";
  10984. colour = Colour::Error;
  10985. if (_stats.infoMessages.size() == 1)
  10986. messageLabel = "explicitly with message";
  10987. if (_stats.infoMessages.size() > 1)
  10988. messageLabel = "explicitly with messages";
  10989. break;
  10990. // These cases are here to prevent compiler warnings
  10991. case ResultWas::Unknown:
  10992. case ResultWas::FailureBit:
  10993. case ResultWas::Exception:
  10994. passOrFail = "** internal error **";
  10995. colour = Colour::Error;
  10996. break;
  10997. }
  10998. }
  10999. void print() const {
  11000. printSourceInfo();
  11001. if (stats.totals.assertions.total() > 0) {
  11002. printResultType();
  11003. printOriginalExpression();
  11004. printReconstructedExpression();
  11005. } else {
  11006. stream << '\n';
  11007. }
  11008. printMessage();
  11009. }
  11010. private:
  11011. void printResultType() const {
  11012. if (!passOrFail.empty()) {
  11013. Colour colourGuard(colour);
  11014. stream << passOrFail << ":\n";
  11015. }
  11016. }
  11017. void printOriginalExpression() const {
  11018. if (result.hasExpression()) {
  11019. Colour colourGuard(Colour::OriginalExpression);
  11020. stream << " ";
  11021. stream << result.getExpressionInMacro();
  11022. stream << '\n';
  11023. }
  11024. }
  11025. void printReconstructedExpression() const {
  11026. if (result.hasExpandedExpression()) {
  11027. stream << "with expansion:\n";
  11028. Colour colourGuard(Colour::ReconstructedExpression);
  11029. stream << Column(result.getExpandedExpression()).indent(2) << '\n';
  11030. }
  11031. }
  11032. void printMessage() const {
  11033. if (!messageLabel.empty())
  11034. stream << messageLabel << ':' << '\n';
  11035. for (auto const& msg : messages) {
  11036. // If this assertion is a warning ignore any INFO messages
  11037. if (printInfoMessages || msg.type != ResultWas::Info)
  11038. stream << Column(msg.message).indent(2) << '\n';
  11039. }
  11040. }
  11041. void printSourceInfo() const {
  11042. Colour colourGuard(Colour::FileName);
  11043. stream << result.getSourceInfo() << ": ";
  11044. }
  11045. std::ostream& stream;
  11046. AssertionStats const& stats;
  11047. AssertionResult const& result;
  11048. Colour::Code colour;
  11049. std::string passOrFail;
  11050. std::string messageLabel;
  11051. std::string message;
  11052. std::vector<MessageInfo> messages;
  11053. bool printInfoMessages;
  11054. };
  11055. std::size_t makeRatio(std::size_t number, std::size_t total) {
  11056. std::size_t ratio = total > 0 ? CATCH_CONFIG_CONSOLE_WIDTH * number / total : 0;
  11057. return (ratio == 0 && number > 0) ? 1 : ratio;
  11058. }
  11059. std::size_t& findMax(std::size_t& i, std::size_t& j, std::size_t& k) {
  11060. if (i > j && i > k)
  11061. return i;
  11062. else if (j > k)
  11063. return j;
  11064. else
  11065. return k;
  11066. }
  11067. struct ColumnInfo {
  11068. enum Justification { Left, Right };
  11069. std::string name;
  11070. int width;
  11071. Justification justification;
  11072. };
  11073. struct ColumnBreak {};
  11074. struct RowBreak {};
  11075. class Duration {
  11076. enum class Unit {
  11077. Auto,
  11078. Nanoseconds,
  11079. Microseconds,
  11080. Milliseconds,
  11081. Seconds,
  11082. Minutes
  11083. };
  11084. static const uint64_t s_nanosecondsInAMicrosecond = 1000;
  11085. static const uint64_t s_nanosecondsInAMillisecond = 1000 * s_nanosecondsInAMicrosecond;
  11086. static const uint64_t s_nanosecondsInASecond = 1000 * s_nanosecondsInAMillisecond;
  11087. static const uint64_t s_nanosecondsInAMinute = 60 * s_nanosecondsInASecond;
  11088. uint64_t m_inNanoseconds;
  11089. Unit m_units;
  11090. public:
  11091. explicit Duration(uint64_t inNanoseconds, Unit units = Unit::Auto)
  11092. : m_inNanoseconds(inNanoseconds),
  11093. m_units(units) {
  11094. if (m_units == Unit::Auto) {
  11095. if (m_inNanoseconds < s_nanosecondsInAMicrosecond)
  11096. m_units = Unit::Nanoseconds;
  11097. else if (m_inNanoseconds < s_nanosecondsInAMillisecond)
  11098. m_units = Unit::Microseconds;
  11099. else if (m_inNanoseconds < s_nanosecondsInASecond)
  11100. m_units = Unit::Milliseconds;
  11101. else if (m_inNanoseconds < s_nanosecondsInAMinute)
  11102. m_units = Unit::Seconds;
  11103. else
  11104. m_units = Unit::Minutes;
  11105. }
  11106. }
  11107. auto value() const -> double {
  11108. switch (m_units) {
  11109. case Unit::Microseconds:
  11110. return m_inNanoseconds / static_cast<double>(s_nanosecondsInAMicrosecond);
  11111. case Unit::Milliseconds:
  11112. return m_inNanoseconds / static_cast<double>(s_nanosecondsInAMillisecond);
  11113. case Unit::Seconds:
  11114. return m_inNanoseconds / static_cast<double>(s_nanosecondsInASecond);
  11115. case Unit::Minutes:
  11116. return m_inNanoseconds / static_cast<double>(s_nanosecondsInAMinute);
  11117. default:
  11118. return static_cast<double>(m_inNanoseconds);
  11119. }
  11120. }
  11121. auto unitsAsString() const -> std::string {
  11122. switch (m_units) {
  11123. case Unit::Nanoseconds:
  11124. return "ns";
  11125. case Unit::Microseconds:
  11126. return "us";
  11127. case Unit::Milliseconds:
  11128. return "ms";
  11129. case Unit::Seconds:
  11130. return "s";
  11131. case Unit::Minutes:
  11132. return "m";
  11133. default:
  11134. return "** internal error **";
  11135. }
  11136. }
  11137. friend auto operator << (std::ostream& os, Duration const& duration) -> std::ostream& {
  11138. return os << duration.value() << " " << duration.unitsAsString();
  11139. }
  11140. };
  11141. } // end anon namespace
  11142. class TablePrinter {
  11143. std::ostream& m_os;
  11144. std::vector<ColumnInfo> m_columnInfos;
  11145. std::ostringstream m_oss;
  11146. int m_currentColumn = -1;
  11147. bool m_isOpen = false;
  11148. public:
  11149. TablePrinter( std::ostream& os, std::vector<ColumnInfo> columnInfos )
  11150. : m_os( os ),
  11151. m_columnInfos( std::move( columnInfos ) ) {}
  11152. auto columnInfos() const -> std::vector<ColumnInfo> const& {
  11153. return m_columnInfos;
  11154. }
  11155. void open() {
  11156. if (!m_isOpen) {
  11157. m_isOpen = true;
  11158. *this << RowBreak();
  11159. for (auto const& info : m_columnInfos)
  11160. *this << info.name << ColumnBreak();
  11161. *this << RowBreak();
  11162. m_os << Catch::getLineOfChars<'-'>() << "\n";
  11163. }
  11164. }
  11165. void close() {
  11166. if (m_isOpen) {
  11167. *this << RowBreak();
  11168. m_os << std::endl;
  11169. m_isOpen = false;
  11170. }
  11171. }
  11172. template<typename T>
  11173. friend TablePrinter& operator << (TablePrinter& tp, T const& value) {
  11174. tp.m_oss << value;
  11175. return tp;
  11176. }
  11177. friend TablePrinter& operator << (TablePrinter& tp, ColumnBreak) {
  11178. auto colStr = tp.m_oss.str();
  11179. // This takes account of utf8 encodings
  11180. auto strSize = Catch::StringRef(colStr).numberOfCharacters();
  11181. tp.m_oss.str("");
  11182. tp.open();
  11183. if (tp.m_currentColumn == static_cast<int>(tp.m_columnInfos.size() - 1)) {
  11184. tp.m_currentColumn = -1;
  11185. tp.m_os << "\n";
  11186. }
  11187. tp.m_currentColumn++;
  11188. auto colInfo = tp.m_columnInfos[tp.m_currentColumn];
  11189. auto padding = (strSize + 2 < static_cast<std::size_t>(colInfo.width))
  11190. ? std::string(colInfo.width - (strSize + 2), ' ')
  11191. : std::string();
  11192. if (colInfo.justification == ColumnInfo::Left)
  11193. tp.m_os << colStr << padding << " ";
  11194. else
  11195. tp.m_os << padding << colStr << " ";
  11196. return tp;
  11197. }
  11198. friend TablePrinter& operator << (TablePrinter& tp, RowBreak) {
  11199. if (tp.m_currentColumn > 0) {
  11200. tp.m_os << "\n";
  11201. tp.m_currentColumn = -1;
  11202. }
  11203. return tp;
  11204. }
  11205. };
  11206. ConsoleReporter::ConsoleReporter(ReporterConfig const& config)
  11207. : StreamingReporterBase(config),
  11208. m_tablePrinter(new TablePrinter(config.stream(),
  11209. {
  11210. { "benchmark name", CATCH_CONFIG_CONSOLE_WIDTH - 32, ColumnInfo::Left },
  11211. { "iters", 8, ColumnInfo::Right },
  11212. { "elapsed ns", 14, ColumnInfo::Right },
  11213. { "average", 14, ColumnInfo::Right }
  11214. })) {}
  11215. ConsoleReporter::~ConsoleReporter() = default;
  11216. std::string ConsoleReporter::getDescription() {
  11217. return "Reports test results as plain lines of text";
  11218. }
  11219. void ConsoleReporter::noMatchingTestCases(std::string const& spec) {
  11220. stream << "No test cases matched '" << spec << '\'' << std::endl;
  11221. }
  11222. void ConsoleReporter::assertionStarting(AssertionInfo const&) {}
  11223. bool ConsoleReporter::assertionEnded(AssertionStats const& _assertionStats) {
  11224. AssertionResult const& result = _assertionStats.assertionResult;
  11225. bool includeResults = m_config->includeSuccessfulResults() || !result.isOk();
  11226. // Drop out if result was successful but we're not printing them.
  11227. if (!includeResults && result.getResultType() != ResultWas::Warning)
  11228. return false;
  11229. lazyPrint();
  11230. ConsoleAssertionPrinter printer(stream, _assertionStats, includeResults);
  11231. printer.print();
  11232. stream << std::endl;
  11233. return true;
  11234. }
  11235. void ConsoleReporter::sectionStarting(SectionInfo const& _sectionInfo) {
  11236. m_headerPrinted = false;
  11237. StreamingReporterBase::sectionStarting(_sectionInfo);
  11238. }
  11239. void ConsoleReporter::sectionEnded(SectionStats const& _sectionStats) {
  11240. m_tablePrinter->close();
  11241. if (_sectionStats.missingAssertions) {
  11242. lazyPrint();
  11243. Colour colour(Colour::ResultError);
  11244. if (m_sectionStack.size() > 1)
  11245. stream << "\nNo assertions in section";
  11246. else
  11247. stream << "\nNo assertions in test case";
  11248. stream << " '" << _sectionStats.sectionInfo.name << "'\n" << std::endl;
  11249. }
  11250. if (m_config->showDurations() == ShowDurations::Always) {
  11251. stream << getFormattedDuration(_sectionStats.durationInSeconds) << " s: " << _sectionStats.sectionInfo.name << std::endl;
  11252. }
  11253. if (m_headerPrinted) {
  11254. m_headerPrinted = false;
  11255. }
  11256. StreamingReporterBase::sectionEnded(_sectionStats);
  11257. }
  11258. void ConsoleReporter::benchmarkStarting(BenchmarkInfo const& info) {
  11259. lazyPrintWithoutClosingBenchmarkTable();
  11260. auto nameCol = Column( info.name ).width( static_cast<std::size_t>( m_tablePrinter->columnInfos()[0].width - 2 ) );
  11261. bool firstLine = true;
  11262. for (auto line : nameCol) {
  11263. if (!firstLine)
  11264. (*m_tablePrinter) << ColumnBreak() << ColumnBreak() << ColumnBreak();
  11265. else
  11266. firstLine = false;
  11267. (*m_tablePrinter) << line << ColumnBreak();
  11268. }
  11269. }
  11270. void ConsoleReporter::benchmarkEnded(BenchmarkStats const& stats) {
  11271. Duration average(stats.elapsedTimeInNanoseconds / stats.iterations);
  11272. (*m_tablePrinter)
  11273. << stats.iterations << ColumnBreak()
  11274. << stats.elapsedTimeInNanoseconds << ColumnBreak()
  11275. << average << ColumnBreak();
  11276. }
  11277. void ConsoleReporter::testCaseEnded(TestCaseStats const& _testCaseStats) {
  11278. m_tablePrinter->close();
  11279. StreamingReporterBase::testCaseEnded(_testCaseStats);
  11280. m_headerPrinted = false;
  11281. }
  11282. void ConsoleReporter::testGroupEnded(TestGroupStats const& _testGroupStats) {
  11283. if (currentGroupInfo.used) {
  11284. printSummaryDivider();
  11285. stream << "Summary for group '" << _testGroupStats.groupInfo.name << "':\n";
  11286. printTotals(_testGroupStats.totals);
  11287. stream << '\n' << std::endl;
  11288. }
  11289. StreamingReporterBase::testGroupEnded(_testGroupStats);
  11290. }
  11291. void ConsoleReporter::testRunEnded(TestRunStats const& _testRunStats) {
  11292. printTotalsDivider(_testRunStats.totals);
  11293. printTotals(_testRunStats.totals);
  11294. stream << std::endl;
  11295. StreamingReporterBase::testRunEnded(_testRunStats);
  11296. }
  11297. void ConsoleReporter::testRunStarting(TestRunInfo const& _testInfo) {
  11298. StreamingReporterBase::testRunStarting(_testInfo);
  11299. printTestFilters();
  11300. }
  11301. void ConsoleReporter::lazyPrint() {
  11302. m_tablePrinter->close();
  11303. lazyPrintWithoutClosingBenchmarkTable();
  11304. }
  11305. void ConsoleReporter::lazyPrintWithoutClosingBenchmarkTable() {
  11306. if (!currentTestRunInfo.used)
  11307. lazyPrintRunInfo();
  11308. if (!currentGroupInfo.used)
  11309. lazyPrintGroupInfo();
  11310. if (!m_headerPrinted) {
  11311. printTestCaseAndSectionHeader();
  11312. m_headerPrinted = true;
  11313. }
  11314. }
  11315. void ConsoleReporter::lazyPrintRunInfo() {
  11316. stream << '\n' << getLineOfChars<'~'>() << '\n';
  11317. Colour colour(Colour::SecondaryText);
  11318. stream << currentTestRunInfo->name
  11319. << " is a Catch v" << libraryVersion() << " host application.\n"
  11320. << "Run with -? for options\n\n";
  11321. if (m_config->rngSeed() != 0)
  11322. stream << "Randomness seeded to: " << m_config->rngSeed() << "\n\n";
  11323. currentTestRunInfo.used = true;
  11324. }
  11325. void ConsoleReporter::lazyPrintGroupInfo() {
  11326. if (!currentGroupInfo->name.empty() && currentGroupInfo->groupsCounts > 1) {
  11327. printClosedHeader("Group: " + currentGroupInfo->name);
  11328. currentGroupInfo.used = true;
  11329. }
  11330. }
  11331. void ConsoleReporter::printTestCaseAndSectionHeader() {
  11332. assert(!m_sectionStack.empty());
  11333. printOpenHeader(currentTestCaseInfo->name);
  11334. if (m_sectionStack.size() > 1) {
  11335. Colour colourGuard(Colour::Headers);
  11336. auto
  11337. it = m_sectionStack.begin() + 1, // Skip first section (test case)
  11338. itEnd = m_sectionStack.end();
  11339. for (; it != itEnd; ++it)
  11340. printHeaderString(it->name, 2);
  11341. }
  11342. SourceLineInfo lineInfo = m_sectionStack.back().lineInfo;
  11343. if (!lineInfo.empty()) {
  11344. stream << getLineOfChars<'-'>() << '\n';
  11345. Colour colourGuard(Colour::FileName);
  11346. stream << lineInfo << '\n';
  11347. }
  11348. stream << getLineOfChars<'.'>() << '\n' << std::endl;
  11349. }
  11350. void ConsoleReporter::printClosedHeader(std::string const& _name) {
  11351. printOpenHeader(_name);
  11352. stream << getLineOfChars<'.'>() << '\n';
  11353. }
  11354. void ConsoleReporter::printOpenHeader(std::string const& _name) {
  11355. stream << getLineOfChars<'-'>() << '\n';
  11356. {
  11357. Colour colourGuard(Colour::Headers);
  11358. printHeaderString(_name);
  11359. }
  11360. }
  11361. // if string has a : in first line will set indent to follow it on
  11362. // subsequent lines
  11363. void ConsoleReporter::printHeaderString(std::string const& _string, std::size_t indent) {
  11364. std::size_t i = _string.find(": ");
  11365. if (i != std::string::npos)
  11366. i += 2;
  11367. else
  11368. i = 0;
  11369. stream << Column(_string).indent(indent + i).initialIndent(indent) << '\n';
  11370. }
  11371. struct SummaryColumn {
  11372. SummaryColumn( std::string _label, Colour::Code _colour )
  11373. : label( std::move( _label ) ),
  11374. colour( _colour ) {}
  11375. SummaryColumn addRow( std::size_t count ) {
  11376. ReusableStringStream rss;
  11377. rss << count;
  11378. std::string row = rss.str();
  11379. for (auto& oldRow : rows) {
  11380. while (oldRow.size() < row.size())
  11381. oldRow = ' ' + oldRow;
  11382. while (oldRow.size() > row.size())
  11383. row = ' ' + row;
  11384. }
  11385. rows.push_back(row);
  11386. return *this;
  11387. }
  11388. std::string label;
  11389. Colour::Code colour;
  11390. std::vector<std::string> rows;
  11391. };
  11392. void ConsoleReporter::printTotals( Totals const& totals ) {
  11393. if (totals.testCases.total() == 0) {
  11394. stream << Colour(Colour::Warning) << "No tests ran\n";
  11395. } else if (totals.assertions.total() > 0 && totals.testCases.allPassed()) {
  11396. stream << Colour(Colour::ResultSuccess) << "All tests passed";
  11397. stream << " ("
  11398. << pluralise(totals.assertions.passed, "assertion") << " in "
  11399. << pluralise(totals.testCases.passed, "test case") << ')'
  11400. << '\n';
  11401. } else {
  11402. std::vector<SummaryColumn> columns;
  11403. columns.push_back(SummaryColumn("", Colour::None)
  11404. .addRow(totals.testCases.total())
  11405. .addRow(totals.assertions.total()));
  11406. columns.push_back(SummaryColumn("passed", Colour::Success)
  11407. .addRow(totals.testCases.passed)
  11408. .addRow(totals.assertions.passed));
  11409. columns.push_back(SummaryColumn("failed", Colour::ResultError)
  11410. .addRow(totals.testCases.failed)
  11411. .addRow(totals.assertions.failed));
  11412. columns.push_back(SummaryColumn("failed as expected", Colour::ResultExpectedFailure)
  11413. .addRow(totals.testCases.failedButOk)
  11414. .addRow(totals.assertions.failedButOk));
  11415. printSummaryRow("test cases", columns, 0);
  11416. printSummaryRow("assertions", columns, 1);
  11417. }
  11418. }
  11419. void ConsoleReporter::printSummaryRow(std::string const& label, std::vector<SummaryColumn> const& cols, std::size_t row) {
  11420. for (auto col : cols) {
  11421. std::string value = col.rows[row];
  11422. if (col.label.empty()) {
  11423. stream << label << ": ";
  11424. if (value != "0")
  11425. stream << value;
  11426. else
  11427. stream << Colour(Colour::Warning) << "- none -";
  11428. } else if (value != "0") {
  11429. stream << Colour(Colour::LightGrey) << " | ";
  11430. stream << Colour(col.colour)
  11431. << value << ' ' << col.label;
  11432. }
  11433. }
  11434. stream << '\n';
  11435. }
  11436. void ConsoleReporter::printTotalsDivider(Totals const& totals) {
  11437. if (totals.testCases.total() > 0) {
  11438. std::size_t failedRatio = makeRatio(totals.testCases.failed, totals.testCases.total());
  11439. std::size_t failedButOkRatio = makeRatio(totals.testCases.failedButOk, totals.testCases.total());
  11440. std::size_t passedRatio = makeRatio(totals.testCases.passed, totals.testCases.total());
  11441. while (failedRatio + failedButOkRatio + passedRatio < CATCH_CONFIG_CONSOLE_WIDTH - 1)
  11442. findMax(failedRatio, failedButOkRatio, passedRatio)++;
  11443. while (failedRatio + failedButOkRatio + passedRatio > CATCH_CONFIG_CONSOLE_WIDTH - 1)
  11444. findMax(failedRatio, failedButOkRatio, passedRatio)--;
  11445. stream << Colour(Colour::Error) << std::string(failedRatio, '=');
  11446. stream << Colour(Colour::ResultExpectedFailure) << std::string(failedButOkRatio, '=');
  11447. if (totals.testCases.allPassed())
  11448. stream << Colour(Colour::ResultSuccess) << std::string(passedRatio, '=');
  11449. else
  11450. stream << Colour(Colour::Success) << std::string(passedRatio, '=');
  11451. } else {
  11452. stream << Colour(Colour::Warning) << std::string(CATCH_CONFIG_CONSOLE_WIDTH - 1, '=');
  11453. }
  11454. stream << '\n';
  11455. }
  11456. void ConsoleReporter::printSummaryDivider() {
  11457. stream << getLineOfChars<'-'>() << '\n';
  11458. }
  11459. void ConsoleReporter::printTestFilters() {
  11460. if (m_config->testSpec().hasFilters())
  11461. stream << Colour(Colour::BrightYellow) << "Filters: " << serializeFilters( m_config->getTestsOrTags() ) << '\n';
  11462. }
  11463. CATCH_REGISTER_REPORTER("console", ConsoleReporter)
  11464. } // end namespace Catch
  11465. #if defined(_MSC_VER)
  11466. #pragma warning(pop)
  11467. #endif
  11468. // end catch_reporter_console.cpp
  11469. // start catch_reporter_junit.cpp
  11470. #include <cassert>
  11471. #include <sstream>
  11472. #include <ctime>
  11473. #include <algorithm>
  11474. namespace Catch {
  11475. namespace {
  11476. std::string getCurrentTimestamp() {
  11477. // Beware, this is not reentrant because of backward compatibility issues
  11478. // Also, UTC only, again because of backward compatibility (%z is C++11)
  11479. time_t rawtime;
  11480. std::time(&rawtime);
  11481. auto const timeStampSize = sizeof("2017-01-16T17:06:45Z");
  11482. #ifdef _MSC_VER
  11483. std::tm timeInfo = {};
  11484. gmtime_s(&timeInfo, &rawtime);
  11485. #else
  11486. std::tm* timeInfo;
  11487. timeInfo = std::gmtime(&rawtime);
  11488. #endif
  11489. char timeStamp[timeStampSize];
  11490. const char * const fmt = "%Y-%m-%dT%H:%M:%SZ";
  11491. #ifdef _MSC_VER
  11492. std::strftime(timeStamp, timeStampSize, fmt, &timeInfo);
  11493. #else
  11494. std::strftime(timeStamp, timeStampSize, fmt, timeInfo);
  11495. #endif
  11496. return std::string(timeStamp);
  11497. }
  11498. std::string fileNameTag(const std::vector<std::string> &tags) {
  11499. auto it = std::find_if(begin(tags),
  11500. end(tags),
  11501. [] (std::string const& tag) {return tag.front() == '#'; });
  11502. if (it != tags.end())
  11503. return it->substr(1);
  11504. return std::string();
  11505. }
  11506. } // anonymous namespace
  11507. JunitReporter::JunitReporter( ReporterConfig const& _config )
  11508. : CumulativeReporterBase( _config ),
  11509. xml( _config.stream() )
  11510. {
  11511. m_reporterPrefs.shouldRedirectStdOut = true;
  11512. m_reporterPrefs.shouldReportAllAssertions = true;
  11513. }
  11514. JunitReporter::~JunitReporter() {}
  11515. std::string JunitReporter::getDescription() {
  11516. return "Reports test results in an XML format that looks like Ant's junitreport target";
  11517. }
  11518. void JunitReporter::noMatchingTestCases( std::string const& /*spec*/ ) {}
  11519. void JunitReporter::testRunStarting( TestRunInfo const& runInfo ) {
  11520. CumulativeReporterBase::testRunStarting( runInfo );
  11521. xml.startElement( "testsuites" );
  11522. if ( m_config->hasTestFilters() || m_config->rngSeed() != 0 )
  11523. xml.startElement("properties");
  11524. if ( m_config->hasTestFilters() ) {
  11525. xml.scopedElement( "property" )
  11526. .writeAttribute( "name" , "filters" )
  11527. .writeAttribute( "value" , serializeFilters( m_config->getTestsOrTags() ) );
  11528. }
  11529. if( m_config->rngSeed() != 0 ) {
  11530. xml.scopedElement( "property" )
  11531. .writeAttribute( "name", "random-seed" )
  11532. .writeAttribute( "value", m_config->rngSeed() );
  11533. xml.endElement();
  11534. }
  11535. }
  11536. void JunitReporter::testGroupStarting( GroupInfo const& groupInfo ) {
  11537. suiteTimer.start();
  11538. stdOutForSuite.clear();
  11539. stdErrForSuite.clear();
  11540. unexpectedExceptions = 0;
  11541. CumulativeReporterBase::testGroupStarting( groupInfo );
  11542. }
  11543. void JunitReporter::testCaseStarting( TestCaseInfo const& testCaseInfo ) {
  11544. m_okToFail = testCaseInfo.okToFail();
  11545. }
  11546. bool JunitReporter::assertionEnded( AssertionStats const& assertionStats ) {
  11547. if( assertionStats.assertionResult.getResultType() == ResultWas::ThrewException && !m_okToFail )
  11548. unexpectedExceptions++;
  11549. return CumulativeReporterBase::assertionEnded( assertionStats );
  11550. }
  11551. void JunitReporter::testCaseEnded( TestCaseStats const& testCaseStats ) {
  11552. stdOutForSuite += testCaseStats.stdOut;
  11553. stdErrForSuite += testCaseStats.stdErr;
  11554. CumulativeReporterBase::testCaseEnded( testCaseStats );
  11555. }
  11556. void JunitReporter::testGroupEnded( TestGroupStats const& testGroupStats ) {
  11557. double suiteTime = suiteTimer.getElapsedSeconds();
  11558. CumulativeReporterBase::testGroupEnded( testGroupStats );
  11559. writeGroup( *m_testGroups.back(), suiteTime );
  11560. }
  11561. void JunitReporter::testRunEndedCumulative() {
  11562. xml.endElement();
  11563. }
  11564. void JunitReporter::writeGroup( TestGroupNode const& groupNode, double suiteTime ) {
  11565. XmlWriter::ScopedElement e = xml.scopedElement( "testsuite" );
  11566. TestGroupStats const& stats = groupNode.value;
  11567. xml.writeAttribute( "name", stats.groupInfo.name );
  11568. xml.writeAttribute( "errors", unexpectedExceptions );
  11569. xml.writeAttribute( "failures", stats.totals.assertions.failed-unexpectedExceptions );
  11570. xml.writeAttribute( "tests", stats.totals.assertions.total() );
  11571. xml.writeAttribute( "hostname", "tbd" ); // !TBD
  11572. if( m_config->showDurations() == ShowDurations::Never )
  11573. xml.writeAttribute( "time", "" );
  11574. else
  11575. xml.writeAttribute( "time", suiteTime );
  11576. xml.writeAttribute( "timestamp", getCurrentTimestamp() );
  11577. // Write test cases
  11578. for( auto const& child : groupNode.children )
  11579. writeTestCase( *child );
  11580. xml.scopedElement( "system-out" ).writeText( trim( stdOutForSuite ), false );
  11581. xml.scopedElement( "system-err" ).writeText( trim( stdErrForSuite ), false );
  11582. }
  11583. void JunitReporter::writeTestCase( TestCaseNode const& testCaseNode ) {
  11584. TestCaseStats const& stats = testCaseNode.value;
  11585. // All test cases have exactly one section - which represents the
  11586. // test case itself. That section may have 0-n nested sections
  11587. assert( testCaseNode.children.size() == 1 );
  11588. SectionNode const& rootSection = *testCaseNode.children.front();
  11589. std::string className = stats.testInfo.className;
  11590. if( className.empty() ) {
  11591. className = fileNameTag(stats.testInfo.tags);
  11592. if ( className.empty() )
  11593. className = "global";
  11594. }
  11595. if ( !m_config->name().empty() )
  11596. className = m_config->name() + "." + className;
  11597. writeSection( className, "", rootSection );
  11598. }
  11599. void JunitReporter::writeSection( std::string const& className,
  11600. std::string const& rootName,
  11601. SectionNode const& sectionNode ) {
  11602. std::string name = trim( sectionNode.stats.sectionInfo.name );
  11603. if( !rootName.empty() )
  11604. name = rootName + '/' + name;
  11605. if( !sectionNode.assertions.empty() ||
  11606. !sectionNode.stdOut.empty() ||
  11607. !sectionNode.stdErr.empty() ) {
  11608. XmlWriter::ScopedElement e = xml.scopedElement( "testcase" );
  11609. if( className.empty() ) {
  11610. xml.writeAttribute( "classname", name );
  11611. xml.writeAttribute( "name", "root" );
  11612. }
  11613. else {
  11614. xml.writeAttribute( "classname", className );
  11615. xml.writeAttribute( "name", name );
  11616. }
  11617. xml.writeAttribute( "time", ::Catch::Detail::stringify( sectionNode.stats.durationInSeconds ) );
  11618. writeAssertions( sectionNode );
  11619. if( !sectionNode.stdOut.empty() )
  11620. xml.scopedElement( "system-out" ).writeText( trim( sectionNode.stdOut ), false );
  11621. if( !sectionNode.stdErr.empty() )
  11622. xml.scopedElement( "system-err" ).writeText( trim( sectionNode.stdErr ), false );
  11623. }
  11624. for( auto const& childNode : sectionNode.childSections )
  11625. if( className.empty() )
  11626. writeSection( name, "", *childNode );
  11627. else
  11628. writeSection( className, name, *childNode );
  11629. }
  11630. void JunitReporter::writeAssertions( SectionNode const& sectionNode ) {
  11631. for( auto const& assertion : sectionNode.assertions )
  11632. writeAssertion( assertion );
  11633. }
  11634. void JunitReporter::writeAssertion( AssertionStats const& stats ) {
  11635. AssertionResult const& result = stats.assertionResult;
  11636. if( !result.isOk() ) {
  11637. std::string elementName;
  11638. switch( result.getResultType() ) {
  11639. case ResultWas::ThrewException:
  11640. case ResultWas::FatalErrorCondition:
  11641. elementName = "error";
  11642. break;
  11643. case ResultWas::ExplicitFailure:
  11644. elementName = "failure";
  11645. break;
  11646. case ResultWas::ExpressionFailed:
  11647. elementName = "failure";
  11648. break;
  11649. case ResultWas::DidntThrowException:
  11650. elementName = "failure";
  11651. break;
  11652. // We should never see these here:
  11653. case ResultWas::Info:
  11654. case ResultWas::Warning:
  11655. case ResultWas::Ok:
  11656. case ResultWas::Unknown:
  11657. case ResultWas::FailureBit:
  11658. case ResultWas::Exception:
  11659. elementName = "internalError";
  11660. break;
  11661. }
  11662. XmlWriter::ScopedElement e = xml.scopedElement( elementName );
  11663. xml.writeAttribute( "message", result.getExpandedExpression() );
  11664. xml.writeAttribute( "type", result.getTestMacroName() );
  11665. ReusableStringStream rss;
  11666. if( !result.getMessage().empty() )
  11667. rss << result.getMessage() << '\n';
  11668. for( auto const& msg : stats.infoMessages )
  11669. if( msg.type == ResultWas::Info )
  11670. rss << msg.message << '\n';
  11671. rss << "at " << result.getSourceInfo();
  11672. xml.writeText( rss.str(), false );
  11673. }
  11674. }
  11675. CATCH_REGISTER_REPORTER( "junit", JunitReporter )
  11676. } // end namespace Catch
  11677. // end catch_reporter_junit.cpp
  11678. // start catch_reporter_listening.cpp
  11679. #include <cassert>
  11680. namespace Catch {
  11681. ListeningReporter::ListeningReporter() {
  11682. // We will assume that listeners will always want all assertions
  11683. m_preferences.shouldReportAllAssertions = true;
  11684. }
  11685. void ListeningReporter::addListener( IStreamingReporterPtr&& listener ) {
  11686. m_listeners.push_back( std::move( listener ) );
  11687. }
  11688. void ListeningReporter::addReporter(IStreamingReporterPtr&& reporter) {
  11689. assert(!m_reporter && "Listening reporter can wrap only 1 real reporter");
  11690. m_reporter = std::move( reporter );
  11691. m_preferences.shouldRedirectStdOut = m_reporter->getPreferences().shouldRedirectStdOut;
  11692. }
  11693. ReporterPreferences ListeningReporter::getPreferences() const {
  11694. return m_preferences;
  11695. }
  11696. std::set<Verbosity> ListeningReporter::getSupportedVerbosities() {
  11697. return std::set<Verbosity>{ };
  11698. }
  11699. void ListeningReporter::noMatchingTestCases( std::string const& spec ) {
  11700. for ( auto const& listener : m_listeners ) {
  11701. listener->noMatchingTestCases( spec );
  11702. }
  11703. m_reporter->noMatchingTestCases( spec );
  11704. }
  11705. void ListeningReporter::benchmarkStarting( BenchmarkInfo const& benchmarkInfo ) {
  11706. for ( auto const& listener : m_listeners ) {
  11707. listener->benchmarkStarting( benchmarkInfo );
  11708. }
  11709. m_reporter->benchmarkStarting( benchmarkInfo );
  11710. }
  11711. void ListeningReporter::benchmarkEnded( BenchmarkStats const& benchmarkStats ) {
  11712. for ( auto const& listener : m_listeners ) {
  11713. listener->benchmarkEnded( benchmarkStats );
  11714. }
  11715. m_reporter->benchmarkEnded( benchmarkStats );
  11716. }
  11717. void ListeningReporter::testRunStarting( TestRunInfo const& testRunInfo ) {
  11718. for ( auto const& listener : m_listeners ) {
  11719. listener->testRunStarting( testRunInfo );
  11720. }
  11721. m_reporter->testRunStarting( testRunInfo );
  11722. }
  11723. void ListeningReporter::testGroupStarting( GroupInfo const& groupInfo ) {
  11724. for ( auto const& listener : m_listeners ) {
  11725. listener->testGroupStarting( groupInfo );
  11726. }
  11727. m_reporter->testGroupStarting( groupInfo );
  11728. }
  11729. void ListeningReporter::testCaseStarting( TestCaseInfo const& testInfo ) {
  11730. for ( auto const& listener : m_listeners ) {
  11731. listener->testCaseStarting( testInfo );
  11732. }
  11733. m_reporter->testCaseStarting( testInfo );
  11734. }
  11735. void ListeningReporter::sectionStarting( SectionInfo const& sectionInfo ) {
  11736. for ( auto const& listener : m_listeners ) {
  11737. listener->sectionStarting( sectionInfo );
  11738. }
  11739. m_reporter->sectionStarting( sectionInfo );
  11740. }
  11741. void ListeningReporter::assertionStarting( AssertionInfo const& assertionInfo ) {
  11742. for ( auto const& listener : m_listeners ) {
  11743. listener->assertionStarting( assertionInfo );
  11744. }
  11745. m_reporter->assertionStarting( assertionInfo );
  11746. }
  11747. // The return value indicates if the messages buffer should be cleared:
  11748. bool ListeningReporter::assertionEnded( AssertionStats const& assertionStats ) {
  11749. for( auto const& listener : m_listeners ) {
  11750. static_cast<void>( listener->assertionEnded( assertionStats ) );
  11751. }
  11752. return m_reporter->assertionEnded( assertionStats );
  11753. }
  11754. void ListeningReporter::sectionEnded( SectionStats const& sectionStats ) {
  11755. for ( auto const& listener : m_listeners ) {
  11756. listener->sectionEnded( sectionStats );
  11757. }
  11758. m_reporter->sectionEnded( sectionStats );
  11759. }
  11760. void ListeningReporter::testCaseEnded( TestCaseStats const& testCaseStats ) {
  11761. for ( auto const& listener : m_listeners ) {
  11762. listener->testCaseEnded( testCaseStats );
  11763. }
  11764. m_reporter->testCaseEnded( testCaseStats );
  11765. }
  11766. void ListeningReporter::testGroupEnded( TestGroupStats const& testGroupStats ) {
  11767. for ( auto const& listener : m_listeners ) {
  11768. listener->testGroupEnded( testGroupStats );
  11769. }
  11770. m_reporter->testGroupEnded( testGroupStats );
  11771. }
  11772. void ListeningReporter::testRunEnded( TestRunStats const& testRunStats ) {
  11773. for ( auto const& listener : m_listeners ) {
  11774. listener->testRunEnded( testRunStats );
  11775. }
  11776. m_reporter->testRunEnded( testRunStats );
  11777. }
  11778. void ListeningReporter::skipTest( TestCaseInfo const& testInfo ) {
  11779. for ( auto const& listener : m_listeners ) {
  11780. listener->skipTest( testInfo );
  11781. }
  11782. m_reporter->skipTest( testInfo );
  11783. }
  11784. bool ListeningReporter::isMulti() const {
  11785. return true;
  11786. }
  11787. } // end namespace Catch
  11788. // end catch_reporter_listening.cpp
  11789. // start catch_reporter_xml.cpp
  11790. #if defined(_MSC_VER)
  11791. #pragma warning(push)
  11792. #pragma warning(disable:4061) // Not all labels are EXPLICITLY handled in switch
  11793. // Note that 4062 (not all labels are handled
  11794. // and default is missing) is enabled
  11795. #endif
  11796. namespace Catch {
  11797. XmlReporter::XmlReporter( ReporterConfig const& _config )
  11798. : StreamingReporterBase( _config ),
  11799. m_xml(_config.stream())
  11800. {
  11801. m_reporterPrefs.shouldRedirectStdOut = true;
  11802. m_reporterPrefs.shouldReportAllAssertions = true;
  11803. }
  11804. XmlReporter::~XmlReporter() = default;
  11805. std::string XmlReporter::getDescription() {
  11806. return "Reports test results as an XML document";
  11807. }
  11808. std::string XmlReporter::getStylesheetRef() const {
  11809. return std::string();
  11810. }
  11811. void XmlReporter::writeSourceInfo( SourceLineInfo const& sourceInfo ) {
  11812. m_xml
  11813. .writeAttribute( "filename", sourceInfo.file )
  11814. .writeAttribute( "line", sourceInfo.line );
  11815. }
  11816. void XmlReporter::noMatchingTestCases( std::string const& s ) {
  11817. StreamingReporterBase::noMatchingTestCases( s );
  11818. }
  11819. void XmlReporter::testRunStarting( TestRunInfo const& testInfo ) {
  11820. StreamingReporterBase::testRunStarting( testInfo );
  11821. std::string stylesheetRef = getStylesheetRef();
  11822. if( !stylesheetRef.empty() )
  11823. m_xml.writeStylesheetRef( stylesheetRef );
  11824. m_xml.startElement( "Catch" );
  11825. if( !m_config->name().empty() )
  11826. m_xml.writeAttribute( "name", m_config->name() );
  11827. if (m_config->testSpec().hasFilters())
  11828. m_xml.writeAttribute( "filters", serializeFilters( m_config->getTestsOrTags() ) );
  11829. if( m_config->rngSeed() != 0 )
  11830. m_xml.scopedElement( "Randomness" )
  11831. .writeAttribute( "seed", m_config->rngSeed() );
  11832. }
  11833. void XmlReporter::testGroupStarting( GroupInfo const& groupInfo ) {
  11834. StreamingReporterBase::testGroupStarting( groupInfo );
  11835. m_xml.startElement( "Group" )
  11836. .writeAttribute( "name", groupInfo.name );
  11837. }
  11838. void XmlReporter::testCaseStarting( TestCaseInfo const& testInfo ) {
  11839. StreamingReporterBase::testCaseStarting(testInfo);
  11840. m_xml.startElement( "TestCase" )
  11841. .writeAttribute( "name", trim( testInfo.name ) )
  11842. .writeAttribute( "description", testInfo.description )
  11843. .writeAttribute( "tags", testInfo.tagsAsString() );
  11844. writeSourceInfo( testInfo.lineInfo );
  11845. if ( m_config->showDurations() == ShowDurations::Always )
  11846. m_testCaseTimer.start();
  11847. m_xml.ensureTagClosed();
  11848. }
  11849. void XmlReporter::sectionStarting( SectionInfo const& sectionInfo ) {
  11850. StreamingReporterBase::sectionStarting( sectionInfo );
  11851. if( m_sectionDepth++ > 0 ) {
  11852. m_xml.startElement( "Section" )
  11853. .writeAttribute( "name", trim( sectionInfo.name ) );
  11854. writeSourceInfo( sectionInfo.lineInfo );
  11855. m_xml.ensureTagClosed();
  11856. }
  11857. }
  11858. void XmlReporter::assertionStarting( AssertionInfo const& ) { }
  11859. bool XmlReporter::assertionEnded( AssertionStats const& assertionStats ) {
  11860. AssertionResult const& result = assertionStats.assertionResult;
  11861. bool includeResults = m_config->includeSuccessfulResults() || !result.isOk();
  11862. if( includeResults || result.getResultType() == ResultWas::Warning ) {
  11863. // Print any info messages in <Info> tags.
  11864. for( auto const& msg : assertionStats.infoMessages ) {
  11865. if( msg.type == ResultWas::Info && includeResults ) {
  11866. m_xml.scopedElement( "Info" )
  11867. .writeText( msg.message );
  11868. } else if ( msg.type == ResultWas::Warning ) {
  11869. m_xml.scopedElement( "Warning" )
  11870. .writeText( msg.message );
  11871. }
  11872. }
  11873. }
  11874. // Drop out if result was successful but we're not printing them.
  11875. if( !includeResults && result.getResultType() != ResultWas::Warning )
  11876. return true;
  11877. // Print the expression if there is one.
  11878. if( result.hasExpression() ) {
  11879. m_xml.startElement( "Expression" )
  11880. .writeAttribute( "success", result.succeeded() )
  11881. .writeAttribute( "type", result.getTestMacroName() );
  11882. writeSourceInfo( result.getSourceInfo() );
  11883. m_xml.scopedElement( "Original" )
  11884. .writeText( result.getExpression() );
  11885. m_xml.scopedElement( "Expanded" )
  11886. .writeText( result.getExpandedExpression() );
  11887. }
  11888. // And... Print a result applicable to each result type.
  11889. switch( result.getResultType() ) {
  11890. case ResultWas::ThrewException:
  11891. m_xml.startElement( "Exception" );
  11892. writeSourceInfo( result.getSourceInfo() );
  11893. m_xml.writeText( result.getMessage() );
  11894. m_xml.endElement();
  11895. break;
  11896. case ResultWas::FatalErrorCondition:
  11897. m_xml.startElement( "FatalErrorCondition" );
  11898. writeSourceInfo( result.getSourceInfo() );
  11899. m_xml.writeText( result.getMessage() );
  11900. m_xml.endElement();
  11901. break;
  11902. case ResultWas::Info:
  11903. m_xml.scopedElement( "Info" )
  11904. .writeText( result.getMessage() );
  11905. break;
  11906. case ResultWas::Warning:
  11907. // Warning will already have been written
  11908. break;
  11909. case ResultWas::ExplicitFailure:
  11910. m_xml.startElement( "Failure" );
  11911. writeSourceInfo( result.getSourceInfo() );
  11912. m_xml.writeText( result.getMessage() );
  11913. m_xml.endElement();
  11914. break;
  11915. default:
  11916. break;
  11917. }
  11918. if( result.hasExpression() )
  11919. m_xml.endElement();
  11920. return true;
  11921. }
  11922. void XmlReporter::sectionEnded( SectionStats const& sectionStats ) {
  11923. StreamingReporterBase::sectionEnded( sectionStats );
  11924. if( --m_sectionDepth > 0 ) {
  11925. XmlWriter::ScopedElement e = m_xml.scopedElement( "OverallResults" );
  11926. e.writeAttribute( "successes", sectionStats.assertions.passed );
  11927. e.writeAttribute( "failures", sectionStats.assertions.failed );
  11928. e.writeAttribute( "expectedFailures", sectionStats.assertions.failedButOk );
  11929. if ( m_config->showDurations() == ShowDurations::Always )
  11930. e.writeAttribute( "durationInSeconds", sectionStats.durationInSeconds );
  11931. m_xml.endElement();
  11932. }
  11933. }
  11934. void XmlReporter::testCaseEnded( TestCaseStats const& testCaseStats ) {
  11935. StreamingReporterBase::testCaseEnded( testCaseStats );
  11936. XmlWriter::ScopedElement e = m_xml.scopedElement( "OverallResult" );
  11937. e.writeAttribute( "success", testCaseStats.totals.assertions.allOk() );
  11938. if ( m_config->showDurations() == ShowDurations::Always )
  11939. e.writeAttribute( "durationInSeconds", m_testCaseTimer.getElapsedSeconds() );
  11940. if( !testCaseStats.stdOut.empty() )
  11941. m_xml.scopedElement( "StdOut" ).writeText( trim( testCaseStats.stdOut ), false );
  11942. if( !testCaseStats.stdErr.empty() )
  11943. m_xml.scopedElement( "StdErr" ).writeText( trim( testCaseStats.stdErr ), false );
  11944. m_xml.endElement();
  11945. }
  11946. void XmlReporter::testGroupEnded( TestGroupStats const& testGroupStats ) {
  11947. StreamingReporterBase::testGroupEnded( testGroupStats );
  11948. // TODO: Check testGroupStats.aborting and act accordingly.
  11949. m_xml.scopedElement( "OverallResults" )
  11950. .writeAttribute( "successes", testGroupStats.totals.assertions.passed )
  11951. .writeAttribute( "failures", testGroupStats.totals.assertions.failed )
  11952. .writeAttribute( "expectedFailures", testGroupStats.totals.assertions.failedButOk );
  11953. m_xml.endElement();
  11954. }
  11955. void XmlReporter::testRunEnded( TestRunStats const& testRunStats ) {
  11956. StreamingReporterBase::testRunEnded( testRunStats );
  11957. m_xml.scopedElement( "OverallResults" )
  11958. .writeAttribute( "successes", testRunStats.totals.assertions.passed )
  11959. .writeAttribute( "failures", testRunStats.totals.assertions.failed )
  11960. .writeAttribute( "expectedFailures", testRunStats.totals.assertions.failedButOk );
  11961. m_xml.endElement();
  11962. }
  11963. CATCH_REGISTER_REPORTER( "xml", XmlReporter )
  11964. } // end namespace Catch
  11965. #if defined(_MSC_VER)
  11966. #pragma warning(pop)
  11967. #endif
  11968. // end catch_reporter_xml.cpp
  11969. namespace Catch {
  11970. LeakDetector leakDetector;
  11971. }
  11972. #ifdef __clang__
  11973. #pragma clang diagnostic pop
  11974. #endif
  11975. // end catch_impl.hpp
  11976. #endif
  11977. #ifdef CATCH_CONFIG_MAIN
  11978. // start catch_default_main.hpp
  11979. #ifndef __OBJC__
  11980. #if defined(CATCH_CONFIG_WCHAR) && defined(WIN32) && defined(_UNICODE) && !defined(DO_NOT_USE_WMAIN)
  11981. // Standard C/C++ Win32 Unicode wmain entry point
  11982. extern "C" int wmain (int argc, wchar_t * argv[], wchar_t * []) {
  11983. #else
  11984. // Standard C/C++ main entry point
  11985. int main (int argc, char * argv[]) {
  11986. #endif
  11987. return Catch::Session().run( argc, argv );
  11988. }
  11989. #else // __OBJC__
  11990. // Objective-C entry point
  11991. int main (int argc, char * const argv[]) {
  11992. #if !CATCH_ARC_ENABLED
  11993. NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
  11994. #endif
  11995. Catch::registerTestMethods();
  11996. int result = Catch::Session().run( argc, (char**)argv );
  11997. #if !CATCH_ARC_ENABLED
  11998. [pool drain];
  11999. #endif
  12000. return result;
  12001. }
  12002. #endif // __OBJC__
  12003. // end catch_default_main.hpp
  12004. #endif
  12005. #if !defined(CATCH_CONFIG_IMPL_ONLY)
  12006. #ifdef CLARA_CONFIG_MAIN_NOT_DEFINED
  12007. # undef CLARA_CONFIG_MAIN
  12008. #endif
  12009. #if !defined(CATCH_CONFIG_DISABLE)
  12010. //////
  12011. // If this config identifier is defined then all CATCH macros are prefixed with CATCH_
  12012. #ifdef CATCH_CONFIG_PREFIX_ALL
  12013. #define CATCH_REQUIRE( ... ) INTERNAL_CATCH_TEST( "CATCH_REQUIRE", Catch::ResultDisposition::Normal, __VA_ARGS__ )
  12014. #define CATCH_REQUIRE_FALSE( ... ) INTERNAL_CATCH_TEST( "CATCH_REQUIRE_FALSE", Catch::ResultDisposition::Normal | Catch::ResultDisposition::FalseTest, __VA_ARGS__ )
  12015. #define CATCH_REQUIRE_THROWS( ... ) INTERNAL_CATCH_THROWS( "CATCH_REQUIRE_THROWS", Catch::ResultDisposition::Normal, __VA_ARGS__ )
  12016. #define CATCH_REQUIRE_THROWS_AS( expr, exceptionType ) INTERNAL_CATCH_THROWS_AS( "CATCH_REQUIRE_THROWS_AS", exceptionType, Catch::ResultDisposition::Normal, expr )
  12017. #define CATCH_REQUIRE_THROWS_WITH( expr, matcher ) INTERNAL_CATCH_THROWS_STR_MATCHES( "CATCH_REQUIRE_THROWS_WITH", Catch::ResultDisposition::Normal, matcher, expr )
  12018. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  12019. #define CATCH_REQUIRE_THROWS_MATCHES( expr, exceptionType, matcher ) INTERNAL_CATCH_THROWS_MATCHES( "CATCH_REQUIRE_THROWS_MATCHES", exceptionType, Catch::ResultDisposition::Normal, matcher, expr )
  12020. #endif// CATCH_CONFIG_DISABLE_MATCHERS
  12021. #define CATCH_REQUIRE_NOTHROW( ... ) INTERNAL_CATCH_NO_THROW( "CATCH_REQUIRE_NOTHROW", Catch::ResultDisposition::Normal, __VA_ARGS__ )
  12022. #define CATCH_CHECK( ... ) INTERNAL_CATCH_TEST( "CATCH_CHECK", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  12023. #define CATCH_CHECK_FALSE( ... ) INTERNAL_CATCH_TEST( "CATCH_CHECK_FALSE", Catch::ResultDisposition::ContinueOnFailure | Catch::ResultDisposition::FalseTest, __VA_ARGS__ )
  12024. #define CATCH_CHECKED_IF( ... ) INTERNAL_CATCH_IF( "CATCH_CHECKED_IF", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  12025. #define CATCH_CHECKED_ELSE( ... ) INTERNAL_CATCH_ELSE( "CATCH_CHECKED_ELSE", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  12026. #define CATCH_CHECK_NOFAIL( ... ) INTERNAL_CATCH_TEST( "CATCH_CHECK_NOFAIL", Catch::ResultDisposition::ContinueOnFailure | Catch::ResultDisposition::SuppressFail, __VA_ARGS__ )
  12027. #define CATCH_CHECK_THROWS( ... ) INTERNAL_CATCH_THROWS( "CATCH_CHECK_THROWS", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  12028. #define CATCH_CHECK_THROWS_AS( expr, exceptionType ) INTERNAL_CATCH_THROWS_AS( "CATCH_CHECK_THROWS_AS", exceptionType, Catch::ResultDisposition::ContinueOnFailure, expr )
  12029. #define CATCH_CHECK_THROWS_WITH( expr, matcher ) INTERNAL_CATCH_THROWS_STR_MATCHES( "CATCH_CHECK_THROWS_WITH", Catch::ResultDisposition::ContinueOnFailure, matcher, expr )
  12030. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  12031. #define CATCH_CHECK_THROWS_MATCHES( expr, exceptionType, matcher ) INTERNAL_CATCH_THROWS_MATCHES( "CATCH_CHECK_THROWS_MATCHES", exceptionType, Catch::ResultDisposition::ContinueOnFailure, matcher, expr )
  12032. #endif // CATCH_CONFIG_DISABLE_MATCHERS
  12033. #define CATCH_CHECK_NOTHROW( ... ) INTERNAL_CATCH_NO_THROW( "CATCH_CHECK_NOTHROW", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  12034. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  12035. #define CATCH_CHECK_THAT( arg, matcher ) INTERNAL_CHECK_THAT( "CATCH_CHECK_THAT", matcher, Catch::ResultDisposition::ContinueOnFailure, arg )
  12036. #define CATCH_REQUIRE_THAT( arg, matcher ) INTERNAL_CHECK_THAT( "CATCH_REQUIRE_THAT", matcher, Catch::ResultDisposition::Normal, arg )
  12037. #endif // CATCH_CONFIG_DISABLE_MATCHERS
  12038. #define CATCH_INFO( msg ) INTERNAL_CATCH_INFO( "CATCH_INFO", msg )
  12039. #define CATCH_WARN( msg ) INTERNAL_CATCH_MSG( "CATCH_WARN", Catch::ResultWas::Warning, Catch::ResultDisposition::ContinueOnFailure, msg )
  12040. #define CATCH_CAPTURE( ... ) INTERNAL_CATCH_CAPTURE( INTERNAL_CATCH_UNIQUE_NAME(capturer), "CATCH_CAPTURE",__VA_ARGS__ )
  12041. #define CATCH_TEST_CASE( ... ) INTERNAL_CATCH_TESTCASE( __VA_ARGS__ )
  12042. #define CATCH_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEST_CASE_METHOD( className, __VA_ARGS__ )
  12043. #define CATCH_METHOD_AS_TEST_CASE( method, ... ) INTERNAL_CATCH_METHOD_AS_TEST_CASE( method, __VA_ARGS__ )
  12044. #define CATCH_REGISTER_TEST_CASE( Function, ... ) INTERNAL_CATCH_REGISTER_TESTCASE( Function, __VA_ARGS__ )
  12045. #define CATCH_SECTION( ... ) INTERNAL_CATCH_SECTION( __VA_ARGS__ )
  12046. #define CATCH_DYNAMIC_SECTION( ... ) INTERNAL_CATCH_DYNAMIC_SECTION( __VA_ARGS__ )
  12047. #define CATCH_FAIL( ... ) INTERNAL_CATCH_MSG( "CATCH_FAIL", Catch::ResultWas::ExplicitFailure, Catch::ResultDisposition::Normal, __VA_ARGS__ )
  12048. #define CATCH_FAIL_CHECK( ... ) INTERNAL_CATCH_MSG( "CATCH_FAIL_CHECK", Catch::ResultWas::ExplicitFailure, Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  12049. #define CATCH_SUCCEED( ... ) INTERNAL_CATCH_MSG( "CATCH_SUCCEED", Catch::ResultWas::Ok, Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  12050. #define CATCH_ANON_TEST_CASE() INTERNAL_CATCH_TESTCASE()
  12051. #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
  12052. #define CATCH_TEMPLATE_TEST_CASE( ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE( __VA_ARGS__ )
  12053. #define CATCH_TEMPLATE_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ )
  12054. #define CATCH_TEMPLATE_PRODUCT_TEST_CASE( ... ) INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE( __VA_ARGS__ )
  12055. #define CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, __VA_ARGS__ )
  12056. #else
  12057. #define CATCH_TEMPLATE_TEST_CASE( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE( __VA_ARGS__ ) )
  12058. #define CATCH_TEMPLATE_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ ) )
  12059. #define CATCH_TEMPLATE_PRODUCT_TEST_CASE( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE( __VA_ARGS__ ) )
  12060. #define CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, __VA_ARGS__ ) )
  12061. #endif
  12062. #if !defined(CATCH_CONFIG_RUNTIME_STATIC_REQUIRE)
  12063. #define CATCH_STATIC_REQUIRE( ... ) static_assert( __VA_ARGS__ , #__VA_ARGS__ ); CATCH_SUCCEED( #__VA_ARGS__ )
  12064. #define CATCH_STATIC_REQUIRE_FALSE( ... ) static_assert( !(__VA_ARGS__), "!(" #__VA_ARGS__ ")" ); CATCH_SUCCEED( #__VA_ARGS__ )
  12065. #else
  12066. #define CATCH_STATIC_REQUIRE( ... ) CATCH_REQUIRE( __VA_ARGS__ )
  12067. #define CATCH_STATIC_REQUIRE_FALSE( ... ) CATCH_REQUIRE_FALSE( __VA_ARGS__ )
  12068. #endif
  12069. // "BDD-style" convenience wrappers
  12070. #define CATCH_SCENARIO( ... ) CATCH_TEST_CASE( "Scenario: " __VA_ARGS__ )
  12071. #define CATCH_SCENARIO_METHOD( className, ... ) INTERNAL_CATCH_TEST_CASE_METHOD( className, "Scenario: " __VA_ARGS__ )
  12072. #define CATCH_GIVEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " Given: " << desc )
  12073. #define CATCH_AND_GIVEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( "And given: " << desc )
  12074. #define CATCH_WHEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " When: " << desc )
  12075. #define CATCH_AND_WHEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " And when: " << desc )
  12076. #define CATCH_THEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " Then: " << desc )
  12077. #define CATCH_AND_THEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " And: " << desc )
  12078. // If CATCH_CONFIG_PREFIX_ALL is not defined then the CATCH_ prefix is not required
  12079. #else
  12080. #define REQUIRE( ... ) INTERNAL_CATCH_TEST( "REQUIRE", Catch::ResultDisposition::Normal, __VA_ARGS__ )
  12081. #define REQUIRE_FALSE( ... ) INTERNAL_CATCH_TEST( "REQUIRE_FALSE", Catch::ResultDisposition::Normal | Catch::ResultDisposition::FalseTest, __VA_ARGS__ )
  12082. #define REQUIRE_THROWS( ... ) INTERNAL_CATCH_THROWS( "REQUIRE_THROWS", Catch::ResultDisposition::Normal, __VA_ARGS__ )
  12083. #define REQUIRE_THROWS_AS( expr, exceptionType ) INTERNAL_CATCH_THROWS_AS( "REQUIRE_THROWS_AS", exceptionType, Catch::ResultDisposition::Normal, expr )
  12084. #define REQUIRE_THROWS_WITH( expr, matcher ) INTERNAL_CATCH_THROWS_STR_MATCHES( "REQUIRE_THROWS_WITH", Catch::ResultDisposition::Normal, matcher, expr )
  12085. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  12086. #define REQUIRE_THROWS_MATCHES( expr, exceptionType, matcher ) INTERNAL_CATCH_THROWS_MATCHES( "REQUIRE_THROWS_MATCHES", exceptionType, Catch::ResultDisposition::Normal, matcher, expr )
  12087. #endif // CATCH_CONFIG_DISABLE_MATCHERS
  12088. #define REQUIRE_NOTHROW( ... ) INTERNAL_CATCH_NO_THROW( "REQUIRE_NOTHROW", Catch::ResultDisposition::Normal, __VA_ARGS__ )
  12089. #define CHECK( ... ) INTERNAL_CATCH_TEST( "CHECK", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  12090. #define CHECK_FALSE( ... ) INTERNAL_CATCH_TEST( "CHECK_FALSE", Catch::ResultDisposition::ContinueOnFailure | Catch::ResultDisposition::FalseTest, __VA_ARGS__ )
  12091. #define CHECKED_IF( ... ) INTERNAL_CATCH_IF( "CHECKED_IF", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  12092. #define CHECKED_ELSE( ... ) INTERNAL_CATCH_ELSE( "CHECKED_ELSE", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  12093. #define CHECK_NOFAIL( ... ) INTERNAL_CATCH_TEST( "CHECK_NOFAIL", Catch::ResultDisposition::ContinueOnFailure | Catch::ResultDisposition::SuppressFail, __VA_ARGS__ )
  12094. #define CHECK_THROWS( ... ) INTERNAL_CATCH_THROWS( "CHECK_THROWS", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  12095. #define CHECK_THROWS_AS( expr, exceptionType ) INTERNAL_CATCH_THROWS_AS( "CHECK_THROWS_AS", exceptionType, Catch::ResultDisposition::ContinueOnFailure, expr )
  12096. #define CHECK_THROWS_WITH( expr, matcher ) INTERNAL_CATCH_THROWS_STR_MATCHES( "CHECK_THROWS_WITH", Catch::ResultDisposition::ContinueOnFailure, matcher, expr )
  12097. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  12098. #define CHECK_THROWS_MATCHES( expr, exceptionType, matcher ) INTERNAL_CATCH_THROWS_MATCHES( "CHECK_THROWS_MATCHES", exceptionType, Catch::ResultDisposition::ContinueOnFailure, matcher, expr )
  12099. #endif // CATCH_CONFIG_DISABLE_MATCHERS
  12100. #define CHECK_NOTHROW( ... ) INTERNAL_CATCH_NO_THROW( "CHECK_NOTHROW", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  12101. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  12102. #define CHECK_THAT( arg, matcher ) INTERNAL_CHECK_THAT( "CHECK_THAT", matcher, Catch::ResultDisposition::ContinueOnFailure, arg )
  12103. #define REQUIRE_THAT( arg, matcher ) INTERNAL_CHECK_THAT( "REQUIRE_THAT", matcher, Catch::ResultDisposition::Normal, arg )
  12104. #endif // CATCH_CONFIG_DISABLE_MATCHERS
  12105. #define INFO( msg ) INTERNAL_CATCH_INFO( "INFO", msg )
  12106. #define UNSCOPED_INFO( msg ) INTERNAL_CATCH_UNSCOPED_INFO( "UNSCOPED_INFO", msg )
  12107. #define WARN( msg ) INTERNAL_CATCH_MSG( "WARN", Catch::ResultWas::Warning, Catch::ResultDisposition::ContinueOnFailure, msg )
  12108. #define CAPTURE( ... ) INTERNAL_CATCH_CAPTURE( INTERNAL_CATCH_UNIQUE_NAME(capturer), "CAPTURE",__VA_ARGS__ )
  12109. #define TEST_CASE( ... ) INTERNAL_CATCH_TESTCASE( __VA_ARGS__ )
  12110. #define TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEST_CASE_METHOD( className, __VA_ARGS__ )
  12111. #define METHOD_AS_TEST_CASE( method, ... ) INTERNAL_CATCH_METHOD_AS_TEST_CASE( method, __VA_ARGS__ )
  12112. #define REGISTER_TEST_CASE( Function, ... ) INTERNAL_CATCH_REGISTER_TESTCASE( Function, __VA_ARGS__ )
  12113. #define SECTION( ... ) INTERNAL_CATCH_SECTION( __VA_ARGS__ )
  12114. #define DYNAMIC_SECTION( ... ) INTERNAL_CATCH_DYNAMIC_SECTION( __VA_ARGS__ )
  12115. #define FAIL( ... ) INTERNAL_CATCH_MSG( "FAIL", Catch::ResultWas::ExplicitFailure, Catch::ResultDisposition::Normal, __VA_ARGS__ )
  12116. #define FAIL_CHECK( ... ) INTERNAL_CATCH_MSG( "FAIL_CHECK", Catch::ResultWas::ExplicitFailure, Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  12117. #define SUCCEED( ... ) INTERNAL_CATCH_MSG( "SUCCEED", Catch::ResultWas::Ok, Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  12118. #define ANON_TEST_CASE() INTERNAL_CATCH_TESTCASE()
  12119. #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
  12120. #define TEMPLATE_TEST_CASE( ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE( __VA_ARGS__ )
  12121. #define TEMPLATE_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ )
  12122. #define TEMPLATE_PRODUCT_TEST_CASE( ... ) INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE( __VA_ARGS__ )
  12123. #define TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, __VA_ARGS__ )
  12124. #else
  12125. #define TEMPLATE_TEST_CASE( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE( __VA_ARGS__ ) )
  12126. #define TEMPLATE_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ ) )
  12127. #define TEMPLATE_PRODUCT_TEST_CASE( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE( __VA_ARGS__ ) )
  12128. #define TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, __VA_ARGS__ ) )
  12129. #endif
  12130. #if !defined(CATCH_CONFIG_RUNTIME_STATIC_REQUIRE)
  12131. #define STATIC_REQUIRE( ... ) static_assert( __VA_ARGS__, #__VA_ARGS__ ); SUCCEED( #__VA_ARGS__ )
  12132. #define STATIC_REQUIRE_FALSE( ... ) static_assert( !(__VA_ARGS__), "!(" #__VA_ARGS__ ")" ); SUCCEED( "!(" #__VA_ARGS__ ")" )
  12133. #else
  12134. #define STATIC_REQUIRE( ... ) REQUIRE( __VA_ARGS__ )
  12135. #define STATIC_REQUIRE_FALSE( ... ) REQUIRE_FALSE( __VA_ARGS__ )
  12136. #endif
  12137. #endif
  12138. #define CATCH_TRANSLATE_EXCEPTION( signature ) INTERNAL_CATCH_TRANSLATE_EXCEPTION( signature )
  12139. // "BDD-style" convenience wrappers
  12140. #define SCENARIO( ... ) TEST_CASE( "Scenario: " __VA_ARGS__ )
  12141. #define SCENARIO_METHOD( className, ... ) INTERNAL_CATCH_TEST_CASE_METHOD( className, "Scenario: " __VA_ARGS__ )
  12142. #define GIVEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " Given: " << desc )
  12143. #define AND_GIVEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( "And given: " << desc )
  12144. #define WHEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " When: " << desc )
  12145. #define AND_WHEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " And when: " << desc )
  12146. #define THEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " Then: " << desc )
  12147. #define AND_THEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " And: " << desc )
  12148. using Catch::Detail::Approx;
  12149. #else // CATCH_CONFIG_DISABLE
  12150. //////
  12151. // If this config identifier is defined then all CATCH macros are prefixed with CATCH_
  12152. #ifdef CATCH_CONFIG_PREFIX_ALL
  12153. #define CATCH_REQUIRE( ... ) (void)(0)
  12154. #define CATCH_REQUIRE_FALSE( ... ) (void)(0)
  12155. #define CATCH_REQUIRE_THROWS( ... ) (void)(0)
  12156. #define CATCH_REQUIRE_THROWS_AS( expr, exceptionType ) (void)(0)
  12157. #define CATCH_REQUIRE_THROWS_WITH( expr, matcher ) (void)(0)
  12158. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  12159. #define CATCH_REQUIRE_THROWS_MATCHES( expr, exceptionType, matcher ) (void)(0)
  12160. #endif// CATCH_CONFIG_DISABLE_MATCHERS
  12161. #define CATCH_REQUIRE_NOTHROW( ... ) (void)(0)
  12162. #define CATCH_CHECK( ... ) (void)(0)
  12163. #define CATCH_CHECK_FALSE( ... ) (void)(0)
  12164. #define CATCH_CHECKED_IF( ... ) if (__VA_ARGS__)
  12165. #define CATCH_CHECKED_ELSE( ... ) if (!(__VA_ARGS__))
  12166. #define CATCH_CHECK_NOFAIL( ... ) (void)(0)
  12167. #define CATCH_CHECK_THROWS( ... ) (void)(0)
  12168. #define CATCH_CHECK_THROWS_AS( expr, exceptionType ) (void)(0)
  12169. #define CATCH_CHECK_THROWS_WITH( expr, matcher ) (void)(0)
  12170. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  12171. #define CATCH_CHECK_THROWS_MATCHES( expr, exceptionType, matcher ) (void)(0)
  12172. #endif // CATCH_CONFIG_DISABLE_MATCHERS
  12173. #define CATCH_CHECK_NOTHROW( ... ) (void)(0)
  12174. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  12175. #define CATCH_CHECK_THAT( arg, matcher ) (void)(0)
  12176. #define CATCH_REQUIRE_THAT( arg, matcher ) (void)(0)
  12177. #endif // CATCH_CONFIG_DISABLE_MATCHERS
  12178. #define CATCH_INFO( msg ) (void)(0)
  12179. #define CATCH_WARN( msg ) (void)(0)
  12180. #define CATCH_CAPTURE( msg ) (void)(0)
  12181. #define CATCH_TEST_CASE( ... ) INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ))
  12182. #define CATCH_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ))
  12183. #define CATCH_METHOD_AS_TEST_CASE( method, ... )
  12184. #define CATCH_REGISTER_TEST_CASE( Function, ... ) (void)(0)
  12185. #define CATCH_SECTION( ... )
  12186. #define CATCH_DYNAMIC_SECTION( ... )
  12187. #define CATCH_FAIL( ... ) (void)(0)
  12188. #define CATCH_FAIL_CHECK( ... ) (void)(0)
  12189. #define CATCH_SUCCEED( ... ) (void)(0)
  12190. #define CATCH_ANON_TEST_CASE() INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ))
  12191. #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
  12192. #define CATCH_TEMPLATE_TEST_CASE( ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ) )
  12193. #define CATCH_TEMPLATE_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ), className )
  12194. #define CATCH_TEMPLATE_PRODUCT_TEST_CASE( ... ) CATCH_TEMPLATE_TEST_CASE( __VA_ARGS__ )
  12195. #define CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, ... ) CATCH_TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ )
  12196. #else
  12197. #define CATCH_TEMPLATE_TEST_CASE( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ) ) )
  12198. #define CATCH_TEMPLATE_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ), className ) )
  12199. #define CATCH_TEMPLATE_PRODUCT_TEST_CASE( ... ) CATCH_TEMPLATE_TEST_CASE( __VA_ARGS__ )
  12200. #define CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, ... ) CATCH_TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ )
  12201. #endif
  12202. // "BDD-style" convenience wrappers
  12203. #define CATCH_SCENARIO( ... ) INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ))
  12204. #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 )
  12205. #define CATCH_GIVEN( desc )
  12206. #define CATCH_AND_GIVEN( desc )
  12207. #define CATCH_WHEN( desc )
  12208. #define CATCH_AND_WHEN( desc )
  12209. #define CATCH_THEN( desc )
  12210. #define CATCH_AND_THEN( desc )
  12211. #define CATCH_STATIC_REQUIRE( ... ) (void)(0)
  12212. #define CATCH_STATIC_REQUIRE_FALSE( ... ) (void)(0)
  12213. // If CATCH_CONFIG_PREFIX_ALL is not defined then the CATCH_ prefix is not required
  12214. #else
  12215. #define REQUIRE( ... ) (void)(0)
  12216. #define REQUIRE_FALSE( ... ) (void)(0)
  12217. #define REQUIRE_THROWS( ... ) (void)(0)
  12218. #define REQUIRE_THROWS_AS( expr, exceptionType ) (void)(0)
  12219. #define REQUIRE_THROWS_WITH( expr, matcher ) (void)(0)
  12220. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  12221. #define REQUIRE_THROWS_MATCHES( expr, exceptionType, matcher ) (void)(0)
  12222. #endif // CATCH_CONFIG_DISABLE_MATCHERS
  12223. #define REQUIRE_NOTHROW( ... ) (void)(0)
  12224. #define CHECK( ... ) (void)(0)
  12225. #define CHECK_FALSE( ... ) (void)(0)
  12226. #define CHECKED_IF( ... ) if (__VA_ARGS__)
  12227. #define CHECKED_ELSE( ... ) if (!(__VA_ARGS__))
  12228. #define CHECK_NOFAIL( ... ) (void)(0)
  12229. #define CHECK_THROWS( ... ) (void)(0)
  12230. #define CHECK_THROWS_AS( expr, exceptionType ) (void)(0)
  12231. #define CHECK_THROWS_WITH( expr, matcher ) (void)(0)
  12232. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  12233. #define CHECK_THROWS_MATCHES( expr, exceptionType, matcher ) (void)(0)
  12234. #endif // CATCH_CONFIG_DISABLE_MATCHERS
  12235. #define CHECK_NOTHROW( ... ) (void)(0)
  12236. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  12237. #define CHECK_THAT( arg, matcher ) (void)(0)
  12238. #define REQUIRE_THAT( arg, matcher ) (void)(0)
  12239. #endif // CATCH_CONFIG_DISABLE_MATCHERS
  12240. #define INFO( msg ) (void)(0)
  12241. #define WARN( msg ) (void)(0)
  12242. #define CAPTURE( msg ) (void)(0)
  12243. #define TEST_CASE( ... ) INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ))
  12244. #define TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ))
  12245. #define METHOD_AS_TEST_CASE( method, ... )
  12246. #define REGISTER_TEST_CASE( Function, ... ) (void)(0)
  12247. #define SECTION( ... )
  12248. #define DYNAMIC_SECTION( ... )
  12249. #define FAIL( ... ) (void)(0)
  12250. #define FAIL_CHECK( ... ) (void)(0)
  12251. #define SUCCEED( ... ) (void)(0)
  12252. #define ANON_TEST_CASE() INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ))
  12253. #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
  12254. #define TEMPLATE_TEST_CASE( ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ) )
  12255. #define TEMPLATE_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ), className )
  12256. #define TEMPLATE_PRODUCT_TEST_CASE( ... ) TEMPLATE_TEST_CASE( __VA_ARGS__ )
  12257. #define TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, ... ) TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ )
  12258. #else
  12259. #define TEMPLATE_TEST_CASE( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ) ) )
  12260. #define TEMPLATE_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ), className ) )
  12261. #define TEMPLATE_PRODUCT_TEST_CASE( ... ) TEMPLATE_TEST_CASE( __VA_ARGS__ )
  12262. #define TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, ... ) TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ )
  12263. #endif
  12264. #define STATIC_REQUIRE( ... ) (void)(0)
  12265. #define STATIC_REQUIRE_FALSE( ... ) (void)(0)
  12266. #endif
  12267. #define CATCH_TRANSLATE_EXCEPTION( signature ) INTERNAL_CATCH_TRANSLATE_EXCEPTION_NO_REG( INTERNAL_CATCH_UNIQUE_NAME( catch_internal_ExceptionTranslator ), signature )
  12268. // "BDD-style" convenience wrappers
  12269. #define SCENARIO( ... ) INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ) )
  12270. #define SCENARIO_METHOD( className, ... ) INTERNAL_CATCH_TESTCASE_METHOD_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ), className )
  12271. #define GIVEN( desc )
  12272. #define AND_GIVEN( desc )
  12273. #define WHEN( desc )
  12274. #define AND_WHEN( desc )
  12275. #define THEN( desc )
  12276. #define AND_THEN( desc )
  12277. using Catch::Detail::Approx;
  12278. #endif
  12279. #endif // ! CATCH_CONFIG_IMPL_ONLY
  12280. // start catch_reenable_warnings.h
  12281. #ifdef __clang__
  12282. # ifdef __ICC // icpc defines the __clang__ macro
  12283. # pragma warning(pop)
  12284. # else
  12285. # pragma clang diagnostic pop
  12286. # endif
  12287. #elif defined __GNUC__
  12288. # pragma GCC diagnostic pop
  12289. #endif
  12290. // end catch_reenable_warnings.h
  12291. // end catch.hpp
  12292. #endif // TWOBLUECUBES_SINGLE_INCLUDE_CATCH_HPP_INCLUDED