Du kannst nicht mehr als 25 Themen auswählen Themen müssen entweder mit einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.

15004 Zeilen
508KB

  1. /*
  2. * Catch v2.7.2
  3. * Generated: 2019-04-22 23:13:14.687465
  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 2
  17. #ifdef __clang__
  18. # pragma clang system_header
  19. #elif defined __GNUC__
  20. # pragma GCC system_header
  21. #endif
  22. // start catch_suppress_warnings.h
  23. #ifdef __clang__
  24. # ifdef __ICC // icpc defines the __clang__ macro
  25. # pragma warning(push)
  26. # pragma warning(disable: 161 1682)
  27. # else // __ICC
  28. # pragma clang diagnostic push
  29. # pragma clang diagnostic ignored "-Wpadded"
  30. # pragma clang diagnostic ignored "-Wswitch-enum"
  31. # pragma clang diagnostic ignored "-Wcovered-switch-default"
  32. # endif
  33. #elif defined __GNUC__
  34. // 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. // inferring 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. template<typename T>
  2623. struct ContainsElementMatcher : MatcherBase<std::vector<T>> {
  2624. ContainsElementMatcher(T const &comparator) : m_comparator( comparator) {}
  2625. bool match(std::vector<T> const &v) const override {
  2626. for (auto const& el : v) {
  2627. if (el == m_comparator) {
  2628. return true;
  2629. }
  2630. }
  2631. return false;
  2632. }
  2633. std::string describe() const override {
  2634. return "Contains: " + ::Catch::Detail::stringify( m_comparator );
  2635. }
  2636. T const& m_comparator;
  2637. };
  2638. template<typename T>
  2639. struct ContainsMatcher : MatcherBase<std::vector<T>> {
  2640. ContainsMatcher(std::vector<T> const &comparator) : m_comparator( comparator ) {}
  2641. bool match(std::vector<T> const &v) const override {
  2642. // !TBD: see note in EqualsMatcher
  2643. if (m_comparator.size() > v.size())
  2644. return false;
  2645. for (auto const& comparator : m_comparator) {
  2646. auto present = false;
  2647. for (const auto& el : v) {
  2648. if (el == comparator) {
  2649. present = true;
  2650. break;
  2651. }
  2652. }
  2653. if (!present) {
  2654. return false;
  2655. }
  2656. }
  2657. return true;
  2658. }
  2659. std::string describe() const override {
  2660. return "Contains: " + ::Catch::Detail::stringify( m_comparator );
  2661. }
  2662. std::vector<T> const& m_comparator;
  2663. };
  2664. template<typename T>
  2665. struct EqualsMatcher : MatcherBase<std::vector<T>> {
  2666. EqualsMatcher(std::vector<T> const &comparator) : m_comparator( comparator ) {}
  2667. bool match(std::vector<T> const &v) const override {
  2668. // !TBD: This currently works if all elements can be compared using !=
  2669. // - a more general approach would be via a compare template that defaults
  2670. // to using !=. but could be specialised for, e.g. std::vector<T> etc
  2671. // - then just call that directly
  2672. if (m_comparator.size() != v.size())
  2673. return false;
  2674. for (std::size_t i = 0; i < v.size(); ++i)
  2675. if (m_comparator[i] != v[i])
  2676. return false;
  2677. return true;
  2678. }
  2679. std::string describe() const override {
  2680. return "Equals: " + ::Catch::Detail::stringify( m_comparator );
  2681. }
  2682. std::vector<T> const& m_comparator;
  2683. };
  2684. template<typename T>
  2685. struct ApproxMatcher : MatcherBase<std::vector<T>> {
  2686. ApproxMatcher(std::vector<T> const& comparator) : m_comparator( comparator ) {}
  2687. bool match(std::vector<T> const &v) const override {
  2688. if (m_comparator.size() != v.size())
  2689. return false;
  2690. for (std::size_t i = 0; i < v.size(); ++i)
  2691. if (m_comparator[i] != approx(v[i]))
  2692. return false;
  2693. return true;
  2694. }
  2695. std::string describe() const override {
  2696. return "is approx: " + ::Catch::Detail::stringify( m_comparator );
  2697. }
  2698. template <typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
  2699. ApproxMatcher& epsilon( T const& newEpsilon ) {
  2700. approx.epsilon(newEpsilon);
  2701. return *this;
  2702. }
  2703. template <typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
  2704. ApproxMatcher& margin( T const& newMargin ) {
  2705. approx.margin(newMargin);
  2706. return *this;
  2707. }
  2708. template <typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
  2709. ApproxMatcher& scale( T const& newScale ) {
  2710. approx.scale(newScale);
  2711. return *this;
  2712. }
  2713. std::vector<T> const& m_comparator;
  2714. mutable Catch::Detail::Approx approx = Catch::Detail::Approx::custom();
  2715. };
  2716. template<typename T>
  2717. struct UnorderedEqualsMatcher : MatcherBase<std::vector<T>> {
  2718. UnorderedEqualsMatcher(std::vector<T> const& target) : m_target(target) {}
  2719. bool match(std::vector<T> const& vec) const override {
  2720. // Note: This is a reimplementation of std::is_permutation,
  2721. // because I don't want to include <algorithm> inside the common path
  2722. if (m_target.size() != vec.size()) {
  2723. return false;
  2724. }
  2725. return std::is_permutation(m_target.begin(), m_target.end(), vec.begin());
  2726. }
  2727. std::string describe() const override {
  2728. return "UnorderedEquals: " + ::Catch::Detail::stringify(m_target);
  2729. }
  2730. private:
  2731. std::vector<T> const& m_target;
  2732. };
  2733. } // namespace Vector
  2734. // The following functions create the actual matcher objects.
  2735. // This allows the types to be inferred
  2736. template<typename T>
  2737. Vector::ContainsMatcher<T> Contains( std::vector<T> const& comparator ) {
  2738. return Vector::ContainsMatcher<T>( comparator );
  2739. }
  2740. template<typename T>
  2741. Vector::ContainsElementMatcher<T> VectorContains( T const& comparator ) {
  2742. return Vector::ContainsElementMatcher<T>( comparator );
  2743. }
  2744. template<typename T>
  2745. Vector::EqualsMatcher<T> Equals( std::vector<T> const& comparator ) {
  2746. return Vector::EqualsMatcher<T>( comparator );
  2747. }
  2748. template<typename T>
  2749. Vector::ApproxMatcher<T> Approx( std::vector<T> const& comparator ) {
  2750. return Vector::ApproxMatcher<T>( comparator );
  2751. }
  2752. template<typename T>
  2753. Vector::UnorderedEqualsMatcher<T> UnorderedEquals(std::vector<T> const& target) {
  2754. return Vector::UnorderedEqualsMatcher<T>(target);
  2755. }
  2756. } // namespace Matchers
  2757. } // namespace Catch
  2758. // end catch_matchers_vector.h
  2759. namespace Catch {
  2760. template<typename ArgT, typename MatcherT>
  2761. class MatchExpr : public ITransientExpression {
  2762. ArgT const& m_arg;
  2763. MatcherT m_matcher;
  2764. StringRef m_matcherString;
  2765. public:
  2766. MatchExpr( ArgT const& arg, MatcherT const& matcher, StringRef const& matcherString )
  2767. : ITransientExpression{ true, matcher.match( arg ) },
  2768. m_arg( arg ),
  2769. m_matcher( matcher ),
  2770. m_matcherString( matcherString )
  2771. {}
  2772. void streamReconstructedExpression( std::ostream &os ) const override {
  2773. auto matcherAsString = m_matcher.toString();
  2774. os << Catch::Detail::stringify( m_arg ) << ' ';
  2775. if( matcherAsString == Detail::unprintableString )
  2776. os << m_matcherString;
  2777. else
  2778. os << matcherAsString;
  2779. }
  2780. };
  2781. using StringMatcher = Matchers::Impl::MatcherBase<std::string>;
  2782. void handleExceptionMatchExpr( AssertionHandler& handler, StringMatcher const& matcher, StringRef const& matcherString );
  2783. template<typename ArgT, typename MatcherT>
  2784. auto makeMatchExpr( ArgT const& arg, MatcherT const& matcher, StringRef const& matcherString ) -> MatchExpr<ArgT, MatcherT> {
  2785. return MatchExpr<ArgT, MatcherT>( arg, matcher, matcherString );
  2786. }
  2787. } // namespace Catch
  2788. ///////////////////////////////////////////////////////////////////////////////
  2789. #define INTERNAL_CHECK_THAT( macroName, matcher, resultDisposition, arg ) \
  2790. do { \
  2791. Catch::AssertionHandler catchAssertionHandler( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(arg) ", " CATCH_INTERNAL_STRINGIFY(matcher), resultDisposition ); \
  2792. INTERNAL_CATCH_TRY { \
  2793. catchAssertionHandler.handleExpr( Catch::makeMatchExpr( arg, matcher, #matcher##_catch_sr ) ); \
  2794. } INTERNAL_CATCH_CATCH( catchAssertionHandler ) \
  2795. INTERNAL_CATCH_REACT( catchAssertionHandler ) \
  2796. } while( false )
  2797. ///////////////////////////////////////////////////////////////////////////////
  2798. #define INTERNAL_CATCH_THROWS_MATCHES( macroName, exceptionType, resultDisposition, matcher, ... ) \
  2799. do { \
  2800. Catch::AssertionHandler catchAssertionHandler( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(__VA_ARGS__) ", " CATCH_INTERNAL_STRINGIFY(exceptionType) ", " CATCH_INTERNAL_STRINGIFY(matcher), resultDisposition ); \
  2801. if( catchAssertionHandler.allowThrows() ) \
  2802. try { \
  2803. static_cast<void>(__VA_ARGS__ ); \
  2804. catchAssertionHandler.handleUnexpectedExceptionNotThrown(); \
  2805. } \
  2806. catch( exceptionType const& ex ) { \
  2807. catchAssertionHandler.handleExpr( Catch::makeMatchExpr( ex, matcher, #matcher##_catch_sr ) ); \
  2808. } \
  2809. catch( ... ) { \
  2810. catchAssertionHandler.handleUnexpectedInflightException(); \
  2811. } \
  2812. else \
  2813. catchAssertionHandler.handleThrowingCallSkipped(); \
  2814. INTERNAL_CATCH_REACT( catchAssertionHandler ) \
  2815. } while( false )
  2816. // end catch_capture_matchers.h
  2817. #endif
  2818. // start catch_generators.hpp
  2819. // start catch_interfaces_generatortracker.h
  2820. #include <memory>
  2821. namespace Catch {
  2822. namespace Generators {
  2823. class GeneratorUntypedBase {
  2824. public:
  2825. GeneratorUntypedBase() = default;
  2826. virtual ~GeneratorUntypedBase();
  2827. // Attempts to move the generator to the next element
  2828. //
  2829. // Returns true iff the move succeeded (and a valid element
  2830. // can be retrieved).
  2831. virtual bool next() = 0;
  2832. };
  2833. using GeneratorBasePtr = std::unique_ptr<GeneratorUntypedBase>;
  2834. } // namespace Generators
  2835. struct IGeneratorTracker {
  2836. virtual ~IGeneratorTracker();
  2837. virtual auto hasGenerator() const -> bool = 0;
  2838. virtual auto getGenerator() const -> Generators::GeneratorBasePtr const& = 0;
  2839. virtual void setGenerator( Generators::GeneratorBasePtr&& generator ) = 0;
  2840. };
  2841. } // namespace Catch
  2842. // end catch_interfaces_generatortracker.h
  2843. // start catch_enforce.h
  2844. #include <stdexcept>
  2845. namespace Catch {
  2846. #if !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
  2847. template <typename Ex>
  2848. [[noreturn]]
  2849. void throw_exception(Ex const& e) {
  2850. throw e;
  2851. }
  2852. #else // ^^ Exceptions are enabled // Exceptions are disabled vv
  2853. [[noreturn]]
  2854. void throw_exception(std::exception const& e);
  2855. #endif
  2856. } // namespace Catch;
  2857. #define CATCH_PREPARE_EXCEPTION( type, msg ) \
  2858. type( ( Catch::ReusableStringStream() << msg ).str() )
  2859. #define CATCH_INTERNAL_ERROR( msg ) \
  2860. Catch::throw_exception(CATCH_PREPARE_EXCEPTION( std::logic_error, CATCH_INTERNAL_LINEINFO << ": Internal Catch error: " << msg))
  2861. #define CATCH_ERROR( msg ) \
  2862. Catch::throw_exception(CATCH_PREPARE_EXCEPTION( std::domain_error, msg ))
  2863. #define CATCH_RUNTIME_ERROR( msg ) \
  2864. Catch::throw_exception(CATCH_PREPARE_EXCEPTION( std::runtime_error, msg ))
  2865. #define CATCH_ENFORCE( condition, msg ) \
  2866. do{ if( !(condition) ) CATCH_ERROR( msg ); } while(false)
  2867. // end catch_enforce.h
  2868. #include <memory>
  2869. #include <vector>
  2870. #include <cassert>
  2871. #include <utility>
  2872. #include <exception>
  2873. namespace Catch {
  2874. class GeneratorException : public std::exception {
  2875. const char* const m_msg = "";
  2876. public:
  2877. GeneratorException(const char* msg):
  2878. m_msg(msg)
  2879. {}
  2880. const char* what() const noexcept override final;
  2881. };
  2882. namespace Generators {
  2883. // !TBD move this into its own location?
  2884. namespace pf{
  2885. template<typename T, typename... Args>
  2886. std::unique_ptr<T> make_unique( Args&&... args ) {
  2887. return std::unique_ptr<T>(new T(std::forward<Args>(args)...));
  2888. }
  2889. }
  2890. template<typename T>
  2891. struct IGenerator : GeneratorUntypedBase {
  2892. virtual ~IGenerator() = default;
  2893. // Returns the current element of the generator
  2894. //
  2895. // \Precondition The generator is either freshly constructed,
  2896. // or the last call to `next()` returned true
  2897. virtual T const& get() const = 0;
  2898. using type = T;
  2899. };
  2900. template<typename T>
  2901. class SingleValueGenerator final : public IGenerator<T> {
  2902. T m_value;
  2903. public:
  2904. SingleValueGenerator(T const& value) : m_value( value ) {}
  2905. SingleValueGenerator(T&& value) : m_value(std::move(value)) {}
  2906. T const& get() const override {
  2907. return m_value;
  2908. }
  2909. bool next() override {
  2910. return false;
  2911. }
  2912. };
  2913. template<typename T>
  2914. class FixedValuesGenerator final : public IGenerator<T> {
  2915. std::vector<T> m_values;
  2916. size_t m_idx = 0;
  2917. public:
  2918. FixedValuesGenerator( std::initializer_list<T> values ) : m_values( values ) {}
  2919. T const& get() const override {
  2920. return m_values[m_idx];
  2921. }
  2922. bool next() override {
  2923. ++m_idx;
  2924. return m_idx < m_values.size();
  2925. }
  2926. };
  2927. template <typename T>
  2928. class GeneratorWrapper final {
  2929. std::unique_ptr<IGenerator<T>> m_generator;
  2930. public:
  2931. GeneratorWrapper(std::unique_ptr<IGenerator<T>> generator):
  2932. m_generator(std::move(generator))
  2933. {}
  2934. T const& get() const {
  2935. return m_generator->get();
  2936. }
  2937. bool next() {
  2938. return m_generator->next();
  2939. }
  2940. };
  2941. template <typename T>
  2942. GeneratorWrapper<T> value(T&& value) {
  2943. return GeneratorWrapper<T>(pf::make_unique<SingleValueGenerator<T>>(std::forward<T>(value)));
  2944. }
  2945. template <typename T>
  2946. GeneratorWrapper<T> values(std::initializer_list<T> values) {
  2947. return GeneratorWrapper<T>(pf::make_unique<FixedValuesGenerator<T>>(values));
  2948. }
  2949. template<typename T>
  2950. class Generators : public IGenerator<T> {
  2951. std::vector<GeneratorWrapper<T>> m_generators;
  2952. size_t m_current = 0;
  2953. void populate(GeneratorWrapper<T>&& generator) {
  2954. m_generators.emplace_back(std::move(generator));
  2955. }
  2956. void populate(T&& val) {
  2957. m_generators.emplace_back(value(std::move(val)));
  2958. }
  2959. template<typename U>
  2960. void populate(U&& val) {
  2961. populate(T(std::move(val)));
  2962. }
  2963. template<typename U, typename... Gs>
  2964. void populate(U&& valueOrGenerator, Gs... moreGenerators) {
  2965. populate(std::forward<U>(valueOrGenerator));
  2966. populate(std::forward<Gs>(moreGenerators)...);
  2967. }
  2968. public:
  2969. template <typename... Gs>
  2970. Generators(Gs... moreGenerators) {
  2971. m_generators.reserve(sizeof...(Gs));
  2972. populate(std::forward<Gs>(moreGenerators)...);
  2973. }
  2974. T const& get() const override {
  2975. return m_generators[m_current].get();
  2976. }
  2977. bool next() override {
  2978. if (m_current >= m_generators.size()) {
  2979. return false;
  2980. }
  2981. const bool current_status = m_generators[m_current].next();
  2982. if (!current_status) {
  2983. ++m_current;
  2984. }
  2985. return m_current < m_generators.size();
  2986. }
  2987. };
  2988. template<typename... Ts>
  2989. GeneratorWrapper<std::tuple<Ts...>> table( std::initializer_list<std::tuple<typename std::decay<Ts>::type...>> tuples ) {
  2990. return values<std::tuple<Ts...>>( tuples );
  2991. }
  2992. // Tag type to signal that a generator sequence should convert arguments to a specific type
  2993. template <typename T>
  2994. struct as {};
  2995. template<typename T, typename... Gs>
  2996. auto makeGenerators( GeneratorWrapper<T>&& generator, Gs... moreGenerators ) -> Generators<T> {
  2997. return Generators<T>(std::move(generator), std::forward<Gs>(moreGenerators)...);
  2998. }
  2999. template<typename T>
  3000. auto makeGenerators( GeneratorWrapper<T>&& generator ) -> Generators<T> {
  3001. return Generators<T>(std::move(generator));
  3002. }
  3003. template<typename T, typename... Gs>
  3004. auto makeGenerators( T&& val, Gs... moreGenerators ) -> Generators<T> {
  3005. return makeGenerators( value( std::forward<T>( val ) ), std::forward<Gs>( moreGenerators )... );
  3006. }
  3007. template<typename T, typename U, typename... Gs>
  3008. auto makeGenerators( as<T>, U&& val, Gs... moreGenerators ) -> Generators<T> {
  3009. return makeGenerators( value( T( std::forward<U>( val ) ) ), std::forward<Gs>( moreGenerators )... );
  3010. }
  3011. auto acquireGeneratorTracker( SourceLineInfo const& lineInfo ) -> IGeneratorTracker&;
  3012. template<typename L>
  3013. // Note: The type after -> is weird, because VS2015 cannot parse
  3014. // the expression used in the typedef inside, when it is in
  3015. // return type. Yeah.
  3016. auto generate( SourceLineInfo const& lineInfo, L const& generatorExpression ) -> decltype(std::declval<decltype(generatorExpression())>().get()) {
  3017. using UnderlyingType = typename decltype(generatorExpression())::type;
  3018. IGeneratorTracker& tracker = acquireGeneratorTracker( lineInfo );
  3019. if (!tracker.hasGenerator()) {
  3020. tracker.setGenerator(pf::make_unique<Generators<UnderlyingType>>(generatorExpression()));
  3021. }
  3022. auto const& generator = static_cast<IGenerator<UnderlyingType> const&>( *tracker.getGenerator() );
  3023. return generator.get();
  3024. }
  3025. } // namespace Generators
  3026. } // namespace Catch
  3027. #define GENERATE( ... ) \
  3028. Catch::Generators::generate( CATCH_INTERNAL_LINEINFO, [ ]{ using namespace Catch::Generators; return makeGenerators( __VA_ARGS__ ); } )
  3029. #define GENERATE_COPY( ... ) \
  3030. Catch::Generators::generate( CATCH_INTERNAL_LINEINFO, [=]{ using namespace Catch::Generators; return makeGenerators( __VA_ARGS__ ); } )
  3031. #define GENERATE_REF( ... ) \
  3032. Catch::Generators::generate( CATCH_INTERNAL_LINEINFO, [&]{ using namespace Catch::Generators; return makeGenerators( __VA_ARGS__ ); } )
  3033. // end catch_generators.hpp
  3034. // start catch_generators_generic.hpp
  3035. namespace Catch {
  3036. namespace Generators {
  3037. template <typename T>
  3038. class TakeGenerator : public IGenerator<T> {
  3039. GeneratorWrapper<T> m_generator;
  3040. size_t m_returned = 0;
  3041. size_t m_target;
  3042. public:
  3043. TakeGenerator(size_t target, GeneratorWrapper<T>&& generator):
  3044. m_generator(std::move(generator)),
  3045. m_target(target)
  3046. {
  3047. assert(target != 0 && "Empty generators are not allowed");
  3048. }
  3049. T const& get() const override {
  3050. return m_generator.get();
  3051. }
  3052. bool next() override {
  3053. ++m_returned;
  3054. if (m_returned >= m_target) {
  3055. return false;
  3056. }
  3057. const auto success = m_generator.next();
  3058. // If the underlying generator does not contain enough values
  3059. // then we cut short as well
  3060. if (!success) {
  3061. m_returned = m_target;
  3062. }
  3063. return success;
  3064. }
  3065. };
  3066. template <typename T>
  3067. GeneratorWrapper<T> take(size_t target, GeneratorWrapper<T>&& generator) {
  3068. return GeneratorWrapper<T>(pf::make_unique<TakeGenerator<T>>(target, std::move(generator)));
  3069. }
  3070. template <typename T, typename Predicate>
  3071. class FilterGenerator : public IGenerator<T> {
  3072. GeneratorWrapper<T> m_generator;
  3073. Predicate m_predicate;
  3074. public:
  3075. template <typename P = Predicate>
  3076. FilterGenerator(P&& pred, GeneratorWrapper<T>&& generator):
  3077. m_generator(std::move(generator)),
  3078. m_predicate(std::forward<P>(pred))
  3079. {
  3080. if (!m_predicate(m_generator.get())) {
  3081. // It might happen that there are no values that pass the
  3082. // filter. In that case we throw an exception.
  3083. auto has_initial_value = next();
  3084. if (!has_initial_value) {
  3085. Catch::throw_exception(GeneratorException("No valid value found in filtered generator"));
  3086. }
  3087. }
  3088. }
  3089. T const& get() const override {
  3090. return m_generator.get();
  3091. }
  3092. bool next() override {
  3093. bool success = m_generator.next();
  3094. if (!success) {
  3095. return false;
  3096. }
  3097. while (!m_predicate(m_generator.get()) && (success = m_generator.next()) == true);
  3098. return success;
  3099. }
  3100. };
  3101. template <typename T, typename Predicate>
  3102. GeneratorWrapper<T> filter(Predicate&& pred, GeneratorWrapper<T>&& generator) {
  3103. return GeneratorWrapper<T>(std::unique_ptr<IGenerator<T>>(pf::make_unique<FilterGenerator<T, Predicate>>(std::forward<Predicate>(pred), std::move(generator))));
  3104. }
  3105. template <typename T>
  3106. class RepeatGenerator : public IGenerator<T> {
  3107. GeneratorWrapper<T> m_generator;
  3108. mutable std::vector<T> m_returned;
  3109. size_t m_target_repeats;
  3110. size_t m_current_repeat = 0;
  3111. size_t m_repeat_index = 0;
  3112. public:
  3113. RepeatGenerator(size_t repeats, GeneratorWrapper<T>&& generator):
  3114. m_generator(std::move(generator)),
  3115. m_target_repeats(repeats)
  3116. {
  3117. assert(m_target_repeats > 0 && "Repeat generator must repeat at least once");
  3118. }
  3119. T const& get() const override {
  3120. if (m_current_repeat == 0) {
  3121. m_returned.push_back(m_generator.get());
  3122. return m_returned.back();
  3123. }
  3124. return m_returned[m_repeat_index];
  3125. }
  3126. bool next() override {
  3127. // There are 2 basic cases:
  3128. // 1) We are still reading the generator
  3129. // 2) We are reading our own cache
  3130. // In the first case, we need to poke the underlying generator.
  3131. // If it happily moves, we are left in that state, otherwise it is time to start reading from our cache
  3132. if (m_current_repeat == 0) {
  3133. const auto success = m_generator.next();
  3134. if (!success) {
  3135. ++m_current_repeat;
  3136. }
  3137. return m_current_repeat < m_target_repeats;
  3138. }
  3139. // In the second case, we need to move indices forward and check that we haven't run up against the end
  3140. ++m_repeat_index;
  3141. if (m_repeat_index == m_returned.size()) {
  3142. m_repeat_index = 0;
  3143. ++m_current_repeat;
  3144. }
  3145. return m_current_repeat < m_target_repeats;
  3146. }
  3147. };
  3148. template <typename T>
  3149. GeneratorWrapper<T> repeat(size_t repeats, GeneratorWrapper<T>&& generator) {
  3150. return GeneratorWrapper<T>(pf::make_unique<RepeatGenerator<T>>(repeats, std::move(generator)));
  3151. }
  3152. template <typename T, typename U, typename Func>
  3153. class MapGenerator : public IGenerator<T> {
  3154. // TBD: provide static assert for mapping function, for friendly error message
  3155. GeneratorWrapper<U> m_generator;
  3156. Func m_function;
  3157. // To avoid returning dangling reference, we have to save the values
  3158. T m_cache;
  3159. public:
  3160. template <typename F2 = Func>
  3161. MapGenerator(F2&& function, GeneratorWrapper<U>&& generator) :
  3162. m_generator(std::move(generator)),
  3163. m_function(std::forward<F2>(function)),
  3164. m_cache(m_function(m_generator.get()))
  3165. {}
  3166. T const& get() const override {
  3167. return m_cache;
  3168. }
  3169. bool next() override {
  3170. const auto success = m_generator.next();
  3171. if (success) {
  3172. m_cache = m_function(m_generator.get());
  3173. }
  3174. return success;
  3175. }
  3176. };
  3177. #if defined(__cpp_lib_is_invocable) && __cpp_lib_is_invocable >= 201703
  3178. // std::result_of is deprecated in C++17 and removed in C++20. Hence, it is
  3179. // replaced with std::invoke_result here. Also *_t format is preferred over
  3180. // typename *::type format.
  3181. template <typename Func, typename U>
  3182. using MapFunctionReturnType = std::remove_reference_t<std::remove_cv_t<std::invoke_result_t<Func, U>>>;
  3183. #else
  3184. template <typename Func, typename U>
  3185. using MapFunctionReturnType = typename std::remove_reference<typename std::remove_cv<typename std::result_of<Func(U)>::type>::type>::type;
  3186. #endif
  3187. template <typename Func, typename U, typename T = MapFunctionReturnType<Func, U>>
  3188. GeneratorWrapper<T> map(Func&& function, GeneratorWrapper<U>&& generator) {
  3189. return GeneratorWrapper<T>(
  3190. pf::make_unique<MapGenerator<T, U, Func>>(std::forward<Func>(function), std::move(generator))
  3191. );
  3192. }
  3193. template <typename T, typename U, typename Func>
  3194. GeneratorWrapper<T> map(Func&& function, GeneratorWrapper<U>&& generator) {
  3195. return GeneratorWrapper<T>(
  3196. pf::make_unique<MapGenerator<T, U, Func>>(std::forward<Func>(function), std::move(generator))
  3197. );
  3198. }
  3199. template <typename T>
  3200. class ChunkGenerator final : public IGenerator<std::vector<T>> {
  3201. std::vector<T> m_chunk;
  3202. size_t m_chunk_size;
  3203. GeneratorWrapper<T> m_generator;
  3204. bool m_used_up = false;
  3205. public:
  3206. ChunkGenerator(size_t size, GeneratorWrapper<T> generator) :
  3207. m_chunk_size(size), m_generator(std::move(generator))
  3208. {
  3209. m_chunk.reserve(m_chunk_size);
  3210. m_chunk.push_back(m_generator.get());
  3211. for (size_t i = 1; i < m_chunk_size; ++i) {
  3212. if (!m_generator.next()) {
  3213. Catch::throw_exception(GeneratorException("Not enough values to initialize the first chunk"));
  3214. }
  3215. m_chunk.push_back(m_generator.get());
  3216. }
  3217. }
  3218. std::vector<T> const& get() const override {
  3219. return m_chunk;
  3220. }
  3221. bool next() override {
  3222. m_chunk.clear();
  3223. for (size_t idx = 0; idx < m_chunk_size; ++idx) {
  3224. if (!m_generator.next()) {
  3225. return false;
  3226. }
  3227. m_chunk.push_back(m_generator.get());
  3228. }
  3229. return true;
  3230. }
  3231. };
  3232. template <typename T>
  3233. GeneratorWrapper<std::vector<T>> chunk(size_t size, GeneratorWrapper<T>&& generator) {
  3234. return GeneratorWrapper<std::vector<T>>(
  3235. pf::make_unique<ChunkGenerator<T>>(size, std::move(generator))
  3236. );
  3237. }
  3238. } // namespace Generators
  3239. } // namespace Catch
  3240. // end catch_generators_generic.hpp
  3241. // start catch_generators_specific.hpp
  3242. // start catch_context.h
  3243. #include <memory>
  3244. namespace Catch {
  3245. struct IResultCapture;
  3246. struct IRunner;
  3247. struct IConfig;
  3248. struct IMutableContext;
  3249. using IConfigPtr = std::shared_ptr<IConfig const>;
  3250. struct IContext
  3251. {
  3252. virtual ~IContext();
  3253. virtual IResultCapture* getResultCapture() = 0;
  3254. virtual IRunner* getRunner() = 0;
  3255. virtual IConfigPtr const& getConfig() const = 0;
  3256. };
  3257. struct IMutableContext : IContext
  3258. {
  3259. virtual ~IMutableContext();
  3260. virtual void setResultCapture( IResultCapture* resultCapture ) = 0;
  3261. virtual void setRunner( IRunner* runner ) = 0;
  3262. virtual void setConfig( IConfigPtr const& config ) = 0;
  3263. private:
  3264. static IMutableContext *currentContext;
  3265. friend IMutableContext& getCurrentMutableContext();
  3266. friend void cleanUpContext();
  3267. static void createContext();
  3268. };
  3269. inline IMutableContext& getCurrentMutableContext()
  3270. {
  3271. if( !IMutableContext::currentContext )
  3272. IMutableContext::createContext();
  3273. return *IMutableContext::currentContext;
  3274. }
  3275. inline IContext& getCurrentContext()
  3276. {
  3277. return getCurrentMutableContext();
  3278. }
  3279. void cleanUpContext();
  3280. }
  3281. // end catch_context.h
  3282. // start catch_interfaces_config.h
  3283. #include <iosfwd>
  3284. #include <string>
  3285. #include <vector>
  3286. #include <memory>
  3287. namespace Catch {
  3288. enum class Verbosity {
  3289. Quiet = 0,
  3290. Normal,
  3291. High
  3292. };
  3293. struct WarnAbout { enum What {
  3294. Nothing = 0x00,
  3295. NoAssertions = 0x01,
  3296. NoTests = 0x02
  3297. }; };
  3298. struct ShowDurations { enum OrNot {
  3299. DefaultForReporter,
  3300. Always,
  3301. Never
  3302. }; };
  3303. struct RunTests { enum InWhatOrder {
  3304. InDeclarationOrder,
  3305. InLexicographicalOrder,
  3306. InRandomOrder
  3307. }; };
  3308. struct UseColour { enum YesOrNo {
  3309. Auto,
  3310. Yes,
  3311. No
  3312. }; };
  3313. struct WaitForKeypress { enum When {
  3314. Never,
  3315. BeforeStart = 1,
  3316. BeforeExit = 2,
  3317. BeforeStartAndExit = BeforeStart | BeforeExit
  3318. }; };
  3319. class TestSpec;
  3320. struct IConfig : NonCopyable {
  3321. virtual ~IConfig();
  3322. virtual bool allowThrows() const = 0;
  3323. virtual std::ostream& stream() const = 0;
  3324. virtual std::string name() const = 0;
  3325. virtual bool includeSuccessfulResults() const = 0;
  3326. virtual bool shouldDebugBreak() const = 0;
  3327. virtual bool warnAboutMissingAssertions() const = 0;
  3328. virtual bool warnAboutNoTests() const = 0;
  3329. virtual int abortAfter() const = 0;
  3330. virtual bool showInvisibles() const = 0;
  3331. virtual ShowDurations::OrNot showDurations() const = 0;
  3332. virtual TestSpec const& testSpec() const = 0;
  3333. virtual bool hasTestFilters() const = 0;
  3334. virtual std::vector<std::string> const& getTestsOrTags() const = 0;
  3335. virtual RunTests::InWhatOrder runOrder() const = 0;
  3336. virtual unsigned int rngSeed() const = 0;
  3337. virtual int benchmarkResolutionMultiple() const = 0;
  3338. virtual UseColour::YesOrNo useColour() const = 0;
  3339. virtual std::vector<std::string> const& getSectionsToRun() const = 0;
  3340. virtual Verbosity verbosity() const = 0;
  3341. };
  3342. using IConfigPtr = std::shared_ptr<IConfig const>;
  3343. }
  3344. // end catch_interfaces_config.h
  3345. #include <random>
  3346. namespace Catch {
  3347. namespace Generators {
  3348. template <typename Float>
  3349. class RandomFloatingGenerator final : public IGenerator<Float> {
  3350. // FIXME: What is the right seed?
  3351. std::minstd_rand m_rand;
  3352. std::uniform_real_distribution<Float> m_dist;
  3353. Float m_current_number;
  3354. public:
  3355. RandomFloatingGenerator(Float a, Float b):
  3356. m_rand(getCurrentContext().getConfig()->rngSeed()),
  3357. m_dist(a, b) {
  3358. static_cast<void>(next());
  3359. }
  3360. Float const& get() const override {
  3361. return m_current_number;
  3362. }
  3363. bool next() override {
  3364. m_current_number = m_dist(m_rand);
  3365. return true;
  3366. }
  3367. };
  3368. template <typename Integer>
  3369. class RandomIntegerGenerator final : public IGenerator<Integer> {
  3370. std::minstd_rand m_rand;
  3371. std::uniform_int_distribution<Integer> m_dist;
  3372. Integer m_current_number;
  3373. public:
  3374. RandomIntegerGenerator(Integer a, Integer b):
  3375. m_rand(getCurrentContext().getConfig()->rngSeed()),
  3376. m_dist(a, b) {
  3377. static_cast<void>(next());
  3378. }
  3379. Integer const& get() const override {
  3380. return m_current_number;
  3381. }
  3382. bool next() override {
  3383. m_current_number = m_dist(m_rand);
  3384. return true;
  3385. }
  3386. };
  3387. // TODO: Ideally this would be also constrained against the various char types,
  3388. // but I don't expect users to run into that in practice.
  3389. template <typename T>
  3390. typename std::enable_if<std::is_integral<T>::value && !std::is_same<T, bool>::value,
  3391. GeneratorWrapper<T>>::type
  3392. random(T a, T b) {
  3393. return GeneratorWrapper<T>(
  3394. pf::make_unique<RandomIntegerGenerator<T>>(a, b)
  3395. );
  3396. }
  3397. template <typename T>
  3398. typename std::enable_if<std::is_floating_point<T>::value,
  3399. GeneratorWrapper<T>>::type
  3400. random(T a, T b) {
  3401. return GeneratorWrapper<T>(
  3402. pf::make_unique<RandomFloatingGenerator<T>>(a, b)
  3403. );
  3404. }
  3405. template <typename T>
  3406. class RangeGenerator final : public IGenerator<T> {
  3407. T m_current;
  3408. T m_end;
  3409. T m_step;
  3410. bool m_positive;
  3411. public:
  3412. RangeGenerator(T const& start, T const& end, T const& step):
  3413. m_current(start),
  3414. m_end(end),
  3415. m_step(step),
  3416. m_positive(m_step > T(0))
  3417. {
  3418. assert(m_current != m_end && "Range start and end cannot be equal");
  3419. assert(m_step != T(0) && "Step size cannot be zero");
  3420. assert(((m_positive && m_current <= m_end) || (!m_positive && m_current >= m_end)) && "Step moves away from end");
  3421. }
  3422. RangeGenerator(T const& start, T const& end):
  3423. RangeGenerator(start, end, (start < end) ? T(1) : T(-1))
  3424. {}
  3425. T const& get() const override {
  3426. return m_current;
  3427. }
  3428. bool next() override {
  3429. m_current += m_step;
  3430. return (m_positive) ? (m_current < m_end) : (m_current > m_end);
  3431. }
  3432. };
  3433. template <typename T>
  3434. GeneratorWrapper<T> range(T const& start, T const& end, T const& step) {
  3435. static_assert(std::is_integral<T>::value && !std::is_same<T, bool>::value, "Type must be an integer");
  3436. return GeneratorWrapper<T>(pf::make_unique<RangeGenerator<T>>(start, end, step));
  3437. }
  3438. template <typename T>
  3439. GeneratorWrapper<T> range(T const& start, T const& end) {
  3440. static_assert(std::is_integral<T>::value && !std::is_same<T, bool>::value, "Type must be an integer");
  3441. return GeneratorWrapper<T>(pf::make_unique<RangeGenerator<T>>(start, end));
  3442. }
  3443. } // namespace Generators
  3444. } // namespace Catch
  3445. // end catch_generators_specific.hpp
  3446. // These files are included here so the single_include script doesn't put them
  3447. // in the conditionally compiled sections
  3448. // start catch_test_case_info.h
  3449. #include <string>
  3450. #include <vector>
  3451. #include <memory>
  3452. #ifdef __clang__
  3453. #pragma clang diagnostic push
  3454. #pragma clang diagnostic ignored "-Wpadded"
  3455. #endif
  3456. namespace Catch {
  3457. struct ITestInvoker;
  3458. struct TestCaseInfo {
  3459. enum SpecialProperties{
  3460. None = 0,
  3461. IsHidden = 1 << 1,
  3462. ShouldFail = 1 << 2,
  3463. MayFail = 1 << 3,
  3464. Throws = 1 << 4,
  3465. NonPortable = 1 << 5,
  3466. Benchmark = 1 << 6
  3467. };
  3468. TestCaseInfo( std::string const& _name,
  3469. std::string const& _className,
  3470. std::string const& _description,
  3471. std::vector<std::string> const& _tags,
  3472. SourceLineInfo const& _lineInfo );
  3473. friend void setTags( TestCaseInfo& testCaseInfo, std::vector<std::string> tags );
  3474. bool isHidden() const;
  3475. bool throws() const;
  3476. bool okToFail() const;
  3477. bool expectedToFail() const;
  3478. std::string tagsAsString() const;
  3479. std::string name;
  3480. std::string className;
  3481. std::string description;
  3482. std::vector<std::string> tags;
  3483. std::vector<std::string> lcaseTags;
  3484. SourceLineInfo lineInfo;
  3485. SpecialProperties properties;
  3486. };
  3487. class TestCase : public TestCaseInfo {
  3488. public:
  3489. TestCase( ITestInvoker* testCase, TestCaseInfo&& info );
  3490. TestCase withName( std::string const& _newName ) const;
  3491. void invoke() const;
  3492. TestCaseInfo const& getTestCaseInfo() const;
  3493. bool operator == ( TestCase const& other ) const;
  3494. bool operator < ( TestCase const& other ) const;
  3495. private:
  3496. std::shared_ptr<ITestInvoker> test;
  3497. };
  3498. TestCase makeTestCase( ITestInvoker* testCase,
  3499. std::string const& className,
  3500. NameAndTags const& nameAndTags,
  3501. SourceLineInfo const& lineInfo );
  3502. }
  3503. #ifdef __clang__
  3504. #pragma clang diagnostic pop
  3505. #endif
  3506. // end catch_test_case_info.h
  3507. // start catch_interfaces_runner.h
  3508. namespace Catch {
  3509. struct IRunner {
  3510. virtual ~IRunner();
  3511. virtual bool aborting() const = 0;
  3512. };
  3513. }
  3514. // end catch_interfaces_runner.h
  3515. #ifdef __OBJC__
  3516. // start catch_objc.hpp
  3517. #import <objc/runtime.h>
  3518. #include <string>
  3519. // NB. Any general catch headers included here must be included
  3520. // in catch.hpp first to make sure they are included by the single
  3521. // header for non obj-usage
  3522. ///////////////////////////////////////////////////////////////////////////////
  3523. // This protocol is really only here for (self) documenting purposes, since
  3524. // all its methods are optional.
  3525. @protocol OcFixture
  3526. @optional
  3527. -(void) setUp;
  3528. -(void) tearDown;
  3529. @end
  3530. namespace Catch {
  3531. class OcMethod : public ITestInvoker {
  3532. public:
  3533. OcMethod( Class cls, SEL sel ) : m_cls( cls ), m_sel( sel ) {}
  3534. virtual void invoke() const {
  3535. id obj = [[m_cls alloc] init];
  3536. performOptionalSelector( obj, @selector(setUp) );
  3537. performOptionalSelector( obj, m_sel );
  3538. performOptionalSelector( obj, @selector(tearDown) );
  3539. arcSafeRelease( obj );
  3540. }
  3541. private:
  3542. virtual ~OcMethod() {}
  3543. Class m_cls;
  3544. SEL m_sel;
  3545. };
  3546. namespace Detail{
  3547. inline std::string getAnnotation( Class cls,
  3548. std::string const& annotationName,
  3549. std::string const& testCaseName ) {
  3550. NSString* selStr = [[NSString alloc] initWithFormat:@"Catch_%s_%s", annotationName.c_str(), testCaseName.c_str()];
  3551. SEL sel = NSSelectorFromString( selStr );
  3552. arcSafeRelease( selStr );
  3553. id value = performOptionalSelector( cls, sel );
  3554. if( value )
  3555. return [(NSString*)value UTF8String];
  3556. return "";
  3557. }
  3558. }
  3559. inline std::size_t registerTestMethods() {
  3560. std::size_t noTestMethods = 0;
  3561. int noClasses = objc_getClassList( nullptr, 0 );
  3562. Class* classes = (CATCH_UNSAFE_UNRETAINED Class *)malloc( sizeof(Class) * noClasses);
  3563. objc_getClassList( classes, noClasses );
  3564. for( int c = 0; c < noClasses; c++ ) {
  3565. Class cls = classes[c];
  3566. {
  3567. u_int count;
  3568. Method* methods = class_copyMethodList( cls, &count );
  3569. for( u_int m = 0; m < count ; m++ ) {
  3570. SEL selector = method_getName(methods[m]);
  3571. std::string methodName = sel_getName(selector);
  3572. if( startsWith( methodName, "Catch_TestCase_" ) ) {
  3573. std::string testCaseName = methodName.substr( 15 );
  3574. std::string name = Detail::getAnnotation( cls, "Name", testCaseName );
  3575. std::string desc = Detail::getAnnotation( cls, "Description", testCaseName );
  3576. const char* className = class_getName( cls );
  3577. getMutableRegistryHub().registerTest( makeTestCase( new OcMethod( cls, selector ), className, NameAndTags( name.c_str(), desc.c_str() ), SourceLineInfo("",0) ) );
  3578. noTestMethods++;
  3579. }
  3580. }
  3581. free(methods);
  3582. }
  3583. }
  3584. return noTestMethods;
  3585. }
  3586. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  3587. namespace Matchers {
  3588. namespace Impl {
  3589. namespace NSStringMatchers {
  3590. struct StringHolder : MatcherBase<NSString*>{
  3591. StringHolder( NSString* substr ) : m_substr( [substr copy] ){}
  3592. StringHolder( StringHolder const& other ) : m_substr( [other.m_substr copy] ){}
  3593. StringHolder() {
  3594. arcSafeRelease( m_substr );
  3595. }
  3596. bool match( NSString* const& str ) const override {
  3597. return false;
  3598. }
  3599. NSString* CATCH_ARC_STRONG m_substr;
  3600. };
  3601. struct Equals : StringHolder {
  3602. Equals( NSString* substr ) : StringHolder( substr ){}
  3603. bool match( NSString* const& str ) const override {
  3604. return (str != nil || m_substr == nil ) &&
  3605. [str isEqualToString:m_substr];
  3606. }
  3607. std::string describe() const override {
  3608. return "equals string: " + Catch::Detail::stringify( m_substr );
  3609. }
  3610. };
  3611. struct Contains : StringHolder {
  3612. Contains( NSString* substr ) : StringHolder( substr ){}
  3613. bool match( NSString* const& str ) const override {
  3614. return (str != nil || m_substr == nil ) &&
  3615. [str rangeOfString:m_substr].location != NSNotFound;
  3616. }
  3617. std::string describe() const override {
  3618. return "contains string: " + Catch::Detail::stringify( m_substr );
  3619. }
  3620. };
  3621. struct StartsWith : StringHolder {
  3622. StartsWith( NSString* substr ) : StringHolder( substr ){}
  3623. bool match( NSString* const& str ) const override {
  3624. return (str != nil || m_substr == nil ) &&
  3625. [str rangeOfString:m_substr].location == 0;
  3626. }
  3627. std::string describe() const override {
  3628. return "starts with: " + Catch::Detail::stringify( m_substr );
  3629. }
  3630. };
  3631. struct EndsWith : StringHolder {
  3632. EndsWith( NSString* substr ) : StringHolder( substr ){}
  3633. bool match( NSString* const& str ) const override {
  3634. return (str != nil || m_substr == nil ) &&
  3635. [str rangeOfString:m_substr].location == [str length] - [m_substr length];
  3636. }
  3637. std::string describe() const override {
  3638. return "ends with: " + Catch::Detail::stringify( m_substr );
  3639. }
  3640. };
  3641. } // namespace NSStringMatchers
  3642. } // namespace Impl
  3643. inline Impl::NSStringMatchers::Equals
  3644. Equals( NSString* substr ){ return Impl::NSStringMatchers::Equals( substr ); }
  3645. inline Impl::NSStringMatchers::Contains
  3646. Contains( NSString* substr ){ return Impl::NSStringMatchers::Contains( substr ); }
  3647. inline Impl::NSStringMatchers::StartsWith
  3648. StartsWith( NSString* substr ){ return Impl::NSStringMatchers::StartsWith( substr ); }
  3649. inline Impl::NSStringMatchers::EndsWith
  3650. EndsWith( NSString* substr ){ return Impl::NSStringMatchers::EndsWith( substr ); }
  3651. } // namespace Matchers
  3652. using namespace Matchers;
  3653. #endif // CATCH_CONFIG_DISABLE_MATCHERS
  3654. } // namespace Catch
  3655. ///////////////////////////////////////////////////////////////////////////////
  3656. #define OC_MAKE_UNIQUE_NAME( root, uniqueSuffix ) root##uniqueSuffix
  3657. #define OC_TEST_CASE2( name, desc, uniqueSuffix ) \
  3658. +(NSString*) OC_MAKE_UNIQUE_NAME( Catch_Name_test_, uniqueSuffix ) \
  3659. { \
  3660. return @ name; \
  3661. } \
  3662. +(NSString*) OC_MAKE_UNIQUE_NAME( Catch_Description_test_, uniqueSuffix ) \
  3663. { \
  3664. return @ desc; \
  3665. } \
  3666. -(void) OC_MAKE_UNIQUE_NAME( Catch_TestCase_test_, uniqueSuffix )
  3667. #define OC_TEST_CASE( name, desc ) OC_TEST_CASE2( name, desc, __LINE__ )
  3668. // end catch_objc.hpp
  3669. #endif
  3670. #ifdef CATCH_CONFIG_EXTERNAL_INTERFACES
  3671. // start catch_external_interfaces.h
  3672. // start catch_reporter_bases.hpp
  3673. // start catch_interfaces_reporter.h
  3674. // start catch_config.hpp
  3675. // start catch_test_spec_parser.h
  3676. #ifdef __clang__
  3677. #pragma clang diagnostic push
  3678. #pragma clang diagnostic ignored "-Wpadded"
  3679. #endif
  3680. // start catch_test_spec.h
  3681. #ifdef __clang__
  3682. #pragma clang diagnostic push
  3683. #pragma clang diagnostic ignored "-Wpadded"
  3684. #endif
  3685. // start catch_wildcard_pattern.h
  3686. namespace Catch
  3687. {
  3688. class WildcardPattern {
  3689. enum WildcardPosition {
  3690. NoWildcard = 0,
  3691. WildcardAtStart = 1,
  3692. WildcardAtEnd = 2,
  3693. WildcardAtBothEnds = WildcardAtStart | WildcardAtEnd
  3694. };
  3695. public:
  3696. WildcardPattern( std::string const& pattern, CaseSensitive::Choice caseSensitivity );
  3697. virtual ~WildcardPattern() = default;
  3698. virtual bool matches( std::string const& str ) const;
  3699. private:
  3700. std::string adjustCase( std::string const& str ) const;
  3701. CaseSensitive::Choice m_caseSensitivity;
  3702. WildcardPosition m_wildcard = NoWildcard;
  3703. std::string m_pattern;
  3704. };
  3705. }
  3706. // end catch_wildcard_pattern.h
  3707. #include <string>
  3708. #include <vector>
  3709. #include <memory>
  3710. namespace Catch {
  3711. class TestSpec {
  3712. struct Pattern {
  3713. virtual ~Pattern();
  3714. virtual bool matches( TestCaseInfo const& testCase ) const = 0;
  3715. };
  3716. using PatternPtr = std::shared_ptr<Pattern>;
  3717. class NamePattern : public Pattern {
  3718. public:
  3719. NamePattern( std::string const& name );
  3720. virtual ~NamePattern();
  3721. bool matches( TestCaseInfo const& testCase ) const override;
  3722. private:
  3723. WildcardPattern m_wildcardPattern;
  3724. };
  3725. class TagPattern : public Pattern {
  3726. public:
  3727. TagPattern( std::string const& tag );
  3728. virtual ~TagPattern();
  3729. bool matches( TestCaseInfo const& testCase ) const override;
  3730. private:
  3731. std::string m_tag;
  3732. };
  3733. class ExcludedPattern : public Pattern {
  3734. public:
  3735. ExcludedPattern( PatternPtr const& underlyingPattern );
  3736. virtual ~ExcludedPattern();
  3737. bool matches( TestCaseInfo const& testCase ) const override;
  3738. private:
  3739. PatternPtr m_underlyingPattern;
  3740. };
  3741. struct Filter {
  3742. std::vector<PatternPtr> m_patterns;
  3743. bool matches( TestCaseInfo const& testCase ) const;
  3744. };
  3745. public:
  3746. bool hasFilters() const;
  3747. bool matches( TestCaseInfo const& testCase ) const;
  3748. private:
  3749. std::vector<Filter> m_filters;
  3750. friend class TestSpecParser;
  3751. };
  3752. }
  3753. #ifdef __clang__
  3754. #pragma clang diagnostic pop
  3755. #endif
  3756. // end catch_test_spec.h
  3757. // start catch_interfaces_tag_alias_registry.h
  3758. #include <string>
  3759. namespace Catch {
  3760. struct TagAlias;
  3761. struct ITagAliasRegistry {
  3762. virtual ~ITagAliasRegistry();
  3763. // Nullptr if not present
  3764. virtual TagAlias const* find( std::string const& alias ) const = 0;
  3765. virtual std::string expandAliases( std::string const& unexpandedTestSpec ) const = 0;
  3766. static ITagAliasRegistry const& get();
  3767. };
  3768. } // end namespace Catch
  3769. // end catch_interfaces_tag_alias_registry.h
  3770. namespace Catch {
  3771. class TestSpecParser {
  3772. enum Mode{ None, Name, QuotedName, Tag, EscapedName };
  3773. Mode m_mode = None;
  3774. bool m_exclusion = false;
  3775. std::size_t m_start = std::string::npos, m_pos = 0;
  3776. std::string m_arg;
  3777. std::vector<std::size_t> m_escapeChars;
  3778. TestSpec::Filter m_currentFilter;
  3779. TestSpec m_testSpec;
  3780. ITagAliasRegistry const* m_tagAliases = nullptr;
  3781. public:
  3782. TestSpecParser( ITagAliasRegistry const& tagAliases );
  3783. TestSpecParser& parse( std::string const& arg );
  3784. TestSpec testSpec();
  3785. private:
  3786. void visitChar( char c );
  3787. void startNewMode( Mode mode, std::size_t start );
  3788. void escape();
  3789. std::string subString() const;
  3790. template<typename T>
  3791. void addPattern() {
  3792. std::string token = subString();
  3793. for( std::size_t i = 0; i < m_escapeChars.size(); ++i )
  3794. token = token.substr( 0, m_escapeChars[i]-m_start-i ) + token.substr( m_escapeChars[i]-m_start-i+1 );
  3795. m_escapeChars.clear();
  3796. if( startsWith( token, "exclude:" ) ) {
  3797. m_exclusion = true;
  3798. token = token.substr( 8 );
  3799. }
  3800. if( !token.empty() ) {
  3801. TestSpec::PatternPtr pattern = std::make_shared<T>( token );
  3802. if( m_exclusion )
  3803. pattern = std::make_shared<TestSpec::ExcludedPattern>( pattern );
  3804. m_currentFilter.m_patterns.push_back( pattern );
  3805. }
  3806. m_exclusion = false;
  3807. m_mode = None;
  3808. }
  3809. void addFilter();
  3810. };
  3811. TestSpec parseTestSpec( std::string const& arg );
  3812. } // namespace Catch
  3813. #ifdef __clang__
  3814. #pragma clang diagnostic pop
  3815. #endif
  3816. // end catch_test_spec_parser.h
  3817. // Libstdc++ doesn't like incomplete classes for unique_ptr
  3818. #include <memory>
  3819. #include <vector>
  3820. #include <string>
  3821. #ifndef CATCH_CONFIG_CONSOLE_WIDTH
  3822. #define CATCH_CONFIG_CONSOLE_WIDTH 80
  3823. #endif
  3824. namespace Catch {
  3825. struct IStream;
  3826. struct ConfigData {
  3827. bool listTests = false;
  3828. bool listTags = false;
  3829. bool listReporters = false;
  3830. bool listTestNamesOnly = false;
  3831. bool showSuccessfulTests = false;
  3832. bool shouldDebugBreak = false;
  3833. bool noThrow = false;
  3834. bool showHelp = false;
  3835. bool showInvisibles = false;
  3836. bool filenamesAsTags = false;
  3837. bool libIdentify = false;
  3838. int abortAfter = -1;
  3839. unsigned int rngSeed = 0;
  3840. int benchmarkResolutionMultiple = 100;
  3841. Verbosity verbosity = Verbosity::Normal;
  3842. WarnAbout::What warnings = WarnAbout::Nothing;
  3843. ShowDurations::OrNot showDurations = ShowDurations::DefaultForReporter;
  3844. RunTests::InWhatOrder runOrder = RunTests::InDeclarationOrder;
  3845. UseColour::YesOrNo useColour = UseColour::Auto;
  3846. WaitForKeypress::When waitForKeypress = WaitForKeypress::Never;
  3847. std::string outputFilename;
  3848. std::string name;
  3849. std::string processName;
  3850. #ifndef CATCH_CONFIG_DEFAULT_REPORTER
  3851. #define CATCH_CONFIG_DEFAULT_REPORTER "console"
  3852. #endif
  3853. std::string reporterName = CATCH_CONFIG_DEFAULT_REPORTER;
  3854. #undef CATCH_CONFIG_DEFAULT_REPORTER
  3855. std::vector<std::string> testsOrTags;
  3856. std::vector<std::string> sectionsToRun;
  3857. };
  3858. class Config : public IConfig {
  3859. public:
  3860. Config() = default;
  3861. Config( ConfigData const& data );
  3862. virtual ~Config() = default;
  3863. std::string const& getFilename() const;
  3864. bool listTests() const;
  3865. bool listTestNamesOnly() const;
  3866. bool listTags() const;
  3867. bool listReporters() const;
  3868. std::string getProcessName() const;
  3869. std::string const& getReporterName() const;
  3870. std::vector<std::string> const& getTestsOrTags() const override;
  3871. std::vector<std::string> const& getSectionsToRun() const override;
  3872. TestSpec const& testSpec() const override;
  3873. bool hasTestFilters() const override;
  3874. bool showHelp() const;
  3875. // IConfig interface
  3876. bool allowThrows() const override;
  3877. std::ostream& stream() const override;
  3878. std::string name() const override;
  3879. bool includeSuccessfulResults() const override;
  3880. bool warnAboutMissingAssertions() const override;
  3881. bool warnAboutNoTests() const override;
  3882. ShowDurations::OrNot showDurations() const override;
  3883. RunTests::InWhatOrder runOrder() const override;
  3884. unsigned int rngSeed() const override;
  3885. int benchmarkResolutionMultiple() const override;
  3886. UseColour::YesOrNo useColour() const override;
  3887. bool shouldDebugBreak() const override;
  3888. int abortAfter() const override;
  3889. bool showInvisibles() const override;
  3890. Verbosity verbosity() const override;
  3891. private:
  3892. IStream const* openStream();
  3893. ConfigData m_data;
  3894. std::unique_ptr<IStream const> m_stream;
  3895. TestSpec m_testSpec;
  3896. bool m_hasTestFilters = false;
  3897. };
  3898. } // end namespace Catch
  3899. // end catch_config.hpp
  3900. // start catch_assertionresult.h
  3901. #include <string>
  3902. namespace Catch {
  3903. struct AssertionResultData
  3904. {
  3905. AssertionResultData() = delete;
  3906. AssertionResultData( ResultWas::OfType _resultType, LazyExpression const& _lazyExpression );
  3907. std::string message;
  3908. mutable std::string reconstructedExpression;
  3909. LazyExpression lazyExpression;
  3910. ResultWas::OfType resultType;
  3911. std::string reconstructExpression() const;
  3912. };
  3913. class AssertionResult {
  3914. public:
  3915. AssertionResult() = delete;
  3916. AssertionResult( AssertionInfo const& info, AssertionResultData const& data );
  3917. bool isOk() const;
  3918. bool succeeded() const;
  3919. ResultWas::OfType getResultType() const;
  3920. bool hasExpression() const;
  3921. bool hasMessage() const;
  3922. std::string getExpression() const;
  3923. std::string getExpressionInMacro() const;
  3924. bool hasExpandedExpression() const;
  3925. std::string getExpandedExpression() const;
  3926. std::string getMessage() const;
  3927. SourceLineInfo getSourceInfo() const;
  3928. StringRef getTestMacroName() const;
  3929. //protected:
  3930. AssertionInfo m_info;
  3931. AssertionResultData m_resultData;
  3932. };
  3933. } // end namespace Catch
  3934. // end catch_assertionresult.h
  3935. // start catch_option.hpp
  3936. namespace Catch {
  3937. // An optional type
  3938. template<typename T>
  3939. class Option {
  3940. public:
  3941. Option() : nullableValue( nullptr ) {}
  3942. Option( T const& _value )
  3943. : nullableValue( new( storage ) T( _value ) )
  3944. {}
  3945. Option( Option const& _other )
  3946. : nullableValue( _other ? new( storage ) T( *_other ) : nullptr )
  3947. {}
  3948. ~Option() {
  3949. reset();
  3950. }
  3951. Option& operator= ( Option const& _other ) {
  3952. if( &_other != this ) {
  3953. reset();
  3954. if( _other )
  3955. nullableValue = new( storage ) T( *_other );
  3956. }
  3957. return *this;
  3958. }
  3959. Option& operator = ( T const& _value ) {
  3960. reset();
  3961. nullableValue = new( storage ) T( _value );
  3962. return *this;
  3963. }
  3964. void reset() {
  3965. if( nullableValue )
  3966. nullableValue->~T();
  3967. nullableValue = nullptr;
  3968. }
  3969. T& operator*() { return *nullableValue; }
  3970. T const& operator*() const { return *nullableValue; }
  3971. T* operator->() { return nullableValue; }
  3972. const T* operator->() const { return nullableValue; }
  3973. T valueOr( T const& defaultValue ) const {
  3974. return nullableValue ? *nullableValue : defaultValue;
  3975. }
  3976. bool some() const { return nullableValue != nullptr; }
  3977. bool none() const { return nullableValue == nullptr; }
  3978. bool operator !() const { return nullableValue == nullptr; }
  3979. explicit operator bool() const {
  3980. return some();
  3981. }
  3982. private:
  3983. T *nullableValue;
  3984. alignas(alignof(T)) char storage[sizeof(T)];
  3985. };
  3986. } // end namespace Catch
  3987. // end catch_option.hpp
  3988. #include <string>
  3989. #include <iosfwd>
  3990. #include <map>
  3991. #include <set>
  3992. #include <memory>
  3993. namespace Catch {
  3994. struct ReporterConfig {
  3995. explicit ReporterConfig( IConfigPtr const& _fullConfig );
  3996. ReporterConfig( IConfigPtr const& _fullConfig, std::ostream& _stream );
  3997. std::ostream& stream() const;
  3998. IConfigPtr fullConfig() const;
  3999. private:
  4000. std::ostream* m_stream;
  4001. IConfigPtr m_fullConfig;
  4002. };
  4003. struct ReporterPreferences {
  4004. bool shouldRedirectStdOut = false;
  4005. bool shouldReportAllAssertions = false;
  4006. };
  4007. template<typename T>
  4008. struct LazyStat : Option<T> {
  4009. LazyStat& operator=( T const& _value ) {
  4010. Option<T>::operator=( _value );
  4011. used = false;
  4012. return *this;
  4013. }
  4014. void reset() {
  4015. Option<T>::reset();
  4016. used = false;
  4017. }
  4018. bool used = false;
  4019. };
  4020. struct TestRunInfo {
  4021. TestRunInfo( std::string const& _name );
  4022. std::string name;
  4023. };
  4024. struct GroupInfo {
  4025. GroupInfo( std::string const& _name,
  4026. std::size_t _groupIndex,
  4027. std::size_t _groupsCount );
  4028. std::string name;
  4029. std::size_t groupIndex;
  4030. std::size_t groupsCounts;
  4031. };
  4032. struct AssertionStats {
  4033. AssertionStats( AssertionResult const& _assertionResult,
  4034. std::vector<MessageInfo> const& _infoMessages,
  4035. Totals const& _totals );
  4036. AssertionStats( AssertionStats const& ) = default;
  4037. AssertionStats( AssertionStats && ) = default;
  4038. AssertionStats& operator = ( AssertionStats const& ) = delete;
  4039. AssertionStats& operator = ( AssertionStats && ) = delete;
  4040. virtual ~AssertionStats();
  4041. AssertionResult assertionResult;
  4042. std::vector<MessageInfo> infoMessages;
  4043. Totals totals;
  4044. };
  4045. struct SectionStats {
  4046. SectionStats( SectionInfo const& _sectionInfo,
  4047. Counts const& _assertions,
  4048. double _durationInSeconds,
  4049. bool _missingAssertions );
  4050. SectionStats( SectionStats const& ) = default;
  4051. SectionStats( SectionStats && ) = default;
  4052. SectionStats& operator = ( SectionStats const& ) = default;
  4053. SectionStats& operator = ( SectionStats && ) = default;
  4054. virtual ~SectionStats();
  4055. SectionInfo sectionInfo;
  4056. Counts assertions;
  4057. double durationInSeconds;
  4058. bool missingAssertions;
  4059. };
  4060. struct TestCaseStats {
  4061. TestCaseStats( TestCaseInfo const& _testInfo,
  4062. Totals const& _totals,
  4063. std::string const& _stdOut,
  4064. std::string const& _stdErr,
  4065. bool _aborting );
  4066. TestCaseStats( TestCaseStats const& ) = default;
  4067. TestCaseStats( TestCaseStats && ) = default;
  4068. TestCaseStats& operator = ( TestCaseStats const& ) = default;
  4069. TestCaseStats& operator = ( TestCaseStats && ) = default;
  4070. virtual ~TestCaseStats();
  4071. TestCaseInfo testInfo;
  4072. Totals totals;
  4073. std::string stdOut;
  4074. std::string stdErr;
  4075. bool aborting;
  4076. };
  4077. struct TestGroupStats {
  4078. TestGroupStats( GroupInfo const& _groupInfo,
  4079. Totals const& _totals,
  4080. bool _aborting );
  4081. TestGroupStats( GroupInfo const& _groupInfo );
  4082. TestGroupStats( TestGroupStats const& ) = default;
  4083. TestGroupStats( TestGroupStats && ) = default;
  4084. TestGroupStats& operator = ( TestGroupStats const& ) = default;
  4085. TestGroupStats& operator = ( TestGroupStats && ) = default;
  4086. virtual ~TestGroupStats();
  4087. GroupInfo groupInfo;
  4088. Totals totals;
  4089. bool aborting;
  4090. };
  4091. struct TestRunStats {
  4092. TestRunStats( TestRunInfo const& _runInfo,
  4093. Totals const& _totals,
  4094. bool _aborting );
  4095. TestRunStats( TestRunStats const& ) = default;
  4096. TestRunStats( TestRunStats && ) = default;
  4097. TestRunStats& operator = ( TestRunStats const& ) = default;
  4098. TestRunStats& operator = ( TestRunStats && ) = default;
  4099. virtual ~TestRunStats();
  4100. TestRunInfo runInfo;
  4101. Totals totals;
  4102. bool aborting;
  4103. };
  4104. struct BenchmarkInfo {
  4105. std::string name;
  4106. };
  4107. struct BenchmarkStats {
  4108. BenchmarkInfo info;
  4109. std::size_t iterations;
  4110. uint64_t elapsedTimeInNanoseconds;
  4111. };
  4112. struct IStreamingReporter {
  4113. virtual ~IStreamingReporter() = default;
  4114. // Implementing class must also provide the following static methods:
  4115. // static std::string getDescription();
  4116. // static std::set<Verbosity> getSupportedVerbosities()
  4117. virtual ReporterPreferences getPreferences() const = 0;
  4118. virtual void noMatchingTestCases( std::string const& spec ) = 0;
  4119. virtual void testRunStarting( TestRunInfo const& testRunInfo ) = 0;
  4120. virtual void testGroupStarting( GroupInfo const& groupInfo ) = 0;
  4121. virtual void testCaseStarting( TestCaseInfo const& testInfo ) = 0;
  4122. virtual void sectionStarting( SectionInfo const& sectionInfo ) = 0;
  4123. // *** experimental ***
  4124. virtual void benchmarkStarting( BenchmarkInfo const& ) {}
  4125. virtual void assertionStarting( AssertionInfo const& assertionInfo ) = 0;
  4126. // The return value indicates if the messages buffer should be cleared:
  4127. virtual bool assertionEnded( AssertionStats const& assertionStats ) = 0;
  4128. // *** experimental ***
  4129. virtual void benchmarkEnded( BenchmarkStats const& ) {}
  4130. virtual void sectionEnded( SectionStats const& sectionStats ) = 0;
  4131. virtual void testCaseEnded( TestCaseStats const& testCaseStats ) = 0;
  4132. virtual void testGroupEnded( TestGroupStats const& testGroupStats ) = 0;
  4133. virtual void testRunEnded( TestRunStats const& testRunStats ) = 0;
  4134. virtual void skipTest( TestCaseInfo const& testInfo ) = 0;
  4135. // Default empty implementation provided
  4136. virtual void fatalErrorEncountered( StringRef name );
  4137. virtual bool isMulti() const;
  4138. };
  4139. using IStreamingReporterPtr = std::unique_ptr<IStreamingReporter>;
  4140. struct IReporterFactory {
  4141. virtual ~IReporterFactory();
  4142. virtual IStreamingReporterPtr create( ReporterConfig const& config ) const = 0;
  4143. virtual std::string getDescription() const = 0;
  4144. };
  4145. using IReporterFactoryPtr = std::shared_ptr<IReporterFactory>;
  4146. struct IReporterRegistry {
  4147. using FactoryMap = std::map<std::string, IReporterFactoryPtr>;
  4148. using Listeners = std::vector<IReporterFactoryPtr>;
  4149. virtual ~IReporterRegistry();
  4150. virtual IStreamingReporterPtr create( std::string const& name, IConfigPtr const& config ) const = 0;
  4151. virtual FactoryMap const& getFactories() const = 0;
  4152. virtual Listeners const& getListeners() const = 0;
  4153. };
  4154. } // end namespace Catch
  4155. // end catch_interfaces_reporter.h
  4156. #include <algorithm>
  4157. #include <cstring>
  4158. #include <cfloat>
  4159. #include <cstdio>
  4160. #include <cassert>
  4161. #include <memory>
  4162. #include <ostream>
  4163. namespace Catch {
  4164. void prepareExpandedExpression(AssertionResult& result);
  4165. // Returns double formatted as %.3f (format expected on output)
  4166. std::string getFormattedDuration( double duration );
  4167. std::string serializeFilters( std::vector<std::string> const& container );
  4168. template<typename DerivedT>
  4169. struct StreamingReporterBase : IStreamingReporter {
  4170. StreamingReporterBase( ReporterConfig const& _config )
  4171. : m_config( _config.fullConfig() ),
  4172. stream( _config.stream() )
  4173. {
  4174. m_reporterPrefs.shouldRedirectStdOut = false;
  4175. if( !DerivedT::getSupportedVerbosities().count( m_config->verbosity() ) )
  4176. CATCH_ERROR( "Verbosity level not supported by this reporter" );
  4177. }
  4178. ReporterPreferences getPreferences() const override {
  4179. return m_reporterPrefs;
  4180. }
  4181. static std::set<Verbosity> getSupportedVerbosities() {
  4182. return { Verbosity::Normal };
  4183. }
  4184. ~StreamingReporterBase() override = default;
  4185. void noMatchingTestCases(std::string const&) override {}
  4186. void testRunStarting(TestRunInfo const& _testRunInfo) override {
  4187. currentTestRunInfo = _testRunInfo;
  4188. }
  4189. void testGroupStarting(GroupInfo const& _groupInfo) override {
  4190. currentGroupInfo = _groupInfo;
  4191. }
  4192. void testCaseStarting(TestCaseInfo const& _testInfo) override {
  4193. currentTestCaseInfo = _testInfo;
  4194. }
  4195. void sectionStarting(SectionInfo const& _sectionInfo) override {
  4196. m_sectionStack.push_back(_sectionInfo);
  4197. }
  4198. void sectionEnded(SectionStats const& /* _sectionStats */) override {
  4199. m_sectionStack.pop_back();
  4200. }
  4201. void testCaseEnded(TestCaseStats const& /* _testCaseStats */) override {
  4202. currentTestCaseInfo.reset();
  4203. }
  4204. void testGroupEnded(TestGroupStats const& /* _testGroupStats */) override {
  4205. currentGroupInfo.reset();
  4206. }
  4207. void testRunEnded(TestRunStats const& /* _testRunStats */) override {
  4208. currentTestCaseInfo.reset();
  4209. currentGroupInfo.reset();
  4210. currentTestRunInfo.reset();
  4211. }
  4212. void skipTest(TestCaseInfo const&) override {
  4213. // Don't do anything with this by default.
  4214. // It can optionally be overridden in the derived class.
  4215. }
  4216. IConfigPtr m_config;
  4217. std::ostream& stream;
  4218. LazyStat<TestRunInfo> currentTestRunInfo;
  4219. LazyStat<GroupInfo> currentGroupInfo;
  4220. LazyStat<TestCaseInfo> currentTestCaseInfo;
  4221. std::vector<SectionInfo> m_sectionStack;
  4222. ReporterPreferences m_reporterPrefs;
  4223. };
  4224. template<typename DerivedT>
  4225. struct CumulativeReporterBase : IStreamingReporter {
  4226. template<typename T, typename ChildNodeT>
  4227. struct Node {
  4228. explicit Node( T const& _value ) : value( _value ) {}
  4229. virtual ~Node() {}
  4230. using ChildNodes = std::vector<std::shared_ptr<ChildNodeT>>;
  4231. T value;
  4232. ChildNodes children;
  4233. };
  4234. struct SectionNode {
  4235. explicit SectionNode(SectionStats const& _stats) : stats(_stats) {}
  4236. virtual ~SectionNode() = default;
  4237. bool operator == (SectionNode const& other) const {
  4238. return stats.sectionInfo.lineInfo == other.stats.sectionInfo.lineInfo;
  4239. }
  4240. bool operator == (std::shared_ptr<SectionNode> const& other) const {
  4241. return operator==(*other);
  4242. }
  4243. SectionStats stats;
  4244. using ChildSections = std::vector<std::shared_ptr<SectionNode>>;
  4245. using Assertions = std::vector<AssertionStats>;
  4246. ChildSections childSections;
  4247. Assertions assertions;
  4248. std::string stdOut;
  4249. std::string stdErr;
  4250. };
  4251. struct BySectionInfo {
  4252. BySectionInfo( SectionInfo const& other ) : m_other( other ) {}
  4253. BySectionInfo( BySectionInfo const& other ) : m_other( other.m_other ) {}
  4254. bool operator() (std::shared_ptr<SectionNode> const& node) const {
  4255. return ((node->stats.sectionInfo.name == m_other.name) &&
  4256. (node->stats.sectionInfo.lineInfo == m_other.lineInfo));
  4257. }
  4258. void operator=(BySectionInfo const&) = delete;
  4259. private:
  4260. SectionInfo const& m_other;
  4261. };
  4262. using TestCaseNode = Node<TestCaseStats, SectionNode>;
  4263. using TestGroupNode = Node<TestGroupStats, TestCaseNode>;
  4264. using TestRunNode = Node<TestRunStats, TestGroupNode>;
  4265. CumulativeReporterBase( ReporterConfig const& _config )
  4266. : m_config( _config.fullConfig() ),
  4267. stream( _config.stream() )
  4268. {
  4269. m_reporterPrefs.shouldRedirectStdOut = false;
  4270. if( !DerivedT::getSupportedVerbosities().count( m_config->verbosity() ) )
  4271. CATCH_ERROR( "Verbosity level not supported by this reporter" );
  4272. }
  4273. ~CumulativeReporterBase() override = default;
  4274. ReporterPreferences getPreferences() const override {
  4275. return m_reporterPrefs;
  4276. }
  4277. static std::set<Verbosity> getSupportedVerbosities() {
  4278. return { Verbosity::Normal };
  4279. }
  4280. void testRunStarting( TestRunInfo const& ) override {}
  4281. void testGroupStarting( GroupInfo const& ) override {}
  4282. void testCaseStarting( TestCaseInfo const& ) override {}
  4283. void sectionStarting( SectionInfo const& sectionInfo ) override {
  4284. SectionStats incompleteStats( sectionInfo, Counts(), 0, false );
  4285. std::shared_ptr<SectionNode> node;
  4286. if( m_sectionStack.empty() ) {
  4287. if( !m_rootSection )
  4288. m_rootSection = std::make_shared<SectionNode>( incompleteStats );
  4289. node = m_rootSection;
  4290. }
  4291. else {
  4292. SectionNode& parentNode = *m_sectionStack.back();
  4293. auto it =
  4294. std::find_if( parentNode.childSections.begin(),
  4295. parentNode.childSections.end(),
  4296. BySectionInfo( sectionInfo ) );
  4297. if( it == parentNode.childSections.end() ) {
  4298. node = std::make_shared<SectionNode>( incompleteStats );
  4299. parentNode.childSections.push_back( node );
  4300. }
  4301. else
  4302. node = *it;
  4303. }
  4304. m_sectionStack.push_back( node );
  4305. m_deepestSection = std::move(node);
  4306. }
  4307. void assertionStarting(AssertionInfo const&) override {}
  4308. bool assertionEnded(AssertionStats const& assertionStats) override {
  4309. assert(!m_sectionStack.empty());
  4310. // AssertionResult holds a pointer to a temporary DecomposedExpression,
  4311. // which getExpandedExpression() calls to build the expression string.
  4312. // Our section stack copy of the assertionResult will likely outlive the
  4313. // temporary, so it must be expanded or discarded now to avoid calling
  4314. // a destroyed object later.
  4315. prepareExpandedExpression(const_cast<AssertionResult&>( assertionStats.assertionResult ) );
  4316. SectionNode& sectionNode = *m_sectionStack.back();
  4317. sectionNode.assertions.push_back(assertionStats);
  4318. return true;
  4319. }
  4320. void sectionEnded(SectionStats const& sectionStats) override {
  4321. assert(!m_sectionStack.empty());
  4322. SectionNode& node = *m_sectionStack.back();
  4323. node.stats = sectionStats;
  4324. m_sectionStack.pop_back();
  4325. }
  4326. void testCaseEnded(TestCaseStats const& testCaseStats) override {
  4327. auto node = std::make_shared<TestCaseNode>(testCaseStats);
  4328. assert(m_sectionStack.size() == 0);
  4329. node->children.push_back(m_rootSection);
  4330. m_testCases.push_back(node);
  4331. m_rootSection.reset();
  4332. assert(m_deepestSection);
  4333. m_deepestSection->stdOut = testCaseStats.stdOut;
  4334. m_deepestSection->stdErr = testCaseStats.stdErr;
  4335. }
  4336. void testGroupEnded(TestGroupStats const& testGroupStats) override {
  4337. auto node = std::make_shared<TestGroupNode>(testGroupStats);
  4338. node->children.swap(m_testCases);
  4339. m_testGroups.push_back(node);
  4340. }
  4341. void testRunEnded(TestRunStats const& testRunStats) override {
  4342. auto node = std::make_shared<TestRunNode>(testRunStats);
  4343. node->children.swap(m_testGroups);
  4344. m_testRuns.push_back(node);
  4345. testRunEndedCumulative();
  4346. }
  4347. virtual void testRunEndedCumulative() = 0;
  4348. void skipTest(TestCaseInfo const&) override {}
  4349. IConfigPtr m_config;
  4350. std::ostream& stream;
  4351. std::vector<AssertionStats> m_assertions;
  4352. std::vector<std::vector<std::shared_ptr<SectionNode>>> m_sections;
  4353. std::vector<std::shared_ptr<TestCaseNode>> m_testCases;
  4354. std::vector<std::shared_ptr<TestGroupNode>> m_testGroups;
  4355. std::vector<std::shared_ptr<TestRunNode>> m_testRuns;
  4356. std::shared_ptr<SectionNode> m_rootSection;
  4357. std::shared_ptr<SectionNode> m_deepestSection;
  4358. std::vector<std::shared_ptr<SectionNode>> m_sectionStack;
  4359. ReporterPreferences m_reporterPrefs;
  4360. };
  4361. template<char C>
  4362. char const* getLineOfChars() {
  4363. static char line[CATCH_CONFIG_CONSOLE_WIDTH] = {0};
  4364. if( !*line ) {
  4365. std::memset( line, C, CATCH_CONFIG_CONSOLE_WIDTH-1 );
  4366. line[CATCH_CONFIG_CONSOLE_WIDTH-1] = 0;
  4367. }
  4368. return line;
  4369. }
  4370. struct TestEventListenerBase : StreamingReporterBase<TestEventListenerBase> {
  4371. TestEventListenerBase( ReporterConfig const& _config );
  4372. static std::set<Verbosity> getSupportedVerbosities();
  4373. void assertionStarting(AssertionInfo const&) override;
  4374. bool assertionEnded(AssertionStats const&) override;
  4375. };
  4376. } // end namespace Catch
  4377. // end catch_reporter_bases.hpp
  4378. // start catch_console_colour.h
  4379. namespace Catch {
  4380. struct Colour {
  4381. enum Code {
  4382. None = 0,
  4383. White,
  4384. Red,
  4385. Green,
  4386. Blue,
  4387. Cyan,
  4388. Yellow,
  4389. Grey,
  4390. Bright = 0x10,
  4391. BrightRed = Bright | Red,
  4392. BrightGreen = Bright | Green,
  4393. LightGrey = Bright | Grey,
  4394. BrightWhite = Bright | White,
  4395. BrightYellow = Bright | Yellow,
  4396. // By intention
  4397. FileName = LightGrey,
  4398. Warning = BrightYellow,
  4399. ResultError = BrightRed,
  4400. ResultSuccess = BrightGreen,
  4401. ResultExpectedFailure = Warning,
  4402. Error = BrightRed,
  4403. Success = Green,
  4404. OriginalExpression = Cyan,
  4405. ReconstructedExpression = BrightYellow,
  4406. SecondaryText = LightGrey,
  4407. Headers = White
  4408. };
  4409. // Use constructed object for RAII guard
  4410. Colour( Code _colourCode );
  4411. Colour( Colour&& other ) noexcept;
  4412. Colour& operator=( Colour&& other ) noexcept;
  4413. ~Colour();
  4414. // Use static method for one-shot changes
  4415. static void use( Code _colourCode );
  4416. private:
  4417. bool m_moved = false;
  4418. };
  4419. std::ostream& operator << ( std::ostream& os, Colour const& );
  4420. } // end namespace Catch
  4421. // end catch_console_colour.h
  4422. // start catch_reporter_registrars.hpp
  4423. namespace Catch {
  4424. template<typename T>
  4425. class ReporterRegistrar {
  4426. class ReporterFactory : public IReporterFactory {
  4427. IStreamingReporterPtr create( ReporterConfig const& config ) const override {
  4428. return std::unique_ptr<T>( new T( config ) );
  4429. }
  4430. std::string getDescription() const override {
  4431. return T::getDescription();
  4432. }
  4433. };
  4434. public:
  4435. explicit ReporterRegistrar( std::string const& name ) {
  4436. getMutableRegistryHub().registerReporter( name, std::make_shared<ReporterFactory>() );
  4437. }
  4438. };
  4439. template<typename T>
  4440. class ListenerRegistrar {
  4441. class ListenerFactory : public IReporterFactory {
  4442. IStreamingReporterPtr create( ReporterConfig const& config ) const override {
  4443. return std::unique_ptr<T>( new T( config ) );
  4444. }
  4445. std::string getDescription() const override {
  4446. return std::string();
  4447. }
  4448. };
  4449. public:
  4450. ListenerRegistrar() {
  4451. getMutableRegistryHub().registerListener( std::make_shared<ListenerFactory>() );
  4452. }
  4453. };
  4454. }
  4455. #if !defined(CATCH_CONFIG_DISABLE)
  4456. #define CATCH_REGISTER_REPORTER( name, reporterType ) \
  4457. CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
  4458. namespace{ Catch::ReporterRegistrar<reporterType> catch_internal_RegistrarFor##reporterType( name ); } \
  4459. CATCH_INTERNAL_UNSUPPRESS_GLOBALS_WARNINGS
  4460. #define CATCH_REGISTER_LISTENER( listenerType ) \
  4461. CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
  4462. namespace{ Catch::ListenerRegistrar<listenerType> catch_internal_RegistrarFor##listenerType; } \
  4463. CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS
  4464. #else // CATCH_CONFIG_DISABLE
  4465. #define CATCH_REGISTER_REPORTER(name, reporterType)
  4466. #define CATCH_REGISTER_LISTENER(listenerType)
  4467. #endif // CATCH_CONFIG_DISABLE
  4468. // end catch_reporter_registrars.hpp
  4469. // Allow users to base their work off existing reporters
  4470. // start catch_reporter_compact.h
  4471. namespace Catch {
  4472. struct CompactReporter : StreamingReporterBase<CompactReporter> {
  4473. using StreamingReporterBase::StreamingReporterBase;
  4474. ~CompactReporter() override;
  4475. static std::string getDescription();
  4476. ReporterPreferences getPreferences() const override;
  4477. void noMatchingTestCases(std::string const& spec) override;
  4478. void assertionStarting(AssertionInfo const&) override;
  4479. bool assertionEnded(AssertionStats const& _assertionStats) override;
  4480. void sectionEnded(SectionStats const& _sectionStats) override;
  4481. void testRunEnded(TestRunStats const& _testRunStats) override;
  4482. };
  4483. } // end namespace Catch
  4484. // end catch_reporter_compact.h
  4485. // start catch_reporter_console.h
  4486. #if defined(_MSC_VER)
  4487. #pragma warning(push)
  4488. #pragma warning(disable:4061) // Not all labels are EXPLICITLY handled in switch
  4489. // Note that 4062 (not all labels are handled
  4490. // and default is missing) is enabled
  4491. #endif
  4492. namespace Catch {
  4493. // Fwd decls
  4494. struct SummaryColumn;
  4495. class TablePrinter;
  4496. struct ConsoleReporter : StreamingReporterBase<ConsoleReporter> {
  4497. std::unique_ptr<TablePrinter> m_tablePrinter;
  4498. ConsoleReporter(ReporterConfig const& config);
  4499. ~ConsoleReporter() override;
  4500. static std::string getDescription();
  4501. void noMatchingTestCases(std::string const& spec) override;
  4502. void assertionStarting(AssertionInfo const&) override;
  4503. bool assertionEnded(AssertionStats const& _assertionStats) override;
  4504. void sectionStarting(SectionInfo const& _sectionInfo) override;
  4505. void sectionEnded(SectionStats const& _sectionStats) override;
  4506. void benchmarkStarting(BenchmarkInfo const& info) override;
  4507. void benchmarkEnded(BenchmarkStats const& stats) override;
  4508. void testCaseEnded(TestCaseStats const& _testCaseStats) override;
  4509. void testGroupEnded(TestGroupStats const& _testGroupStats) override;
  4510. void testRunEnded(TestRunStats const& _testRunStats) override;
  4511. void testRunStarting(TestRunInfo const& _testRunInfo) override;
  4512. private:
  4513. void lazyPrint();
  4514. void lazyPrintWithoutClosingBenchmarkTable();
  4515. void lazyPrintRunInfo();
  4516. void lazyPrintGroupInfo();
  4517. void printTestCaseAndSectionHeader();
  4518. void printClosedHeader(std::string const& _name);
  4519. void printOpenHeader(std::string const& _name);
  4520. // if string has a : in first line will set indent to follow it on
  4521. // subsequent lines
  4522. void printHeaderString(std::string const& _string, std::size_t indent = 0);
  4523. void printTotals(Totals const& totals);
  4524. void printSummaryRow(std::string const& label, std::vector<SummaryColumn> const& cols, std::size_t row);
  4525. void printTotalsDivider(Totals const& totals);
  4526. void printSummaryDivider();
  4527. void printTestFilters();
  4528. private:
  4529. bool m_headerPrinted = false;
  4530. };
  4531. } // end namespace Catch
  4532. #if defined(_MSC_VER)
  4533. #pragma warning(pop)
  4534. #endif
  4535. // end catch_reporter_console.h
  4536. // start catch_reporter_junit.h
  4537. // start catch_xmlwriter.h
  4538. #include <vector>
  4539. namespace Catch {
  4540. class XmlEncode {
  4541. public:
  4542. enum ForWhat { ForTextNodes, ForAttributes };
  4543. XmlEncode( std::string const& str, ForWhat forWhat = ForTextNodes );
  4544. void encodeTo( std::ostream& os ) const;
  4545. friend std::ostream& operator << ( std::ostream& os, XmlEncode const& xmlEncode );
  4546. private:
  4547. std::string m_str;
  4548. ForWhat m_forWhat;
  4549. };
  4550. class XmlWriter {
  4551. public:
  4552. class ScopedElement {
  4553. public:
  4554. ScopedElement( XmlWriter* writer );
  4555. ScopedElement( ScopedElement&& other ) noexcept;
  4556. ScopedElement& operator=( ScopedElement&& other ) noexcept;
  4557. ~ScopedElement();
  4558. ScopedElement& writeText( std::string const& text, bool indent = true );
  4559. template<typename T>
  4560. ScopedElement& writeAttribute( std::string const& name, T const& attribute ) {
  4561. m_writer->writeAttribute( name, attribute );
  4562. return *this;
  4563. }
  4564. private:
  4565. mutable XmlWriter* m_writer = nullptr;
  4566. };
  4567. XmlWriter( std::ostream& os = Catch::cout() );
  4568. ~XmlWriter();
  4569. XmlWriter( XmlWriter const& ) = delete;
  4570. XmlWriter& operator=( XmlWriter const& ) = delete;
  4571. XmlWriter& startElement( std::string const& name );
  4572. ScopedElement scopedElement( std::string const& name );
  4573. XmlWriter& endElement();
  4574. XmlWriter& writeAttribute( std::string const& name, std::string const& attribute );
  4575. XmlWriter& writeAttribute( std::string const& name, bool attribute );
  4576. template<typename T>
  4577. XmlWriter& writeAttribute( std::string const& name, T const& attribute ) {
  4578. ReusableStringStream rss;
  4579. rss << attribute;
  4580. return writeAttribute( name, rss.str() );
  4581. }
  4582. XmlWriter& writeText( std::string const& text, bool indent = true );
  4583. XmlWriter& writeComment( std::string const& text );
  4584. void writeStylesheetRef( std::string const& url );
  4585. XmlWriter& writeBlankLine();
  4586. void ensureTagClosed();
  4587. private:
  4588. void writeDeclaration();
  4589. void newlineIfNecessary();
  4590. bool m_tagIsOpen = false;
  4591. bool m_needsNewline = false;
  4592. std::vector<std::string> m_tags;
  4593. std::string m_indent;
  4594. std::ostream& m_os;
  4595. };
  4596. }
  4597. // end catch_xmlwriter.h
  4598. namespace Catch {
  4599. class JunitReporter : public CumulativeReporterBase<JunitReporter> {
  4600. public:
  4601. JunitReporter(ReporterConfig const& _config);
  4602. ~JunitReporter() override;
  4603. static std::string getDescription();
  4604. void noMatchingTestCases(std::string const& /*spec*/) override;
  4605. void testRunStarting(TestRunInfo const& runInfo) override;
  4606. void testGroupStarting(GroupInfo const& groupInfo) override;
  4607. void testCaseStarting(TestCaseInfo const& testCaseInfo) override;
  4608. bool assertionEnded(AssertionStats const& assertionStats) override;
  4609. void testCaseEnded(TestCaseStats const& testCaseStats) override;
  4610. void testGroupEnded(TestGroupStats const& testGroupStats) override;
  4611. void testRunEndedCumulative() override;
  4612. void writeGroup(TestGroupNode const& groupNode, double suiteTime);
  4613. void writeTestCase(TestCaseNode const& testCaseNode);
  4614. void writeSection(std::string const& className,
  4615. std::string const& rootName,
  4616. SectionNode const& sectionNode);
  4617. void writeAssertions(SectionNode const& sectionNode);
  4618. void writeAssertion(AssertionStats const& stats);
  4619. XmlWriter xml;
  4620. Timer suiteTimer;
  4621. std::string stdOutForSuite;
  4622. std::string stdErrForSuite;
  4623. unsigned int unexpectedExceptions = 0;
  4624. bool m_okToFail = false;
  4625. };
  4626. } // end namespace Catch
  4627. // end catch_reporter_junit.h
  4628. // start catch_reporter_xml.h
  4629. namespace Catch {
  4630. class XmlReporter : public StreamingReporterBase<XmlReporter> {
  4631. public:
  4632. XmlReporter(ReporterConfig const& _config);
  4633. ~XmlReporter() override;
  4634. static std::string getDescription();
  4635. virtual std::string getStylesheetRef() const;
  4636. void writeSourceInfo(SourceLineInfo const& sourceInfo);
  4637. public: // StreamingReporterBase
  4638. void noMatchingTestCases(std::string const& s) override;
  4639. void testRunStarting(TestRunInfo const& testInfo) override;
  4640. void testGroupStarting(GroupInfo const& groupInfo) override;
  4641. void testCaseStarting(TestCaseInfo const& testInfo) override;
  4642. void sectionStarting(SectionInfo const& sectionInfo) override;
  4643. void assertionStarting(AssertionInfo const&) override;
  4644. bool assertionEnded(AssertionStats const& assertionStats) override;
  4645. void sectionEnded(SectionStats const& sectionStats) override;
  4646. void testCaseEnded(TestCaseStats const& testCaseStats) override;
  4647. void testGroupEnded(TestGroupStats const& testGroupStats) override;
  4648. void testRunEnded(TestRunStats const& testRunStats) override;
  4649. private:
  4650. Timer m_testCaseTimer;
  4651. XmlWriter m_xml;
  4652. int m_sectionDepth = 0;
  4653. };
  4654. } // end namespace Catch
  4655. // end catch_reporter_xml.h
  4656. // end catch_external_interfaces.h
  4657. #endif
  4658. #endif // ! CATCH_CONFIG_IMPL_ONLY
  4659. #ifdef CATCH_IMPL
  4660. // start catch_impl.hpp
  4661. #ifdef __clang__
  4662. #pragma clang diagnostic push
  4663. #pragma clang diagnostic ignored "-Wweak-vtables"
  4664. #endif
  4665. // Keep these here for external reporters
  4666. // start catch_test_case_tracker.h
  4667. #include <string>
  4668. #include <vector>
  4669. #include <memory>
  4670. namespace Catch {
  4671. namespace TestCaseTracking {
  4672. struct NameAndLocation {
  4673. std::string name;
  4674. SourceLineInfo location;
  4675. NameAndLocation( std::string const& _name, SourceLineInfo const& _location );
  4676. };
  4677. struct ITracker;
  4678. using ITrackerPtr = std::shared_ptr<ITracker>;
  4679. struct ITracker {
  4680. virtual ~ITracker();
  4681. // static queries
  4682. virtual NameAndLocation const& nameAndLocation() const = 0;
  4683. // dynamic queries
  4684. virtual bool isComplete() const = 0; // Successfully completed or failed
  4685. virtual bool isSuccessfullyCompleted() const = 0;
  4686. virtual bool isOpen() const = 0; // Started but not complete
  4687. virtual bool hasChildren() const = 0;
  4688. virtual ITracker& parent() = 0;
  4689. // actions
  4690. virtual void close() = 0; // Successfully complete
  4691. virtual void fail() = 0;
  4692. virtual void markAsNeedingAnotherRun() = 0;
  4693. virtual void addChild( ITrackerPtr const& child ) = 0;
  4694. virtual ITrackerPtr findChild( NameAndLocation const& nameAndLocation ) = 0;
  4695. virtual void openChild() = 0;
  4696. // Debug/ checking
  4697. virtual bool isSectionTracker() const = 0;
  4698. virtual bool isGeneratorTracker() const = 0;
  4699. };
  4700. class TrackerContext {
  4701. enum RunState {
  4702. NotStarted,
  4703. Executing,
  4704. CompletedCycle
  4705. };
  4706. ITrackerPtr m_rootTracker;
  4707. ITracker* m_currentTracker = nullptr;
  4708. RunState m_runState = NotStarted;
  4709. public:
  4710. ITracker& startRun();
  4711. void endRun();
  4712. void startCycle();
  4713. void completeCycle();
  4714. bool completedCycle() const;
  4715. ITracker& currentTracker();
  4716. void setCurrentTracker( ITracker* tracker );
  4717. };
  4718. class TrackerBase : public ITracker {
  4719. protected:
  4720. enum CycleState {
  4721. NotStarted,
  4722. Executing,
  4723. ExecutingChildren,
  4724. NeedsAnotherRun,
  4725. CompletedSuccessfully,
  4726. Failed
  4727. };
  4728. using Children = std::vector<ITrackerPtr>;
  4729. NameAndLocation m_nameAndLocation;
  4730. TrackerContext& m_ctx;
  4731. ITracker* m_parent;
  4732. Children m_children;
  4733. CycleState m_runState = NotStarted;
  4734. public:
  4735. TrackerBase( NameAndLocation const& nameAndLocation, TrackerContext& ctx, ITracker* parent );
  4736. NameAndLocation const& nameAndLocation() const override;
  4737. bool isComplete() const override;
  4738. bool isSuccessfullyCompleted() const override;
  4739. bool isOpen() const override;
  4740. bool hasChildren() const override;
  4741. void addChild( ITrackerPtr const& child ) override;
  4742. ITrackerPtr findChild( NameAndLocation const& nameAndLocation ) override;
  4743. ITracker& parent() override;
  4744. void openChild() override;
  4745. bool isSectionTracker() const override;
  4746. bool isGeneratorTracker() const override;
  4747. void open();
  4748. void close() override;
  4749. void fail() override;
  4750. void markAsNeedingAnotherRun() override;
  4751. private:
  4752. void moveToParent();
  4753. void moveToThis();
  4754. };
  4755. class SectionTracker : public TrackerBase {
  4756. std::vector<std::string> m_filters;
  4757. public:
  4758. SectionTracker( NameAndLocation const& nameAndLocation, TrackerContext& ctx, ITracker* parent );
  4759. bool isSectionTracker() const override;
  4760. bool isComplete() const override;
  4761. static SectionTracker& acquire( TrackerContext& ctx, NameAndLocation const& nameAndLocation );
  4762. void tryOpen();
  4763. void addInitialFilters( std::vector<std::string> const& filters );
  4764. void addNextFilters( std::vector<std::string> const& filters );
  4765. };
  4766. } // namespace TestCaseTracking
  4767. using TestCaseTracking::ITracker;
  4768. using TestCaseTracking::TrackerContext;
  4769. using TestCaseTracking::SectionTracker;
  4770. } // namespace Catch
  4771. // end catch_test_case_tracker.h
  4772. // start catch_leak_detector.h
  4773. namespace Catch {
  4774. struct LeakDetector {
  4775. LeakDetector();
  4776. ~LeakDetector();
  4777. };
  4778. }
  4779. // end catch_leak_detector.h
  4780. // Cpp files will be included in the single-header file here
  4781. // start catch_approx.cpp
  4782. #include <cmath>
  4783. #include <limits>
  4784. namespace {
  4785. // Performs equivalent check of std::fabs(lhs - rhs) <= margin
  4786. // But without the subtraction to allow for INFINITY in comparison
  4787. bool marginComparison(double lhs, double rhs, double margin) {
  4788. return (lhs + margin >= rhs) && (rhs + margin >= lhs);
  4789. }
  4790. }
  4791. namespace Catch {
  4792. namespace Detail {
  4793. Approx::Approx ( double value )
  4794. : m_epsilon( std::numeric_limits<float>::epsilon()*100 ),
  4795. m_margin( 0.0 ),
  4796. m_scale( 0.0 ),
  4797. m_value( value )
  4798. {}
  4799. Approx Approx::custom() {
  4800. return Approx( 0 );
  4801. }
  4802. Approx Approx::operator-() const {
  4803. auto temp(*this);
  4804. temp.m_value = -temp.m_value;
  4805. return temp;
  4806. }
  4807. std::string Approx::toString() const {
  4808. ReusableStringStream rss;
  4809. rss << "Approx( " << ::Catch::Detail::stringify( m_value ) << " )";
  4810. return rss.str();
  4811. }
  4812. bool Approx::equalityComparisonImpl(const double other) const {
  4813. // First try with fixed margin, then compute margin based on epsilon, scale and Approx's value
  4814. // Thanks to Richard Harris for his help refining the scaled margin value
  4815. return marginComparison(m_value, other, m_margin) || marginComparison(m_value, other, m_epsilon * (m_scale + std::fabs(m_value)));
  4816. }
  4817. void Approx::setMargin(double newMargin) {
  4818. CATCH_ENFORCE(newMargin >= 0,
  4819. "Invalid Approx::margin: " << newMargin << '.'
  4820. << " Approx::Margin has to be non-negative.");
  4821. m_margin = newMargin;
  4822. }
  4823. void Approx::setEpsilon(double newEpsilon) {
  4824. CATCH_ENFORCE(newEpsilon >= 0 && newEpsilon <= 1.0,
  4825. "Invalid Approx::epsilon: " << newEpsilon << '.'
  4826. << " Approx::epsilon has to be in [0, 1]");
  4827. m_epsilon = newEpsilon;
  4828. }
  4829. } // end namespace Detail
  4830. namespace literals {
  4831. Detail::Approx operator "" _a(long double val) {
  4832. return Detail::Approx(val);
  4833. }
  4834. Detail::Approx operator "" _a(unsigned long long val) {
  4835. return Detail::Approx(val);
  4836. }
  4837. } // end namespace literals
  4838. std::string StringMaker<Catch::Detail::Approx>::convert(Catch::Detail::Approx const& value) {
  4839. return value.toString();
  4840. }
  4841. } // end namespace Catch
  4842. // end catch_approx.cpp
  4843. // start catch_assertionhandler.cpp
  4844. // start catch_debugger.h
  4845. namespace Catch {
  4846. bool isDebuggerActive();
  4847. }
  4848. #ifdef CATCH_PLATFORM_MAC
  4849. #define CATCH_TRAP() __asm__("int $3\n" : : ) /* NOLINT */
  4850. #elif defined(CATCH_PLATFORM_LINUX)
  4851. // If we can use inline assembler, do it because this allows us to break
  4852. // directly at the location of the failing check instead of breaking inside
  4853. // raise() called from it, i.e. one stack frame below.
  4854. #if defined(__GNUC__) && (defined(__i386) || defined(__x86_64))
  4855. #define CATCH_TRAP() asm volatile ("int $3") /* NOLINT */
  4856. #else // Fall back to the generic way.
  4857. #include <signal.h>
  4858. #define CATCH_TRAP() raise(SIGTRAP)
  4859. #endif
  4860. #elif defined(_MSC_VER)
  4861. #define CATCH_TRAP() __debugbreak()
  4862. #elif defined(__MINGW32__)
  4863. extern "C" __declspec(dllimport) void __stdcall DebugBreak();
  4864. #define CATCH_TRAP() DebugBreak()
  4865. #endif
  4866. #ifdef CATCH_TRAP
  4867. #define CATCH_BREAK_INTO_DEBUGGER() []{ if( Catch::isDebuggerActive() ) { CATCH_TRAP(); } }()
  4868. #else
  4869. #define CATCH_BREAK_INTO_DEBUGGER() []{}()
  4870. #endif
  4871. // end catch_debugger.h
  4872. // start catch_run_context.h
  4873. // start catch_fatal_condition.h
  4874. // start catch_windows_h_proxy.h
  4875. #if defined(CATCH_PLATFORM_WINDOWS)
  4876. #if !defined(NOMINMAX) && !defined(CATCH_CONFIG_NO_NOMINMAX)
  4877. # define CATCH_DEFINED_NOMINMAX
  4878. # define NOMINMAX
  4879. #endif
  4880. #if !defined(WIN32_LEAN_AND_MEAN) && !defined(CATCH_CONFIG_NO_WIN32_LEAN_AND_MEAN)
  4881. # define CATCH_DEFINED_WIN32_LEAN_AND_MEAN
  4882. # define WIN32_LEAN_AND_MEAN
  4883. #endif
  4884. #ifdef __AFXDLL
  4885. #include <AfxWin.h>
  4886. #else
  4887. #include <windows.h>
  4888. #endif
  4889. #ifdef CATCH_DEFINED_NOMINMAX
  4890. # undef NOMINMAX
  4891. #endif
  4892. #ifdef CATCH_DEFINED_WIN32_LEAN_AND_MEAN
  4893. # undef WIN32_LEAN_AND_MEAN
  4894. #endif
  4895. #endif // defined(CATCH_PLATFORM_WINDOWS)
  4896. // end catch_windows_h_proxy.h
  4897. #if defined( CATCH_CONFIG_WINDOWS_SEH )
  4898. namespace Catch {
  4899. struct FatalConditionHandler {
  4900. static LONG CALLBACK handleVectoredException(PEXCEPTION_POINTERS ExceptionInfo);
  4901. FatalConditionHandler();
  4902. static void reset();
  4903. ~FatalConditionHandler();
  4904. private:
  4905. static bool isSet;
  4906. static ULONG guaranteeSize;
  4907. static PVOID exceptionHandlerHandle;
  4908. };
  4909. } // namespace Catch
  4910. #elif defined ( CATCH_CONFIG_POSIX_SIGNALS )
  4911. #include <signal.h>
  4912. namespace Catch {
  4913. struct FatalConditionHandler {
  4914. static bool isSet;
  4915. static struct sigaction oldSigActions[];
  4916. static stack_t oldSigStack;
  4917. static char altStackMem[];
  4918. static void handleSignal( int sig );
  4919. FatalConditionHandler();
  4920. ~FatalConditionHandler();
  4921. static void reset();
  4922. };
  4923. } // namespace Catch
  4924. #else
  4925. namespace Catch {
  4926. struct FatalConditionHandler {
  4927. void reset();
  4928. };
  4929. }
  4930. #endif
  4931. // end catch_fatal_condition.h
  4932. #include <string>
  4933. namespace Catch {
  4934. struct IMutableContext;
  4935. ///////////////////////////////////////////////////////////////////////////
  4936. class RunContext : public IResultCapture, public IRunner {
  4937. public:
  4938. RunContext( RunContext const& ) = delete;
  4939. RunContext& operator =( RunContext const& ) = delete;
  4940. explicit RunContext( IConfigPtr const& _config, IStreamingReporterPtr&& reporter );
  4941. ~RunContext() override;
  4942. void testGroupStarting( std::string const& testSpec, std::size_t groupIndex, std::size_t groupsCount );
  4943. void testGroupEnded( std::string const& testSpec, Totals const& totals, std::size_t groupIndex, std::size_t groupsCount );
  4944. Totals runTest(TestCase const& testCase);
  4945. IConfigPtr config() const;
  4946. IStreamingReporter& reporter() const;
  4947. public: // IResultCapture
  4948. // Assertion handlers
  4949. void handleExpr
  4950. ( AssertionInfo const& info,
  4951. ITransientExpression const& expr,
  4952. AssertionReaction& reaction ) override;
  4953. void handleMessage
  4954. ( AssertionInfo const& info,
  4955. ResultWas::OfType resultType,
  4956. StringRef const& message,
  4957. AssertionReaction& reaction ) override;
  4958. void handleUnexpectedExceptionNotThrown
  4959. ( AssertionInfo const& info,
  4960. AssertionReaction& reaction ) override;
  4961. void handleUnexpectedInflightException
  4962. ( AssertionInfo const& info,
  4963. std::string const& message,
  4964. AssertionReaction& reaction ) override;
  4965. void handleIncomplete
  4966. ( AssertionInfo const& info ) override;
  4967. void handleNonExpr
  4968. ( AssertionInfo const &info,
  4969. ResultWas::OfType resultType,
  4970. AssertionReaction &reaction ) override;
  4971. bool sectionStarted( SectionInfo const& sectionInfo, Counts& assertions ) override;
  4972. void sectionEnded( SectionEndInfo const& endInfo ) override;
  4973. void sectionEndedEarly( SectionEndInfo const& endInfo ) override;
  4974. auto acquireGeneratorTracker( SourceLineInfo const& lineInfo ) -> IGeneratorTracker& override;
  4975. void benchmarkStarting( BenchmarkInfo const& info ) override;
  4976. void benchmarkEnded( BenchmarkStats const& stats ) override;
  4977. void pushScopedMessage( MessageInfo const& message ) override;
  4978. void popScopedMessage( MessageInfo const& message ) override;
  4979. void emplaceUnscopedMessage( MessageBuilder const& builder ) override;
  4980. std::string getCurrentTestName() const override;
  4981. const AssertionResult* getLastResult() const override;
  4982. void exceptionEarlyReported() override;
  4983. void handleFatalErrorCondition( StringRef message ) override;
  4984. bool lastAssertionPassed() override;
  4985. void assertionPassed() override;
  4986. public:
  4987. // !TBD We need to do this another way!
  4988. bool aborting() const final;
  4989. private:
  4990. void runCurrentTest( std::string& redirectedCout, std::string& redirectedCerr );
  4991. void invokeActiveTestCase();
  4992. void resetAssertionInfo();
  4993. bool testForMissingAssertions( Counts& assertions );
  4994. void assertionEnded( AssertionResult const& result );
  4995. void reportExpr
  4996. ( AssertionInfo const &info,
  4997. ResultWas::OfType resultType,
  4998. ITransientExpression const *expr,
  4999. bool negated );
  5000. void populateReaction( AssertionReaction& reaction );
  5001. private:
  5002. void handleUnfinishedSections();
  5003. TestRunInfo m_runInfo;
  5004. IMutableContext& m_context;
  5005. TestCase const* m_activeTestCase = nullptr;
  5006. ITracker* m_testCaseTracker = nullptr;
  5007. Option<AssertionResult> m_lastResult;
  5008. IConfigPtr m_config;
  5009. Totals m_totals;
  5010. IStreamingReporterPtr m_reporter;
  5011. std::vector<MessageInfo> m_messages;
  5012. std::vector<ScopedMessage> m_messageScopes; /* Keeps owners of so-called unscoped messages. */
  5013. AssertionInfo m_lastAssertionInfo;
  5014. std::vector<SectionEndInfo> m_unfinishedSections;
  5015. std::vector<ITracker*> m_activeSections;
  5016. TrackerContext m_trackerContext;
  5017. bool m_lastAssertionPassed = false;
  5018. bool m_shouldReportUnexpected = true;
  5019. bool m_includeSuccessfulResults;
  5020. };
  5021. } // end namespace Catch
  5022. // end catch_run_context.h
  5023. namespace Catch {
  5024. namespace {
  5025. auto operator <<( std::ostream& os, ITransientExpression const& expr ) -> std::ostream& {
  5026. expr.streamReconstructedExpression( os );
  5027. return os;
  5028. }
  5029. }
  5030. LazyExpression::LazyExpression( bool isNegated )
  5031. : m_isNegated( isNegated )
  5032. {}
  5033. LazyExpression::LazyExpression( LazyExpression const& other ) : m_isNegated( other.m_isNegated ) {}
  5034. LazyExpression::operator bool() const {
  5035. return m_transientExpression != nullptr;
  5036. }
  5037. auto operator << ( std::ostream& os, LazyExpression const& lazyExpr ) -> std::ostream& {
  5038. if( lazyExpr.m_isNegated )
  5039. os << "!";
  5040. if( lazyExpr ) {
  5041. if( lazyExpr.m_isNegated && lazyExpr.m_transientExpression->isBinaryExpression() )
  5042. os << "(" << *lazyExpr.m_transientExpression << ")";
  5043. else
  5044. os << *lazyExpr.m_transientExpression;
  5045. }
  5046. else {
  5047. os << "{** error - unchecked empty expression requested **}";
  5048. }
  5049. return os;
  5050. }
  5051. AssertionHandler::AssertionHandler
  5052. ( StringRef const& macroName,
  5053. SourceLineInfo const& lineInfo,
  5054. StringRef capturedExpression,
  5055. ResultDisposition::Flags resultDisposition )
  5056. : m_assertionInfo{ macroName, lineInfo, capturedExpression, resultDisposition },
  5057. m_resultCapture( getResultCapture() )
  5058. {}
  5059. void AssertionHandler::handleExpr( ITransientExpression const& expr ) {
  5060. m_resultCapture.handleExpr( m_assertionInfo, expr, m_reaction );
  5061. }
  5062. void AssertionHandler::handleMessage(ResultWas::OfType resultType, StringRef const& message) {
  5063. m_resultCapture.handleMessage( m_assertionInfo, resultType, message, m_reaction );
  5064. }
  5065. auto AssertionHandler::allowThrows() const -> bool {
  5066. return getCurrentContext().getConfig()->allowThrows();
  5067. }
  5068. void AssertionHandler::complete() {
  5069. setCompleted();
  5070. if( m_reaction.shouldDebugBreak ) {
  5071. // If you find your debugger stopping you here then go one level up on the
  5072. // call-stack for the code that caused it (typically a failed assertion)
  5073. // (To go back to the test and change execution, jump over the throw, next)
  5074. CATCH_BREAK_INTO_DEBUGGER();
  5075. }
  5076. if (m_reaction.shouldThrow) {
  5077. #if !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
  5078. throw Catch::TestFailureException();
  5079. #else
  5080. CATCH_ERROR( "Test failure requires aborting test!" );
  5081. #endif
  5082. }
  5083. }
  5084. void AssertionHandler::setCompleted() {
  5085. m_completed = true;
  5086. }
  5087. void AssertionHandler::handleUnexpectedInflightException() {
  5088. m_resultCapture.handleUnexpectedInflightException( m_assertionInfo, Catch::translateActiveException(), m_reaction );
  5089. }
  5090. void AssertionHandler::handleExceptionThrownAsExpected() {
  5091. m_resultCapture.handleNonExpr(m_assertionInfo, ResultWas::Ok, m_reaction);
  5092. }
  5093. void AssertionHandler::handleExceptionNotThrownAsExpected() {
  5094. m_resultCapture.handleNonExpr(m_assertionInfo, ResultWas::Ok, m_reaction);
  5095. }
  5096. void AssertionHandler::handleUnexpectedExceptionNotThrown() {
  5097. m_resultCapture.handleUnexpectedExceptionNotThrown( m_assertionInfo, m_reaction );
  5098. }
  5099. void AssertionHandler::handleThrowingCallSkipped() {
  5100. m_resultCapture.handleNonExpr(m_assertionInfo, ResultWas::Ok, m_reaction);
  5101. }
  5102. // This is the overload that takes a string and infers the Equals matcher from it
  5103. // The more general overload, that takes any string matcher, is in catch_capture_matchers.cpp
  5104. void handleExceptionMatchExpr( AssertionHandler& handler, std::string const& str, StringRef const& matcherString ) {
  5105. handleExceptionMatchExpr( handler, Matchers::Equals( str ), matcherString );
  5106. }
  5107. } // namespace Catch
  5108. // end catch_assertionhandler.cpp
  5109. // start catch_assertionresult.cpp
  5110. namespace Catch {
  5111. AssertionResultData::AssertionResultData(ResultWas::OfType _resultType, LazyExpression const & _lazyExpression):
  5112. lazyExpression(_lazyExpression),
  5113. resultType(_resultType) {}
  5114. std::string AssertionResultData::reconstructExpression() const {
  5115. if( reconstructedExpression.empty() ) {
  5116. if( lazyExpression ) {
  5117. ReusableStringStream rss;
  5118. rss << lazyExpression;
  5119. reconstructedExpression = rss.str();
  5120. }
  5121. }
  5122. return reconstructedExpression;
  5123. }
  5124. AssertionResult::AssertionResult( AssertionInfo const& info, AssertionResultData const& data )
  5125. : m_info( info ),
  5126. m_resultData( data )
  5127. {}
  5128. // Result was a success
  5129. bool AssertionResult::succeeded() const {
  5130. return Catch::isOk( m_resultData.resultType );
  5131. }
  5132. // Result was a success, or failure is suppressed
  5133. bool AssertionResult::isOk() const {
  5134. return Catch::isOk( m_resultData.resultType ) || shouldSuppressFailure( m_info.resultDisposition );
  5135. }
  5136. ResultWas::OfType AssertionResult::getResultType() const {
  5137. return m_resultData.resultType;
  5138. }
  5139. bool AssertionResult::hasExpression() const {
  5140. return m_info.capturedExpression[0] != 0;
  5141. }
  5142. bool AssertionResult::hasMessage() const {
  5143. return !m_resultData.message.empty();
  5144. }
  5145. std::string AssertionResult::getExpression() const {
  5146. if( isFalseTest( m_info.resultDisposition ) )
  5147. return "!(" + m_info.capturedExpression + ")";
  5148. else
  5149. return m_info.capturedExpression;
  5150. }
  5151. std::string AssertionResult::getExpressionInMacro() const {
  5152. std::string expr;
  5153. if( m_info.macroName[0] == 0 )
  5154. expr = m_info.capturedExpression;
  5155. else {
  5156. expr.reserve( m_info.macroName.size() + m_info.capturedExpression.size() + 4 );
  5157. expr += m_info.macroName;
  5158. expr += "( ";
  5159. expr += m_info.capturedExpression;
  5160. expr += " )";
  5161. }
  5162. return expr;
  5163. }
  5164. bool AssertionResult::hasExpandedExpression() const {
  5165. return hasExpression() && getExpandedExpression() != getExpression();
  5166. }
  5167. std::string AssertionResult::getExpandedExpression() const {
  5168. std::string expr = m_resultData.reconstructExpression();
  5169. return expr.empty()
  5170. ? getExpression()
  5171. : expr;
  5172. }
  5173. std::string AssertionResult::getMessage() const {
  5174. return m_resultData.message;
  5175. }
  5176. SourceLineInfo AssertionResult::getSourceInfo() const {
  5177. return m_info.lineInfo;
  5178. }
  5179. StringRef AssertionResult::getTestMacroName() const {
  5180. return m_info.macroName;
  5181. }
  5182. } // end namespace Catch
  5183. // end catch_assertionresult.cpp
  5184. // start catch_benchmark.cpp
  5185. namespace Catch {
  5186. auto BenchmarkLooper::getResolution() -> uint64_t {
  5187. return getEstimatedClockResolution() * getCurrentContext().getConfig()->benchmarkResolutionMultiple();
  5188. }
  5189. void BenchmarkLooper::reportStart() {
  5190. getResultCapture().benchmarkStarting( { m_name } );
  5191. }
  5192. auto BenchmarkLooper::needsMoreIterations() -> bool {
  5193. auto elapsed = m_timer.getElapsedNanoseconds();
  5194. // Exponentially increasing iterations until we're confident in our timer resolution
  5195. if( elapsed < m_resolution ) {
  5196. m_iterationsToRun *= 10;
  5197. return true;
  5198. }
  5199. getResultCapture().benchmarkEnded( { { m_name }, m_count, elapsed } );
  5200. return false;
  5201. }
  5202. } // end namespace Catch
  5203. // end catch_benchmark.cpp
  5204. // start catch_capture_matchers.cpp
  5205. namespace Catch {
  5206. using StringMatcher = Matchers::Impl::MatcherBase<std::string>;
  5207. // This is the general overload that takes a any string matcher
  5208. // There is another overload, in catch_assertionhandler.h/.cpp, that only takes a string and infers
  5209. // the Equals matcher (so the header does not mention matchers)
  5210. void handleExceptionMatchExpr( AssertionHandler& handler, StringMatcher const& matcher, StringRef const& matcherString ) {
  5211. std::string exceptionMessage = Catch::translateActiveException();
  5212. MatchExpr<std::string, StringMatcher const&> expr( exceptionMessage, matcher, matcherString );
  5213. handler.handleExpr( expr );
  5214. }
  5215. } // namespace Catch
  5216. // end catch_capture_matchers.cpp
  5217. // start catch_commandline.cpp
  5218. // start catch_commandline.h
  5219. // start catch_clara.h
  5220. // Use Catch's value for console width (store Clara's off to the side, if present)
  5221. #ifdef CLARA_CONFIG_CONSOLE_WIDTH
  5222. #define CATCH_TEMP_CLARA_CONFIG_CONSOLE_WIDTH CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH
  5223. #undef CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH
  5224. #endif
  5225. #define CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH CATCH_CONFIG_CONSOLE_WIDTH-1
  5226. #ifdef __clang__
  5227. #pragma clang diagnostic push
  5228. #pragma clang diagnostic ignored "-Wweak-vtables"
  5229. #pragma clang diagnostic ignored "-Wexit-time-destructors"
  5230. #pragma clang diagnostic ignored "-Wshadow"
  5231. #endif
  5232. // start clara.hpp
  5233. // Copyright 2017 Two Blue Cubes Ltd. All rights reserved.
  5234. //
  5235. // Distributed under the Boost Software License, Version 1.0. (See accompanying
  5236. // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
  5237. //
  5238. // See https://github.com/philsquared/Clara for more details
  5239. // Clara v1.1.5
  5240. #ifndef CATCH_CLARA_CONFIG_CONSOLE_WIDTH
  5241. #define CATCH_CLARA_CONFIG_CONSOLE_WIDTH 80
  5242. #endif
  5243. #ifndef CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH
  5244. #define CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH CATCH_CLARA_CONFIG_CONSOLE_WIDTH
  5245. #endif
  5246. #ifndef CLARA_CONFIG_OPTIONAL_TYPE
  5247. #ifdef __has_include
  5248. #if __has_include(<optional>) && __cplusplus >= 201703L
  5249. #include <optional>
  5250. #define CLARA_CONFIG_OPTIONAL_TYPE std::optional
  5251. #endif
  5252. #endif
  5253. #endif
  5254. // ----------- #included from clara_textflow.hpp -----------
  5255. // TextFlowCpp
  5256. //
  5257. // A single-header library for wrapping and laying out basic text, by Phil Nash
  5258. //
  5259. // Distributed under the Boost Software License, Version 1.0. (See accompanying
  5260. // file LICENSE.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
  5261. //
  5262. // This project is hosted at https://github.com/philsquared/textflowcpp
  5263. #include <cassert>
  5264. #include <ostream>
  5265. #include <sstream>
  5266. #include <vector>
  5267. #ifndef CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH
  5268. #define CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH 80
  5269. #endif
  5270. namespace Catch {
  5271. namespace clara {
  5272. namespace TextFlow {
  5273. inline auto isWhitespace(char c) -> bool {
  5274. static std::string chars = " \t\n\r";
  5275. return chars.find(c) != std::string::npos;
  5276. }
  5277. inline auto isBreakableBefore(char c) -> bool {
  5278. static std::string chars = "[({<|";
  5279. return chars.find(c) != std::string::npos;
  5280. }
  5281. inline auto isBreakableAfter(char c) -> bool {
  5282. static std::string chars = "])}>.,:;*+-=&/\\";
  5283. return chars.find(c) != std::string::npos;
  5284. }
  5285. class Columns;
  5286. class Column {
  5287. std::vector<std::string> m_strings;
  5288. size_t m_width = CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH;
  5289. size_t m_indent = 0;
  5290. size_t m_initialIndent = std::string::npos;
  5291. public:
  5292. class iterator {
  5293. friend Column;
  5294. Column const& m_column;
  5295. size_t m_stringIndex = 0;
  5296. size_t m_pos = 0;
  5297. size_t m_len = 0;
  5298. size_t m_end = 0;
  5299. bool m_suffix = false;
  5300. iterator(Column const& column, size_t stringIndex)
  5301. : m_column(column),
  5302. m_stringIndex(stringIndex) {}
  5303. auto line() const -> std::string const& { return m_column.m_strings[m_stringIndex]; }
  5304. auto isBoundary(size_t at) const -> bool {
  5305. assert(at > 0);
  5306. assert(at <= line().size());
  5307. return at == line().size() ||
  5308. (isWhitespace(line()[at]) && !isWhitespace(line()[at - 1])) ||
  5309. isBreakableBefore(line()[at]) ||
  5310. isBreakableAfter(line()[at - 1]);
  5311. }
  5312. void calcLength() {
  5313. assert(m_stringIndex < m_column.m_strings.size());
  5314. m_suffix = false;
  5315. auto width = m_column.m_width - indent();
  5316. m_end = m_pos;
  5317. if (line()[m_pos] == '\n') {
  5318. ++m_end;
  5319. }
  5320. while (m_end < line().size() && line()[m_end] != '\n')
  5321. ++m_end;
  5322. if (m_end < m_pos + width) {
  5323. m_len = m_end - m_pos;
  5324. } else {
  5325. size_t len = width;
  5326. while (len > 0 && !isBoundary(m_pos + len))
  5327. --len;
  5328. while (len > 0 && isWhitespace(line()[m_pos + len - 1]))
  5329. --len;
  5330. if (len > 0) {
  5331. m_len = len;
  5332. } else {
  5333. m_suffix = true;
  5334. m_len = width - 1;
  5335. }
  5336. }
  5337. }
  5338. auto indent() const -> size_t {
  5339. auto initial = m_pos == 0 && m_stringIndex == 0 ? m_column.m_initialIndent : std::string::npos;
  5340. return initial == std::string::npos ? m_column.m_indent : initial;
  5341. }
  5342. auto addIndentAndSuffix(std::string const &plain) const -> std::string {
  5343. return std::string(indent(), ' ') + (m_suffix ? plain + "-" : plain);
  5344. }
  5345. public:
  5346. using difference_type = std::ptrdiff_t;
  5347. using value_type = std::string;
  5348. using pointer = value_type * ;
  5349. using reference = value_type & ;
  5350. using iterator_category = std::forward_iterator_tag;
  5351. explicit iterator(Column const& column) : m_column(column) {
  5352. assert(m_column.m_width > m_column.m_indent);
  5353. assert(m_column.m_initialIndent == std::string::npos || m_column.m_width > m_column.m_initialIndent);
  5354. calcLength();
  5355. if (m_len == 0)
  5356. m_stringIndex++; // Empty string
  5357. }
  5358. auto operator *() const -> std::string {
  5359. assert(m_stringIndex < m_column.m_strings.size());
  5360. assert(m_pos <= m_end);
  5361. return addIndentAndSuffix(line().substr(m_pos, m_len));
  5362. }
  5363. auto operator ++() -> iterator& {
  5364. m_pos += m_len;
  5365. if (m_pos < line().size() && line()[m_pos] == '\n')
  5366. m_pos += 1;
  5367. else
  5368. while (m_pos < line().size() && isWhitespace(line()[m_pos]))
  5369. ++m_pos;
  5370. if (m_pos == line().size()) {
  5371. m_pos = 0;
  5372. ++m_stringIndex;
  5373. }
  5374. if (m_stringIndex < m_column.m_strings.size())
  5375. calcLength();
  5376. return *this;
  5377. }
  5378. auto operator ++(int) -> iterator {
  5379. iterator prev(*this);
  5380. operator++();
  5381. return prev;
  5382. }
  5383. auto operator ==(iterator const& other) const -> bool {
  5384. return
  5385. m_pos == other.m_pos &&
  5386. m_stringIndex == other.m_stringIndex &&
  5387. &m_column == &other.m_column;
  5388. }
  5389. auto operator !=(iterator const& other) const -> bool {
  5390. return !operator==(other);
  5391. }
  5392. };
  5393. using const_iterator = iterator;
  5394. explicit Column(std::string const& text) { m_strings.push_back(text); }
  5395. auto width(size_t newWidth) -> Column& {
  5396. assert(newWidth > 0);
  5397. m_width = newWidth;
  5398. return *this;
  5399. }
  5400. auto indent(size_t newIndent) -> Column& {
  5401. m_indent = newIndent;
  5402. return *this;
  5403. }
  5404. auto initialIndent(size_t newIndent) -> Column& {
  5405. m_initialIndent = newIndent;
  5406. return *this;
  5407. }
  5408. auto width() const -> size_t { return m_width; }
  5409. auto begin() const -> iterator { return iterator(*this); }
  5410. auto end() const -> iterator { return { *this, m_strings.size() }; }
  5411. inline friend std::ostream& operator << (std::ostream& os, Column const& col) {
  5412. bool first = true;
  5413. for (auto line : col) {
  5414. if (first)
  5415. first = false;
  5416. else
  5417. os << "\n";
  5418. os << line;
  5419. }
  5420. return os;
  5421. }
  5422. auto operator + (Column const& other)->Columns;
  5423. auto toString() const -> std::string {
  5424. std::ostringstream oss;
  5425. oss << *this;
  5426. return oss.str();
  5427. }
  5428. };
  5429. class Spacer : public Column {
  5430. public:
  5431. explicit Spacer(size_t spaceWidth) : Column("") {
  5432. width(spaceWidth);
  5433. }
  5434. };
  5435. class Columns {
  5436. std::vector<Column> m_columns;
  5437. public:
  5438. class iterator {
  5439. friend Columns;
  5440. struct EndTag {};
  5441. std::vector<Column> const& m_columns;
  5442. std::vector<Column::iterator> m_iterators;
  5443. size_t m_activeIterators;
  5444. iterator(Columns const& columns, EndTag)
  5445. : m_columns(columns.m_columns),
  5446. m_activeIterators(0) {
  5447. m_iterators.reserve(m_columns.size());
  5448. for (auto const& col : m_columns)
  5449. m_iterators.push_back(col.end());
  5450. }
  5451. public:
  5452. using difference_type = std::ptrdiff_t;
  5453. using value_type = std::string;
  5454. using pointer = value_type * ;
  5455. using reference = value_type & ;
  5456. using iterator_category = std::forward_iterator_tag;
  5457. explicit iterator(Columns const& columns)
  5458. : m_columns(columns.m_columns),
  5459. m_activeIterators(m_columns.size()) {
  5460. m_iterators.reserve(m_columns.size());
  5461. for (auto const& col : m_columns)
  5462. m_iterators.push_back(col.begin());
  5463. }
  5464. auto operator ==(iterator const& other) const -> bool {
  5465. return m_iterators == other.m_iterators;
  5466. }
  5467. auto operator !=(iterator const& other) const -> bool {
  5468. return m_iterators != other.m_iterators;
  5469. }
  5470. auto operator *() const -> std::string {
  5471. std::string row, padding;
  5472. for (size_t i = 0; i < m_columns.size(); ++i) {
  5473. auto width = m_columns[i].width();
  5474. if (m_iterators[i] != m_columns[i].end()) {
  5475. std::string col = *m_iterators[i];
  5476. row += padding + col;
  5477. if (col.size() < width)
  5478. padding = std::string(width - col.size(), ' ');
  5479. else
  5480. padding = "";
  5481. } else {
  5482. padding += std::string(width, ' ');
  5483. }
  5484. }
  5485. return row;
  5486. }
  5487. auto operator ++() -> iterator& {
  5488. for (size_t i = 0; i < m_columns.size(); ++i) {
  5489. if (m_iterators[i] != m_columns[i].end())
  5490. ++m_iterators[i];
  5491. }
  5492. return *this;
  5493. }
  5494. auto operator ++(int) -> iterator {
  5495. iterator prev(*this);
  5496. operator++();
  5497. return prev;
  5498. }
  5499. };
  5500. using const_iterator = iterator;
  5501. auto begin() const -> iterator { return iterator(*this); }
  5502. auto end() const -> iterator { return { *this, iterator::EndTag() }; }
  5503. auto operator += (Column const& col) -> Columns& {
  5504. m_columns.push_back(col);
  5505. return *this;
  5506. }
  5507. auto operator + (Column const& col) -> Columns {
  5508. Columns combined = *this;
  5509. combined += col;
  5510. return combined;
  5511. }
  5512. inline friend std::ostream& operator << (std::ostream& os, Columns const& cols) {
  5513. bool first = true;
  5514. for (auto line : cols) {
  5515. if (first)
  5516. first = false;
  5517. else
  5518. os << "\n";
  5519. os << line;
  5520. }
  5521. return os;
  5522. }
  5523. auto toString() const -> std::string {
  5524. std::ostringstream oss;
  5525. oss << *this;
  5526. return oss.str();
  5527. }
  5528. };
  5529. inline auto Column::operator + (Column const& other) -> Columns {
  5530. Columns cols;
  5531. cols += *this;
  5532. cols += other;
  5533. return cols;
  5534. }
  5535. }
  5536. }
  5537. }
  5538. // ----------- end of #include from clara_textflow.hpp -----------
  5539. // ........... back in clara.hpp
  5540. #include <cctype>
  5541. #include <string>
  5542. #include <memory>
  5543. #include <set>
  5544. #include <algorithm>
  5545. #if !defined(CATCH_PLATFORM_WINDOWS) && ( defined(WIN32) || defined(__WIN32__) || defined(_WIN32) || defined(_MSC_VER) )
  5546. #define CATCH_PLATFORM_WINDOWS
  5547. #endif
  5548. namespace Catch { namespace clara {
  5549. namespace detail {
  5550. // Traits for extracting arg and return type of lambdas (for single argument lambdas)
  5551. template<typename L>
  5552. struct UnaryLambdaTraits : UnaryLambdaTraits<decltype( &L::operator() )> {};
  5553. template<typename ClassT, typename ReturnT, typename... Args>
  5554. struct UnaryLambdaTraits<ReturnT( ClassT::* )( Args... ) const> {
  5555. static const bool isValid = false;
  5556. };
  5557. template<typename ClassT, typename ReturnT, typename ArgT>
  5558. struct UnaryLambdaTraits<ReturnT( ClassT::* )( ArgT ) const> {
  5559. static const bool isValid = true;
  5560. using ArgType = typename std::remove_const<typename std::remove_reference<ArgT>::type>::type;
  5561. using ReturnType = ReturnT;
  5562. };
  5563. class TokenStream;
  5564. // Transport for raw args (copied from main args, or supplied via init list for testing)
  5565. class Args {
  5566. friend TokenStream;
  5567. std::string m_exeName;
  5568. std::vector<std::string> m_args;
  5569. public:
  5570. Args( int argc, char const* const* argv )
  5571. : m_exeName(argv[0]),
  5572. m_args(argv + 1, argv + argc) {}
  5573. Args( std::initializer_list<std::string> args )
  5574. : m_exeName( *args.begin() ),
  5575. m_args( args.begin()+1, args.end() )
  5576. {}
  5577. auto exeName() const -> std::string {
  5578. return m_exeName;
  5579. }
  5580. };
  5581. // Wraps a token coming from a token stream. These may not directly correspond to strings as a single string
  5582. // may encode an option + its argument if the : or = form is used
  5583. enum class TokenType {
  5584. Option, Argument
  5585. };
  5586. struct Token {
  5587. TokenType type;
  5588. std::string token;
  5589. };
  5590. inline auto isOptPrefix( char c ) -> bool {
  5591. return c == '-'
  5592. #ifdef CATCH_PLATFORM_WINDOWS
  5593. || c == '/'
  5594. #endif
  5595. ;
  5596. }
  5597. // Abstracts iterators into args as a stream of tokens, with option arguments uniformly handled
  5598. class TokenStream {
  5599. using Iterator = std::vector<std::string>::const_iterator;
  5600. Iterator it;
  5601. Iterator itEnd;
  5602. std::vector<Token> m_tokenBuffer;
  5603. void loadBuffer() {
  5604. m_tokenBuffer.resize( 0 );
  5605. // Skip any empty strings
  5606. while( it != itEnd && it->empty() )
  5607. ++it;
  5608. if( it != itEnd ) {
  5609. auto const &next = *it;
  5610. if( isOptPrefix( next[0] ) ) {
  5611. auto delimiterPos = next.find_first_of( " :=" );
  5612. if( delimiterPos != std::string::npos ) {
  5613. m_tokenBuffer.push_back( { TokenType::Option, next.substr( 0, delimiterPos ) } );
  5614. m_tokenBuffer.push_back( { TokenType::Argument, next.substr( delimiterPos + 1 ) } );
  5615. } else {
  5616. if( next[1] != '-' && next.size() > 2 ) {
  5617. std::string opt = "- ";
  5618. for( size_t i = 1; i < next.size(); ++i ) {
  5619. opt[1] = next[i];
  5620. m_tokenBuffer.push_back( { TokenType::Option, opt } );
  5621. }
  5622. } else {
  5623. m_tokenBuffer.push_back( { TokenType::Option, next } );
  5624. }
  5625. }
  5626. } else {
  5627. m_tokenBuffer.push_back( { TokenType::Argument, next } );
  5628. }
  5629. }
  5630. }
  5631. public:
  5632. explicit TokenStream( Args const &args ) : TokenStream( args.m_args.begin(), args.m_args.end() ) {}
  5633. TokenStream( Iterator it, Iterator itEnd ) : it( it ), itEnd( itEnd ) {
  5634. loadBuffer();
  5635. }
  5636. explicit operator bool() const {
  5637. return !m_tokenBuffer.empty() || it != itEnd;
  5638. }
  5639. auto count() const -> size_t { return m_tokenBuffer.size() + (itEnd - it); }
  5640. auto operator*() const -> Token {
  5641. assert( !m_tokenBuffer.empty() );
  5642. return m_tokenBuffer.front();
  5643. }
  5644. auto operator->() const -> Token const * {
  5645. assert( !m_tokenBuffer.empty() );
  5646. return &m_tokenBuffer.front();
  5647. }
  5648. auto operator++() -> TokenStream & {
  5649. if( m_tokenBuffer.size() >= 2 ) {
  5650. m_tokenBuffer.erase( m_tokenBuffer.begin() );
  5651. } else {
  5652. if( it != itEnd )
  5653. ++it;
  5654. loadBuffer();
  5655. }
  5656. return *this;
  5657. }
  5658. };
  5659. class ResultBase {
  5660. public:
  5661. enum Type {
  5662. Ok, LogicError, RuntimeError
  5663. };
  5664. protected:
  5665. ResultBase( Type type ) : m_type( type ) {}
  5666. virtual ~ResultBase() = default;
  5667. virtual void enforceOk() const = 0;
  5668. Type m_type;
  5669. };
  5670. template<typename T>
  5671. class ResultValueBase : public ResultBase {
  5672. public:
  5673. auto value() const -> T const & {
  5674. enforceOk();
  5675. return m_value;
  5676. }
  5677. protected:
  5678. ResultValueBase( Type type ) : ResultBase( type ) {}
  5679. ResultValueBase( ResultValueBase const &other ) : ResultBase( other ) {
  5680. if( m_type == ResultBase::Ok )
  5681. new( &m_value ) T( other.m_value );
  5682. }
  5683. ResultValueBase( Type, T const &value ) : ResultBase( Ok ) {
  5684. new( &m_value ) T( value );
  5685. }
  5686. auto operator=( ResultValueBase const &other ) -> ResultValueBase & {
  5687. if( m_type == ResultBase::Ok )
  5688. m_value.~T();
  5689. ResultBase::operator=(other);
  5690. if( m_type == ResultBase::Ok )
  5691. new( &m_value ) T( other.m_value );
  5692. return *this;
  5693. }
  5694. ~ResultValueBase() override {
  5695. if( m_type == Ok )
  5696. m_value.~T();
  5697. }
  5698. union {
  5699. T m_value;
  5700. };
  5701. };
  5702. template<>
  5703. class ResultValueBase<void> : public ResultBase {
  5704. protected:
  5705. using ResultBase::ResultBase;
  5706. };
  5707. template<typename T = void>
  5708. class BasicResult : public ResultValueBase<T> {
  5709. public:
  5710. template<typename U>
  5711. explicit BasicResult( BasicResult<U> const &other )
  5712. : ResultValueBase<T>( other.type() ),
  5713. m_errorMessage( other.errorMessage() )
  5714. {
  5715. assert( type() != ResultBase::Ok );
  5716. }
  5717. template<typename U>
  5718. static auto ok( U const &value ) -> BasicResult { return { ResultBase::Ok, value }; }
  5719. static auto ok() -> BasicResult { return { ResultBase::Ok }; }
  5720. static auto logicError( std::string const &message ) -> BasicResult { return { ResultBase::LogicError, message }; }
  5721. static auto runtimeError( std::string const &message ) -> BasicResult { return { ResultBase::RuntimeError, message }; }
  5722. explicit operator bool() const { return m_type == ResultBase::Ok; }
  5723. auto type() const -> ResultBase::Type { return m_type; }
  5724. auto errorMessage() const -> std::string { return m_errorMessage; }
  5725. protected:
  5726. void enforceOk() const override {
  5727. // Errors shouldn't reach this point, but if they do
  5728. // the actual error message will be in m_errorMessage
  5729. assert( m_type != ResultBase::LogicError );
  5730. assert( m_type != ResultBase::RuntimeError );
  5731. if( m_type != ResultBase::Ok )
  5732. std::abort();
  5733. }
  5734. std::string m_errorMessage; // Only populated if resultType is an error
  5735. BasicResult( ResultBase::Type type, std::string const &message )
  5736. : ResultValueBase<T>(type),
  5737. m_errorMessage(message)
  5738. {
  5739. assert( m_type != ResultBase::Ok );
  5740. }
  5741. using ResultValueBase<T>::ResultValueBase;
  5742. using ResultBase::m_type;
  5743. };
  5744. enum class ParseResultType {
  5745. Matched, NoMatch, ShortCircuitAll, ShortCircuitSame
  5746. };
  5747. class ParseState {
  5748. public:
  5749. ParseState( ParseResultType type, TokenStream const &remainingTokens )
  5750. : m_type(type),
  5751. m_remainingTokens( remainingTokens )
  5752. {}
  5753. auto type() const -> ParseResultType { return m_type; }
  5754. auto remainingTokens() const -> TokenStream { return m_remainingTokens; }
  5755. private:
  5756. ParseResultType m_type;
  5757. TokenStream m_remainingTokens;
  5758. };
  5759. using Result = BasicResult<void>;
  5760. using ParserResult = BasicResult<ParseResultType>;
  5761. using InternalParseResult = BasicResult<ParseState>;
  5762. struct HelpColumns {
  5763. std::string left;
  5764. std::string right;
  5765. };
  5766. template<typename T>
  5767. inline auto convertInto( std::string const &source, T& target ) -> ParserResult {
  5768. std::stringstream ss;
  5769. ss << source;
  5770. ss >> target;
  5771. if( ss.fail() )
  5772. return ParserResult::runtimeError( "Unable to convert '" + source + "' to destination type" );
  5773. else
  5774. return ParserResult::ok( ParseResultType::Matched );
  5775. }
  5776. inline auto convertInto( std::string const &source, std::string& target ) -> ParserResult {
  5777. target = source;
  5778. return ParserResult::ok( ParseResultType::Matched );
  5779. }
  5780. inline auto convertInto( std::string const &source, bool &target ) -> ParserResult {
  5781. std::string srcLC = source;
  5782. std::transform( srcLC.begin(), srcLC.end(), srcLC.begin(), []( char c ) { return static_cast<char>( std::tolower(c) ); } );
  5783. if (srcLC == "y" || srcLC == "1" || srcLC == "true" || srcLC == "yes" || srcLC == "on")
  5784. target = true;
  5785. else if (srcLC == "n" || srcLC == "0" || srcLC == "false" || srcLC == "no" || srcLC == "off")
  5786. target = false;
  5787. else
  5788. return ParserResult::runtimeError( "Expected a boolean value but did not recognise: '" + source + "'" );
  5789. return ParserResult::ok( ParseResultType::Matched );
  5790. }
  5791. #ifdef CLARA_CONFIG_OPTIONAL_TYPE
  5792. template<typename T>
  5793. inline auto convertInto( std::string const &source, CLARA_CONFIG_OPTIONAL_TYPE<T>& target ) -> ParserResult {
  5794. T temp;
  5795. auto result = convertInto( source, temp );
  5796. if( result )
  5797. target = std::move(temp);
  5798. return result;
  5799. }
  5800. #endif // CLARA_CONFIG_OPTIONAL_TYPE
  5801. struct NonCopyable {
  5802. NonCopyable() = default;
  5803. NonCopyable( NonCopyable const & ) = delete;
  5804. NonCopyable( NonCopyable && ) = delete;
  5805. NonCopyable &operator=( NonCopyable const & ) = delete;
  5806. NonCopyable &operator=( NonCopyable && ) = delete;
  5807. };
  5808. struct BoundRef : NonCopyable {
  5809. virtual ~BoundRef() = default;
  5810. virtual auto isContainer() const -> bool { return false; }
  5811. virtual auto isFlag() const -> bool { return false; }
  5812. };
  5813. struct BoundValueRefBase : BoundRef {
  5814. virtual auto setValue( std::string const &arg ) -> ParserResult = 0;
  5815. };
  5816. struct BoundFlagRefBase : BoundRef {
  5817. virtual auto setFlag( bool flag ) -> ParserResult = 0;
  5818. virtual auto isFlag() const -> bool { return true; }
  5819. };
  5820. template<typename T>
  5821. struct BoundValueRef : BoundValueRefBase {
  5822. T &m_ref;
  5823. explicit BoundValueRef( T &ref ) : m_ref( ref ) {}
  5824. auto setValue( std::string const &arg ) -> ParserResult override {
  5825. return convertInto( arg, m_ref );
  5826. }
  5827. };
  5828. template<typename T>
  5829. struct BoundValueRef<std::vector<T>> : BoundValueRefBase {
  5830. std::vector<T> &m_ref;
  5831. explicit BoundValueRef( std::vector<T> &ref ) : m_ref( ref ) {}
  5832. auto isContainer() const -> bool override { return true; }
  5833. auto setValue( std::string const &arg ) -> ParserResult override {
  5834. T temp;
  5835. auto result = convertInto( arg, temp );
  5836. if( result )
  5837. m_ref.push_back( temp );
  5838. return result;
  5839. }
  5840. };
  5841. struct BoundFlagRef : BoundFlagRefBase {
  5842. bool &m_ref;
  5843. explicit BoundFlagRef( bool &ref ) : m_ref( ref ) {}
  5844. auto setFlag( bool flag ) -> ParserResult override {
  5845. m_ref = flag;
  5846. return ParserResult::ok( ParseResultType::Matched );
  5847. }
  5848. };
  5849. template<typename ReturnType>
  5850. struct LambdaInvoker {
  5851. static_assert( std::is_same<ReturnType, ParserResult>::value, "Lambda must return void or clara::ParserResult" );
  5852. template<typename L, typename ArgType>
  5853. static auto invoke( L const &lambda, ArgType const &arg ) -> ParserResult {
  5854. return lambda( arg );
  5855. }
  5856. };
  5857. template<>
  5858. struct LambdaInvoker<void> {
  5859. template<typename L, typename ArgType>
  5860. static auto invoke( L const &lambda, ArgType const &arg ) -> ParserResult {
  5861. lambda( arg );
  5862. return ParserResult::ok( ParseResultType::Matched );
  5863. }
  5864. };
  5865. template<typename ArgType, typename L>
  5866. inline auto invokeLambda( L const &lambda, std::string const &arg ) -> ParserResult {
  5867. ArgType temp{};
  5868. auto result = convertInto( arg, temp );
  5869. return !result
  5870. ? result
  5871. : LambdaInvoker<typename UnaryLambdaTraits<L>::ReturnType>::invoke( lambda, temp );
  5872. }
  5873. template<typename L>
  5874. struct BoundLambda : BoundValueRefBase {
  5875. L m_lambda;
  5876. static_assert( UnaryLambdaTraits<L>::isValid, "Supplied lambda must take exactly one argument" );
  5877. explicit BoundLambda( L const &lambda ) : m_lambda( lambda ) {}
  5878. auto setValue( std::string const &arg ) -> ParserResult override {
  5879. return invokeLambda<typename UnaryLambdaTraits<L>::ArgType>( m_lambda, arg );
  5880. }
  5881. };
  5882. template<typename L>
  5883. struct BoundFlagLambda : BoundFlagRefBase {
  5884. L m_lambda;
  5885. static_assert( UnaryLambdaTraits<L>::isValid, "Supplied lambda must take exactly one argument" );
  5886. static_assert( std::is_same<typename UnaryLambdaTraits<L>::ArgType, bool>::value, "flags must be boolean" );
  5887. explicit BoundFlagLambda( L const &lambda ) : m_lambda( lambda ) {}
  5888. auto setFlag( bool flag ) -> ParserResult override {
  5889. return LambdaInvoker<typename UnaryLambdaTraits<L>::ReturnType>::invoke( m_lambda, flag );
  5890. }
  5891. };
  5892. enum class Optionality { Optional, Required };
  5893. struct Parser;
  5894. class ParserBase {
  5895. public:
  5896. virtual ~ParserBase() = default;
  5897. virtual auto validate() const -> Result { return Result::ok(); }
  5898. virtual auto parse( std::string const& exeName, TokenStream const &tokens) const -> InternalParseResult = 0;
  5899. virtual auto cardinality() const -> size_t { return 1; }
  5900. auto parse( Args const &args ) const -> InternalParseResult {
  5901. return parse( args.exeName(), TokenStream( args ) );
  5902. }
  5903. };
  5904. template<typename DerivedT>
  5905. class ComposableParserImpl : public ParserBase {
  5906. public:
  5907. template<typename T>
  5908. auto operator|( T const &other ) const -> Parser;
  5909. template<typename T>
  5910. auto operator+( T const &other ) const -> Parser;
  5911. };
  5912. // Common code and state for Args and Opts
  5913. template<typename DerivedT>
  5914. class ParserRefImpl : public ComposableParserImpl<DerivedT> {
  5915. protected:
  5916. Optionality m_optionality = Optionality::Optional;
  5917. std::shared_ptr<BoundRef> m_ref;
  5918. std::string m_hint;
  5919. std::string m_description;
  5920. explicit ParserRefImpl( std::shared_ptr<BoundRef> const &ref ) : m_ref( ref ) {}
  5921. public:
  5922. template<typename T>
  5923. ParserRefImpl( T &ref, std::string const &hint )
  5924. : m_ref( std::make_shared<BoundValueRef<T>>( ref ) ),
  5925. m_hint( hint )
  5926. {}
  5927. template<typename LambdaT>
  5928. ParserRefImpl( LambdaT const &ref, std::string const &hint )
  5929. : m_ref( std::make_shared<BoundLambda<LambdaT>>( ref ) ),
  5930. m_hint(hint)
  5931. {}
  5932. auto operator()( std::string const &description ) -> DerivedT & {
  5933. m_description = description;
  5934. return static_cast<DerivedT &>( *this );
  5935. }
  5936. auto optional() -> DerivedT & {
  5937. m_optionality = Optionality::Optional;
  5938. return static_cast<DerivedT &>( *this );
  5939. };
  5940. auto required() -> DerivedT & {
  5941. m_optionality = Optionality::Required;
  5942. return static_cast<DerivedT &>( *this );
  5943. };
  5944. auto isOptional() const -> bool {
  5945. return m_optionality == Optionality::Optional;
  5946. }
  5947. auto cardinality() const -> size_t override {
  5948. if( m_ref->isContainer() )
  5949. return 0;
  5950. else
  5951. return 1;
  5952. }
  5953. auto hint() const -> std::string { return m_hint; }
  5954. };
  5955. class ExeName : public ComposableParserImpl<ExeName> {
  5956. std::shared_ptr<std::string> m_name;
  5957. std::shared_ptr<BoundValueRefBase> m_ref;
  5958. template<typename LambdaT>
  5959. static auto makeRef(LambdaT const &lambda) -> std::shared_ptr<BoundValueRefBase> {
  5960. return std::make_shared<BoundLambda<LambdaT>>( lambda) ;
  5961. }
  5962. public:
  5963. ExeName() : m_name( std::make_shared<std::string>( "<executable>" ) ) {}
  5964. explicit ExeName( std::string &ref ) : ExeName() {
  5965. m_ref = std::make_shared<BoundValueRef<std::string>>( ref );
  5966. }
  5967. template<typename LambdaT>
  5968. explicit ExeName( LambdaT const& lambda ) : ExeName() {
  5969. m_ref = std::make_shared<BoundLambda<LambdaT>>( lambda );
  5970. }
  5971. // The exe name is not parsed out of the normal tokens, but is handled specially
  5972. auto parse( std::string const&, TokenStream const &tokens ) const -> InternalParseResult override {
  5973. return InternalParseResult::ok( ParseState( ParseResultType::NoMatch, tokens ) );
  5974. }
  5975. auto name() const -> std::string { return *m_name; }
  5976. auto set( std::string const& newName ) -> ParserResult {
  5977. auto lastSlash = newName.find_last_of( "\\/" );
  5978. auto filename = ( lastSlash == std::string::npos )
  5979. ? newName
  5980. : newName.substr( lastSlash+1 );
  5981. *m_name = filename;
  5982. if( m_ref )
  5983. return m_ref->setValue( filename );
  5984. else
  5985. return ParserResult::ok( ParseResultType::Matched );
  5986. }
  5987. };
  5988. class Arg : public ParserRefImpl<Arg> {
  5989. public:
  5990. using ParserRefImpl::ParserRefImpl;
  5991. auto parse( std::string const &, TokenStream const &tokens ) const -> InternalParseResult override {
  5992. auto validationResult = validate();
  5993. if( !validationResult )
  5994. return InternalParseResult( validationResult );
  5995. auto remainingTokens = tokens;
  5996. auto const &token = *remainingTokens;
  5997. if( token.type != TokenType::Argument )
  5998. return InternalParseResult::ok( ParseState( ParseResultType::NoMatch, remainingTokens ) );
  5999. assert( !m_ref->isFlag() );
  6000. auto valueRef = static_cast<detail::BoundValueRefBase*>( m_ref.get() );
  6001. auto result = valueRef->setValue( remainingTokens->token );
  6002. if( !result )
  6003. return InternalParseResult( result );
  6004. else
  6005. return InternalParseResult::ok( ParseState( ParseResultType::Matched, ++remainingTokens ) );
  6006. }
  6007. };
  6008. inline auto normaliseOpt( std::string const &optName ) -> std::string {
  6009. #ifdef CATCH_PLATFORM_WINDOWS
  6010. if( optName[0] == '/' )
  6011. return "-" + optName.substr( 1 );
  6012. else
  6013. #endif
  6014. return optName;
  6015. }
  6016. class Opt : public ParserRefImpl<Opt> {
  6017. protected:
  6018. std::vector<std::string> m_optNames;
  6019. public:
  6020. template<typename LambdaT>
  6021. explicit Opt( LambdaT const &ref ) : ParserRefImpl( std::make_shared<BoundFlagLambda<LambdaT>>( ref ) ) {}
  6022. explicit Opt( bool &ref ) : ParserRefImpl( std::make_shared<BoundFlagRef>( ref ) ) {}
  6023. template<typename LambdaT>
  6024. Opt( LambdaT const &ref, std::string const &hint ) : ParserRefImpl( ref, hint ) {}
  6025. template<typename T>
  6026. Opt( T &ref, std::string const &hint ) : ParserRefImpl( ref, hint ) {}
  6027. auto operator[]( std::string const &optName ) -> Opt & {
  6028. m_optNames.push_back( optName );
  6029. return *this;
  6030. }
  6031. auto getHelpColumns() const -> std::vector<HelpColumns> {
  6032. std::ostringstream oss;
  6033. bool first = true;
  6034. for( auto const &opt : m_optNames ) {
  6035. if (first)
  6036. first = false;
  6037. else
  6038. oss << ", ";
  6039. oss << opt;
  6040. }
  6041. if( !m_hint.empty() )
  6042. oss << " <" << m_hint << ">";
  6043. return { { oss.str(), m_description } };
  6044. }
  6045. auto isMatch( std::string const &optToken ) const -> bool {
  6046. auto normalisedToken = normaliseOpt( optToken );
  6047. for( auto const &name : m_optNames ) {
  6048. if( normaliseOpt( name ) == normalisedToken )
  6049. return true;
  6050. }
  6051. return false;
  6052. }
  6053. using ParserBase::parse;
  6054. auto parse( std::string const&, TokenStream const &tokens ) const -> InternalParseResult override {
  6055. auto validationResult = validate();
  6056. if( !validationResult )
  6057. return InternalParseResult( validationResult );
  6058. auto remainingTokens = tokens;
  6059. if( remainingTokens && remainingTokens->type == TokenType::Option ) {
  6060. auto const &token = *remainingTokens;
  6061. if( isMatch(token.token ) ) {
  6062. if( m_ref->isFlag() ) {
  6063. auto flagRef = static_cast<detail::BoundFlagRefBase*>( m_ref.get() );
  6064. auto result = flagRef->setFlag( true );
  6065. if( !result )
  6066. return InternalParseResult( result );
  6067. if( result.value() == ParseResultType::ShortCircuitAll )
  6068. return InternalParseResult::ok( ParseState( result.value(), remainingTokens ) );
  6069. } else {
  6070. auto valueRef = static_cast<detail::BoundValueRefBase*>( m_ref.get() );
  6071. ++remainingTokens;
  6072. if( !remainingTokens )
  6073. return InternalParseResult::runtimeError( "Expected argument following " + token.token );
  6074. auto const &argToken = *remainingTokens;
  6075. if( argToken.type != TokenType::Argument )
  6076. return InternalParseResult::runtimeError( "Expected argument following " + token.token );
  6077. auto result = valueRef->setValue( argToken.token );
  6078. if( !result )
  6079. return InternalParseResult( result );
  6080. if( result.value() == ParseResultType::ShortCircuitAll )
  6081. return InternalParseResult::ok( ParseState( result.value(), remainingTokens ) );
  6082. }
  6083. return InternalParseResult::ok( ParseState( ParseResultType::Matched, ++remainingTokens ) );
  6084. }
  6085. }
  6086. return InternalParseResult::ok( ParseState( ParseResultType::NoMatch, remainingTokens ) );
  6087. }
  6088. auto validate() const -> Result override {
  6089. if( m_optNames.empty() )
  6090. return Result::logicError( "No options supplied to Opt" );
  6091. for( auto const &name : m_optNames ) {
  6092. if( name.empty() )
  6093. return Result::logicError( "Option name cannot be empty" );
  6094. #ifdef CATCH_PLATFORM_WINDOWS
  6095. if( name[0] != '-' && name[0] != '/' )
  6096. return Result::logicError( "Option name must begin with '-' or '/'" );
  6097. #else
  6098. if( name[0] != '-' )
  6099. return Result::logicError( "Option name must begin with '-'" );
  6100. #endif
  6101. }
  6102. return ParserRefImpl::validate();
  6103. }
  6104. };
  6105. struct Help : Opt {
  6106. Help( bool &showHelpFlag )
  6107. : Opt([&]( bool flag ) {
  6108. showHelpFlag = flag;
  6109. return ParserResult::ok( ParseResultType::ShortCircuitAll );
  6110. })
  6111. {
  6112. static_cast<Opt &>( *this )
  6113. ("display usage information")
  6114. ["-?"]["-h"]["--help"]
  6115. .optional();
  6116. }
  6117. };
  6118. struct Parser : ParserBase {
  6119. mutable ExeName m_exeName;
  6120. std::vector<Opt> m_options;
  6121. std::vector<Arg> m_args;
  6122. auto operator|=( ExeName const &exeName ) -> Parser & {
  6123. m_exeName = exeName;
  6124. return *this;
  6125. }
  6126. auto operator|=( Arg const &arg ) -> Parser & {
  6127. m_args.push_back(arg);
  6128. return *this;
  6129. }
  6130. auto operator|=( Opt const &opt ) -> Parser & {
  6131. m_options.push_back(opt);
  6132. return *this;
  6133. }
  6134. auto operator|=( Parser const &other ) -> Parser & {
  6135. m_options.insert(m_options.end(), other.m_options.begin(), other.m_options.end());
  6136. m_args.insert(m_args.end(), other.m_args.begin(), other.m_args.end());
  6137. return *this;
  6138. }
  6139. template<typename T>
  6140. auto operator|( T const &other ) const -> Parser {
  6141. return Parser( *this ) |= other;
  6142. }
  6143. // Forward deprecated interface with '+' instead of '|'
  6144. template<typename T>
  6145. auto operator+=( T const &other ) -> Parser & { return operator|=( other ); }
  6146. template<typename T>
  6147. auto operator+( T const &other ) const -> Parser { return operator|( other ); }
  6148. auto getHelpColumns() const -> std::vector<HelpColumns> {
  6149. std::vector<HelpColumns> cols;
  6150. for (auto const &o : m_options) {
  6151. auto childCols = o.getHelpColumns();
  6152. cols.insert( cols.end(), childCols.begin(), childCols.end() );
  6153. }
  6154. return cols;
  6155. }
  6156. void writeToStream( std::ostream &os ) const {
  6157. if (!m_exeName.name().empty()) {
  6158. os << "usage:\n" << " " << m_exeName.name() << " ";
  6159. bool required = true, first = true;
  6160. for( auto const &arg : m_args ) {
  6161. if (first)
  6162. first = false;
  6163. else
  6164. os << " ";
  6165. if( arg.isOptional() && required ) {
  6166. os << "[";
  6167. required = false;
  6168. }
  6169. os << "<" << arg.hint() << ">";
  6170. if( arg.cardinality() == 0 )
  6171. os << " ... ";
  6172. }
  6173. if( !required )
  6174. os << "]";
  6175. if( !m_options.empty() )
  6176. os << " options";
  6177. os << "\n\nwhere options are:" << std::endl;
  6178. }
  6179. auto rows = getHelpColumns();
  6180. size_t consoleWidth = CATCH_CLARA_CONFIG_CONSOLE_WIDTH;
  6181. size_t optWidth = 0;
  6182. for( auto const &cols : rows )
  6183. optWidth = (std::max)(optWidth, cols.left.size() + 2);
  6184. optWidth = (std::min)(optWidth, consoleWidth/2);
  6185. for( auto const &cols : rows ) {
  6186. auto row =
  6187. TextFlow::Column( cols.left ).width( optWidth ).indent( 2 ) +
  6188. TextFlow::Spacer(4) +
  6189. TextFlow::Column( cols.right ).width( consoleWidth - 7 - optWidth );
  6190. os << row << std::endl;
  6191. }
  6192. }
  6193. friend auto operator<<( std::ostream &os, Parser const &parser ) -> std::ostream& {
  6194. parser.writeToStream( os );
  6195. return os;
  6196. }
  6197. auto validate() const -> Result override {
  6198. for( auto const &opt : m_options ) {
  6199. auto result = opt.validate();
  6200. if( !result )
  6201. return result;
  6202. }
  6203. for( auto const &arg : m_args ) {
  6204. auto result = arg.validate();
  6205. if( !result )
  6206. return result;
  6207. }
  6208. return Result::ok();
  6209. }
  6210. using ParserBase::parse;
  6211. auto parse( std::string const& exeName, TokenStream const &tokens ) const -> InternalParseResult override {
  6212. struct ParserInfo {
  6213. ParserBase const* parser = nullptr;
  6214. size_t count = 0;
  6215. };
  6216. const size_t totalParsers = m_options.size() + m_args.size();
  6217. assert( totalParsers < 512 );
  6218. // ParserInfo parseInfos[totalParsers]; // <-- this is what we really want to do
  6219. ParserInfo parseInfos[512];
  6220. {
  6221. size_t i = 0;
  6222. for (auto const &opt : m_options) parseInfos[i++].parser = &opt;
  6223. for (auto const &arg : m_args) parseInfos[i++].parser = &arg;
  6224. }
  6225. m_exeName.set( exeName );
  6226. auto result = InternalParseResult::ok( ParseState( ParseResultType::NoMatch, tokens ) );
  6227. while( result.value().remainingTokens() ) {
  6228. bool tokenParsed = false;
  6229. for( size_t i = 0; i < totalParsers; ++i ) {
  6230. auto& parseInfo = parseInfos[i];
  6231. if( parseInfo.parser->cardinality() == 0 || parseInfo.count < parseInfo.parser->cardinality() ) {
  6232. result = parseInfo.parser->parse(exeName, result.value().remainingTokens());
  6233. if (!result)
  6234. return result;
  6235. if (result.value().type() != ParseResultType::NoMatch) {
  6236. tokenParsed = true;
  6237. ++parseInfo.count;
  6238. break;
  6239. }
  6240. }
  6241. }
  6242. if( result.value().type() == ParseResultType::ShortCircuitAll )
  6243. return result;
  6244. if( !tokenParsed )
  6245. return InternalParseResult::runtimeError( "Unrecognised token: " + result.value().remainingTokens()->token );
  6246. }
  6247. // !TBD Check missing required options
  6248. return result;
  6249. }
  6250. };
  6251. template<typename DerivedT>
  6252. template<typename T>
  6253. auto ComposableParserImpl<DerivedT>::operator|( T const &other ) const -> Parser {
  6254. return Parser() | static_cast<DerivedT const &>( *this ) | other;
  6255. }
  6256. } // namespace detail
  6257. // A Combined parser
  6258. using detail::Parser;
  6259. // A parser for options
  6260. using detail::Opt;
  6261. // A parser for arguments
  6262. using detail::Arg;
  6263. // Wrapper for argc, argv from main()
  6264. using detail::Args;
  6265. // Specifies the name of the executable
  6266. using detail::ExeName;
  6267. // Convenience wrapper for option parser that specifies the help option
  6268. using detail::Help;
  6269. // enum of result types from a parse
  6270. using detail::ParseResultType;
  6271. // Result type for parser operation
  6272. using detail::ParserResult;
  6273. }} // namespace Catch::clara
  6274. // end clara.hpp
  6275. #ifdef __clang__
  6276. #pragma clang diagnostic pop
  6277. #endif
  6278. // Restore Clara's value for console width, if present
  6279. #ifdef CATCH_TEMP_CLARA_CONFIG_CONSOLE_WIDTH
  6280. #define CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH CATCH_TEMP_CLARA_CONFIG_CONSOLE_WIDTH
  6281. #undef CATCH_TEMP_CLARA_CONFIG_CONSOLE_WIDTH
  6282. #endif
  6283. // end catch_clara.h
  6284. namespace Catch {
  6285. clara::Parser makeCommandLineParser( ConfigData& config );
  6286. } // end namespace Catch
  6287. // end catch_commandline.h
  6288. #include <fstream>
  6289. #include <ctime>
  6290. namespace Catch {
  6291. clara::Parser makeCommandLineParser( ConfigData& config ) {
  6292. using namespace clara;
  6293. auto const setWarning = [&]( std::string const& warning ) {
  6294. auto warningSet = [&]() {
  6295. if( warning == "NoAssertions" )
  6296. return WarnAbout::NoAssertions;
  6297. if ( warning == "NoTests" )
  6298. return WarnAbout::NoTests;
  6299. return WarnAbout::Nothing;
  6300. }();
  6301. if (warningSet == WarnAbout::Nothing)
  6302. return ParserResult::runtimeError( "Unrecognised warning: '" + warning + "'" );
  6303. config.warnings = static_cast<WarnAbout::What>( config.warnings | warningSet );
  6304. return ParserResult::ok( ParseResultType::Matched );
  6305. };
  6306. auto const loadTestNamesFromFile = [&]( std::string const& filename ) {
  6307. std::ifstream f( filename.c_str() );
  6308. if( !f.is_open() )
  6309. return ParserResult::runtimeError( "Unable to load input file: '" + filename + "'" );
  6310. std::string line;
  6311. while( std::getline( f, line ) ) {
  6312. line = trim(line);
  6313. if( !line.empty() && !startsWith( line, '#' ) ) {
  6314. if( !startsWith( line, '"' ) )
  6315. line = '"' + line + '"';
  6316. config.testsOrTags.push_back( line + ',' );
  6317. }
  6318. }
  6319. return ParserResult::ok( ParseResultType::Matched );
  6320. };
  6321. auto const setTestOrder = [&]( std::string const& order ) {
  6322. if( startsWith( "declared", order ) )
  6323. config.runOrder = RunTests::InDeclarationOrder;
  6324. else if( startsWith( "lexical", order ) )
  6325. config.runOrder = RunTests::InLexicographicalOrder;
  6326. else if( startsWith( "random", order ) )
  6327. config.runOrder = RunTests::InRandomOrder;
  6328. else
  6329. return clara::ParserResult::runtimeError( "Unrecognised ordering: '" + order + "'" );
  6330. return ParserResult::ok( ParseResultType::Matched );
  6331. };
  6332. auto const setRngSeed = [&]( std::string const& seed ) {
  6333. if( seed != "time" )
  6334. return clara::detail::convertInto( seed, config.rngSeed );
  6335. config.rngSeed = static_cast<unsigned int>( std::time(nullptr) );
  6336. return ParserResult::ok( ParseResultType::Matched );
  6337. };
  6338. auto const setColourUsage = [&]( std::string const& useColour ) {
  6339. auto mode = toLower( useColour );
  6340. if( mode == "yes" )
  6341. config.useColour = UseColour::Yes;
  6342. else if( mode == "no" )
  6343. config.useColour = UseColour::No;
  6344. else if( mode == "auto" )
  6345. config.useColour = UseColour::Auto;
  6346. else
  6347. return ParserResult::runtimeError( "colour mode must be one of: auto, yes or no. '" + useColour + "' not recognised" );
  6348. return ParserResult::ok( ParseResultType::Matched );
  6349. };
  6350. auto const setWaitForKeypress = [&]( std::string const& keypress ) {
  6351. auto keypressLc = toLower( keypress );
  6352. if( keypressLc == "start" )
  6353. config.waitForKeypress = WaitForKeypress::BeforeStart;
  6354. else if( keypressLc == "exit" )
  6355. config.waitForKeypress = WaitForKeypress::BeforeExit;
  6356. else if( keypressLc == "both" )
  6357. config.waitForKeypress = WaitForKeypress::BeforeStartAndExit;
  6358. else
  6359. return ParserResult::runtimeError( "keypress argument must be one of: start, exit or both. '" + keypress + "' not recognised" );
  6360. return ParserResult::ok( ParseResultType::Matched );
  6361. };
  6362. auto const setVerbosity = [&]( std::string const& verbosity ) {
  6363. auto lcVerbosity = toLower( verbosity );
  6364. if( lcVerbosity == "quiet" )
  6365. config.verbosity = Verbosity::Quiet;
  6366. else if( lcVerbosity == "normal" )
  6367. config.verbosity = Verbosity::Normal;
  6368. else if( lcVerbosity == "high" )
  6369. config.verbosity = Verbosity::High;
  6370. else
  6371. return ParserResult::runtimeError( "Unrecognised verbosity, '" + verbosity + "'" );
  6372. return ParserResult::ok( ParseResultType::Matched );
  6373. };
  6374. auto const setReporter = [&]( std::string const& reporter ) {
  6375. IReporterRegistry::FactoryMap const& factories = getRegistryHub().getReporterRegistry().getFactories();
  6376. auto lcReporter = toLower( reporter );
  6377. auto result = factories.find( lcReporter );
  6378. if( factories.end() != result )
  6379. config.reporterName = lcReporter;
  6380. else
  6381. return ParserResult::runtimeError( "Unrecognized reporter, '" + reporter + "'. Check available with --list-reporters" );
  6382. return ParserResult::ok( ParseResultType::Matched );
  6383. };
  6384. auto cli
  6385. = ExeName( config.processName )
  6386. | Help( config.showHelp )
  6387. | Opt( config.listTests )
  6388. ["-l"]["--list-tests"]
  6389. ( "list all/matching test cases" )
  6390. | Opt( config.listTags )
  6391. ["-t"]["--list-tags"]
  6392. ( "list all/matching tags" )
  6393. | Opt( config.showSuccessfulTests )
  6394. ["-s"]["--success"]
  6395. ( "include successful tests in output" )
  6396. | Opt( config.shouldDebugBreak )
  6397. ["-b"]["--break"]
  6398. ( "break into debugger on failure" )
  6399. | Opt( config.noThrow )
  6400. ["-e"]["--nothrow"]
  6401. ( "skip exception tests" )
  6402. | Opt( config.showInvisibles )
  6403. ["-i"]["--invisibles"]
  6404. ( "show invisibles (tabs, newlines)" )
  6405. | Opt( config.outputFilename, "filename" )
  6406. ["-o"]["--out"]
  6407. ( "output filename" )
  6408. | Opt( setReporter, "name" )
  6409. ["-r"]["--reporter"]
  6410. ( "reporter to use (defaults to console)" )
  6411. | Opt( config.name, "name" )
  6412. ["-n"]["--name"]
  6413. ( "suite name" )
  6414. | Opt( [&]( bool ){ config.abortAfter = 1; } )
  6415. ["-a"]["--abort"]
  6416. ( "abort at first failure" )
  6417. | Opt( [&]( int x ){ config.abortAfter = x; }, "no. failures" )
  6418. ["-x"]["--abortx"]
  6419. ( "abort after x failures" )
  6420. | Opt( setWarning, "warning name" )
  6421. ["-w"]["--warn"]
  6422. ( "enable warnings" )
  6423. | Opt( [&]( bool flag ) { config.showDurations = flag ? ShowDurations::Always : ShowDurations::Never; }, "yes|no" )
  6424. ["-d"]["--durations"]
  6425. ( "show test durations" )
  6426. | Opt( loadTestNamesFromFile, "filename" )
  6427. ["-f"]["--input-file"]
  6428. ( "load test names to run from a file" )
  6429. | Opt( config.filenamesAsTags )
  6430. ["-#"]["--filenames-as-tags"]
  6431. ( "adds a tag for the filename" )
  6432. | Opt( config.sectionsToRun, "section name" )
  6433. ["-c"]["--section"]
  6434. ( "specify section to run" )
  6435. | Opt( setVerbosity, "quiet|normal|high" )
  6436. ["-v"]["--verbosity"]
  6437. ( "set output verbosity" )
  6438. | Opt( config.listTestNamesOnly )
  6439. ["--list-test-names-only"]
  6440. ( "list all/matching test cases names only" )
  6441. | Opt( config.listReporters )
  6442. ["--list-reporters"]
  6443. ( "list all reporters" )
  6444. | Opt( setTestOrder, "decl|lex|rand" )
  6445. ["--order"]
  6446. ( "test case order (defaults to decl)" )
  6447. | Opt( setRngSeed, "'time'|number" )
  6448. ["--rng-seed"]
  6449. ( "set a specific seed for random numbers" )
  6450. | Opt( setColourUsage, "yes|no" )
  6451. ["--use-colour"]
  6452. ( "should output be colourised" )
  6453. | Opt( config.libIdentify )
  6454. ["--libidentify"]
  6455. ( "report name and version according to libidentify standard" )
  6456. | Opt( setWaitForKeypress, "start|exit|both" )
  6457. ["--wait-for-keypress"]
  6458. ( "waits for a keypress before exiting" )
  6459. | Opt( config.benchmarkResolutionMultiple, "multiplier" )
  6460. ["--benchmark-resolution-multiple"]
  6461. ( "multiple of clock resolution to run benchmarks" )
  6462. | Arg( config.testsOrTags, "test name|pattern|tags" )
  6463. ( "which test or tests to use" );
  6464. return cli;
  6465. }
  6466. } // end namespace Catch
  6467. // end catch_commandline.cpp
  6468. // start catch_common.cpp
  6469. #include <cstring>
  6470. #include <ostream>
  6471. namespace Catch {
  6472. bool SourceLineInfo::empty() const noexcept {
  6473. return file[0] == '\0';
  6474. }
  6475. bool SourceLineInfo::operator == ( SourceLineInfo const& other ) const noexcept {
  6476. return line == other.line && (file == other.file || std::strcmp(file, other.file) == 0);
  6477. }
  6478. bool SourceLineInfo::operator < ( SourceLineInfo const& other ) const noexcept {
  6479. // We can assume that the same file will usually have the same pointer.
  6480. // Thus, if the pointers are the same, there is no point in calling the strcmp
  6481. return line < other.line || ( line == other.line && file != other.file && (std::strcmp(file, other.file) < 0));
  6482. }
  6483. std::ostream& operator << ( std::ostream& os, SourceLineInfo const& info ) {
  6484. #ifndef __GNUG__
  6485. os << info.file << '(' << info.line << ')';
  6486. #else
  6487. os << info.file << ':' << info.line;
  6488. #endif
  6489. return os;
  6490. }
  6491. std::string StreamEndStop::operator+() const {
  6492. return std::string();
  6493. }
  6494. NonCopyable::NonCopyable() = default;
  6495. NonCopyable::~NonCopyable() = default;
  6496. }
  6497. // end catch_common.cpp
  6498. // start catch_config.cpp
  6499. namespace Catch {
  6500. Config::Config( ConfigData const& data )
  6501. : m_data( data ),
  6502. m_stream( openStream() )
  6503. {
  6504. TestSpecParser parser(ITagAliasRegistry::get());
  6505. if (!data.testsOrTags.empty()) {
  6506. m_hasTestFilters = true;
  6507. for( auto const& testOrTags : data.testsOrTags )
  6508. parser.parse( testOrTags );
  6509. }
  6510. m_testSpec = parser.testSpec();
  6511. }
  6512. std::string const& Config::getFilename() const {
  6513. return m_data.outputFilename ;
  6514. }
  6515. bool Config::listTests() const { return m_data.listTests; }
  6516. bool Config::listTestNamesOnly() const { return m_data.listTestNamesOnly; }
  6517. bool Config::listTags() const { return m_data.listTags; }
  6518. bool Config::listReporters() const { return m_data.listReporters; }
  6519. std::string Config::getProcessName() const { return m_data.processName; }
  6520. std::string const& Config::getReporterName() const { return m_data.reporterName; }
  6521. std::vector<std::string> const& Config::getTestsOrTags() const { return m_data.testsOrTags; }
  6522. std::vector<std::string> const& Config::getSectionsToRun() const { return m_data.sectionsToRun; }
  6523. TestSpec const& Config::testSpec() const { return m_testSpec; }
  6524. bool Config::hasTestFilters() const { return m_hasTestFilters; }
  6525. bool Config::showHelp() const { return m_data.showHelp; }
  6526. // IConfig interface
  6527. bool Config::allowThrows() const { return !m_data.noThrow; }
  6528. std::ostream& Config::stream() const { return m_stream->stream(); }
  6529. std::string Config::name() const { return m_data.name.empty() ? m_data.processName : m_data.name; }
  6530. bool Config::includeSuccessfulResults() const { return m_data.showSuccessfulTests; }
  6531. bool Config::warnAboutMissingAssertions() const { return !!(m_data.warnings & WarnAbout::NoAssertions); }
  6532. bool Config::warnAboutNoTests() const { return !!(m_data.warnings & WarnAbout::NoTests); }
  6533. ShowDurations::OrNot Config::showDurations() const { return m_data.showDurations; }
  6534. RunTests::InWhatOrder Config::runOrder() const { return m_data.runOrder; }
  6535. unsigned int Config::rngSeed() const { return m_data.rngSeed; }
  6536. int Config::benchmarkResolutionMultiple() const { return m_data.benchmarkResolutionMultiple; }
  6537. UseColour::YesOrNo Config::useColour() const { return m_data.useColour; }
  6538. bool Config::shouldDebugBreak() const { return m_data.shouldDebugBreak; }
  6539. int Config::abortAfter() const { return m_data.abortAfter; }
  6540. bool Config::showInvisibles() const { return m_data.showInvisibles; }
  6541. Verbosity Config::verbosity() const { return m_data.verbosity; }
  6542. IStream const* Config::openStream() {
  6543. return Catch::makeStream(m_data.outputFilename);
  6544. }
  6545. } // end namespace Catch
  6546. // end catch_config.cpp
  6547. // start catch_console_colour.cpp
  6548. #if defined(__clang__)
  6549. # pragma clang diagnostic push
  6550. # pragma clang diagnostic ignored "-Wexit-time-destructors"
  6551. #endif
  6552. // start catch_errno_guard.h
  6553. namespace Catch {
  6554. class ErrnoGuard {
  6555. public:
  6556. ErrnoGuard();
  6557. ~ErrnoGuard();
  6558. private:
  6559. int m_oldErrno;
  6560. };
  6561. }
  6562. // end catch_errno_guard.h
  6563. #include <sstream>
  6564. namespace Catch {
  6565. namespace {
  6566. struct IColourImpl {
  6567. virtual ~IColourImpl() = default;
  6568. virtual void use( Colour::Code _colourCode ) = 0;
  6569. };
  6570. struct NoColourImpl : IColourImpl {
  6571. void use( Colour::Code ) {}
  6572. static IColourImpl* instance() {
  6573. static NoColourImpl s_instance;
  6574. return &s_instance;
  6575. }
  6576. };
  6577. } // anon namespace
  6578. } // namespace Catch
  6579. #if !defined( CATCH_CONFIG_COLOUR_NONE ) && !defined( CATCH_CONFIG_COLOUR_WINDOWS ) && !defined( CATCH_CONFIG_COLOUR_ANSI )
  6580. # ifdef CATCH_PLATFORM_WINDOWS
  6581. # define CATCH_CONFIG_COLOUR_WINDOWS
  6582. # else
  6583. # define CATCH_CONFIG_COLOUR_ANSI
  6584. # endif
  6585. #endif
  6586. #if defined ( CATCH_CONFIG_COLOUR_WINDOWS ) /////////////////////////////////////////
  6587. namespace Catch {
  6588. namespace {
  6589. class Win32ColourImpl : public IColourImpl {
  6590. public:
  6591. Win32ColourImpl() : stdoutHandle( GetStdHandle(STD_OUTPUT_HANDLE) )
  6592. {
  6593. CONSOLE_SCREEN_BUFFER_INFO csbiInfo;
  6594. GetConsoleScreenBufferInfo( stdoutHandle, &csbiInfo );
  6595. originalForegroundAttributes = csbiInfo.wAttributes & ~( BACKGROUND_GREEN | BACKGROUND_RED | BACKGROUND_BLUE | BACKGROUND_INTENSITY );
  6596. originalBackgroundAttributes = csbiInfo.wAttributes & ~( FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_BLUE | FOREGROUND_INTENSITY );
  6597. }
  6598. void use( Colour::Code _colourCode ) override {
  6599. switch( _colourCode ) {
  6600. case Colour::None: return setTextAttribute( originalForegroundAttributes );
  6601. case Colour::White: return setTextAttribute( FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_BLUE );
  6602. case Colour::Red: return setTextAttribute( FOREGROUND_RED );
  6603. case Colour::Green: return setTextAttribute( FOREGROUND_GREEN );
  6604. case Colour::Blue: return setTextAttribute( FOREGROUND_BLUE );
  6605. case Colour::Cyan: return setTextAttribute( FOREGROUND_BLUE | FOREGROUND_GREEN );
  6606. case Colour::Yellow: return setTextAttribute( FOREGROUND_RED | FOREGROUND_GREEN );
  6607. case Colour::Grey: return setTextAttribute( 0 );
  6608. case Colour::LightGrey: return setTextAttribute( FOREGROUND_INTENSITY );
  6609. case Colour::BrightRed: return setTextAttribute( FOREGROUND_INTENSITY | FOREGROUND_RED );
  6610. case Colour::BrightGreen: return setTextAttribute( FOREGROUND_INTENSITY | FOREGROUND_GREEN );
  6611. case Colour::BrightWhite: return setTextAttribute( FOREGROUND_INTENSITY | FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_BLUE );
  6612. case Colour::BrightYellow: return setTextAttribute( FOREGROUND_INTENSITY | FOREGROUND_RED | FOREGROUND_GREEN );
  6613. case Colour::Bright: CATCH_INTERNAL_ERROR( "not a colour" );
  6614. default:
  6615. CATCH_ERROR( "Unknown colour requested" );
  6616. }
  6617. }
  6618. private:
  6619. void setTextAttribute( WORD _textAttribute ) {
  6620. SetConsoleTextAttribute( stdoutHandle, _textAttribute | originalBackgroundAttributes );
  6621. }
  6622. HANDLE stdoutHandle;
  6623. WORD originalForegroundAttributes;
  6624. WORD originalBackgroundAttributes;
  6625. };
  6626. IColourImpl* platformColourInstance() {
  6627. static Win32ColourImpl s_instance;
  6628. IConfigPtr config = getCurrentContext().getConfig();
  6629. UseColour::YesOrNo colourMode = config
  6630. ? config->useColour()
  6631. : UseColour::Auto;
  6632. if( colourMode == UseColour::Auto )
  6633. colourMode = UseColour::Yes;
  6634. return colourMode == UseColour::Yes
  6635. ? &s_instance
  6636. : NoColourImpl::instance();
  6637. }
  6638. } // end anon namespace
  6639. } // end namespace Catch
  6640. #elif defined( CATCH_CONFIG_COLOUR_ANSI ) //////////////////////////////////////
  6641. #include <unistd.h>
  6642. namespace Catch {
  6643. namespace {
  6644. // use POSIX/ ANSI console terminal codes
  6645. // Thanks to Adam Strzelecki for original contribution
  6646. // (http://github.com/nanoant)
  6647. // https://github.com/philsquared/Catch/pull/131
  6648. class PosixColourImpl : public IColourImpl {
  6649. public:
  6650. void use( Colour::Code _colourCode ) override {
  6651. switch( _colourCode ) {
  6652. case Colour::None:
  6653. case Colour::White: return setColour( "[0m" );
  6654. case Colour::Red: return setColour( "[0;31m" );
  6655. case Colour::Green: return setColour( "[0;32m" );
  6656. case Colour::Blue: return setColour( "[0;34m" );
  6657. case Colour::Cyan: return setColour( "[0;36m" );
  6658. case Colour::Yellow: return setColour( "[0;33m" );
  6659. case Colour::Grey: return setColour( "[1;30m" );
  6660. case Colour::LightGrey: return setColour( "[0;37m" );
  6661. case Colour::BrightRed: return setColour( "[1;31m" );
  6662. case Colour::BrightGreen: return setColour( "[1;32m" );
  6663. case Colour::BrightWhite: return setColour( "[1;37m" );
  6664. case Colour::BrightYellow: return setColour( "[1;33m" );
  6665. case Colour::Bright: CATCH_INTERNAL_ERROR( "not a colour" );
  6666. default: CATCH_INTERNAL_ERROR( "Unknown colour requested" );
  6667. }
  6668. }
  6669. static IColourImpl* instance() {
  6670. static PosixColourImpl s_instance;
  6671. return &s_instance;
  6672. }
  6673. private:
  6674. void setColour( const char* _escapeCode ) {
  6675. getCurrentContext().getConfig()->stream()
  6676. << '\033' << _escapeCode;
  6677. }
  6678. };
  6679. bool useColourOnPlatform() {
  6680. return
  6681. #ifdef CATCH_PLATFORM_MAC
  6682. !isDebuggerActive() &&
  6683. #endif
  6684. #if !(defined(__DJGPP__) && defined(__STRICT_ANSI__))
  6685. isatty(STDOUT_FILENO)
  6686. #else
  6687. false
  6688. #endif
  6689. ;
  6690. }
  6691. IColourImpl* platformColourInstance() {
  6692. ErrnoGuard guard;
  6693. IConfigPtr config = getCurrentContext().getConfig();
  6694. UseColour::YesOrNo colourMode = config
  6695. ? config->useColour()
  6696. : UseColour::Auto;
  6697. if( colourMode == UseColour::Auto )
  6698. colourMode = useColourOnPlatform()
  6699. ? UseColour::Yes
  6700. : UseColour::No;
  6701. return colourMode == UseColour::Yes
  6702. ? PosixColourImpl::instance()
  6703. : NoColourImpl::instance();
  6704. }
  6705. } // end anon namespace
  6706. } // end namespace Catch
  6707. #else // not Windows or ANSI ///////////////////////////////////////////////
  6708. namespace Catch {
  6709. static IColourImpl* platformColourInstance() { return NoColourImpl::instance(); }
  6710. } // end namespace Catch
  6711. #endif // Windows/ ANSI/ None
  6712. namespace Catch {
  6713. Colour::Colour( Code _colourCode ) { use( _colourCode ); }
  6714. Colour::Colour( Colour&& rhs ) noexcept {
  6715. m_moved = rhs.m_moved;
  6716. rhs.m_moved = true;
  6717. }
  6718. Colour& Colour::operator=( Colour&& rhs ) noexcept {
  6719. m_moved = rhs.m_moved;
  6720. rhs.m_moved = true;
  6721. return *this;
  6722. }
  6723. Colour::~Colour(){ if( !m_moved ) use( None ); }
  6724. void Colour::use( Code _colourCode ) {
  6725. static IColourImpl* impl = platformColourInstance();
  6726. impl->use( _colourCode );
  6727. }
  6728. std::ostream& operator << ( std::ostream& os, Colour const& ) {
  6729. return os;
  6730. }
  6731. } // end namespace Catch
  6732. #if defined(__clang__)
  6733. # pragma clang diagnostic pop
  6734. #endif
  6735. // end catch_console_colour.cpp
  6736. // start catch_context.cpp
  6737. namespace Catch {
  6738. class Context : public IMutableContext, NonCopyable {
  6739. public: // IContext
  6740. IResultCapture* getResultCapture() override {
  6741. return m_resultCapture;
  6742. }
  6743. IRunner* getRunner() override {
  6744. return m_runner;
  6745. }
  6746. IConfigPtr const& getConfig() const override {
  6747. return m_config;
  6748. }
  6749. ~Context() override;
  6750. public: // IMutableContext
  6751. void setResultCapture( IResultCapture* resultCapture ) override {
  6752. m_resultCapture = resultCapture;
  6753. }
  6754. void setRunner( IRunner* runner ) override {
  6755. m_runner = runner;
  6756. }
  6757. void setConfig( IConfigPtr const& config ) override {
  6758. m_config = config;
  6759. }
  6760. friend IMutableContext& getCurrentMutableContext();
  6761. private:
  6762. IConfigPtr m_config;
  6763. IRunner* m_runner = nullptr;
  6764. IResultCapture* m_resultCapture = nullptr;
  6765. };
  6766. IMutableContext *IMutableContext::currentContext = nullptr;
  6767. void IMutableContext::createContext()
  6768. {
  6769. currentContext = new Context();
  6770. }
  6771. void cleanUpContext() {
  6772. delete IMutableContext::currentContext;
  6773. IMutableContext::currentContext = nullptr;
  6774. }
  6775. IContext::~IContext() = default;
  6776. IMutableContext::~IMutableContext() = default;
  6777. Context::~Context() = default;
  6778. }
  6779. // end catch_context.cpp
  6780. // start catch_debug_console.cpp
  6781. // start catch_debug_console.h
  6782. #include <string>
  6783. namespace Catch {
  6784. void writeToDebugConsole( std::string const& text );
  6785. }
  6786. // end catch_debug_console.h
  6787. #ifdef CATCH_PLATFORM_WINDOWS
  6788. namespace Catch {
  6789. void writeToDebugConsole( std::string const& text ) {
  6790. ::OutputDebugStringA( text.c_str() );
  6791. }
  6792. }
  6793. #else
  6794. namespace Catch {
  6795. void writeToDebugConsole( std::string const& text ) {
  6796. // !TBD: Need a version for Mac/ XCode and other IDEs
  6797. Catch::cout() << text;
  6798. }
  6799. }
  6800. #endif // Platform
  6801. // end catch_debug_console.cpp
  6802. // start catch_debugger.cpp
  6803. #ifdef CATCH_PLATFORM_MAC
  6804. # include <assert.h>
  6805. # include <stdbool.h>
  6806. # include <sys/types.h>
  6807. # include <unistd.h>
  6808. # include <cstddef>
  6809. # include <ostream>
  6810. #ifdef __apple_build_version__
  6811. // These headers will only compile with AppleClang (XCode)
  6812. // For other compilers (Clang, GCC, ... ) we need to exclude them
  6813. # include <sys/sysctl.h>
  6814. #endif
  6815. namespace Catch {
  6816. #ifdef __apple_build_version__
  6817. // The following function is taken directly from the following technical note:
  6818. // https://developer.apple.com/library/archive/qa/qa1361/_index.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. #else
  6844. bool isDebuggerActive() {
  6845. // We need to find another way to determine this for non-appleclang compilers on macOS
  6846. return false;
  6847. }
  6848. #endif
  6849. } // namespace Catch
  6850. #elif defined(CATCH_PLATFORM_LINUX)
  6851. #include <fstream>
  6852. #include <string>
  6853. namespace Catch{
  6854. // The standard POSIX way of detecting a debugger is to attempt to
  6855. // ptrace() the process, but this needs to be done from a child and not
  6856. // this process itself to still allow attaching to this process later
  6857. // if wanted, so is rather heavy. Under Linux we have the PID of the
  6858. // "debugger" (which doesn't need to be gdb, of course, it could also
  6859. // be strace, for example) in /proc/$PID/status, so just get it from
  6860. // there instead.
  6861. bool isDebuggerActive(){
  6862. // Libstdc++ has a bug, where std::ifstream sets errno to 0
  6863. // This way our users can properly assert over errno values
  6864. ErrnoGuard guard;
  6865. std::ifstream in("/proc/self/status");
  6866. for( std::string line; std::getline(in, line); ) {
  6867. static const int PREFIX_LEN = 11;
  6868. if( line.compare(0, PREFIX_LEN, "TracerPid:\t") == 0 ) {
  6869. // We're traced if the PID is not 0 and no other PID starts
  6870. // with 0 digit, so it's enough to check for just a single
  6871. // character.
  6872. return line.length() > PREFIX_LEN && line[PREFIX_LEN] != '0';
  6873. }
  6874. }
  6875. return false;
  6876. }
  6877. } // namespace Catch
  6878. #elif defined(_MSC_VER)
  6879. extern "C" __declspec(dllimport) int __stdcall IsDebuggerPresent();
  6880. namespace Catch {
  6881. bool isDebuggerActive() {
  6882. return IsDebuggerPresent() != 0;
  6883. }
  6884. }
  6885. #elif defined(__MINGW32__)
  6886. extern "C" __declspec(dllimport) int __stdcall IsDebuggerPresent();
  6887. namespace Catch {
  6888. bool isDebuggerActive() {
  6889. return IsDebuggerPresent() != 0;
  6890. }
  6891. }
  6892. #else
  6893. namespace Catch {
  6894. bool isDebuggerActive() { return false; }
  6895. }
  6896. #endif // Platform
  6897. // end catch_debugger.cpp
  6898. // start catch_decomposer.cpp
  6899. namespace Catch {
  6900. ITransientExpression::~ITransientExpression() = default;
  6901. void formatReconstructedExpression( std::ostream &os, std::string const& lhs, StringRef op, std::string const& rhs ) {
  6902. if( lhs.size() + rhs.size() < 40 &&
  6903. lhs.find('\n') == std::string::npos &&
  6904. rhs.find('\n') == std::string::npos )
  6905. os << lhs << " " << op << " " << rhs;
  6906. else
  6907. os << lhs << "\n" << op << "\n" << rhs;
  6908. }
  6909. }
  6910. // end catch_decomposer.cpp
  6911. // start catch_enforce.cpp
  6912. namespace Catch {
  6913. #if defined(CATCH_CONFIG_DISABLE_EXCEPTIONS) && !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS_CUSTOM_HANDLER)
  6914. [[noreturn]]
  6915. void throw_exception(std::exception const& e) {
  6916. Catch::cerr() << "Catch will terminate because it needed to throw an exception.\n"
  6917. << "The message was: " << e.what() << '\n';
  6918. std::terminate();
  6919. }
  6920. #endif
  6921. } // namespace Catch;
  6922. // end catch_enforce.cpp
  6923. // start catch_errno_guard.cpp
  6924. #include <cerrno>
  6925. namespace Catch {
  6926. ErrnoGuard::ErrnoGuard():m_oldErrno(errno){}
  6927. ErrnoGuard::~ErrnoGuard() { errno = m_oldErrno; }
  6928. }
  6929. // end catch_errno_guard.cpp
  6930. // start catch_exception_translator_registry.cpp
  6931. // start catch_exception_translator_registry.h
  6932. #include <vector>
  6933. #include <string>
  6934. #include <memory>
  6935. namespace Catch {
  6936. class ExceptionTranslatorRegistry : public IExceptionTranslatorRegistry {
  6937. public:
  6938. ~ExceptionTranslatorRegistry();
  6939. virtual void registerTranslator( const IExceptionTranslator* translator );
  6940. std::string translateActiveException() const override;
  6941. std::string tryTranslators() const;
  6942. private:
  6943. std::vector<std::unique_ptr<IExceptionTranslator const>> m_translators;
  6944. };
  6945. }
  6946. // end catch_exception_translator_registry.h
  6947. #ifdef __OBJC__
  6948. #import "Foundation/Foundation.h"
  6949. #endif
  6950. namespace Catch {
  6951. ExceptionTranslatorRegistry::~ExceptionTranslatorRegistry() {
  6952. }
  6953. void ExceptionTranslatorRegistry::registerTranslator( const IExceptionTranslator* translator ) {
  6954. m_translators.push_back( std::unique_ptr<const IExceptionTranslator>( translator ) );
  6955. }
  6956. #if !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
  6957. std::string ExceptionTranslatorRegistry::translateActiveException() const {
  6958. try {
  6959. #ifdef __OBJC__
  6960. // In Objective-C try objective-c exceptions first
  6961. @try {
  6962. return tryTranslators();
  6963. }
  6964. @catch (NSException *exception) {
  6965. return Catch::Detail::stringify( [exception description] );
  6966. }
  6967. #else
  6968. // Compiling a mixed mode project with MSVC means that CLR
  6969. // exceptions will be caught in (...) as well. However, these
  6970. // do not fill-in std::current_exception and thus lead to crash
  6971. // when attempting rethrow.
  6972. // /EHa switch also causes structured exceptions to be caught
  6973. // here, but they fill-in current_exception properly, so
  6974. // at worst the output should be a little weird, instead of
  6975. // causing a crash.
  6976. if (std::current_exception() == nullptr) {
  6977. return "Non C++ exception. Possibly a CLR exception.";
  6978. }
  6979. return tryTranslators();
  6980. #endif
  6981. }
  6982. catch( TestFailureException& ) {
  6983. std::rethrow_exception(std::current_exception());
  6984. }
  6985. catch( std::exception& ex ) {
  6986. return ex.what();
  6987. }
  6988. catch( std::string& msg ) {
  6989. return msg;
  6990. }
  6991. catch( const char* msg ) {
  6992. return msg;
  6993. }
  6994. catch(...) {
  6995. return "Unknown exception";
  6996. }
  6997. }
  6998. std::string ExceptionTranslatorRegistry::tryTranslators() const {
  6999. if (m_translators.empty()) {
  7000. std::rethrow_exception(std::current_exception());
  7001. } else {
  7002. return m_translators[0]->translate(m_translators.begin() + 1, m_translators.end());
  7003. }
  7004. }
  7005. #else // ^^ Exceptions are enabled // Exceptions are disabled vv
  7006. std::string ExceptionTranslatorRegistry::translateActiveException() const {
  7007. CATCH_INTERNAL_ERROR("Attempted to translate active exception under CATCH_CONFIG_DISABLE_EXCEPTIONS!");
  7008. }
  7009. std::string ExceptionTranslatorRegistry::tryTranslators() const {
  7010. CATCH_INTERNAL_ERROR("Attempted to use exception translators under CATCH_CONFIG_DISABLE_EXCEPTIONS!");
  7011. }
  7012. #endif
  7013. }
  7014. // end catch_exception_translator_registry.cpp
  7015. // start catch_fatal_condition.cpp
  7016. #if defined(__GNUC__)
  7017. # pragma GCC diagnostic push
  7018. # pragma GCC diagnostic ignored "-Wmissing-field-initializers"
  7019. #endif
  7020. #if defined( CATCH_CONFIG_WINDOWS_SEH ) || defined( CATCH_CONFIG_POSIX_SIGNALS )
  7021. namespace {
  7022. // Report the error condition
  7023. void reportFatal( char const * const message ) {
  7024. Catch::getCurrentContext().getResultCapture()->handleFatalErrorCondition( message );
  7025. }
  7026. }
  7027. #endif // signals/SEH handling
  7028. #if defined( CATCH_CONFIG_WINDOWS_SEH )
  7029. namespace Catch {
  7030. struct SignalDefs { DWORD id; const char* name; };
  7031. // There is no 1-1 mapping between signals and windows exceptions.
  7032. // Windows can easily distinguish between SO and SigSegV,
  7033. // but SigInt, SigTerm, etc are handled differently.
  7034. static SignalDefs signalDefs[] = {
  7035. { static_cast<DWORD>(EXCEPTION_ILLEGAL_INSTRUCTION), "SIGILL - Illegal instruction signal" },
  7036. { static_cast<DWORD>(EXCEPTION_STACK_OVERFLOW), "SIGSEGV - Stack overflow" },
  7037. { static_cast<DWORD>(EXCEPTION_ACCESS_VIOLATION), "SIGSEGV - Segmentation violation signal" },
  7038. { static_cast<DWORD>(EXCEPTION_INT_DIVIDE_BY_ZERO), "Divide by zero error" },
  7039. };
  7040. LONG CALLBACK FatalConditionHandler::handleVectoredException(PEXCEPTION_POINTERS ExceptionInfo) {
  7041. for (auto const& def : signalDefs) {
  7042. if (ExceptionInfo->ExceptionRecord->ExceptionCode == def.id) {
  7043. reportFatal(def.name);
  7044. }
  7045. }
  7046. // If its not an exception we care about, pass it along.
  7047. // This stops us from eating debugger breaks etc.
  7048. return EXCEPTION_CONTINUE_SEARCH;
  7049. }
  7050. FatalConditionHandler::FatalConditionHandler() {
  7051. isSet = true;
  7052. // 32k seems enough for Catch to handle stack overflow,
  7053. // but the value was found experimentally, so there is no strong guarantee
  7054. guaranteeSize = 32 * 1024;
  7055. exceptionHandlerHandle = nullptr;
  7056. // Register as first handler in current chain
  7057. exceptionHandlerHandle = AddVectoredExceptionHandler(1, handleVectoredException);
  7058. // Pass in guarantee size to be filled
  7059. SetThreadStackGuarantee(&guaranteeSize);
  7060. }
  7061. void FatalConditionHandler::reset() {
  7062. if (isSet) {
  7063. RemoveVectoredExceptionHandler(exceptionHandlerHandle);
  7064. SetThreadStackGuarantee(&guaranteeSize);
  7065. exceptionHandlerHandle = nullptr;
  7066. isSet = false;
  7067. }
  7068. }
  7069. FatalConditionHandler::~FatalConditionHandler() {
  7070. reset();
  7071. }
  7072. bool FatalConditionHandler::isSet = false;
  7073. ULONG FatalConditionHandler::guaranteeSize = 0;
  7074. PVOID FatalConditionHandler::exceptionHandlerHandle = nullptr;
  7075. } // namespace Catch
  7076. #elif defined( CATCH_CONFIG_POSIX_SIGNALS )
  7077. namespace Catch {
  7078. struct SignalDefs {
  7079. int id;
  7080. const char* name;
  7081. };
  7082. // 32kb for the alternate stack seems to be sufficient. However, this value
  7083. // is experimentally determined, so that's not guaranteed.
  7084. constexpr static std::size_t sigStackSize = 32768 >= MINSIGSTKSZ ? 32768 : MINSIGSTKSZ;
  7085. static SignalDefs signalDefs[] = {
  7086. { SIGINT, "SIGINT - Terminal interrupt signal" },
  7087. { SIGILL, "SIGILL - Illegal instruction signal" },
  7088. { SIGFPE, "SIGFPE - Floating point error signal" },
  7089. { SIGSEGV, "SIGSEGV - Segmentation violation signal" },
  7090. { SIGTERM, "SIGTERM - Termination request signal" },
  7091. { SIGABRT, "SIGABRT - Abort (abnormal termination) signal" }
  7092. };
  7093. void FatalConditionHandler::handleSignal( int sig ) {
  7094. char const * name = "<unknown signal>";
  7095. for (auto const& def : signalDefs) {
  7096. if (sig == def.id) {
  7097. name = def.name;
  7098. break;
  7099. }
  7100. }
  7101. reset();
  7102. reportFatal(name);
  7103. raise( sig );
  7104. }
  7105. FatalConditionHandler::FatalConditionHandler() {
  7106. isSet = true;
  7107. stack_t sigStack;
  7108. sigStack.ss_sp = altStackMem;
  7109. sigStack.ss_size = sigStackSize;
  7110. sigStack.ss_flags = 0;
  7111. sigaltstack(&sigStack, &oldSigStack);
  7112. struct sigaction sa = { };
  7113. sa.sa_handler = handleSignal;
  7114. sa.sa_flags = SA_ONSTACK;
  7115. for (std::size_t i = 0; i < sizeof(signalDefs)/sizeof(SignalDefs); ++i) {
  7116. sigaction(signalDefs[i].id, &sa, &oldSigActions[i]);
  7117. }
  7118. }
  7119. FatalConditionHandler::~FatalConditionHandler() {
  7120. reset();
  7121. }
  7122. void FatalConditionHandler::reset() {
  7123. if( isSet ) {
  7124. // Set signals back to previous values -- hopefully nobody overwrote them in the meantime
  7125. for( std::size_t i = 0; i < sizeof(signalDefs)/sizeof(SignalDefs); ++i ) {
  7126. sigaction(signalDefs[i].id, &oldSigActions[i], nullptr);
  7127. }
  7128. // Return the old stack
  7129. sigaltstack(&oldSigStack, nullptr);
  7130. isSet = false;
  7131. }
  7132. }
  7133. bool FatalConditionHandler::isSet = false;
  7134. struct sigaction FatalConditionHandler::oldSigActions[sizeof(signalDefs)/sizeof(SignalDefs)] = {};
  7135. stack_t FatalConditionHandler::oldSigStack = {};
  7136. char FatalConditionHandler::altStackMem[sigStackSize] = {};
  7137. } // namespace Catch
  7138. #else
  7139. namespace Catch {
  7140. void FatalConditionHandler::reset() {}
  7141. }
  7142. #endif // signals/SEH handling
  7143. #if defined(__GNUC__)
  7144. # pragma GCC diagnostic pop
  7145. #endif
  7146. // end catch_fatal_condition.cpp
  7147. // start catch_generators.cpp
  7148. // start catch_random_number_generator.h
  7149. #include <algorithm>
  7150. #include <random>
  7151. namespace Catch {
  7152. struct IConfig;
  7153. std::mt19937& rng();
  7154. void seedRng( IConfig const& config );
  7155. unsigned int rngSeed();
  7156. }
  7157. // end catch_random_number_generator.h
  7158. #include <limits>
  7159. #include <set>
  7160. namespace Catch {
  7161. IGeneratorTracker::~IGeneratorTracker() {}
  7162. const char* GeneratorException::what() const noexcept {
  7163. return m_msg;
  7164. }
  7165. namespace Generators {
  7166. GeneratorUntypedBase::~GeneratorUntypedBase() {}
  7167. auto acquireGeneratorTracker( SourceLineInfo const& lineInfo ) -> IGeneratorTracker& {
  7168. return getResultCapture().acquireGeneratorTracker( lineInfo );
  7169. }
  7170. } // namespace Generators
  7171. } // namespace Catch
  7172. // end catch_generators.cpp
  7173. // start catch_interfaces_capture.cpp
  7174. namespace Catch {
  7175. IResultCapture::~IResultCapture() = default;
  7176. }
  7177. // end catch_interfaces_capture.cpp
  7178. // start catch_interfaces_config.cpp
  7179. namespace Catch {
  7180. IConfig::~IConfig() = default;
  7181. }
  7182. // end catch_interfaces_config.cpp
  7183. // start catch_interfaces_exception.cpp
  7184. namespace Catch {
  7185. IExceptionTranslator::~IExceptionTranslator() = default;
  7186. IExceptionTranslatorRegistry::~IExceptionTranslatorRegistry() = default;
  7187. }
  7188. // end catch_interfaces_exception.cpp
  7189. // start catch_interfaces_registry_hub.cpp
  7190. namespace Catch {
  7191. IRegistryHub::~IRegistryHub() = default;
  7192. IMutableRegistryHub::~IMutableRegistryHub() = default;
  7193. }
  7194. // end catch_interfaces_registry_hub.cpp
  7195. // start catch_interfaces_reporter.cpp
  7196. // start catch_reporter_listening.h
  7197. namespace Catch {
  7198. class ListeningReporter : public IStreamingReporter {
  7199. using Reporters = std::vector<IStreamingReporterPtr>;
  7200. Reporters m_listeners;
  7201. IStreamingReporterPtr m_reporter = nullptr;
  7202. ReporterPreferences m_preferences;
  7203. public:
  7204. ListeningReporter();
  7205. void addListener( IStreamingReporterPtr&& listener );
  7206. void addReporter( IStreamingReporterPtr&& reporter );
  7207. public: // IStreamingReporter
  7208. ReporterPreferences getPreferences() const override;
  7209. void noMatchingTestCases( std::string const& spec ) override;
  7210. static std::set<Verbosity> getSupportedVerbosities();
  7211. void benchmarkStarting( BenchmarkInfo const& benchmarkInfo ) override;
  7212. void benchmarkEnded( BenchmarkStats const& benchmarkStats ) override;
  7213. void testRunStarting( TestRunInfo const& testRunInfo ) override;
  7214. void testGroupStarting( GroupInfo const& groupInfo ) override;
  7215. void testCaseStarting( TestCaseInfo const& testInfo ) override;
  7216. void sectionStarting( SectionInfo const& sectionInfo ) override;
  7217. void assertionStarting( AssertionInfo const& assertionInfo ) override;
  7218. // The return value indicates if the messages buffer should be cleared:
  7219. bool assertionEnded( AssertionStats const& assertionStats ) override;
  7220. void sectionEnded( SectionStats const& sectionStats ) override;
  7221. void testCaseEnded( TestCaseStats const& testCaseStats ) override;
  7222. void testGroupEnded( TestGroupStats const& testGroupStats ) override;
  7223. void testRunEnded( TestRunStats const& testRunStats ) override;
  7224. void skipTest( TestCaseInfo const& testInfo ) override;
  7225. bool isMulti() const override;
  7226. };
  7227. } // end namespace Catch
  7228. // end catch_reporter_listening.h
  7229. namespace Catch {
  7230. ReporterConfig::ReporterConfig( IConfigPtr const& _fullConfig )
  7231. : m_stream( &_fullConfig->stream() ), m_fullConfig( _fullConfig ) {}
  7232. ReporterConfig::ReporterConfig( IConfigPtr const& _fullConfig, std::ostream& _stream )
  7233. : m_stream( &_stream ), m_fullConfig( _fullConfig ) {}
  7234. std::ostream& ReporterConfig::stream() const { return *m_stream; }
  7235. IConfigPtr ReporterConfig::fullConfig() const { return m_fullConfig; }
  7236. TestRunInfo::TestRunInfo( std::string const& _name ) : name( _name ) {}
  7237. GroupInfo::GroupInfo( std::string const& _name,
  7238. std::size_t _groupIndex,
  7239. std::size_t _groupsCount )
  7240. : name( _name ),
  7241. groupIndex( _groupIndex ),
  7242. groupsCounts( _groupsCount )
  7243. {}
  7244. AssertionStats::AssertionStats( AssertionResult const& _assertionResult,
  7245. std::vector<MessageInfo> const& _infoMessages,
  7246. Totals const& _totals )
  7247. : assertionResult( _assertionResult ),
  7248. infoMessages( _infoMessages ),
  7249. totals( _totals )
  7250. {
  7251. assertionResult.m_resultData.lazyExpression.m_transientExpression = _assertionResult.m_resultData.lazyExpression.m_transientExpression;
  7252. if( assertionResult.hasMessage() ) {
  7253. // Copy message into messages list.
  7254. // !TBD This should have been done earlier, somewhere
  7255. MessageBuilder builder( assertionResult.getTestMacroName(), assertionResult.getSourceInfo(), assertionResult.getResultType() );
  7256. builder << assertionResult.getMessage();
  7257. builder.m_info.message = builder.m_stream.str();
  7258. infoMessages.push_back( builder.m_info );
  7259. }
  7260. }
  7261. AssertionStats::~AssertionStats() = default;
  7262. SectionStats::SectionStats( SectionInfo const& _sectionInfo,
  7263. Counts const& _assertions,
  7264. double _durationInSeconds,
  7265. bool _missingAssertions )
  7266. : sectionInfo( _sectionInfo ),
  7267. assertions( _assertions ),
  7268. durationInSeconds( _durationInSeconds ),
  7269. missingAssertions( _missingAssertions )
  7270. {}
  7271. SectionStats::~SectionStats() = default;
  7272. TestCaseStats::TestCaseStats( TestCaseInfo const& _testInfo,
  7273. Totals const& _totals,
  7274. std::string const& _stdOut,
  7275. std::string const& _stdErr,
  7276. bool _aborting )
  7277. : testInfo( _testInfo ),
  7278. totals( _totals ),
  7279. stdOut( _stdOut ),
  7280. stdErr( _stdErr ),
  7281. aborting( _aborting )
  7282. {}
  7283. TestCaseStats::~TestCaseStats() = default;
  7284. TestGroupStats::TestGroupStats( GroupInfo const& _groupInfo,
  7285. Totals const& _totals,
  7286. bool _aborting )
  7287. : groupInfo( _groupInfo ),
  7288. totals( _totals ),
  7289. aborting( _aborting )
  7290. {}
  7291. TestGroupStats::TestGroupStats( GroupInfo const& _groupInfo )
  7292. : groupInfo( _groupInfo ),
  7293. aborting( false )
  7294. {}
  7295. TestGroupStats::~TestGroupStats() = default;
  7296. TestRunStats::TestRunStats( TestRunInfo const& _runInfo,
  7297. Totals const& _totals,
  7298. bool _aborting )
  7299. : runInfo( _runInfo ),
  7300. totals( _totals ),
  7301. aborting( _aborting )
  7302. {}
  7303. TestRunStats::~TestRunStats() = default;
  7304. void IStreamingReporter::fatalErrorEncountered( StringRef ) {}
  7305. bool IStreamingReporter::isMulti() const { return false; }
  7306. IReporterFactory::~IReporterFactory() = default;
  7307. IReporterRegistry::~IReporterRegistry() = default;
  7308. } // end namespace Catch
  7309. // end catch_interfaces_reporter.cpp
  7310. // start catch_interfaces_runner.cpp
  7311. namespace Catch {
  7312. IRunner::~IRunner() = default;
  7313. }
  7314. // end catch_interfaces_runner.cpp
  7315. // start catch_interfaces_testcase.cpp
  7316. namespace Catch {
  7317. ITestInvoker::~ITestInvoker() = default;
  7318. ITestCaseRegistry::~ITestCaseRegistry() = default;
  7319. }
  7320. // end catch_interfaces_testcase.cpp
  7321. // start catch_leak_detector.cpp
  7322. #ifdef CATCH_CONFIG_WINDOWS_CRTDBG
  7323. #include <crtdbg.h>
  7324. namespace Catch {
  7325. LeakDetector::LeakDetector() {
  7326. int flag = _CrtSetDbgFlag(_CRTDBG_REPORT_FLAG);
  7327. flag |= _CRTDBG_LEAK_CHECK_DF;
  7328. flag |= _CRTDBG_ALLOC_MEM_DF;
  7329. _CrtSetDbgFlag(flag);
  7330. _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE | _CRTDBG_MODE_DEBUG);
  7331. _CrtSetReportFile(_CRT_WARN, _CRTDBG_FILE_STDERR);
  7332. // Change this to leaking allocation's number to break there
  7333. _CrtSetBreakAlloc(-1);
  7334. }
  7335. }
  7336. #else
  7337. Catch::LeakDetector::LeakDetector() {}
  7338. #endif
  7339. Catch::LeakDetector::~LeakDetector() {
  7340. Catch::cleanUp();
  7341. }
  7342. // end catch_leak_detector.cpp
  7343. // start catch_list.cpp
  7344. // start catch_list.h
  7345. #include <set>
  7346. namespace Catch {
  7347. std::size_t listTests( Config const& config );
  7348. std::size_t listTestsNamesOnly( Config const& config );
  7349. struct TagInfo {
  7350. void add( std::string const& spelling );
  7351. std::string all() const;
  7352. std::set<std::string> spellings;
  7353. std::size_t count = 0;
  7354. };
  7355. std::size_t listTags( Config const& config );
  7356. std::size_t listReporters();
  7357. Option<std::size_t> list( std::shared_ptr<Config> const& config );
  7358. } // end namespace Catch
  7359. // end catch_list.h
  7360. // start catch_text.h
  7361. namespace Catch {
  7362. using namespace clara::TextFlow;
  7363. }
  7364. // end catch_text.h
  7365. #include <limits>
  7366. #include <algorithm>
  7367. #include <iomanip>
  7368. namespace Catch {
  7369. std::size_t listTests( Config const& config ) {
  7370. TestSpec testSpec = config.testSpec();
  7371. if( config.hasTestFilters() )
  7372. Catch::cout() << "Matching test cases:\n";
  7373. else {
  7374. Catch::cout() << "All available test cases:\n";
  7375. }
  7376. auto matchedTestCases = filterTests( getAllTestCasesSorted( config ), testSpec, config );
  7377. for( auto const& testCaseInfo : matchedTestCases ) {
  7378. Colour::Code colour = testCaseInfo.isHidden()
  7379. ? Colour::SecondaryText
  7380. : Colour::None;
  7381. Colour colourGuard( colour );
  7382. Catch::cout() << Column( testCaseInfo.name ).initialIndent( 2 ).indent( 4 ) << "\n";
  7383. if( config.verbosity() >= Verbosity::High ) {
  7384. Catch::cout() << Column( Catch::Detail::stringify( testCaseInfo.lineInfo ) ).indent(4) << std::endl;
  7385. std::string description = testCaseInfo.description;
  7386. if( description.empty() )
  7387. description = "(NO DESCRIPTION)";
  7388. Catch::cout() << Column( description ).indent(4) << std::endl;
  7389. }
  7390. if( !testCaseInfo.tags.empty() )
  7391. Catch::cout() << Column( testCaseInfo.tagsAsString() ).indent( 6 ) << "\n";
  7392. }
  7393. if( !config.hasTestFilters() )
  7394. Catch::cout() << pluralise( matchedTestCases.size(), "test case" ) << '\n' << std::endl;
  7395. else
  7396. Catch::cout() << pluralise( matchedTestCases.size(), "matching test case" ) << '\n' << std::endl;
  7397. return matchedTestCases.size();
  7398. }
  7399. std::size_t listTestsNamesOnly( Config const& config ) {
  7400. TestSpec testSpec = config.testSpec();
  7401. std::size_t matchedTests = 0;
  7402. std::vector<TestCase> matchedTestCases = filterTests( getAllTestCasesSorted( config ), testSpec, config );
  7403. for( auto const& testCaseInfo : matchedTestCases ) {
  7404. matchedTests++;
  7405. if( startsWith( testCaseInfo.name, '#' ) )
  7406. Catch::cout() << '"' << testCaseInfo.name << '"';
  7407. else
  7408. Catch::cout() << testCaseInfo.name;
  7409. if ( config.verbosity() >= Verbosity::High )
  7410. Catch::cout() << "\t@" << testCaseInfo.lineInfo;
  7411. Catch::cout() << std::endl;
  7412. }
  7413. return matchedTests;
  7414. }
  7415. void TagInfo::add( std::string const& spelling ) {
  7416. ++count;
  7417. spellings.insert( spelling );
  7418. }
  7419. std::string TagInfo::all() const {
  7420. std::string out;
  7421. for( auto const& spelling : spellings )
  7422. out += "[" + spelling + "]";
  7423. return out;
  7424. }
  7425. std::size_t listTags( Config const& config ) {
  7426. TestSpec testSpec = config.testSpec();
  7427. if( config.hasTestFilters() )
  7428. Catch::cout() << "Tags for matching test cases:\n";
  7429. else {
  7430. Catch::cout() << "All available tags:\n";
  7431. }
  7432. std::map<std::string, TagInfo> tagCounts;
  7433. std::vector<TestCase> matchedTestCases = filterTests( getAllTestCasesSorted( config ), testSpec, config );
  7434. for( auto const& testCase : matchedTestCases ) {
  7435. for( auto const& tagName : testCase.getTestCaseInfo().tags ) {
  7436. std::string lcaseTagName = toLower( tagName );
  7437. auto countIt = tagCounts.find( lcaseTagName );
  7438. if( countIt == tagCounts.end() )
  7439. countIt = tagCounts.insert( std::make_pair( lcaseTagName, TagInfo() ) ).first;
  7440. countIt->second.add( tagName );
  7441. }
  7442. }
  7443. for( auto const& tagCount : tagCounts ) {
  7444. ReusableStringStream rss;
  7445. rss << " " << std::setw(2) << tagCount.second.count << " ";
  7446. auto str = rss.str();
  7447. auto wrapper = Column( tagCount.second.all() )
  7448. .initialIndent( 0 )
  7449. .indent( str.size() )
  7450. .width( CATCH_CONFIG_CONSOLE_WIDTH-10 );
  7451. Catch::cout() << str << wrapper << '\n';
  7452. }
  7453. Catch::cout() << pluralise( tagCounts.size(), "tag" ) << '\n' << std::endl;
  7454. return tagCounts.size();
  7455. }
  7456. std::size_t listReporters() {
  7457. Catch::cout() << "Available reporters:\n";
  7458. IReporterRegistry::FactoryMap const& factories = getRegistryHub().getReporterRegistry().getFactories();
  7459. std::size_t maxNameLen = 0;
  7460. for( auto const& factoryKvp : factories )
  7461. maxNameLen = (std::max)( maxNameLen, factoryKvp.first.size() );
  7462. for( auto const& factoryKvp : factories ) {
  7463. Catch::cout()
  7464. << Column( factoryKvp.first + ":" )
  7465. .indent(2)
  7466. .width( 5+maxNameLen )
  7467. + Column( factoryKvp.second->getDescription() )
  7468. .initialIndent(0)
  7469. .indent(2)
  7470. .width( CATCH_CONFIG_CONSOLE_WIDTH - maxNameLen-8 )
  7471. << "\n";
  7472. }
  7473. Catch::cout() << std::endl;
  7474. return factories.size();
  7475. }
  7476. Option<std::size_t> list( std::shared_ptr<Config> const& config ) {
  7477. Option<std::size_t> listedCount;
  7478. getCurrentMutableContext().setConfig( config );
  7479. if( config->listTests() )
  7480. listedCount = listedCount.valueOr(0) + listTests( *config );
  7481. if( config->listTestNamesOnly() )
  7482. listedCount = listedCount.valueOr(0) + listTestsNamesOnly( *config );
  7483. if( config->listTags() )
  7484. listedCount = listedCount.valueOr(0) + listTags( *config );
  7485. if( config->listReporters() )
  7486. listedCount = listedCount.valueOr(0) + listReporters();
  7487. return listedCount;
  7488. }
  7489. } // end namespace Catch
  7490. // end catch_list.cpp
  7491. // start catch_matchers.cpp
  7492. namespace Catch {
  7493. namespace Matchers {
  7494. namespace Impl {
  7495. std::string MatcherUntypedBase::toString() const {
  7496. if( m_cachedToString.empty() )
  7497. m_cachedToString = describe();
  7498. return m_cachedToString;
  7499. }
  7500. MatcherUntypedBase::~MatcherUntypedBase() = default;
  7501. } // namespace Impl
  7502. } // namespace Matchers
  7503. using namespace Matchers;
  7504. using Matchers::Impl::MatcherBase;
  7505. } // namespace Catch
  7506. // end catch_matchers.cpp
  7507. // start catch_matchers_floating.cpp
  7508. // start catch_polyfills.hpp
  7509. namespace Catch {
  7510. bool isnan(float f);
  7511. bool isnan(double d);
  7512. }
  7513. // end catch_polyfills.hpp
  7514. // start catch_to_string.hpp
  7515. #include <string>
  7516. namespace Catch {
  7517. template <typename T>
  7518. std::string to_string(T const& t) {
  7519. #if defined(CATCH_CONFIG_CPP11_TO_STRING)
  7520. return std::to_string(t);
  7521. #else
  7522. ReusableStringStream rss;
  7523. rss << t;
  7524. return rss.str();
  7525. #endif
  7526. }
  7527. } // end namespace Catch
  7528. // end catch_to_string.hpp
  7529. #include <cstdlib>
  7530. #include <cstdint>
  7531. #include <cstring>
  7532. namespace Catch {
  7533. namespace Matchers {
  7534. namespace Floating {
  7535. enum class FloatingPointKind : uint8_t {
  7536. Float,
  7537. Double
  7538. };
  7539. }
  7540. }
  7541. }
  7542. namespace {
  7543. template <typename T>
  7544. struct Converter;
  7545. template <>
  7546. struct Converter<float> {
  7547. static_assert(sizeof(float) == sizeof(int32_t), "Important ULP matcher assumption violated");
  7548. Converter(float f) {
  7549. std::memcpy(&i, &f, sizeof(f));
  7550. }
  7551. int32_t i;
  7552. };
  7553. template <>
  7554. struct Converter<double> {
  7555. static_assert(sizeof(double) == sizeof(int64_t), "Important ULP matcher assumption violated");
  7556. Converter(double d) {
  7557. std::memcpy(&i, &d, sizeof(d));
  7558. }
  7559. int64_t i;
  7560. };
  7561. template <typename T>
  7562. auto convert(T t) -> Converter<T> {
  7563. return Converter<T>(t);
  7564. }
  7565. template <typename FP>
  7566. bool almostEqualUlps(FP lhs, FP rhs, int maxUlpDiff) {
  7567. // Comparison with NaN should always be false.
  7568. // This way we can rule it out before getting into the ugly details
  7569. if (Catch::isnan(lhs) || Catch::isnan(rhs)) {
  7570. return false;
  7571. }
  7572. auto lc = convert(lhs);
  7573. auto rc = convert(rhs);
  7574. if ((lc.i < 0) != (rc.i < 0)) {
  7575. // Potentially we can have +0 and -0
  7576. return lhs == rhs;
  7577. }
  7578. auto ulpDiff = std::abs(lc.i - rc.i);
  7579. return ulpDiff <= maxUlpDiff;
  7580. }
  7581. }
  7582. namespace Catch {
  7583. namespace Matchers {
  7584. namespace Floating {
  7585. WithinAbsMatcher::WithinAbsMatcher(double target, double margin)
  7586. :m_target{ target }, m_margin{ margin } {
  7587. CATCH_ENFORCE(margin >= 0, "Invalid margin: " << margin << '.'
  7588. << " Margin has to be non-negative.");
  7589. }
  7590. // Performs equivalent check of std::fabs(lhs - rhs) <= margin
  7591. // But without the subtraction to allow for INFINITY in comparison
  7592. bool WithinAbsMatcher::match(double const& matchee) const {
  7593. return (matchee + m_margin >= m_target) && (m_target + m_margin >= matchee);
  7594. }
  7595. std::string WithinAbsMatcher::describe() const {
  7596. return "is within " + ::Catch::Detail::stringify(m_margin) + " of " + ::Catch::Detail::stringify(m_target);
  7597. }
  7598. WithinUlpsMatcher::WithinUlpsMatcher(double target, int ulps, FloatingPointKind baseType)
  7599. :m_target{ target }, m_ulps{ ulps }, m_type{ baseType } {
  7600. CATCH_ENFORCE(ulps >= 0, "Invalid ULP setting: " << ulps << '.'
  7601. << " ULPs have to be non-negative.");
  7602. }
  7603. #if defined(__clang__)
  7604. #pragma clang diagnostic push
  7605. // Clang <3.5 reports on the default branch in the switch below
  7606. #pragma clang diagnostic ignored "-Wunreachable-code"
  7607. #endif
  7608. bool WithinUlpsMatcher::match(double const& matchee) const {
  7609. switch (m_type) {
  7610. case FloatingPointKind::Float:
  7611. return almostEqualUlps<float>(static_cast<float>(matchee), static_cast<float>(m_target), m_ulps);
  7612. case FloatingPointKind::Double:
  7613. return almostEqualUlps<double>(matchee, m_target, m_ulps);
  7614. default:
  7615. CATCH_INTERNAL_ERROR( "Unknown FloatingPointKind value" );
  7616. }
  7617. }
  7618. #if defined(__clang__)
  7619. #pragma clang diagnostic pop
  7620. #endif
  7621. std::string WithinUlpsMatcher::describe() const {
  7622. return "is within " + Catch::to_string(m_ulps) + " ULPs of " + ::Catch::Detail::stringify(m_target) + ((m_type == FloatingPointKind::Float)? "f" : "");
  7623. }
  7624. }// namespace Floating
  7625. Floating::WithinUlpsMatcher WithinULP(double target, int maxUlpDiff) {
  7626. return Floating::WithinUlpsMatcher(target, maxUlpDiff, Floating::FloatingPointKind::Double);
  7627. }
  7628. Floating::WithinUlpsMatcher WithinULP(float target, int maxUlpDiff) {
  7629. return Floating::WithinUlpsMatcher(target, maxUlpDiff, Floating::FloatingPointKind::Float);
  7630. }
  7631. Floating::WithinAbsMatcher WithinAbs(double target, double margin) {
  7632. return Floating::WithinAbsMatcher(target, margin);
  7633. }
  7634. } // namespace Matchers
  7635. } // namespace Catch
  7636. // end catch_matchers_floating.cpp
  7637. // start catch_matchers_generic.cpp
  7638. std::string Catch::Matchers::Generic::Detail::finalizeDescription(const std::string& desc) {
  7639. if (desc.empty()) {
  7640. return "matches undescribed predicate";
  7641. } else {
  7642. return "matches predicate: \"" + desc + '"';
  7643. }
  7644. }
  7645. // end catch_matchers_generic.cpp
  7646. // start catch_matchers_string.cpp
  7647. #include <regex>
  7648. namespace Catch {
  7649. namespace Matchers {
  7650. namespace StdString {
  7651. CasedString::CasedString( std::string const& str, CaseSensitive::Choice caseSensitivity )
  7652. : m_caseSensitivity( caseSensitivity ),
  7653. m_str( adjustString( str ) )
  7654. {}
  7655. std::string CasedString::adjustString( std::string const& str ) const {
  7656. return m_caseSensitivity == CaseSensitive::No
  7657. ? toLower( str )
  7658. : str;
  7659. }
  7660. std::string CasedString::caseSensitivitySuffix() const {
  7661. return m_caseSensitivity == CaseSensitive::No
  7662. ? " (case insensitive)"
  7663. : std::string();
  7664. }
  7665. StringMatcherBase::StringMatcherBase( std::string const& operation, CasedString const& comparator )
  7666. : m_comparator( comparator ),
  7667. m_operation( operation ) {
  7668. }
  7669. std::string StringMatcherBase::describe() const {
  7670. std::string description;
  7671. description.reserve(5 + m_operation.size() + m_comparator.m_str.size() +
  7672. m_comparator.caseSensitivitySuffix().size());
  7673. description += m_operation;
  7674. description += ": \"";
  7675. description += m_comparator.m_str;
  7676. description += "\"";
  7677. description += m_comparator.caseSensitivitySuffix();
  7678. return description;
  7679. }
  7680. EqualsMatcher::EqualsMatcher( CasedString const& comparator ) : StringMatcherBase( "equals", comparator ) {}
  7681. bool EqualsMatcher::match( std::string const& source ) const {
  7682. return m_comparator.adjustString( source ) == m_comparator.m_str;
  7683. }
  7684. ContainsMatcher::ContainsMatcher( CasedString const& comparator ) : StringMatcherBase( "contains", comparator ) {}
  7685. bool ContainsMatcher::match( std::string const& source ) const {
  7686. return contains( m_comparator.adjustString( source ), m_comparator.m_str );
  7687. }
  7688. StartsWithMatcher::StartsWithMatcher( CasedString const& comparator ) : StringMatcherBase( "starts with", comparator ) {}
  7689. bool StartsWithMatcher::match( std::string const& source ) const {
  7690. return startsWith( m_comparator.adjustString( source ), m_comparator.m_str );
  7691. }
  7692. EndsWithMatcher::EndsWithMatcher( CasedString const& comparator ) : StringMatcherBase( "ends with", comparator ) {}
  7693. bool EndsWithMatcher::match( std::string const& source ) const {
  7694. return endsWith( m_comparator.adjustString( source ), m_comparator.m_str );
  7695. }
  7696. RegexMatcher::RegexMatcher(std::string regex, CaseSensitive::Choice caseSensitivity): m_regex(std::move(regex)), m_caseSensitivity(caseSensitivity) {}
  7697. bool RegexMatcher::match(std::string const& matchee) const {
  7698. auto flags = std::regex::ECMAScript; // ECMAScript is the default syntax option anyway
  7699. if (m_caseSensitivity == CaseSensitive::Choice::No) {
  7700. flags |= std::regex::icase;
  7701. }
  7702. auto reg = std::regex(m_regex, flags);
  7703. return std::regex_match(matchee, reg);
  7704. }
  7705. std::string RegexMatcher::describe() const {
  7706. return "matches " + ::Catch::Detail::stringify(m_regex) + ((m_caseSensitivity == CaseSensitive::Choice::Yes)? " case sensitively" : " case insensitively");
  7707. }
  7708. } // namespace StdString
  7709. StdString::EqualsMatcher Equals( std::string const& str, CaseSensitive::Choice caseSensitivity ) {
  7710. return StdString::EqualsMatcher( StdString::CasedString( str, caseSensitivity) );
  7711. }
  7712. StdString::ContainsMatcher Contains( std::string const& str, CaseSensitive::Choice caseSensitivity ) {
  7713. return StdString::ContainsMatcher( StdString::CasedString( str, caseSensitivity) );
  7714. }
  7715. StdString::EndsWithMatcher EndsWith( std::string const& str, CaseSensitive::Choice caseSensitivity ) {
  7716. return StdString::EndsWithMatcher( StdString::CasedString( str, caseSensitivity) );
  7717. }
  7718. StdString::StartsWithMatcher StartsWith( std::string const& str, CaseSensitive::Choice caseSensitivity ) {
  7719. return StdString::StartsWithMatcher( StdString::CasedString( str, caseSensitivity) );
  7720. }
  7721. StdString::RegexMatcher Matches(std::string const& regex, CaseSensitive::Choice caseSensitivity) {
  7722. return StdString::RegexMatcher(regex, caseSensitivity);
  7723. }
  7724. } // namespace Matchers
  7725. } // namespace Catch
  7726. // end catch_matchers_string.cpp
  7727. // start catch_message.cpp
  7728. // start catch_uncaught_exceptions.h
  7729. namespace Catch {
  7730. bool uncaught_exceptions();
  7731. } // end namespace Catch
  7732. // end catch_uncaught_exceptions.h
  7733. #include <cassert>
  7734. #include <stack>
  7735. namespace Catch {
  7736. MessageInfo::MessageInfo( StringRef const& _macroName,
  7737. SourceLineInfo const& _lineInfo,
  7738. ResultWas::OfType _type )
  7739. : macroName( _macroName ),
  7740. lineInfo( _lineInfo ),
  7741. type( _type ),
  7742. sequence( ++globalCount )
  7743. {}
  7744. bool MessageInfo::operator==( MessageInfo const& other ) const {
  7745. return sequence == other.sequence;
  7746. }
  7747. bool MessageInfo::operator<( MessageInfo const& other ) const {
  7748. return sequence < other.sequence;
  7749. }
  7750. // This may need protecting if threading support is added
  7751. unsigned int MessageInfo::globalCount = 0;
  7752. ////////////////////////////////////////////////////////////////////////////
  7753. Catch::MessageBuilder::MessageBuilder( StringRef const& macroName,
  7754. SourceLineInfo const& lineInfo,
  7755. ResultWas::OfType type )
  7756. :m_info(macroName, lineInfo, type) {}
  7757. ////////////////////////////////////////////////////////////////////////////
  7758. ScopedMessage::ScopedMessage( MessageBuilder const& builder )
  7759. : m_info( builder.m_info ), m_moved()
  7760. {
  7761. m_info.message = builder.m_stream.str();
  7762. getResultCapture().pushScopedMessage( m_info );
  7763. }
  7764. ScopedMessage::ScopedMessage( ScopedMessage&& old )
  7765. : m_info( old.m_info ), m_moved()
  7766. {
  7767. old.m_moved = true;
  7768. }
  7769. ScopedMessage::~ScopedMessage() {
  7770. if ( !uncaught_exceptions() && !m_moved ){
  7771. getResultCapture().popScopedMessage(m_info);
  7772. }
  7773. }
  7774. Capturer::Capturer( StringRef macroName, SourceLineInfo const& lineInfo, ResultWas::OfType resultType, StringRef names ) {
  7775. auto trimmed = [&] (size_t start, size_t end) {
  7776. while (names[start] == ',' || isspace(names[start])) {
  7777. ++start;
  7778. }
  7779. while (names[end] == ',' || isspace(names[end])) {
  7780. --end;
  7781. }
  7782. return names.substr(start, end - start + 1);
  7783. };
  7784. size_t start = 0;
  7785. std::stack<char> openings;
  7786. for (size_t pos = 0; pos < names.size(); ++pos) {
  7787. char c = names[pos];
  7788. switch (c) {
  7789. case '[':
  7790. case '{':
  7791. case '(':
  7792. // It is basically impossible to disambiguate between
  7793. // comparison and start of template args in this context
  7794. // case '<':
  7795. openings.push(c);
  7796. break;
  7797. case ']':
  7798. case '}':
  7799. case ')':
  7800. // case '>':
  7801. openings.pop();
  7802. break;
  7803. case ',':
  7804. if (start != pos && openings.size() == 0) {
  7805. m_messages.emplace_back(macroName, lineInfo, resultType);
  7806. m_messages.back().message = trimmed(start, pos);
  7807. m_messages.back().message += " := ";
  7808. start = pos;
  7809. }
  7810. }
  7811. }
  7812. assert(openings.size() == 0 && "Mismatched openings");
  7813. m_messages.emplace_back(macroName, lineInfo, resultType);
  7814. m_messages.back().message = trimmed(start, names.size() - 1);
  7815. m_messages.back().message += " := ";
  7816. }
  7817. Capturer::~Capturer() {
  7818. if ( !uncaught_exceptions() ){
  7819. assert( m_captured == m_messages.size() );
  7820. for( size_t i = 0; i < m_captured; ++i )
  7821. m_resultCapture.popScopedMessage( m_messages[i] );
  7822. }
  7823. }
  7824. void Capturer::captureValue( size_t index, std::string const& value ) {
  7825. assert( index < m_messages.size() );
  7826. m_messages[index].message += value;
  7827. m_resultCapture.pushScopedMessage( m_messages[index] );
  7828. m_captured++;
  7829. }
  7830. } // end namespace Catch
  7831. // end catch_message.cpp
  7832. // start catch_output_redirect.cpp
  7833. // start catch_output_redirect.h
  7834. #ifndef TWOBLUECUBES_CATCH_OUTPUT_REDIRECT_H
  7835. #define TWOBLUECUBES_CATCH_OUTPUT_REDIRECT_H
  7836. #include <cstdio>
  7837. #include <iosfwd>
  7838. #include <string>
  7839. namespace Catch {
  7840. class RedirectedStream {
  7841. std::ostream& m_originalStream;
  7842. std::ostream& m_redirectionStream;
  7843. std::streambuf* m_prevBuf;
  7844. public:
  7845. RedirectedStream( std::ostream& originalStream, std::ostream& redirectionStream );
  7846. ~RedirectedStream();
  7847. };
  7848. class RedirectedStdOut {
  7849. ReusableStringStream m_rss;
  7850. RedirectedStream m_cout;
  7851. public:
  7852. RedirectedStdOut();
  7853. auto str() const -> std::string;
  7854. };
  7855. // StdErr has two constituent streams in C++, std::cerr and std::clog
  7856. // This means that we need to redirect 2 streams into 1 to keep proper
  7857. // order of writes
  7858. class RedirectedStdErr {
  7859. ReusableStringStream m_rss;
  7860. RedirectedStream m_cerr;
  7861. RedirectedStream m_clog;
  7862. public:
  7863. RedirectedStdErr();
  7864. auto str() const -> std::string;
  7865. };
  7866. class RedirectedStreams {
  7867. public:
  7868. RedirectedStreams(RedirectedStreams const&) = delete;
  7869. RedirectedStreams& operator=(RedirectedStreams const&) = delete;
  7870. RedirectedStreams(RedirectedStreams&&) = delete;
  7871. RedirectedStreams& operator=(RedirectedStreams&&) = delete;
  7872. RedirectedStreams(std::string& redirectedCout, std::string& redirectedCerr);
  7873. ~RedirectedStreams();
  7874. private:
  7875. std::string& m_redirectedCout;
  7876. std::string& m_redirectedCerr;
  7877. RedirectedStdOut m_redirectedStdOut;
  7878. RedirectedStdErr m_redirectedStdErr;
  7879. };
  7880. #if defined(CATCH_CONFIG_NEW_CAPTURE)
  7881. // Windows's implementation of std::tmpfile is terrible (it tries
  7882. // to create a file inside system folder, thus requiring elevated
  7883. // privileges for the binary), so we have to use tmpnam(_s) and
  7884. // create the file ourselves there.
  7885. class TempFile {
  7886. public:
  7887. TempFile(TempFile const&) = delete;
  7888. TempFile& operator=(TempFile const&) = delete;
  7889. TempFile(TempFile&&) = delete;
  7890. TempFile& operator=(TempFile&&) = delete;
  7891. TempFile();
  7892. ~TempFile();
  7893. std::FILE* getFile();
  7894. std::string getContents();
  7895. private:
  7896. std::FILE* m_file = nullptr;
  7897. #if defined(_MSC_VER)
  7898. char m_buffer[L_tmpnam] = { 0 };
  7899. #endif
  7900. };
  7901. class OutputRedirect {
  7902. public:
  7903. OutputRedirect(OutputRedirect const&) = delete;
  7904. OutputRedirect& operator=(OutputRedirect const&) = delete;
  7905. OutputRedirect(OutputRedirect&&) = delete;
  7906. OutputRedirect& operator=(OutputRedirect&&) = delete;
  7907. OutputRedirect(std::string& stdout_dest, std::string& stderr_dest);
  7908. ~OutputRedirect();
  7909. private:
  7910. int m_originalStdout = -1;
  7911. int m_originalStderr = -1;
  7912. TempFile m_stdoutFile;
  7913. TempFile m_stderrFile;
  7914. std::string& m_stdoutDest;
  7915. std::string& m_stderrDest;
  7916. };
  7917. #endif
  7918. } // end namespace Catch
  7919. #endif // TWOBLUECUBES_CATCH_OUTPUT_REDIRECT_H
  7920. // end catch_output_redirect.h
  7921. #include <cstdio>
  7922. #include <cstring>
  7923. #include <fstream>
  7924. #include <sstream>
  7925. #include <stdexcept>
  7926. #if defined(CATCH_CONFIG_NEW_CAPTURE)
  7927. #if defined(_MSC_VER)
  7928. #include <io.h> //_dup and _dup2
  7929. #define dup _dup
  7930. #define dup2 _dup2
  7931. #define fileno _fileno
  7932. #else
  7933. #include <unistd.h> // dup and dup2
  7934. #endif
  7935. #endif
  7936. namespace Catch {
  7937. RedirectedStream::RedirectedStream( std::ostream& originalStream, std::ostream& redirectionStream )
  7938. : m_originalStream( originalStream ),
  7939. m_redirectionStream( redirectionStream ),
  7940. m_prevBuf( m_originalStream.rdbuf() )
  7941. {
  7942. m_originalStream.rdbuf( m_redirectionStream.rdbuf() );
  7943. }
  7944. RedirectedStream::~RedirectedStream() {
  7945. m_originalStream.rdbuf( m_prevBuf );
  7946. }
  7947. RedirectedStdOut::RedirectedStdOut() : m_cout( Catch::cout(), m_rss.get() ) {}
  7948. auto RedirectedStdOut::str() const -> std::string { return m_rss.str(); }
  7949. RedirectedStdErr::RedirectedStdErr()
  7950. : m_cerr( Catch::cerr(), m_rss.get() ),
  7951. m_clog( Catch::clog(), m_rss.get() )
  7952. {}
  7953. auto RedirectedStdErr::str() const -> std::string { return m_rss.str(); }
  7954. RedirectedStreams::RedirectedStreams(std::string& redirectedCout, std::string& redirectedCerr)
  7955. : m_redirectedCout(redirectedCout),
  7956. m_redirectedCerr(redirectedCerr)
  7957. {}
  7958. RedirectedStreams::~RedirectedStreams() {
  7959. m_redirectedCout += m_redirectedStdOut.str();
  7960. m_redirectedCerr += m_redirectedStdErr.str();
  7961. }
  7962. #if defined(CATCH_CONFIG_NEW_CAPTURE)
  7963. #if defined(_MSC_VER)
  7964. TempFile::TempFile() {
  7965. if (tmpnam_s(m_buffer)) {
  7966. CATCH_RUNTIME_ERROR("Could not get a temp filename");
  7967. }
  7968. if (fopen_s(&m_file, m_buffer, "w")) {
  7969. char buffer[100];
  7970. if (strerror_s(buffer, errno)) {
  7971. CATCH_RUNTIME_ERROR("Could not translate errno to a string");
  7972. }
  7973. CATCH_RUNTIME_ERROR("Could not open the temp file: '" << m_buffer << "' because: " << buffer);
  7974. }
  7975. }
  7976. #else
  7977. TempFile::TempFile() {
  7978. m_file = std::tmpfile();
  7979. if (!m_file) {
  7980. CATCH_RUNTIME_ERROR("Could not create a temp file.");
  7981. }
  7982. }
  7983. #endif
  7984. TempFile::~TempFile() {
  7985. // TBD: What to do about errors here?
  7986. std::fclose(m_file);
  7987. // We manually create the file on Windows only, on Linux
  7988. // it will be autodeleted
  7989. #if defined(_MSC_VER)
  7990. std::remove(m_buffer);
  7991. #endif
  7992. }
  7993. FILE* TempFile::getFile() {
  7994. return m_file;
  7995. }
  7996. std::string TempFile::getContents() {
  7997. std::stringstream sstr;
  7998. char buffer[100] = {};
  7999. std::rewind(m_file);
  8000. while (std::fgets(buffer, sizeof(buffer), m_file)) {
  8001. sstr << buffer;
  8002. }
  8003. return sstr.str();
  8004. }
  8005. OutputRedirect::OutputRedirect(std::string& stdout_dest, std::string& stderr_dest) :
  8006. m_originalStdout(dup(1)),
  8007. m_originalStderr(dup(2)),
  8008. m_stdoutDest(stdout_dest),
  8009. m_stderrDest(stderr_dest) {
  8010. dup2(fileno(m_stdoutFile.getFile()), 1);
  8011. dup2(fileno(m_stderrFile.getFile()), 2);
  8012. }
  8013. OutputRedirect::~OutputRedirect() {
  8014. Catch::cout() << std::flush;
  8015. fflush(stdout);
  8016. // Since we support overriding these streams, we flush cerr
  8017. // even though std::cerr is unbuffered
  8018. Catch::cerr() << std::flush;
  8019. Catch::clog() << std::flush;
  8020. fflush(stderr);
  8021. dup2(m_originalStdout, 1);
  8022. dup2(m_originalStderr, 2);
  8023. m_stdoutDest += m_stdoutFile.getContents();
  8024. m_stderrDest += m_stderrFile.getContents();
  8025. }
  8026. #endif // CATCH_CONFIG_NEW_CAPTURE
  8027. } // namespace Catch
  8028. #if defined(CATCH_CONFIG_NEW_CAPTURE)
  8029. #if defined(_MSC_VER)
  8030. #undef dup
  8031. #undef dup2
  8032. #undef fileno
  8033. #endif
  8034. #endif
  8035. // end catch_output_redirect.cpp
  8036. // start catch_polyfills.cpp
  8037. #include <cmath>
  8038. namespace Catch {
  8039. #if !defined(CATCH_CONFIG_POLYFILL_ISNAN)
  8040. bool isnan(float f) {
  8041. return std::isnan(f);
  8042. }
  8043. bool isnan(double d) {
  8044. return std::isnan(d);
  8045. }
  8046. #else
  8047. // For now we only use this for embarcadero
  8048. bool isnan(float f) {
  8049. return std::_isnan(f);
  8050. }
  8051. bool isnan(double d) {
  8052. return std::_isnan(d);
  8053. }
  8054. #endif
  8055. } // end namespace Catch
  8056. // end catch_polyfills.cpp
  8057. // start catch_random_number_generator.cpp
  8058. namespace Catch {
  8059. std::mt19937& rng() {
  8060. static std::mt19937 s_rng;
  8061. return s_rng;
  8062. }
  8063. void seedRng( IConfig const& config ) {
  8064. if( config.rngSeed() != 0 ) {
  8065. std::srand( config.rngSeed() );
  8066. rng().seed( config.rngSeed() );
  8067. }
  8068. }
  8069. unsigned int rngSeed() {
  8070. return getCurrentContext().getConfig()->rngSeed();
  8071. }
  8072. }
  8073. // end catch_random_number_generator.cpp
  8074. // start catch_registry_hub.cpp
  8075. // start catch_test_case_registry_impl.h
  8076. #include <vector>
  8077. #include <set>
  8078. #include <algorithm>
  8079. #include <ios>
  8080. namespace Catch {
  8081. class TestCase;
  8082. struct IConfig;
  8083. std::vector<TestCase> sortTests( IConfig const& config, std::vector<TestCase> const& unsortedTestCases );
  8084. bool matchTest( TestCase const& testCase, TestSpec const& testSpec, IConfig const& config );
  8085. void enforceNoDuplicateTestCases( std::vector<TestCase> const& functions );
  8086. std::vector<TestCase> filterTests( std::vector<TestCase> const& testCases, TestSpec const& testSpec, IConfig const& config );
  8087. std::vector<TestCase> const& getAllTestCasesSorted( IConfig const& config );
  8088. class TestRegistry : public ITestCaseRegistry {
  8089. public:
  8090. virtual ~TestRegistry() = default;
  8091. virtual void registerTest( TestCase const& testCase );
  8092. std::vector<TestCase> const& getAllTests() const override;
  8093. std::vector<TestCase> const& getAllTestsSorted( IConfig const& config ) const override;
  8094. private:
  8095. std::vector<TestCase> m_functions;
  8096. mutable RunTests::InWhatOrder m_currentSortOrder = RunTests::InDeclarationOrder;
  8097. mutable std::vector<TestCase> m_sortedFunctions;
  8098. std::size_t m_unnamedCount = 0;
  8099. std::ios_base::Init m_ostreamInit; // Forces cout/ cerr to be initialised
  8100. };
  8101. ///////////////////////////////////////////////////////////////////////////
  8102. class TestInvokerAsFunction : public ITestInvoker {
  8103. void(*m_testAsFunction)();
  8104. public:
  8105. TestInvokerAsFunction( void(*testAsFunction)() ) noexcept;
  8106. void invoke() const override;
  8107. };
  8108. std::string extractClassName( StringRef const& classOrQualifiedMethodName );
  8109. ///////////////////////////////////////////////////////////////////////////
  8110. } // end namespace Catch
  8111. // end catch_test_case_registry_impl.h
  8112. // start catch_reporter_registry.h
  8113. #include <map>
  8114. namespace Catch {
  8115. class ReporterRegistry : public IReporterRegistry {
  8116. public:
  8117. ~ReporterRegistry() override;
  8118. IStreamingReporterPtr create( std::string const& name, IConfigPtr const& config ) const override;
  8119. void registerReporter( std::string const& name, IReporterFactoryPtr const& factory );
  8120. void registerListener( IReporterFactoryPtr const& factory );
  8121. FactoryMap const& getFactories() const override;
  8122. Listeners const& getListeners() const override;
  8123. private:
  8124. FactoryMap m_factories;
  8125. Listeners m_listeners;
  8126. };
  8127. }
  8128. // end catch_reporter_registry.h
  8129. // start catch_tag_alias_registry.h
  8130. // start catch_tag_alias.h
  8131. #include <string>
  8132. namespace Catch {
  8133. struct TagAlias {
  8134. TagAlias(std::string const& _tag, SourceLineInfo _lineInfo);
  8135. std::string tag;
  8136. SourceLineInfo lineInfo;
  8137. };
  8138. } // end namespace Catch
  8139. // end catch_tag_alias.h
  8140. #include <map>
  8141. namespace Catch {
  8142. class TagAliasRegistry : public ITagAliasRegistry {
  8143. public:
  8144. ~TagAliasRegistry() override;
  8145. TagAlias const* find( std::string const& alias ) const override;
  8146. std::string expandAliases( std::string const& unexpandedTestSpec ) const override;
  8147. void add( std::string const& alias, std::string const& tag, SourceLineInfo const& lineInfo );
  8148. private:
  8149. std::map<std::string, TagAlias> m_registry;
  8150. };
  8151. } // end namespace Catch
  8152. // end catch_tag_alias_registry.h
  8153. // start catch_startup_exception_registry.h
  8154. #include <vector>
  8155. #include <exception>
  8156. namespace Catch {
  8157. class StartupExceptionRegistry {
  8158. public:
  8159. void add(std::exception_ptr const& exception) noexcept;
  8160. std::vector<std::exception_ptr> const& getExceptions() const noexcept;
  8161. private:
  8162. std::vector<std::exception_ptr> m_exceptions;
  8163. };
  8164. } // end namespace Catch
  8165. // end catch_startup_exception_registry.h
  8166. // start catch_singletons.hpp
  8167. namespace Catch {
  8168. struct ISingleton {
  8169. virtual ~ISingleton();
  8170. };
  8171. void addSingleton( ISingleton* singleton );
  8172. void cleanupSingletons();
  8173. template<typename SingletonImplT, typename InterfaceT = SingletonImplT, typename MutableInterfaceT = InterfaceT>
  8174. class Singleton : SingletonImplT, public ISingleton {
  8175. static auto getInternal() -> Singleton* {
  8176. static Singleton* s_instance = nullptr;
  8177. if( !s_instance ) {
  8178. s_instance = new Singleton;
  8179. addSingleton( s_instance );
  8180. }
  8181. return s_instance;
  8182. }
  8183. public:
  8184. static auto get() -> InterfaceT const& {
  8185. return *getInternal();
  8186. }
  8187. static auto getMutable() -> MutableInterfaceT& {
  8188. return *getInternal();
  8189. }
  8190. };
  8191. } // namespace Catch
  8192. // end catch_singletons.hpp
  8193. namespace Catch {
  8194. namespace {
  8195. class RegistryHub : public IRegistryHub, public IMutableRegistryHub,
  8196. private NonCopyable {
  8197. public: // IRegistryHub
  8198. RegistryHub() = default;
  8199. IReporterRegistry const& getReporterRegistry() const override {
  8200. return m_reporterRegistry;
  8201. }
  8202. ITestCaseRegistry const& getTestCaseRegistry() const override {
  8203. return m_testCaseRegistry;
  8204. }
  8205. IExceptionTranslatorRegistry const& getExceptionTranslatorRegistry() const override {
  8206. return m_exceptionTranslatorRegistry;
  8207. }
  8208. ITagAliasRegistry const& getTagAliasRegistry() const override {
  8209. return m_tagAliasRegistry;
  8210. }
  8211. StartupExceptionRegistry const& getStartupExceptionRegistry() const override {
  8212. return m_exceptionRegistry;
  8213. }
  8214. public: // IMutableRegistryHub
  8215. void registerReporter( std::string const& name, IReporterFactoryPtr const& factory ) override {
  8216. m_reporterRegistry.registerReporter( name, factory );
  8217. }
  8218. void registerListener( IReporterFactoryPtr const& factory ) override {
  8219. m_reporterRegistry.registerListener( factory );
  8220. }
  8221. void registerTest( TestCase const& testInfo ) override {
  8222. m_testCaseRegistry.registerTest( testInfo );
  8223. }
  8224. void registerTranslator( const IExceptionTranslator* translator ) override {
  8225. m_exceptionTranslatorRegistry.registerTranslator( translator );
  8226. }
  8227. void registerTagAlias( std::string const& alias, std::string const& tag, SourceLineInfo const& lineInfo ) override {
  8228. m_tagAliasRegistry.add( alias, tag, lineInfo );
  8229. }
  8230. void registerStartupException() noexcept override {
  8231. m_exceptionRegistry.add(std::current_exception());
  8232. }
  8233. private:
  8234. TestRegistry m_testCaseRegistry;
  8235. ReporterRegistry m_reporterRegistry;
  8236. ExceptionTranslatorRegistry m_exceptionTranslatorRegistry;
  8237. TagAliasRegistry m_tagAliasRegistry;
  8238. StartupExceptionRegistry m_exceptionRegistry;
  8239. };
  8240. }
  8241. using RegistryHubSingleton = Singleton<RegistryHub, IRegistryHub, IMutableRegistryHub>;
  8242. IRegistryHub const& getRegistryHub() {
  8243. return RegistryHubSingleton::get();
  8244. }
  8245. IMutableRegistryHub& getMutableRegistryHub() {
  8246. return RegistryHubSingleton::getMutable();
  8247. }
  8248. void cleanUp() {
  8249. cleanupSingletons();
  8250. cleanUpContext();
  8251. }
  8252. std::string translateActiveException() {
  8253. return getRegistryHub().getExceptionTranslatorRegistry().translateActiveException();
  8254. }
  8255. } // end namespace Catch
  8256. // end catch_registry_hub.cpp
  8257. // start catch_reporter_registry.cpp
  8258. namespace Catch {
  8259. ReporterRegistry::~ReporterRegistry() = default;
  8260. IStreamingReporterPtr ReporterRegistry::create( std::string const& name, IConfigPtr const& config ) const {
  8261. auto it = m_factories.find( name );
  8262. if( it == m_factories.end() )
  8263. return nullptr;
  8264. return it->second->create( ReporterConfig( config ) );
  8265. }
  8266. void ReporterRegistry::registerReporter( std::string const& name, IReporterFactoryPtr const& factory ) {
  8267. m_factories.emplace(name, factory);
  8268. }
  8269. void ReporterRegistry::registerListener( IReporterFactoryPtr const& factory ) {
  8270. m_listeners.push_back( factory );
  8271. }
  8272. IReporterRegistry::FactoryMap const& ReporterRegistry::getFactories() const {
  8273. return m_factories;
  8274. }
  8275. IReporterRegistry::Listeners const& ReporterRegistry::getListeners() const {
  8276. return m_listeners;
  8277. }
  8278. }
  8279. // end catch_reporter_registry.cpp
  8280. // start catch_result_type.cpp
  8281. namespace Catch {
  8282. bool isOk( ResultWas::OfType resultType ) {
  8283. return ( resultType & ResultWas::FailureBit ) == 0;
  8284. }
  8285. bool isJustInfo( int flags ) {
  8286. return flags == ResultWas::Info;
  8287. }
  8288. ResultDisposition::Flags operator | ( ResultDisposition::Flags lhs, ResultDisposition::Flags rhs ) {
  8289. return static_cast<ResultDisposition::Flags>( static_cast<int>( lhs ) | static_cast<int>( rhs ) );
  8290. }
  8291. bool shouldContinueOnFailure( int flags ) { return ( flags & ResultDisposition::ContinueOnFailure ) != 0; }
  8292. bool shouldSuppressFailure( int flags ) { return ( flags & ResultDisposition::SuppressFail ) != 0; }
  8293. } // end namespace Catch
  8294. // end catch_result_type.cpp
  8295. // start catch_run_context.cpp
  8296. #include <cassert>
  8297. #include <algorithm>
  8298. #include <sstream>
  8299. namespace Catch {
  8300. namespace Generators {
  8301. struct GeneratorTracker : TestCaseTracking::TrackerBase, IGeneratorTracker {
  8302. GeneratorBasePtr m_generator;
  8303. GeneratorTracker( TestCaseTracking::NameAndLocation const& nameAndLocation, TrackerContext& ctx, ITracker* parent )
  8304. : TrackerBase( nameAndLocation, ctx, parent )
  8305. {}
  8306. ~GeneratorTracker();
  8307. static GeneratorTracker& acquire( TrackerContext& ctx, TestCaseTracking::NameAndLocation const& nameAndLocation ) {
  8308. std::shared_ptr<GeneratorTracker> tracker;
  8309. ITracker& currentTracker = ctx.currentTracker();
  8310. if( TestCaseTracking::ITrackerPtr childTracker = currentTracker.findChild( nameAndLocation ) ) {
  8311. assert( childTracker );
  8312. assert( childTracker->isGeneratorTracker() );
  8313. tracker = std::static_pointer_cast<GeneratorTracker>( childTracker );
  8314. }
  8315. else {
  8316. tracker = std::make_shared<GeneratorTracker>( nameAndLocation, ctx, &currentTracker );
  8317. currentTracker.addChild( tracker );
  8318. }
  8319. if( !ctx.completedCycle() && !tracker->isComplete() ) {
  8320. tracker->open();
  8321. }
  8322. return *tracker;
  8323. }
  8324. // TrackerBase interface
  8325. bool isGeneratorTracker() const override { return true; }
  8326. auto hasGenerator() const -> bool override {
  8327. return !!m_generator;
  8328. }
  8329. void close() override {
  8330. TrackerBase::close();
  8331. // Generator interface only finds out if it has another item on atual move
  8332. if (m_runState == CompletedSuccessfully && m_generator->next()) {
  8333. m_children.clear();
  8334. m_runState = Executing;
  8335. }
  8336. }
  8337. // IGeneratorTracker interface
  8338. auto getGenerator() const -> GeneratorBasePtr const& override {
  8339. return m_generator;
  8340. }
  8341. void setGenerator( GeneratorBasePtr&& generator ) override {
  8342. m_generator = std::move( generator );
  8343. }
  8344. };
  8345. GeneratorTracker::~GeneratorTracker() {}
  8346. }
  8347. RunContext::RunContext(IConfigPtr const& _config, IStreamingReporterPtr&& reporter)
  8348. : m_runInfo(_config->name()),
  8349. m_context(getCurrentMutableContext()),
  8350. m_config(_config),
  8351. m_reporter(std::move(reporter)),
  8352. m_lastAssertionInfo{ StringRef(), SourceLineInfo("",0), StringRef(), ResultDisposition::Normal },
  8353. m_includeSuccessfulResults( m_config->includeSuccessfulResults() || m_reporter->getPreferences().shouldReportAllAssertions )
  8354. {
  8355. m_context.setRunner(this);
  8356. m_context.setConfig(m_config);
  8357. m_context.setResultCapture(this);
  8358. m_reporter->testRunStarting(m_runInfo);
  8359. }
  8360. RunContext::~RunContext() {
  8361. m_reporter->testRunEnded(TestRunStats(m_runInfo, m_totals, aborting()));
  8362. }
  8363. void RunContext::testGroupStarting(std::string const& testSpec, std::size_t groupIndex, std::size_t groupsCount) {
  8364. m_reporter->testGroupStarting(GroupInfo(testSpec, groupIndex, groupsCount));
  8365. }
  8366. void RunContext::testGroupEnded(std::string const& testSpec, Totals const& totals, std::size_t groupIndex, std::size_t groupsCount) {
  8367. m_reporter->testGroupEnded(TestGroupStats(GroupInfo(testSpec, groupIndex, groupsCount), totals, aborting()));
  8368. }
  8369. Totals RunContext::runTest(TestCase const& testCase) {
  8370. Totals prevTotals = m_totals;
  8371. std::string redirectedCout;
  8372. std::string redirectedCerr;
  8373. auto const& testInfo = testCase.getTestCaseInfo();
  8374. m_reporter->testCaseStarting(testInfo);
  8375. m_activeTestCase = &testCase;
  8376. ITracker& rootTracker = m_trackerContext.startRun();
  8377. assert(rootTracker.isSectionTracker());
  8378. static_cast<SectionTracker&>(rootTracker).addInitialFilters(m_config->getSectionsToRun());
  8379. do {
  8380. m_trackerContext.startCycle();
  8381. m_testCaseTracker = &SectionTracker::acquire(m_trackerContext, TestCaseTracking::NameAndLocation(testInfo.name, testInfo.lineInfo));
  8382. runCurrentTest(redirectedCout, redirectedCerr);
  8383. } while (!m_testCaseTracker->isSuccessfullyCompleted() && !aborting());
  8384. Totals deltaTotals = m_totals.delta(prevTotals);
  8385. if (testInfo.expectedToFail() && deltaTotals.testCases.passed > 0) {
  8386. deltaTotals.assertions.failed++;
  8387. deltaTotals.testCases.passed--;
  8388. deltaTotals.testCases.failed++;
  8389. }
  8390. m_totals.testCases += deltaTotals.testCases;
  8391. m_reporter->testCaseEnded(TestCaseStats(testInfo,
  8392. deltaTotals,
  8393. redirectedCout,
  8394. redirectedCerr,
  8395. aborting()));
  8396. m_activeTestCase = nullptr;
  8397. m_testCaseTracker = nullptr;
  8398. return deltaTotals;
  8399. }
  8400. IConfigPtr RunContext::config() const {
  8401. return m_config;
  8402. }
  8403. IStreamingReporter& RunContext::reporter() const {
  8404. return *m_reporter;
  8405. }
  8406. void RunContext::assertionEnded(AssertionResult const & result) {
  8407. if (result.getResultType() == ResultWas::Ok) {
  8408. m_totals.assertions.passed++;
  8409. m_lastAssertionPassed = true;
  8410. } else if (!result.isOk()) {
  8411. m_lastAssertionPassed = false;
  8412. if( m_activeTestCase->getTestCaseInfo().okToFail() )
  8413. m_totals.assertions.failedButOk++;
  8414. else
  8415. m_totals.assertions.failed++;
  8416. }
  8417. else {
  8418. m_lastAssertionPassed = true;
  8419. }
  8420. // We have no use for the return value (whether messages should be cleared), because messages were made scoped
  8421. // and should be let to clear themselves out.
  8422. static_cast<void>(m_reporter->assertionEnded(AssertionStats(result, m_messages, m_totals)));
  8423. if (result.getResultType() != ResultWas::Warning)
  8424. m_messageScopes.clear();
  8425. // Reset working state
  8426. resetAssertionInfo();
  8427. m_lastResult = result;
  8428. }
  8429. void RunContext::resetAssertionInfo() {
  8430. m_lastAssertionInfo.macroName = StringRef();
  8431. m_lastAssertionInfo.capturedExpression = "{Unknown expression after the reported line}"_sr;
  8432. }
  8433. bool RunContext::sectionStarted(SectionInfo const & sectionInfo, Counts & assertions) {
  8434. ITracker& sectionTracker = SectionTracker::acquire(m_trackerContext, TestCaseTracking::NameAndLocation(sectionInfo.name, sectionInfo.lineInfo));
  8435. if (!sectionTracker.isOpen())
  8436. return false;
  8437. m_activeSections.push_back(&sectionTracker);
  8438. m_lastAssertionInfo.lineInfo = sectionInfo.lineInfo;
  8439. m_reporter->sectionStarting(sectionInfo);
  8440. assertions = m_totals.assertions;
  8441. return true;
  8442. }
  8443. auto RunContext::acquireGeneratorTracker( SourceLineInfo const& lineInfo ) -> IGeneratorTracker& {
  8444. using namespace Generators;
  8445. GeneratorTracker& tracker = GeneratorTracker::acquire( m_trackerContext, TestCaseTracking::NameAndLocation( "generator", lineInfo ) );
  8446. assert( tracker.isOpen() );
  8447. m_lastAssertionInfo.lineInfo = lineInfo;
  8448. return tracker;
  8449. }
  8450. bool RunContext::testForMissingAssertions(Counts& assertions) {
  8451. if (assertions.total() != 0)
  8452. return false;
  8453. if (!m_config->warnAboutMissingAssertions())
  8454. return false;
  8455. if (m_trackerContext.currentTracker().hasChildren())
  8456. return false;
  8457. m_totals.assertions.failed++;
  8458. assertions.failed++;
  8459. return true;
  8460. }
  8461. void RunContext::sectionEnded(SectionEndInfo const & endInfo) {
  8462. Counts assertions = m_totals.assertions - endInfo.prevAssertions;
  8463. bool missingAssertions = testForMissingAssertions(assertions);
  8464. if (!m_activeSections.empty()) {
  8465. m_activeSections.back()->close();
  8466. m_activeSections.pop_back();
  8467. }
  8468. m_reporter->sectionEnded(SectionStats(endInfo.sectionInfo, assertions, endInfo.durationInSeconds, missingAssertions));
  8469. m_messages.clear();
  8470. m_messageScopes.clear();
  8471. }
  8472. void RunContext::sectionEndedEarly(SectionEndInfo const & endInfo) {
  8473. if (m_unfinishedSections.empty())
  8474. m_activeSections.back()->fail();
  8475. else
  8476. m_activeSections.back()->close();
  8477. m_activeSections.pop_back();
  8478. m_unfinishedSections.push_back(endInfo);
  8479. }
  8480. void RunContext::benchmarkStarting( BenchmarkInfo const& info ) {
  8481. m_reporter->benchmarkStarting( info );
  8482. }
  8483. void RunContext::benchmarkEnded( BenchmarkStats const& stats ) {
  8484. m_reporter->benchmarkEnded( stats );
  8485. }
  8486. void RunContext::pushScopedMessage(MessageInfo const & message) {
  8487. m_messages.push_back(message);
  8488. }
  8489. void RunContext::popScopedMessage(MessageInfo const & message) {
  8490. m_messages.erase(std::remove(m_messages.begin(), m_messages.end(), message), m_messages.end());
  8491. }
  8492. void RunContext::emplaceUnscopedMessage( MessageBuilder const& builder ) {
  8493. m_messageScopes.emplace_back( builder );
  8494. }
  8495. std::string RunContext::getCurrentTestName() const {
  8496. return m_activeTestCase
  8497. ? m_activeTestCase->getTestCaseInfo().name
  8498. : std::string();
  8499. }
  8500. const AssertionResult * RunContext::getLastResult() const {
  8501. return &(*m_lastResult);
  8502. }
  8503. void RunContext::exceptionEarlyReported() {
  8504. m_shouldReportUnexpected = false;
  8505. }
  8506. void RunContext::handleFatalErrorCondition( StringRef message ) {
  8507. // First notify reporter that bad things happened
  8508. m_reporter->fatalErrorEncountered(message);
  8509. // Don't rebuild the result -- the stringification itself can cause more fatal errors
  8510. // Instead, fake a result data.
  8511. AssertionResultData tempResult( ResultWas::FatalErrorCondition, { false } );
  8512. tempResult.message = message;
  8513. AssertionResult result(m_lastAssertionInfo, tempResult);
  8514. assertionEnded(result);
  8515. handleUnfinishedSections();
  8516. // Recreate section for test case (as we will lose the one that was in scope)
  8517. auto const& testCaseInfo = m_activeTestCase->getTestCaseInfo();
  8518. SectionInfo testCaseSection(testCaseInfo.lineInfo, testCaseInfo.name);
  8519. Counts assertions;
  8520. assertions.failed = 1;
  8521. SectionStats testCaseSectionStats(testCaseSection, assertions, 0, false);
  8522. m_reporter->sectionEnded(testCaseSectionStats);
  8523. auto const& testInfo = m_activeTestCase->getTestCaseInfo();
  8524. Totals deltaTotals;
  8525. deltaTotals.testCases.failed = 1;
  8526. deltaTotals.assertions.failed = 1;
  8527. m_reporter->testCaseEnded(TestCaseStats(testInfo,
  8528. deltaTotals,
  8529. std::string(),
  8530. std::string(),
  8531. false));
  8532. m_totals.testCases.failed++;
  8533. testGroupEnded(std::string(), m_totals, 1, 1);
  8534. m_reporter->testRunEnded(TestRunStats(m_runInfo, m_totals, false));
  8535. }
  8536. bool RunContext::lastAssertionPassed() {
  8537. return m_lastAssertionPassed;
  8538. }
  8539. void RunContext::assertionPassed() {
  8540. m_lastAssertionPassed = true;
  8541. ++m_totals.assertions.passed;
  8542. resetAssertionInfo();
  8543. m_messageScopes.clear();
  8544. }
  8545. bool RunContext::aborting() const {
  8546. return m_totals.assertions.failed >= static_cast<std::size_t>(m_config->abortAfter());
  8547. }
  8548. void RunContext::runCurrentTest(std::string & redirectedCout, std::string & redirectedCerr) {
  8549. auto const& testCaseInfo = m_activeTestCase->getTestCaseInfo();
  8550. SectionInfo testCaseSection(testCaseInfo.lineInfo, testCaseInfo.name);
  8551. m_reporter->sectionStarting(testCaseSection);
  8552. Counts prevAssertions = m_totals.assertions;
  8553. double duration = 0;
  8554. m_shouldReportUnexpected = true;
  8555. m_lastAssertionInfo = { "TEST_CASE"_sr, testCaseInfo.lineInfo, StringRef(), ResultDisposition::Normal };
  8556. seedRng(*m_config);
  8557. Timer timer;
  8558. CATCH_TRY {
  8559. if (m_reporter->getPreferences().shouldRedirectStdOut) {
  8560. #if !defined(CATCH_CONFIG_EXPERIMENTAL_REDIRECT)
  8561. RedirectedStreams redirectedStreams(redirectedCout, redirectedCerr);
  8562. timer.start();
  8563. invokeActiveTestCase();
  8564. #else
  8565. OutputRedirect r(redirectedCout, redirectedCerr);
  8566. timer.start();
  8567. invokeActiveTestCase();
  8568. #endif
  8569. } else {
  8570. timer.start();
  8571. invokeActiveTestCase();
  8572. }
  8573. duration = timer.getElapsedSeconds();
  8574. } CATCH_CATCH_ANON (TestFailureException&) {
  8575. // This just means the test was aborted due to failure
  8576. } CATCH_CATCH_ALL {
  8577. // Under CATCH_CONFIG_FAST_COMPILE, unexpected exceptions under REQUIRE assertions
  8578. // are reported without translation at the point of origin.
  8579. if( m_shouldReportUnexpected ) {
  8580. AssertionReaction dummyReaction;
  8581. handleUnexpectedInflightException( m_lastAssertionInfo, translateActiveException(), dummyReaction );
  8582. }
  8583. }
  8584. Counts assertions = m_totals.assertions - prevAssertions;
  8585. bool missingAssertions = testForMissingAssertions(assertions);
  8586. m_testCaseTracker->close();
  8587. handleUnfinishedSections();
  8588. m_messages.clear();
  8589. m_messageScopes.clear();
  8590. SectionStats testCaseSectionStats(testCaseSection, assertions, duration, missingAssertions);
  8591. m_reporter->sectionEnded(testCaseSectionStats);
  8592. }
  8593. void RunContext::invokeActiveTestCase() {
  8594. FatalConditionHandler fatalConditionHandler; // Handle signals
  8595. m_activeTestCase->invoke();
  8596. fatalConditionHandler.reset();
  8597. }
  8598. void RunContext::handleUnfinishedSections() {
  8599. // If sections ended prematurely due to an exception we stored their
  8600. // infos here so we can tear them down outside the unwind process.
  8601. for (auto it = m_unfinishedSections.rbegin(),
  8602. itEnd = m_unfinishedSections.rend();
  8603. it != itEnd;
  8604. ++it)
  8605. sectionEnded(*it);
  8606. m_unfinishedSections.clear();
  8607. }
  8608. void RunContext::handleExpr(
  8609. AssertionInfo const& info,
  8610. ITransientExpression const& expr,
  8611. AssertionReaction& reaction
  8612. ) {
  8613. m_reporter->assertionStarting( info );
  8614. bool negated = isFalseTest( info.resultDisposition );
  8615. bool result = expr.getResult() != negated;
  8616. if( result ) {
  8617. if (!m_includeSuccessfulResults) {
  8618. assertionPassed();
  8619. }
  8620. else {
  8621. reportExpr(info, ResultWas::Ok, &expr, negated);
  8622. }
  8623. }
  8624. else {
  8625. reportExpr(info, ResultWas::ExpressionFailed, &expr, negated );
  8626. populateReaction( reaction );
  8627. }
  8628. }
  8629. void RunContext::reportExpr(
  8630. AssertionInfo const &info,
  8631. ResultWas::OfType resultType,
  8632. ITransientExpression const *expr,
  8633. bool negated ) {
  8634. m_lastAssertionInfo = info;
  8635. AssertionResultData data( resultType, LazyExpression( negated ) );
  8636. AssertionResult assertionResult{ info, data };
  8637. assertionResult.m_resultData.lazyExpression.m_transientExpression = expr;
  8638. assertionEnded( assertionResult );
  8639. }
  8640. void RunContext::handleMessage(
  8641. AssertionInfo const& info,
  8642. ResultWas::OfType resultType,
  8643. StringRef const& message,
  8644. AssertionReaction& reaction
  8645. ) {
  8646. m_reporter->assertionStarting( info );
  8647. m_lastAssertionInfo = info;
  8648. AssertionResultData data( resultType, LazyExpression( false ) );
  8649. data.message = message;
  8650. AssertionResult assertionResult{ m_lastAssertionInfo, data };
  8651. assertionEnded( assertionResult );
  8652. if( !assertionResult.isOk() )
  8653. populateReaction( reaction );
  8654. }
  8655. void RunContext::handleUnexpectedExceptionNotThrown(
  8656. AssertionInfo const& info,
  8657. AssertionReaction& reaction
  8658. ) {
  8659. handleNonExpr(info, Catch::ResultWas::DidntThrowException, reaction);
  8660. }
  8661. void RunContext::handleUnexpectedInflightException(
  8662. AssertionInfo const& info,
  8663. std::string const& message,
  8664. AssertionReaction& reaction
  8665. ) {
  8666. m_lastAssertionInfo = info;
  8667. AssertionResultData data( ResultWas::ThrewException, LazyExpression( false ) );
  8668. data.message = message;
  8669. AssertionResult assertionResult{ info, data };
  8670. assertionEnded( assertionResult );
  8671. populateReaction( reaction );
  8672. }
  8673. void RunContext::populateReaction( AssertionReaction& reaction ) {
  8674. reaction.shouldDebugBreak = m_config->shouldDebugBreak();
  8675. reaction.shouldThrow = aborting() || (m_lastAssertionInfo.resultDisposition & ResultDisposition::Normal);
  8676. }
  8677. void RunContext::handleIncomplete(
  8678. AssertionInfo const& info
  8679. ) {
  8680. m_lastAssertionInfo = info;
  8681. AssertionResultData data( ResultWas::ThrewException, LazyExpression( false ) );
  8682. data.message = "Exception translation was disabled by CATCH_CONFIG_FAST_COMPILE";
  8683. AssertionResult assertionResult{ info, data };
  8684. assertionEnded( assertionResult );
  8685. }
  8686. void RunContext::handleNonExpr(
  8687. AssertionInfo const &info,
  8688. ResultWas::OfType resultType,
  8689. AssertionReaction &reaction
  8690. ) {
  8691. m_lastAssertionInfo = info;
  8692. AssertionResultData data( resultType, LazyExpression( false ) );
  8693. AssertionResult assertionResult{ info, data };
  8694. assertionEnded( assertionResult );
  8695. if( !assertionResult.isOk() )
  8696. populateReaction( reaction );
  8697. }
  8698. IResultCapture& getResultCapture() {
  8699. if (auto* capture = getCurrentContext().getResultCapture())
  8700. return *capture;
  8701. else
  8702. CATCH_INTERNAL_ERROR("No result capture instance");
  8703. }
  8704. }
  8705. // end catch_run_context.cpp
  8706. // start catch_section.cpp
  8707. namespace Catch {
  8708. Section::Section( SectionInfo const& info )
  8709. : m_info( info ),
  8710. m_sectionIncluded( getResultCapture().sectionStarted( m_info, m_assertions ) )
  8711. {
  8712. m_timer.start();
  8713. }
  8714. Section::~Section() {
  8715. if( m_sectionIncluded ) {
  8716. SectionEndInfo endInfo{ m_info, m_assertions, m_timer.getElapsedSeconds() };
  8717. if( uncaught_exceptions() )
  8718. getResultCapture().sectionEndedEarly( endInfo );
  8719. else
  8720. getResultCapture().sectionEnded( endInfo );
  8721. }
  8722. }
  8723. // This indicates whether the section should be executed or not
  8724. Section::operator bool() const {
  8725. return m_sectionIncluded;
  8726. }
  8727. } // end namespace Catch
  8728. // end catch_section.cpp
  8729. // start catch_section_info.cpp
  8730. namespace Catch {
  8731. SectionInfo::SectionInfo
  8732. ( SourceLineInfo const& _lineInfo,
  8733. std::string const& _name )
  8734. : name( _name ),
  8735. lineInfo( _lineInfo )
  8736. {}
  8737. } // end namespace Catch
  8738. // end catch_section_info.cpp
  8739. // start catch_session.cpp
  8740. // start catch_session.h
  8741. #include <memory>
  8742. namespace Catch {
  8743. class Session : NonCopyable {
  8744. public:
  8745. Session();
  8746. ~Session() override;
  8747. void showHelp() const;
  8748. void libIdentify();
  8749. int applyCommandLine( int argc, char const * const * argv );
  8750. #if defined(CATCH_CONFIG_WCHAR) && defined(WIN32) && defined(UNICODE)
  8751. int applyCommandLine( int argc, wchar_t const * const * argv );
  8752. #endif
  8753. void useConfigData( ConfigData const& configData );
  8754. template<typename CharT>
  8755. int run(int argc, CharT const * const argv[]) {
  8756. if (m_startupExceptions)
  8757. return 1;
  8758. int returnCode = applyCommandLine(argc, argv);
  8759. if (returnCode == 0)
  8760. returnCode = run();
  8761. return returnCode;
  8762. }
  8763. int run();
  8764. clara::Parser const& cli() const;
  8765. void cli( clara::Parser const& newParser );
  8766. ConfigData& configData();
  8767. Config& config();
  8768. private:
  8769. int runInternal();
  8770. clara::Parser m_cli;
  8771. ConfigData m_configData;
  8772. std::shared_ptr<Config> m_config;
  8773. bool m_startupExceptions = false;
  8774. };
  8775. } // end namespace Catch
  8776. // end catch_session.h
  8777. // start catch_version.h
  8778. #include <iosfwd>
  8779. namespace Catch {
  8780. // Versioning information
  8781. struct Version {
  8782. Version( Version const& ) = delete;
  8783. Version& operator=( Version const& ) = delete;
  8784. Version( unsigned int _majorVersion,
  8785. unsigned int _minorVersion,
  8786. unsigned int _patchNumber,
  8787. char const * const _branchName,
  8788. unsigned int _buildNumber );
  8789. unsigned int const majorVersion;
  8790. unsigned int const minorVersion;
  8791. unsigned int const patchNumber;
  8792. // buildNumber is only used if branchName is not null
  8793. char const * const branchName;
  8794. unsigned int const buildNumber;
  8795. friend std::ostream& operator << ( std::ostream& os, Version const& version );
  8796. };
  8797. Version const& libraryVersion();
  8798. }
  8799. // end catch_version.h
  8800. #include <cstdlib>
  8801. #include <iomanip>
  8802. namespace Catch {
  8803. namespace {
  8804. const int MaxExitCode = 255;
  8805. IStreamingReporterPtr createReporter(std::string const& reporterName, IConfigPtr const& config) {
  8806. auto reporter = Catch::getRegistryHub().getReporterRegistry().create(reporterName, config);
  8807. CATCH_ENFORCE(reporter, "No reporter registered with name: '" << reporterName << "'");
  8808. return reporter;
  8809. }
  8810. IStreamingReporterPtr makeReporter(std::shared_ptr<Config> const& config) {
  8811. if (Catch::getRegistryHub().getReporterRegistry().getListeners().empty()) {
  8812. return createReporter(config->getReporterName(), config);
  8813. }
  8814. // On older platforms, returning std::unique_ptr<ListeningReporter>
  8815. // when the return type is std::unique_ptr<IStreamingReporter>
  8816. // doesn't compile without a std::move call. However, this causes
  8817. // a warning on newer platforms. Thus, we have to work around
  8818. // it a bit and downcast the pointer manually.
  8819. auto ret = std::unique_ptr<IStreamingReporter>(new ListeningReporter);
  8820. auto& multi = static_cast<ListeningReporter&>(*ret);
  8821. auto const& listeners = Catch::getRegistryHub().getReporterRegistry().getListeners();
  8822. for (auto const& listener : listeners) {
  8823. multi.addListener(listener->create(Catch::ReporterConfig(config)));
  8824. }
  8825. multi.addReporter(createReporter(config->getReporterName(), config));
  8826. return ret;
  8827. }
  8828. Catch::Totals runTests(std::shared_ptr<Config> const& config) {
  8829. auto reporter = makeReporter(config);
  8830. RunContext context(config, std::move(reporter));
  8831. Totals totals;
  8832. context.testGroupStarting(config->name(), 1, 1);
  8833. TestSpec testSpec = config->testSpec();
  8834. auto const& allTestCases = getAllTestCasesSorted(*config);
  8835. for (auto const& testCase : allTestCases) {
  8836. bool matching = (!testSpec.hasFilters() && !testCase.isHidden()) ||
  8837. (testSpec.hasFilters() && matchTest(testCase, testSpec, *config));
  8838. if (!context.aborting() && matching)
  8839. totals += context.runTest(testCase);
  8840. else
  8841. context.reporter().skipTest(testCase);
  8842. }
  8843. if (config->warnAboutNoTests() && totals.testCases.total() == 0) {
  8844. ReusableStringStream testConfig;
  8845. bool first = true;
  8846. for (const auto& input : config->getTestsOrTags()) {
  8847. if (!first) { testConfig << ' '; }
  8848. first = false;
  8849. testConfig << input;
  8850. }
  8851. context.reporter().noMatchingTestCases(testConfig.str());
  8852. totals.error = -1;
  8853. }
  8854. context.testGroupEnded(config->name(), totals, 1, 1);
  8855. return totals;
  8856. }
  8857. void applyFilenamesAsTags(Catch::IConfig const& config) {
  8858. auto& tests = const_cast<std::vector<TestCase>&>(getAllTestCasesSorted(config));
  8859. for (auto& testCase : tests) {
  8860. auto tags = testCase.tags;
  8861. std::string filename = testCase.lineInfo.file;
  8862. auto lastSlash = filename.find_last_of("\\/");
  8863. if (lastSlash != std::string::npos) {
  8864. filename.erase(0, lastSlash);
  8865. filename[0] = '#';
  8866. }
  8867. auto lastDot = filename.find_last_of('.');
  8868. if (lastDot != std::string::npos) {
  8869. filename.erase(lastDot);
  8870. }
  8871. tags.push_back(std::move(filename));
  8872. setTags(testCase, tags);
  8873. }
  8874. }
  8875. } // anon namespace
  8876. Session::Session() {
  8877. static bool alreadyInstantiated = false;
  8878. if( alreadyInstantiated ) {
  8879. CATCH_TRY { CATCH_INTERNAL_ERROR( "Only one instance of Catch::Session can ever be used" ); }
  8880. CATCH_CATCH_ALL { getMutableRegistryHub().registerStartupException(); }
  8881. }
  8882. // There cannot be exceptions at startup in no-exception mode.
  8883. #if !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
  8884. const auto& exceptions = getRegistryHub().getStartupExceptionRegistry().getExceptions();
  8885. if ( !exceptions.empty() ) {
  8886. m_startupExceptions = true;
  8887. Colour colourGuard( Colour::Red );
  8888. Catch::cerr() << "Errors occurred during startup!" << '\n';
  8889. // iterate over all exceptions and notify user
  8890. for ( const auto& ex_ptr : exceptions ) {
  8891. try {
  8892. std::rethrow_exception(ex_ptr);
  8893. } catch ( std::exception const& ex ) {
  8894. Catch::cerr() << Column( ex.what() ).indent(2) << '\n';
  8895. }
  8896. }
  8897. }
  8898. #endif
  8899. alreadyInstantiated = true;
  8900. m_cli = makeCommandLineParser( m_configData );
  8901. }
  8902. Session::~Session() {
  8903. Catch::cleanUp();
  8904. }
  8905. void Session::showHelp() const {
  8906. Catch::cout()
  8907. << "\nCatch v" << libraryVersion() << "\n"
  8908. << m_cli << std::endl
  8909. << "For more detailed usage please see the project docs\n" << std::endl;
  8910. }
  8911. void Session::libIdentify() {
  8912. Catch::cout()
  8913. << std::left << std::setw(16) << "description: " << "A Catch test executable\n"
  8914. << std::left << std::setw(16) << "category: " << "testframework\n"
  8915. << std::left << std::setw(16) << "framework: " << "Catch Test\n"
  8916. << std::left << std::setw(16) << "version: " << libraryVersion() << std::endl;
  8917. }
  8918. int Session::applyCommandLine( int argc, char const * const * argv ) {
  8919. if( m_startupExceptions )
  8920. return 1;
  8921. auto result = m_cli.parse( clara::Args( argc, argv ) );
  8922. if( !result ) {
  8923. config();
  8924. getCurrentMutableContext().setConfig(m_config);
  8925. Catch::cerr()
  8926. << Colour( Colour::Red )
  8927. << "\nError(s) in input:\n"
  8928. << Column( result.errorMessage() ).indent( 2 )
  8929. << "\n\n";
  8930. Catch::cerr() << "Run with -? for usage\n" << std::endl;
  8931. return MaxExitCode;
  8932. }
  8933. if( m_configData.showHelp )
  8934. showHelp();
  8935. if( m_configData.libIdentify )
  8936. libIdentify();
  8937. m_config.reset();
  8938. return 0;
  8939. }
  8940. #if defined(CATCH_CONFIG_WCHAR) && defined(WIN32) && defined(UNICODE)
  8941. int Session::applyCommandLine( int argc, wchar_t const * const * argv ) {
  8942. char **utf8Argv = new char *[ argc ];
  8943. for ( int i = 0; i < argc; ++i ) {
  8944. int bufSize = WideCharToMultiByte( CP_UTF8, 0, argv[i], -1, NULL, 0, NULL, NULL );
  8945. utf8Argv[ i ] = new char[ bufSize ];
  8946. WideCharToMultiByte( CP_UTF8, 0, argv[i], -1, utf8Argv[i], bufSize, NULL, NULL );
  8947. }
  8948. int returnCode = applyCommandLine( argc, utf8Argv );
  8949. for ( int i = 0; i < argc; ++i )
  8950. delete [] utf8Argv[ i ];
  8951. delete [] utf8Argv;
  8952. return returnCode;
  8953. }
  8954. #endif
  8955. void Session::useConfigData( ConfigData const& configData ) {
  8956. m_configData = configData;
  8957. m_config.reset();
  8958. }
  8959. int Session::run() {
  8960. if( ( m_configData.waitForKeypress & WaitForKeypress::BeforeStart ) != 0 ) {
  8961. Catch::cout() << "...waiting for enter/ return before starting" << std::endl;
  8962. static_cast<void>(std::getchar());
  8963. }
  8964. int exitCode = runInternal();
  8965. if( ( m_configData.waitForKeypress & WaitForKeypress::BeforeExit ) != 0 ) {
  8966. Catch::cout() << "...waiting for enter/ return before exiting, with code: " << exitCode << std::endl;
  8967. static_cast<void>(std::getchar());
  8968. }
  8969. return exitCode;
  8970. }
  8971. clara::Parser const& Session::cli() const {
  8972. return m_cli;
  8973. }
  8974. void Session::cli( clara::Parser const& newParser ) {
  8975. m_cli = newParser;
  8976. }
  8977. ConfigData& Session::configData() {
  8978. return m_configData;
  8979. }
  8980. Config& Session::config() {
  8981. if( !m_config )
  8982. m_config = std::make_shared<Config>( m_configData );
  8983. return *m_config;
  8984. }
  8985. int Session::runInternal() {
  8986. if( m_startupExceptions )
  8987. return 1;
  8988. if (m_configData.showHelp || m_configData.libIdentify) {
  8989. return 0;
  8990. }
  8991. CATCH_TRY {
  8992. config(); // Force config to be constructed
  8993. seedRng( *m_config );
  8994. if( m_configData.filenamesAsTags )
  8995. applyFilenamesAsTags( *m_config );
  8996. // Handle list request
  8997. if( Option<std::size_t> listed = list( m_config ) )
  8998. return static_cast<int>( *listed );
  8999. auto totals = runTests( m_config );
  9000. // Note that on unices only the lower 8 bits are usually used, clamping
  9001. // the return value to 255 prevents false negative when some multiple
  9002. // of 256 tests has failed
  9003. return (std::min) (MaxExitCode, (std::max) (totals.error, static_cast<int>(totals.assertions.failed)));
  9004. }
  9005. #if !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
  9006. catch( std::exception& ex ) {
  9007. Catch::cerr() << ex.what() << std::endl;
  9008. return MaxExitCode;
  9009. }
  9010. #endif
  9011. }
  9012. } // end namespace Catch
  9013. // end catch_session.cpp
  9014. // start catch_singletons.cpp
  9015. #include <vector>
  9016. namespace Catch {
  9017. namespace {
  9018. static auto getSingletons() -> std::vector<ISingleton*>*& {
  9019. static std::vector<ISingleton*>* g_singletons = nullptr;
  9020. if( !g_singletons )
  9021. g_singletons = new std::vector<ISingleton*>();
  9022. return g_singletons;
  9023. }
  9024. }
  9025. ISingleton::~ISingleton() {}
  9026. void addSingleton(ISingleton* singleton ) {
  9027. getSingletons()->push_back( singleton );
  9028. }
  9029. void cleanupSingletons() {
  9030. auto& singletons = getSingletons();
  9031. for( auto singleton : *singletons )
  9032. delete singleton;
  9033. delete singletons;
  9034. singletons = nullptr;
  9035. }
  9036. } // namespace Catch
  9037. // end catch_singletons.cpp
  9038. // start catch_startup_exception_registry.cpp
  9039. namespace Catch {
  9040. void StartupExceptionRegistry::add( std::exception_ptr const& exception ) noexcept {
  9041. CATCH_TRY {
  9042. m_exceptions.push_back(exception);
  9043. } CATCH_CATCH_ALL {
  9044. // If we run out of memory during start-up there's really not a lot more we can do about it
  9045. std::terminate();
  9046. }
  9047. }
  9048. std::vector<std::exception_ptr> const& StartupExceptionRegistry::getExceptions() const noexcept {
  9049. return m_exceptions;
  9050. }
  9051. } // end namespace Catch
  9052. // end catch_startup_exception_registry.cpp
  9053. // start catch_stream.cpp
  9054. #include <cstdio>
  9055. #include <iostream>
  9056. #include <fstream>
  9057. #include <sstream>
  9058. #include <vector>
  9059. #include <memory>
  9060. namespace Catch {
  9061. Catch::IStream::~IStream() = default;
  9062. namespace detail { namespace {
  9063. template<typename WriterF, std::size_t bufferSize=256>
  9064. class StreamBufImpl : public std::streambuf {
  9065. char data[bufferSize];
  9066. WriterF m_writer;
  9067. public:
  9068. StreamBufImpl() {
  9069. setp( data, data + sizeof(data) );
  9070. }
  9071. ~StreamBufImpl() noexcept {
  9072. StreamBufImpl::sync();
  9073. }
  9074. private:
  9075. int overflow( int c ) override {
  9076. sync();
  9077. if( c != EOF ) {
  9078. if( pbase() == epptr() )
  9079. m_writer( std::string( 1, static_cast<char>( c ) ) );
  9080. else
  9081. sputc( static_cast<char>( c ) );
  9082. }
  9083. return 0;
  9084. }
  9085. int sync() override {
  9086. if( pbase() != pptr() ) {
  9087. m_writer( std::string( pbase(), static_cast<std::string::size_type>( pptr() - pbase() ) ) );
  9088. setp( pbase(), epptr() );
  9089. }
  9090. return 0;
  9091. }
  9092. };
  9093. ///////////////////////////////////////////////////////////////////////////
  9094. struct OutputDebugWriter {
  9095. void operator()( std::string const&str ) {
  9096. writeToDebugConsole( str );
  9097. }
  9098. };
  9099. ///////////////////////////////////////////////////////////////////////////
  9100. class FileStream : public IStream {
  9101. mutable std::ofstream m_ofs;
  9102. public:
  9103. FileStream( StringRef filename ) {
  9104. m_ofs.open( filename.c_str() );
  9105. CATCH_ENFORCE( !m_ofs.fail(), "Unable to open file: '" << filename << "'" );
  9106. }
  9107. ~FileStream() override = default;
  9108. public: // IStream
  9109. std::ostream& stream() const override {
  9110. return m_ofs;
  9111. }
  9112. };
  9113. ///////////////////////////////////////////////////////////////////////////
  9114. class CoutStream : public IStream {
  9115. mutable std::ostream m_os;
  9116. public:
  9117. // Store the streambuf from cout up-front because
  9118. // cout may get redirected when running tests
  9119. CoutStream() : m_os( Catch::cout().rdbuf() ) {}
  9120. ~CoutStream() override = default;
  9121. public: // IStream
  9122. std::ostream& stream() const override { return m_os; }
  9123. };
  9124. ///////////////////////////////////////////////////////////////////////////
  9125. class DebugOutStream : public IStream {
  9126. std::unique_ptr<StreamBufImpl<OutputDebugWriter>> m_streamBuf;
  9127. mutable std::ostream m_os;
  9128. public:
  9129. DebugOutStream()
  9130. : m_streamBuf( new StreamBufImpl<OutputDebugWriter>() ),
  9131. m_os( m_streamBuf.get() )
  9132. {}
  9133. ~DebugOutStream() override = default;
  9134. public: // IStream
  9135. std::ostream& stream() const override { return m_os; }
  9136. };
  9137. }} // namespace anon::detail
  9138. ///////////////////////////////////////////////////////////////////////////
  9139. auto makeStream( StringRef const &filename ) -> IStream const* {
  9140. if( filename.empty() )
  9141. return new detail::CoutStream();
  9142. else if( filename[0] == '%' ) {
  9143. if( filename == "%debug" )
  9144. return new detail::DebugOutStream();
  9145. else
  9146. CATCH_ERROR( "Unrecognised stream: '" << filename << "'" );
  9147. }
  9148. else
  9149. return new detail::FileStream( filename );
  9150. }
  9151. // This class encapsulates the idea of a pool of ostringstreams that can be reused.
  9152. struct StringStreams {
  9153. std::vector<std::unique_ptr<std::ostringstream>> m_streams;
  9154. std::vector<std::size_t> m_unused;
  9155. std::ostringstream m_referenceStream; // Used for copy state/ flags from
  9156. auto add() -> std::size_t {
  9157. if( m_unused.empty() ) {
  9158. m_streams.push_back( std::unique_ptr<std::ostringstream>( new std::ostringstream ) );
  9159. return m_streams.size()-1;
  9160. }
  9161. else {
  9162. auto index = m_unused.back();
  9163. m_unused.pop_back();
  9164. return index;
  9165. }
  9166. }
  9167. void release( std::size_t index ) {
  9168. m_streams[index]->copyfmt( m_referenceStream ); // Restore initial flags and other state
  9169. m_unused.push_back(index);
  9170. }
  9171. };
  9172. ReusableStringStream::ReusableStringStream()
  9173. : m_index( Singleton<StringStreams>::getMutable().add() ),
  9174. m_oss( Singleton<StringStreams>::getMutable().m_streams[m_index].get() )
  9175. {}
  9176. ReusableStringStream::~ReusableStringStream() {
  9177. static_cast<std::ostringstream*>( m_oss )->str("");
  9178. m_oss->clear();
  9179. Singleton<StringStreams>::getMutable().release( m_index );
  9180. }
  9181. auto ReusableStringStream::str() const -> std::string {
  9182. return static_cast<std::ostringstream*>( m_oss )->str();
  9183. }
  9184. ///////////////////////////////////////////////////////////////////////////
  9185. #ifndef CATCH_CONFIG_NOSTDOUT // If you #define this you must implement these functions
  9186. std::ostream& cout() { return std::cout; }
  9187. std::ostream& cerr() { return std::cerr; }
  9188. std::ostream& clog() { return std::clog; }
  9189. #endif
  9190. }
  9191. // end catch_stream.cpp
  9192. // start catch_string_manip.cpp
  9193. #include <algorithm>
  9194. #include <ostream>
  9195. #include <cstring>
  9196. #include <cctype>
  9197. namespace Catch {
  9198. namespace {
  9199. char toLowerCh(char c) {
  9200. return static_cast<char>( std::tolower( c ) );
  9201. }
  9202. }
  9203. bool startsWith( std::string const& s, std::string const& prefix ) {
  9204. return s.size() >= prefix.size() && std::equal(prefix.begin(), prefix.end(), s.begin());
  9205. }
  9206. bool startsWith( std::string const& s, char prefix ) {
  9207. return !s.empty() && s[0] == prefix;
  9208. }
  9209. bool endsWith( std::string const& s, std::string const& suffix ) {
  9210. return s.size() >= suffix.size() && std::equal(suffix.rbegin(), suffix.rend(), s.rbegin());
  9211. }
  9212. bool endsWith( std::string const& s, char suffix ) {
  9213. return !s.empty() && s[s.size()-1] == suffix;
  9214. }
  9215. bool contains( std::string const& s, std::string const& infix ) {
  9216. return s.find( infix ) != std::string::npos;
  9217. }
  9218. void toLowerInPlace( std::string& s ) {
  9219. std::transform( s.begin(), s.end(), s.begin(), toLowerCh );
  9220. }
  9221. std::string toLower( std::string const& s ) {
  9222. std::string lc = s;
  9223. toLowerInPlace( lc );
  9224. return lc;
  9225. }
  9226. std::string trim( std::string const& str ) {
  9227. static char const* whitespaceChars = "\n\r\t ";
  9228. std::string::size_type start = str.find_first_not_of( whitespaceChars );
  9229. std::string::size_type end = str.find_last_not_of( whitespaceChars );
  9230. return start != std::string::npos ? str.substr( start, 1+end-start ) : std::string();
  9231. }
  9232. bool replaceInPlace( std::string& str, std::string const& replaceThis, std::string const& withThis ) {
  9233. bool replaced = false;
  9234. std::size_t i = str.find( replaceThis );
  9235. while( i != std::string::npos ) {
  9236. replaced = true;
  9237. str = str.substr( 0, i ) + withThis + str.substr( i+replaceThis.size() );
  9238. if( i < str.size()-withThis.size() )
  9239. i = str.find( replaceThis, i+withThis.size() );
  9240. else
  9241. i = std::string::npos;
  9242. }
  9243. return replaced;
  9244. }
  9245. pluralise::pluralise( std::size_t count, std::string const& label )
  9246. : m_count( count ),
  9247. m_label( label )
  9248. {}
  9249. std::ostream& operator << ( std::ostream& os, pluralise const& pluraliser ) {
  9250. os << pluraliser.m_count << ' ' << pluraliser.m_label;
  9251. if( pluraliser.m_count != 1 )
  9252. os << 's';
  9253. return os;
  9254. }
  9255. }
  9256. // end catch_string_manip.cpp
  9257. // start catch_stringref.cpp
  9258. #if defined(__clang__)
  9259. # pragma clang diagnostic push
  9260. # pragma clang diagnostic ignored "-Wexit-time-destructors"
  9261. #endif
  9262. #include <ostream>
  9263. #include <cstring>
  9264. #include <cstdint>
  9265. namespace {
  9266. const uint32_t byte_2_lead = 0xC0;
  9267. const uint32_t byte_3_lead = 0xE0;
  9268. const uint32_t byte_4_lead = 0xF0;
  9269. }
  9270. namespace Catch {
  9271. StringRef::StringRef( char const* rawChars ) noexcept
  9272. : StringRef( rawChars, static_cast<StringRef::size_type>(std::strlen(rawChars) ) )
  9273. {}
  9274. StringRef::operator std::string() const {
  9275. return std::string( m_start, m_size );
  9276. }
  9277. void StringRef::swap( StringRef& other ) noexcept {
  9278. std::swap( m_start, other.m_start );
  9279. std::swap( m_size, other.m_size );
  9280. std::swap( m_data, other.m_data );
  9281. }
  9282. auto StringRef::c_str() const -> char const* {
  9283. if( isSubstring() )
  9284. const_cast<StringRef*>( this )->takeOwnership();
  9285. return m_start;
  9286. }
  9287. auto StringRef::currentData() const noexcept -> char const* {
  9288. return m_start;
  9289. }
  9290. auto StringRef::isOwned() const noexcept -> bool {
  9291. return m_data != nullptr;
  9292. }
  9293. auto StringRef::isSubstring() const noexcept -> bool {
  9294. return m_start[m_size] != '\0';
  9295. }
  9296. void StringRef::takeOwnership() {
  9297. if( !isOwned() ) {
  9298. m_data = new char[m_size+1];
  9299. memcpy( m_data, m_start, m_size );
  9300. m_data[m_size] = '\0';
  9301. m_start = m_data;
  9302. }
  9303. }
  9304. auto StringRef::substr( size_type start, size_type size ) const noexcept -> StringRef {
  9305. if( start < m_size )
  9306. return StringRef( m_start+start, size );
  9307. else
  9308. return StringRef();
  9309. }
  9310. auto StringRef::operator == ( StringRef const& other ) const noexcept -> bool {
  9311. return
  9312. size() == other.size() &&
  9313. (std::strncmp( m_start, other.m_start, size() ) == 0);
  9314. }
  9315. auto StringRef::operator != ( StringRef const& other ) const noexcept -> bool {
  9316. return !operator==( other );
  9317. }
  9318. auto StringRef::operator[](size_type index) const noexcept -> char {
  9319. return m_start[index];
  9320. }
  9321. auto StringRef::numberOfCharacters() const noexcept -> size_type {
  9322. size_type noChars = m_size;
  9323. // Make adjustments for uft encodings
  9324. for( size_type i=0; i < m_size; ++i ) {
  9325. char c = m_start[i];
  9326. if( ( c & byte_2_lead ) == byte_2_lead ) {
  9327. noChars--;
  9328. if (( c & byte_3_lead ) == byte_3_lead )
  9329. noChars--;
  9330. if( ( c & byte_4_lead ) == byte_4_lead )
  9331. noChars--;
  9332. }
  9333. }
  9334. return noChars;
  9335. }
  9336. auto operator + ( StringRef const& lhs, StringRef const& rhs ) -> std::string {
  9337. std::string str;
  9338. str.reserve( lhs.size() + rhs.size() );
  9339. str += lhs;
  9340. str += rhs;
  9341. return str;
  9342. }
  9343. auto operator + ( StringRef const& lhs, const char* rhs ) -> std::string {
  9344. return std::string( lhs ) + std::string( rhs );
  9345. }
  9346. auto operator + ( char const* lhs, StringRef const& rhs ) -> std::string {
  9347. return std::string( lhs ) + std::string( rhs );
  9348. }
  9349. auto operator << ( std::ostream& os, StringRef const& str ) -> std::ostream& {
  9350. return os.write(str.currentData(), str.size());
  9351. }
  9352. auto operator+=( std::string& lhs, StringRef const& rhs ) -> std::string& {
  9353. lhs.append(rhs.currentData(), rhs.size());
  9354. return lhs;
  9355. }
  9356. } // namespace Catch
  9357. #if defined(__clang__)
  9358. # pragma clang diagnostic pop
  9359. #endif
  9360. // end catch_stringref.cpp
  9361. // start catch_tag_alias.cpp
  9362. namespace Catch {
  9363. TagAlias::TagAlias(std::string const & _tag, SourceLineInfo _lineInfo): tag(_tag), lineInfo(_lineInfo) {}
  9364. }
  9365. // end catch_tag_alias.cpp
  9366. // start catch_tag_alias_autoregistrar.cpp
  9367. namespace Catch {
  9368. RegistrarForTagAliases::RegistrarForTagAliases(char const* alias, char const* tag, SourceLineInfo const& lineInfo) {
  9369. CATCH_TRY {
  9370. getMutableRegistryHub().registerTagAlias(alias, tag, lineInfo);
  9371. } CATCH_CATCH_ALL {
  9372. // Do not throw when constructing global objects, instead register the exception to be processed later
  9373. getMutableRegistryHub().registerStartupException();
  9374. }
  9375. }
  9376. }
  9377. // end catch_tag_alias_autoregistrar.cpp
  9378. // start catch_tag_alias_registry.cpp
  9379. #include <sstream>
  9380. namespace Catch {
  9381. TagAliasRegistry::~TagAliasRegistry() {}
  9382. TagAlias const* TagAliasRegistry::find( std::string const& alias ) const {
  9383. auto it = m_registry.find( alias );
  9384. if( it != m_registry.end() )
  9385. return &(it->second);
  9386. else
  9387. return nullptr;
  9388. }
  9389. std::string TagAliasRegistry::expandAliases( std::string const& unexpandedTestSpec ) const {
  9390. std::string expandedTestSpec = unexpandedTestSpec;
  9391. for( auto const& registryKvp : m_registry ) {
  9392. std::size_t pos = expandedTestSpec.find( registryKvp.first );
  9393. if( pos != std::string::npos ) {
  9394. expandedTestSpec = expandedTestSpec.substr( 0, pos ) +
  9395. registryKvp.second.tag +
  9396. expandedTestSpec.substr( pos + registryKvp.first.size() );
  9397. }
  9398. }
  9399. return expandedTestSpec;
  9400. }
  9401. void TagAliasRegistry::add( std::string const& alias, std::string const& tag, SourceLineInfo const& lineInfo ) {
  9402. CATCH_ENFORCE( startsWith(alias, "[@") && endsWith(alias, ']'),
  9403. "error: tag alias, '" << alias << "' is not of the form [@alias name].\n" << lineInfo );
  9404. CATCH_ENFORCE( m_registry.insert(std::make_pair(alias, TagAlias(tag, lineInfo))).second,
  9405. "error: tag alias, '" << alias << "' already registered.\n"
  9406. << "\tFirst seen at: " << find(alias)->lineInfo << "\n"
  9407. << "\tRedefined at: " << lineInfo );
  9408. }
  9409. ITagAliasRegistry::~ITagAliasRegistry() {}
  9410. ITagAliasRegistry const& ITagAliasRegistry::get() {
  9411. return getRegistryHub().getTagAliasRegistry();
  9412. }
  9413. } // end namespace Catch
  9414. // end catch_tag_alias_registry.cpp
  9415. // start catch_test_case_info.cpp
  9416. #include <cctype>
  9417. #include <exception>
  9418. #include <algorithm>
  9419. #include <sstream>
  9420. namespace Catch {
  9421. namespace {
  9422. TestCaseInfo::SpecialProperties parseSpecialTag( std::string const& tag ) {
  9423. if( startsWith( tag, '.' ) ||
  9424. tag == "!hide" )
  9425. return TestCaseInfo::IsHidden;
  9426. else if( tag == "!throws" )
  9427. return TestCaseInfo::Throws;
  9428. else if( tag == "!shouldfail" )
  9429. return TestCaseInfo::ShouldFail;
  9430. else if( tag == "!mayfail" )
  9431. return TestCaseInfo::MayFail;
  9432. else if( tag == "!nonportable" )
  9433. return TestCaseInfo::NonPortable;
  9434. else if( tag == "!benchmark" )
  9435. return static_cast<TestCaseInfo::SpecialProperties>( TestCaseInfo::Benchmark | TestCaseInfo::IsHidden );
  9436. else
  9437. return TestCaseInfo::None;
  9438. }
  9439. bool isReservedTag( std::string const& tag ) {
  9440. return parseSpecialTag( tag ) == TestCaseInfo::None && tag.size() > 0 && !std::isalnum( static_cast<unsigned char>(tag[0]) );
  9441. }
  9442. void enforceNotReservedTag( std::string const& tag, SourceLineInfo const& _lineInfo ) {
  9443. CATCH_ENFORCE( !isReservedTag(tag),
  9444. "Tag name: [" << tag << "] is not allowed.\n"
  9445. << "Tag names starting with non alphanumeric characters are reserved\n"
  9446. << _lineInfo );
  9447. }
  9448. }
  9449. TestCase makeTestCase( ITestInvoker* _testCase,
  9450. std::string const& _className,
  9451. NameAndTags const& nameAndTags,
  9452. SourceLineInfo const& _lineInfo )
  9453. {
  9454. bool isHidden = false;
  9455. // Parse out tags
  9456. std::vector<std::string> tags;
  9457. std::string desc, tag;
  9458. bool inTag = false;
  9459. std::string _descOrTags = nameAndTags.tags;
  9460. for (char c : _descOrTags) {
  9461. if( !inTag ) {
  9462. if( c == '[' )
  9463. inTag = true;
  9464. else
  9465. desc += c;
  9466. }
  9467. else {
  9468. if( c == ']' ) {
  9469. TestCaseInfo::SpecialProperties prop = parseSpecialTag( tag );
  9470. if( ( prop & TestCaseInfo::IsHidden ) != 0 )
  9471. isHidden = true;
  9472. else if( prop == TestCaseInfo::None )
  9473. enforceNotReservedTag( tag, _lineInfo );
  9474. // Merged hide tags like `[.approvals]` should be added as
  9475. // `[.][approvals]`. The `[.]` is added at later point, so
  9476. // we only strip the prefix
  9477. if (startsWith(tag, '.') && tag.size() > 1) {
  9478. tag.erase(0, 1);
  9479. }
  9480. tags.push_back( tag );
  9481. tag.clear();
  9482. inTag = false;
  9483. }
  9484. else
  9485. tag += c;
  9486. }
  9487. }
  9488. if( isHidden ) {
  9489. tags.push_back( "." );
  9490. }
  9491. TestCaseInfo info( nameAndTags.name, _className, desc, tags, _lineInfo );
  9492. return TestCase( _testCase, std::move(info) );
  9493. }
  9494. void setTags( TestCaseInfo& testCaseInfo, std::vector<std::string> tags ) {
  9495. std::sort(begin(tags), end(tags));
  9496. tags.erase(std::unique(begin(tags), end(tags)), end(tags));
  9497. testCaseInfo.lcaseTags.clear();
  9498. for( auto const& tag : tags ) {
  9499. std::string lcaseTag = toLower( tag );
  9500. testCaseInfo.properties = static_cast<TestCaseInfo::SpecialProperties>( testCaseInfo.properties | parseSpecialTag( lcaseTag ) );
  9501. testCaseInfo.lcaseTags.push_back( lcaseTag );
  9502. }
  9503. testCaseInfo.tags = std::move(tags);
  9504. }
  9505. TestCaseInfo::TestCaseInfo( std::string const& _name,
  9506. std::string const& _className,
  9507. std::string const& _description,
  9508. std::vector<std::string> const& _tags,
  9509. SourceLineInfo const& _lineInfo )
  9510. : name( _name ),
  9511. className( _className ),
  9512. description( _description ),
  9513. lineInfo( _lineInfo ),
  9514. properties( None )
  9515. {
  9516. setTags( *this, _tags );
  9517. }
  9518. bool TestCaseInfo::isHidden() const {
  9519. return ( properties & IsHidden ) != 0;
  9520. }
  9521. bool TestCaseInfo::throws() const {
  9522. return ( properties & Throws ) != 0;
  9523. }
  9524. bool TestCaseInfo::okToFail() const {
  9525. return ( properties & (ShouldFail | MayFail ) ) != 0;
  9526. }
  9527. bool TestCaseInfo::expectedToFail() const {
  9528. return ( properties & (ShouldFail ) ) != 0;
  9529. }
  9530. std::string TestCaseInfo::tagsAsString() const {
  9531. std::string ret;
  9532. // '[' and ']' per tag
  9533. std::size_t full_size = 2 * tags.size();
  9534. for (const auto& tag : tags) {
  9535. full_size += tag.size();
  9536. }
  9537. ret.reserve(full_size);
  9538. for (const auto& tag : tags) {
  9539. ret.push_back('[');
  9540. ret.append(tag);
  9541. ret.push_back(']');
  9542. }
  9543. return ret;
  9544. }
  9545. TestCase::TestCase( ITestInvoker* testCase, TestCaseInfo&& info ) : TestCaseInfo( std::move(info) ), test( testCase ) {}
  9546. TestCase TestCase::withName( std::string const& _newName ) const {
  9547. TestCase other( *this );
  9548. other.name = _newName;
  9549. return other;
  9550. }
  9551. void TestCase::invoke() const {
  9552. test->invoke();
  9553. }
  9554. bool TestCase::operator == ( TestCase const& other ) const {
  9555. return test.get() == other.test.get() &&
  9556. name == other.name &&
  9557. className == other.className;
  9558. }
  9559. bool TestCase::operator < ( TestCase const& other ) const {
  9560. return name < other.name;
  9561. }
  9562. TestCaseInfo const& TestCase::getTestCaseInfo() const
  9563. {
  9564. return *this;
  9565. }
  9566. } // end namespace Catch
  9567. // end catch_test_case_info.cpp
  9568. // start catch_test_case_registry_impl.cpp
  9569. #include <sstream>
  9570. namespace Catch {
  9571. std::vector<TestCase> sortTests( IConfig const& config, std::vector<TestCase> const& unsortedTestCases ) {
  9572. std::vector<TestCase> sorted = unsortedTestCases;
  9573. switch( config.runOrder() ) {
  9574. case RunTests::InLexicographicalOrder:
  9575. std::sort( sorted.begin(), sorted.end() );
  9576. break;
  9577. case RunTests::InRandomOrder:
  9578. seedRng( config );
  9579. std::shuffle( sorted.begin(), sorted.end(), rng() );
  9580. break;
  9581. case RunTests::InDeclarationOrder:
  9582. // already in declaration order
  9583. break;
  9584. }
  9585. return sorted;
  9586. }
  9587. bool matchTest( TestCase const& testCase, TestSpec const& testSpec, IConfig const& config ) {
  9588. return testSpec.matches( testCase ) && ( config.allowThrows() || !testCase.throws() );
  9589. }
  9590. void enforceNoDuplicateTestCases( std::vector<TestCase> const& functions ) {
  9591. std::set<TestCase> seenFunctions;
  9592. for( auto const& function : functions ) {
  9593. auto prev = seenFunctions.insert( function );
  9594. CATCH_ENFORCE( prev.second,
  9595. "error: TEST_CASE( \"" << function.name << "\" ) already defined.\n"
  9596. << "\tFirst seen at " << prev.first->getTestCaseInfo().lineInfo << "\n"
  9597. << "\tRedefined at " << function.getTestCaseInfo().lineInfo );
  9598. }
  9599. }
  9600. std::vector<TestCase> filterTests( std::vector<TestCase> const& testCases, TestSpec const& testSpec, IConfig const& config ) {
  9601. std::vector<TestCase> filtered;
  9602. filtered.reserve( testCases.size() );
  9603. for (auto const& testCase : testCases) {
  9604. if ((!testSpec.hasFilters() && !testCase.isHidden()) ||
  9605. (testSpec.hasFilters() && matchTest(testCase, testSpec, config))) {
  9606. filtered.push_back(testCase);
  9607. }
  9608. }
  9609. return filtered;
  9610. }
  9611. std::vector<TestCase> const& getAllTestCasesSorted( IConfig const& config ) {
  9612. return getRegistryHub().getTestCaseRegistry().getAllTestsSorted( config );
  9613. }
  9614. void TestRegistry::registerTest( TestCase const& testCase ) {
  9615. std::string name = testCase.getTestCaseInfo().name;
  9616. if( name.empty() ) {
  9617. ReusableStringStream rss;
  9618. rss << "Anonymous test case " << ++m_unnamedCount;
  9619. return registerTest( testCase.withName( rss.str() ) );
  9620. }
  9621. m_functions.push_back( testCase );
  9622. }
  9623. std::vector<TestCase> const& TestRegistry::getAllTests() const {
  9624. return m_functions;
  9625. }
  9626. std::vector<TestCase> const& TestRegistry::getAllTestsSorted( IConfig const& config ) const {
  9627. if( m_sortedFunctions.empty() )
  9628. enforceNoDuplicateTestCases( m_functions );
  9629. if( m_currentSortOrder != config.runOrder() || m_sortedFunctions.empty() ) {
  9630. m_sortedFunctions = sortTests( config, m_functions );
  9631. m_currentSortOrder = config.runOrder();
  9632. }
  9633. return m_sortedFunctions;
  9634. }
  9635. ///////////////////////////////////////////////////////////////////////////
  9636. TestInvokerAsFunction::TestInvokerAsFunction( void(*testAsFunction)() ) noexcept : m_testAsFunction( testAsFunction ) {}
  9637. void TestInvokerAsFunction::invoke() const {
  9638. m_testAsFunction();
  9639. }
  9640. std::string extractClassName( StringRef const& classOrQualifiedMethodName ) {
  9641. std::string className = classOrQualifiedMethodName;
  9642. if( startsWith( className, '&' ) )
  9643. {
  9644. std::size_t lastColons = className.rfind( "::" );
  9645. std::size_t penultimateColons = className.rfind( "::", lastColons-1 );
  9646. if( penultimateColons == std::string::npos )
  9647. penultimateColons = 1;
  9648. className = className.substr( penultimateColons, lastColons-penultimateColons );
  9649. }
  9650. return className;
  9651. }
  9652. } // end namespace Catch
  9653. // end catch_test_case_registry_impl.cpp
  9654. // start catch_test_case_tracker.cpp
  9655. #include <algorithm>
  9656. #include <cassert>
  9657. #include <stdexcept>
  9658. #include <memory>
  9659. #include <sstream>
  9660. #if defined(__clang__)
  9661. # pragma clang diagnostic push
  9662. # pragma clang diagnostic ignored "-Wexit-time-destructors"
  9663. #endif
  9664. namespace Catch {
  9665. namespace TestCaseTracking {
  9666. NameAndLocation::NameAndLocation( std::string const& _name, SourceLineInfo const& _location )
  9667. : name( _name ),
  9668. location( _location )
  9669. {}
  9670. ITracker::~ITracker() = default;
  9671. ITracker& TrackerContext::startRun() {
  9672. m_rootTracker = std::make_shared<SectionTracker>( NameAndLocation( "{root}", CATCH_INTERNAL_LINEINFO ), *this, nullptr );
  9673. m_currentTracker = nullptr;
  9674. m_runState = Executing;
  9675. return *m_rootTracker;
  9676. }
  9677. void TrackerContext::endRun() {
  9678. m_rootTracker.reset();
  9679. m_currentTracker = nullptr;
  9680. m_runState = NotStarted;
  9681. }
  9682. void TrackerContext::startCycle() {
  9683. m_currentTracker = m_rootTracker.get();
  9684. m_runState = Executing;
  9685. }
  9686. void TrackerContext::completeCycle() {
  9687. m_runState = CompletedCycle;
  9688. }
  9689. bool TrackerContext::completedCycle() const {
  9690. return m_runState == CompletedCycle;
  9691. }
  9692. ITracker& TrackerContext::currentTracker() {
  9693. return *m_currentTracker;
  9694. }
  9695. void TrackerContext::setCurrentTracker( ITracker* tracker ) {
  9696. m_currentTracker = tracker;
  9697. }
  9698. TrackerBase::TrackerBase( NameAndLocation const& nameAndLocation, TrackerContext& ctx, ITracker* parent )
  9699. : m_nameAndLocation( nameAndLocation ),
  9700. m_ctx( ctx ),
  9701. m_parent( parent )
  9702. {}
  9703. NameAndLocation const& TrackerBase::nameAndLocation() const {
  9704. return m_nameAndLocation;
  9705. }
  9706. bool TrackerBase::isComplete() const {
  9707. return m_runState == CompletedSuccessfully || m_runState == Failed;
  9708. }
  9709. bool TrackerBase::isSuccessfullyCompleted() const {
  9710. return m_runState == CompletedSuccessfully;
  9711. }
  9712. bool TrackerBase::isOpen() const {
  9713. return m_runState != NotStarted && !isComplete();
  9714. }
  9715. bool TrackerBase::hasChildren() const {
  9716. return !m_children.empty();
  9717. }
  9718. void TrackerBase::addChild( ITrackerPtr const& child ) {
  9719. m_children.push_back( child );
  9720. }
  9721. ITrackerPtr TrackerBase::findChild( NameAndLocation const& nameAndLocation ) {
  9722. auto it = std::find_if( m_children.begin(), m_children.end(),
  9723. [&nameAndLocation]( ITrackerPtr const& tracker ){
  9724. return
  9725. tracker->nameAndLocation().location == nameAndLocation.location &&
  9726. tracker->nameAndLocation().name == nameAndLocation.name;
  9727. } );
  9728. return( it != m_children.end() )
  9729. ? *it
  9730. : nullptr;
  9731. }
  9732. ITracker& TrackerBase::parent() {
  9733. assert( m_parent ); // Should always be non-null except for root
  9734. return *m_parent;
  9735. }
  9736. void TrackerBase::openChild() {
  9737. if( m_runState != ExecutingChildren ) {
  9738. m_runState = ExecutingChildren;
  9739. if( m_parent )
  9740. m_parent->openChild();
  9741. }
  9742. }
  9743. bool TrackerBase::isSectionTracker() const { return false; }
  9744. bool TrackerBase::isGeneratorTracker() const { return false; }
  9745. void TrackerBase::open() {
  9746. m_runState = Executing;
  9747. moveToThis();
  9748. if( m_parent )
  9749. m_parent->openChild();
  9750. }
  9751. void TrackerBase::close() {
  9752. // Close any still open children (e.g. generators)
  9753. while( &m_ctx.currentTracker() != this )
  9754. m_ctx.currentTracker().close();
  9755. switch( m_runState ) {
  9756. case NeedsAnotherRun:
  9757. break;
  9758. case Executing:
  9759. m_runState = CompletedSuccessfully;
  9760. break;
  9761. case ExecutingChildren:
  9762. if( m_children.empty() || m_children.back()->isComplete() )
  9763. m_runState = CompletedSuccessfully;
  9764. break;
  9765. case NotStarted:
  9766. case CompletedSuccessfully:
  9767. case Failed:
  9768. CATCH_INTERNAL_ERROR( "Illogical state: " << m_runState );
  9769. default:
  9770. CATCH_INTERNAL_ERROR( "Unknown state: " << m_runState );
  9771. }
  9772. moveToParent();
  9773. m_ctx.completeCycle();
  9774. }
  9775. void TrackerBase::fail() {
  9776. m_runState = Failed;
  9777. if( m_parent )
  9778. m_parent->markAsNeedingAnotherRun();
  9779. moveToParent();
  9780. m_ctx.completeCycle();
  9781. }
  9782. void TrackerBase::markAsNeedingAnotherRun() {
  9783. m_runState = NeedsAnotherRun;
  9784. }
  9785. void TrackerBase::moveToParent() {
  9786. assert( m_parent );
  9787. m_ctx.setCurrentTracker( m_parent );
  9788. }
  9789. void TrackerBase::moveToThis() {
  9790. m_ctx.setCurrentTracker( this );
  9791. }
  9792. SectionTracker::SectionTracker( NameAndLocation const& nameAndLocation, TrackerContext& ctx, ITracker* parent )
  9793. : TrackerBase( nameAndLocation, ctx, parent )
  9794. {
  9795. if( parent ) {
  9796. while( !parent->isSectionTracker() )
  9797. parent = &parent->parent();
  9798. SectionTracker& parentSection = static_cast<SectionTracker&>( *parent );
  9799. addNextFilters( parentSection.m_filters );
  9800. }
  9801. }
  9802. bool SectionTracker::isComplete() const {
  9803. bool complete = true;
  9804. if ((m_filters.empty() || m_filters[0] == "") ||
  9805. std::find(m_filters.begin(), m_filters.end(),
  9806. m_nameAndLocation.name) != m_filters.end())
  9807. complete = TrackerBase::isComplete();
  9808. return complete;
  9809. }
  9810. bool SectionTracker::isSectionTracker() const { return true; }
  9811. SectionTracker& SectionTracker::acquire( TrackerContext& ctx, NameAndLocation const& nameAndLocation ) {
  9812. std::shared_ptr<SectionTracker> section;
  9813. ITracker& currentTracker = ctx.currentTracker();
  9814. if( ITrackerPtr childTracker = currentTracker.findChild( nameAndLocation ) ) {
  9815. assert( childTracker );
  9816. assert( childTracker->isSectionTracker() );
  9817. section = std::static_pointer_cast<SectionTracker>( childTracker );
  9818. }
  9819. else {
  9820. section = std::make_shared<SectionTracker>( nameAndLocation, ctx, &currentTracker );
  9821. currentTracker.addChild( section );
  9822. }
  9823. if( !ctx.completedCycle() )
  9824. section->tryOpen();
  9825. return *section;
  9826. }
  9827. void SectionTracker::tryOpen() {
  9828. if( !isComplete() && (m_filters.empty() || m_filters[0].empty() || m_filters[0] == m_nameAndLocation.name ) )
  9829. open();
  9830. }
  9831. void SectionTracker::addInitialFilters( std::vector<std::string> const& filters ) {
  9832. if( !filters.empty() ) {
  9833. m_filters.push_back(""); // Root - should never be consulted
  9834. m_filters.push_back(""); // Test Case - not a section filter
  9835. m_filters.insert( m_filters.end(), filters.begin(), filters.end() );
  9836. }
  9837. }
  9838. void SectionTracker::addNextFilters( std::vector<std::string> const& filters ) {
  9839. if( filters.size() > 1 )
  9840. m_filters.insert( m_filters.end(), ++filters.begin(), filters.end() );
  9841. }
  9842. } // namespace TestCaseTracking
  9843. using TestCaseTracking::ITracker;
  9844. using TestCaseTracking::TrackerContext;
  9845. using TestCaseTracking::SectionTracker;
  9846. } // namespace Catch
  9847. #if defined(__clang__)
  9848. # pragma clang diagnostic pop
  9849. #endif
  9850. // end catch_test_case_tracker.cpp
  9851. // start catch_test_registry.cpp
  9852. namespace Catch {
  9853. auto makeTestInvoker( void(*testAsFunction)() ) noexcept -> ITestInvoker* {
  9854. return new(std::nothrow) TestInvokerAsFunction( testAsFunction );
  9855. }
  9856. NameAndTags::NameAndTags( StringRef const& name_ , StringRef const& tags_ ) noexcept : name( name_ ), tags( tags_ ) {}
  9857. AutoReg::AutoReg( ITestInvoker* invoker, SourceLineInfo const& lineInfo, StringRef const& classOrMethod, NameAndTags const& nameAndTags ) noexcept {
  9858. CATCH_TRY {
  9859. getMutableRegistryHub()
  9860. .registerTest(
  9861. makeTestCase(
  9862. invoker,
  9863. extractClassName( classOrMethod ),
  9864. nameAndTags,
  9865. lineInfo));
  9866. } CATCH_CATCH_ALL {
  9867. // Do not throw when constructing global objects, instead register the exception to be processed later
  9868. getMutableRegistryHub().registerStartupException();
  9869. }
  9870. }
  9871. AutoReg::~AutoReg() = default;
  9872. }
  9873. // end catch_test_registry.cpp
  9874. // start catch_test_spec.cpp
  9875. #include <algorithm>
  9876. #include <string>
  9877. #include <vector>
  9878. #include <memory>
  9879. namespace Catch {
  9880. TestSpec::Pattern::~Pattern() = default;
  9881. TestSpec::NamePattern::~NamePattern() = default;
  9882. TestSpec::TagPattern::~TagPattern() = default;
  9883. TestSpec::ExcludedPattern::~ExcludedPattern() = default;
  9884. TestSpec::NamePattern::NamePattern( std::string const& name )
  9885. : m_wildcardPattern( toLower( name ), CaseSensitive::No )
  9886. {}
  9887. bool TestSpec::NamePattern::matches( TestCaseInfo const& testCase ) const {
  9888. return m_wildcardPattern.matches( toLower( testCase.name ) );
  9889. }
  9890. TestSpec::TagPattern::TagPattern( std::string const& tag ) : m_tag( toLower( tag ) ) {}
  9891. bool TestSpec::TagPattern::matches( TestCaseInfo const& testCase ) const {
  9892. return std::find(begin(testCase.lcaseTags),
  9893. end(testCase.lcaseTags),
  9894. m_tag) != end(testCase.lcaseTags);
  9895. }
  9896. TestSpec::ExcludedPattern::ExcludedPattern( PatternPtr const& underlyingPattern ) : m_underlyingPattern( underlyingPattern ) {}
  9897. bool TestSpec::ExcludedPattern::matches( TestCaseInfo const& testCase ) const { return !m_underlyingPattern->matches( testCase ); }
  9898. bool TestSpec::Filter::matches( TestCaseInfo const& testCase ) const {
  9899. // All patterns in a filter must match for the filter to be a match
  9900. for( auto const& pattern : m_patterns ) {
  9901. if( !pattern->matches( testCase ) )
  9902. return false;
  9903. }
  9904. return true;
  9905. }
  9906. bool TestSpec::hasFilters() const {
  9907. return !m_filters.empty();
  9908. }
  9909. bool TestSpec::matches( TestCaseInfo const& testCase ) const {
  9910. // A TestSpec matches if any filter matches
  9911. for( auto const& filter : m_filters )
  9912. if( filter.matches( testCase ) )
  9913. return true;
  9914. return false;
  9915. }
  9916. }
  9917. // end catch_test_spec.cpp
  9918. // start catch_test_spec_parser.cpp
  9919. namespace Catch {
  9920. TestSpecParser::TestSpecParser( ITagAliasRegistry const& tagAliases ) : m_tagAliases( &tagAliases ) {}
  9921. TestSpecParser& TestSpecParser::parse( std::string const& arg ) {
  9922. m_mode = None;
  9923. m_exclusion = false;
  9924. m_start = std::string::npos;
  9925. m_arg = m_tagAliases->expandAliases( arg );
  9926. m_escapeChars.clear();
  9927. for( m_pos = 0; m_pos < m_arg.size(); ++m_pos )
  9928. visitChar( m_arg[m_pos] );
  9929. if( m_mode == Name )
  9930. addPattern<TestSpec::NamePattern>();
  9931. return *this;
  9932. }
  9933. TestSpec TestSpecParser::testSpec() {
  9934. addFilter();
  9935. return m_testSpec;
  9936. }
  9937. void TestSpecParser::visitChar( char c ) {
  9938. if( m_mode == None ) {
  9939. switch( c ) {
  9940. case ' ': return;
  9941. case '~': m_exclusion = true; return;
  9942. case '[': return startNewMode( Tag, ++m_pos );
  9943. case '"': return startNewMode( QuotedName, ++m_pos );
  9944. case '\\': return escape();
  9945. default: startNewMode( Name, m_pos ); break;
  9946. }
  9947. }
  9948. if( m_mode == Name ) {
  9949. if( c == ',' ) {
  9950. addPattern<TestSpec::NamePattern>();
  9951. addFilter();
  9952. }
  9953. else if( c == '[' ) {
  9954. if( subString() == "exclude:" )
  9955. m_exclusion = true;
  9956. else
  9957. addPattern<TestSpec::NamePattern>();
  9958. startNewMode( Tag, ++m_pos );
  9959. }
  9960. else if( c == '\\' )
  9961. escape();
  9962. }
  9963. else if( m_mode == EscapedName )
  9964. m_mode = Name;
  9965. else if( m_mode == QuotedName && c == '"' )
  9966. addPattern<TestSpec::NamePattern>();
  9967. else if( m_mode == Tag && c == ']' )
  9968. addPattern<TestSpec::TagPattern>();
  9969. }
  9970. void TestSpecParser::startNewMode( Mode mode, std::size_t start ) {
  9971. m_mode = mode;
  9972. m_start = start;
  9973. }
  9974. void TestSpecParser::escape() {
  9975. if( m_mode == None )
  9976. m_start = m_pos;
  9977. m_mode = EscapedName;
  9978. m_escapeChars.push_back( m_pos );
  9979. }
  9980. std::string TestSpecParser::subString() const { return m_arg.substr( m_start, m_pos - m_start ); }
  9981. void TestSpecParser::addFilter() {
  9982. if( !m_currentFilter.m_patterns.empty() ) {
  9983. m_testSpec.m_filters.push_back( m_currentFilter );
  9984. m_currentFilter = TestSpec::Filter();
  9985. }
  9986. }
  9987. TestSpec parseTestSpec( std::string const& arg ) {
  9988. return TestSpecParser( ITagAliasRegistry::get() ).parse( arg ).testSpec();
  9989. }
  9990. } // namespace Catch
  9991. // end catch_test_spec_parser.cpp
  9992. // start catch_timer.cpp
  9993. #include <chrono>
  9994. static const uint64_t nanosecondsInSecond = 1000000000;
  9995. namespace Catch {
  9996. auto getCurrentNanosecondsSinceEpoch() -> uint64_t {
  9997. return std::chrono::duration_cast<std::chrono::nanoseconds>( std::chrono::high_resolution_clock::now().time_since_epoch() ).count();
  9998. }
  9999. namespace {
  10000. auto estimateClockResolution() -> uint64_t {
  10001. uint64_t sum = 0;
  10002. static const uint64_t iterations = 1000000;
  10003. auto startTime = getCurrentNanosecondsSinceEpoch();
  10004. for( std::size_t i = 0; i < iterations; ++i ) {
  10005. uint64_t ticks;
  10006. uint64_t baseTicks = getCurrentNanosecondsSinceEpoch();
  10007. do {
  10008. ticks = getCurrentNanosecondsSinceEpoch();
  10009. } while( ticks == baseTicks );
  10010. auto delta = ticks - baseTicks;
  10011. sum += delta;
  10012. // If we have been calibrating for over 3 seconds -- the clock
  10013. // is terrible and we should move on.
  10014. // TBD: How to signal that the measured resolution is probably wrong?
  10015. if (ticks > startTime + 3 * nanosecondsInSecond) {
  10016. return sum / ( i + 1u );
  10017. }
  10018. }
  10019. // We're just taking the mean, here. To do better we could take the std. dev and exclude outliers
  10020. // - and potentially do more iterations if there's a high variance.
  10021. return sum/iterations;
  10022. }
  10023. }
  10024. auto getEstimatedClockResolution() -> uint64_t {
  10025. static auto s_resolution = estimateClockResolution();
  10026. return s_resolution;
  10027. }
  10028. void Timer::start() {
  10029. m_nanoseconds = getCurrentNanosecondsSinceEpoch();
  10030. }
  10031. auto Timer::getElapsedNanoseconds() const -> uint64_t {
  10032. return getCurrentNanosecondsSinceEpoch() - m_nanoseconds;
  10033. }
  10034. auto Timer::getElapsedMicroseconds() const -> uint64_t {
  10035. return getElapsedNanoseconds()/1000;
  10036. }
  10037. auto Timer::getElapsedMilliseconds() const -> unsigned int {
  10038. return static_cast<unsigned int>(getElapsedMicroseconds()/1000);
  10039. }
  10040. auto Timer::getElapsedSeconds() const -> double {
  10041. return getElapsedMicroseconds()/1000000.0;
  10042. }
  10043. } // namespace Catch
  10044. // end catch_timer.cpp
  10045. // start catch_tostring.cpp
  10046. #if defined(__clang__)
  10047. # pragma clang diagnostic push
  10048. # pragma clang diagnostic ignored "-Wexit-time-destructors"
  10049. # pragma clang diagnostic ignored "-Wglobal-constructors"
  10050. #endif
  10051. // Enable specific decls locally
  10052. #if !defined(CATCH_CONFIG_ENABLE_CHRONO_STRINGMAKER)
  10053. #define CATCH_CONFIG_ENABLE_CHRONO_STRINGMAKER
  10054. #endif
  10055. #include <cmath>
  10056. #include <iomanip>
  10057. namespace Catch {
  10058. namespace Detail {
  10059. const std::string unprintableString = "{?}";
  10060. namespace {
  10061. const int hexThreshold = 255;
  10062. struct Endianness {
  10063. enum Arch { Big, Little };
  10064. static Arch which() {
  10065. union _{
  10066. int asInt;
  10067. char asChar[sizeof (int)];
  10068. } u;
  10069. u.asInt = 1;
  10070. return ( u.asChar[sizeof(int)-1] == 1 ) ? Big : Little;
  10071. }
  10072. };
  10073. }
  10074. std::string rawMemoryToString( const void *object, std::size_t size ) {
  10075. // Reverse order for little endian architectures
  10076. int i = 0, end = static_cast<int>( size ), inc = 1;
  10077. if( Endianness::which() == Endianness::Little ) {
  10078. i = end-1;
  10079. end = inc = -1;
  10080. }
  10081. unsigned char const *bytes = static_cast<unsigned char const *>(object);
  10082. ReusableStringStream rss;
  10083. rss << "0x" << std::setfill('0') << std::hex;
  10084. for( ; i != end; i += inc )
  10085. rss << std::setw(2) << static_cast<unsigned>(bytes[i]);
  10086. return rss.str();
  10087. }
  10088. }
  10089. template<typename T>
  10090. std::string fpToString( T value, int precision ) {
  10091. if (Catch::isnan(value)) {
  10092. return "nan";
  10093. }
  10094. ReusableStringStream rss;
  10095. rss << std::setprecision( precision )
  10096. << std::fixed
  10097. << value;
  10098. std::string d = rss.str();
  10099. std::size_t i = d.find_last_not_of( '0' );
  10100. if( i != std::string::npos && i != d.size()-1 ) {
  10101. if( d[i] == '.' )
  10102. i++;
  10103. d = d.substr( 0, i+1 );
  10104. }
  10105. return d;
  10106. }
  10107. //// ======================================================= ////
  10108. //
  10109. // Out-of-line defs for full specialization of StringMaker
  10110. //
  10111. //// ======================================================= ////
  10112. std::string StringMaker<std::string>::convert(const std::string& str) {
  10113. if (!getCurrentContext().getConfig()->showInvisibles()) {
  10114. return '"' + str + '"';
  10115. }
  10116. std::string s("\"");
  10117. for (char c : str) {
  10118. switch (c) {
  10119. case '\n':
  10120. s.append("\\n");
  10121. break;
  10122. case '\t':
  10123. s.append("\\t");
  10124. break;
  10125. default:
  10126. s.push_back(c);
  10127. break;
  10128. }
  10129. }
  10130. s.append("\"");
  10131. return s;
  10132. }
  10133. #ifdef CATCH_CONFIG_CPP17_STRING_VIEW
  10134. std::string StringMaker<std::string_view>::convert(std::string_view str) {
  10135. return ::Catch::Detail::stringify(std::string{ str });
  10136. }
  10137. #endif
  10138. std::string StringMaker<char const*>::convert(char const* str) {
  10139. if (str) {
  10140. return ::Catch::Detail::stringify(std::string{ str });
  10141. } else {
  10142. return{ "{null string}" };
  10143. }
  10144. }
  10145. std::string StringMaker<char*>::convert(char* str) {
  10146. if (str) {
  10147. return ::Catch::Detail::stringify(std::string{ str });
  10148. } else {
  10149. return{ "{null string}" };
  10150. }
  10151. }
  10152. #ifdef CATCH_CONFIG_WCHAR
  10153. std::string StringMaker<std::wstring>::convert(const std::wstring& wstr) {
  10154. std::string s;
  10155. s.reserve(wstr.size());
  10156. for (auto c : wstr) {
  10157. s += (c <= 0xff) ? static_cast<char>(c) : '?';
  10158. }
  10159. return ::Catch::Detail::stringify(s);
  10160. }
  10161. # ifdef CATCH_CONFIG_CPP17_STRING_VIEW
  10162. std::string StringMaker<std::wstring_view>::convert(std::wstring_view str) {
  10163. return StringMaker<std::wstring>::convert(std::wstring(str));
  10164. }
  10165. # endif
  10166. std::string StringMaker<wchar_t const*>::convert(wchar_t const * str) {
  10167. if (str) {
  10168. return ::Catch::Detail::stringify(std::wstring{ str });
  10169. } else {
  10170. return{ "{null string}" };
  10171. }
  10172. }
  10173. std::string StringMaker<wchar_t *>::convert(wchar_t * str) {
  10174. if (str) {
  10175. return ::Catch::Detail::stringify(std::wstring{ str });
  10176. } else {
  10177. return{ "{null string}" };
  10178. }
  10179. }
  10180. #endif
  10181. std::string StringMaker<int>::convert(int value) {
  10182. return ::Catch::Detail::stringify(static_cast<long long>(value));
  10183. }
  10184. std::string StringMaker<long>::convert(long value) {
  10185. return ::Catch::Detail::stringify(static_cast<long long>(value));
  10186. }
  10187. std::string StringMaker<long long>::convert(long long value) {
  10188. ReusableStringStream rss;
  10189. rss << value;
  10190. if (value > Detail::hexThreshold) {
  10191. rss << " (0x" << std::hex << value << ')';
  10192. }
  10193. return rss.str();
  10194. }
  10195. std::string StringMaker<unsigned int>::convert(unsigned int value) {
  10196. return ::Catch::Detail::stringify(static_cast<unsigned long long>(value));
  10197. }
  10198. std::string StringMaker<unsigned long>::convert(unsigned long value) {
  10199. return ::Catch::Detail::stringify(static_cast<unsigned long long>(value));
  10200. }
  10201. std::string StringMaker<unsigned long long>::convert(unsigned long long value) {
  10202. ReusableStringStream rss;
  10203. rss << value;
  10204. if (value > Detail::hexThreshold) {
  10205. rss << " (0x" << std::hex << value << ')';
  10206. }
  10207. return rss.str();
  10208. }
  10209. std::string StringMaker<bool>::convert(bool b) {
  10210. return b ? "true" : "false";
  10211. }
  10212. std::string StringMaker<signed char>::convert(signed char value) {
  10213. if (value == '\r') {
  10214. return "'\\r'";
  10215. } else if (value == '\f') {
  10216. return "'\\f'";
  10217. } else if (value == '\n') {
  10218. return "'\\n'";
  10219. } else if (value == '\t') {
  10220. return "'\\t'";
  10221. } else if ('\0' <= value && value < ' ') {
  10222. return ::Catch::Detail::stringify(static_cast<unsigned int>(value));
  10223. } else {
  10224. char chstr[] = "' '";
  10225. chstr[1] = value;
  10226. return chstr;
  10227. }
  10228. }
  10229. std::string StringMaker<char>::convert(char c) {
  10230. return ::Catch::Detail::stringify(static_cast<signed char>(c));
  10231. }
  10232. std::string StringMaker<unsigned char>::convert(unsigned char c) {
  10233. return ::Catch::Detail::stringify(static_cast<char>(c));
  10234. }
  10235. std::string StringMaker<std::nullptr_t>::convert(std::nullptr_t) {
  10236. return "nullptr";
  10237. }
  10238. std::string StringMaker<float>::convert(float value) {
  10239. return fpToString(value, 5) + 'f';
  10240. }
  10241. std::string StringMaker<double>::convert(double value) {
  10242. return fpToString(value, 10);
  10243. }
  10244. std::string ratio_string<std::atto>::symbol() { return "a"; }
  10245. std::string ratio_string<std::femto>::symbol() { return "f"; }
  10246. std::string ratio_string<std::pico>::symbol() { return "p"; }
  10247. std::string ratio_string<std::nano>::symbol() { return "n"; }
  10248. std::string ratio_string<std::micro>::symbol() { return "u"; }
  10249. std::string ratio_string<std::milli>::symbol() { return "m"; }
  10250. } // end namespace Catch
  10251. #if defined(__clang__)
  10252. # pragma clang diagnostic pop
  10253. #endif
  10254. // end catch_tostring.cpp
  10255. // start catch_totals.cpp
  10256. namespace Catch {
  10257. Counts Counts::operator - ( Counts const& other ) const {
  10258. Counts diff;
  10259. diff.passed = passed - other.passed;
  10260. diff.failed = failed - other.failed;
  10261. diff.failedButOk = failedButOk - other.failedButOk;
  10262. return diff;
  10263. }
  10264. Counts& Counts::operator += ( Counts const& other ) {
  10265. passed += other.passed;
  10266. failed += other.failed;
  10267. failedButOk += other.failedButOk;
  10268. return *this;
  10269. }
  10270. std::size_t Counts::total() const {
  10271. return passed + failed + failedButOk;
  10272. }
  10273. bool Counts::allPassed() const {
  10274. return failed == 0 && failedButOk == 0;
  10275. }
  10276. bool Counts::allOk() const {
  10277. return failed == 0;
  10278. }
  10279. Totals Totals::operator - ( Totals const& other ) const {
  10280. Totals diff;
  10281. diff.assertions = assertions - other.assertions;
  10282. diff.testCases = testCases - other.testCases;
  10283. return diff;
  10284. }
  10285. Totals& Totals::operator += ( Totals const& other ) {
  10286. assertions += other.assertions;
  10287. testCases += other.testCases;
  10288. return *this;
  10289. }
  10290. Totals Totals::delta( Totals const& prevTotals ) const {
  10291. Totals diff = *this - prevTotals;
  10292. if( diff.assertions.failed > 0 )
  10293. ++diff.testCases.failed;
  10294. else if( diff.assertions.failedButOk > 0 )
  10295. ++diff.testCases.failedButOk;
  10296. else
  10297. ++diff.testCases.passed;
  10298. return diff;
  10299. }
  10300. }
  10301. // end catch_totals.cpp
  10302. // start catch_uncaught_exceptions.cpp
  10303. #include <exception>
  10304. namespace Catch {
  10305. bool uncaught_exceptions() {
  10306. #if defined(CATCH_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS)
  10307. return std::uncaught_exceptions() > 0;
  10308. #else
  10309. return std::uncaught_exception();
  10310. #endif
  10311. }
  10312. } // end namespace Catch
  10313. // end catch_uncaught_exceptions.cpp
  10314. // start catch_version.cpp
  10315. #include <ostream>
  10316. namespace Catch {
  10317. Version::Version
  10318. ( unsigned int _majorVersion,
  10319. unsigned int _minorVersion,
  10320. unsigned int _patchNumber,
  10321. char const * const _branchName,
  10322. unsigned int _buildNumber )
  10323. : majorVersion( _majorVersion ),
  10324. minorVersion( _minorVersion ),
  10325. patchNumber( _patchNumber ),
  10326. branchName( _branchName ),
  10327. buildNumber( _buildNumber )
  10328. {}
  10329. std::ostream& operator << ( std::ostream& os, Version const& version ) {
  10330. os << version.majorVersion << '.'
  10331. << version.minorVersion << '.'
  10332. << version.patchNumber;
  10333. // branchName is never null -> 0th char is \0 if it is empty
  10334. if (version.branchName[0]) {
  10335. os << '-' << version.branchName
  10336. << '.' << version.buildNumber;
  10337. }
  10338. return os;
  10339. }
  10340. Version const& libraryVersion() {
  10341. static Version version( 2, 7, 2, "", 0 );
  10342. return version;
  10343. }
  10344. }
  10345. // end catch_version.cpp
  10346. // start catch_wildcard_pattern.cpp
  10347. #include <sstream>
  10348. namespace Catch {
  10349. WildcardPattern::WildcardPattern( std::string const& pattern,
  10350. CaseSensitive::Choice caseSensitivity )
  10351. : m_caseSensitivity( caseSensitivity ),
  10352. m_pattern( adjustCase( pattern ) )
  10353. {
  10354. if( startsWith( m_pattern, '*' ) ) {
  10355. m_pattern = m_pattern.substr( 1 );
  10356. m_wildcard = WildcardAtStart;
  10357. }
  10358. if( endsWith( m_pattern, '*' ) ) {
  10359. m_pattern = m_pattern.substr( 0, m_pattern.size()-1 );
  10360. m_wildcard = static_cast<WildcardPosition>( m_wildcard | WildcardAtEnd );
  10361. }
  10362. }
  10363. bool WildcardPattern::matches( std::string const& str ) const {
  10364. switch( m_wildcard ) {
  10365. case NoWildcard:
  10366. return m_pattern == adjustCase( str );
  10367. case WildcardAtStart:
  10368. return endsWith( adjustCase( str ), m_pattern );
  10369. case WildcardAtEnd:
  10370. return startsWith( adjustCase( str ), m_pattern );
  10371. case WildcardAtBothEnds:
  10372. return contains( adjustCase( str ), m_pattern );
  10373. default:
  10374. CATCH_INTERNAL_ERROR( "Unknown enum" );
  10375. }
  10376. }
  10377. std::string WildcardPattern::adjustCase( std::string const& str ) const {
  10378. return m_caseSensitivity == CaseSensitive::No ? toLower( str ) : str;
  10379. }
  10380. }
  10381. // end catch_wildcard_pattern.cpp
  10382. // start catch_xmlwriter.cpp
  10383. #include <iomanip>
  10384. using uchar = unsigned char;
  10385. namespace Catch {
  10386. namespace {
  10387. size_t trailingBytes(unsigned char c) {
  10388. if ((c & 0xE0) == 0xC0) {
  10389. return 2;
  10390. }
  10391. if ((c & 0xF0) == 0xE0) {
  10392. return 3;
  10393. }
  10394. if ((c & 0xF8) == 0xF0) {
  10395. return 4;
  10396. }
  10397. CATCH_INTERNAL_ERROR("Invalid multibyte utf-8 start byte encountered");
  10398. }
  10399. uint32_t headerValue(unsigned char c) {
  10400. if ((c & 0xE0) == 0xC0) {
  10401. return c & 0x1F;
  10402. }
  10403. if ((c & 0xF0) == 0xE0) {
  10404. return c & 0x0F;
  10405. }
  10406. if ((c & 0xF8) == 0xF0) {
  10407. return c & 0x07;
  10408. }
  10409. CATCH_INTERNAL_ERROR("Invalid multibyte utf-8 start byte encountered");
  10410. }
  10411. void hexEscapeChar(std::ostream& os, unsigned char c) {
  10412. std::ios_base::fmtflags f(os.flags());
  10413. os << "\\x"
  10414. << std::uppercase << std::hex << std::setfill('0') << std::setw(2)
  10415. << static_cast<int>(c);
  10416. os.flags(f);
  10417. }
  10418. } // anonymous namespace
  10419. XmlEncode::XmlEncode( std::string const& str, ForWhat forWhat )
  10420. : m_str( str ),
  10421. m_forWhat( forWhat )
  10422. {}
  10423. void XmlEncode::encodeTo( std::ostream& os ) const {
  10424. // Apostrophe escaping not necessary if we always use " to write attributes
  10425. // (see: http://www.w3.org/TR/xml/#syntax)
  10426. for( std::size_t idx = 0; idx < m_str.size(); ++ idx ) {
  10427. uchar c = m_str[idx];
  10428. switch (c) {
  10429. case '<': os << "&lt;"; break;
  10430. case '&': os << "&amp;"; break;
  10431. case '>':
  10432. // See: http://www.w3.org/TR/xml/#syntax
  10433. if (idx > 2 && m_str[idx - 1] == ']' && m_str[idx - 2] == ']')
  10434. os << "&gt;";
  10435. else
  10436. os << c;
  10437. break;
  10438. case '\"':
  10439. if (m_forWhat == ForAttributes)
  10440. os << "&quot;";
  10441. else
  10442. os << c;
  10443. break;
  10444. default:
  10445. // Check for control characters and invalid utf-8
  10446. // Escape control characters in standard ascii
  10447. // see http://stackoverflow.com/questions/404107/why-are-control-characters-illegal-in-xml-1-0
  10448. if (c < 0x09 || (c > 0x0D && c < 0x20) || c == 0x7F) {
  10449. hexEscapeChar(os, c);
  10450. break;
  10451. }
  10452. // Plain ASCII: Write it to stream
  10453. if (c < 0x7F) {
  10454. os << c;
  10455. break;
  10456. }
  10457. // UTF-8 territory
  10458. // Check if the encoding is valid and if it is not, hex escape bytes.
  10459. // Important: We do not check the exact decoded values for validity, only the encoding format
  10460. // First check that this bytes is a valid lead byte:
  10461. // This means that it is not encoded as 1111 1XXX
  10462. // Or as 10XX XXXX
  10463. if (c < 0xC0 ||
  10464. c >= 0xF8) {
  10465. hexEscapeChar(os, c);
  10466. break;
  10467. }
  10468. auto encBytes = trailingBytes(c);
  10469. // Are there enough bytes left to avoid accessing out-of-bounds memory?
  10470. if (idx + encBytes - 1 >= m_str.size()) {
  10471. hexEscapeChar(os, c);
  10472. break;
  10473. }
  10474. // The header is valid, check data
  10475. // The next encBytes bytes must together be a valid utf-8
  10476. // This means: bitpattern 10XX XXXX and the extracted value is sane (ish)
  10477. bool valid = true;
  10478. uint32_t value = headerValue(c);
  10479. for (std::size_t n = 1; n < encBytes; ++n) {
  10480. uchar nc = m_str[idx + n];
  10481. valid &= ((nc & 0xC0) == 0x80);
  10482. value = (value << 6) | (nc & 0x3F);
  10483. }
  10484. if (
  10485. // Wrong bit pattern of following bytes
  10486. (!valid) ||
  10487. // Overlong encodings
  10488. (value < 0x80) ||
  10489. (0x80 <= value && value < 0x800 && encBytes > 2) ||
  10490. (0x800 < value && value < 0x10000 && encBytes > 3) ||
  10491. // Encoded value out of range
  10492. (value >= 0x110000)
  10493. ) {
  10494. hexEscapeChar(os, c);
  10495. break;
  10496. }
  10497. // If we got here, this is in fact a valid(ish) utf-8 sequence
  10498. for (std::size_t n = 0; n < encBytes; ++n) {
  10499. os << m_str[idx + n];
  10500. }
  10501. idx += encBytes - 1;
  10502. break;
  10503. }
  10504. }
  10505. }
  10506. std::ostream& operator << ( std::ostream& os, XmlEncode const& xmlEncode ) {
  10507. xmlEncode.encodeTo( os );
  10508. return os;
  10509. }
  10510. XmlWriter::ScopedElement::ScopedElement( XmlWriter* writer )
  10511. : m_writer( writer )
  10512. {}
  10513. XmlWriter::ScopedElement::ScopedElement( ScopedElement&& other ) noexcept
  10514. : m_writer( other.m_writer ){
  10515. other.m_writer = nullptr;
  10516. }
  10517. XmlWriter::ScopedElement& XmlWriter::ScopedElement::operator=( ScopedElement&& other ) noexcept {
  10518. if ( m_writer ) {
  10519. m_writer->endElement();
  10520. }
  10521. m_writer = other.m_writer;
  10522. other.m_writer = nullptr;
  10523. return *this;
  10524. }
  10525. XmlWriter::ScopedElement::~ScopedElement() {
  10526. if( m_writer )
  10527. m_writer->endElement();
  10528. }
  10529. XmlWriter::ScopedElement& XmlWriter::ScopedElement::writeText( std::string const& text, bool indent ) {
  10530. m_writer->writeText( text, indent );
  10531. return *this;
  10532. }
  10533. XmlWriter::XmlWriter( std::ostream& os ) : m_os( os )
  10534. {
  10535. writeDeclaration();
  10536. }
  10537. XmlWriter::~XmlWriter() {
  10538. while( !m_tags.empty() )
  10539. endElement();
  10540. }
  10541. XmlWriter& XmlWriter::startElement( std::string const& name ) {
  10542. ensureTagClosed();
  10543. newlineIfNecessary();
  10544. m_os << m_indent << '<' << name;
  10545. m_tags.push_back( name );
  10546. m_indent += " ";
  10547. m_tagIsOpen = true;
  10548. return *this;
  10549. }
  10550. XmlWriter::ScopedElement XmlWriter::scopedElement( std::string const& name ) {
  10551. ScopedElement scoped( this );
  10552. startElement( name );
  10553. return scoped;
  10554. }
  10555. XmlWriter& XmlWriter::endElement() {
  10556. newlineIfNecessary();
  10557. m_indent = m_indent.substr( 0, m_indent.size()-2 );
  10558. if( m_tagIsOpen ) {
  10559. m_os << "/>";
  10560. m_tagIsOpen = false;
  10561. }
  10562. else {
  10563. m_os << m_indent << "</" << m_tags.back() << ">";
  10564. }
  10565. m_os << std::endl;
  10566. m_tags.pop_back();
  10567. return *this;
  10568. }
  10569. XmlWriter& XmlWriter::writeAttribute( std::string const& name, std::string const& attribute ) {
  10570. if( !name.empty() && !attribute.empty() )
  10571. m_os << ' ' << name << "=\"" << XmlEncode( attribute, XmlEncode::ForAttributes ) << '"';
  10572. return *this;
  10573. }
  10574. XmlWriter& XmlWriter::writeAttribute( std::string const& name, bool attribute ) {
  10575. m_os << ' ' << name << "=\"" << ( attribute ? "true" : "false" ) << '"';
  10576. return *this;
  10577. }
  10578. XmlWriter& XmlWriter::writeText( std::string const& text, bool indent ) {
  10579. if( !text.empty() ){
  10580. bool tagWasOpen = m_tagIsOpen;
  10581. ensureTagClosed();
  10582. if( tagWasOpen && indent )
  10583. m_os << m_indent;
  10584. m_os << XmlEncode( text );
  10585. m_needsNewline = true;
  10586. }
  10587. return *this;
  10588. }
  10589. XmlWriter& XmlWriter::writeComment( std::string const& text ) {
  10590. ensureTagClosed();
  10591. m_os << m_indent << "<!--" << text << "-->";
  10592. m_needsNewline = true;
  10593. return *this;
  10594. }
  10595. void XmlWriter::writeStylesheetRef( std::string const& url ) {
  10596. m_os << "<?xml-stylesheet type=\"text/xsl\" href=\"" << url << "\"?>\n";
  10597. }
  10598. XmlWriter& XmlWriter::writeBlankLine() {
  10599. ensureTagClosed();
  10600. m_os << '\n';
  10601. return *this;
  10602. }
  10603. void XmlWriter::ensureTagClosed() {
  10604. if( m_tagIsOpen ) {
  10605. m_os << ">" << std::endl;
  10606. m_tagIsOpen = false;
  10607. }
  10608. }
  10609. void XmlWriter::writeDeclaration() {
  10610. m_os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
  10611. }
  10612. void XmlWriter::newlineIfNecessary() {
  10613. if( m_needsNewline ) {
  10614. m_os << std::endl;
  10615. m_needsNewline = false;
  10616. }
  10617. }
  10618. }
  10619. // end catch_xmlwriter.cpp
  10620. // start catch_reporter_bases.cpp
  10621. #include <cstring>
  10622. #include <cfloat>
  10623. #include <cstdio>
  10624. #include <cassert>
  10625. #include <memory>
  10626. namespace Catch {
  10627. void prepareExpandedExpression(AssertionResult& result) {
  10628. result.getExpandedExpression();
  10629. }
  10630. // Because formatting using c++ streams is stateful, drop down to C is required
  10631. // Alternatively we could use stringstream, but its performance is... not good.
  10632. std::string getFormattedDuration( double duration ) {
  10633. // Max exponent + 1 is required to represent the whole part
  10634. // + 1 for decimal point
  10635. // + 3 for the 3 decimal places
  10636. // + 1 for null terminator
  10637. const std::size_t maxDoubleSize = DBL_MAX_10_EXP + 1 + 1 + 3 + 1;
  10638. char buffer[maxDoubleSize];
  10639. // Save previous errno, to prevent sprintf from overwriting it
  10640. ErrnoGuard guard;
  10641. #ifdef _MSC_VER
  10642. sprintf_s(buffer, "%.3f", duration);
  10643. #else
  10644. std::sprintf(buffer, "%.3f", duration);
  10645. #endif
  10646. return std::string(buffer);
  10647. }
  10648. std::string serializeFilters( std::vector<std::string> const& container ) {
  10649. ReusableStringStream oss;
  10650. bool first = true;
  10651. for (auto&& filter : container)
  10652. {
  10653. if (!first)
  10654. oss << ' ';
  10655. else
  10656. first = false;
  10657. oss << filter;
  10658. }
  10659. return oss.str();
  10660. }
  10661. TestEventListenerBase::TestEventListenerBase(ReporterConfig const & _config)
  10662. :StreamingReporterBase(_config) {}
  10663. std::set<Verbosity> TestEventListenerBase::getSupportedVerbosities() {
  10664. return { Verbosity::Quiet, Verbosity::Normal, Verbosity::High };
  10665. }
  10666. void TestEventListenerBase::assertionStarting(AssertionInfo const &) {}
  10667. bool TestEventListenerBase::assertionEnded(AssertionStats const &) {
  10668. return false;
  10669. }
  10670. } // end namespace Catch
  10671. // end catch_reporter_bases.cpp
  10672. // start catch_reporter_compact.cpp
  10673. namespace {
  10674. #ifdef CATCH_PLATFORM_MAC
  10675. const char* failedString() { return "FAILED"; }
  10676. const char* passedString() { return "PASSED"; }
  10677. #else
  10678. const char* failedString() { return "failed"; }
  10679. const char* passedString() { return "passed"; }
  10680. #endif
  10681. // Colour::LightGrey
  10682. Catch::Colour::Code dimColour() { return Catch::Colour::FileName; }
  10683. std::string bothOrAll( std::size_t count ) {
  10684. return count == 1 ? std::string() :
  10685. count == 2 ? "both " : "all " ;
  10686. }
  10687. } // anon namespace
  10688. namespace Catch {
  10689. namespace {
  10690. // Colour, message variants:
  10691. // - white: No tests ran.
  10692. // - red: Failed [both/all] N test cases, failed [both/all] M assertions.
  10693. // - white: Passed [both/all] N test cases (no assertions).
  10694. // - red: Failed N tests cases, failed M assertions.
  10695. // - green: Passed [both/all] N tests cases with M assertions.
  10696. void printTotals(std::ostream& out, const Totals& totals) {
  10697. if (totals.testCases.total() == 0) {
  10698. out << "No tests ran.";
  10699. } else if (totals.testCases.failed == totals.testCases.total()) {
  10700. Colour colour(Colour::ResultError);
  10701. const std::string qualify_assertions_failed =
  10702. totals.assertions.failed == totals.assertions.total() ?
  10703. bothOrAll(totals.assertions.failed) : std::string();
  10704. out <<
  10705. "Failed " << bothOrAll(totals.testCases.failed)
  10706. << pluralise(totals.testCases.failed, "test case") << ", "
  10707. "failed " << qualify_assertions_failed <<
  10708. pluralise(totals.assertions.failed, "assertion") << '.';
  10709. } else if (totals.assertions.total() == 0) {
  10710. out <<
  10711. "Passed " << bothOrAll(totals.testCases.total())
  10712. << pluralise(totals.testCases.total(), "test case")
  10713. << " (no assertions).";
  10714. } else if (totals.assertions.failed) {
  10715. Colour colour(Colour::ResultError);
  10716. out <<
  10717. "Failed " << pluralise(totals.testCases.failed, "test case") << ", "
  10718. "failed " << pluralise(totals.assertions.failed, "assertion") << '.';
  10719. } else {
  10720. Colour colour(Colour::ResultSuccess);
  10721. out <<
  10722. "Passed " << bothOrAll(totals.testCases.passed)
  10723. << pluralise(totals.testCases.passed, "test case") <<
  10724. " with " << pluralise(totals.assertions.passed, "assertion") << '.';
  10725. }
  10726. }
  10727. // Implementation of CompactReporter formatting
  10728. class AssertionPrinter {
  10729. public:
  10730. AssertionPrinter& operator= (AssertionPrinter const&) = delete;
  10731. AssertionPrinter(AssertionPrinter const&) = delete;
  10732. AssertionPrinter(std::ostream& _stream, AssertionStats const& _stats, bool _printInfoMessages)
  10733. : stream(_stream)
  10734. , result(_stats.assertionResult)
  10735. , messages(_stats.infoMessages)
  10736. , itMessage(_stats.infoMessages.begin())
  10737. , printInfoMessages(_printInfoMessages) {}
  10738. void print() {
  10739. printSourceInfo();
  10740. itMessage = messages.begin();
  10741. switch (result.getResultType()) {
  10742. case ResultWas::Ok:
  10743. printResultType(Colour::ResultSuccess, passedString());
  10744. printOriginalExpression();
  10745. printReconstructedExpression();
  10746. if (!result.hasExpression())
  10747. printRemainingMessages(Colour::None);
  10748. else
  10749. printRemainingMessages();
  10750. break;
  10751. case ResultWas::ExpressionFailed:
  10752. if (result.isOk())
  10753. printResultType(Colour::ResultSuccess, failedString() + std::string(" - but was ok"));
  10754. else
  10755. printResultType(Colour::Error, failedString());
  10756. printOriginalExpression();
  10757. printReconstructedExpression();
  10758. printRemainingMessages();
  10759. break;
  10760. case ResultWas::ThrewException:
  10761. printResultType(Colour::Error, failedString());
  10762. printIssue("unexpected exception with message:");
  10763. printMessage();
  10764. printExpressionWas();
  10765. printRemainingMessages();
  10766. break;
  10767. case ResultWas::FatalErrorCondition:
  10768. printResultType(Colour::Error, failedString());
  10769. printIssue("fatal error condition with message:");
  10770. printMessage();
  10771. printExpressionWas();
  10772. printRemainingMessages();
  10773. break;
  10774. case ResultWas::DidntThrowException:
  10775. printResultType(Colour::Error, failedString());
  10776. printIssue("expected exception, got none");
  10777. printExpressionWas();
  10778. printRemainingMessages();
  10779. break;
  10780. case ResultWas::Info:
  10781. printResultType(Colour::None, "info");
  10782. printMessage();
  10783. printRemainingMessages();
  10784. break;
  10785. case ResultWas::Warning:
  10786. printResultType(Colour::None, "warning");
  10787. printMessage();
  10788. printRemainingMessages();
  10789. break;
  10790. case ResultWas::ExplicitFailure:
  10791. printResultType(Colour::Error, failedString());
  10792. printIssue("explicitly");
  10793. printRemainingMessages(Colour::None);
  10794. break;
  10795. // These cases are here to prevent compiler warnings
  10796. case ResultWas::Unknown:
  10797. case ResultWas::FailureBit:
  10798. case ResultWas::Exception:
  10799. printResultType(Colour::Error, "** internal error **");
  10800. break;
  10801. }
  10802. }
  10803. private:
  10804. void printSourceInfo() const {
  10805. Colour colourGuard(Colour::FileName);
  10806. stream << result.getSourceInfo() << ':';
  10807. }
  10808. void printResultType(Colour::Code colour, std::string const& passOrFail) const {
  10809. if (!passOrFail.empty()) {
  10810. {
  10811. Colour colourGuard(colour);
  10812. stream << ' ' << passOrFail;
  10813. }
  10814. stream << ':';
  10815. }
  10816. }
  10817. void printIssue(std::string const& issue) const {
  10818. stream << ' ' << issue;
  10819. }
  10820. void printExpressionWas() {
  10821. if (result.hasExpression()) {
  10822. stream << ';';
  10823. {
  10824. Colour colour(dimColour());
  10825. stream << " expression was:";
  10826. }
  10827. printOriginalExpression();
  10828. }
  10829. }
  10830. void printOriginalExpression() const {
  10831. if (result.hasExpression()) {
  10832. stream << ' ' << result.getExpression();
  10833. }
  10834. }
  10835. void printReconstructedExpression() const {
  10836. if (result.hasExpandedExpression()) {
  10837. {
  10838. Colour colour(dimColour());
  10839. stream << " for: ";
  10840. }
  10841. stream << result.getExpandedExpression();
  10842. }
  10843. }
  10844. void printMessage() {
  10845. if (itMessage != messages.end()) {
  10846. stream << " '" << itMessage->message << '\'';
  10847. ++itMessage;
  10848. }
  10849. }
  10850. void printRemainingMessages(Colour::Code colour = dimColour()) {
  10851. if (itMessage == messages.end())
  10852. return;
  10853. // using messages.end() directly yields (or auto) compilation error:
  10854. std::vector<MessageInfo>::const_iterator itEnd = messages.end();
  10855. const std::size_t N = static_cast<std::size_t>(std::distance(itMessage, itEnd));
  10856. {
  10857. Colour colourGuard(colour);
  10858. stream << " with " << pluralise(N, "message") << ':';
  10859. }
  10860. for (; itMessage != itEnd; ) {
  10861. // If this assertion is a warning ignore any INFO messages
  10862. if (printInfoMessages || itMessage->type != ResultWas::Info) {
  10863. stream << " '" << itMessage->message << '\'';
  10864. if (++itMessage != itEnd) {
  10865. Colour colourGuard(dimColour());
  10866. stream << " and";
  10867. }
  10868. }
  10869. }
  10870. }
  10871. private:
  10872. std::ostream& stream;
  10873. AssertionResult const& result;
  10874. std::vector<MessageInfo> messages;
  10875. std::vector<MessageInfo>::const_iterator itMessage;
  10876. bool printInfoMessages;
  10877. };
  10878. } // anon namespace
  10879. std::string CompactReporter::getDescription() {
  10880. return "Reports test results on a single line, suitable for IDEs";
  10881. }
  10882. ReporterPreferences CompactReporter::getPreferences() const {
  10883. return m_reporterPrefs;
  10884. }
  10885. void CompactReporter::noMatchingTestCases( std::string const& spec ) {
  10886. stream << "No test cases matched '" << spec << '\'' << std::endl;
  10887. }
  10888. void CompactReporter::assertionStarting( AssertionInfo const& ) {}
  10889. bool CompactReporter::assertionEnded( AssertionStats const& _assertionStats ) {
  10890. AssertionResult const& result = _assertionStats.assertionResult;
  10891. bool printInfoMessages = true;
  10892. // Drop out if result was successful and we're not printing those
  10893. if( !m_config->includeSuccessfulResults() && result.isOk() ) {
  10894. if( result.getResultType() != ResultWas::Warning )
  10895. return false;
  10896. printInfoMessages = false;
  10897. }
  10898. AssertionPrinter printer( stream, _assertionStats, printInfoMessages );
  10899. printer.print();
  10900. stream << std::endl;
  10901. return true;
  10902. }
  10903. void CompactReporter::sectionEnded(SectionStats const& _sectionStats) {
  10904. if (m_config->showDurations() == ShowDurations::Always) {
  10905. stream << getFormattedDuration(_sectionStats.durationInSeconds) << " s: " << _sectionStats.sectionInfo.name << std::endl;
  10906. }
  10907. }
  10908. void CompactReporter::testRunEnded( TestRunStats const& _testRunStats ) {
  10909. printTotals( stream, _testRunStats.totals );
  10910. stream << '\n' << std::endl;
  10911. StreamingReporterBase::testRunEnded( _testRunStats );
  10912. }
  10913. CompactReporter::~CompactReporter() {}
  10914. CATCH_REGISTER_REPORTER( "compact", CompactReporter )
  10915. } // end namespace Catch
  10916. // end catch_reporter_compact.cpp
  10917. // start catch_reporter_console.cpp
  10918. #include <cfloat>
  10919. #include <cstdio>
  10920. #if defined(_MSC_VER)
  10921. #pragma warning(push)
  10922. #pragma warning(disable:4061) // Not all labels are EXPLICITLY handled in switch
  10923. // Note that 4062 (not all labels are handled
  10924. // and default is missing) is enabled
  10925. #endif
  10926. namespace Catch {
  10927. namespace {
  10928. // Formatter impl for ConsoleReporter
  10929. class ConsoleAssertionPrinter {
  10930. public:
  10931. ConsoleAssertionPrinter& operator= (ConsoleAssertionPrinter const&) = delete;
  10932. ConsoleAssertionPrinter(ConsoleAssertionPrinter const&) = delete;
  10933. ConsoleAssertionPrinter(std::ostream& _stream, AssertionStats const& _stats, bool _printInfoMessages)
  10934. : stream(_stream),
  10935. stats(_stats),
  10936. result(_stats.assertionResult),
  10937. colour(Colour::None),
  10938. message(result.getMessage()),
  10939. messages(_stats.infoMessages),
  10940. printInfoMessages(_printInfoMessages) {
  10941. switch (result.getResultType()) {
  10942. case ResultWas::Ok:
  10943. colour = Colour::Success;
  10944. passOrFail = "PASSED";
  10945. //if( result.hasMessage() )
  10946. if (_stats.infoMessages.size() == 1)
  10947. messageLabel = "with message";
  10948. if (_stats.infoMessages.size() > 1)
  10949. messageLabel = "with messages";
  10950. break;
  10951. case ResultWas::ExpressionFailed:
  10952. if (result.isOk()) {
  10953. colour = Colour::Success;
  10954. passOrFail = "FAILED - but was ok";
  10955. } else {
  10956. colour = Colour::Error;
  10957. passOrFail = "FAILED";
  10958. }
  10959. if (_stats.infoMessages.size() == 1)
  10960. messageLabel = "with message";
  10961. if (_stats.infoMessages.size() > 1)
  10962. messageLabel = "with messages";
  10963. break;
  10964. case ResultWas::ThrewException:
  10965. colour = Colour::Error;
  10966. passOrFail = "FAILED";
  10967. messageLabel = "due to unexpected exception with ";
  10968. if (_stats.infoMessages.size() == 1)
  10969. messageLabel += "message";
  10970. if (_stats.infoMessages.size() > 1)
  10971. messageLabel += "messages";
  10972. break;
  10973. case ResultWas::FatalErrorCondition:
  10974. colour = Colour::Error;
  10975. passOrFail = "FAILED";
  10976. messageLabel = "due to a fatal error condition";
  10977. break;
  10978. case ResultWas::DidntThrowException:
  10979. colour = Colour::Error;
  10980. passOrFail = "FAILED";
  10981. messageLabel = "because no exception was thrown where one was expected";
  10982. break;
  10983. case ResultWas::Info:
  10984. messageLabel = "info";
  10985. break;
  10986. case ResultWas::Warning:
  10987. messageLabel = "warning";
  10988. break;
  10989. case ResultWas::ExplicitFailure:
  10990. passOrFail = "FAILED";
  10991. colour = Colour::Error;
  10992. if (_stats.infoMessages.size() == 1)
  10993. messageLabel = "explicitly with message";
  10994. if (_stats.infoMessages.size() > 1)
  10995. messageLabel = "explicitly with messages";
  10996. break;
  10997. // These cases are here to prevent compiler warnings
  10998. case ResultWas::Unknown:
  10999. case ResultWas::FailureBit:
  11000. case ResultWas::Exception:
  11001. passOrFail = "** internal error **";
  11002. colour = Colour::Error;
  11003. break;
  11004. }
  11005. }
  11006. void print() const {
  11007. printSourceInfo();
  11008. if (stats.totals.assertions.total() > 0) {
  11009. printResultType();
  11010. printOriginalExpression();
  11011. printReconstructedExpression();
  11012. } else {
  11013. stream << '\n';
  11014. }
  11015. printMessage();
  11016. }
  11017. private:
  11018. void printResultType() const {
  11019. if (!passOrFail.empty()) {
  11020. Colour colourGuard(colour);
  11021. stream << passOrFail << ":\n";
  11022. }
  11023. }
  11024. void printOriginalExpression() const {
  11025. if (result.hasExpression()) {
  11026. Colour colourGuard(Colour::OriginalExpression);
  11027. stream << " ";
  11028. stream << result.getExpressionInMacro();
  11029. stream << '\n';
  11030. }
  11031. }
  11032. void printReconstructedExpression() const {
  11033. if (result.hasExpandedExpression()) {
  11034. stream << "with expansion:\n";
  11035. Colour colourGuard(Colour::ReconstructedExpression);
  11036. stream << Column(result.getExpandedExpression()).indent(2) << '\n';
  11037. }
  11038. }
  11039. void printMessage() const {
  11040. if (!messageLabel.empty())
  11041. stream << messageLabel << ':' << '\n';
  11042. for (auto const& msg : messages) {
  11043. // If this assertion is a warning ignore any INFO messages
  11044. if (printInfoMessages || msg.type != ResultWas::Info)
  11045. stream << Column(msg.message).indent(2) << '\n';
  11046. }
  11047. }
  11048. void printSourceInfo() const {
  11049. Colour colourGuard(Colour::FileName);
  11050. stream << result.getSourceInfo() << ": ";
  11051. }
  11052. std::ostream& stream;
  11053. AssertionStats const& stats;
  11054. AssertionResult const& result;
  11055. Colour::Code colour;
  11056. std::string passOrFail;
  11057. std::string messageLabel;
  11058. std::string message;
  11059. std::vector<MessageInfo> messages;
  11060. bool printInfoMessages;
  11061. };
  11062. std::size_t makeRatio(std::size_t number, std::size_t total) {
  11063. std::size_t ratio = total > 0 ? CATCH_CONFIG_CONSOLE_WIDTH * number / total : 0;
  11064. return (ratio == 0 && number > 0) ? 1 : ratio;
  11065. }
  11066. std::size_t& findMax(std::size_t& i, std::size_t& j, std::size_t& k) {
  11067. if (i > j && i > k)
  11068. return i;
  11069. else if (j > k)
  11070. return j;
  11071. else
  11072. return k;
  11073. }
  11074. struct ColumnInfo {
  11075. enum Justification { Left, Right };
  11076. std::string name;
  11077. int width;
  11078. Justification justification;
  11079. };
  11080. struct ColumnBreak {};
  11081. struct RowBreak {};
  11082. class Duration {
  11083. enum class Unit {
  11084. Auto,
  11085. Nanoseconds,
  11086. Microseconds,
  11087. Milliseconds,
  11088. Seconds,
  11089. Minutes
  11090. };
  11091. static const uint64_t s_nanosecondsInAMicrosecond = 1000;
  11092. static const uint64_t s_nanosecondsInAMillisecond = 1000 * s_nanosecondsInAMicrosecond;
  11093. static const uint64_t s_nanosecondsInASecond = 1000 * s_nanosecondsInAMillisecond;
  11094. static const uint64_t s_nanosecondsInAMinute = 60 * s_nanosecondsInASecond;
  11095. uint64_t m_inNanoseconds;
  11096. Unit m_units;
  11097. public:
  11098. explicit Duration(uint64_t inNanoseconds, Unit units = Unit::Auto)
  11099. : m_inNanoseconds(inNanoseconds),
  11100. m_units(units) {
  11101. if (m_units == Unit::Auto) {
  11102. if (m_inNanoseconds < s_nanosecondsInAMicrosecond)
  11103. m_units = Unit::Nanoseconds;
  11104. else if (m_inNanoseconds < s_nanosecondsInAMillisecond)
  11105. m_units = Unit::Microseconds;
  11106. else if (m_inNanoseconds < s_nanosecondsInASecond)
  11107. m_units = Unit::Milliseconds;
  11108. else if (m_inNanoseconds < s_nanosecondsInAMinute)
  11109. m_units = Unit::Seconds;
  11110. else
  11111. m_units = Unit::Minutes;
  11112. }
  11113. }
  11114. auto value() const -> double {
  11115. switch (m_units) {
  11116. case Unit::Microseconds:
  11117. return m_inNanoseconds / static_cast<double>(s_nanosecondsInAMicrosecond);
  11118. case Unit::Milliseconds:
  11119. return m_inNanoseconds / static_cast<double>(s_nanosecondsInAMillisecond);
  11120. case Unit::Seconds:
  11121. return m_inNanoseconds / static_cast<double>(s_nanosecondsInASecond);
  11122. case Unit::Minutes:
  11123. return m_inNanoseconds / static_cast<double>(s_nanosecondsInAMinute);
  11124. default:
  11125. return static_cast<double>(m_inNanoseconds);
  11126. }
  11127. }
  11128. auto unitsAsString() const -> std::string {
  11129. switch (m_units) {
  11130. case Unit::Nanoseconds:
  11131. return "ns";
  11132. case Unit::Microseconds:
  11133. return "us";
  11134. case Unit::Milliseconds:
  11135. return "ms";
  11136. case Unit::Seconds:
  11137. return "s";
  11138. case Unit::Minutes:
  11139. return "m";
  11140. default:
  11141. return "** internal error **";
  11142. }
  11143. }
  11144. friend auto operator << (std::ostream& os, Duration const& duration) -> std::ostream& {
  11145. return os << duration.value() << " " << duration.unitsAsString();
  11146. }
  11147. };
  11148. } // end anon namespace
  11149. class TablePrinter {
  11150. std::ostream& m_os;
  11151. std::vector<ColumnInfo> m_columnInfos;
  11152. std::ostringstream m_oss;
  11153. int m_currentColumn = -1;
  11154. bool m_isOpen = false;
  11155. public:
  11156. TablePrinter( std::ostream& os, std::vector<ColumnInfo> columnInfos )
  11157. : m_os( os ),
  11158. m_columnInfos( std::move( columnInfos ) ) {}
  11159. auto columnInfos() const -> std::vector<ColumnInfo> const& {
  11160. return m_columnInfos;
  11161. }
  11162. void open() {
  11163. if (!m_isOpen) {
  11164. m_isOpen = true;
  11165. *this << RowBreak();
  11166. for (auto const& info : m_columnInfos)
  11167. *this << info.name << ColumnBreak();
  11168. *this << RowBreak();
  11169. m_os << Catch::getLineOfChars<'-'>() << "\n";
  11170. }
  11171. }
  11172. void close() {
  11173. if (m_isOpen) {
  11174. *this << RowBreak();
  11175. m_os << std::endl;
  11176. m_isOpen = false;
  11177. }
  11178. }
  11179. template<typename T>
  11180. friend TablePrinter& operator << (TablePrinter& tp, T const& value) {
  11181. tp.m_oss << value;
  11182. return tp;
  11183. }
  11184. friend TablePrinter& operator << (TablePrinter& tp, ColumnBreak) {
  11185. auto colStr = tp.m_oss.str();
  11186. // This takes account of utf8 encodings
  11187. auto strSize = Catch::StringRef(colStr).numberOfCharacters();
  11188. tp.m_oss.str("");
  11189. tp.open();
  11190. if (tp.m_currentColumn == static_cast<int>(tp.m_columnInfos.size() - 1)) {
  11191. tp.m_currentColumn = -1;
  11192. tp.m_os << "\n";
  11193. }
  11194. tp.m_currentColumn++;
  11195. auto colInfo = tp.m_columnInfos[tp.m_currentColumn];
  11196. auto padding = (strSize + 2 < static_cast<std::size_t>(colInfo.width))
  11197. ? std::string(colInfo.width - (strSize + 2), ' ')
  11198. : std::string();
  11199. if (colInfo.justification == ColumnInfo::Left)
  11200. tp.m_os << colStr << padding << " ";
  11201. else
  11202. tp.m_os << padding << colStr << " ";
  11203. return tp;
  11204. }
  11205. friend TablePrinter& operator << (TablePrinter& tp, RowBreak) {
  11206. if (tp.m_currentColumn > 0) {
  11207. tp.m_os << "\n";
  11208. tp.m_currentColumn = -1;
  11209. }
  11210. return tp;
  11211. }
  11212. };
  11213. ConsoleReporter::ConsoleReporter(ReporterConfig const& config)
  11214. : StreamingReporterBase(config),
  11215. m_tablePrinter(new TablePrinter(config.stream(),
  11216. {
  11217. { "benchmark name", CATCH_CONFIG_CONSOLE_WIDTH - 32, ColumnInfo::Left },
  11218. { "iters", 8, ColumnInfo::Right },
  11219. { "elapsed ns", 14, ColumnInfo::Right },
  11220. { "average", 14, ColumnInfo::Right }
  11221. })) {}
  11222. ConsoleReporter::~ConsoleReporter() = default;
  11223. std::string ConsoleReporter::getDescription() {
  11224. return "Reports test results as plain lines of text";
  11225. }
  11226. void ConsoleReporter::noMatchingTestCases(std::string const& spec) {
  11227. stream << "No test cases matched '" << spec << '\'' << std::endl;
  11228. }
  11229. void ConsoleReporter::assertionStarting(AssertionInfo const&) {}
  11230. bool ConsoleReporter::assertionEnded(AssertionStats const& _assertionStats) {
  11231. AssertionResult const& result = _assertionStats.assertionResult;
  11232. bool includeResults = m_config->includeSuccessfulResults() || !result.isOk();
  11233. // Drop out if result was successful but we're not printing them.
  11234. if (!includeResults && result.getResultType() != ResultWas::Warning)
  11235. return false;
  11236. lazyPrint();
  11237. ConsoleAssertionPrinter printer(stream, _assertionStats, includeResults);
  11238. printer.print();
  11239. stream << std::endl;
  11240. return true;
  11241. }
  11242. void ConsoleReporter::sectionStarting(SectionInfo const& _sectionInfo) {
  11243. m_headerPrinted = false;
  11244. StreamingReporterBase::sectionStarting(_sectionInfo);
  11245. }
  11246. void ConsoleReporter::sectionEnded(SectionStats const& _sectionStats) {
  11247. m_tablePrinter->close();
  11248. if (_sectionStats.missingAssertions) {
  11249. lazyPrint();
  11250. Colour colour(Colour::ResultError);
  11251. if (m_sectionStack.size() > 1)
  11252. stream << "\nNo assertions in section";
  11253. else
  11254. stream << "\nNo assertions in test case";
  11255. stream << " '" << _sectionStats.sectionInfo.name << "'\n" << std::endl;
  11256. }
  11257. if (m_config->showDurations() == ShowDurations::Always) {
  11258. stream << getFormattedDuration(_sectionStats.durationInSeconds) << " s: " << _sectionStats.sectionInfo.name << std::endl;
  11259. }
  11260. if (m_headerPrinted) {
  11261. m_headerPrinted = false;
  11262. }
  11263. StreamingReporterBase::sectionEnded(_sectionStats);
  11264. }
  11265. void ConsoleReporter::benchmarkStarting(BenchmarkInfo const& info) {
  11266. lazyPrintWithoutClosingBenchmarkTable();
  11267. auto nameCol = Column( info.name ).width( static_cast<std::size_t>( m_tablePrinter->columnInfos()[0].width - 2 ) );
  11268. bool firstLine = true;
  11269. for (auto line : nameCol) {
  11270. if (!firstLine)
  11271. (*m_tablePrinter) << ColumnBreak() << ColumnBreak() << ColumnBreak();
  11272. else
  11273. firstLine = false;
  11274. (*m_tablePrinter) << line << ColumnBreak();
  11275. }
  11276. }
  11277. void ConsoleReporter::benchmarkEnded(BenchmarkStats const& stats) {
  11278. Duration average(stats.elapsedTimeInNanoseconds / stats.iterations);
  11279. (*m_tablePrinter)
  11280. << stats.iterations << ColumnBreak()
  11281. << stats.elapsedTimeInNanoseconds << ColumnBreak()
  11282. << average << ColumnBreak();
  11283. }
  11284. void ConsoleReporter::testCaseEnded(TestCaseStats const& _testCaseStats) {
  11285. m_tablePrinter->close();
  11286. StreamingReporterBase::testCaseEnded(_testCaseStats);
  11287. m_headerPrinted = false;
  11288. }
  11289. void ConsoleReporter::testGroupEnded(TestGroupStats const& _testGroupStats) {
  11290. if (currentGroupInfo.used) {
  11291. printSummaryDivider();
  11292. stream << "Summary for group '" << _testGroupStats.groupInfo.name << "':\n";
  11293. printTotals(_testGroupStats.totals);
  11294. stream << '\n' << std::endl;
  11295. }
  11296. StreamingReporterBase::testGroupEnded(_testGroupStats);
  11297. }
  11298. void ConsoleReporter::testRunEnded(TestRunStats const& _testRunStats) {
  11299. printTotalsDivider(_testRunStats.totals);
  11300. printTotals(_testRunStats.totals);
  11301. stream << std::endl;
  11302. StreamingReporterBase::testRunEnded(_testRunStats);
  11303. }
  11304. void ConsoleReporter::testRunStarting(TestRunInfo const& _testInfo) {
  11305. StreamingReporterBase::testRunStarting(_testInfo);
  11306. printTestFilters();
  11307. }
  11308. void ConsoleReporter::lazyPrint() {
  11309. m_tablePrinter->close();
  11310. lazyPrintWithoutClosingBenchmarkTable();
  11311. }
  11312. void ConsoleReporter::lazyPrintWithoutClosingBenchmarkTable() {
  11313. if (!currentTestRunInfo.used)
  11314. lazyPrintRunInfo();
  11315. if (!currentGroupInfo.used)
  11316. lazyPrintGroupInfo();
  11317. if (!m_headerPrinted) {
  11318. printTestCaseAndSectionHeader();
  11319. m_headerPrinted = true;
  11320. }
  11321. }
  11322. void ConsoleReporter::lazyPrintRunInfo() {
  11323. stream << '\n' << getLineOfChars<'~'>() << '\n';
  11324. Colour colour(Colour::SecondaryText);
  11325. stream << currentTestRunInfo->name
  11326. << " is a Catch v" << libraryVersion() << " host application.\n"
  11327. << "Run with -? for options\n\n";
  11328. if (m_config->rngSeed() != 0)
  11329. stream << "Randomness seeded to: " << m_config->rngSeed() << "\n\n";
  11330. currentTestRunInfo.used = true;
  11331. }
  11332. void ConsoleReporter::lazyPrintGroupInfo() {
  11333. if (!currentGroupInfo->name.empty() && currentGroupInfo->groupsCounts > 1) {
  11334. printClosedHeader("Group: " + currentGroupInfo->name);
  11335. currentGroupInfo.used = true;
  11336. }
  11337. }
  11338. void ConsoleReporter::printTestCaseAndSectionHeader() {
  11339. assert(!m_sectionStack.empty());
  11340. printOpenHeader(currentTestCaseInfo->name);
  11341. if (m_sectionStack.size() > 1) {
  11342. Colour colourGuard(Colour::Headers);
  11343. auto
  11344. it = m_sectionStack.begin() + 1, // Skip first section (test case)
  11345. itEnd = m_sectionStack.end();
  11346. for (; it != itEnd; ++it)
  11347. printHeaderString(it->name, 2);
  11348. }
  11349. SourceLineInfo lineInfo = m_sectionStack.back().lineInfo;
  11350. if (!lineInfo.empty()) {
  11351. stream << getLineOfChars<'-'>() << '\n';
  11352. Colour colourGuard(Colour::FileName);
  11353. stream << lineInfo << '\n';
  11354. }
  11355. stream << getLineOfChars<'.'>() << '\n' << std::endl;
  11356. }
  11357. void ConsoleReporter::printClosedHeader(std::string const& _name) {
  11358. printOpenHeader(_name);
  11359. stream << getLineOfChars<'.'>() << '\n';
  11360. }
  11361. void ConsoleReporter::printOpenHeader(std::string const& _name) {
  11362. stream << getLineOfChars<'-'>() << '\n';
  11363. {
  11364. Colour colourGuard(Colour::Headers);
  11365. printHeaderString(_name);
  11366. }
  11367. }
  11368. // if string has a : in first line will set indent to follow it on
  11369. // subsequent lines
  11370. void ConsoleReporter::printHeaderString(std::string const& _string, std::size_t indent) {
  11371. std::size_t i = _string.find(": ");
  11372. if (i != std::string::npos)
  11373. i += 2;
  11374. else
  11375. i = 0;
  11376. stream << Column(_string).indent(indent + i).initialIndent(indent) << '\n';
  11377. }
  11378. struct SummaryColumn {
  11379. SummaryColumn( std::string _label, Colour::Code _colour )
  11380. : label( std::move( _label ) ),
  11381. colour( _colour ) {}
  11382. SummaryColumn addRow( std::size_t count ) {
  11383. ReusableStringStream rss;
  11384. rss << count;
  11385. std::string row = rss.str();
  11386. for (auto& oldRow : rows) {
  11387. while (oldRow.size() < row.size())
  11388. oldRow = ' ' + oldRow;
  11389. while (oldRow.size() > row.size())
  11390. row = ' ' + row;
  11391. }
  11392. rows.push_back(row);
  11393. return *this;
  11394. }
  11395. std::string label;
  11396. Colour::Code colour;
  11397. std::vector<std::string> rows;
  11398. };
  11399. void ConsoleReporter::printTotals( Totals const& totals ) {
  11400. if (totals.testCases.total() == 0) {
  11401. stream << Colour(Colour::Warning) << "No tests ran\n";
  11402. } else if (totals.assertions.total() > 0 && totals.testCases.allPassed()) {
  11403. stream << Colour(Colour::ResultSuccess) << "All tests passed";
  11404. stream << " ("
  11405. << pluralise(totals.assertions.passed, "assertion") << " in "
  11406. << pluralise(totals.testCases.passed, "test case") << ')'
  11407. << '\n';
  11408. } else {
  11409. std::vector<SummaryColumn> columns;
  11410. columns.push_back(SummaryColumn("", Colour::None)
  11411. .addRow(totals.testCases.total())
  11412. .addRow(totals.assertions.total()));
  11413. columns.push_back(SummaryColumn("passed", Colour::Success)
  11414. .addRow(totals.testCases.passed)
  11415. .addRow(totals.assertions.passed));
  11416. columns.push_back(SummaryColumn("failed", Colour::ResultError)
  11417. .addRow(totals.testCases.failed)
  11418. .addRow(totals.assertions.failed));
  11419. columns.push_back(SummaryColumn("failed as expected", Colour::ResultExpectedFailure)
  11420. .addRow(totals.testCases.failedButOk)
  11421. .addRow(totals.assertions.failedButOk));
  11422. printSummaryRow("test cases", columns, 0);
  11423. printSummaryRow("assertions", columns, 1);
  11424. }
  11425. }
  11426. void ConsoleReporter::printSummaryRow(std::string const& label, std::vector<SummaryColumn> const& cols, std::size_t row) {
  11427. for (auto col : cols) {
  11428. std::string value = col.rows[row];
  11429. if (col.label.empty()) {
  11430. stream << label << ": ";
  11431. if (value != "0")
  11432. stream << value;
  11433. else
  11434. stream << Colour(Colour::Warning) << "- none -";
  11435. } else if (value != "0") {
  11436. stream << Colour(Colour::LightGrey) << " | ";
  11437. stream << Colour(col.colour)
  11438. << value << ' ' << col.label;
  11439. }
  11440. }
  11441. stream << '\n';
  11442. }
  11443. void ConsoleReporter::printTotalsDivider(Totals const& totals) {
  11444. if (totals.testCases.total() > 0) {
  11445. std::size_t failedRatio = makeRatio(totals.testCases.failed, totals.testCases.total());
  11446. std::size_t failedButOkRatio = makeRatio(totals.testCases.failedButOk, totals.testCases.total());
  11447. std::size_t passedRatio = makeRatio(totals.testCases.passed, totals.testCases.total());
  11448. while (failedRatio + failedButOkRatio + passedRatio < CATCH_CONFIG_CONSOLE_WIDTH - 1)
  11449. findMax(failedRatio, failedButOkRatio, passedRatio)++;
  11450. while (failedRatio + failedButOkRatio + passedRatio > CATCH_CONFIG_CONSOLE_WIDTH - 1)
  11451. findMax(failedRatio, failedButOkRatio, passedRatio)--;
  11452. stream << Colour(Colour::Error) << std::string(failedRatio, '=');
  11453. stream << Colour(Colour::ResultExpectedFailure) << std::string(failedButOkRatio, '=');
  11454. if (totals.testCases.allPassed())
  11455. stream << Colour(Colour::ResultSuccess) << std::string(passedRatio, '=');
  11456. else
  11457. stream << Colour(Colour::Success) << std::string(passedRatio, '=');
  11458. } else {
  11459. stream << Colour(Colour::Warning) << std::string(CATCH_CONFIG_CONSOLE_WIDTH - 1, '=');
  11460. }
  11461. stream << '\n';
  11462. }
  11463. void ConsoleReporter::printSummaryDivider() {
  11464. stream << getLineOfChars<'-'>() << '\n';
  11465. }
  11466. void ConsoleReporter::printTestFilters() {
  11467. if (m_config->testSpec().hasFilters())
  11468. stream << Colour(Colour::BrightYellow) << "Filters: " << serializeFilters( m_config->getTestsOrTags() ) << '\n';
  11469. }
  11470. CATCH_REGISTER_REPORTER("console", ConsoleReporter)
  11471. } // end namespace Catch
  11472. #if defined(_MSC_VER)
  11473. #pragma warning(pop)
  11474. #endif
  11475. // end catch_reporter_console.cpp
  11476. // start catch_reporter_junit.cpp
  11477. #include <cassert>
  11478. #include <sstream>
  11479. #include <ctime>
  11480. #include <algorithm>
  11481. namespace Catch {
  11482. namespace {
  11483. std::string getCurrentTimestamp() {
  11484. // Beware, this is not reentrant because of backward compatibility issues
  11485. // Also, UTC only, again because of backward compatibility (%z is C++11)
  11486. time_t rawtime;
  11487. std::time(&rawtime);
  11488. auto const timeStampSize = sizeof("2017-01-16T17:06:45Z");
  11489. #ifdef _MSC_VER
  11490. std::tm timeInfo = {};
  11491. gmtime_s(&timeInfo, &rawtime);
  11492. #else
  11493. std::tm* timeInfo;
  11494. timeInfo = std::gmtime(&rawtime);
  11495. #endif
  11496. char timeStamp[timeStampSize];
  11497. const char * const fmt = "%Y-%m-%dT%H:%M:%SZ";
  11498. #ifdef _MSC_VER
  11499. std::strftime(timeStamp, timeStampSize, fmt, &timeInfo);
  11500. #else
  11501. std::strftime(timeStamp, timeStampSize, fmt, timeInfo);
  11502. #endif
  11503. return std::string(timeStamp);
  11504. }
  11505. std::string fileNameTag(const std::vector<std::string> &tags) {
  11506. auto it = std::find_if(begin(tags),
  11507. end(tags),
  11508. [] (std::string const& tag) {return tag.front() == '#'; });
  11509. if (it != tags.end())
  11510. return it->substr(1);
  11511. return std::string();
  11512. }
  11513. } // anonymous namespace
  11514. JunitReporter::JunitReporter( ReporterConfig const& _config )
  11515. : CumulativeReporterBase( _config ),
  11516. xml( _config.stream() )
  11517. {
  11518. m_reporterPrefs.shouldRedirectStdOut = true;
  11519. m_reporterPrefs.shouldReportAllAssertions = true;
  11520. }
  11521. JunitReporter::~JunitReporter() {}
  11522. std::string JunitReporter::getDescription() {
  11523. return "Reports test results in an XML format that looks like Ant's junitreport target";
  11524. }
  11525. void JunitReporter::noMatchingTestCases( std::string const& /*spec*/ ) {}
  11526. void JunitReporter::testRunStarting( TestRunInfo const& runInfo ) {
  11527. CumulativeReporterBase::testRunStarting( runInfo );
  11528. xml.startElement( "testsuites" );
  11529. }
  11530. void JunitReporter::testGroupStarting( GroupInfo const& groupInfo ) {
  11531. suiteTimer.start();
  11532. stdOutForSuite.clear();
  11533. stdErrForSuite.clear();
  11534. unexpectedExceptions = 0;
  11535. CumulativeReporterBase::testGroupStarting( groupInfo );
  11536. }
  11537. void JunitReporter::testCaseStarting( TestCaseInfo const& testCaseInfo ) {
  11538. m_okToFail = testCaseInfo.okToFail();
  11539. }
  11540. bool JunitReporter::assertionEnded( AssertionStats const& assertionStats ) {
  11541. if( assertionStats.assertionResult.getResultType() == ResultWas::ThrewException && !m_okToFail )
  11542. unexpectedExceptions++;
  11543. return CumulativeReporterBase::assertionEnded( assertionStats );
  11544. }
  11545. void JunitReporter::testCaseEnded( TestCaseStats const& testCaseStats ) {
  11546. stdOutForSuite += testCaseStats.stdOut;
  11547. stdErrForSuite += testCaseStats.stdErr;
  11548. CumulativeReporterBase::testCaseEnded( testCaseStats );
  11549. }
  11550. void JunitReporter::testGroupEnded( TestGroupStats const& testGroupStats ) {
  11551. double suiteTime = suiteTimer.getElapsedSeconds();
  11552. CumulativeReporterBase::testGroupEnded( testGroupStats );
  11553. writeGroup( *m_testGroups.back(), suiteTime );
  11554. }
  11555. void JunitReporter::testRunEndedCumulative() {
  11556. xml.endElement();
  11557. }
  11558. void JunitReporter::writeGroup( TestGroupNode const& groupNode, double suiteTime ) {
  11559. XmlWriter::ScopedElement e = xml.scopedElement( "testsuite" );
  11560. TestGroupStats const& stats = groupNode.value;
  11561. xml.writeAttribute( "name", stats.groupInfo.name );
  11562. xml.writeAttribute( "errors", unexpectedExceptions );
  11563. xml.writeAttribute( "failures", stats.totals.assertions.failed-unexpectedExceptions );
  11564. xml.writeAttribute( "tests", stats.totals.assertions.total() );
  11565. xml.writeAttribute( "hostname", "tbd" ); // !TBD
  11566. if( m_config->showDurations() == ShowDurations::Never )
  11567. xml.writeAttribute( "time", "" );
  11568. else
  11569. xml.writeAttribute( "time", suiteTime );
  11570. xml.writeAttribute( "timestamp", getCurrentTimestamp() );
  11571. // Write properties if there are any
  11572. if (m_config->hasTestFilters() || m_config->rngSeed() != 0) {
  11573. auto properties = xml.scopedElement("properties");
  11574. if (m_config->hasTestFilters()) {
  11575. xml.scopedElement("property")
  11576. .writeAttribute("name", "filters")
  11577. .writeAttribute("value", serializeFilters(m_config->getTestsOrTags()));
  11578. }
  11579. if (m_config->rngSeed() != 0) {
  11580. xml.scopedElement("property")
  11581. .writeAttribute("name", "random-seed")
  11582. .writeAttribute("value", m_config->rngSeed());
  11583. }
  11584. }
  11585. // Write test cases
  11586. for( auto const& child : groupNode.children )
  11587. writeTestCase( *child );
  11588. xml.scopedElement( "system-out" ).writeText( trim( stdOutForSuite ), false );
  11589. xml.scopedElement( "system-err" ).writeText( trim( stdErrForSuite ), false );
  11590. }
  11591. void JunitReporter::writeTestCase( TestCaseNode const& testCaseNode ) {
  11592. TestCaseStats const& stats = testCaseNode.value;
  11593. // All test cases have exactly one section - which represents the
  11594. // test case itself. That section may have 0-n nested sections
  11595. assert( testCaseNode.children.size() == 1 );
  11596. SectionNode const& rootSection = *testCaseNode.children.front();
  11597. std::string className = stats.testInfo.className;
  11598. if( className.empty() ) {
  11599. className = fileNameTag(stats.testInfo.tags);
  11600. if ( className.empty() )
  11601. className = "global";
  11602. }
  11603. if ( !m_config->name().empty() )
  11604. className = m_config->name() + "." + className;
  11605. writeSection( className, "", rootSection );
  11606. }
  11607. void JunitReporter::writeSection( std::string const& className,
  11608. std::string const& rootName,
  11609. SectionNode const& sectionNode ) {
  11610. std::string name = trim( sectionNode.stats.sectionInfo.name );
  11611. if( !rootName.empty() )
  11612. name = rootName + '/' + name;
  11613. if( !sectionNode.assertions.empty() ||
  11614. !sectionNode.stdOut.empty() ||
  11615. !sectionNode.stdErr.empty() ) {
  11616. XmlWriter::ScopedElement e = xml.scopedElement( "testcase" );
  11617. if( className.empty() ) {
  11618. xml.writeAttribute( "classname", name );
  11619. xml.writeAttribute( "name", "root" );
  11620. }
  11621. else {
  11622. xml.writeAttribute( "classname", className );
  11623. xml.writeAttribute( "name", name );
  11624. }
  11625. xml.writeAttribute( "time", ::Catch::Detail::stringify( sectionNode.stats.durationInSeconds ) );
  11626. writeAssertions( sectionNode );
  11627. if( !sectionNode.stdOut.empty() )
  11628. xml.scopedElement( "system-out" ).writeText( trim( sectionNode.stdOut ), false );
  11629. if( !sectionNode.stdErr.empty() )
  11630. xml.scopedElement( "system-err" ).writeText( trim( sectionNode.stdErr ), false );
  11631. }
  11632. for( auto const& childNode : sectionNode.childSections )
  11633. if( className.empty() )
  11634. writeSection( name, "", *childNode );
  11635. else
  11636. writeSection( className, name, *childNode );
  11637. }
  11638. void JunitReporter::writeAssertions( SectionNode const& sectionNode ) {
  11639. for( auto const& assertion : sectionNode.assertions )
  11640. writeAssertion( assertion );
  11641. }
  11642. void JunitReporter::writeAssertion( AssertionStats const& stats ) {
  11643. AssertionResult const& result = stats.assertionResult;
  11644. if( !result.isOk() ) {
  11645. std::string elementName;
  11646. switch( result.getResultType() ) {
  11647. case ResultWas::ThrewException:
  11648. case ResultWas::FatalErrorCondition:
  11649. elementName = "error";
  11650. break;
  11651. case ResultWas::ExplicitFailure:
  11652. elementName = "failure";
  11653. break;
  11654. case ResultWas::ExpressionFailed:
  11655. elementName = "failure";
  11656. break;
  11657. case ResultWas::DidntThrowException:
  11658. elementName = "failure";
  11659. break;
  11660. // We should never see these here:
  11661. case ResultWas::Info:
  11662. case ResultWas::Warning:
  11663. case ResultWas::Ok:
  11664. case ResultWas::Unknown:
  11665. case ResultWas::FailureBit:
  11666. case ResultWas::Exception:
  11667. elementName = "internalError";
  11668. break;
  11669. }
  11670. XmlWriter::ScopedElement e = xml.scopedElement( elementName );
  11671. xml.writeAttribute( "message", result.getExpandedExpression() );
  11672. xml.writeAttribute( "type", result.getTestMacroName() );
  11673. ReusableStringStream rss;
  11674. if( !result.getMessage().empty() )
  11675. rss << result.getMessage() << '\n';
  11676. for( auto const& msg : stats.infoMessages )
  11677. if( msg.type == ResultWas::Info )
  11678. rss << msg.message << '\n';
  11679. rss << "at " << result.getSourceInfo();
  11680. xml.writeText( rss.str(), false );
  11681. }
  11682. }
  11683. CATCH_REGISTER_REPORTER( "junit", JunitReporter )
  11684. } // end namespace Catch
  11685. // end catch_reporter_junit.cpp
  11686. // start catch_reporter_listening.cpp
  11687. #include <cassert>
  11688. namespace Catch {
  11689. ListeningReporter::ListeningReporter() {
  11690. // We will assume that listeners will always want all assertions
  11691. m_preferences.shouldReportAllAssertions = true;
  11692. }
  11693. void ListeningReporter::addListener( IStreamingReporterPtr&& listener ) {
  11694. m_listeners.push_back( std::move( listener ) );
  11695. }
  11696. void ListeningReporter::addReporter(IStreamingReporterPtr&& reporter) {
  11697. assert(!m_reporter && "Listening reporter can wrap only 1 real reporter");
  11698. m_reporter = std::move( reporter );
  11699. m_preferences.shouldRedirectStdOut = m_reporter->getPreferences().shouldRedirectStdOut;
  11700. }
  11701. ReporterPreferences ListeningReporter::getPreferences() const {
  11702. return m_preferences;
  11703. }
  11704. std::set<Verbosity> ListeningReporter::getSupportedVerbosities() {
  11705. return std::set<Verbosity>{ };
  11706. }
  11707. void ListeningReporter::noMatchingTestCases( std::string const& spec ) {
  11708. for ( auto const& listener : m_listeners ) {
  11709. listener->noMatchingTestCases( spec );
  11710. }
  11711. m_reporter->noMatchingTestCases( spec );
  11712. }
  11713. void ListeningReporter::benchmarkStarting( BenchmarkInfo const& benchmarkInfo ) {
  11714. for ( auto const& listener : m_listeners ) {
  11715. listener->benchmarkStarting( benchmarkInfo );
  11716. }
  11717. m_reporter->benchmarkStarting( benchmarkInfo );
  11718. }
  11719. void ListeningReporter::benchmarkEnded( BenchmarkStats const& benchmarkStats ) {
  11720. for ( auto const& listener : m_listeners ) {
  11721. listener->benchmarkEnded( benchmarkStats );
  11722. }
  11723. m_reporter->benchmarkEnded( benchmarkStats );
  11724. }
  11725. void ListeningReporter::testRunStarting( TestRunInfo const& testRunInfo ) {
  11726. for ( auto const& listener : m_listeners ) {
  11727. listener->testRunStarting( testRunInfo );
  11728. }
  11729. m_reporter->testRunStarting( testRunInfo );
  11730. }
  11731. void ListeningReporter::testGroupStarting( GroupInfo const& groupInfo ) {
  11732. for ( auto const& listener : m_listeners ) {
  11733. listener->testGroupStarting( groupInfo );
  11734. }
  11735. m_reporter->testGroupStarting( groupInfo );
  11736. }
  11737. void ListeningReporter::testCaseStarting( TestCaseInfo const& testInfo ) {
  11738. for ( auto const& listener : m_listeners ) {
  11739. listener->testCaseStarting( testInfo );
  11740. }
  11741. m_reporter->testCaseStarting( testInfo );
  11742. }
  11743. void ListeningReporter::sectionStarting( SectionInfo const& sectionInfo ) {
  11744. for ( auto const& listener : m_listeners ) {
  11745. listener->sectionStarting( sectionInfo );
  11746. }
  11747. m_reporter->sectionStarting( sectionInfo );
  11748. }
  11749. void ListeningReporter::assertionStarting( AssertionInfo const& assertionInfo ) {
  11750. for ( auto const& listener : m_listeners ) {
  11751. listener->assertionStarting( assertionInfo );
  11752. }
  11753. m_reporter->assertionStarting( assertionInfo );
  11754. }
  11755. // The return value indicates if the messages buffer should be cleared:
  11756. bool ListeningReporter::assertionEnded( AssertionStats const& assertionStats ) {
  11757. for( auto const& listener : m_listeners ) {
  11758. static_cast<void>( listener->assertionEnded( assertionStats ) );
  11759. }
  11760. return m_reporter->assertionEnded( assertionStats );
  11761. }
  11762. void ListeningReporter::sectionEnded( SectionStats const& sectionStats ) {
  11763. for ( auto const& listener : m_listeners ) {
  11764. listener->sectionEnded( sectionStats );
  11765. }
  11766. m_reporter->sectionEnded( sectionStats );
  11767. }
  11768. void ListeningReporter::testCaseEnded( TestCaseStats const& testCaseStats ) {
  11769. for ( auto const& listener : m_listeners ) {
  11770. listener->testCaseEnded( testCaseStats );
  11771. }
  11772. m_reporter->testCaseEnded( testCaseStats );
  11773. }
  11774. void ListeningReporter::testGroupEnded( TestGroupStats const& testGroupStats ) {
  11775. for ( auto const& listener : m_listeners ) {
  11776. listener->testGroupEnded( testGroupStats );
  11777. }
  11778. m_reporter->testGroupEnded( testGroupStats );
  11779. }
  11780. void ListeningReporter::testRunEnded( TestRunStats const& testRunStats ) {
  11781. for ( auto const& listener : m_listeners ) {
  11782. listener->testRunEnded( testRunStats );
  11783. }
  11784. m_reporter->testRunEnded( testRunStats );
  11785. }
  11786. void ListeningReporter::skipTest( TestCaseInfo const& testInfo ) {
  11787. for ( auto const& listener : m_listeners ) {
  11788. listener->skipTest( testInfo );
  11789. }
  11790. m_reporter->skipTest( testInfo );
  11791. }
  11792. bool ListeningReporter::isMulti() const {
  11793. return true;
  11794. }
  11795. } // end namespace Catch
  11796. // end catch_reporter_listening.cpp
  11797. // start catch_reporter_xml.cpp
  11798. #if defined(_MSC_VER)
  11799. #pragma warning(push)
  11800. #pragma warning(disable:4061) // Not all labels are EXPLICITLY handled in switch
  11801. // Note that 4062 (not all labels are handled
  11802. // and default is missing) is enabled
  11803. #endif
  11804. namespace Catch {
  11805. XmlReporter::XmlReporter( ReporterConfig const& _config )
  11806. : StreamingReporterBase( _config ),
  11807. m_xml(_config.stream())
  11808. {
  11809. m_reporterPrefs.shouldRedirectStdOut = true;
  11810. m_reporterPrefs.shouldReportAllAssertions = true;
  11811. }
  11812. XmlReporter::~XmlReporter() = default;
  11813. std::string XmlReporter::getDescription() {
  11814. return "Reports test results as an XML document";
  11815. }
  11816. std::string XmlReporter::getStylesheetRef() const {
  11817. return std::string();
  11818. }
  11819. void XmlReporter::writeSourceInfo( SourceLineInfo const& sourceInfo ) {
  11820. m_xml
  11821. .writeAttribute( "filename", sourceInfo.file )
  11822. .writeAttribute( "line", sourceInfo.line );
  11823. }
  11824. void XmlReporter::noMatchingTestCases( std::string const& s ) {
  11825. StreamingReporterBase::noMatchingTestCases( s );
  11826. }
  11827. void XmlReporter::testRunStarting( TestRunInfo const& testInfo ) {
  11828. StreamingReporterBase::testRunStarting( testInfo );
  11829. std::string stylesheetRef = getStylesheetRef();
  11830. if( !stylesheetRef.empty() )
  11831. m_xml.writeStylesheetRef( stylesheetRef );
  11832. m_xml.startElement( "Catch" );
  11833. if( !m_config->name().empty() )
  11834. m_xml.writeAttribute( "name", m_config->name() );
  11835. if (m_config->testSpec().hasFilters())
  11836. m_xml.writeAttribute( "filters", serializeFilters( m_config->getTestsOrTags() ) );
  11837. if( m_config->rngSeed() != 0 )
  11838. m_xml.scopedElement( "Randomness" )
  11839. .writeAttribute( "seed", m_config->rngSeed() );
  11840. }
  11841. void XmlReporter::testGroupStarting( GroupInfo const& groupInfo ) {
  11842. StreamingReporterBase::testGroupStarting( groupInfo );
  11843. m_xml.startElement( "Group" )
  11844. .writeAttribute( "name", groupInfo.name );
  11845. }
  11846. void XmlReporter::testCaseStarting( TestCaseInfo const& testInfo ) {
  11847. StreamingReporterBase::testCaseStarting(testInfo);
  11848. m_xml.startElement( "TestCase" )
  11849. .writeAttribute( "name", trim( testInfo.name ) )
  11850. .writeAttribute( "description", testInfo.description )
  11851. .writeAttribute( "tags", testInfo.tagsAsString() );
  11852. writeSourceInfo( testInfo.lineInfo );
  11853. if ( m_config->showDurations() == ShowDurations::Always )
  11854. m_testCaseTimer.start();
  11855. m_xml.ensureTagClosed();
  11856. }
  11857. void XmlReporter::sectionStarting( SectionInfo const& sectionInfo ) {
  11858. StreamingReporterBase::sectionStarting( sectionInfo );
  11859. if( m_sectionDepth++ > 0 ) {
  11860. m_xml.startElement( "Section" )
  11861. .writeAttribute( "name", trim( sectionInfo.name ) );
  11862. writeSourceInfo( sectionInfo.lineInfo );
  11863. m_xml.ensureTagClosed();
  11864. }
  11865. }
  11866. void XmlReporter::assertionStarting( AssertionInfo const& ) { }
  11867. bool XmlReporter::assertionEnded( AssertionStats const& assertionStats ) {
  11868. AssertionResult const& result = assertionStats.assertionResult;
  11869. bool includeResults = m_config->includeSuccessfulResults() || !result.isOk();
  11870. if( includeResults || result.getResultType() == ResultWas::Warning ) {
  11871. // Print any info messages in <Info> tags.
  11872. for( auto const& msg : assertionStats.infoMessages ) {
  11873. if( msg.type == ResultWas::Info && includeResults ) {
  11874. m_xml.scopedElement( "Info" )
  11875. .writeText( msg.message );
  11876. } else if ( msg.type == ResultWas::Warning ) {
  11877. m_xml.scopedElement( "Warning" )
  11878. .writeText( msg.message );
  11879. }
  11880. }
  11881. }
  11882. // Drop out if result was successful but we're not printing them.
  11883. if( !includeResults && result.getResultType() != ResultWas::Warning )
  11884. return true;
  11885. // Print the expression if there is one.
  11886. if( result.hasExpression() ) {
  11887. m_xml.startElement( "Expression" )
  11888. .writeAttribute( "success", result.succeeded() )
  11889. .writeAttribute( "type", result.getTestMacroName() );
  11890. writeSourceInfo( result.getSourceInfo() );
  11891. m_xml.scopedElement( "Original" )
  11892. .writeText( result.getExpression() );
  11893. m_xml.scopedElement( "Expanded" )
  11894. .writeText( result.getExpandedExpression() );
  11895. }
  11896. // And... Print a result applicable to each result type.
  11897. switch( result.getResultType() ) {
  11898. case ResultWas::ThrewException:
  11899. m_xml.startElement( "Exception" );
  11900. writeSourceInfo( result.getSourceInfo() );
  11901. m_xml.writeText( result.getMessage() );
  11902. m_xml.endElement();
  11903. break;
  11904. case ResultWas::FatalErrorCondition:
  11905. m_xml.startElement( "FatalErrorCondition" );
  11906. writeSourceInfo( result.getSourceInfo() );
  11907. m_xml.writeText( result.getMessage() );
  11908. m_xml.endElement();
  11909. break;
  11910. case ResultWas::Info:
  11911. m_xml.scopedElement( "Info" )
  11912. .writeText( result.getMessage() );
  11913. break;
  11914. case ResultWas::Warning:
  11915. // Warning will already have been written
  11916. break;
  11917. case ResultWas::ExplicitFailure:
  11918. m_xml.startElement( "Failure" );
  11919. writeSourceInfo( result.getSourceInfo() );
  11920. m_xml.writeText( result.getMessage() );
  11921. m_xml.endElement();
  11922. break;
  11923. default:
  11924. break;
  11925. }
  11926. if( result.hasExpression() )
  11927. m_xml.endElement();
  11928. return true;
  11929. }
  11930. void XmlReporter::sectionEnded( SectionStats const& sectionStats ) {
  11931. StreamingReporterBase::sectionEnded( sectionStats );
  11932. if( --m_sectionDepth > 0 ) {
  11933. XmlWriter::ScopedElement e = m_xml.scopedElement( "OverallResults" );
  11934. e.writeAttribute( "successes", sectionStats.assertions.passed );
  11935. e.writeAttribute( "failures", sectionStats.assertions.failed );
  11936. e.writeAttribute( "expectedFailures", sectionStats.assertions.failedButOk );
  11937. if ( m_config->showDurations() == ShowDurations::Always )
  11938. e.writeAttribute( "durationInSeconds", sectionStats.durationInSeconds );
  11939. m_xml.endElement();
  11940. }
  11941. }
  11942. void XmlReporter::testCaseEnded( TestCaseStats const& testCaseStats ) {
  11943. StreamingReporterBase::testCaseEnded( testCaseStats );
  11944. XmlWriter::ScopedElement e = m_xml.scopedElement( "OverallResult" );
  11945. e.writeAttribute( "success", testCaseStats.totals.assertions.allOk() );
  11946. if ( m_config->showDurations() == ShowDurations::Always )
  11947. e.writeAttribute( "durationInSeconds", m_testCaseTimer.getElapsedSeconds() );
  11948. if( !testCaseStats.stdOut.empty() )
  11949. m_xml.scopedElement( "StdOut" ).writeText( trim( testCaseStats.stdOut ), false );
  11950. if( !testCaseStats.stdErr.empty() )
  11951. m_xml.scopedElement( "StdErr" ).writeText( trim( testCaseStats.stdErr ), false );
  11952. m_xml.endElement();
  11953. }
  11954. void XmlReporter::testGroupEnded( TestGroupStats const& testGroupStats ) {
  11955. StreamingReporterBase::testGroupEnded( testGroupStats );
  11956. // TODO: Check testGroupStats.aborting and act accordingly.
  11957. m_xml.scopedElement( "OverallResults" )
  11958. .writeAttribute( "successes", testGroupStats.totals.assertions.passed )
  11959. .writeAttribute( "failures", testGroupStats.totals.assertions.failed )
  11960. .writeAttribute( "expectedFailures", testGroupStats.totals.assertions.failedButOk );
  11961. m_xml.endElement();
  11962. }
  11963. void XmlReporter::testRunEnded( TestRunStats const& testRunStats ) {
  11964. StreamingReporterBase::testRunEnded( testRunStats );
  11965. m_xml.scopedElement( "OverallResults" )
  11966. .writeAttribute( "successes", testRunStats.totals.assertions.passed )
  11967. .writeAttribute( "failures", testRunStats.totals.assertions.failed )
  11968. .writeAttribute( "expectedFailures", testRunStats.totals.assertions.failedButOk );
  11969. m_xml.endElement();
  11970. }
  11971. CATCH_REGISTER_REPORTER( "xml", XmlReporter )
  11972. } // end namespace Catch
  11973. #if defined(_MSC_VER)
  11974. #pragma warning(pop)
  11975. #endif
  11976. // end catch_reporter_xml.cpp
  11977. namespace Catch {
  11978. LeakDetector leakDetector;
  11979. }
  11980. #ifdef __clang__
  11981. #pragma clang diagnostic pop
  11982. #endif
  11983. // end catch_impl.hpp
  11984. #endif
  11985. #ifdef CATCH_CONFIG_MAIN
  11986. // start catch_default_main.hpp
  11987. #ifndef __OBJC__
  11988. #if defined(CATCH_CONFIG_WCHAR) && defined(WIN32) && defined(_UNICODE) && !defined(DO_NOT_USE_WMAIN)
  11989. // Standard C/C++ Win32 Unicode wmain entry point
  11990. extern "C" int wmain (int argc, wchar_t * argv[], wchar_t * []) {
  11991. #else
  11992. // Standard C/C++ main entry point
  11993. int main (int argc, char * argv[]) {
  11994. #endif
  11995. return Catch::Session().run( argc, argv );
  11996. }
  11997. #else // __OBJC__
  11998. // Objective-C entry point
  11999. int main (int argc, char * const argv[]) {
  12000. #if !CATCH_ARC_ENABLED
  12001. NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
  12002. #endif
  12003. Catch::registerTestMethods();
  12004. int result = Catch::Session().run( argc, (char**)argv );
  12005. #if !CATCH_ARC_ENABLED
  12006. [pool drain];
  12007. #endif
  12008. return result;
  12009. }
  12010. #endif // __OBJC__
  12011. // end catch_default_main.hpp
  12012. #endif
  12013. #if !defined(CATCH_CONFIG_IMPL_ONLY)
  12014. #ifdef CLARA_CONFIG_MAIN_NOT_DEFINED
  12015. # undef CLARA_CONFIG_MAIN
  12016. #endif
  12017. #if !defined(CATCH_CONFIG_DISABLE)
  12018. //////
  12019. // If this config identifier is defined then all CATCH macros are prefixed with CATCH_
  12020. #ifdef CATCH_CONFIG_PREFIX_ALL
  12021. #define CATCH_REQUIRE( ... ) INTERNAL_CATCH_TEST( "CATCH_REQUIRE", Catch::ResultDisposition::Normal, __VA_ARGS__ )
  12022. #define CATCH_REQUIRE_FALSE( ... ) INTERNAL_CATCH_TEST( "CATCH_REQUIRE_FALSE", Catch::ResultDisposition::Normal | Catch::ResultDisposition::FalseTest, __VA_ARGS__ )
  12023. #define CATCH_REQUIRE_THROWS( ... ) INTERNAL_CATCH_THROWS( "CATCH_REQUIRE_THROWS", Catch::ResultDisposition::Normal, __VA_ARGS__ )
  12024. #define CATCH_REQUIRE_THROWS_AS( expr, exceptionType ) INTERNAL_CATCH_THROWS_AS( "CATCH_REQUIRE_THROWS_AS", exceptionType, Catch::ResultDisposition::Normal, expr )
  12025. #define CATCH_REQUIRE_THROWS_WITH( expr, matcher ) INTERNAL_CATCH_THROWS_STR_MATCHES( "CATCH_REQUIRE_THROWS_WITH", Catch::ResultDisposition::Normal, matcher, expr )
  12026. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  12027. #define CATCH_REQUIRE_THROWS_MATCHES( expr, exceptionType, matcher ) INTERNAL_CATCH_THROWS_MATCHES( "CATCH_REQUIRE_THROWS_MATCHES", exceptionType, Catch::ResultDisposition::Normal, matcher, expr )
  12028. #endif// CATCH_CONFIG_DISABLE_MATCHERS
  12029. #define CATCH_REQUIRE_NOTHROW( ... ) INTERNAL_CATCH_NO_THROW( "CATCH_REQUIRE_NOTHROW", Catch::ResultDisposition::Normal, __VA_ARGS__ )
  12030. #define CATCH_CHECK( ... ) INTERNAL_CATCH_TEST( "CATCH_CHECK", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  12031. #define CATCH_CHECK_FALSE( ... ) INTERNAL_CATCH_TEST( "CATCH_CHECK_FALSE", Catch::ResultDisposition::ContinueOnFailure | Catch::ResultDisposition::FalseTest, __VA_ARGS__ )
  12032. #define CATCH_CHECKED_IF( ... ) INTERNAL_CATCH_IF( "CATCH_CHECKED_IF", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  12033. #define CATCH_CHECKED_ELSE( ... ) INTERNAL_CATCH_ELSE( "CATCH_CHECKED_ELSE", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  12034. #define CATCH_CHECK_NOFAIL( ... ) INTERNAL_CATCH_TEST( "CATCH_CHECK_NOFAIL", Catch::ResultDisposition::ContinueOnFailure | Catch::ResultDisposition::SuppressFail, __VA_ARGS__ )
  12035. #define CATCH_CHECK_THROWS( ... ) INTERNAL_CATCH_THROWS( "CATCH_CHECK_THROWS", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  12036. #define CATCH_CHECK_THROWS_AS( expr, exceptionType ) INTERNAL_CATCH_THROWS_AS( "CATCH_CHECK_THROWS_AS", exceptionType, Catch::ResultDisposition::ContinueOnFailure, expr )
  12037. #define CATCH_CHECK_THROWS_WITH( expr, matcher ) INTERNAL_CATCH_THROWS_STR_MATCHES( "CATCH_CHECK_THROWS_WITH", Catch::ResultDisposition::ContinueOnFailure, matcher, expr )
  12038. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  12039. #define CATCH_CHECK_THROWS_MATCHES( expr, exceptionType, matcher ) INTERNAL_CATCH_THROWS_MATCHES( "CATCH_CHECK_THROWS_MATCHES", exceptionType, Catch::ResultDisposition::ContinueOnFailure, matcher, expr )
  12040. #endif // CATCH_CONFIG_DISABLE_MATCHERS
  12041. #define CATCH_CHECK_NOTHROW( ... ) INTERNAL_CATCH_NO_THROW( "CATCH_CHECK_NOTHROW", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  12042. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  12043. #define CATCH_CHECK_THAT( arg, matcher ) INTERNAL_CHECK_THAT( "CATCH_CHECK_THAT", matcher, Catch::ResultDisposition::ContinueOnFailure, arg )
  12044. #define CATCH_REQUIRE_THAT( arg, matcher ) INTERNAL_CHECK_THAT( "CATCH_REQUIRE_THAT", matcher, Catch::ResultDisposition::Normal, arg )
  12045. #endif // CATCH_CONFIG_DISABLE_MATCHERS
  12046. #define CATCH_INFO( msg ) INTERNAL_CATCH_INFO( "CATCH_INFO", msg )
  12047. #define CATCH_WARN( msg ) INTERNAL_CATCH_MSG( "CATCH_WARN", Catch::ResultWas::Warning, Catch::ResultDisposition::ContinueOnFailure, msg )
  12048. #define CATCH_CAPTURE( ... ) INTERNAL_CATCH_CAPTURE( INTERNAL_CATCH_UNIQUE_NAME(capturer), "CATCH_CAPTURE",__VA_ARGS__ )
  12049. #define CATCH_TEST_CASE( ... ) INTERNAL_CATCH_TESTCASE( __VA_ARGS__ )
  12050. #define CATCH_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEST_CASE_METHOD( className, __VA_ARGS__ )
  12051. #define CATCH_METHOD_AS_TEST_CASE( method, ... ) INTERNAL_CATCH_METHOD_AS_TEST_CASE( method, __VA_ARGS__ )
  12052. #define CATCH_REGISTER_TEST_CASE( Function, ... ) INTERNAL_CATCH_REGISTER_TESTCASE( Function, __VA_ARGS__ )
  12053. #define CATCH_SECTION( ... ) INTERNAL_CATCH_SECTION( __VA_ARGS__ )
  12054. #define CATCH_DYNAMIC_SECTION( ... ) INTERNAL_CATCH_DYNAMIC_SECTION( __VA_ARGS__ )
  12055. #define CATCH_FAIL( ... ) INTERNAL_CATCH_MSG( "CATCH_FAIL", Catch::ResultWas::ExplicitFailure, Catch::ResultDisposition::Normal, __VA_ARGS__ )
  12056. #define CATCH_FAIL_CHECK( ... ) INTERNAL_CATCH_MSG( "CATCH_FAIL_CHECK", Catch::ResultWas::ExplicitFailure, Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  12057. #define CATCH_SUCCEED( ... ) INTERNAL_CATCH_MSG( "CATCH_SUCCEED", Catch::ResultWas::Ok, Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  12058. #define CATCH_ANON_TEST_CASE() INTERNAL_CATCH_TESTCASE()
  12059. #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
  12060. #define CATCH_TEMPLATE_TEST_CASE( ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE( __VA_ARGS__ )
  12061. #define CATCH_TEMPLATE_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ )
  12062. #define CATCH_TEMPLATE_PRODUCT_TEST_CASE( ... ) INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE( __VA_ARGS__ )
  12063. #define CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, __VA_ARGS__ )
  12064. #else
  12065. #define CATCH_TEMPLATE_TEST_CASE( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE( __VA_ARGS__ ) )
  12066. #define CATCH_TEMPLATE_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ ) )
  12067. #define CATCH_TEMPLATE_PRODUCT_TEST_CASE( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE( __VA_ARGS__ ) )
  12068. #define CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, __VA_ARGS__ ) )
  12069. #endif
  12070. #if !defined(CATCH_CONFIG_RUNTIME_STATIC_REQUIRE)
  12071. #define CATCH_STATIC_REQUIRE( ... ) static_assert( __VA_ARGS__ , #__VA_ARGS__ ); CATCH_SUCCEED( #__VA_ARGS__ )
  12072. #define CATCH_STATIC_REQUIRE_FALSE( ... ) static_assert( !(__VA_ARGS__), "!(" #__VA_ARGS__ ")" ); CATCH_SUCCEED( #__VA_ARGS__ )
  12073. #else
  12074. #define CATCH_STATIC_REQUIRE( ... ) CATCH_REQUIRE( __VA_ARGS__ )
  12075. #define CATCH_STATIC_REQUIRE_FALSE( ... ) CATCH_REQUIRE_FALSE( __VA_ARGS__ )
  12076. #endif
  12077. // "BDD-style" convenience wrappers
  12078. #define CATCH_SCENARIO( ... ) CATCH_TEST_CASE( "Scenario: " __VA_ARGS__ )
  12079. #define CATCH_SCENARIO_METHOD( className, ... ) INTERNAL_CATCH_TEST_CASE_METHOD( className, "Scenario: " __VA_ARGS__ )
  12080. #define CATCH_GIVEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " Given: " << desc )
  12081. #define CATCH_AND_GIVEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( "And given: " << desc )
  12082. #define CATCH_WHEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " When: " << desc )
  12083. #define CATCH_AND_WHEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " And when: " << desc )
  12084. #define CATCH_THEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " Then: " << desc )
  12085. #define CATCH_AND_THEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " And: " << desc )
  12086. // If CATCH_CONFIG_PREFIX_ALL is not defined then the CATCH_ prefix is not required
  12087. #else
  12088. #define REQUIRE( ... ) INTERNAL_CATCH_TEST( "REQUIRE", Catch::ResultDisposition::Normal, __VA_ARGS__ )
  12089. #define REQUIRE_FALSE( ... ) INTERNAL_CATCH_TEST( "REQUIRE_FALSE", Catch::ResultDisposition::Normal | Catch::ResultDisposition::FalseTest, __VA_ARGS__ )
  12090. #define REQUIRE_THROWS( ... ) INTERNAL_CATCH_THROWS( "REQUIRE_THROWS", Catch::ResultDisposition::Normal, __VA_ARGS__ )
  12091. #define REQUIRE_THROWS_AS( expr, exceptionType ) INTERNAL_CATCH_THROWS_AS( "REQUIRE_THROWS_AS", exceptionType, Catch::ResultDisposition::Normal, expr )
  12092. #define REQUIRE_THROWS_WITH( expr, matcher ) INTERNAL_CATCH_THROWS_STR_MATCHES( "REQUIRE_THROWS_WITH", Catch::ResultDisposition::Normal, matcher, expr )
  12093. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  12094. #define REQUIRE_THROWS_MATCHES( expr, exceptionType, matcher ) INTERNAL_CATCH_THROWS_MATCHES( "REQUIRE_THROWS_MATCHES", exceptionType, Catch::ResultDisposition::Normal, matcher, expr )
  12095. #endif // CATCH_CONFIG_DISABLE_MATCHERS
  12096. #define REQUIRE_NOTHROW( ... ) INTERNAL_CATCH_NO_THROW( "REQUIRE_NOTHROW", Catch::ResultDisposition::Normal, __VA_ARGS__ )
  12097. #define CHECK( ... ) INTERNAL_CATCH_TEST( "CHECK", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  12098. #define CHECK_FALSE( ... ) INTERNAL_CATCH_TEST( "CHECK_FALSE", Catch::ResultDisposition::ContinueOnFailure | Catch::ResultDisposition::FalseTest, __VA_ARGS__ )
  12099. #define CHECKED_IF( ... ) INTERNAL_CATCH_IF( "CHECKED_IF", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  12100. #define CHECKED_ELSE( ... ) INTERNAL_CATCH_ELSE( "CHECKED_ELSE", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  12101. #define CHECK_NOFAIL( ... ) INTERNAL_CATCH_TEST( "CHECK_NOFAIL", Catch::ResultDisposition::ContinueOnFailure | Catch::ResultDisposition::SuppressFail, __VA_ARGS__ )
  12102. #define CHECK_THROWS( ... ) INTERNAL_CATCH_THROWS( "CHECK_THROWS", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  12103. #define CHECK_THROWS_AS( expr, exceptionType ) INTERNAL_CATCH_THROWS_AS( "CHECK_THROWS_AS", exceptionType, Catch::ResultDisposition::ContinueOnFailure, expr )
  12104. #define CHECK_THROWS_WITH( expr, matcher ) INTERNAL_CATCH_THROWS_STR_MATCHES( "CHECK_THROWS_WITH", Catch::ResultDisposition::ContinueOnFailure, matcher, expr )
  12105. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  12106. #define CHECK_THROWS_MATCHES( expr, exceptionType, matcher ) INTERNAL_CATCH_THROWS_MATCHES( "CHECK_THROWS_MATCHES", exceptionType, Catch::ResultDisposition::ContinueOnFailure, matcher, expr )
  12107. #endif // CATCH_CONFIG_DISABLE_MATCHERS
  12108. #define CHECK_NOTHROW( ... ) INTERNAL_CATCH_NO_THROW( "CHECK_NOTHROW", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  12109. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  12110. #define CHECK_THAT( arg, matcher ) INTERNAL_CHECK_THAT( "CHECK_THAT", matcher, Catch::ResultDisposition::ContinueOnFailure, arg )
  12111. #define REQUIRE_THAT( arg, matcher ) INTERNAL_CHECK_THAT( "REQUIRE_THAT", matcher, Catch::ResultDisposition::Normal, arg )
  12112. #endif // CATCH_CONFIG_DISABLE_MATCHERS
  12113. #define INFO( msg ) INTERNAL_CATCH_INFO( "INFO", msg )
  12114. #define UNSCOPED_INFO( msg ) INTERNAL_CATCH_UNSCOPED_INFO( "UNSCOPED_INFO", msg )
  12115. #define WARN( msg ) INTERNAL_CATCH_MSG( "WARN", Catch::ResultWas::Warning, Catch::ResultDisposition::ContinueOnFailure, msg )
  12116. #define CAPTURE( ... ) INTERNAL_CATCH_CAPTURE( INTERNAL_CATCH_UNIQUE_NAME(capturer), "CAPTURE",__VA_ARGS__ )
  12117. #define TEST_CASE( ... ) INTERNAL_CATCH_TESTCASE( __VA_ARGS__ )
  12118. #define TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEST_CASE_METHOD( className, __VA_ARGS__ )
  12119. #define METHOD_AS_TEST_CASE( method, ... ) INTERNAL_CATCH_METHOD_AS_TEST_CASE( method, __VA_ARGS__ )
  12120. #define REGISTER_TEST_CASE( Function, ... ) INTERNAL_CATCH_REGISTER_TESTCASE( Function, __VA_ARGS__ )
  12121. #define SECTION( ... ) INTERNAL_CATCH_SECTION( __VA_ARGS__ )
  12122. #define DYNAMIC_SECTION( ... ) INTERNAL_CATCH_DYNAMIC_SECTION( __VA_ARGS__ )
  12123. #define FAIL( ... ) INTERNAL_CATCH_MSG( "FAIL", Catch::ResultWas::ExplicitFailure, Catch::ResultDisposition::Normal, __VA_ARGS__ )
  12124. #define FAIL_CHECK( ... ) INTERNAL_CATCH_MSG( "FAIL_CHECK", Catch::ResultWas::ExplicitFailure, Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  12125. #define SUCCEED( ... ) INTERNAL_CATCH_MSG( "SUCCEED", Catch::ResultWas::Ok, Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  12126. #define ANON_TEST_CASE() INTERNAL_CATCH_TESTCASE()
  12127. #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
  12128. #define TEMPLATE_TEST_CASE( ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE( __VA_ARGS__ )
  12129. #define TEMPLATE_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ )
  12130. #define TEMPLATE_PRODUCT_TEST_CASE( ... ) INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE( __VA_ARGS__ )
  12131. #define TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, __VA_ARGS__ )
  12132. #else
  12133. #define TEMPLATE_TEST_CASE( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE( __VA_ARGS__ ) )
  12134. #define TEMPLATE_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ ) )
  12135. #define TEMPLATE_PRODUCT_TEST_CASE( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE( __VA_ARGS__ ) )
  12136. #define TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, __VA_ARGS__ ) )
  12137. #endif
  12138. #if !defined(CATCH_CONFIG_RUNTIME_STATIC_REQUIRE)
  12139. #define STATIC_REQUIRE( ... ) static_assert( __VA_ARGS__, #__VA_ARGS__ ); SUCCEED( #__VA_ARGS__ )
  12140. #define STATIC_REQUIRE_FALSE( ... ) static_assert( !(__VA_ARGS__), "!(" #__VA_ARGS__ ")" ); SUCCEED( "!(" #__VA_ARGS__ ")" )
  12141. #else
  12142. #define STATIC_REQUIRE( ... ) REQUIRE( __VA_ARGS__ )
  12143. #define STATIC_REQUIRE_FALSE( ... ) REQUIRE_FALSE( __VA_ARGS__ )
  12144. #endif
  12145. #endif
  12146. #define CATCH_TRANSLATE_EXCEPTION( signature ) INTERNAL_CATCH_TRANSLATE_EXCEPTION( signature )
  12147. // "BDD-style" convenience wrappers
  12148. #define SCENARIO( ... ) TEST_CASE( "Scenario: " __VA_ARGS__ )
  12149. #define SCENARIO_METHOD( className, ... ) INTERNAL_CATCH_TEST_CASE_METHOD( className, "Scenario: " __VA_ARGS__ )
  12150. #define GIVEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " Given: " << desc )
  12151. #define AND_GIVEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( "And given: " << desc )
  12152. #define WHEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " When: " << desc )
  12153. #define AND_WHEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " And when: " << desc )
  12154. #define THEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " Then: " << desc )
  12155. #define AND_THEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " And: " << desc )
  12156. using Catch::Detail::Approx;
  12157. #else // CATCH_CONFIG_DISABLE
  12158. //////
  12159. // If this config identifier is defined then all CATCH macros are prefixed with CATCH_
  12160. #ifdef CATCH_CONFIG_PREFIX_ALL
  12161. #define CATCH_REQUIRE( ... ) (void)(0)
  12162. #define CATCH_REQUIRE_FALSE( ... ) (void)(0)
  12163. #define CATCH_REQUIRE_THROWS( ... ) (void)(0)
  12164. #define CATCH_REQUIRE_THROWS_AS( expr, exceptionType ) (void)(0)
  12165. #define CATCH_REQUIRE_THROWS_WITH( expr, matcher ) (void)(0)
  12166. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  12167. #define CATCH_REQUIRE_THROWS_MATCHES( expr, exceptionType, matcher ) (void)(0)
  12168. #endif// CATCH_CONFIG_DISABLE_MATCHERS
  12169. #define CATCH_REQUIRE_NOTHROW( ... ) (void)(0)
  12170. #define CATCH_CHECK( ... ) (void)(0)
  12171. #define CATCH_CHECK_FALSE( ... ) (void)(0)
  12172. #define CATCH_CHECKED_IF( ... ) if (__VA_ARGS__)
  12173. #define CATCH_CHECKED_ELSE( ... ) if (!(__VA_ARGS__))
  12174. #define CATCH_CHECK_NOFAIL( ... ) (void)(0)
  12175. #define CATCH_CHECK_THROWS( ... ) (void)(0)
  12176. #define CATCH_CHECK_THROWS_AS( expr, exceptionType ) (void)(0)
  12177. #define CATCH_CHECK_THROWS_WITH( expr, matcher ) (void)(0)
  12178. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  12179. #define CATCH_CHECK_THROWS_MATCHES( expr, exceptionType, matcher ) (void)(0)
  12180. #endif // CATCH_CONFIG_DISABLE_MATCHERS
  12181. #define CATCH_CHECK_NOTHROW( ... ) (void)(0)
  12182. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  12183. #define CATCH_CHECK_THAT( arg, matcher ) (void)(0)
  12184. #define CATCH_REQUIRE_THAT( arg, matcher ) (void)(0)
  12185. #endif // CATCH_CONFIG_DISABLE_MATCHERS
  12186. #define CATCH_INFO( msg ) (void)(0)
  12187. #define CATCH_WARN( msg ) (void)(0)
  12188. #define CATCH_CAPTURE( msg ) (void)(0)
  12189. #define CATCH_TEST_CASE( ... ) INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ))
  12190. #define CATCH_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ))
  12191. #define CATCH_METHOD_AS_TEST_CASE( method, ... )
  12192. #define CATCH_REGISTER_TEST_CASE( Function, ... ) (void)(0)
  12193. #define CATCH_SECTION( ... )
  12194. #define CATCH_DYNAMIC_SECTION( ... )
  12195. #define CATCH_FAIL( ... ) (void)(0)
  12196. #define CATCH_FAIL_CHECK( ... ) (void)(0)
  12197. #define CATCH_SUCCEED( ... ) (void)(0)
  12198. #define CATCH_ANON_TEST_CASE() INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ))
  12199. #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
  12200. #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____ ) )
  12201. #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 )
  12202. #define CATCH_TEMPLATE_PRODUCT_TEST_CASE( ... ) CATCH_TEMPLATE_TEST_CASE( __VA_ARGS__ )
  12203. #define CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, ... ) CATCH_TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ )
  12204. #else
  12205. #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____ ) ) )
  12206. #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 ) )
  12207. #define CATCH_TEMPLATE_PRODUCT_TEST_CASE( ... ) CATCH_TEMPLATE_TEST_CASE( __VA_ARGS__ )
  12208. #define CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, ... ) CATCH_TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ )
  12209. #endif
  12210. // "BDD-style" convenience wrappers
  12211. #define CATCH_SCENARIO( ... ) INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ))
  12212. #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 )
  12213. #define CATCH_GIVEN( desc )
  12214. #define CATCH_AND_GIVEN( desc )
  12215. #define CATCH_WHEN( desc )
  12216. #define CATCH_AND_WHEN( desc )
  12217. #define CATCH_THEN( desc )
  12218. #define CATCH_AND_THEN( desc )
  12219. #define CATCH_STATIC_REQUIRE( ... ) (void)(0)
  12220. #define CATCH_STATIC_REQUIRE_FALSE( ... ) (void)(0)
  12221. // If CATCH_CONFIG_PREFIX_ALL is not defined then the CATCH_ prefix is not required
  12222. #else
  12223. #define REQUIRE( ... ) (void)(0)
  12224. #define REQUIRE_FALSE( ... ) (void)(0)
  12225. #define REQUIRE_THROWS( ... ) (void)(0)
  12226. #define REQUIRE_THROWS_AS( expr, exceptionType ) (void)(0)
  12227. #define REQUIRE_THROWS_WITH( expr, matcher ) (void)(0)
  12228. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  12229. #define REQUIRE_THROWS_MATCHES( expr, exceptionType, matcher ) (void)(0)
  12230. #endif // CATCH_CONFIG_DISABLE_MATCHERS
  12231. #define REQUIRE_NOTHROW( ... ) (void)(0)
  12232. #define CHECK( ... ) (void)(0)
  12233. #define CHECK_FALSE( ... ) (void)(0)
  12234. #define CHECKED_IF( ... ) if (__VA_ARGS__)
  12235. #define CHECKED_ELSE( ... ) if (!(__VA_ARGS__))
  12236. #define CHECK_NOFAIL( ... ) (void)(0)
  12237. #define CHECK_THROWS( ... ) (void)(0)
  12238. #define CHECK_THROWS_AS( expr, exceptionType ) (void)(0)
  12239. #define CHECK_THROWS_WITH( expr, matcher ) (void)(0)
  12240. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  12241. #define CHECK_THROWS_MATCHES( expr, exceptionType, matcher ) (void)(0)
  12242. #endif // CATCH_CONFIG_DISABLE_MATCHERS
  12243. #define CHECK_NOTHROW( ... ) (void)(0)
  12244. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  12245. #define CHECK_THAT( arg, matcher ) (void)(0)
  12246. #define REQUIRE_THAT( arg, matcher ) (void)(0)
  12247. #endif // CATCH_CONFIG_DISABLE_MATCHERS
  12248. #define INFO( msg ) (void)(0)
  12249. #define WARN( msg ) (void)(0)
  12250. #define CAPTURE( msg ) (void)(0)
  12251. #define TEST_CASE( ... ) INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ))
  12252. #define TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ))
  12253. #define METHOD_AS_TEST_CASE( method, ... )
  12254. #define REGISTER_TEST_CASE( Function, ... ) (void)(0)
  12255. #define SECTION( ... )
  12256. #define DYNAMIC_SECTION( ... )
  12257. #define FAIL( ... ) (void)(0)
  12258. #define FAIL_CHECK( ... ) (void)(0)
  12259. #define SUCCEED( ... ) (void)(0)
  12260. #define ANON_TEST_CASE() INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ))
  12261. #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
  12262. #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____ ) )
  12263. #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 )
  12264. #define TEMPLATE_PRODUCT_TEST_CASE( ... ) TEMPLATE_TEST_CASE( __VA_ARGS__ )
  12265. #define TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, ... ) TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ )
  12266. #else
  12267. #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____ ) ) )
  12268. #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 ) )
  12269. #define TEMPLATE_PRODUCT_TEST_CASE( ... ) TEMPLATE_TEST_CASE( __VA_ARGS__ )
  12270. #define TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, ... ) TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ )
  12271. #endif
  12272. #define STATIC_REQUIRE( ... ) (void)(0)
  12273. #define STATIC_REQUIRE_FALSE( ... ) (void)(0)
  12274. #endif
  12275. #define CATCH_TRANSLATE_EXCEPTION( signature ) INTERNAL_CATCH_TRANSLATE_EXCEPTION_NO_REG( INTERNAL_CATCH_UNIQUE_NAME( catch_internal_ExceptionTranslator ), signature )
  12276. // "BDD-style" convenience wrappers
  12277. #define SCENARIO( ... ) INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ) )
  12278. #define SCENARIO_METHOD( className, ... ) INTERNAL_CATCH_TESTCASE_METHOD_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ), className )
  12279. #define GIVEN( desc )
  12280. #define AND_GIVEN( desc )
  12281. #define WHEN( desc )
  12282. #define AND_WHEN( desc )
  12283. #define THEN( desc )
  12284. #define AND_THEN( desc )
  12285. using Catch::Detail::Approx;
  12286. #endif
  12287. #endif // ! CATCH_CONFIG_IMPL_ONLY
  12288. // start catch_reenable_warnings.h
  12289. #ifdef __clang__
  12290. # ifdef __ICC // icpc defines the __clang__ macro
  12291. # pragma warning(pop)
  12292. # else
  12293. # pragma clang diagnostic pop
  12294. # endif
  12295. #elif defined __GNUC__
  12296. # pragma GCC diagnostic pop
  12297. #endif
  12298. // end catch_reenable_warnings.h
  12299. // end catch.hpp
  12300. #endif // TWOBLUECUBES_SINGLE_INCLUDE_CATCH_HPP_INCLUDED