Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

14363 lines
480KB

  1. /*
  2. * Catch v2.5.0
  3. * Generated: 2018-11-26 20:46:12.165372
  4. * ----------------------------------------------------------
  5. * This file has been merged from multiple headers. Please don't edit it directly
  6. * Copyright (c) 2018 Two Blue Cubes Ltd. All rights reserved.
  7. *
  8. * Distributed under the Boost Software License, Version 1.0. (See accompanying
  9. * file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
  10. */
  11. #ifndef TWOBLUECUBES_SINGLE_INCLUDE_CATCH_HPP_INCLUDED
  12. #define TWOBLUECUBES_SINGLE_INCLUDE_CATCH_HPP_INCLUDED
  13. // start catch.hpp
  14. #define CATCH_VERSION_MAJOR 2
  15. #define CATCH_VERSION_MINOR 5
  16. #define CATCH_VERSION_PATCH 0
  17. #ifdef __clang__
  18. # pragma clang system_header
  19. #elif defined __GNUC__
  20. # pragma GCC system_header
  21. #endif
  22. // start catch_suppress_warnings.h
  23. #ifdef __clang__
  24. # ifdef __ICC // icpc defines the __clang__ macro
  25. # pragma warning(push)
  26. # pragma warning(disable: 161 1682)
  27. # else // __ICC
  28. # pragma clang diagnostic push
  29. # pragma clang diagnostic ignored "-Wpadded"
  30. # pragma clang diagnostic ignored "-Wswitch-enum"
  31. # pragma clang diagnostic ignored "-Wcovered-switch-default"
  32. # endif
  33. #elif defined __GNUC__
  34. // GCC likes to warn on REQUIREs, and we cannot suppress them
  35. // locally because g++'s support for _Pragma is lacking in older,
  36. // still supported, versions
  37. # pragma GCC diagnostic ignored "-Wparentheses"
  38. # pragma GCC diagnostic push
  39. # pragma GCC diagnostic ignored "-Wunused-variable"
  40. # pragma GCC diagnostic ignored "-Wpadded"
  41. #endif
  42. // end catch_suppress_warnings.h
  43. #if defined(CATCH_CONFIG_MAIN) || defined(CATCH_CONFIG_RUNNER)
  44. # define CATCH_IMPL
  45. # define CATCH_CONFIG_ALL_PARTS
  46. #endif
  47. // In the impl file, we want to have access to all parts of the headers
  48. // Can also be used to sanely support PCHs
  49. #if defined(CATCH_CONFIG_ALL_PARTS)
  50. # define CATCH_CONFIG_EXTERNAL_INTERFACES
  51. # if defined(CATCH_CONFIG_DISABLE_MATCHERS)
  52. # undef CATCH_CONFIG_DISABLE_MATCHERS
  53. # endif
  54. # if !defined(CATCH_CONFIG_ENABLE_CHRONO_STRINGMAKER)
  55. # define CATCH_CONFIG_ENABLE_CHRONO_STRINGMAKER
  56. # endif
  57. #endif
  58. #if !defined(CATCH_CONFIG_IMPL_ONLY)
  59. // start catch_platform.h
  60. #ifdef __APPLE__
  61. # include <TargetConditionals.h>
  62. # if TARGET_OS_OSX == 1
  63. # define CATCH_PLATFORM_MAC
  64. # elif TARGET_OS_IPHONE == 1
  65. # define CATCH_PLATFORM_IPHONE
  66. # endif
  67. #elif defined(linux) || defined(__linux) || defined(__linux__)
  68. # define CATCH_PLATFORM_LINUX
  69. #elif defined(WIN32) || defined(__WIN32__) || defined(_WIN32) || defined(_MSC_VER) || defined(__MINGW32__)
  70. # define CATCH_PLATFORM_WINDOWS
  71. #endif
  72. // end catch_platform.h
  73. #ifdef CATCH_IMPL
  74. # ifndef CLARA_CONFIG_MAIN
  75. # define CLARA_CONFIG_MAIN_NOT_DEFINED
  76. # define CLARA_CONFIG_MAIN
  77. # endif
  78. #endif
  79. // start catch_user_interfaces.h
  80. namespace Catch {
  81. unsigned int rngSeed();
  82. }
  83. // end catch_user_interfaces.h
  84. // start catch_tag_alias_autoregistrar.h
  85. // start catch_common.h
  86. // start catch_compiler_capabilities.h
  87. // Detect a number of compiler features - by compiler
  88. // The following features are defined:
  89. //
  90. // CATCH_CONFIG_COUNTER : is the __COUNTER__ macro supported?
  91. // CATCH_CONFIG_WINDOWS_SEH : is Windows SEH supported?
  92. // CATCH_CONFIG_POSIX_SIGNALS : are POSIX signals supported?
  93. // CATCH_CONFIG_DISABLE_EXCEPTIONS : Are exceptions enabled?
  94. // ****************
  95. // Note to maintainers: if new toggles are added please document them
  96. // in configuration.md, too
  97. // ****************
  98. // In general each macro has a _NO_<feature name> form
  99. // (e.g. CATCH_CONFIG_NO_POSIX_SIGNALS) which disables the feature.
  100. // Many features, at point of detection, define an _INTERNAL_ macro, so they
  101. // can be combined, en-mass, with the _NO_ forms later.
  102. #ifdef __cplusplus
  103. # if (__cplusplus >= 201402L) || (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 variant is available and usable
  227. #if defined(__has_include)
  228. # if __has_include(<variant>) && defined(CATCH_CPP17_OR_GREATER)
  229. # if defined(__clang__) && (__clang_major__ < 8)
  230. // work around clang bug with libstdc++ https://bugs.llvm.org/show_bug.cgi?id=31852
  231. // fix should be in clang 8, workaround in libstdc++ 8.2
  232. # include <ciso646>
  233. # if defined(__GLIBCXX__) && defined(_GLIBCXX_RELEASE) && (_GLIBCXX_RELEASE < 9)
  234. # define CATCH_CONFIG_NO_CPP17_VARIANT
  235. # else
  236. # define CATCH_INTERNAL_CONFIG_CPP17_VARIANT
  237. # endif // defined(__GLIBCXX__) && defined(_GLIBCXX_RELEASE) && (_GLIBCXX_RELEASE < 9)
  238. # endif // defined(__clang__) && (__clang_major__ < 8)
  239. # endif // __has_include(<variant>) && defined(CATCH_CPP17_OR_GREATER)
  240. #endif // __has_include
  241. #if defined(CATCH_INTERNAL_CONFIG_COUNTER) && !defined(CATCH_CONFIG_NO_COUNTER) && !defined(CATCH_CONFIG_COUNTER)
  242. # define CATCH_CONFIG_COUNTER
  243. #endif
  244. #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)
  245. # define CATCH_CONFIG_WINDOWS_SEH
  246. #endif
  247. // This is set by default, because we assume that unix compilers are posix-signal-compatible by default.
  248. #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)
  249. # define CATCH_CONFIG_POSIX_SIGNALS
  250. #endif
  251. // This is set by default, because we assume that compilers with no wchar_t support are just rare exceptions.
  252. #if !defined(CATCH_INTERNAL_CONFIG_NO_WCHAR) && !defined(CATCH_CONFIG_NO_WCHAR) && !defined(CATCH_CONFIG_WCHAR)
  253. # define CATCH_CONFIG_WCHAR
  254. #endif
  255. #if !defined(CATCH_INTERNAL_CONFIG_NO_CPP11_TO_STRING) && !defined(CATCH_CONFIG_NO_CPP11_TO_STRING) && !defined(CATCH_CONFIG_CPP11_TO_STRING)
  256. # define CATCH_CONFIG_CPP11_TO_STRING
  257. #endif
  258. #if defined(CATCH_INTERNAL_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS) && !defined(CATCH_CONFIG_NO_CPP17_UNCAUGHT_EXCEPTIONS) && !defined(CATCH_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS)
  259. # define CATCH_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS
  260. #endif
  261. #if defined(CATCH_INTERNAL_CONFIG_CPP17_STRING_VIEW) && !defined(CATCH_CONFIG_NO_CPP17_STRING_VIEW) && !defined(CATCH_CONFIG_CPP17_STRING_VIEW)
  262. # define CATCH_CONFIG_CPP17_STRING_VIEW
  263. #endif
  264. #if defined(CATCH_INTERNAL_CONFIG_CPP17_VARIANT) && !defined(CATCH_CONFIG_NO_CPP17_VARIANT) && !defined(CATCH_CONFIG_CPP17_VARIANT)
  265. # define CATCH_CONFIG_CPP17_VARIANT
  266. #endif
  267. #if defined(CATCH_CONFIG_EXPERIMENTAL_REDIRECT)
  268. # define CATCH_INTERNAL_CONFIG_NEW_CAPTURE
  269. #endif
  270. #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)
  271. # define CATCH_CONFIG_NEW_CAPTURE
  272. #endif
  273. #if !defined(CATCH_INTERNAL_CONFIG_EXCEPTIONS_ENABLED) && !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
  274. # define CATCH_CONFIG_DISABLE_EXCEPTIONS
  275. #endif
  276. #if defined(CATCH_INTERNAL_CONFIG_POLYFILL_ISNAN) && !defined(CATCH_CONFIG_NO_POLYFILL_ISNAN) && !defined(CATCH_CONFIG_POLYFILL_ISNAN)
  277. # define CATCH_CONFIG_POLYFILL_ISNAN
  278. #endif
  279. #if !defined(CATCH_INTERNAL_SUPPRESS_PARENTHESES_WARNINGS)
  280. # define CATCH_INTERNAL_SUPPRESS_PARENTHESES_WARNINGS
  281. # define CATCH_INTERNAL_UNSUPPRESS_PARENTHESES_WARNINGS
  282. #endif
  283. #if !defined(CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS)
  284. # define CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS
  285. # define CATCH_INTERNAL_UNSUPPRESS_GLOBALS_WARNINGS
  286. #endif
  287. #if !defined(CATCH_INTERNAL_SUPPRESS_UNUSED_WARNINGS)
  288. # define CATCH_INTERNAL_SUPPRESS_UNUSED_WARNINGS
  289. # define CATCH_INTERNAL_UNSUPPRESS_UNUSED_WARNINGS
  290. #endif
  291. #if defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
  292. #define CATCH_TRY if ((true))
  293. #define CATCH_CATCH_ALL if ((false))
  294. #define CATCH_CATCH_ANON(type) if ((false))
  295. #else
  296. #define CATCH_TRY try
  297. #define CATCH_CATCH_ALL catch (...)
  298. #define CATCH_CATCH_ANON(type) catch (type)
  299. #endif
  300. #if defined(CATCH_INTERNAL_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR) && !defined(CATCH_CONFIG_NO_TRADITIONAL_MSVC_PREPROCESSOR) && !defined(CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR)
  301. #define CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
  302. #endif
  303. // end catch_compiler_capabilities.h
  304. #define INTERNAL_CATCH_UNIQUE_NAME_LINE2( name, line ) name##line
  305. #define INTERNAL_CATCH_UNIQUE_NAME_LINE( name, line ) INTERNAL_CATCH_UNIQUE_NAME_LINE2( name, line )
  306. #ifdef CATCH_CONFIG_COUNTER
  307. # define INTERNAL_CATCH_UNIQUE_NAME( name ) INTERNAL_CATCH_UNIQUE_NAME_LINE( name, __COUNTER__ )
  308. #else
  309. # define INTERNAL_CATCH_UNIQUE_NAME( name ) INTERNAL_CATCH_UNIQUE_NAME_LINE( name, __LINE__ )
  310. #endif
  311. #include <iosfwd>
  312. #include <string>
  313. #include <cstdint>
  314. // We need a dummy global operator<< so we can bring it into Catch namespace later
  315. struct Catch_global_namespace_dummy {};
  316. std::ostream& operator<<(std::ostream&, Catch_global_namespace_dummy);
  317. namespace Catch {
  318. struct CaseSensitive { enum Choice {
  319. Yes,
  320. No
  321. }; };
  322. class NonCopyable {
  323. NonCopyable( NonCopyable const& ) = delete;
  324. NonCopyable( NonCopyable && ) = delete;
  325. NonCopyable& operator = ( NonCopyable const& ) = delete;
  326. NonCopyable& operator = ( NonCopyable && ) = delete;
  327. protected:
  328. NonCopyable();
  329. virtual ~NonCopyable();
  330. };
  331. struct SourceLineInfo {
  332. SourceLineInfo() = delete;
  333. SourceLineInfo( char const* _file, std::size_t _line ) noexcept
  334. : file( _file ),
  335. line( _line )
  336. {}
  337. SourceLineInfo( SourceLineInfo const& other ) = default;
  338. SourceLineInfo( SourceLineInfo && ) = default;
  339. SourceLineInfo& operator = ( SourceLineInfo const& ) = default;
  340. SourceLineInfo& operator = ( SourceLineInfo && ) = default;
  341. bool empty() const noexcept;
  342. bool operator == ( SourceLineInfo const& other ) const noexcept;
  343. bool operator < ( SourceLineInfo const& other ) const noexcept;
  344. char const* file;
  345. std::size_t line;
  346. };
  347. std::ostream& operator << ( std::ostream& os, SourceLineInfo const& info );
  348. // Bring in operator<< from global namespace into Catch namespace
  349. // This is necessary because the overload of operator<< above makes
  350. // lookup stop at namespace Catch
  351. using ::operator<<;
  352. // Use this in variadic streaming macros to allow
  353. // >> +StreamEndStop
  354. // as well as
  355. // >> stuff +StreamEndStop
  356. struct StreamEndStop {
  357. std::string operator+() const;
  358. };
  359. template<typename T>
  360. T const& operator + ( T const& value, StreamEndStop ) {
  361. return value;
  362. }
  363. }
  364. #define CATCH_INTERNAL_LINEINFO \
  365. ::Catch::SourceLineInfo( __FILE__, static_cast<std::size_t>( __LINE__ ) )
  366. // end catch_common.h
  367. namespace Catch {
  368. struct RegistrarForTagAliases {
  369. RegistrarForTagAliases( char const* alias, char const* tag, SourceLineInfo const& lineInfo );
  370. };
  371. } // end namespace Catch
  372. #define CATCH_REGISTER_TAG_ALIAS( alias, spec ) \
  373. CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
  374. namespace{ Catch::RegistrarForTagAliases INTERNAL_CATCH_UNIQUE_NAME( AutoRegisterTagAlias )( alias, spec, CATCH_INTERNAL_LINEINFO ); } \
  375. CATCH_INTERNAL_UNSUPPRESS_GLOBALS_WARNINGS
  376. // end catch_tag_alias_autoregistrar.h
  377. // start catch_test_registry.h
  378. // start catch_interfaces_testcase.h
  379. #include <vector>
  380. #include <memory>
  381. namespace Catch {
  382. class TestSpec;
  383. struct ITestInvoker {
  384. virtual void invoke () const = 0;
  385. virtual ~ITestInvoker();
  386. };
  387. using ITestCasePtr = std::shared_ptr<ITestInvoker>;
  388. class TestCase;
  389. struct IConfig;
  390. struct ITestCaseRegistry {
  391. virtual ~ITestCaseRegistry();
  392. virtual std::vector<TestCase> const& getAllTests() const = 0;
  393. virtual std::vector<TestCase> const& getAllTestsSorted( IConfig const& config ) const = 0;
  394. };
  395. bool matchTest( TestCase const& testCase, TestSpec const& testSpec, IConfig const& config );
  396. std::vector<TestCase> filterTests( std::vector<TestCase> const& testCases, TestSpec const& testSpec, IConfig const& config );
  397. std::vector<TestCase> const& getAllTestCasesSorted( IConfig const& config );
  398. }
  399. // end catch_interfaces_testcase.h
  400. // start catch_stringref.h
  401. #include <cstddef>
  402. #include <string>
  403. #include <iosfwd>
  404. namespace Catch {
  405. class StringData;
  406. /// A non-owning string class (similar to the forthcoming std::string_view)
  407. /// Note that, because a StringRef may be a substring of another string,
  408. /// it may not be null terminated. c_str() must return a null terminated
  409. /// string, however, and so the StringRef will internally take ownership
  410. /// (taking a copy), if necessary. In theory this ownership is not externally
  411. /// visible - but it does mean (substring) StringRefs should not be shared between
  412. /// threads.
  413. class StringRef {
  414. public:
  415. using size_type = std::size_t;
  416. private:
  417. friend struct StringRefTestAccess;
  418. char const* m_start;
  419. size_type m_size;
  420. char* m_data = nullptr;
  421. void takeOwnership();
  422. static constexpr char const* const s_empty = "";
  423. public: // construction/ assignment
  424. StringRef() noexcept
  425. : StringRef( s_empty, 0 )
  426. {}
  427. StringRef( StringRef const& other ) noexcept
  428. : m_start( other.m_start ),
  429. m_size( other.m_size )
  430. {}
  431. StringRef( StringRef&& other ) noexcept
  432. : m_start( other.m_start ),
  433. m_size( other.m_size ),
  434. m_data( other.m_data )
  435. {
  436. other.m_data = nullptr;
  437. }
  438. StringRef( char const* rawChars ) noexcept;
  439. StringRef( char const* rawChars, size_type size ) noexcept
  440. : m_start( rawChars ),
  441. m_size( size )
  442. {}
  443. StringRef( std::string const& stdString ) noexcept
  444. : m_start( stdString.c_str() ),
  445. m_size( stdString.size() )
  446. {}
  447. ~StringRef() noexcept {
  448. delete[] m_data;
  449. }
  450. auto operator = ( StringRef const &other ) noexcept -> StringRef& {
  451. delete[] m_data;
  452. m_data = nullptr;
  453. m_start = other.m_start;
  454. m_size = other.m_size;
  455. return *this;
  456. }
  457. operator std::string() const;
  458. void swap( StringRef& other ) noexcept;
  459. public: // operators
  460. auto operator == ( StringRef const& other ) const noexcept -> bool;
  461. auto operator != ( StringRef const& other ) const noexcept -> bool;
  462. auto operator[] ( size_type index ) const noexcept -> char;
  463. public: // named queries
  464. auto empty() const noexcept -> bool {
  465. return m_size == 0;
  466. }
  467. auto size() const noexcept -> size_type {
  468. return m_size;
  469. }
  470. auto numberOfCharacters() const noexcept -> size_type;
  471. auto c_str() const -> char const*;
  472. public: // substrings and searches
  473. auto substr( size_type start, size_type size ) const noexcept -> StringRef;
  474. // Returns the current start pointer.
  475. // Note that the pointer can change when if the StringRef is a substring
  476. auto currentData() const noexcept -> char const*;
  477. private: // ownership queries - may not be consistent between calls
  478. auto isOwned() const noexcept -> bool;
  479. auto isSubstring() const noexcept -> bool;
  480. };
  481. auto operator + ( StringRef const& lhs, StringRef const& rhs ) -> std::string;
  482. auto operator + ( StringRef const& lhs, char const* rhs ) -> std::string;
  483. auto operator + ( char const* lhs, StringRef const& rhs ) -> std::string;
  484. auto operator += ( std::string& lhs, StringRef const& sr ) -> std::string&;
  485. auto operator << ( std::ostream& os, StringRef const& sr ) -> std::ostream&;
  486. inline auto operator "" _sr( char const* rawChars, std::size_t size ) noexcept -> StringRef {
  487. return StringRef( rawChars, size );
  488. }
  489. } // namespace Catch
  490. inline auto operator "" _catch_sr( char const* rawChars, std::size_t size ) noexcept -> Catch::StringRef {
  491. return Catch::StringRef( rawChars, size );
  492. }
  493. // end catch_stringref.h
  494. // start catch_type_traits.hpp
  495. namespace Catch{
  496. #ifdef CATCH_CPP17_OR_GREATER
  497. template <typename...>
  498. inline constexpr auto is_unique = std::true_type{};
  499. template <typename T, typename... Rest>
  500. inline constexpr auto is_unique<T, Rest...> = std::bool_constant<
  501. (!std::is_same_v<T, Rest> && ...) && is_unique<Rest...>
  502. >{};
  503. #else
  504. template <typename...>
  505. struct is_unique : std::true_type{};
  506. template <typename T0, typename T1, typename... Rest>
  507. struct is_unique<T0, T1, Rest...> : std::integral_constant
  508. <bool,
  509. !std::is_same<T0, T1>::value
  510. && is_unique<T0, Rest...>::value
  511. && is_unique<T1, Rest...>::value
  512. >{};
  513. #endif
  514. }
  515. // end catch_type_traits.hpp
  516. // start catch_preprocessor.hpp
  517. #define CATCH_RECURSION_LEVEL0(...) __VA_ARGS__
  518. #define CATCH_RECURSION_LEVEL1(...) CATCH_RECURSION_LEVEL0(CATCH_RECURSION_LEVEL0(CATCH_RECURSION_LEVEL0(__VA_ARGS__)))
  519. #define CATCH_RECURSION_LEVEL2(...) CATCH_RECURSION_LEVEL1(CATCH_RECURSION_LEVEL1(CATCH_RECURSION_LEVEL1(__VA_ARGS__)))
  520. #define CATCH_RECURSION_LEVEL3(...) CATCH_RECURSION_LEVEL2(CATCH_RECURSION_LEVEL2(CATCH_RECURSION_LEVEL2(__VA_ARGS__)))
  521. #define CATCH_RECURSION_LEVEL4(...) CATCH_RECURSION_LEVEL3(CATCH_RECURSION_LEVEL3(CATCH_RECURSION_LEVEL3(__VA_ARGS__)))
  522. #define CATCH_RECURSION_LEVEL5(...) CATCH_RECURSION_LEVEL4(CATCH_RECURSION_LEVEL4(CATCH_RECURSION_LEVEL4(__VA_ARGS__)))
  523. #ifdef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
  524. #define INTERNAL_CATCH_EXPAND_VARGS(...) __VA_ARGS__
  525. // MSVC needs more evaluations
  526. #define CATCH_RECURSION_LEVEL6(...) CATCH_RECURSION_LEVEL5(CATCH_RECURSION_LEVEL5(CATCH_RECURSION_LEVEL5(__VA_ARGS__)))
  527. #define CATCH_RECURSE(...) CATCH_RECURSION_LEVEL6(CATCH_RECURSION_LEVEL6(__VA_ARGS__))
  528. #else
  529. #define CATCH_RECURSE(...) CATCH_RECURSION_LEVEL5(__VA_ARGS__)
  530. #endif
  531. #define CATCH_REC_END(...)
  532. #define CATCH_REC_OUT
  533. #define CATCH_EMPTY()
  534. #define CATCH_DEFER(id) id CATCH_EMPTY()
  535. #define CATCH_REC_GET_END2() 0, CATCH_REC_END
  536. #define CATCH_REC_GET_END1(...) CATCH_REC_GET_END2
  537. #define CATCH_REC_GET_END(...) CATCH_REC_GET_END1
  538. #define CATCH_REC_NEXT0(test, next, ...) next CATCH_REC_OUT
  539. #define CATCH_REC_NEXT1(test, next) CATCH_DEFER ( CATCH_REC_NEXT0 ) ( test, next, 0)
  540. #define CATCH_REC_NEXT(test, next) CATCH_REC_NEXT1(CATCH_REC_GET_END test, next)
  541. #define CATCH_REC_LIST0(f, x, peek, ...) , f(x) CATCH_DEFER ( CATCH_REC_NEXT(peek, CATCH_REC_LIST1) ) ( f, peek, __VA_ARGS__ )
  542. #define CATCH_REC_LIST1(f, x, peek, ...) , f(x) CATCH_DEFER ( CATCH_REC_NEXT(peek, CATCH_REC_LIST0) ) ( f, peek, __VA_ARGS__ )
  543. #define CATCH_REC_LIST2(f, x, peek, ...) f(x) CATCH_DEFER ( CATCH_REC_NEXT(peek, CATCH_REC_LIST1) ) ( f, peek, __VA_ARGS__ )
  544. #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__ )
  545. #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__ )
  546. #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__ )
  547. // Applies the function macro `f` to each of the remaining parameters, inserts commas between the results,
  548. // and passes userdata as the first parameter to each invocation,
  549. // e.g. CATCH_REC_LIST_UD(f, x, a, b, c) evaluates to f(x, a), f(x, b), f(x, c)
  550. #define CATCH_REC_LIST_UD(f, userdata, ...) CATCH_RECURSE(CATCH_REC_LIST2_UD(f, userdata, __VA_ARGS__, ()()(), ()()(), ()()(), 0))
  551. #define CATCH_REC_LIST(f, ...) CATCH_RECURSE(CATCH_REC_LIST2(f, __VA_ARGS__, ()()(), ()()(), ()()(), 0))
  552. #define INTERNAL_CATCH_EXPAND1(param) INTERNAL_CATCH_EXPAND2(param)
  553. #define INTERNAL_CATCH_EXPAND2(...) INTERNAL_CATCH_NO## __VA_ARGS__
  554. #define INTERNAL_CATCH_DEF(...) INTERNAL_CATCH_DEF __VA_ARGS__
  555. #define INTERNAL_CATCH_NOINTERNAL_CATCH_DEF
  556. #define INTERNAL_CATCH_REMOVE_PARENS(...) INTERNAL_CATCH_EXPAND1(INTERNAL_CATCH_DEF __VA_ARGS__)
  557. #define INTERNAL_CATCH_TEMPLATE_UNIQUE_NAME2(Name, ...) INTERNAL_CATCH_TEMPLATE_UNIQUE_NAME3(Name, __VA_ARGS__)
  558. #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
  559. #define INTERNAL_CATCH_TEMPLATE_UNIQUE_NAME3(Name,...) Name " - " #__VA_ARGS__
  560. #define INTERNAL_CATCH_TEMPLATE_UNIQUE_NAME(Name,...) INTERNAL_CATCH_TEMPLATE_UNIQUE_NAME2(Name, INTERNAL_CATCH_REMOVE_PARENS(__VA_ARGS__))
  561. #else
  562. // MSVC is adding extra space and needs more calls to properly remove ()
  563. #define INTERNAL_CATCH_TEMPLATE_UNIQUE_NAME3(Name,...) Name " -" #__VA_ARGS__
  564. #define INTERNAL_CATCH_TEMPLATE_UNIQUE_NAME1(Name, ...) INTERNAL_CATCH_TEMPLATE_UNIQUE_NAME2(Name, __VA_ARGS__)
  565. #define INTERNAL_CATCH_TEMPLATE_UNIQUE_NAME(Name, ...) INTERNAL_CATCH_TEMPLATE_UNIQUE_NAME1(Name, INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_REMOVE_PARENS(__VA_ARGS__)))
  566. #endif
  567. // end catch_preprocessor.hpp
  568. namespace Catch {
  569. template<typename C>
  570. class TestInvokerAsMethod : public ITestInvoker {
  571. void (C::*m_testAsMethod)();
  572. public:
  573. TestInvokerAsMethod( void (C::*testAsMethod)() ) noexcept : m_testAsMethod( testAsMethod ) {}
  574. void invoke() const override {
  575. C obj;
  576. (obj.*m_testAsMethod)();
  577. }
  578. };
  579. auto makeTestInvoker( void(*testAsFunction)() ) noexcept -> ITestInvoker*;
  580. template<typename C>
  581. auto makeTestInvoker( void (C::*testAsMethod)() ) noexcept -> ITestInvoker* {
  582. return new(std::nothrow) TestInvokerAsMethod<C>( testAsMethod );
  583. }
  584. struct NameAndTags {
  585. NameAndTags( StringRef const& name_ = StringRef(), StringRef const& tags_ = StringRef() ) noexcept;
  586. StringRef name;
  587. StringRef tags;
  588. };
  589. struct AutoReg : NonCopyable {
  590. AutoReg( ITestInvoker* invoker, SourceLineInfo const& lineInfo, StringRef const& classOrMethod, NameAndTags const& nameAndTags ) noexcept;
  591. ~AutoReg();
  592. };
  593. } // end namespace Catch
  594. #if defined(CATCH_CONFIG_DISABLE)
  595. #define INTERNAL_CATCH_TESTCASE_NO_REGISTRATION( TestName, ... ) \
  596. static void TestName()
  597. #define INTERNAL_CATCH_TESTCASE_METHOD_NO_REGISTRATION( TestName, ClassName, ... ) \
  598. namespace{ \
  599. struct TestName : INTERNAL_CATCH_REMOVE_PARENS(ClassName) { \
  600. void test(); \
  601. }; \
  602. } \
  603. void TestName::test()
  604. #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION( TestName, ... ) \
  605. template<typename TestType> \
  606. static void TestName()
  607. #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION( TestName, ClassName, ... ) \
  608. namespace{ \
  609. template<typename TestType> \
  610. struct TestName : INTERNAL_CATCH_REMOVE_PARENS(ClassName <TestType>) { \
  611. void test(); \
  612. }; \
  613. } \
  614. template<typename TestType> \
  615. void TestName::test()
  616. #endif
  617. ///////////////////////////////////////////////////////////////////////////////
  618. #define INTERNAL_CATCH_TESTCASE2( TestName, ... ) \
  619. static void TestName(); \
  620. CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
  621. namespace{ Catch::AutoReg INTERNAL_CATCH_UNIQUE_NAME( autoRegistrar )( Catch::makeTestInvoker( &TestName ), CATCH_INTERNAL_LINEINFO, Catch::StringRef(), Catch::NameAndTags{ __VA_ARGS__ } ); } /* NOLINT */ \
  622. CATCH_INTERNAL_UNSUPPRESS_GLOBALS_WARNINGS \
  623. static void TestName()
  624. #define INTERNAL_CATCH_TESTCASE( ... ) \
  625. INTERNAL_CATCH_TESTCASE2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ), __VA_ARGS__ )
  626. ///////////////////////////////////////////////////////////////////////////////
  627. #define INTERNAL_CATCH_METHOD_AS_TEST_CASE( QualifiedMethod, ... ) \
  628. CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
  629. namespace{ Catch::AutoReg INTERNAL_CATCH_UNIQUE_NAME( autoRegistrar )( Catch::makeTestInvoker( &QualifiedMethod ), CATCH_INTERNAL_LINEINFO, "&" #QualifiedMethod, Catch::NameAndTags{ __VA_ARGS__ } ); } /* NOLINT */ \
  630. CATCH_INTERNAL_UNSUPPRESS_GLOBALS_WARNINGS
  631. ///////////////////////////////////////////////////////////////////////////////
  632. #define INTERNAL_CATCH_TEST_CASE_METHOD2( TestName, ClassName, ... )\
  633. CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
  634. namespace{ \
  635. struct TestName : INTERNAL_CATCH_REMOVE_PARENS(ClassName) { \
  636. void test(); \
  637. }; \
  638. Catch::AutoReg INTERNAL_CATCH_UNIQUE_NAME( autoRegistrar ) ( Catch::makeTestInvoker( &TestName::test ), CATCH_INTERNAL_LINEINFO, #ClassName, Catch::NameAndTags{ __VA_ARGS__ } ); /* NOLINT */ \
  639. } \
  640. CATCH_INTERNAL_UNSUPPRESS_GLOBALS_WARNINGS \
  641. void TestName::test()
  642. #define INTERNAL_CATCH_TEST_CASE_METHOD( ClassName, ... ) \
  643. INTERNAL_CATCH_TEST_CASE_METHOD2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ), ClassName, __VA_ARGS__ )
  644. ///////////////////////////////////////////////////////////////////////////////
  645. #define INTERNAL_CATCH_REGISTER_TESTCASE( Function, ... ) \
  646. CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
  647. Catch::AutoReg INTERNAL_CATCH_UNIQUE_NAME( autoRegistrar )( Catch::makeTestInvoker( Function ), CATCH_INTERNAL_LINEINFO, Catch::StringRef(), Catch::NameAndTags{ __VA_ARGS__ } ); /* NOLINT */ \
  648. CATCH_INTERNAL_UNSUPPRESS_GLOBALS_WARNINGS
  649. ///////////////////////////////////////////////////////////////////////////////
  650. #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_2(TestName, TestFunc, Name, Tags, ... )\
  651. CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
  652. template<typename TestType> \
  653. static void TestFunc();\
  654. namespace {\
  655. template<typename...Types> \
  656. struct TestName{\
  657. template<typename...Ts> \
  658. TestName(Ts...names){\
  659. CATCH_INTERNAL_CHECK_UNIQUE_TYPES(CATCH_REC_LIST(INTERNAL_CATCH_REMOVE_PARENS, __VA_ARGS__)) \
  660. using expander = int[];\
  661. (void)expander{(Catch::AutoReg( Catch::makeTestInvoker( &TestFunc<Types> ), CATCH_INTERNAL_LINEINFO, Catch::StringRef(), Catch::NameAndTags{ names, Tags } ), 0)... };/* NOLINT */ \
  662. }\
  663. };\
  664. INTERNAL_CATCH_TEMPLATE_REGISTRY_INITIATE(TestName, Name, __VA_ARGS__) \
  665. }\
  666. CATCH_INTERNAL_UNSUPPRESS_GLOBALS_WARNINGS \
  667. template<typename TestType> \
  668. static void TestFunc()
  669. #if defined(CATCH_CPP17_OR_GREATER)
  670. #define CATCH_INTERNAL_CHECK_UNIQUE_TYPES(...) static_assert(Catch::is_unique<__VA_ARGS__>,"Duplicate type detected in declaration of template test case");
  671. #else
  672. #define CATCH_INTERNAL_CHECK_UNIQUE_TYPES(...) static_assert(Catch::is_unique<__VA_ARGS__>::value,"Duplicate type detected in declaration of template test case");
  673. #endif
  674. #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
  675. #define INTERNAL_CATCH_TEMPLATE_TEST_CASE(Name, Tags, ...) \
  676. 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__ )
  677. #else
  678. #define INTERNAL_CATCH_TEMPLATE_TEST_CASE(Name, Tags, ...) \
  679. 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__ ) )
  680. #endif
  681. #define INTERNAL_CATCH_TEMPLATE_REGISTRY_INITIATE(TestName, Name, ...)\
  682. static int INTERNAL_CATCH_UNIQUE_NAME( globalRegistrar ) = [](){\
  683. TestName<CATCH_REC_LIST(INTERNAL_CATCH_REMOVE_PARENS, __VA_ARGS__)>(CATCH_REC_LIST_UD(INTERNAL_CATCH_TEMPLATE_UNIQUE_NAME,Name, __VA_ARGS__));\
  684. return 0;\
  685. }();
  686. #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_2( TestNameClass, TestName, ClassName, Name, Tags, ... ) \
  687. CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
  688. namespace{ \
  689. template<typename TestType> \
  690. struct TestName : INTERNAL_CATCH_REMOVE_PARENS(ClassName <TestType>) { \
  691. void test();\
  692. };\
  693. template<typename...Types> \
  694. struct TestNameClass{\
  695. template<typename...Ts> \
  696. TestNameClass(Ts...names){\
  697. CATCH_INTERNAL_CHECK_UNIQUE_TYPES(CATCH_REC_LIST(INTERNAL_CATCH_REMOVE_PARENS, __VA_ARGS__)) \
  698. using expander = int[];\
  699. (void)expander{(Catch::AutoReg( Catch::makeTestInvoker( &TestName<Types>::test ), CATCH_INTERNAL_LINEINFO, #ClassName, Catch::NameAndTags{ names, Tags } ), 0)... };/* NOLINT */ \
  700. }\
  701. };\
  702. INTERNAL_CATCH_TEMPLATE_REGISTRY_INITIATE(TestNameClass, Name, __VA_ARGS__)\
  703. }\
  704. CATCH_INTERNAL_UNSUPPRESS_GLOBALS_WARNINGS\
  705. template<typename TestType> \
  706. void TestName<TestType>::test()
  707. #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
  708. #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD( ClassName, Name, Tags,... ) \
  709. 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__ )
  710. #else
  711. #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD( ClassName, Name, Tags,... ) \
  712. 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__ ) )
  713. #endif
  714. // end catch_test_registry.h
  715. // start catch_capture.hpp
  716. // start catch_assertionhandler.h
  717. // start catch_assertioninfo.h
  718. // start catch_result_type.h
  719. namespace Catch {
  720. // ResultWas::OfType enum
  721. struct ResultWas { enum OfType {
  722. Unknown = -1,
  723. Ok = 0,
  724. Info = 1,
  725. Warning = 2,
  726. FailureBit = 0x10,
  727. ExpressionFailed = FailureBit | 1,
  728. ExplicitFailure = FailureBit | 2,
  729. Exception = 0x100 | FailureBit,
  730. ThrewException = Exception | 1,
  731. DidntThrowException = Exception | 2,
  732. FatalErrorCondition = 0x200 | FailureBit
  733. }; };
  734. bool isOk( ResultWas::OfType resultType );
  735. bool isJustInfo( int flags );
  736. // ResultDisposition::Flags enum
  737. struct ResultDisposition { enum Flags {
  738. Normal = 0x01,
  739. ContinueOnFailure = 0x02, // Failures fail test, but execution continues
  740. FalseTest = 0x04, // Prefix expression with !
  741. SuppressFail = 0x08 // Failures are reported but do not fail the test
  742. }; };
  743. ResultDisposition::Flags operator | ( ResultDisposition::Flags lhs, ResultDisposition::Flags rhs );
  744. bool shouldContinueOnFailure( int flags );
  745. inline bool isFalseTest( int flags ) { return ( flags & ResultDisposition::FalseTest ) != 0; }
  746. bool shouldSuppressFailure( int flags );
  747. } // end namespace Catch
  748. // end catch_result_type.h
  749. namespace Catch {
  750. struct AssertionInfo
  751. {
  752. StringRef macroName;
  753. SourceLineInfo lineInfo;
  754. StringRef capturedExpression;
  755. ResultDisposition::Flags resultDisposition;
  756. // We want to delete this constructor but a compiler bug in 4.8 means
  757. // the struct is then treated as non-aggregate
  758. //AssertionInfo() = delete;
  759. };
  760. } // end namespace Catch
  761. // end catch_assertioninfo.h
  762. // start catch_decomposer.h
  763. // start catch_tostring.h
  764. #include <vector>
  765. #include <cstddef>
  766. #include <type_traits>
  767. #include <string>
  768. // start catch_stream.h
  769. #include <iosfwd>
  770. #include <cstddef>
  771. #include <ostream>
  772. namespace Catch {
  773. std::ostream& cout();
  774. std::ostream& cerr();
  775. std::ostream& clog();
  776. class StringRef;
  777. struct IStream {
  778. virtual ~IStream();
  779. virtual std::ostream& stream() const = 0;
  780. };
  781. auto makeStream( StringRef const &filename ) -> IStream const*;
  782. class ReusableStringStream {
  783. std::size_t m_index;
  784. std::ostream* m_oss;
  785. public:
  786. ReusableStringStream();
  787. ~ReusableStringStream();
  788. auto str() const -> std::string;
  789. template<typename T>
  790. auto operator << ( T const& value ) -> ReusableStringStream& {
  791. *m_oss << value;
  792. return *this;
  793. }
  794. auto get() -> std::ostream& { return *m_oss; }
  795. };
  796. }
  797. // end catch_stream.h
  798. #ifdef CATCH_CONFIG_CPP17_STRING_VIEW
  799. #include <string_view>
  800. #endif
  801. #ifdef __OBJC__
  802. // start catch_objc_arc.hpp
  803. #import <Foundation/Foundation.h>
  804. #ifdef __has_feature
  805. #define CATCH_ARC_ENABLED __has_feature(objc_arc)
  806. #else
  807. #define CATCH_ARC_ENABLED 0
  808. #endif
  809. void arcSafeRelease( NSObject* obj );
  810. id performOptionalSelector( id obj, SEL sel );
  811. #if !CATCH_ARC_ENABLED
  812. inline void arcSafeRelease( NSObject* obj ) {
  813. [obj release];
  814. }
  815. inline id performOptionalSelector( id obj, SEL sel ) {
  816. if( [obj respondsToSelector: sel] )
  817. return [obj performSelector: sel];
  818. return nil;
  819. }
  820. #define CATCH_UNSAFE_UNRETAINED
  821. #define CATCH_ARC_STRONG
  822. #else
  823. inline void arcSafeRelease( NSObject* ){}
  824. inline id performOptionalSelector( id obj, SEL sel ) {
  825. #ifdef __clang__
  826. #pragma clang diagnostic push
  827. #pragma clang diagnostic ignored "-Warc-performSelector-leaks"
  828. #endif
  829. if( [obj respondsToSelector: sel] )
  830. return [obj performSelector: sel];
  831. #ifdef __clang__
  832. #pragma clang diagnostic pop
  833. #endif
  834. return nil;
  835. }
  836. #define CATCH_UNSAFE_UNRETAINED __unsafe_unretained
  837. #define CATCH_ARC_STRONG __strong
  838. #endif
  839. // end catch_objc_arc.hpp
  840. #endif
  841. #ifdef _MSC_VER
  842. #pragma warning(push)
  843. #pragma warning(disable:4180) // We attempt to stream a function (address) by const&, which MSVC complains about but is harmless
  844. #endif
  845. namespace Catch {
  846. namespace Detail {
  847. extern const std::string unprintableString;
  848. std::string rawMemoryToString( const void *object, std::size_t size );
  849. template<typename T>
  850. std::string rawMemoryToString( const T& object ) {
  851. return rawMemoryToString( &object, sizeof(object) );
  852. }
  853. template<typename T>
  854. class IsStreamInsertable {
  855. template<typename SS, typename TT>
  856. static auto test(int)
  857. -> decltype(std::declval<SS&>() << std::declval<TT>(), std::true_type());
  858. template<typename, typename>
  859. static auto test(...)->std::false_type;
  860. public:
  861. static const bool value = decltype(test<std::ostream, const T&>(0))::value;
  862. };
  863. template<typename E>
  864. std::string convertUnknownEnumToString( E e );
  865. template<typename T>
  866. typename std::enable_if<
  867. !std::is_enum<T>::value && !std::is_base_of<std::exception, T>::value,
  868. std::string>::type convertUnstreamable( T const& ) {
  869. return Detail::unprintableString;
  870. }
  871. template<typename T>
  872. typename std::enable_if<
  873. !std::is_enum<T>::value && std::is_base_of<std::exception, T>::value,
  874. std::string>::type convertUnstreamable(T const& ex) {
  875. return ex.what();
  876. }
  877. template<typename T>
  878. typename std::enable_if<
  879. std::is_enum<T>::value
  880. , std::string>::type convertUnstreamable( T const& value ) {
  881. return convertUnknownEnumToString( value );
  882. }
  883. #if defined(_MANAGED)
  884. //! Convert a CLR string to a utf8 std::string
  885. template<typename T>
  886. std::string clrReferenceToString( T^ ref ) {
  887. if (ref == nullptr)
  888. return std::string("null");
  889. auto bytes = System::Text::Encoding::UTF8->GetBytes(ref->ToString());
  890. cli::pin_ptr<System::Byte> p = &bytes[0];
  891. return std::string(reinterpret_cast<char const *>(p), bytes->Length);
  892. }
  893. #endif
  894. } // namespace Detail
  895. // If we decide for C++14, change these to enable_if_ts
  896. template <typename T, typename = void>
  897. struct StringMaker {
  898. template <typename Fake = T>
  899. static
  900. typename std::enable_if<::Catch::Detail::IsStreamInsertable<Fake>::value, std::string>::type
  901. convert(const Fake& value) {
  902. ReusableStringStream rss;
  903. // NB: call using the function-like syntax to avoid ambiguity with
  904. // user-defined templated operator<< under clang.
  905. rss.operator<<(value);
  906. return rss.str();
  907. }
  908. template <typename Fake = T>
  909. static
  910. typename std::enable_if<!::Catch::Detail::IsStreamInsertable<Fake>::value, std::string>::type
  911. convert( const Fake& value ) {
  912. #if !defined(CATCH_CONFIG_FALLBACK_STRINGIFIER)
  913. return Detail::convertUnstreamable(value);
  914. #else
  915. return CATCH_CONFIG_FALLBACK_STRINGIFIER(value);
  916. #endif
  917. }
  918. };
  919. namespace Detail {
  920. // This function dispatches all stringification requests inside of Catch.
  921. // Should be preferably called fully qualified, like ::Catch::Detail::stringify
  922. template <typename T>
  923. std::string stringify(const T& e) {
  924. return ::Catch::StringMaker<typename std::remove_cv<typename std::remove_reference<T>::type>::type>::convert(e);
  925. }
  926. template<typename E>
  927. std::string convertUnknownEnumToString( E e ) {
  928. return ::Catch::Detail::stringify(static_cast<typename std::underlying_type<E>::type>(e));
  929. }
  930. #if defined(_MANAGED)
  931. template <typename T>
  932. std::string stringify( T^ e ) {
  933. return ::Catch::StringMaker<T^>::convert(e);
  934. }
  935. #endif
  936. } // namespace Detail
  937. // Some predefined specializations
  938. template<>
  939. struct StringMaker<std::string> {
  940. static std::string convert(const std::string& str);
  941. };
  942. #ifdef CATCH_CONFIG_CPP17_STRING_VIEW
  943. template<>
  944. struct StringMaker<std::string_view> {
  945. static std::string convert(std::string_view str);
  946. };
  947. #endif
  948. template<>
  949. struct StringMaker<char const *> {
  950. static std::string convert(char const * str);
  951. };
  952. template<>
  953. struct StringMaker<char *> {
  954. static std::string convert(char * str);
  955. };
  956. #ifdef CATCH_CONFIG_WCHAR
  957. template<>
  958. struct StringMaker<std::wstring> {
  959. static std::string convert(const std::wstring& wstr);
  960. };
  961. # ifdef CATCH_CONFIG_CPP17_STRING_VIEW
  962. template<>
  963. struct StringMaker<std::wstring_view> {
  964. static std::string convert(std::wstring_view str);
  965. };
  966. # endif
  967. template<>
  968. struct StringMaker<wchar_t const *> {
  969. static std::string convert(wchar_t const * str);
  970. };
  971. template<>
  972. struct StringMaker<wchar_t *> {
  973. static std::string convert(wchar_t * str);
  974. };
  975. #endif
  976. // TBD: Should we use `strnlen` to ensure that we don't go out of the buffer,
  977. // while keeping string semantics?
  978. template<int SZ>
  979. struct StringMaker<char[SZ]> {
  980. static std::string convert(char const* str) {
  981. return ::Catch::Detail::stringify(std::string{ str });
  982. }
  983. };
  984. template<int SZ>
  985. struct StringMaker<signed char[SZ]> {
  986. static std::string convert(signed char const* str) {
  987. return ::Catch::Detail::stringify(std::string{ reinterpret_cast<char const *>(str) });
  988. }
  989. };
  990. template<int SZ>
  991. struct StringMaker<unsigned char[SZ]> {
  992. static std::string convert(unsigned char const* str) {
  993. return ::Catch::Detail::stringify(std::string{ reinterpret_cast<char const *>(str) });
  994. }
  995. };
  996. template<>
  997. struct StringMaker<int> {
  998. static std::string convert(int value);
  999. };
  1000. template<>
  1001. struct StringMaker<long> {
  1002. static std::string convert(long value);
  1003. };
  1004. template<>
  1005. struct StringMaker<long long> {
  1006. static std::string convert(long long value);
  1007. };
  1008. template<>
  1009. struct StringMaker<unsigned int> {
  1010. static std::string convert(unsigned int value);
  1011. };
  1012. template<>
  1013. struct StringMaker<unsigned long> {
  1014. static std::string convert(unsigned long value);
  1015. };
  1016. template<>
  1017. struct StringMaker<unsigned long long> {
  1018. static std::string convert(unsigned long long value);
  1019. };
  1020. template<>
  1021. struct StringMaker<bool> {
  1022. static std::string convert(bool b);
  1023. };
  1024. template<>
  1025. struct StringMaker<char> {
  1026. static std::string convert(char c);
  1027. };
  1028. template<>
  1029. struct StringMaker<signed char> {
  1030. static std::string convert(signed char c);
  1031. };
  1032. template<>
  1033. struct StringMaker<unsigned char> {
  1034. static std::string convert(unsigned char c);
  1035. };
  1036. template<>
  1037. struct StringMaker<std::nullptr_t> {
  1038. static std::string convert(std::nullptr_t);
  1039. };
  1040. template<>
  1041. struct StringMaker<float> {
  1042. static std::string convert(float value);
  1043. };
  1044. template<>
  1045. struct StringMaker<double> {
  1046. static std::string convert(double value);
  1047. };
  1048. template <typename T>
  1049. struct StringMaker<T*> {
  1050. template <typename U>
  1051. static std::string convert(U* p) {
  1052. if (p) {
  1053. return ::Catch::Detail::rawMemoryToString(p);
  1054. } else {
  1055. return "nullptr";
  1056. }
  1057. }
  1058. };
  1059. template <typename R, typename C>
  1060. struct StringMaker<R C::*> {
  1061. static std::string convert(R C::* p) {
  1062. if (p) {
  1063. return ::Catch::Detail::rawMemoryToString(p);
  1064. } else {
  1065. return "nullptr";
  1066. }
  1067. }
  1068. };
  1069. #if defined(_MANAGED)
  1070. template <typename T>
  1071. struct StringMaker<T^> {
  1072. static std::string convert( T^ ref ) {
  1073. return ::Catch::Detail::clrReferenceToString(ref);
  1074. }
  1075. };
  1076. #endif
  1077. namespace Detail {
  1078. template<typename InputIterator>
  1079. std::string rangeToString(InputIterator first, InputIterator last) {
  1080. ReusableStringStream rss;
  1081. rss << "{ ";
  1082. if (first != last) {
  1083. rss << ::Catch::Detail::stringify(*first);
  1084. for (++first; first != last; ++first)
  1085. rss << ", " << ::Catch::Detail::stringify(*first);
  1086. }
  1087. rss << " }";
  1088. return rss.str();
  1089. }
  1090. }
  1091. #ifdef __OBJC__
  1092. template<>
  1093. struct StringMaker<NSString*> {
  1094. static std::string convert(NSString * nsstring) {
  1095. if (!nsstring)
  1096. return "nil";
  1097. return std::string("@") + [nsstring UTF8String];
  1098. }
  1099. };
  1100. template<>
  1101. struct StringMaker<NSObject*> {
  1102. static std::string convert(NSObject* nsObject) {
  1103. return ::Catch::Detail::stringify([nsObject description]);
  1104. }
  1105. };
  1106. namespace Detail {
  1107. inline std::string stringify( NSString* nsstring ) {
  1108. return StringMaker<NSString*>::convert( nsstring );
  1109. }
  1110. } // namespace Detail
  1111. #endif // __OBJC__
  1112. } // namespace Catch
  1113. //////////////////////////////////////////////////////
  1114. // Separate std-lib types stringification, so it can be selectively enabled
  1115. // This means that we do not bring in
  1116. #if defined(CATCH_CONFIG_ENABLE_ALL_STRINGMAKERS)
  1117. # define CATCH_CONFIG_ENABLE_PAIR_STRINGMAKER
  1118. # define CATCH_CONFIG_ENABLE_TUPLE_STRINGMAKER
  1119. # define CATCH_CONFIG_ENABLE_VARIANT_STRINGMAKER
  1120. # define CATCH_CONFIG_ENABLE_CHRONO_STRINGMAKER
  1121. #endif
  1122. // Separate std::pair specialization
  1123. #if defined(CATCH_CONFIG_ENABLE_PAIR_STRINGMAKER)
  1124. #include <utility>
  1125. namespace Catch {
  1126. template<typename T1, typename T2>
  1127. struct StringMaker<std::pair<T1, T2> > {
  1128. static std::string convert(const std::pair<T1, T2>& pair) {
  1129. ReusableStringStream rss;
  1130. rss << "{ "
  1131. << ::Catch::Detail::stringify(pair.first)
  1132. << ", "
  1133. << ::Catch::Detail::stringify(pair.second)
  1134. << " }";
  1135. return rss.str();
  1136. }
  1137. };
  1138. }
  1139. #endif // CATCH_CONFIG_ENABLE_PAIR_STRINGMAKER
  1140. // Separate std::tuple specialization
  1141. #if defined(CATCH_CONFIG_ENABLE_TUPLE_STRINGMAKER)
  1142. #include <tuple>
  1143. namespace Catch {
  1144. namespace Detail {
  1145. template<
  1146. typename Tuple,
  1147. std::size_t N = 0,
  1148. bool = (N < std::tuple_size<Tuple>::value)
  1149. >
  1150. struct TupleElementPrinter {
  1151. static void print(const Tuple& tuple, std::ostream& os) {
  1152. os << (N ? ", " : " ")
  1153. << ::Catch::Detail::stringify(std::get<N>(tuple));
  1154. TupleElementPrinter<Tuple, N + 1>::print(tuple, os);
  1155. }
  1156. };
  1157. template<
  1158. typename Tuple,
  1159. std::size_t N
  1160. >
  1161. struct TupleElementPrinter<Tuple, N, false> {
  1162. static void print(const Tuple&, std::ostream&) {}
  1163. };
  1164. }
  1165. template<typename ...Types>
  1166. struct StringMaker<std::tuple<Types...>> {
  1167. static std::string convert(const std::tuple<Types...>& tuple) {
  1168. ReusableStringStream rss;
  1169. rss << '{';
  1170. Detail::TupleElementPrinter<std::tuple<Types...>>::print(tuple, rss.get());
  1171. rss << " }";
  1172. return rss.str();
  1173. }
  1174. };
  1175. }
  1176. #endif // CATCH_CONFIG_ENABLE_TUPLE_STRINGMAKER
  1177. #if defined(CATCH_CONFIG_ENABLE_VARIANT_STRINGMAKER) && defined(CATCH_CONFIG_CPP17_VARIANT)
  1178. #include <variant>
  1179. namespace Catch {
  1180. template<>
  1181. struct StringMaker<std::monostate> {
  1182. static std::string convert(const std::monostate&) {
  1183. return "{ }";
  1184. }
  1185. };
  1186. template<typename... Elements>
  1187. struct StringMaker<std::variant<Elements...>> {
  1188. static std::string convert(const std::variant<Elements...>& variant) {
  1189. if (variant.valueless_by_exception()) {
  1190. return "{valueless variant}";
  1191. } else {
  1192. return std::visit(
  1193. [](const auto& value) {
  1194. return ::Catch::Detail::stringify(value);
  1195. },
  1196. variant
  1197. );
  1198. }
  1199. }
  1200. };
  1201. }
  1202. #endif // CATCH_CONFIG_ENABLE_VARIANT_STRINGMAKER
  1203. namespace Catch {
  1204. struct not_this_one {}; // Tag type for detecting which begin/ end are being selected
  1205. // Import begin/ end from std here so they are considered alongside the fallback (...) overloads in this namespace
  1206. using std::begin;
  1207. using std::end;
  1208. not_this_one begin( ... );
  1209. not_this_one end( ... );
  1210. template <typename T>
  1211. struct is_range {
  1212. static const bool value =
  1213. !std::is_same<decltype(begin(std::declval<T>())), not_this_one>::value &&
  1214. !std::is_same<decltype(end(std::declval<T>())), not_this_one>::value;
  1215. };
  1216. #if defined(_MANAGED) // Managed types are never ranges
  1217. template <typename T>
  1218. struct is_range<T^> {
  1219. static const bool value = false;
  1220. };
  1221. #endif
  1222. template<typename Range>
  1223. std::string rangeToString( Range const& range ) {
  1224. return ::Catch::Detail::rangeToString( begin( range ), end( range ) );
  1225. }
  1226. // Handle vector<bool> specially
  1227. template<typename Allocator>
  1228. std::string rangeToString( std::vector<bool, Allocator> const& v ) {
  1229. ReusableStringStream rss;
  1230. rss << "{ ";
  1231. bool first = true;
  1232. for( bool b : v ) {
  1233. if( first )
  1234. first = false;
  1235. else
  1236. rss << ", ";
  1237. rss << ::Catch::Detail::stringify( b );
  1238. }
  1239. rss << " }";
  1240. return rss.str();
  1241. }
  1242. template<typename R>
  1243. struct StringMaker<R, typename std::enable_if<is_range<R>::value && !::Catch::Detail::IsStreamInsertable<R>::value>::type> {
  1244. static std::string convert( R const& range ) {
  1245. return rangeToString( range );
  1246. }
  1247. };
  1248. template <typename T, int SZ>
  1249. struct StringMaker<T[SZ]> {
  1250. static std::string convert(T const(&arr)[SZ]) {
  1251. return rangeToString(arr);
  1252. }
  1253. };
  1254. } // namespace Catch
  1255. // Separate std::chrono::duration specialization
  1256. #if defined(CATCH_CONFIG_ENABLE_CHRONO_STRINGMAKER)
  1257. #include <ctime>
  1258. #include <ratio>
  1259. #include <chrono>
  1260. namespace Catch {
  1261. template <class Ratio>
  1262. struct ratio_string {
  1263. static std::string symbol();
  1264. };
  1265. template <class Ratio>
  1266. std::string ratio_string<Ratio>::symbol() {
  1267. Catch::ReusableStringStream rss;
  1268. rss << '[' << Ratio::num << '/'
  1269. << Ratio::den << ']';
  1270. return rss.str();
  1271. }
  1272. template <>
  1273. struct ratio_string<std::atto> {
  1274. static std::string symbol();
  1275. };
  1276. template <>
  1277. struct ratio_string<std::femto> {
  1278. static std::string symbol();
  1279. };
  1280. template <>
  1281. struct ratio_string<std::pico> {
  1282. static std::string symbol();
  1283. };
  1284. template <>
  1285. struct ratio_string<std::nano> {
  1286. static std::string symbol();
  1287. };
  1288. template <>
  1289. struct ratio_string<std::micro> {
  1290. static std::string symbol();
  1291. };
  1292. template <>
  1293. struct ratio_string<std::milli> {
  1294. static std::string symbol();
  1295. };
  1296. ////////////
  1297. // std::chrono::duration specializations
  1298. template<typename Value, typename Ratio>
  1299. struct StringMaker<std::chrono::duration<Value, Ratio>> {
  1300. static std::string convert(std::chrono::duration<Value, Ratio> const& duration) {
  1301. ReusableStringStream rss;
  1302. rss << duration.count() << ' ' << ratio_string<Ratio>::symbol() << 's';
  1303. return rss.str();
  1304. }
  1305. };
  1306. template<typename Value>
  1307. struct StringMaker<std::chrono::duration<Value, std::ratio<1>>> {
  1308. static std::string convert(std::chrono::duration<Value, std::ratio<1>> const& duration) {
  1309. ReusableStringStream rss;
  1310. rss << duration.count() << " s";
  1311. return rss.str();
  1312. }
  1313. };
  1314. template<typename Value>
  1315. struct StringMaker<std::chrono::duration<Value, std::ratio<60>>> {
  1316. static std::string convert(std::chrono::duration<Value, std::ratio<60>> const& duration) {
  1317. ReusableStringStream rss;
  1318. rss << duration.count() << " m";
  1319. return rss.str();
  1320. }
  1321. };
  1322. template<typename Value>
  1323. struct StringMaker<std::chrono::duration<Value, std::ratio<3600>>> {
  1324. static std::string convert(std::chrono::duration<Value, std::ratio<3600>> const& duration) {
  1325. ReusableStringStream rss;
  1326. rss << duration.count() << " h";
  1327. return rss.str();
  1328. }
  1329. };
  1330. ////////////
  1331. // std::chrono::time_point specialization
  1332. // Generic time_point cannot be specialized, only std::chrono::time_point<system_clock>
  1333. template<typename Clock, typename Duration>
  1334. struct StringMaker<std::chrono::time_point<Clock, Duration>> {
  1335. static std::string convert(std::chrono::time_point<Clock, Duration> const& time_point) {
  1336. return ::Catch::Detail::stringify(time_point.time_since_epoch()) + " since epoch";
  1337. }
  1338. };
  1339. // std::chrono::time_point<system_clock> specialization
  1340. template<typename Duration>
  1341. struct StringMaker<std::chrono::time_point<std::chrono::system_clock, Duration>> {
  1342. static std::string convert(std::chrono::time_point<std::chrono::system_clock, Duration> const& time_point) {
  1343. auto converted = std::chrono::system_clock::to_time_t(time_point);
  1344. #ifdef _MSC_VER
  1345. std::tm timeInfo = {};
  1346. gmtime_s(&timeInfo, &converted);
  1347. #else
  1348. std::tm* timeInfo = std::gmtime(&converted);
  1349. #endif
  1350. auto const timeStampSize = sizeof("2017-01-16T17:06:45Z");
  1351. char timeStamp[timeStampSize];
  1352. const char * const fmt = "%Y-%m-%dT%H:%M:%SZ";
  1353. #ifdef _MSC_VER
  1354. std::strftime(timeStamp, timeStampSize, fmt, &timeInfo);
  1355. #else
  1356. std::strftime(timeStamp, timeStampSize, fmt, timeInfo);
  1357. #endif
  1358. return std::string(timeStamp);
  1359. }
  1360. };
  1361. }
  1362. #endif // CATCH_CONFIG_ENABLE_CHRONO_STRINGMAKER
  1363. #ifdef _MSC_VER
  1364. #pragma warning(pop)
  1365. #endif
  1366. // end catch_tostring.h
  1367. #include <iosfwd>
  1368. #ifdef _MSC_VER
  1369. #pragma warning(push)
  1370. #pragma warning(disable:4389) // '==' : signed/unsigned mismatch
  1371. #pragma warning(disable:4018) // more "signed/unsigned mismatch"
  1372. #pragma warning(disable:4312) // Converting int to T* using reinterpret_cast (issue on x64 platform)
  1373. #pragma warning(disable:4180) // qualifier applied to function type has no meaning
  1374. #endif
  1375. namespace Catch {
  1376. struct ITransientExpression {
  1377. auto isBinaryExpression() const -> bool { return m_isBinaryExpression; }
  1378. auto getResult() const -> bool { return m_result; }
  1379. virtual void streamReconstructedExpression( std::ostream &os ) const = 0;
  1380. ITransientExpression( bool isBinaryExpression, bool result )
  1381. : m_isBinaryExpression( isBinaryExpression ),
  1382. m_result( result )
  1383. {}
  1384. // We don't actually need a virtual destructor, but many static analysers
  1385. // complain if it's not here :-(
  1386. virtual ~ITransientExpression();
  1387. bool m_isBinaryExpression;
  1388. bool m_result;
  1389. };
  1390. void formatReconstructedExpression( std::ostream &os, std::string const& lhs, StringRef op, std::string const& rhs );
  1391. template<typename LhsT, typename RhsT>
  1392. class BinaryExpr : public ITransientExpression {
  1393. LhsT m_lhs;
  1394. StringRef m_op;
  1395. RhsT m_rhs;
  1396. void streamReconstructedExpression( std::ostream &os ) const override {
  1397. formatReconstructedExpression
  1398. ( os, Catch::Detail::stringify( m_lhs ), m_op, Catch::Detail::stringify( m_rhs ) );
  1399. }
  1400. public:
  1401. BinaryExpr( bool comparisonResult, LhsT lhs, StringRef op, RhsT rhs )
  1402. : ITransientExpression{ true, comparisonResult },
  1403. m_lhs( lhs ),
  1404. m_op( op ),
  1405. m_rhs( rhs )
  1406. {}
  1407. };
  1408. template<typename LhsT>
  1409. class UnaryExpr : public ITransientExpression {
  1410. LhsT m_lhs;
  1411. void streamReconstructedExpression( std::ostream &os ) const override {
  1412. os << Catch::Detail::stringify( m_lhs );
  1413. }
  1414. public:
  1415. explicit UnaryExpr( LhsT lhs )
  1416. : ITransientExpression{ false, lhs ? true : false },
  1417. m_lhs( lhs )
  1418. {}
  1419. };
  1420. // Specialised comparison functions to handle equality comparisons between ints and pointers (NULL deduces as an int)
  1421. template<typename LhsT, typename RhsT>
  1422. auto compareEqual( LhsT const& lhs, RhsT const& rhs ) -> bool { return static_cast<bool>(lhs == rhs); }
  1423. template<typename T>
  1424. auto compareEqual( T* const& lhs, int rhs ) -> bool { return lhs == reinterpret_cast<void const*>( rhs ); }
  1425. template<typename T>
  1426. auto compareEqual( T* const& lhs, long rhs ) -> bool { return lhs == reinterpret_cast<void const*>( rhs ); }
  1427. template<typename T>
  1428. auto compareEqual( int lhs, T* const& rhs ) -> bool { return reinterpret_cast<void const*>( lhs ) == rhs; }
  1429. template<typename T>
  1430. auto compareEqual( long lhs, T* const& rhs ) -> bool { return reinterpret_cast<void const*>( lhs ) == rhs; }
  1431. template<typename LhsT, typename RhsT>
  1432. auto compareNotEqual( LhsT const& lhs, RhsT&& rhs ) -> bool { return static_cast<bool>(lhs != rhs); }
  1433. template<typename T>
  1434. auto compareNotEqual( T* const& lhs, int rhs ) -> bool { return lhs != reinterpret_cast<void const*>( rhs ); }
  1435. template<typename T>
  1436. auto compareNotEqual( T* const& lhs, long rhs ) -> bool { return lhs != reinterpret_cast<void const*>( rhs ); }
  1437. template<typename T>
  1438. auto compareNotEqual( int lhs, T* const& rhs ) -> bool { return reinterpret_cast<void const*>( lhs ) != rhs; }
  1439. template<typename T>
  1440. auto compareNotEqual( long lhs, T* const& rhs ) -> bool { return reinterpret_cast<void const*>( lhs ) != rhs; }
  1441. template<typename LhsT>
  1442. class ExprLhs {
  1443. LhsT m_lhs;
  1444. public:
  1445. explicit ExprLhs( LhsT lhs ) : m_lhs( lhs ) {}
  1446. template<typename RhsT>
  1447. auto operator == ( RhsT const& rhs ) -> BinaryExpr<LhsT, RhsT const&> const {
  1448. return { compareEqual( m_lhs, rhs ), m_lhs, "==", rhs };
  1449. }
  1450. auto operator == ( bool rhs ) -> BinaryExpr<LhsT, bool> const {
  1451. return { m_lhs == rhs, m_lhs, "==", rhs };
  1452. }
  1453. template<typename RhsT>
  1454. auto operator != ( RhsT const& rhs ) -> BinaryExpr<LhsT, RhsT const&> const {
  1455. return { compareNotEqual( m_lhs, rhs ), m_lhs, "!=", rhs };
  1456. }
  1457. auto operator != ( bool rhs ) -> BinaryExpr<LhsT, bool> const {
  1458. return { m_lhs != rhs, m_lhs, "!=", rhs };
  1459. }
  1460. template<typename RhsT>
  1461. auto operator > ( RhsT const& rhs ) -> BinaryExpr<LhsT, RhsT const&> const {
  1462. return { static_cast<bool>(m_lhs > rhs), m_lhs, ">", rhs };
  1463. }
  1464. template<typename RhsT>
  1465. auto operator < ( RhsT const& rhs ) -> BinaryExpr<LhsT, RhsT const&> const {
  1466. return { static_cast<bool>(m_lhs < rhs), m_lhs, "<", rhs };
  1467. }
  1468. template<typename RhsT>
  1469. auto operator >= ( RhsT const& rhs ) -> BinaryExpr<LhsT, RhsT const&> const {
  1470. return { static_cast<bool>(m_lhs >= rhs), m_lhs, ">=", rhs };
  1471. }
  1472. template<typename RhsT>
  1473. auto operator <= ( RhsT const& rhs ) -> BinaryExpr<LhsT, RhsT const&> const {
  1474. return { static_cast<bool>(m_lhs <= rhs), m_lhs, "<=", rhs };
  1475. }
  1476. auto makeUnaryExpr() const -> UnaryExpr<LhsT> {
  1477. return UnaryExpr<LhsT>{ m_lhs };
  1478. }
  1479. };
  1480. void handleExpression( ITransientExpression const& expr );
  1481. template<typename T>
  1482. void handleExpression( ExprLhs<T> const& expr ) {
  1483. handleExpression( expr.makeUnaryExpr() );
  1484. }
  1485. struct Decomposer {
  1486. template<typename T>
  1487. auto operator <= ( T const& lhs ) -> ExprLhs<T const&> {
  1488. return ExprLhs<T const&>{ lhs };
  1489. }
  1490. auto operator <=( bool value ) -> ExprLhs<bool> {
  1491. return ExprLhs<bool>{ value };
  1492. }
  1493. };
  1494. } // end namespace Catch
  1495. #ifdef _MSC_VER
  1496. #pragma warning(pop)
  1497. #endif
  1498. // end catch_decomposer.h
  1499. // start catch_interfaces_capture.h
  1500. #include <string>
  1501. namespace Catch {
  1502. class AssertionResult;
  1503. struct AssertionInfo;
  1504. struct SectionInfo;
  1505. struct SectionEndInfo;
  1506. struct MessageInfo;
  1507. struct Counts;
  1508. struct BenchmarkInfo;
  1509. struct BenchmarkStats;
  1510. struct AssertionReaction;
  1511. struct SourceLineInfo;
  1512. struct ITransientExpression;
  1513. struct IGeneratorTracker;
  1514. struct IResultCapture {
  1515. virtual ~IResultCapture();
  1516. virtual bool sectionStarted( SectionInfo const& sectionInfo,
  1517. Counts& assertions ) = 0;
  1518. virtual void sectionEnded( SectionEndInfo const& endInfo ) = 0;
  1519. virtual void sectionEndedEarly( SectionEndInfo const& endInfo ) = 0;
  1520. virtual auto acquireGeneratorTracker( SourceLineInfo const& lineInfo ) -> IGeneratorTracker& = 0;
  1521. virtual void benchmarkStarting( BenchmarkInfo const& info ) = 0;
  1522. virtual void benchmarkEnded( BenchmarkStats const& stats ) = 0;
  1523. virtual void pushScopedMessage( MessageInfo const& message ) = 0;
  1524. virtual void popScopedMessage( MessageInfo const& message ) = 0;
  1525. virtual void handleFatalErrorCondition( StringRef message ) = 0;
  1526. virtual void handleExpr
  1527. ( AssertionInfo const& info,
  1528. ITransientExpression const& expr,
  1529. AssertionReaction& reaction ) = 0;
  1530. virtual void handleMessage
  1531. ( AssertionInfo const& info,
  1532. ResultWas::OfType resultType,
  1533. StringRef const& message,
  1534. AssertionReaction& reaction ) = 0;
  1535. virtual void handleUnexpectedExceptionNotThrown
  1536. ( AssertionInfo const& info,
  1537. AssertionReaction& reaction ) = 0;
  1538. virtual void handleUnexpectedInflightException
  1539. ( AssertionInfo const& info,
  1540. std::string const& message,
  1541. AssertionReaction& reaction ) = 0;
  1542. virtual void handleIncomplete
  1543. ( AssertionInfo const& info ) = 0;
  1544. virtual void handleNonExpr
  1545. ( AssertionInfo const &info,
  1546. ResultWas::OfType resultType,
  1547. AssertionReaction &reaction ) = 0;
  1548. virtual bool lastAssertionPassed() = 0;
  1549. virtual void assertionPassed() = 0;
  1550. // Deprecated, do not use:
  1551. virtual std::string getCurrentTestName() const = 0;
  1552. virtual const AssertionResult* getLastResult() const = 0;
  1553. virtual void exceptionEarlyReported() = 0;
  1554. };
  1555. IResultCapture& getResultCapture();
  1556. }
  1557. // end catch_interfaces_capture.h
  1558. namespace Catch {
  1559. struct TestFailureException{};
  1560. struct AssertionResultData;
  1561. struct IResultCapture;
  1562. class RunContext;
  1563. class LazyExpression {
  1564. friend class AssertionHandler;
  1565. friend struct AssertionStats;
  1566. friend class RunContext;
  1567. ITransientExpression const* m_transientExpression = nullptr;
  1568. bool m_isNegated;
  1569. public:
  1570. LazyExpression( bool isNegated );
  1571. LazyExpression( LazyExpression const& other );
  1572. LazyExpression& operator = ( LazyExpression const& ) = delete;
  1573. explicit operator bool() const;
  1574. friend auto operator << ( std::ostream& os, LazyExpression const& lazyExpr ) -> std::ostream&;
  1575. };
  1576. struct AssertionReaction {
  1577. bool shouldDebugBreak = false;
  1578. bool shouldThrow = false;
  1579. };
  1580. class AssertionHandler {
  1581. AssertionInfo m_assertionInfo;
  1582. AssertionReaction m_reaction;
  1583. bool m_completed = false;
  1584. IResultCapture& m_resultCapture;
  1585. public:
  1586. AssertionHandler
  1587. ( StringRef const& macroName,
  1588. SourceLineInfo const& lineInfo,
  1589. StringRef capturedExpression,
  1590. ResultDisposition::Flags resultDisposition );
  1591. ~AssertionHandler() {
  1592. if ( !m_completed ) {
  1593. m_resultCapture.handleIncomplete( m_assertionInfo );
  1594. }
  1595. }
  1596. template<typename T>
  1597. void handleExpr( ExprLhs<T> const& expr ) {
  1598. handleExpr( expr.makeUnaryExpr() );
  1599. }
  1600. void handleExpr( ITransientExpression const& expr );
  1601. void handleMessage(ResultWas::OfType resultType, StringRef const& message);
  1602. void handleExceptionThrownAsExpected();
  1603. void handleUnexpectedExceptionNotThrown();
  1604. void handleExceptionNotThrownAsExpected();
  1605. void handleThrowingCallSkipped();
  1606. void handleUnexpectedInflightException();
  1607. void complete();
  1608. void setCompleted();
  1609. // query
  1610. auto allowThrows() const -> bool;
  1611. };
  1612. void handleExceptionMatchExpr( AssertionHandler& handler, std::string const& str, StringRef const& matcherString );
  1613. } // namespace Catch
  1614. // end catch_assertionhandler.h
  1615. // start catch_message.h
  1616. #include <string>
  1617. #include <vector>
  1618. namespace Catch {
  1619. struct MessageInfo {
  1620. MessageInfo( StringRef const& _macroName,
  1621. SourceLineInfo const& _lineInfo,
  1622. ResultWas::OfType _type );
  1623. StringRef macroName;
  1624. std::string message;
  1625. SourceLineInfo lineInfo;
  1626. ResultWas::OfType type;
  1627. unsigned int sequence;
  1628. bool operator == ( MessageInfo const& other ) const;
  1629. bool operator < ( MessageInfo const& other ) const;
  1630. private:
  1631. static unsigned int globalCount;
  1632. };
  1633. struct MessageStream {
  1634. template<typename T>
  1635. MessageStream& operator << ( T const& value ) {
  1636. m_stream << value;
  1637. return *this;
  1638. }
  1639. ReusableStringStream m_stream;
  1640. };
  1641. struct MessageBuilder : MessageStream {
  1642. MessageBuilder( StringRef const& macroName,
  1643. SourceLineInfo const& lineInfo,
  1644. ResultWas::OfType type );
  1645. template<typename T>
  1646. MessageBuilder& operator << ( T const& value ) {
  1647. m_stream << value;
  1648. return *this;
  1649. }
  1650. MessageInfo m_info;
  1651. };
  1652. class ScopedMessage {
  1653. public:
  1654. explicit ScopedMessage( MessageBuilder const& builder );
  1655. ~ScopedMessage();
  1656. MessageInfo m_info;
  1657. };
  1658. class Capturer {
  1659. std::vector<MessageInfo> m_messages;
  1660. IResultCapture& m_resultCapture = getResultCapture();
  1661. size_t m_captured = 0;
  1662. public:
  1663. Capturer( StringRef macroName, SourceLineInfo const& lineInfo, ResultWas::OfType resultType, StringRef names );
  1664. ~Capturer();
  1665. void captureValue( size_t index, std::string const& value );
  1666. template<typename T>
  1667. void captureValues( size_t index, T const& value ) {
  1668. captureValue( index, Catch::Detail::stringify( value ) );
  1669. }
  1670. template<typename T, typename... Ts>
  1671. void captureValues( size_t index, T const& value, Ts const&... values ) {
  1672. captureValue( index, Catch::Detail::stringify(value) );
  1673. captureValues( index+1, values... );
  1674. }
  1675. };
  1676. } // end namespace Catch
  1677. // end catch_message.h
  1678. #if !defined(CATCH_CONFIG_DISABLE)
  1679. #if !defined(CATCH_CONFIG_DISABLE_STRINGIFICATION)
  1680. #define CATCH_INTERNAL_STRINGIFY(...) #__VA_ARGS__
  1681. #else
  1682. #define CATCH_INTERNAL_STRINGIFY(...) "Disabled by CATCH_CONFIG_DISABLE_STRINGIFICATION"
  1683. #endif
  1684. #if defined(CATCH_CONFIG_FAST_COMPILE) || defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
  1685. ///////////////////////////////////////////////////////////////////////////////
  1686. // Another way to speed-up compilation is to omit local try-catch for REQUIRE*
  1687. // macros.
  1688. #define INTERNAL_CATCH_TRY
  1689. #define INTERNAL_CATCH_CATCH( capturer )
  1690. #else // CATCH_CONFIG_FAST_COMPILE
  1691. #define INTERNAL_CATCH_TRY try
  1692. #define INTERNAL_CATCH_CATCH( handler ) catch(...) { handler.handleUnexpectedInflightException(); }
  1693. #endif
  1694. #define INTERNAL_CATCH_REACT( handler ) handler.complete();
  1695. ///////////////////////////////////////////////////////////////////////////////
  1696. #define INTERNAL_CATCH_TEST( macroName, resultDisposition, ... ) \
  1697. do { \
  1698. Catch::AssertionHandler catchAssertionHandler( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(__VA_ARGS__), resultDisposition ); \
  1699. INTERNAL_CATCH_TRY { \
  1700. CATCH_INTERNAL_SUPPRESS_PARENTHESES_WARNINGS \
  1701. catchAssertionHandler.handleExpr( Catch::Decomposer() <= __VA_ARGS__ ); \
  1702. CATCH_INTERNAL_UNSUPPRESS_PARENTHESES_WARNINGS \
  1703. } INTERNAL_CATCH_CATCH( catchAssertionHandler ) \
  1704. INTERNAL_CATCH_REACT( catchAssertionHandler ) \
  1705. } 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
  1706. // The double negation silences MSVC's C4800 warning, the static_cast forces short-circuit evaluation if the type has overloaded &&.
  1707. ///////////////////////////////////////////////////////////////////////////////
  1708. #define INTERNAL_CATCH_IF( macroName, resultDisposition, ... ) \
  1709. INTERNAL_CATCH_TEST( macroName, resultDisposition, __VA_ARGS__ ); \
  1710. if( Catch::getResultCapture().lastAssertionPassed() )
  1711. ///////////////////////////////////////////////////////////////////////////////
  1712. #define INTERNAL_CATCH_ELSE( macroName, resultDisposition, ... ) \
  1713. INTERNAL_CATCH_TEST( macroName, resultDisposition, __VA_ARGS__ ); \
  1714. if( !Catch::getResultCapture().lastAssertionPassed() )
  1715. ///////////////////////////////////////////////////////////////////////////////
  1716. #define INTERNAL_CATCH_NO_THROW( macroName, resultDisposition, ... ) \
  1717. do { \
  1718. Catch::AssertionHandler catchAssertionHandler( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(__VA_ARGS__), resultDisposition ); \
  1719. try { \
  1720. static_cast<void>(__VA_ARGS__); \
  1721. catchAssertionHandler.handleExceptionNotThrownAsExpected(); \
  1722. } \
  1723. catch( ... ) { \
  1724. catchAssertionHandler.handleUnexpectedInflightException(); \
  1725. } \
  1726. INTERNAL_CATCH_REACT( catchAssertionHandler ) \
  1727. } while( false )
  1728. ///////////////////////////////////////////////////////////////////////////////
  1729. #define INTERNAL_CATCH_THROWS( macroName, resultDisposition, ... ) \
  1730. do { \
  1731. Catch::AssertionHandler catchAssertionHandler( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(__VA_ARGS__), resultDisposition); \
  1732. if( catchAssertionHandler.allowThrows() ) \
  1733. try { \
  1734. static_cast<void>(__VA_ARGS__); \
  1735. catchAssertionHandler.handleUnexpectedExceptionNotThrown(); \
  1736. } \
  1737. catch( ... ) { \
  1738. catchAssertionHandler.handleExceptionThrownAsExpected(); \
  1739. } \
  1740. else \
  1741. catchAssertionHandler.handleThrowingCallSkipped(); \
  1742. INTERNAL_CATCH_REACT( catchAssertionHandler ) \
  1743. } while( false )
  1744. ///////////////////////////////////////////////////////////////////////////////
  1745. #define INTERNAL_CATCH_THROWS_AS( macroName, exceptionType, resultDisposition, expr ) \
  1746. do { \
  1747. Catch::AssertionHandler catchAssertionHandler( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(expr) ", " CATCH_INTERNAL_STRINGIFY(exceptionType), resultDisposition ); \
  1748. if( catchAssertionHandler.allowThrows() ) \
  1749. try { \
  1750. static_cast<void>(expr); \
  1751. catchAssertionHandler.handleUnexpectedExceptionNotThrown(); \
  1752. } \
  1753. catch( exceptionType const& ) { \
  1754. catchAssertionHandler.handleExceptionThrownAsExpected(); \
  1755. } \
  1756. catch( ... ) { \
  1757. catchAssertionHandler.handleUnexpectedInflightException(); \
  1758. } \
  1759. else \
  1760. catchAssertionHandler.handleThrowingCallSkipped(); \
  1761. INTERNAL_CATCH_REACT( catchAssertionHandler ) \
  1762. } while( false )
  1763. ///////////////////////////////////////////////////////////////////////////////
  1764. #define INTERNAL_CATCH_MSG( macroName, messageType, resultDisposition, ... ) \
  1765. do { \
  1766. Catch::AssertionHandler catchAssertionHandler( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, Catch::StringRef(), resultDisposition ); \
  1767. catchAssertionHandler.handleMessage( messageType, ( Catch::MessageStream() << __VA_ARGS__ + ::Catch::StreamEndStop() ).m_stream.str() ); \
  1768. INTERNAL_CATCH_REACT( catchAssertionHandler ) \
  1769. } while( false )
  1770. ///////////////////////////////////////////////////////////////////////////////
  1771. #define INTERNAL_CATCH_CAPTURE( varName, macroName, ... ) \
  1772. auto varName = Catch::Capturer( macroName, CATCH_INTERNAL_LINEINFO, Catch::ResultWas::Info, #__VA_ARGS__ ); \
  1773. varName.captureValues( 0, __VA_ARGS__ )
  1774. ///////////////////////////////////////////////////////////////////////////////
  1775. #define INTERNAL_CATCH_INFO( macroName, log ) \
  1776. Catch::ScopedMessage INTERNAL_CATCH_UNIQUE_NAME( scopedMessage )( Catch::MessageBuilder( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, Catch::ResultWas::Info ) << log );
  1777. ///////////////////////////////////////////////////////////////////////////////
  1778. // Although this is matcher-based, it can be used with just a string
  1779. #define INTERNAL_CATCH_THROWS_STR_MATCHES( macroName, resultDisposition, matcher, ... ) \
  1780. do { \
  1781. Catch::AssertionHandler catchAssertionHandler( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(__VA_ARGS__) ", " CATCH_INTERNAL_STRINGIFY(matcher), resultDisposition ); \
  1782. if( catchAssertionHandler.allowThrows() ) \
  1783. try { \
  1784. static_cast<void>(__VA_ARGS__); \
  1785. catchAssertionHandler.handleUnexpectedExceptionNotThrown(); \
  1786. } \
  1787. catch( ... ) { \
  1788. Catch::handleExceptionMatchExpr( catchAssertionHandler, matcher, #matcher##_catch_sr ); \
  1789. } \
  1790. else \
  1791. catchAssertionHandler.handleThrowingCallSkipped(); \
  1792. INTERNAL_CATCH_REACT( catchAssertionHandler ) \
  1793. } while( false )
  1794. #endif // CATCH_CONFIG_DISABLE
  1795. // end catch_capture.hpp
  1796. // start catch_section.h
  1797. // start catch_section_info.h
  1798. // start catch_totals.h
  1799. #include <cstddef>
  1800. namespace Catch {
  1801. struct Counts {
  1802. Counts operator - ( Counts const& other ) const;
  1803. Counts& operator += ( Counts const& other );
  1804. std::size_t total() const;
  1805. bool allPassed() const;
  1806. bool allOk() const;
  1807. std::size_t passed = 0;
  1808. std::size_t failed = 0;
  1809. std::size_t failedButOk = 0;
  1810. };
  1811. struct Totals {
  1812. Totals operator - ( Totals const& other ) const;
  1813. Totals& operator += ( Totals const& other );
  1814. Totals delta( Totals const& prevTotals ) const;
  1815. int error = 0;
  1816. Counts assertions;
  1817. Counts testCases;
  1818. };
  1819. }
  1820. // end catch_totals.h
  1821. #include <string>
  1822. namespace Catch {
  1823. struct SectionInfo {
  1824. SectionInfo
  1825. ( SourceLineInfo const& _lineInfo,
  1826. std::string const& _name );
  1827. // Deprecated
  1828. SectionInfo
  1829. ( SourceLineInfo const& _lineInfo,
  1830. std::string const& _name,
  1831. std::string const& ) : SectionInfo( _lineInfo, _name ) {}
  1832. std::string name;
  1833. std::string description; // !Deprecated: this will always be empty
  1834. SourceLineInfo lineInfo;
  1835. };
  1836. struct SectionEndInfo {
  1837. SectionInfo sectionInfo;
  1838. Counts prevAssertions;
  1839. double durationInSeconds;
  1840. };
  1841. } // end namespace Catch
  1842. // end catch_section_info.h
  1843. // start catch_timer.h
  1844. #include <cstdint>
  1845. namespace Catch {
  1846. auto getCurrentNanosecondsSinceEpoch() -> uint64_t;
  1847. auto getEstimatedClockResolution() -> uint64_t;
  1848. class Timer {
  1849. uint64_t m_nanoseconds = 0;
  1850. public:
  1851. void start();
  1852. auto getElapsedNanoseconds() const -> uint64_t;
  1853. auto getElapsedMicroseconds() const -> uint64_t;
  1854. auto getElapsedMilliseconds() const -> unsigned int;
  1855. auto getElapsedSeconds() const -> double;
  1856. };
  1857. } // namespace Catch
  1858. // end catch_timer.h
  1859. #include <string>
  1860. namespace Catch {
  1861. class Section : NonCopyable {
  1862. public:
  1863. Section( SectionInfo const& info );
  1864. ~Section();
  1865. // This indicates whether the section should be executed or not
  1866. explicit operator bool() const;
  1867. private:
  1868. SectionInfo m_info;
  1869. std::string m_name;
  1870. Counts m_assertions;
  1871. bool m_sectionIncluded;
  1872. Timer m_timer;
  1873. };
  1874. } // end namespace Catch
  1875. #define INTERNAL_CATCH_SECTION( ... ) \
  1876. CATCH_INTERNAL_SUPPRESS_UNUSED_WARNINGS \
  1877. if( Catch::Section const& INTERNAL_CATCH_UNIQUE_NAME( catch_internal_Section ) = Catch::SectionInfo( CATCH_INTERNAL_LINEINFO, __VA_ARGS__ ) ) \
  1878. CATCH_INTERNAL_UNSUPPRESS_UNUSED_WARNINGS
  1879. #define INTERNAL_CATCH_DYNAMIC_SECTION( ... ) \
  1880. CATCH_INTERNAL_SUPPRESS_UNUSED_WARNINGS \
  1881. if( Catch::Section const& INTERNAL_CATCH_UNIQUE_NAME( catch_internal_Section ) = Catch::SectionInfo( CATCH_INTERNAL_LINEINFO, (Catch::ReusableStringStream() << __VA_ARGS__).str() ) ) \
  1882. CATCH_INTERNAL_UNSUPPRESS_UNUSED_WARNINGS
  1883. // end catch_section.h
  1884. // start catch_benchmark.h
  1885. #include <cstdint>
  1886. #include <string>
  1887. namespace Catch {
  1888. class BenchmarkLooper {
  1889. std::string m_name;
  1890. std::size_t m_count = 0;
  1891. std::size_t m_iterationsToRun = 1;
  1892. uint64_t m_resolution;
  1893. Timer m_timer;
  1894. static auto getResolution() -> uint64_t;
  1895. public:
  1896. // Keep most of this inline as it's on the code path that is being timed
  1897. BenchmarkLooper( StringRef name )
  1898. : m_name( name ),
  1899. m_resolution( getResolution() )
  1900. {
  1901. reportStart();
  1902. m_timer.start();
  1903. }
  1904. explicit operator bool() {
  1905. if( m_count < m_iterationsToRun )
  1906. return true;
  1907. return needsMoreIterations();
  1908. }
  1909. void increment() {
  1910. ++m_count;
  1911. }
  1912. void reportStart();
  1913. auto needsMoreIterations() -> bool;
  1914. };
  1915. } // end namespace Catch
  1916. #define BENCHMARK( name ) \
  1917. for( Catch::BenchmarkLooper looper( name ); looper; looper.increment() )
  1918. // end catch_benchmark.h
  1919. // start catch_interfaces_exception.h
  1920. // start catch_interfaces_registry_hub.h
  1921. #include <string>
  1922. #include <memory>
  1923. namespace Catch {
  1924. class TestCase;
  1925. struct ITestCaseRegistry;
  1926. struct IExceptionTranslatorRegistry;
  1927. struct IExceptionTranslator;
  1928. struct IReporterRegistry;
  1929. struct IReporterFactory;
  1930. struct ITagAliasRegistry;
  1931. class StartupExceptionRegistry;
  1932. using IReporterFactoryPtr = std::shared_ptr<IReporterFactory>;
  1933. struct IRegistryHub {
  1934. virtual ~IRegistryHub();
  1935. virtual IReporterRegistry const& getReporterRegistry() const = 0;
  1936. virtual ITestCaseRegistry const& getTestCaseRegistry() const = 0;
  1937. virtual ITagAliasRegistry const& getTagAliasRegistry() const = 0;
  1938. virtual IExceptionTranslatorRegistry const& getExceptionTranslatorRegistry() const = 0;
  1939. virtual StartupExceptionRegistry const& getStartupExceptionRegistry() const = 0;
  1940. };
  1941. struct IMutableRegistryHub {
  1942. virtual ~IMutableRegistryHub();
  1943. virtual void registerReporter( std::string const& name, IReporterFactoryPtr const& factory ) = 0;
  1944. virtual void registerListener( IReporterFactoryPtr const& factory ) = 0;
  1945. virtual void registerTest( TestCase const& testInfo ) = 0;
  1946. virtual void registerTranslator( const IExceptionTranslator* translator ) = 0;
  1947. virtual void registerTagAlias( std::string const& alias, std::string const& tag, SourceLineInfo const& lineInfo ) = 0;
  1948. virtual void registerStartupException() noexcept = 0;
  1949. };
  1950. IRegistryHub const& getRegistryHub();
  1951. IMutableRegistryHub& getMutableRegistryHub();
  1952. void cleanUp();
  1953. std::string translateActiveException();
  1954. }
  1955. // end catch_interfaces_registry_hub.h
  1956. #if defined(CATCH_CONFIG_DISABLE)
  1957. #define INTERNAL_CATCH_TRANSLATE_EXCEPTION_NO_REG( translatorName, signature) \
  1958. static std::string translatorName( signature )
  1959. #endif
  1960. #include <exception>
  1961. #include <string>
  1962. #include <vector>
  1963. namespace Catch {
  1964. using exceptionTranslateFunction = std::string(*)();
  1965. struct IExceptionTranslator;
  1966. using ExceptionTranslators = std::vector<std::unique_ptr<IExceptionTranslator const>>;
  1967. struct IExceptionTranslator {
  1968. virtual ~IExceptionTranslator();
  1969. virtual std::string translate( ExceptionTranslators::const_iterator it, ExceptionTranslators::const_iterator itEnd ) const = 0;
  1970. };
  1971. struct IExceptionTranslatorRegistry {
  1972. virtual ~IExceptionTranslatorRegistry();
  1973. virtual std::string translateActiveException() const = 0;
  1974. };
  1975. class ExceptionTranslatorRegistrar {
  1976. template<typename T>
  1977. class ExceptionTranslator : public IExceptionTranslator {
  1978. public:
  1979. ExceptionTranslator( std::string(*translateFunction)( T& ) )
  1980. : m_translateFunction( translateFunction )
  1981. {}
  1982. std::string translate( ExceptionTranslators::const_iterator it, ExceptionTranslators::const_iterator itEnd ) const override {
  1983. try {
  1984. if( it == itEnd )
  1985. std::rethrow_exception(std::current_exception());
  1986. else
  1987. return (*it)->translate( it+1, itEnd );
  1988. }
  1989. catch( T& ex ) {
  1990. return m_translateFunction( ex );
  1991. }
  1992. }
  1993. protected:
  1994. std::string(*m_translateFunction)( T& );
  1995. };
  1996. public:
  1997. template<typename T>
  1998. ExceptionTranslatorRegistrar( std::string(*translateFunction)( T& ) ) {
  1999. getMutableRegistryHub().registerTranslator
  2000. ( new ExceptionTranslator<T>( translateFunction ) );
  2001. }
  2002. };
  2003. }
  2004. ///////////////////////////////////////////////////////////////////////////////
  2005. #define INTERNAL_CATCH_TRANSLATE_EXCEPTION2( translatorName, signature ) \
  2006. static std::string translatorName( signature ); \
  2007. CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
  2008. namespace{ Catch::ExceptionTranslatorRegistrar INTERNAL_CATCH_UNIQUE_NAME( catch_internal_ExceptionRegistrar )( &translatorName ); } \
  2009. CATCH_INTERNAL_UNSUPPRESS_GLOBALS_WARNINGS \
  2010. static std::string translatorName( signature )
  2011. #define INTERNAL_CATCH_TRANSLATE_EXCEPTION( signature ) INTERNAL_CATCH_TRANSLATE_EXCEPTION2( INTERNAL_CATCH_UNIQUE_NAME( catch_internal_ExceptionTranslator ), signature )
  2012. // end catch_interfaces_exception.h
  2013. // start catch_approx.h
  2014. #include <type_traits>
  2015. namespace Catch {
  2016. namespace Detail {
  2017. class Approx {
  2018. private:
  2019. bool equalityComparisonImpl(double other) const;
  2020. // Validates the new margin (margin >= 0)
  2021. // out-of-line to avoid including stdexcept in the header
  2022. void setMargin(double margin);
  2023. // Validates the new epsilon (0 < epsilon < 1)
  2024. // out-of-line to avoid including stdexcept in the header
  2025. void setEpsilon(double epsilon);
  2026. public:
  2027. explicit Approx ( double value );
  2028. static Approx custom();
  2029. Approx operator-() const;
  2030. template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
  2031. Approx operator()( T const& value ) {
  2032. Approx approx( static_cast<double>(value) );
  2033. approx.m_epsilon = m_epsilon;
  2034. approx.m_margin = m_margin;
  2035. approx.m_scale = m_scale;
  2036. return approx;
  2037. }
  2038. template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
  2039. explicit Approx( T const& value ): Approx(static_cast<double>(value))
  2040. {}
  2041. template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
  2042. friend bool operator == ( const T& lhs, Approx const& rhs ) {
  2043. auto lhs_v = static_cast<double>(lhs);
  2044. return rhs.equalityComparisonImpl(lhs_v);
  2045. }
  2046. template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
  2047. friend bool operator == ( Approx const& lhs, const T& rhs ) {
  2048. return operator==( rhs, lhs );
  2049. }
  2050. template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
  2051. friend bool operator != ( T const& lhs, Approx const& rhs ) {
  2052. return !operator==( lhs, rhs );
  2053. }
  2054. template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
  2055. friend bool operator != ( Approx const& lhs, T const& rhs ) {
  2056. return !operator==( rhs, lhs );
  2057. }
  2058. template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
  2059. friend bool operator <= ( T const& lhs, Approx const& rhs ) {
  2060. return static_cast<double>(lhs) < rhs.m_value || lhs == rhs;
  2061. }
  2062. template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
  2063. friend bool operator <= ( Approx const& lhs, T const& rhs ) {
  2064. return lhs.m_value < static_cast<double>(rhs) || lhs == rhs;
  2065. }
  2066. template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
  2067. friend bool operator >= ( T const& lhs, Approx const& rhs ) {
  2068. return static_cast<double>(lhs) > rhs.m_value || lhs == rhs;
  2069. }
  2070. template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
  2071. friend bool operator >= ( Approx const& lhs, T const& rhs ) {
  2072. return lhs.m_value > static_cast<double>(rhs) || lhs == rhs;
  2073. }
  2074. template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
  2075. Approx& epsilon( T const& newEpsilon ) {
  2076. double epsilonAsDouble = static_cast<double>(newEpsilon);
  2077. setEpsilon(epsilonAsDouble);
  2078. return *this;
  2079. }
  2080. template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
  2081. Approx& margin( T const& newMargin ) {
  2082. double marginAsDouble = static_cast<double>(newMargin);
  2083. setMargin(marginAsDouble);
  2084. return *this;
  2085. }
  2086. template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
  2087. Approx& scale( T const& newScale ) {
  2088. m_scale = static_cast<double>(newScale);
  2089. return *this;
  2090. }
  2091. std::string toString() const;
  2092. private:
  2093. double m_epsilon;
  2094. double m_margin;
  2095. double m_scale;
  2096. double m_value;
  2097. };
  2098. } // end namespace Detail
  2099. namespace literals {
  2100. Detail::Approx operator "" _a(long double val);
  2101. Detail::Approx operator "" _a(unsigned long long val);
  2102. } // end namespace literals
  2103. template<>
  2104. struct StringMaker<Catch::Detail::Approx> {
  2105. static std::string convert(Catch::Detail::Approx const& value);
  2106. };
  2107. } // end namespace Catch
  2108. // end catch_approx.h
  2109. // start catch_string_manip.h
  2110. #include <string>
  2111. #include <iosfwd>
  2112. namespace Catch {
  2113. bool startsWith( std::string const& s, std::string const& prefix );
  2114. bool startsWith( std::string const& s, char prefix );
  2115. bool endsWith( std::string const& s, std::string const& suffix );
  2116. bool endsWith( std::string const& s, char suffix );
  2117. bool contains( std::string const& s, std::string const& infix );
  2118. void toLowerInPlace( std::string& s );
  2119. std::string toLower( std::string const& s );
  2120. std::string trim( std::string const& str );
  2121. bool replaceInPlace( std::string& str, std::string const& replaceThis, std::string const& withThis );
  2122. struct pluralise {
  2123. pluralise( std::size_t count, std::string const& label );
  2124. friend std::ostream& operator << ( std::ostream& os, pluralise const& pluraliser );
  2125. std::size_t m_count;
  2126. std::string m_label;
  2127. };
  2128. }
  2129. // end catch_string_manip.h
  2130. #ifndef CATCH_CONFIG_DISABLE_MATCHERS
  2131. // start catch_capture_matchers.h
  2132. // start catch_matchers.h
  2133. #include <string>
  2134. #include <vector>
  2135. namespace Catch {
  2136. namespace Matchers {
  2137. namespace Impl {
  2138. template<typename ArgT> struct MatchAllOf;
  2139. template<typename ArgT> struct MatchAnyOf;
  2140. template<typename ArgT> struct MatchNotOf;
  2141. class MatcherUntypedBase {
  2142. public:
  2143. MatcherUntypedBase() = default;
  2144. MatcherUntypedBase ( MatcherUntypedBase const& ) = default;
  2145. MatcherUntypedBase& operator = ( MatcherUntypedBase const& ) = delete;
  2146. std::string toString() const;
  2147. protected:
  2148. virtual ~MatcherUntypedBase();
  2149. virtual std::string describe() const = 0;
  2150. mutable std::string m_cachedToString;
  2151. };
  2152. #ifdef __clang__
  2153. # pragma clang diagnostic push
  2154. # pragma clang diagnostic ignored "-Wnon-virtual-dtor"
  2155. #endif
  2156. template<typename ObjectT>
  2157. struct MatcherMethod {
  2158. virtual bool match( ObjectT const& arg ) const = 0;
  2159. };
  2160. #ifdef __clang__
  2161. # pragma clang diagnostic pop
  2162. #endif
  2163. template<typename T>
  2164. struct MatcherBase : MatcherUntypedBase, MatcherMethod<T> {
  2165. MatchAllOf<T> operator && ( MatcherBase const& other ) const;
  2166. MatchAnyOf<T> operator || ( MatcherBase const& other ) const;
  2167. MatchNotOf<T> operator ! () const;
  2168. };
  2169. template<typename ArgT>
  2170. struct MatchAllOf : MatcherBase<ArgT> {
  2171. bool match( ArgT const& arg ) const override {
  2172. for( auto matcher : m_matchers ) {
  2173. if (!matcher->match(arg))
  2174. return false;
  2175. }
  2176. return true;
  2177. }
  2178. std::string describe() const override {
  2179. std::string description;
  2180. description.reserve( 4 + m_matchers.size()*32 );
  2181. description += "( ";
  2182. bool first = true;
  2183. for( auto matcher : m_matchers ) {
  2184. if( first )
  2185. first = false;
  2186. else
  2187. description += " and ";
  2188. description += matcher->toString();
  2189. }
  2190. description += " )";
  2191. return description;
  2192. }
  2193. MatchAllOf<ArgT>& operator && ( MatcherBase<ArgT> const& other ) {
  2194. m_matchers.push_back( &other );
  2195. return *this;
  2196. }
  2197. std::vector<MatcherBase<ArgT> const*> m_matchers;
  2198. };
  2199. template<typename ArgT>
  2200. struct MatchAnyOf : MatcherBase<ArgT> {
  2201. bool match( ArgT const& arg ) const override {
  2202. for( auto matcher : m_matchers ) {
  2203. if (matcher->match(arg))
  2204. return true;
  2205. }
  2206. return false;
  2207. }
  2208. std::string describe() const override {
  2209. std::string description;
  2210. description.reserve( 4 + m_matchers.size()*32 );
  2211. description += "( ";
  2212. bool first = true;
  2213. for( auto matcher : m_matchers ) {
  2214. if( first )
  2215. first = false;
  2216. else
  2217. description += " or ";
  2218. description += matcher->toString();
  2219. }
  2220. description += " )";
  2221. return description;
  2222. }
  2223. MatchAnyOf<ArgT>& operator || ( MatcherBase<ArgT> const& other ) {
  2224. m_matchers.push_back( &other );
  2225. return *this;
  2226. }
  2227. std::vector<MatcherBase<ArgT> const*> m_matchers;
  2228. };
  2229. template<typename ArgT>
  2230. struct MatchNotOf : MatcherBase<ArgT> {
  2231. MatchNotOf( MatcherBase<ArgT> const& underlyingMatcher ) : m_underlyingMatcher( underlyingMatcher ) {}
  2232. bool match( ArgT const& arg ) const override {
  2233. return !m_underlyingMatcher.match( arg );
  2234. }
  2235. std::string describe() const override {
  2236. return "not " + m_underlyingMatcher.toString();
  2237. }
  2238. MatcherBase<ArgT> const& m_underlyingMatcher;
  2239. };
  2240. template<typename T>
  2241. MatchAllOf<T> MatcherBase<T>::operator && ( MatcherBase const& other ) const {
  2242. return MatchAllOf<T>() && *this && other;
  2243. }
  2244. template<typename T>
  2245. MatchAnyOf<T> MatcherBase<T>::operator || ( MatcherBase const& other ) const {
  2246. return MatchAnyOf<T>() || *this || other;
  2247. }
  2248. template<typename T>
  2249. MatchNotOf<T> MatcherBase<T>::operator ! () const {
  2250. return MatchNotOf<T>( *this );
  2251. }
  2252. } // namespace Impl
  2253. } // namespace Matchers
  2254. using namespace Matchers;
  2255. using Matchers::Impl::MatcherBase;
  2256. } // namespace Catch
  2257. // end catch_matchers.h
  2258. // start catch_matchers_floating.h
  2259. #include <type_traits>
  2260. #include <cmath>
  2261. namespace Catch {
  2262. namespace Matchers {
  2263. namespace Floating {
  2264. enum class FloatingPointKind : uint8_t;
  2265. struct WithinAbsMatcher : MatcherBase<double> {
  2266. WithinAbsMatcher(double target, double margin);
  2267. bool match(double const& matchee) const override;
  2268. std::string describe() const override;
  2269. private:
  2270. double m_target;
  2271. double m_margin;
  2272. };
  2273. struct WithinUlpsMatcher : MatcherBase<double> {
  2274. WithinUlpsMatcher(double target, int ulps, FloatingPointKind baseType);
  2275. bool match(double const& matchee) const override;
  2276. std::string describe() const override;
  2277. private:
  2278. double m_target;
  2279. int m_ulps;
  2280. FloatingPointKind m_type;
  2281. };
  2282. } // namespace Floating
  2283. // The following functions create the actual matcher objects.
  2284. // This allows the types to be inferred
  2285. Floating::WithinUlpsMatcher WithinULP(double target, int maxUlpDiff);
  2286. Floating::WithinUlpsMatcher WithinULP(float target, int maxUlpDiff);
  2287. Floating::WithinAbsMatcher WithinAbs(double target, double margin);
  2288. } // namespace Matchers
  2289. } // namespace Catch
  2290. // end catch_matchers_floating.h
  2291. // start catch_matchers_generic.hpp
  2292. #include <functional>
  2293. #include <string>
  2294. namespace Catch {
  2295. namespace Matchers {
  2296. namespace Generic {
  2297. namespace Detail {
  2298. std::string finalizeDescription(const std::string& desc);
  2299. }
  2300. template <typename T>
  2301. class PredicateMatcher : public MatcherBase<T> {
  2302. std::function<bool(T const&)> m_predicate;
  2303. std::string m_description;
  2304. public:
  2305. PredicateMatcher(std::function<bool(T const&)> const& elem, std::string const& descr)
  2306. :m_predicate(std::move(elem)),
  2307. m_description(Detail::finalizeDescription(descr))
  2308. {}
  2309. bool match( T const& item ) const override {
  2310. return m_predicate(item);
  2311. }
  2312. std::string describe() const override {
  2313. return m_description;
  2314. }
  2315. };
  2316. } // namespace Generic
  2317. // The following functions create the actual matcher objects.
  2318. // The user has to explicitly specify type to the function, because
  2319. // infering std::function<bool(T const&)> is hard (but possible) and
  2320. // requires a lot of TMP.
  2321. template<typename T>
  2322. Generic::PredicateMatcher<T> Predicate(std::function<bool(T const&)> const& predicate, std::string const& description = "") {
  2323. return Generic::PredicateMatcher<T>(predicate, description);
  2324. }
  2325. } // namespace Matchers
  2326. } // namespace Catch
  2327. // end catch_matchers_generic.hpp
  2328. // start catch_matchers_string.h
  2329. #include <string>
  2330. namespace Catch {
  2331. namespace Matchers {
  2332. namespace StdString {
  2333. struct CasedString
  2334. {
  2335. CasedString( std::string const& str, CaseSensitive::Choice caseSensitivity );
  2336. std::string adjustString( std::string const& str ) const;
  2337. std::string caseSensitivitySuffix() const;
  2338. CaseSensitive::Choice m_caseSensitivity;
  2339. std::string m_str;
  2340. };
  2341. struct StringMatcherBase : MatcherBase<std::string> {
  2342. StringMatcherBase( std::string const& operation, CasedString const& comparator );
  2343. std::string describe() const override;
  2344. CasedString m_comparator;
  2345. std::string m_operation;
  2346. };
  2347. struct EqualsMatcher : StringMatcherBase {
  2348. EqualsMatcher( CasedString const& comparator );
  2349. bool match( std::string const& source ) const override;
  2350. };
  2351. struct ContainsMatcher : StringMatcherBase {
  2352. ContainsMatcher( CasedString const& comparator );
  2353. bool match( std::string const& source ) const override;
  2354. };
  2355. struct StartsWithMatcher : StringMatcherBase {
  2356. StartsWithMatcher( CasedString const& comparator );
  2357. bool match( std::string const& source ) const override;
  2358. };
  2359. struct EndsWithMatcher : StringMatcherBase {
  2360. EndsWithMatcher( CasedString const& comparator );
  2361. bool match( std::string const& source ) const override;
  2362. };
  2363. struct RegexMatcher : MatcherBase<std::string> {
  2364. RegexMatcher( std::string regex, CaseSensitive::Choice caseSensitivity );
  2365. bool match( std::string const& matchee ) const override;
  2366. std::string describe() const override;
  2367. private:
  2368. std::string m_regex;
  2369. CaseSensitive::Choice m_caseSensitivity;
  2370. };
  2371. } // namespace StdString
  2372. // The following functions create the actual matcher objects.
  2373. // This allows the types to be inferred
  2374. StdString::EqualsMatcher Equals( std::string const& str, CaseSensitive::Choice caseSensitivity = CaseSensitive::Yes );
  2375. StdString::ContainsMatcher Contains( std::string const& str, CaseSensitive::Choice caseSensitivity = CaseSensitive::Yes );
  2376. StdString::EndsWithMatcher EndsWith( std::string const& str, CaseSensitive::Choice caseSensitivity = CaseSensitive::Yes );
  2377. StdString::StartsWithMatcher StartsWith( std::string const& str, CaseSensitive::Choice caseSensitivity = CaseSensitive::Yes );
  2378. StdString::RegexMatcher Matches( std::string const& regex, CaseSensitive::Choice caseSensitivity = CaseSensitive::Yes );
  2379. } // namespace Matchers
  2380. } // namespace Catch
  2381. // end catch_matchers_string.h
  2382. // start catch_matchers_vector.h
  2383. #include <algorithm>
  2384. namespace Catch {
  2385. namespace Matchers {
  2386. namespace Vector {
  2387. namespace Detail {
  2388. template <typename InputIterator, typename T>
  2389. size_t count(InputIterator first, InputIterator last, T const& item) {
  2390. size_t cnt = 0;
  2391. for (; first != last; ++first) {
  2392. if (*first == item) {
  2393. ++cnt;
  2394. }
  2395. }
  2396. return cnt;
  2397. }
  2398. template <typename InputIterator, typename T>
  2399. bool contains(InputIterator first, InputIterator last, T const& item) {
  2400. for (; first != last; ++first) {
  2401. if (*first == item) {
  2402. return true;
  2403. }
  2404. }
  2405. return false;
  2406. }
  2407. }
  2408. template<typename T>
  2409. struct ContainsElementMatcher : MatcherBase<std::vector<T>> {
  2410. ContainsElementMatcher(T const &comparator) : m_comparator( comparator) {}
  2411. bool match(std::vector<T> const &v) const override {
  2412. for (auto const& el : v) {
  2413. if (el == m_comparator) {
  2414. return true;
  2415. }
  2416. }
  2417. return false;
  2418. }
  2419. std::string describe() const override {
  2420. return "Contains: " + ::Catch::Detail::stringify( m_comparator );
  2421. }
  2422. T const& m_comparator;
  2423. };
  2424. template<typename T>
  2425. struct ContainsMatcher : MatcherBase<std::vector<T>> {
  2426. ContainsMatcher(std::vector<T> const &comparator) : m_comparator( comparator ) {}
  2427. bool match(std::vector<T> const &v) const override {
  2428. // !TBD: see note in EqualsMatcher
  2429. if (m_comparator.size() > v.size())
  2430. return false;
  2431. for (auto const& comparator : m_comparator) {
  2432. auto present = false;
  2433. for (const auto& el : v) {
  2434. if (el == comparator) {
  2435. present = true;
  2436. break;
  2437. }
  2438. }
  2439. if (!present) {
  2440. return false;
  2441. }
  2442. }
  2443. return true;
  2444. }
  2445. std::string describe() const override {
  2446. return "Contains: " + ::Catch::Detail::stringify( m_comparator );
  2447. }
  2448. std::vector<T> const& m_comparator;
  2449. };
  2450. template<typename T>
  2451. struct EqualsMatcher : MatcherBase<std::vector<T>> {
  2452. EqualsMatcher(std::vector<T> const &comparator) : m_comparator( comparator ) {}
  2453. bool match(std::vector<T> const &v) const override {
  2454. // !TBD: This currently works if all elements can be compared using !=
  2455. // - a more general approach would be via a compare template that defaults
  2456. // to using !=. but could be specialised for, e.g. std::vector<T> etc
  2457. // - then just call that directly
  2458. if (m_comparator.size() != v.size())
  2459. return false;
  2460. for (std::size_t i = 0; i < v.size(); ++i)
  2461. if (m_comparator[i] != v[i])
  2462. return false;
  2463. return true;
  2464. }
  2465. std::string describe() const override {
  2466. return "Equals: " + ::Catch::Detail::stringify( m_comparator );
  2467. }
  2468. std::vector<T> const& m_comparator;
  2469. };
  2470. template<typename T>
  2471. struct UnorderedEqualsMatcher : MatcherBase<std::vector<T>> {
  2472. UnorderedEqualsMatcher(std::vector<T> const& target) : m_target(target) {}
  2473. bool match(std::vector<T> const& vec) const override {
  2474. // Note: This is a reimplementation of std::is_permutation,
  2475. // because I don't want to include <algorithm> inside the common path
  2476. if (m_target.size() != vec.size()) {
  2477. return false;
  2478. }
  2479. auto lfirst = m_target.begin(), llast = m_target.end();
  2480. auto rfirst = vec.begin(), rlast = vec.end();
  2481. // Cut common prefix to optimize checking of permuted parts
  2482. while (lfirst != llast && *lfirst == *rfirst) {
  2483. ++lfirst; ++rfirst;
  2484. }
  2485. if (lfirst == llast) {
  2486. return true;
  2487. }
  2488. for (auto mid = lfirst; mid != llast; ++mid) {
  2489. // Skip already counted items
  2490. if (Detail::contains(lfirst, mid, *mid)) {
  2491. continue;
  2492. }
  2493. size_t num_vec = Detail::count(rfirst, rlast, *mid);
  2494. if (num_vec == 0 || Detail::count(lfirst, llast, *mid) != num_vec) {
  2495. return false;
  2496. }
  2497. }
  2498. return true;
  2499. }
  2500. std::string describe() const override {
  2501. return "UnorderedEquals: " + ::Catch::Detail::stringify(m_target);
  2502. }
  2503. private:
  2504. std::vector<T> const& m_target;
  2505. };
  2506. } // namespace Vector
  2507. // The following functions create the actual matcher objects.
  2508. // This allows the types to be inferred
  2509. template<typename T>
  2510. Vector::ContainsMatcher<T> Contains( std::vector<T> const& comparator ) {
  2511. return Vector::ContainsMatcher<T>( comparator );
  2512. }
  2513. template<typename T>
  2514. Vector::ContainsElementMatcher<T> VectorContains( T const& comparator ) {
  2515. return Vector::ContainsElementMatcher<T>( comparator );
  2516. }
  2517. template<typename T>
  2518. Vector::EqualsMatcher<T> Equals( std::vector<T> const& comparator ) {
  2519. return Vector::EqualsMatcher<T>( comparator );
  2520. }
  2521. template<typename T>
  2522. Vector::UnorderedEqualsMatcher<T> UnorderedEquals(std::vector<T> const& target) {
  2523. return Vector::UnorderedEqualsMatcher<T>(target);
  2524. }
  2525. } // namespace Matchers
  2526. } // namespace Catch
  2527. // end catch_matchers_vector.h
  2528. namespace Catch {
  2529. template<typename ArgT, typename MatcherT>
  2530. class MatchExpr : public ITransientExpression {
  2531. ArgT const& m_arg;
  2532. MatcherT m_matcher;
  2533. StringRef m_matcherString;
  2534. public:
  2535. MatchExpr( ArgT const& arg, MatcherT const& matcher, StringRef const& matcherString )
  2536. : ITransientExpression{ true, matcher.match( arg ) },
  2537. m_arg( arg ),
  2538. m_matcher( matcher ),
  2539. m_matcherString( matcherString )
  2540. {}
  2541. void streamReconstructedExpression( std::ostream &os ) const override {
  2542. auto matcherAsString = m_matcher.toString();
  2543. os << Catch::Detail::stringify( m_arg ) << ' ';
  2544. if( matcherAsString == Detail::unprintableString )
  2545. os << m_matcherString;
  2546. else
  2547. os << matcherAsString;
  2548. }
  2549. };
  2550. using StringMatcher = Matchers::Impl::MatcherBase<std::string>;
  2551. void handleExceptionMatchExpr( AssertionHandler& handler, StringMatcher const& matcher, StringRef const& matcherString );
  2552. template<typename ArgT, typename MatcherT>
  2553. auto makeMatchExpr( ArgT const& arg, MatcherT const& matcher, StringRef const& matcherString ) -> MatchExpr<ArgT, MatcherT> {
  2554. return MatchExpr<ArgT, MatcherT>( arg, matcher, matcherString );
  2555. }
  2556. } // namespace Catch
  2557. ///////////////////////////////////////////////////////////////////////////////
  2558. #define INTERNAL_CHECK_THAT( macroName, matcher, resultDisposition, arg ) \
  2559. do { \
  2560. Catch::AssertionHandler catchAssertionHandler( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(arg) ", " CATCH_INTERNAL_STRINGIFY(matcher), resultDisposition ); \
  2561. INTERNAL_CATCH_TRY { \
  2562. catchAssertionHandler.handleExpr( Catch::makeMatchExpr( arg, matcher, #matcher##_catch_sr ) ); \
  2563. } INTERNAL_CATCH_CATCH( catchAssertionHandler ) \
  2564. INTERNAL_CATCH_REACT( catchAssertionHandler ) \
  2565. } while( false )
  2566. ///////////////////////////////////////////////////////////////////////////////
  2567. #define INTERNAL_CATCH_THROWS_MATCHES( macroName, exceptionType, resultDisposition, matcher, ... ) \
  2568. do { \
  2569. Catch::AssertionHandler catchAssertionHandler( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(__VA_ARGS__) ", " CATCH_INTERNAL_STRINGIFY(exceptionType) ", " CATCH_INTERNAL_STRINGIFY(matcher), resultDisposition ); \
  2570. if( catchAssertionHandler.allowThrows() ) \
  2571. try { \
  2572. static_cast<void>(__VA_ARGS__ ); \
  2573. catchAssertionHandler.handleUnexpectedExceptionNotThrown(); \
  2574. } \
  2575. catch( exceptionType const& ex ) { \
  2576. catchAssertionHandler.handleExpr( Catch::makeMatchExpr( ex, matcher, #matcher##_catch_sr ) ); \
  2577. } \
  2578. catch( ... ) { \
  2579. catchAssertionHandler.handleUnexpectedInflightException(); \
  2580. } \
  2581. else \
  2582. catchAssertionHandler.handleThrowingCallSkipped(); \
  2583. INTERNAL_CATCH_REACT( catchAssertionHandler ) \
  2584. } while( false )
  2585. // end catch_capture_matchers.h
  2586. #endif
  2587. // start catch_generators.hpp
  2588. // start catch_interfaces_generatortracker.h
  2589. #include <memory>
  2590. namespace Catch {
  2591. namespace Generators {
  2592. class GeneratorBase {
  2593. protected:
  2594. size_t m_size = 0;
  2595. public:
  2596. GeneratorBase( size_t size ) : m_size( size ) {}
  2597. virtual ~GeneratorBase();
  2598. auto size() const -> size_t { return m_size; }
  2599. };
  2600. using GeneratorBasePtr = std::unique_ptr<GeneratorBase>;
  2601. } // namespace Generators
  2602. struct IGeneratorTracker {
  2603. virtual ~IGeneratorTracker();
  2604. virtual auto hasGenerator() const -> bool = 0;
  2605. virtual auto getGenerator() const -> Generators::GeneratorBasePtr const& = 0;
  2606. virtual void setGenerator( Generators::GeneratorBasePtr&& generator ) = 0;
  2607. virtual auto getIndex() const -> std::size_t = 0;
  2608. };
  2609. } // namespace Catch
  2610. // end catch_interfaces_generatortracker.h
  2611. // start catch_enforce.h
  2612. #include <stdexcept>
  2613. namespace Catch {
  2614. #if !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
  2615. template <typename Ex>
  2616. [[noreturn]]
  2617. void throw_exception(Ex const& e) {
  2618. throw e;
  2619. }
  2620. #else // ^^ Exceptions are enabled // Exceptions are disabled vv
  2621. [[noreturn]]
  2622. void throw_exception(std::exception const& e);
  2623. #endif
  2624. } // namespace Catch;
  2625. #define CATCH_PREPARE_EXCEPTION( type, msg ) \
  2626. type( ( Catch::ReusableStringStream() << msg ).str() )
  2627. #define CATCH_INTERNAL_ERROR( msg ) \
  2628. Catch::throw_exception(CATCH_PREPARE_EXCEPTION( std::logic_error, CATCH_INTERNAL_LINEINFO << ": Internal Catch error: " << msg))
  2629. #define CATCH_ERROR( msg ) \
  2630. Catch::throw_exception(CATCH_PREPARE_EXCEPTION( std::domain_error, msg ))
  2631. #define CATCH_RUNTIME_ERROR( msg ) \
  2632. Catch::throw_exception(CATCH_PREPARE_EXCEPTION( std::runtime_error, msg ))
  2633. #define CATCH_ENFORCE( condition, msg ) \
  2634. do{ if( !(condition) ) CATCH_ERROR( msg ); } while(false)
  2635. // end catch_enforce.h
  2636. #include <memory>
  2637. #include <vector>
  2638. #include <cassert>
  2639. #include <utility>
  2640. namespace Catch {
  2641. namespace Generators {
  2642. // !TBD move this into its own location?
  2643. namespace pf{
  2644. template<typename T, typename... Args>
  2645. std::unique_ptr<T> make_unique( Args&&... args ) {
  2646. return std::unique_ptr<T>(new T(std::forward<Args>(args)...));
  2647. }
  2648. }
  2649. template<typename T>
  2650. struct IGenerator {
  2651. virtual ~IGenerator() {}
  2652. virtual auto get( size_t index ) const -> T = 0;
  2653. };
  2654. template<typename T>
  2655. class SingleValueGenerator : public IGenerator<T> {
  2656. T m_value;
  2657. public:
  2658. SingleValueGenerator( T const& value ) : m_value( value ) {}
  2659. auto get( size_t ) const -> T override {
  2660. return m_value;
  2661. }
  2662. };
  2663. template<typename T>
  2664. class FixedValuesGenerator : public IGenerator<T> {
  2665. std::vector<T> m_values;
  2666. public:
  2667. FixedValuesGenerator( std::initializer_list<T> values ) : m_values( values ) {}
  2668. auto get( size_t index ) const -> T override {
  2669. return m_values[index];
  2670. }
  2671. };
  2672. template<typename T>
  2673. class RangeGenerator : public IGenerator<T> {
  2674. T const m_first;
  2675. T const m_last;
  2676. public:
  2677. RangeGenerator( T const& first, T const& last ) : m_first( first ), m_last( last ) {
  2678. assert( m_last > m_first );
  2679. }
  2680. auto get( size_t index ) const -> T override {
  2681. // ToDo:: introduce a safe cast to catch potential overflows
  2682. return static_cast<T>(m_first+index);
  2683. }
  2684. };
  2685. template<typename T>
  2686. struct NullGenerator : IGenerator<T> {
  2687. auto get( size_t ) const -> T override {
  2688. CATCH_INTERNAL_ERROR("A Null Generator is always empty");
  2689. }
  2690. };
  2691. template<typename T>
  2692. class Generator {
  2693. std::unique_ptr<IGenerator<T>> m_generator;
  2694. size_t m_size;
  2695. public:
  2696. Generator( size_t size, std::unique_ptr<IGenerator<T>> generator )
  2697. : m_generator( std::move( generator ) ),
  2698. m_size( size )
  2699. {}
  2700. auto size() const -> size_t { return m_size; }
  2701. auto operator[]( size_t index ) const -> T {
  2702. assert( index < m_size );
  2703. return m_generator->get( index );
  2704. }
  2705. };
  2706. std::vector<size_t> randomiseIndices( size_t selectionSize, size_t sourceSize );
  2707. template<typename T>
  2708. class GeneratorRandomiser : public IGenerator<T> {
  2709. Generator<T> m_baseGenerator;
  2710. std::vector<size_t> m_indices;
  2711. public:
  2712. GeneratorRandomiser( Generator<T>&& baseGenerator, size_t numberOfItems )
  2713. : m_baseGenerator( std::move( baseGenerator ) ),
  2714. m_indices( randomiseIndices( numberOfItems, m_baseGenerator.size() ) )
  2715. {}
  2716. auto get( size_t index ) const -> T override {
  2717. return m_baseGenerator[m_indices[index]];
  2718. }
  2719. };
  2720. template<typename T>
  2721. struct RequiresASpecialisationFor;
  2722. template<typename T>
  2723. auto all() -> Generator<T> { return RequiresASpecialisationFor<T>(); }
  2724. template<>
  2725. auto all<int>() -> Generator<int>;
  2726. template<typename T>
  2727. auto range( T const& first, T const& last ) -> Generator<T> {
  2728. return Generator<T>( (last-first), pf::make_unique<RangeGenerator<T>>( first, last ) );
  2729. }
  2730. template<typename T>
  2731. auto random( T const& first, T const& last ) -> Generator<T> {
  2732. auto gen = range( first, last );
  2733. auto size = gen.size();
  2734. return Generator<T>( size, pf::make_unique<GeneratorRandomiser<T>>( std::move( gen ), size ) );
  2735. }
  2736. template<typename T>
  2737. auto random( size_t size ) -> Generator<T> {
  2738. return Generator<T>( size, pf::make_unique<GeneratorRandomiser<T>>( all<T>(), size ) );
  2739. }
  2740. template<typename T>
  2741. auto values( std::initializer_list<T> values ) -> Generator<T> {
  2742. return Generator<T>( values.size(), pf::make_unique<FixedValuesGenerator<T>>( values ) );
  2743. }
  2744. template<typename T>
  2745. auto value( T const& val ) -> Generator<T> {
  2746. return Generator<T>( 1, pf::make_unique<SingleValueGenerator<T>>( val ) );
  2747. }
  2748. template<typename T>
  2749. auto as() -> Generator<T> {
  2750. return Generator<T>( 0, pf::make_unique<NullGenerator<T>>() );
  2751. }
  2752. template<typename... Ts>
  2753. auto table( std::initializer_list<std::tuple<Ts...>>&& tuples ) -> Generator<std::tuple<Ts...>> {
  2754. return values<std::tuple<Ts...>>( std::forward<std::initializer_list<std::tuple<Ts...>>>( tuples ) );
  2755. }
  2756. template<typename T>
  2757. struct Generators : GeneratorBase {
  2758. std::vector<Generator<T>> m_generators;
  2759. using type = T;
  2760. Generators() : GeneratorBase( 0 ) {}
  2761. void populate( T&& val ) {
  2762. m_size += 1;
  2763. m_generators.emplace_back( value( std::move( val ) ) );
  2764. }
  2765. template<typename U>
  2766. void populate( U&& val ) {
  2767. populate( T( std::move( val ) ) );
  2768. }
  2769. void populate( Generator<T>&& generator ) {
  2770. m_size += generator.size();
  2771. m_generators.emplace_back( std::move( generator ) );
  2772. }
  2773. template<typename U, typename... Gs>
  2774. void populate( U&& valueOrGenerator, Gs... moreGenerators ) {
  2775. populate( std::forward<U>( valueOrGenerator ) );
  2776. populate( std::forward<Gs>( moreGenerators )... );
  2777. }
  2778. auto operator[]( size_t index ) const -> T {
  2779. size_t sizes = 0;
  2780. for( auto const& gen : m_generators ) {
  2781. auto localIndex = index-sizes;
  2782. sizes += gen.size();
  2783. if( index < sizes )
  2784. return gen[localIndex];
  2785. }
  2786. CATCH_INTERNAL_ERROR("Index '" << index << "' is out of range (" << sizes << ')');
  2787. }
  2788. };
  2789. template<typename T, typename... Gs>
  2790. auto makeGenerators( Generator<T>&& generator, Gs... moreGenerators ) -> Generators<T> {
  2791. Generators<T> generators;
  2792. generators.m_generators.reserve( 1+sizeof...(Gs) );
  2793. generators.populate( std::move( generator ), std::forward<Gs>( moreGenerators )... );
  2794. return generators;
  2795. }
  2796. template<typename T>
  2797. auto makeGenerators( Generator<T>&& generator ) -> Generators<T> {
  2798. Generators<T> generators;
  2799. generators.populate( std::move( generator ) );
  2800. return generators;
  2801. }
  2802. template<typename T, typename... Gs>
  2803. auto makeGenerators( T&& val, Gs... moreGenerators ) -> Generators<T> {
  2804. return makeGenerators( value( std::forward<T>( val ) ), std::forward<Gs>( moreGenerators )... );
  2805. }
  2806. template<typename T, typename U, typename... Gs>
  2807. auto makeGenerators( U&& val, Gs... moreGenerators ) -> Generators<T> {
  2808. return makeGenerators( value( T( std::forward<U>( val ) ) ), std::forward<Gs>( moreGenerators )... );
  2809. }
  2810. auto acquireGeneratorTracker( SourceLineInfo const& lineInfo ) -> IGeneratorTracker&;
  2811. template<typename L>
  2812. // Note: The type after -> is weird, because VS2015 cannot parse
  2813. // the expression used in the typedef inside, when it is in
  2814. // return type. Yeah, ¯\_(ツ)_/¯
  2815. auto generate( SourceLineInfo const& lineInfo, L const& generatorExpression ) -> decltype(std::declval<decltype(generatorExpression())>()[0]) {
  2816. using UnderlyingType = typename decltype(generatorExpression())::type;
  2817. IGeneratorTracker& tracker = acquireGeneratorTracker( lineInfo );
  2818. if( !tracker.hasGenerator() )
  2819. tracker.setGenerator( pf::make_unique<Generators<UnderlyingType>>( generatorExpression() ) );
  2820. auto const& generator = static_cast<Generators<UnderlyingType> const&>( *tracker.getGenerator() );
  2821. return generator[tracker.getIndex()];
  2822. }
  2823. } // namespace Generators
  2824. } // namespace Catch
  2825. #define GENERATE( ... ) \
  2826. Catch::Generators::generate( CATCH_INTERNAL_LINEINFO, []{ using namespace Catch::Generators; return makeGenerators( __VA_ARGS__ ); } )
  2827. // end catch_generators.hpp
  2828. // These files are included here so the single_include script doesn't put them
  2829. // in the conditionally compiled sections
  2830. // start catch_test_case_info.h
  2831. #include <string>
  2832. #include <vector>
  2833. #include <memory>
  2834. #ifdef __clang__
  2835. #pragma clang diagnostic push
  2836. #pragma clang diagnostic ignored "-Wpadded"
  2837. #endif
  2838. namespace Catch {
  2839. struct ITestInvoker;
  2840. struct TestCaseInfo {
  2841. enum SpecialProperties{
  2842. None = 0,
  2843. IsHidden = 1 << 1,
  2844. ShouldFail = 1 << 2,
  2845. MayFail = 1 << 3,
  2846. Throws = 1 << 4,
  2847. NonPortable = 1 << 5,
  2848. Benchmark = 1 << 6
  2849. };
  2850. TestCaseInfo( std::string const& _name,
  2851. std::string const& _className,
  2852. std::string const& _description,
  2853. std::vector<std::string> const& _tags,
  2854. SourceLineInfo const& _lineInfo );
  2855. friend void setTags( TestCaseInfo& testCaseInfo, std::vector<std::string> tags );
  2856. bool isHidden() const;
  2857. bool throws() const;
  2858. bool okToFail() const;
  2859. bool expectedToFail() const;
  2860. std::string tagsAsString() const;
  2861. std::string name;
  2862. std::string className;
  2863. std::string description;
  2864. std::vector<std::string> tags;
  2865. std::vector<std::string> lcaseTags;
  2866. SourceLineInfo lineInfo;
  2867. SpecialProperties properties;
  2868. };
  2869. class TestCase : public TestCaseInfo {
  2870. public:
  2871. TestCase( ITestInvoker* testCase, TestCaseInfo&& info );
  2872. TestCase withName( std::string const& _newName ) const;
  2873. void invoke() const;
  2874. TestCaseInfo const& getTestCaseInfo() const;
  2875. bool operator == ( TestCase const& other ) const;
  2876. bool operator < ( TestCase const& other ) const;
  2877. private:
  2878. std::shared_ptr<ITestInvoker> test;
  2879. };
  2880. TestCase makeTestCase( ITestInvoker* testCase,
  2881. std::string const& className,
  2882. NameAndTags const& nameAndTags,
  2883. SourceLineInfo const& lineInfo );
  2884. }
  2885. #ifdef __clang__
  2886. #pragma clang diagnostic pop
  2887. #endif
  2888. // end catch_test_case_info.h
  2889. // start catch_interfaces_runner.h
  2890. namespace Catch {
  2891. struct IRunner {
  2892. virtual ~IRunner();
  2893. virtual bool aborting() const = 0;
  2894. };
  2895. }
  2896. // end catch_interfaces_runner.h
  2897. #ifdef __OBJC__
  2898. // start catch_objc.hpp
  2899. #import <objc/runtime.h>
  2900. #include <string>
  2901. // NB. Any general catch headers included here must be included
  2902. // in catch.hpp first to make sure they are included by the single
  2903. // header for non obj-usage
  2904. ///////////////////////////////////////////////////////////////////////////////
  2905. // This protocol is really only here for (self) documenting purposes, since
  2906. // all its methods are optional.
  2907. @protocol OcFixture
  2908. @optional
  2909. -(void) setUp;
  2910. -(void) tearDown;
  2911. @end
  2912. namespace Catch {
  2913. class OcMethod : public ITestInvoker {
  2914. public:
  2915. OcMethod( Class cls, SEL sel ) : m_cls( cls ), m_sel( sel ) {}
  2916. virtual void invoke() const {
  2917. id obj = [[m_cls alloc] init];
  2918. performOptionalSelector( obj, @selector(setUp) );
  2919. performOptionalSelector( obj, m_sel );
  2920. performOptionalSelector( obj, @selector(tearDown) );
  2921. arcSafeRelease( obj );
  2922. }
  2923. private:
  2924. virtual ~OcMethod() {}
  2925. Class m_cls;
  2926. SEL m_sel;
  2927. };
  2928. namespace Detail{
  2929. inline std::string getAnnotation( Class cls,
  2930. std::string const& annotationName,
  2931. std::string const& testCaseName ) {
  2932. NSString* selStr = [[NSString alloc] initWithFormat:@"Catch_%s_%s", annotationName.c_str(), testCaseName.c_str()];
  2933. SEL sel = NSSelectorFromString( selStr );
  2934. arcSafeRelease( selStr );
  2935. id value = performOptionalSelector( cls, sel );
  2936. if( value )
  2937. return [(NSString*)value UTF8String];
  2938. return "";
  2939. }
  2940. }
  2941. inline std::size_t registerTestMethods() {
  2942. std::size_t noTestMethods = 0;
  2943. int noClasses = objc_getClassList( nullptr, 0 );
  2944. Class* classes = (CATCH_UNSAFE_UNRETAINED Class *)malloc( sizeof(Class) * noClasses);
  2945. objc_getClassList( classes, noClasses );
  2946. for( int c = 0; c < noClasses; c++ ) {
  2947. Class cls = classes[c];
  2948. {
  2949. u_int count;
  2950. Method* methods = class_copyMethodList( cls, &count );
  2951. for( u_int m = 0; m < count ; m++ ) {
  2952. SEL selector = method_getName(methods[m]);
  2953. std::string methodName = sel_getName(selector);
  2954. if( startsWith( methodName, "Catch_TestCase_" ) ) {
  2955. std::string testCaseName = methodName.substr( 15 );
  2956. std::string name = Detail::getAnnotation( cls, "Name", testCaseName );
  2957. std::string desc = Detail::getAnnotation( cls, "Description", testCaseName );
  2958. const char* className = class_getName( cls );
  2959. getMutableRegistryHub().registerTest( makeTestCase( new OcMethod( cls, selector ), className, NameAndTags( name.c_str(), desc.c_str() ), SourceLineInfo("",0) ) );
  2960. noTestMethods++;
  2961. }
  2962. }
  2963. free(methods);
  2964. }
  2965. }
  2966. return noTestMethods;
  2967. }
  2968. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  2969. namespace Matchers {
  2970. namespace Impl {
  2971. namespace NSStringMatchers {
  2972. struct StringHolder : MatcherBase<NSString*>{
  2973. StringHolder( NSString* substr ) : m_substr( [substr copy] ){}
  2974. StringHolder( StringHolder const& other ) : m_substr( [other.m_substr copy] ){}
  2975. StringHolder() {
  2976. arcSafeRelease( m_substr );
  2977. }
  2978. bool match( NSString* arg ) const override {
  2979. return false;
  2980. }
  2981. NSString* CATCH_ARC_STRONG m_substr;
  2982. };
  2983. struct Equals : StringHolder {
  2984. Equals( NSString* substr ) : StringHolder( substr ){}
  2985. bool match( NSString* str ) const override {
  2986. return (str != nil || m_substr == nil ) &&
  2987. [str isEqualToString:m_substr];
  2988. }
  2989. std::string describe() const override {
  2990. return "equals string: " + Catch::Detail::stringify( m_substr );
  2991. }
  2992. };
  2993. struct Contains : StringHolder {
  2994. Contains( NSString* substr ) : StringHolder( substr ){}
  2995. bool match( NSString* str ) const {
  2996. return (str != nil || m_substr == nil ) &&
  2997. [str rangeOfString:m_substr].location != NSNotFound;
  2998. }
  2999. std::string describe() const override {
  3000. return "contains string: " + Catch::Detail::stringify( m_substr );
  3001. }
  3002. };
  3003. struct StartsWith : StringHolder {
  3004. StartsWith( NSString* substr ) : StringHolder( substr ){}
  3005. bool match( NSString* str ) const override {
  3006. return (str != nil || m_substr == nil ) &&
  3007. [str rangeOfString:m_substr].location == 0;
  3008. }
  3009. std::string describe() const override {
  3010. return "starts with: " + Catch::Detail::stringify( m_substr );
  3011. }
  3012. };
  3013. struct EndsWith : StringHolder {
  3014. EndsWith( NSString* substr ) : StringHolder( substr ){}
  3015. bool match( NSString* str ) const override {
  3016. return (str != nil || m_substr == nil ) &&
  3017. [str rangeOfString:m_substr].location == [str length] - [m_substr length];
  3018. }
  3019. std::string describe() const override {
  3020. return "ends with: " + Catch::Detail::stringify( m_substr );
  3021. }
  3022. };
  3023. } // namespace NSStringMatchers
  3024. } // namespace Impl
  3025. inline Impl::NSStringMatchers::Equals
  3026. Equals( NSString* substr ){ return Impl::NSStringMatchers::Equals( substr ); }
  3027. inline Impl::NSStringMatchers::Contains
  3028. Contains( NSString* substr ){ return Impl::NSStringMatchers::Contains( substr ); }
  3029. inline Impl::NSStringMatchers::StartsWith
  3030. StartsWith( NSString* substr ){ return Impl::NSStringMatchers::StartsWith( substr ); }
  3031. inline Impl::NSStringMatchers::EndsWith
  3032. EndsWith( NSString* substr ){ return Impl::NSStringMatchers::EndsWith( substr ); }
  3033. } // namespace Matchers
  3034. using namespace Matchers;
  3035. #endif // CATCH_CONFIG_DISABLE_MATCHERS
  3036. } // namespace Catch
  3037. ///////////////////////////////////////////////////////////////////////////////
  3038. #define OC_MAKE_UNIQUE_NAME( root, uniqueSuffix ) root##uniqueSuffix
  3039. #define OC_TEST_CASE2( name, desc, uniqueSuffix ) \
  3040. +(NSString*) OC_MAKE_UNIQUE_NAME( Catch_Name_test_, uniqueSuffix ) \
  3041. { \
  3042. return @ name; \
  3043. } \
  3044. +(NSString*) OC_MAKE_UNIQUE_NAME( Catch_Description_test_, uniqueSuffix ) \
  3045. { \
  3046. return @ desc; \
  3047. } \
  3048. -(void) OC_MAKE_UNIQUE_NAME( Catch_TestCase_test_, uniqueSuffix )
  3049. #define OC_TEST_CASE( name, desc ) OC_TEST_CASE2( name, desc, __LINE__ )
  3050. // end catch_objc.hpp
  3051. #endif
  3052. #ifdef CATCH_CONFIG_EXTERNAL_INTERFACES
  3053. // start catch_external_interfaces.h
  3054. // start catch_reporter_bases.hpp
  3055. // start catch_interfaces_reporter.h
  3056. // start catch_config.hpp
  3057. // start catch_test_spec_parser.h
  3058. #ifdef __clang__
  3059. #pragma clang diagnostic push
  3060. #pragma clang diagnostic ignored "-Wpadded"
  3061. #endif
  3062. // start catch_test_spec.h
  3063. #ifdef __clang__
  3064. #pragma clang diagnostic push
  3065. #pragma clang diagnostic ignored "-Wpadded"
  3066. #endif
  3067. // start catch_wildcard_pattern.h
  3068. namespace Catch
  3069. {
  3070. class WildcardPattern {
  3071. enum WildcardPosition {
  3072. NoWildcard = 0,
  3073. WildcardAtStart = 1,
  3074. WildcardAtEnd = 2,
  3075. WildcardAtBothEnds = WildcardAtStart | WildcardAtEnd
  3076. };
  3077. public:
  3078. WildcardPattern( std::string const& pattern, CaseSensitive::Choice caseSensitivity );
  3079. virtual ~WildcardPattern() = default;
  3080. virtual bool matches( std::string const& str ) const;
  3081. private:
  3082. std::string adjustCase( std::string const& str ) const;
  3083. CaseSensitive::Choice m_caseSensitivity;
  3084. WildcardPosition m_wildcard = NoWildcard;
  3085. std::string m_pattern;
  3086. };
  3087. }
  3088. // end catch_wildcard_pattern.h
  3089. #include <string>
  3090. #include <vector>
  3091. #include <memory>
  3092. namespace Catch {
  3093. class TestSpec {
  3094. struct Pattern {
  3095. virtual ~Pattern();
  3096. virtual bool matches( TestCaseInfo const& testCase ) const = 0;
  3097. };
  3098. using PatternPtr = std::shared_ptr<Pattern>;
  3099. class NamePattern : public Pattern {
  3100. public:
  3101. NamePattern( std::string const& name );
  3102. virtual ~NamePattern();
  3103. virtual bool matches( TestCaseInfo const& testCase ) const override;
  3104. private:
  3105. WildcardPattern m_wildcardPattern;
  3106. };
  3107. class TagPattern : public Pattern {
  3108. public:
  3109. TagPattern( std::string const& tag );
  3110. virtual ~TagPattern();
  3111. virtual bool matches( TestCaseInfo const& testCase ) const override;
  3112. private:
  3113. std::string m_tag;
  3114. };
  3115. class ExcludedPattern : public Pattern {
  3116. public:
  3117. ExcludedPattern( PatternPtr const& underlyingPattern );
  3118. virtual ~ExcludedPattern();
  3119. virtual bool matches( TestCaseInfo const& testCase ) const override;
  3120. private:
  3121. PatternPtr m_underlyingPattern;
  3122. };
  3123. struct Filter {
  3124. std::vector<PatternPtr> m_patterns;
  3125. bool matches( TestCaseInfo const& testCase ) const;
  3126. };
  3127. public:
  3128. bool hasFilters() const;
  3129. bool matches( TestCaseInfo const& testCase ) const;
  3130. private:
  3131. std::vector<Filter> m_filters;
  3132. friend class TestSpecParser;
  3133. };
  3134. }
  3135. #ifdef __clang__
  3136. #pragma clang diagnostic pop
  3137. #endif
  3138. // end catch_test_spec.h
  3139. // start catch_interfaces_tag_alias_registry.h
  3140. #include <string>
  3141. namespace Catch {
  3142. struct TagAlias;
  3143. struct ITagAliasRegistry {
  3144. virtual ~ITagAliasRegistry();
  3145. // Nullptr if not present
  3146. virtual TagAlias const* find( std::string const& alias ) const = 0;
  3147. virtual std::string expandAliases( std::string const& unexpandedTestSpec ) const = 0;
  3148. static ITagAliasRegistry const& get();
  3149. };
  3150. } // end namespace Catch
  3151. // end catch_interfaces_tag_alias_registry.h
  3152. namespace Catch {
  3153. class TestSpecParser {
  3154. enum Mode{ None, Name, QuotedName, Tag, EscapedName };
  3155. Mode m_mode = None;
  3156. bool m_exclusion = false;
  3157. std::size_t m_start = std::string::npos, m_pos = 0;
  3158. std::string m_arg;
  3159. std::vector<std::size_t> m_escapeChars;
  3160. TestSpec::Filter m_currentFilter;
  3161. TestSpec m_testSpec;
  3162. ITagAliasRegistry const* m_tagAliases = nullptr;
  3163. public:
  3164. TestSpecParser( ITagAliasRegistry const& tagAliases );
  3165. TestSpecParser& parse( std::string const& arg );
  3166. TestSpec testSpec();
  3167. private:
  3168. void visitChar( char c );
  3169. void startNewMode( Mode mode, std::size_t start );
  3170. void escape();
  3171. std::string subString() const;
  3172. template<typename T>
  3173. void addPattern() {
  3174. std::string token = subString();
  3175. for( std::size_t i = 0; i < m_escapeChars.size(); ++i )
  3176. token = token.substr( 0, m_escapeChars[i]-m_start-i ) + token.substr( m_escapeChars[i]-m_start-i+1 );
  3177. m_escapeChars.clear();
  3178. if( startsWith( token, "exclude:" ) ) {
  3179. m_exclusion = true;
  3180. token = token.substr( 8 );
  3181. }
  3182. if( !token.empty() ) {
  3183. TestSpec::PatternPtr pattern = std::make_shared<T>( token );
  3184. if( m_exclusion )
  3185. pattern = std::make_shared<TestSpec::ExcludedPattern>( pattern );
  3186. m_currentFilter.m_patterns.push_back( pattern );
  3187. }
  3188. m_exclusion = false;
  3189. m_mode = None;
  3190. }
  3191. void addFilter();
  3192. };
  3193. TestSpec parseTestSpec( std::string const& arg );
  3194. } // namespace Catch
  3195. #ifdef __clang__
  3196. #pragma clang diagnostic pop
  3197. #endif
  3198. // end catch_test_spec_parser.h
  3199. // start catch_interfaces_config.h
  3200. #include <iosfwd>
  3201. #include <string>
  3202. #include <vector>
  3203. #include <memory>
  3204. namespace Catch {
  3205. enum class Verbosity {
  3206. Quiet = 0,
  3207. Normal,
  3208. High
  3209. };
  3210. struct WarnAbout { enum What {
  3211. Nothing = 0x00,
  3212. NoAssertions = 0x01,
  3213. NoTests = 0x02
  3214. }; };
  3215. struct ShowDurations { enum OrNot {
  3216. DefaultForReporter,
  3217. Always,
  3218. Never
  3219. }; };
  3220. struct RunTests { enum InWhatOrder {
  3221. InDeclarationOrder,
  3222. InLexicographicalOrder,
  3223. InRandomOrder
  3224. }; };
  3225. struct UseColour { enum YesOrNo {
  3226. Auto,
  3227. Yes,
  3228. No
  3229. }; };
  3230. struct WaitForKeypress { enum When {
  3231. Never,
  3232. BeforeStart = 1,
  3233. BeforeExit = 2,
  3234. BeforeStartAndExit = BeforeStart | BeforeExit
  3235. }; };
  3236. class TestSpec;
  3237. struct IConfig : NonCopyable {
  3238. virtual ~IConfig();
  3239. virtual bool allowThrows() const = 0;
  3240. virtual std::ostream& stream() const = 0;
  3241. virtual std::string name() const = 0;
  3242. virtual bool includeSuccessfulResults() const = 0;
  3243. virtual bool shouldDebugBreak() const = 0;
  3244. virtual bool warnAboutMissingAssertions() const = 0;
  3245. virtual bool warnAboutNoTests() const = 0;
  3246. virtual int abortAfter() const = 0;
  3247. virtual bool showInvisibles() const = 0;
  3248. virtual ShowDurations::OrNot showDurations() const = 0;
  3249. virtual TestSpec const& testSpec() const = 0;
  3250. virtual bool hasTestFilters() const = 0;
  3251. virtual RunTests::InWhatOrder runOrder() const = 0;
  3252. virtual unsigned int rngSeed() const = 0;
  3253. virtual int benchmarkResolutionMultiple() const = 0;
  3254. virtual UseColour::YesOrNo useColour() const = 0;
  3255. virtual std::vector<std::string> const& getSectionsToRun() const = 0;
  3256. virtual Verbosity verbosity() const = 0;
  3257. };
  3258. using IConfigPtr = std::shared_ptr<IConfig const>;
  3259. }
  3260. // end catch_interfaces_config.h
  3261. // Libstdc++ doesn't like incomplete classes for unique_ptr
  3262. #include <memory>
  3263. #include <vector>
  3264. #include <string>
  3265. #ifndef CATCH_CONFIG_CONSOLE_WIDTH
  3266. #define CATCH_CONFIG_CONSOLE_WIDTH 80
  3267. #endif
  3268. namespace Catch {
  3269. struct IStream;
  3270. struct ConfigData {
  3271. bool listTests = false;
  3272. bool listTags = false;
  3273. bool listReporters = false;
  3274. bool listTestNamesOnly = false;
  3275. bool showSuccessfulTests = false;
  3276. bool shouldDebugBreak = false;
  3277. bool noThrow = false;
  3278. bool showHelp = false;
  3279. bool showInvisibles = false;
  3280. bool filenamesAsTags = false;
  3281. bool libIdentify = false;
  3282. int abortAfter = -1;
  3283. unsigned int rngSeed = 0;
  3284. int benchmarkResolutionMultiple = 100;
  3285. Verbosity verbosity = Verbosity::Normal;
  3286. WarnAbout::What warnings = WarnAbout::Nothing;
  3287. ShowDurations::OrNot showDurations = ShowDurations::DefaultForReporter;
  3288. RunTests::InWhatOrder runOrder = RunTests::InDeclarationOrder;
  3289. UseColour::YesOrNo useColour = UseColour::Auto;
  3290. WaitForKeypress::When waitForKeypress = WaitForKeypress::Never;
  3291. std::string outputFilename;
  3292. std::string name;
  3293. std::string processName;
  3294. #ifndef CATCH_CONFIG_DEFAULT_REPORTER
  3295. #define CATCH_CONFIG_DEFAULT_REPORTER "console"
  3296. #endif
  3297. std::string reporterName = CATCH_CONFIG_DEFAULT_REPORTER;
  3298. #undef CATCH_CONFIG_DEFAULT_REPORTER
  3299. std::vector<std::string> testsOrTags;
  3300. std::vector<std::string> sectionsToRun;
  3301. };
  3302. class Config : public IConfig {
  3303. public:
  3304. Config() = default;
  3305. Config( ConfigData const& data );
  3306. virtual ~Config() = default;
  3307. std::string const& getFilename() const;
  3308. bool listTests() const;
  3309. bool listTestNamesOnly() const;
  3310. bool listTags() const;
  3311. bool listReporters() const;
  3312. std::string getProcessName() const;
  3313. std::string const& getReporterName() const;
  3314. std::vector<std::string> const& getTestsOrTags() const;
  3315. std::vector<std::string> const& getSectionsToRun() const override;
  3316. virtual TestSpec const& testSpec() const override;
  3317. bool hasTestFilters() const override;
  3318. bool showHelp() const;
  3319. // IConfig interface
  3320. bool allowThrows() const override;
  3321. std::ostream& stream() const override;
  3322. std::string name() const override;
  3323. bool includeSuccessfulResults() const override;
  3324. bool warnAboutMissingAssertions() const override;
  3325. bool warnAboutNoTests() const override;
  3326. ShowDurations::OrNot showDurations() const override;
  3327. RunTests::InWhatOrder runOrder() const override;
  3328. unsigned int rngSeed() const override;
  3329. int benchmarkResolutionMultiple() const override;
  3330. UseColour::YesOrNo useColour() const override;
  3331. bool shouldDebugBreak() const override;
  3332. int abortAfter() const override;
  3333. bool showInvisibles() const override;
  3334. Verbosity verbosity() const override;
  3335. private:
  3336. IStream const* openStream();
  3337. ConfigData m_data;
  3338. std::unique_ptr<IStream const> m_stream;
  3339. TestSpec m_testSpec;
  3340. bool m_hasTestFilters = false;
  3341. };
  3342. } // end namespace Catch
  3343. // end catch_config.hpp
  3344. // start catch_assertionresult.h
  3345. #include <string>
  3346. namespace Catch {
  3347. struct AssertionResultData
  3348. {
  3349. AssertionResultData() = delete;
  3350. AssertionResultData( ResultWas::OfType _resultType, LazyExpression const& _lazyExpression );
  3351. std::string message;
  3352. mutable std::string reconstructedExpression;
  3353. LazyExpression lazyExpression;
  3354. ResultWas::OfType resultType;
  3355. std::string reconstructExpression() const;
  3356. };
  3357. class AssertionResult {
  3358. public:
  3359. AssertionResult() = delete;
  3360. AssertionResult( AssertionInfo const& info, AssertionResultData const& data );
  3361. bool isOk() const;
  3362. bool succeeded() const;
  3363. ResultWas::OfType getResultType() const;
  3364. bool hasExpression() const;
  3365. bool hasMessage() const;
  3366. std::string getExpression() const;
  3367. std::string getExpressionInMacro() const;
  3368. bool hasExpandedExpression() const;
  3369. std::string getExpandedExpression() const;
  3370. std::string getMessage() const;
  3371. SourceLineInfo getSourceInfo() const;
  3372. StringRef getTestMacroName() const;
  3373. //protected:
  3374. AssertionInfo m_info;
  3375. AssertionResultData m_resultData;
  3376. };
  3377. } // end namespace Catch
  3378. // end catch_assertionresult.h
  3379. // start catch_option.hpp
  3380. namespace Catch {
  3381. // An optional type
  3382. template<typename T>
  3383. class Option {
  3384. public:
  3385. Option() : nullableValue( nullptr ) {}
  3386. Option( T const& _value )
  3387. : nullableValue( new( storage ) T( _value ) )
  3388. {}
  3389. Option( Option const& _other )
  3390. : nullableValue( _other ? new( storage ) T( *_other ) : nullptr )
  3391. {}
  3392. ~Option() {
  3393. reset();
  3394. }
  3395. Option& operator= ( Option const& _other ) {
  3396. if( &_other != this ) {
  3397. reset();
  3398. if( _other )
  3399. nullableValue = new( storage ) T( *_other );
  3400. }
  3401. return *this;
  3402. }
  3403. Option& operator = ( T const& _value ) {
  3404. reset();
  3405. nullableValue = new( storage ) T( _value );
  3406. return *this;
  3407. }
  3408. void reset() {
  3409. if( nullableValue )
  3410. nullableValue->~T();
  3411. nullableValue = nullptr;
  3412. }
  3413. T& operator*() { return *nullableValue; }
  3414. T const& operator*() const { return *nullableValue; }
  3415. T* operator->() { return nullableValue; }
  3416. const T* operator->() const { return nullableValue; }
  3417. T valueOr( T const& defaultValue ) const {
  3418. return nullableValue ? *nullableValue : defaultValue;
  3419. }
  3420. bool some() const { return nullableValue != nullptr; }
  3421. bool none() const { return nullableValue == nullptr; }
  3422. bool operator !() const { return nullableValue == nullptr; }
  3423. explicit operator bool() const {
  3424. return some();
  3425. }
  3426. private:
  3427. T *nullableValue;
  3428. alignas(alignof(T)) char storage[sizeof(T)];
  3429. };
  3430. } // end namespace Catch
  3431. // end catch_option.hpp
  3432. #include <string>
  3433. #include <iosfwd>
  3434. #include <map>
  3435. #include <set>
  3436. #include <memory>
  3437. namespace Catch {
  3438. struct ReporterConfig {
  3439. explicit ReporterConfig( IConfigPtr const& _fullConfig );
  3440. ReporterConfig( IConfigPtr const& _fullConfig, std::ostream& _stream );
  3441. std::ostream& stream() const;
  3442. IConfigPtr fullConfig() const;
  3443. private:
  3444. std::ostream* m_stream;
  3445. IConfigPtr m_fullConfig;
  3446. };
  3447. struct ReporterPreferences {
  3448. bool shouldRedirectStdOut = false;
  3449. bool shouldReportAllAssertions = false;
  3450. };
  3451. template<typename T>
  3452. struct LazyStat : Option<T> {
  3453. LazyStat& operator=( T const& _value ) {
  3454. Option<T>::operator=( _value );
  3455. used = false;
  3456. return *this;
  3457. }
  3458. void reset() {
  3459. Option<T>::reset();
  3460. used = false;
  3461. }
  3462. bool used = false;
  3463. };
  3464. struct TestRunInfo {
  3465. TestRunInfo( std::string const& _name );
  3466. std::string name;
  3467. };
  3468. struct GroupInfo {
  3469. GroupInfo( std::string const& _name,
  3470. std::size_t _groupIndex,
  3471. std::size_t _groupsCount );
  3472. std::string name;
  3473. std::size_t groupIndex;
  3474. std::size_t groupsCounts;
  3475. };
  3476. struct AssertionStats {
  3477. AssertionStats( AssertionResult const& _assertionResult,
  3478. std::vector<MessageInfo> const& _infoMessages,
  3479. Totals const& _totals );
  3480. AssertionStats( AssertionStats const& ) = default;
  3481. AssertionStats( AssertionStats && ) = default;
  3482. AssertionStats& operator = ( AssertionStats const& ) = default;
  3483. AssertionStats& operator = ( AssertionStats && ) = default;
  3484. virtual ~AssertionStats();
  3485. AssertionResult assertionResult;
  3486. std::vector<MessageInfo> infoMessages;
  3487. Totals totals;
  3488. };
  3489. struct SectionStats {
  3490. SectionStats( SectionInfo const& _sectionInfo,
  3491. Counts const& _assertions,
  3492. double _durationInSeconds,
  3493. bool _missingAssertions );
  3494. SectionStats( SectionStats const& ) = default;
  3495. SectionStats( SectionStats && ) = default;
  3496. SectionStats& operator = ( SectionStats const& ) = default;
  3497. SectionStats& operator = ( SectionStats && ) = default;
  3498. virtual ~SectionStats();
  3499. SectionInfo sectionInfo;
  3500. Counts assertions;
  3501. double durationInSeconds;
  3502. bool missingAssertions;
  3503. };
  3504. struct TestCaseStats {
  3505. TestCaseStats( TestCaseInfo const& _testInfo,
  3506. Totals const& _totals,
  3507. std::string const& _stdOut,
  3508. std::string const& _stdErr,
  3509. bool _aborting );
  3510. TestCaseStats( TestCaseStats const& ) = default;
  3511. TestCaseStats( TestCaseStats && ) = default;
  3512. TestCaseStats& operator = ( TestCaseStats const& ) = default;
  3513. TestCaseStats& operator = ( TestCaseStats && ) = default;
  3514. virtual ~TestCaseStats();
  3515. TestCaseInfo testInfo;
  3516. Totals totals;
  3517. std::string stdOut;
  3518. std::string stdErr;
  3519. bool aborting;
  3520. };
  3521. struct TestGroupStats {
  3522. TestGroupStats( GroupInfo const& _groupInfo,
  3523. Totals const& _totals,
  3524. bool _aborting );
  3525. TestGroupStats( GroupInfo const& _groupInfo );
  3526. TestGroupStats( TestGroupStats const& ) = default;
  3527. TestGroupStats( TestGroupStats && ) = default;
  3528. TestGroupStats& operator = ( TestGroupStats const& ) = default;
  3529. TestGroupStats& operator = ( TestGroupStats && ) = default;
  3530. virtual ~TestGroupStats();
  3531. GroupInfo groupInfo;
  3532. Totals totals;
  3533. bool aborting;
  3534. };
  3535. struct TestRunStats {
  3536. TestRunStats( TestRunInfo const& _runInfo,
  3537. Totals const& _totals,
  3538. bool _aborting );
  3539. TestRunStats( TestRunStats const& ) = default;
  3540. TestRunStats( TestRunStats && ) = default;
  3541. TestRunStats& operator = ( TestRunStats const& ) = default;
  3542. TestRunStats& operator = ( TestRunStats && ) = default;
  3543. virtual ~TestRunStats();
  3544. TestRunInfo runInfo;
  3545. Totals totals;
  3546. bool aborting;
  3547. };
  3548. struct BenchmarkInfo {
  3549. std::string name;
  3550. };
  3551. struct BenchmarkStats {
  3552. BenchmarkInfo info;
  3553. std::size_t iterations;
  3554. uint64_t elapsedTimeInNanoseconds;
  3555. };
  3556. struct IStreamingReporter {
  3557. virtual ~IStreamingReporter() = default;
  3558. // Implementing class must also provide the following static methods:
  3559. // static std::string getDescription();
  3560. // static std::set<Verbosity> getSupportedVerbosities()
  3561. virtual ReporterPreferences getPreferences() const = 0;
  3562. virtual void noMatchingTestCases( std::string const& spec ) = 0;
  3563. virtual void testRunStarting( TestRunInfo const& testRunInfo ) = 0;
  3564. virtual void testGroupStarting( GroupInfo const& groupInfo ) = 0;
  3565. virtual void testCaseStarting( TestCaseInfo const& testInfo ) = 0;
  3566. virtual void sectionStarting( SectionInfo const& sectionInfo ) = 0;
  3567. // *** experimental ***
  3568. virtual void benchmarkStarting( BenchmarkInfo const& ) {}
  3569. virtual void assertionStarting( AssertionInfo const& assertionInfo ) = 0;
  3570. // The return value indicates if the messages buffer should be cleared:
  3571. virtual bool assertionEnded( AssertionStats const& assertionStats ) = 0;
  3572. // *** experimental ***
  3573. virtual void benchmarkEnded( BenchmarkStats const& ) {}
  3574. virtual void sectionEnded( SectionStats const& sectionStats ) = 0;
  3575. virtual void testCaseEnded( TestCaseStats const& testCaseStats ) = 0;
  3576. virtual void testGroupEnded( TestGroupStats const& testGroupStats ) = 0;
  3577. virtual void testRunEnded( TestRunStats const& testRunStats ) = 0;
  3578. virtual void skipTest( TestCaseInfo const& testInfo ) = 0;
  3579. // Default empty implementation provided
  3580. virtual void fatalErrorEncountered( StringRef name );
  3581. virtual bool isMulti() const;
  3582. };
  3583. using IStreamingReporterPtr = std::unique_ptr<IStreamingReporter>;
  3584. struct IReporterFactory {
  3585. virtual ~IReporterFactory();
  3586. virtual IStreamingReporterPtr create( ReporterConfig const& config ) const = 0;
  3587. virtual std::string getDescription() const = 0;
  3588. };
  3589. using IReporterFactoryPtr = std::shared_ptr<IReporterFactory>;
  3590. struct IReporterRegistry {
  3591. using FactoryMap = std::map<std::string, IReporterFactoryPtr>;
  3592. using Listeners = std::vector<IReporterFactoryPtr>;
  3593. virtual ~IReporterRegistry();
  3594. virtual IStreamingReporterPtr create( std::string const& name, IConfigPtr const& config ) const = 0;
  3595. virtual FactoryMap const& getFactories() const = 0;
  3596. virtual Listeners const& getListeners() const = 0;
  3597. };
  3598. } // end namespace Catch
  3599. // end catch_interfaces_reporter.h
  3600. #include <algorithm>
  3601. #include <cstring>
  3602. #include <cfloat>
  3603. #include <cstdio>
  3604. #include <cassert>
  3605. #include <memory>
  3606. #include <ostream>
  3607. namespace Catch {
  3608. void prepareExpandedExpression(AssertionResult& result);
  3609. // Returns double formatted as %.3f (format expected on output)
  3610. std::string getFormattedDuration( double duration );
  3611. template<typename DerivedT>
  3612. struct StreamingReporterBase : IStreamingReporter {
  3613. StreamingReporterBase( ReporterConfig const& _config )
  3614. : m_config( _config.fullConfig() ),
  3615. stream( _config.stream() )
  3616. {
  3617. m_reporterPrefs.shouldRedirectStdOut = false;
  3618. if( !DerivedT::getSupportedVerbosities().count( m_config->verbosity() ) )
  3619. CATCH_ERROR( "Verbosity level not supported by this reporter" );
  3620. }
  3621. ReporterPreferences getPreferences() const override {
  3622. return m_reporterPrefs;
  3623. }
  3624. static std::set<Verbosity> getSupportedVerbosities() {
  3625. return { Verbosity::Normal };
  3626. }
  3627. ~StreamingReporterBase() override = default;
  3628. void noMatchingTestCases(std::string const&) override {}
  3629. void testRunStarting(TestRunInfo const& _testRunInfo) override {
  3630. currentTestRunInfo = _testRunInfo;
  3631. }
  3632. void testGroupStarting(GroupInfo const& _groupInfo) override {
  3633. currentGroupInfo = _groupInfo;
  3634. }
  3635. void testCaseStarting(TestCaseInfo const& _testInfo) override {
  3636. currentTestCaseInfo = _testInfo;
  3637. }
  3638. void sectionStarting(SectionInfo const& _sectionInfo) override {
  3639. m_sectionStack.push_back(_sectionInfo);
  3640. }
  3641. void sectionEnded(SectionStats const& /* _sectionStats */) override {
  3642. m_sectionStack.pop_back();
  3643. }
  3644. void testCaseEnded(TestCaseStats const& /* _testCaseStats */) override {
  3645. currentTestCaseInfo.reset();
  3646. }
  3647. void testGroupEnded(TestGroupStats const& /* _testGroupStats */) override {
  3648. currentGroupInfo.reset();
  3649. }
  3650. void testRunEnded(TestRunStats const& /* _testRunStats */) override {
  3651. currentTestCaseInfo.reset();
  3652. currentGroupInfo.reset();
  3653. currentTestRunInfo.reset();
  3654. }
  3655. void skipTest(TestCaseInfo const&) override {
  3656. // Don't do anything with this by default.
  3657. // It can optionally be overridden in the derived class.
  3658. }
  3659. IConfigPtr m_config;
  3660. std::ostream& stream;
  3661. LazyStat<TestRunInfo> currentTestRunInfo;
  3662. LazyStat<GroupInfo> currentGroupInfo;
  3663. LazyStat<TestCaseInfo> currentTestCaseInfo;
  3664. std::vector<SectionInfo> m_sectionStack;
  3665. ReporterPreferences m_reporterPrefs;
  3666. };
  3667. template<typename DerivedT>
  3668. struct CumulativeReporterBase : IStreamingReporter {
  3669. template<typename T, typename ChildNodeT>
  3670. struct Node {
  3671. explicit Node( T const& _value ) : value( _value ) {}
  3672. virtual ~Node() {}
  3673. using ChildNodes = std::vector<std::shared_ptr<ChildNodeT>>;
  3674. T value;
  3675. ChildNodes children;
  3676. };
  3677. struct SectionNode {
  3678. explicit SectionNode(SectionStats const& _stats) : stats(_stats) {}
  3679. virtual ~SectionNode() = default;
  3680. bool operator == (SectionNode const& other) const {
  3681. return stats.sectionInfo.lineInfo == other.stats.sectionInfo.lineInfo;
  3682. }
  3683. bool operator == (std::shared_ptr<SectionNode> const& other) const {
  3684. return operator==(*other);
  3685. }
  3686. SectionStats stats;
  3687. using ChildSections = std::vector<std::shared_ptr<SectionNode>>;
  3688. using Assertions = std::vector<AssertionStats>;
  3689. ChildSections childSections;
  3690. Assertions assertions;
  3691. std::string stdOut;
  3692. std::string stdErr;
  3693. };
  3694. struct BySectionInfo {
  3695. BySectionInfo( SectionInfo const& other ) : m_other( other ) {}
  3696. BySectionInfo( BySectionInfo const& other ) : m_other( other.m_other ) {}
  3697. bool operator() (std::shared_ptr<SectionNode> const& node) const {
  3698. return ((node->stats.sectionInfo.name == m_other.name) &&
  3699. (node->stats.sectionInfo.lineInfo == m_other.lineInfo));
  3700. }
  3701. void operator=(BySectionInfo const&) = delete;
  3702. private:
  3703. SectionInfo const& m_other;
  3704. };
  3705. using TestCaseNode = Node<TestCaseStats, SectionNode>;
  3706. using TestGroupNode = Node<TestGroupStats, TestCaseNode>;
  3707. using TestRunNode = Node<TestRunStats, TestGroupNode>;
  3708. CumulativeReporterBase( ReporterConfig const& _config )
  3709. : m_config( _config.fullConfig() ),
  3710. stream( _config.stream() )
  3711. {
  3712. m_reporterPrefs.shouldRedirectStdOut = false;
  3713. if( !DerivedT::getSupportedVerbosities().count( m_config->verbosity() ) )
  3714. CATCH_ERROR( "Verbosity level not supported by this reporter" );
  3715. }
  3716. ~CumulativeReporterBase() override = default;
  3717. ReporterPreferences getPreferences() const override {
  3718. return m_reporterPrefs;
  3719. }
  3720. static std::set<Verbosity> getSupportedVerbosities() {
  3721. return { Verbosity::Normal };
  3722. }
  3723. void testRunStarting( TestRunInfo const& ) override {}
  3724. void testGroupStarting( GroupInfo const& ) override {}
  3725. void testCaseStarting( TestCaseInfo const& ) override {}
  3726. void sectionStarting( SectionInfo const& sectionInfo ) override {
  3727. SectionStats incompleteStats( sectionInfo, Counts(), 0, false );
  3728. std::shared_ptr<SectionNode> node;
  3729. if( m_sectionStack.empty() ) {
  3730. if( !m_rootSection )
  3731. m_rootSection = std::make_shared<SectionNode>( incompleteStats );
  3732. node = m_rootSection;
  3733. }
  3734. else {
  3735. SectionNode& parentNode = *m_sectionStack.back();
  3736. auto it =
  3737. std::find_if( parentNode.childSections.begin(),
  3738. parentNode.childSections.end(),
  3739. BySectionInfo( sectionInfo ) );
  3740. if( it == parentNode.childSections.end() ) {
  3741. node = std::make_shared<SectionNode>( incompleteStats );
  3742. parentNode.childSections.push_back( node );
  3743. }
  3744. else
  3745. node = *it;
  3746. }
  3747. m_sectionStack.push_back( node );
  3748. m_deepestSection = std::move(node);
  3749. }
  3750. void assertionStarting(AssertionInfo const&) override {}
  3751. bool assertionEnded(AssertionStats const& assertionStats) override {
  3752. assert(!m_sectionStack.empty());
  3753. // AssertionResult holds a pointer to a temporary DecomposedExpression,
  3754. // which getExpandedExpression() calls to build the expression string.
  3755. // Our section stack copy of the assertionResult will likely outlive the
  3756. // temporary, so it must be expanded or discarded now to avoid calling
  3757. // a destroyed object later.
  3758. prepareExpandedExpression(const_cast<AssertionResult&>( assertionStats.assertionResult ) );
  3759. SectionNode& sectionNode = *m_sectionStack.back();
  3760. sectionNode.assertions.push_back(assertionStats);
  3761. return true;
  3762. }
  3763. void sectionEnded(SectionStats const& sectionStats) override {
  3764. assert(!m_sectionStack.empty());
  3765. SectionNode& node = *m_sectionStack.back();
  3766. node.stats = sectionStats;
  3767. m_sectionStack.pop_back();
  3768. }
  3769. void testCaseEnded(TestCaseStats const& testCaseStats) override {
  3770. auto node = std::make_shared<TestCaseNode>(testCaseStats);
  3771. assert(m_sectionStack.size() == 0);
  3772. node->children.push_back(m_rootSection);
  3773. m_testCases.push_back(node);
  3774. m_rootSection.reset();
  3775. assert(m_deepestSection);
  3776. m_deepestSection->stdOut = testCaseStats.stdOut;
  3777. m_deepestSection->stdErr = testCaseStats.stdErr;
  3778. }
  3779. void testGroupEnded(TestGroupStats const& testGroupStats) override {
  3780. auto node = std::make_shared<TestGroupNode>(testGroupStats);
  3781. node->children.swap(m_testCases);
  3782. m_testGroups.push_back(node);
  3783. }
  3784. void testRunEnded(TestRunStats const& testRunStats) override {
  3785. auto node = std::make_shared<TestRunNode>(testRunStats);
  3786. node->children.swap(m_testGroups);
  3787. m_testRuns.push_back(node);
  3788. testRunEndedCumulative();
  3789. }
  3790. virtual void testRunEndedCumulative() = 0;
  3791. void skipTest(TestCaseInfo const&) override {}
  3792. IConfigPtr m_config;
  3793. std::ostream& stream;
  3794. std::vector<AssertionStats> m_assertions;
  3795. std::vector<std::vector<std::shared_ptr<SectionNode>>> m_sections;
  3796. std::vector<std::shared_ptr<TestCaseNode>> m_testCases;
  3797. std::vector<std::shared_ptr<TestGroupNode>> m_testGroups;
  3798. std::vector<std::shared_ptr<TestRunNode>> m_testRuns;
  3799. std::shared_ptr<SectionNode> m_rootSection;
  3800. std::shared_ptr<SectionNode> m_deepestSection;
  3801. std::vector<std::shared_ptr<SectionNode>> m_sectionStack;
  3802. ReporterPreferences m_reporterPrefs;
  3803. };
  3804. template<char C>
  3805. char const* getLineOfChars() {
  3806. static char line[CATCH_CONFIG_CONSOLE_WIDTH] = {0};
  3807. if( !*line ) {
  3808. std::memset( line, C, CATCH_CONFIG_CONSOLE_WIDTH-1 );
  3809. line[CATCH_CONFIG_CONSOLE_WIDTH-1] = 0;
  3810. }
  3811. return line;
  3812. }
  3813. struct TestEventListenerBase : StreamingReporterBase<TestEventListenerBase> {
  3814. TestEventListenerBase( ReporterConfig const& _config );
  3815. static std::set<Verbosity> getSupportedVerbosities();
  3816. void assertionStarting(AssertionInfo const&) override;
  3817. bool assertionEnded(AssertionStats const&) override;
  3818. };
  3819. } // end namespace Catch
  3820. // end catch_reporter_bases.hpp
  3821. // start catch_console_colour.h
  3822. namespace Catch {
  3823. struct Colour {
  3824. enum Code {
  3825. None = 0,
  3826. White,
  3827. Red,
  3828. Green,
  3829. Blue,
  3830. Cyan,
  3831. Yellow,
  3832. Grey,
  3833. Bright = 0x10,
  3834. BrightRed = Bright | Red,
  3835. BrightGreen = Bright | Green,
  3836. LightGrey = Bright | Grey,
  3837. BrightWhite = Bright | White,
  3838. BrightYellow = Bright | Yellow,
  3839. // By intention
  3840. FileName = LightGrey,
  3841. Warning = BrightYellow,
  3842. ResultError = BrightRed,
  3843. ResultSuccess = BrightGreen,
  3844. ResultExpectedFailure = Warning,
  3845. Error = BrightRed,
  3846. Success = Green,
  3847. OriginalExpression = Cyan,
  3848. ReconstructedExpression = BrightYellow,
  3849. SecondaryText = LightGrey,
  3850. Headers = White
  3851. };
  3852. // Use constructed object for RAII guard
  3853. Colour( Code _colourCode );
  3854. Colour( Colour&& other ) noexcept;
  3855. Colour& operator=( Colour&& other ) noexcept;
  3856. ~Colour();
  3857. // Use static method for one-shot changes
  3858. static void use( Code _colourCode );
  3859. private:
  3860. bool m_moved = false;
  3861. };
  3862. std::ostream& operator << ( std::ostream& os, Colour const& );
  3863. } // end namespace Catch
  3864. // end catch_console_colour.h
  3865. // start catch_reporter_registrars.hpp
  3866. namespace Catch {
  3867. template<typename T>
  3868. class ReporterRegistrar {
  3869. class ReporterFactory : public IReporterFactory {
  3870. virtual IStreamingReporterPtr create( ReporterConfig const& config ) const override {
  3871. return std::unique_ptr<T>( new T( config ) );
  3872. }
  3873. virtual std::string getDescription() const override {
  3874. return T::getDescription();
  3875. }
  3876. };
  3877. public:
  3878. explicit ReporterRegistrar( std::string const& name ) {
  3879. getMutableRegistryHub().registerReporter( name, std::make_shared<ReporterFactory>() );
  3880. }
  3881. };
  3882. template<typename T>
  3883. class ListenerRegistrar {
  3884. class ListenerFactory : public IReporterFactory {
  3885. virtual IStreamingReporterPtr create( ReporterConfig const& config ) const override {
  3886. return std::unique_ptr<T>( new T( config ) );
  3887. }
  3888. virtual std::string getDescription() const override {
  3889. return std::string();
  3890. }
  3891. };
  3892. public:
  3893. ListenerRegistrar() {
  3894. getMutableRegistryHub().registerListener( std::make_shared<ListenerFactory>() );
  3895. }
  3896. };
  3897. }
  3898. #if !defined(CATCH_CONFIG_DISABLE)
  3899. #define CATCH_REGISTER_REPORTER( name, reporterType ) \
  3900. CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
  3901. namespace{ Catch::ReporterRegistrar<reporterType> catch_internal_RegistrarFor##reporterType( name ); } \
  3902. CATCH_INTERNAL_UNSUPPRESS_GLOBALS_WARNINGS
  3903. #define CATCH_REGISTER_LISTENER( listenerType ) \
  3904. CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
  3905. namespace{ Catch::ListenerRegistrar<listenerType> catch_internal_RegistrarFor##listenerType; } \
  3906. CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS
  3907. #else // CATCH_CONFIG_DISABLE
  3908. #define CATCH_REGISTER_REPORTER(name, reporterType)
  3909. #define CATCH_REGISTER_LISTENER(listenerType)
  3910. #endif // CATCH_CONFIG_DISABLE
  3911. // end catch_reporter_registrars.hpp
  3912. // Allow users to base their work off existing reporters
  3913. // start catch_reporter_compact.h
  3914. namespace Catch {
  3915. struct CompactReporter : StreamingReporterBase<CompactReporter> {
  3916. using StreamingReporterBase::StreamingReporterBase;
  3917. ~CompactReporter() override;
  3918. static std::string getDescription();
  3919. ReporterPreferences getPreferences() const override;
  3920. void noMatchingTestCases(std::string const& spec) override;
  3921. void assertionStarting(AssertionInfo const&) override;
  3922. bool assertionEnded(AssertionStats const& _assertionStats) override;
  3923. void sectionEnded(SectionStats const& _sectionStats) override;
  3924. void testRunEnded(TestRunStats const& _testRunStats) override;
  3925. };
  3926. } // end namespace Catch
  3927. // end catch_reporter_compact.h
  3928. // start catch_reporter_console.h
  3929. #if defined(_MSC_VER)
  3930. #pragma warning(push)
  3931. #pragma warning(disable:4061) // Not all labels are EXPLICITLY handled in switch
  3932. // Note that 4062 (not all labels are handled
  3933. // and default is missing) is enabled
  3934. #endif
  3935. namespace Catch {
  3936. // Fwd decls
  3937. struct SummaryColumn;
  3938. class TablePrinter;
  3939. struct ConsoleReporter : StreamingReporterBase<ConsoleReporter> {
  3940. std::unique_ptr<TablePrinter> m_tablePrinter;
  3941. ConsoleReporter(ReporterConfig const& config);
  3942. ~ConsoleReporter() override;
  3943. static std::string getDescription();
  3944. void noMatchingTestCases(std::string const& spec) override;
  3945. void assertionStarting(AssertionInfo const&) override;
  3946. bool assertionEnded(AssertionStats const& _assertionStats) override;
  3947. void sectionStarting(SectionInfo const& _sectionInfo) override;
  3948. void sectionEnded(SectionStats const& _sectionStats) override;
  3949. void benchmarkStarting(BenchmarkInfo const& info) override;
  3950. void benchmarkEnded(BenchmarkStats const& stats) override;
  3951. void testCaseEnded(TestCaseStats const& _testCaseStats) override;
  3952. void testGroupEnded(TestGroupStats const& _testGroupStats) override;
  3953. void testRunEnded(TestRunStats const& _testRunStats) override;
  3954. private:
  3955. void lazyPrint();
  3956. void lazyPrintWithoutClosingBenchmarkTable();
  3957. void lazyPrintRunInfo();
  3958. void lazyPrintGroupInfo();
  3959. void printTestCaseAndSectionHeader();
  3960. void printClosedHeader(std::string const& _name);
  3961. void printOpenHeader(std::string const& _name);
  3962. // if string has a : in first line will set indent to follow it on
  3963. // subsequent lines
  3964. void printHeaderString(std::string const& _string, std::size_t indent = 0);
  3965. void printTotals(Totals const& totals);
  3966. void printSummaryRow(std::string const& label, std::vector<SummaryColumn> const& cols, std::size_t row);
  3967. void printTotalsDivider(Totals const& totals);
  3968. void printSummaryDivider();
  3969. private:
  3970. bool m_headerPrinted = false;
  3971. };
  3972. } // end namespace Catch
  3973. #if defined(_MSC_VER)
  3974. #pragma warning(pop)
  3975. #endif
  3976. // end catch_reporter_console.h
  3977. // start catch_reporter_junit.h
  3978. // start catch_xmlwriter.h
  3979. #include <vector>
  3980. namespace Catch {
  3981. class XmlEncode {
  3982. public:
  3983. enum ForWhat { ForTextNodes, ForAttributes };
  3984. XmlEncode( std::string const& str, ForWhat forWhat = ForTextNodes );
  3985. void encodeTo( std::ostream& os ) const;
  3986. friend std::ostream& operator << ( std::ostream& os, XmlEncode const& xmlEncode );
  3987. private:
  3988. std::string m_str;
  3989. ForWhat m_forWhat;
  3990. };
  3991. class XmlWriter {
  3992. public:
  3993. class ScopedElement {
  3994. public:
  3995. ScopedElement( XmlWriter* writer );
  3996. ScopedElement( ScopedElement&& other ) noexcept;
  3997. ScopedElement& operator=( ScopedElement&& other ) noexcept;
  3998. ~ScopedElement();
  3999. ScopedElement& writeText( std::string const& text, bool indent = true );
  4000. template<typename T>
  4001. ScopedElement& writeAttribute( std::string const& name, T const& attribute ) {
  4002. m_writer->writeAttribute( name, attribute );
  4003. return *this;
  4004. }
  4005. private:
  4006. mutable XmlWriter* m_writer = nullptr;
  4007. };
  4008. XmlWriter( std::ostream& os = Catch::cout() );
  4009. ~XmlWriter();
  4010. XmlWriter( XmlWriter const& ) = delete;
  4011. XmlWriter& operator=( XmlWriter const& ) = delete;
  4012. XmlWriter& startElement( std::string const& name );
  4013. ScopedElement scopedElement( std::string const& name );
  4014. XmlWriter& endElement();
  4015. XmlWriter& writeAttribute( std::string const& name, std::string const& attribute );
  4016. XmlWriter& writeAttribute( std::string const& name, bool attribute );
  4017. template<typename T>
  4018. XmlWriter& writeAttribute( std::string const& name, T const& attribute ) {
  4019. ReusableStringStream rss;
  4020. rss << attribute;
  4021. return writeAttribute( name, rss.str() );
  4022. }
  4023. XmlWriter& writeText( std::string const& text, bool indent = true );
  4024. XmlWriter& writeComment( std::string const& text );
  4025. void writeStylesheetRef( std::string const& url );
  4026. XmlWriter& writeBlankLine();
  4027. void ensureTagClosed();
  4028. private:
  4029. void writeDeclaration();
  4030. void newlineIfNecessary();
  4031. bool m_tagIsOpen = false;
  4032. bool m_needsNewline = false;
  4033. std::vector<std::string> m_tags;
  4034. std::string m_indent;
  4035. std::ostream& m_os;
  4036. };
  4037. }
  4038. // end catch_xmlwriter.h
  4039. namespace Catch {
  4040. class JunitReporter : public CumulativeReporterBase<JunitReporter> {
  4041. public:
  4042. JunitReporter(ReporterConfig const& _config);
  4043. ~JunitReporter() override;
  4044. static std::string getDescription();
  4045. void noMatchingTestCases(std::string const& /*spec*/) override;
  4046. void testRunStarting(TestRunInfo const& runInfo) override;
  4047. void testGroupStarting(GroupInfo const& groupInfo) override;
  4048. void testCaseStarting(TestCaseInfo const& testCaseInfo) override;
  4049. bool assertionEnded(AssertionStats const& assertionStats) override;
  4050. void testCaseEnded(TestCaseStats const& testCaseStats) override;
  4051. void testGroupEnded(TestGroupStats const& testGroupStats) override;
  4052. void testRunEndedCumulative() override;
  4053. void writeGroup(TestGroupNode const& groupNode, double suiteTime);
  4054. void writeTestCase(TestCaseNode const& testCaseNode);
  4055. void writeSection(std::string const& className,
  4056. std::string const& rootName,
  4057. SectionNode const& sectionNode);
  4058. void writeAssertions(SectionNode const& sectionNode);
  4059. void writeAssertion(AssertionStats const& stats);
  4060. XmlWriter xml;
  4061. Timer suiteTimer;
  4062. std::string stdOutForSuite;
  4063. std::string stdErrForSuite;
  4064. unsigned int unexpectedExceptions = 0;
  4065. bool m_okToFail = false;
  4066. };
  4067. } // end namespace Catch
  4068. // end catch_reporter_junit.h
  4069. // start catch_reporter_xml.h
  4070. namespace Catch {
  4071. class XmlReporter : public StreamingReporterBase<XmlReporter> {
  4072. public:
  4073. XmlReporter(ReporterConfig const& _config);
  4074. ~XmlReporter() override;
  4075. static std::string getDescription();
  4076. virtual std::string getStylesheetRef() const;
  4077. void writeSourceInfo(SourceLineInfo const& sourceInfo);
  4078. public: // StreamingReporterBase
  4079. void noMatchingTestCases(std::string const& s) override;
  4080. void testRunStarting(TestRunInfo const& testInfo) override;
  4081. void testGroupStarting(GroupInfo const& groupInfo) override;
  4082. void testCaseStarting(TestCaseInfo const& testInfo) override;
  4083. void sectionStarting(SectionInfo const& sectionInfo) override;
  4084. void assertionStarting(AssertionInfo const&) override;
  4085. bool assertionEnded(AssertionStats const& assertionStats) override;
  4086. void sectionEnded(SectionStats const& sectionStats) override;
  4087. void testCaseEnded(TestCaseStats const& testCaseStats) override;
  4088. void testGroupEnded(TestGroupStats const& testGroupStats) override;
  4089. void testRunEnded(TestRunStats const& testRunStats) override;
  4090. private:
  4091. Timer m_testCaseTimer;
  4092. XmlWriter m_xml;
  4093. int m_sectionDepth = 0;
  4094. };
  4095. } // end namespace Catch
  4096. // end catch_reporter_xml.h
  4097. // end catch_external_interfaces.h
  4098. #endif
  4099. #endif // ! CATCH_CONFIG_IMPL_ONLY
  4100. #ifdef CATCH_IMPL
  4101. // start catch_impl.hpp
  4102. #ifdef __clang__
  4103. #pragma clang diagnostic push
  4104. #pragma clang diagnostic ignored "-Wweak-vtables"
  4105. #endif
  4106. // Keep these here for external reporters
  4107. // start catch_test_case_tracker.h
  4108. #include <string>
  4109. #include <vector>
  4110. #include <memory>
  4111. namespace Catch {
  4112. namespace TestCaseTracking {
  4113. struct NameAndLocation {
  4114. std::string name;
  4115. SourceLineInfo location;
  4116. NameAndLocation( std::string const& _name, SourceLineInfo const& _location );
  4117. };
  4118. struct ITracker;
  4119. using ITrackerPtr = std::shared_ptr<ITracker>;
  4120. struct ITracker {
  4121. virtual ~ITracker();
  4122. // static queries
  4123. virtual NameAndLocation const& nameAndLocation() const = 0;
  4124. // dynamic queries
  4125. virtual bool isComplete() const = 0; // Successfully completed or failed
  4126. virtual bool isSuccessfullyCompleted() const = 0;
  4127. virtual bool isOpen() const = 0; // Started but not complete
  4128. virtual bool hasChildren() const = 0;
  4129. virtual ITracker& parent() = 0;
  4130. // actions
  4131. virtual void close() = 0; // Successfully complete
  4132. virtual void fail() = 0;
  4133. virtual void markAsNeedingAnotherRun() = 0;
  4134. virtual void addChild( ITrackerPtr const& child ) = 0;
  4135. virtual ITrackerPtr findChild( NameAndLocation const& nameAndLocation ) = 0;
  4136. virtual void openChild() = 0;
  4137. // Debug/ checking
  4138. virtual bool isSectionTracker() const = 0;
  4139. virtual bool isIndexTracker() const = 0;
  4140. };
  4141. class TrackerContext {
  4142. enum RunState {
  4143. NotStarted,
  4144. Executing,
  4145. CompletedCycle
  4146. };
  4147. ITrackerPtr m_rootTracker;
  4148. ITracker* m_currentTracker = nullptr;
  4149. RunState m_runState = NotStarted;
  4150. public:
  4151. static TrackerContext& instance();
  4152. ITracker& startRun();
  4153. void endRun();
  4154. void startCycle();
  4155. void completeCycle();
  4156. bool completedCycle() const;
  4157. ITracker& currentTracker();
  4158. void setCurrentTracker( ITracker* tracker );
  4159. };
  4160. class TrackerBase : public ITracker {
  4161. protected:
  4162. enum CycleState {
  4163. NotStarted,
  4164. Executing,
  4165. ExecutingChildren,
  4166. NeedsAnotherRun,
  4167. CompletedSuccessfully,
  4168. Failed
  4169. };
  4170. using Children = std::vector<ITrackerPtr>;
  4171. NameAndLocation m_nameAndLocation;
  4172. TrackerContext& m_ctx;
  4173. ITracker* m_parent;
  4174. Children m_children;
  4175. CycleState m_runState = NotStarted;
  4176. public:
  4177. TrackerBase( NameAndLocation const& nameAndLocation, TrackerContext& ctx, ITracker* parent );
  4178. NameAndLocation const& nameAndLocation() const override;
  4179. bool isComplete() const override;
  4180. bool isSuccessfullyCompleted() const override;
  4181. bool isOpen() const override;
  4182. bool hasChildren() const override;
  4183. void addChild( ITrackerPtr const& child ) override;
  4184. ITrackerPtr findChild( NameAndLocation const& nameAndLocation ) override;
  4185. ITracker& parent() override;
  4186. void openChild() override;
  4187. bool isSectionTracker() const override;
  4188. bool isIndexTracker() const override;
  4189. void open();
  4190. void close() override;
  4191. void fail() override;
  4192. void markAsNeedingAnotherRun() override;
  4193. private:
  4194. void moveToParent();
  4195. void moveToThis();
  4196. };
  4197. class SectionTracker : public TrackerBase {
  4198. std::vector<std::string> m_filters;
  4199. public:
  4200. SectionTracker( NameAndLocation const& nameAndLocation, TrackerContext& ctx, ITracker* parent );
  4201. bool isSectionTracker() const override;
  4202. static SectionTracker& acquire( TrackerContext& ctx, NameAndLocation const& nameAndLocation );
  4203. void tryOpen();
  4204. void addInitialFilters( std::vector<std::string> const& filters );
  4205. void addNextFilters( std::vector<std::string> const& filters );
  4206. };
  4207. class IndexTracker : public TrackerBase {
  4208. int m_size;
  4209. int m_index = -1;
  4210. public:
  4211. IndexTracker( NameAndLocation const& nameAndLocation, TrackerContext& ctx, ITracker* parent, int size );
  4212. bool isIndexTracker() const override;
  4213. void close() override;
  4214. static IndexTracker& acquire( TrackerContext& ctx, NameAndLocation const& nameAndLocation, int size );
  4215. int index() const;
  4216. void moveNext();
  4217. };
  4218. } // namespace TestCaseTracking
  4219. using TestCaseTracking::ITracker;
  4220. using TestCaseTracking::TrackerContext;
  4221. using TestCaseTracking::SectionTracker;
  4222. using TestCaseTracking::IndexTracker;
  4223. } // namespace Catch
  4224. // end catch_test_case_tracker.h
  4225. // start catch_leak_detector.h
  4226. namespace Catch {
  4227. struct LeakDetector {
  4228. LeakDetector();
  4229. ~LeakDetector();
  4230. };
  4231. }
  4232. // end catch_leak_detector.h
  4233. // Cpp files will be included in the single-header file here
  4234. // start catch_approx.cpp
  4235. #include <cmath>
  4236. #include <limits>
  4237. namespace {
  4238. // Performs equivalent check of std::fabs(lhs - rhs) <= margin
  4239. // But without the subtraction to allow for INFINITY in comparison
  4240. bool marginComparison(double lhs, double rhs, double margin) {
  4241. return (lhs + margin >= rhs) && (rhs + margin >= lhs);
  4242. }
  4243. }
  4244. namespace Catch {
  4245. namespace Detail {
  4246. Approx::Approx ( double value )
  4247. : m_epsilon( std::numeric_limits<float>::epsilon()*100 ),
  4248. m_margin( 0.0 ),
  4249. m_scale( 0.0 ),
  4250. m_value( value )
  4251. {}
  4252. Approx Approx::custom() {
  4253. return Approx( 0 );
  4254. }
  4255. Approx Approx::operator-() const {
  4256. auto temp(*this);
  4257. temp.m_value = -temp.m_value;
  4258. return temp;
  4259. }
  4260. std::string Approx::toString() const {
  4261. ReusableStringStream rss;
  4262. rss << "Approx( " << ::Catch::Detail::stringify( m_value ) << " )";
  4263. return rss.str();
  4264. }
  4265. bool Approx::equalityComparisonImpl(const double other) const {
  4266. // First try with fixed margin, then compute margin based on epsilon, scale and Approx's value
  4267. // Thanks to Richard Harris for his help refining the scaled margin value
  4268. return marginComparison(m_value, other, m_margin) || marginComparison(m_value, other, m_epsilon * (m_scale + std::fabs(m_value)));
  4269. }
  4270. void Approx::setMargin(double margin) {
  4271. CATCH_ENFORCE(margin >= 0,
  4272. "Invalid Approx::margin: " << margin << '.'
  4273. << " Approx::Margin has to be non-negative.");
  4274. m_margin = margin;
  4275. }
  4276. void Approx::setEpsilon(double epsilon) {
  4277. CATCH_ENFORCE(epsilon >= 0 && epsilon <= 1.0,
  4278. "Invalid Approx::epsilon: " << epsilon << '.'
  4279. << " Approx::epsilon has to be in [0, 1]");
  4280. m_epsilon = epsilon;
  4281. }
  4282. } // end namespace Detail
  4283. namespace literals {
  4284. Detail::Approx operator "" _a(long double val) {
  4285. return Detail::Approx(val);
  4286. }
  4287. Detail::Approx operator "" _a(unsigned long long val) {
  4288. return Detail::Approx(val);
  4289. }
  4290. } // end namespace literals
  4291. std::string StringMaker<Catch::Detail::Approx>::convert(Catch::Detail::Approx const& value) {
  4292. return value.toString();
  4293. }
  4294. } // end namespace Catch
  4295. // end catch_approx.cpp
  4296. // start catch_assertionhandler.cpp
  4297. // start catch_context.h
  4298. #include <memory>
  4299. namespace Catch {
  4300. struct IResultCapture;
  4301. struct IRunner;
  4302. struct IConfig;
  4303. struct IMutableContext;
  4304. using IConfigPtr = std::shared_ptr<IConfig const>;
  4305. struct IContext
  4306. {
  4307. virtual ~IContext();
  4308. virtual IResultCapture* getResultCapture() = 0;
  4309. virtual IRunner* getRunner() = 0;
  4310. virtual IConfigPtr const& getConfig() const = 0;
  4311. };
  4312. struct IMutableContext : IContext
  4313. {
  4314. virtual ~IMutableContext();
  4315. virtual void setResultCapture( IResultCapture* resultCapture ) = 0;
  4316. virtual void setRunner( IRunner* runner ) = 0;
  4317. virtual void setConfig( IConfigPtr const& config ) = 0;
  4318. private:
  4319. static IMutableContext *currentContext;
  4320. friend IMutableContext& getCurrentMutableContext();
  4321. friend void cleanUpContext();
  4322. static void createContext();
  4323. };
  4324. inline IMutableContext& getCurrentMutableContext()
  4325. {
  4326. if( !IMutableContext::currentContext )
  4327. IMutableContext::createContext();
  4328. return *IMutableContext::currentContext;
  4329. }
  4330. inline IContext& getCurrentContext()
  4331. {
  4332. return getCurrentMutableContext();
  4333. }
  4334. void cleanUpContext();
  4335. }
  4336. // end catch_context.h
  4337. // start catch_debugger.h
  4338. namespace Catch {
  4339. bool isDebuggerActive();
  4340. }
  4341. #ifdef CATCH_PLATFORM_MAC
  4342. #define CATCH_TRAP() __asm__("int $3\n" : : ) /* NOLINT */
  4343. #elif defined(CATCH_PLATFORM_LINUX)
  4344. // If we can use inline assembler, do it because this allows us to break
  4345. // directly at the location of the failing check instead of breaking inside
  4346. // raise() called from it, i.e. one stack frame below.
  4347. #if defined(__GNUC__) && (defined(__i386) || defined(__x86_64))
  4348. #define CATCH_TRAP() asm volatile ("int $3") /* NOLINT */
  4349. #else // Fall back to the generic way.
  4350. #include <signal.h>
  4351. #define CATCH_TRAP() raise(SIGTRAP)
  4352. #endif
  4353. #elif defined(_MSC_VER)
  4354. #define CATCH_TRAP() __debugbreak()
  4355. #elif defined(__MINGW32__)
  4356. extern "C" __declspec(dllimport) void __stdcall DebugBreak();
  4357. #define CATCH_TRAP() DebugBreak()
  4358. #endif
  4359. #ifdef CATCH_TRAP
  4360. #define CATCH_BREAK_INTO_DEBUGGER() if( Catch::isDebuggerActive() ) { CATCH_TRAP(); }
  4361. #else
  4362. namespace Catch {
  4363. inline void doNothing() {}
  4364. }
  4365. #define CATCH_BREAK_INTO_DEBUGGER() Catch::doNothing()
  4366. #endif
  4367. // end catch_debugger.h
  4368. // start catch_run_context.h
  4369. // start catch_fatal_condition.h
  4370. // start catch_windows_h_proxy.h
  4371. #if defined(CATCH_PLATFORM_WINDOWS)
  4372. #if !defined(NOMINMAX) && !defined(CATCH_CONFIG_NO_NOMINMAX)
  4373. # define CATCH_DEFINED_NOMINMAX
  4374. # define NOMINMAX
  4375. #endif
  4376. #if !defined(WIN32_LEAN_AND_MEAN) && !defined(CATCH_CONFIG_NO_WIN32_LEAN_AND_MEAN)
  4377. # define CATCH_DEFINED_WIN32_LEAN_AND_MEAN
  4378. # define WIN32_LEAN_AND_MEAN
  4379. #endif
  4380. #ifdef __AFXDLL
  4381. #include <AfxWin.h>
  4382. #else
  4383. #include <windows.h>
  4384. #endif
  4385. #ifdef CATCH_DEFINED_NOMINMAX
  4386. # undef NOMINMAX
  4387. #endif
  4388. #ifdef CATCH_DEFINED_WIN32_LEAN_AND_MEAN
  4389. # undef WIN32_LEAN_AND_MEAN
  4390. #endif
  4391. #endif // defined(CATCH_PLATFORM_WINDOWS)
  4392. // end catch_windows_h_proxy.h
  4393. #if defined( CATCH_CONFIG_WINDOWS_SEH )
  4394. namespace Catch {
  4395. struct FatalConditionHandler {
  4396. static LONG CALLBACK handleVectoredException(PEXCEPTION_POINTERS ExceptionInfo);
  4397. FatalConditionHandler();
  4398. static void reset();
  4399. ~FatalConditionHandler();
  4400. private:
  4401. static bool isSet;
  4402. static ULONG guaranteeSize;
  4403. static PVOID exceptionHandlerHandle;
  4404. };
  4405. } // namespace Catch
  4406. #elif defined ( CATCH_CONFIG_POSIX_SIGNALS )
  4407. #include <signal.h>
  4408. namespace Catch {
  4409. struct FatalConditionHandler {
  4410. static bool isSet;
  4411. static struct sigaction oldSigActions[];
  4412. static stack_t oldSigStack;
  4413. static char altStackMem[];
  4414. static void handleSignal( int sig );
  4415. FatalConditionHandler();
  4416. ~FatalConditionHandler();
  4417. static void reset();
  4418. };
  4419. } // namespace Catch
  4420. #else
  4421. namespace Catch {
  4422. struct FatalConditionHandler {
  4423. void reset();
  4424. };
  4425. }
  4426. #endif
  4427. // end catch_fatal_condition.h
  4428. #include <string>
  4429. namespace Catch {
  4430. struct IMutableContext;
  4431. ///////////////////////////////////////////////////////////////////////////
  4432. class RunContext : public IResultCapture, public IRunner {
  4433. public:
  4434. RunContext( RunContext const& ) = delete;
  4435. RunContext& operator =( RunContext const& ) = delete;
  4436. explicit RunContext( IConfigPtr const& _config, IStreamingReporterPtr&& reporter );
  4437. ~RunContext() override;
  4438. void testGroupStarting( std::string const& testSpec, std::size_t groupIndex, std::size_t groupsCount );
  4439. void testGroupEnded( std::string const& testSpec, Totals const& totals, std::size_t groupIndex, std::size_t groupsCount );
  4440. Totals runTest(TestCase const& testCase);
  4441. IConfigPtr config() const;
  4442. IStreamingReporter& reporter() const;
  4443. public: // IResultCapture
  4444. // Assertion handlers
  4445. void handleExpr
  4446. ( AssertionInfo const& info,
  4447. ITransientExpression const& expr,
  4448. AssertionReaction& reaction ) override;
  4449. void handleMessage
  4450. ( AssertionInfo const& info,
  4451. ResultWas::OfType resultType,
  4452. StringRef const& message,
  4453. AssertionReaction& reaction ) override;
  4454. void handleUnexpectedExceptionNotThrown
  4455. ( AssertionInfo const& info,
  4456. AssertionReaction& reaction ) override;
  4457. void handleUnexpectedInflightException
  4458. ( AssertionInfo const& info,
  4459. std::string const& message,
  4460. AssertionReaction& reaction ) override;
  4461. void handleIncomplete
  4462. ( AssertionInfo const& info ) override;
  4463. void handleNonExpr
  4464. ( AssertionInfo const &info,
  4465. ResultWas::OfType resultType,
  4466. AssertionReaction &reaction ) override;
  4467. bool sectionStarted( SectionInfo const& sectionInfo, Counts& assertions ) override;
  4468. void sectionEnded( SectionEndInfo const& endInfo ) override;
  4469. void sectionEndedEarly( SectionEndInfo const& endInfo ) override;
  4470. auto acquireGeneratorTracker( SourceLineInfo const& lineInfo ) -> IGeneratorTracker& override;
  4471. void benchmarkStarting( BenchmarkInfo const& info ) override;
  4472. void benchmarkEnded( BenchmarkStats const& stats ) override;
  4473. void pushScopedMessage( MessageInfo const& message ) override;
  4474. void popScopedMessage( MessageInfo const& message ) override;
  4475. std::string getCurrentTestName() const override;
  4476. const AssertionResult* getLastResult() const override;
  4477. void exceptionEarlyReported() override;
  4478. void handleFatalErrorCondition( StringRef message ) override;
  4479. bool lastAssertionPassed() override;
  4480. void assertionPassed() override;
  4481. public:
  4482. // !TBD We need to do this another way!
  4483. bool aborting() const final;
  4484. private:
  4485. void runCurrentTest( std::string& redirectedCout, std::string& redirectedCerr );
  4486. void invokeActiveTestCase();
  4487. void resetAssertionInfo();
  4488. bool testForMissingAssertions( Counts& assertions );
  4489. void assertionEnded( AssertionResult const& result );
  4490. void reportExpr
  4491. ( AssertionInfo const &info,
  4492. ResultWas::OfType resultType,
  4493. ITransientExpression const *expr,
  4494. bool negated );
  4495. void populateReaction( AssertionReaction& reaction );
  4496. private:
  4497. void handleUnfinishedSections();
  4498. TestRunInfo m_runInfo;
  4499. IMutableContext& m_context;
  4500. TestCase const* m_activeTestCase = nullptr;
  4501. ITracker* m_testCaseTracker;
  4502. Option<AssertionResult> m_lastResult;
  4503. IConfigPtr m_config;
  4504. Totals m_totals;
  4505. IStreamingReporterPtr m_reporter;
  4506. std::vector<MessageInfo> m_messages;
  4507. AssertionInfo m_lastAssertionInfo;
  4508. std::vector<SectionEndInfo> m_unfinishedSections;
  4509. std::vector<ITracker*> m_activeSections;
  4510. TrackerContext m_trackerContext;
  4511. bool m_lastAssertionPassed = false;
  4512. bool m_shouldReportUnexpected = true;
  4513. bool m_includeSuccessfulResults;
  4514. };
  4515. } // end namespace Catch
  4516. // end catch_run_context.h
  4517. namespace Catch {
  4518. namespace {
  4519. auto operator <<( std::ostream& os, ITransientExpression const& expr ) -> std::ostream& {
  4520. expr.streamReconstructedExpression( os );
  4521. return os;
  4522. }
  4523. }
  4524. LazyExpression::LazyExpression( bool isNegated )
  4525. : m_isNegated( isNegated )
  4526. {}
  4527. LazyExpression::LazyExpression( LazyExpression const& other ) : m_isNegated( other.m_isNegated ) {}
  4528. LazyExpression::operator bool() const {
  4529. return m_transientExpression != nullptr;
  4530. }
  4531. auto operator << ( std::ostream& os, LazyExpression const& lazyExpr ) -> std::ostream& {
  4532. if( lazyExpr.m_isNegated )
  4533. os << "!";
  4534. if( lazyExpr ) {
  4535. if( lazyExpr.m_isNegated && lazyExpr.m_transientExpression->isBinaryExpression() )
  4536. os << "(" << *lazyExpr.m_transientExpression << ")";
  4537. else
  4538. os << *lazyExpr.m_transientExpression;
  4539. }
  4540. else {
  4541. os << "{** error - unchecked empty expression requested **}";
  4542. }
  4543. return os;
  4544. }
  4545. AssertionHandler::AssertionHandler
  4546. ( StringRef const& macroName,
  4547. SourceLineInfo const& lineInfo,
  4548. StringRef capturedExpression,
  4549. ResultDisposition::Flags resultDisposition )
  4550. : m_assertionInfo{ macroName, lineInfo, capturedExpression, resultDisposition },
  4551. m_resultCapture( getResultCapture() )
  4552. {}
  4553. void AssertionHandler::handleExpr( ITransientExpression const& expr ) {
  4554. m_resultCapture.handleExpr( m_assertionInfo, expr, m_reaction );
  4555. }
  4556. void AssertionHandler::handleMessage(ResultWas::OfType resultType, StringRef const& message) {
  4557. m_resultCapture.handleMessage( m_assertionInfo, resultType, message, m_reaction );
  4558. }
  4559. auto AssertionHandler::allowThrows() const -> bool {
  4560. return getCurrentContext().getConfig()->allowThrows();
  4561. }
  4562. void AssertionHandler::complete() {
  4563. setCompleted();
  4564. if( m_reaction.shouldDebugBreak ) {
  4565. // If you find your debugger stopping you here then go one level up on the
  4566. // call-stack for the code that caused it (typically a failed assertion)
  4567. // (To go back to the test and change execution, jump over the throw, next)
  4568. CATCH_BREAK_INTO_DEBUGGER();
  4569. }
  4570. if (m_reaction.shouldThrow) {
  4571. #if !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
  4572. throw Catch::TestFailureException();
  4573. #else
  4574. CATCH_ERROR( "Test failure requires aborting test!" );
  4575. #endif
  4576. }
  4577. }
  4578. void AssertionHandler::setCompleted() {
  4579. m_completed = true;
  4580. }
  4581. void AssertionHandler::handleUnexpectedInflightException() {
  4582. m_resultCapture.handleUnexpectedInflightException( m_assertionInfo, Catch::translateActiveException(), m_reaction );
  4583. }
  4584. void AssertionHandler::handleExceptionThrownAsExpected() {
  4585. m_resultCapture.handleNonExpr(m_assertionInfo, ResultWas::Ok, m_reaction);
  4586. }
  4587. void AssertionHandler::handleExceptionNotThrownAsExpected() {
  4588. m_resultCapture.handleNonExpr(m_assertionInfo, ResultWas::Ok, m_reaction);
  4589. }
  4590. void AssertionHandler::handleUnexpectedExceptionNotThrown() {
  4591. m_resultCapture.handleUnexpectedExceptionNotThrown( m_assertionInfo, m_reaction );
  4592. }
  4593. void AssertionHandler::handleThrowingCallSkipped() {
  4594. m_resultCapture.handleNonExpr(m_assertionInfo, ResultWas::Ok, m_reaction);
  4595. }
  4596. // This is the overload that takes a string and infers the Equals matcher from it
  4597. // The more general overload, that takes any string matcher, is in catch_capture_matchers.cpp
  4598. void handleExceptionMatchExpr( AssertionHandler& handler, std::string const& str, StringRef const& matcherString ) {
  4599. handleExceptionMatchExpr( handler, Matchers::Equals( str ), matcherString );
  4600. }
  4601. } // namespace Catch
  4602. // end catch_assertionhandler.cpp
  4603. // start catch_assertionresult.cpp
  4604. namespace Catch {
  4605. AssertionResultData::AssertionResultData(ResultWas::OfType _resultType, LazyExpression const & _lazyExpression):
  4606. lazyExpression(_lazyExpression),
  4607. resultType(_resultType) {}
  4608. std::string AssertionResultData::reconstructExpression() const {
  4609. if( reconstructedExpression.empty() ) {
  4610. if( lazyExpression ) {
  4611. ReusableStringStream rss;
  4612. rss << lazyExpression;
  4613. reconstructedExpression = rss.str();
  4614. }
  4615. }
  4616. return reconstructedExpression;
  4617. }
  4618. AssertionResult::AssertionResult( AssertionInfo const& info, AssertionResultData const& data )
  4619. : m_info( info ),
  4620. m_resultData( data )
  4621. {}
  4622. // Result was a success
  4623. bool AssertionResult::succeeded() const {
  4624. return Catch::isOk( m_resultData.resultType );
  4625. }
  4626. // Result was a success, or failure is suppressed
  4627. bool AssertionResult::isOk() const {
  4628. return Catch::isOk( m_resultData.resultType ) || shouldSuppressFailure( m_info.resultDisposition );
  4629. }
  4630. ResultWas::OfType AssertionResult::getResultType() const {
  4631. return m_resultData.resultType;
  4632. }
  4633. bool AssertionResult::hasExpression() const {
  4634. return m_info.capturedExpression[0] != 0;
  4635. }
  4636. bool AssertionResult::hasMessage() const {
  4637. return !m_resultData.message.empty();
  4638. }
  4639. std::string AssertionResult::getExpression() const {
  4640. if( isFalseTest( m_info.resultDisposition ) )
  4641. return "!(" + m_info.capturedExpression + ")";
  4642. else
  4643. return m_info.capturedExpression;
  4644. }
  4645. std::string AssertionResult::getExpressionInMacro() const {
  4646. std::string expr;
  4647. if( m_info.macroName[0] == 0 )
  4648. expr = m_info.capturedExpression;
  4649. else {
  4650. expr.reserve( m_info.macroName.size() + m_info.capturedExpression.size() + 4 );
  4651. expr += m_info.macroName;
  4652. expr += "( ";
  4653. expr += m_info.capturedExpression;
  4654. expr += " )";
  4655. }
  4656. return expr;
  4657. }
  4658. bool AssertionResult::hasExpandedExpression() const {
  4659. return hasExpression() && getExpandedExpression() != getExpression();
  4660. }
  4661. std::string AssertionResult::getExpandedExpression() const {
  4662. std::string expr = m_resultData.reconstructExpression();
  4663. return expr.empty()
  4664. ? getExpression()
  4665. : expr;
  4666. }
  4667. std::string AssertionResult::getMessage() const {
  4668. return m_resultData.message;
  4669. }
  4670. SourceLineInfo AssertionResult::getSourceInfo() const {
  4671. return m_info.lineInfo;
  4672. }
  4673. StringRef AssertionResult::getTestMacroName() const {
  4674. return m_info.macroName;
  4675. }
  4676. } // end namespace Catch
  4677. // end catch_assertionresult.cpp
  4678. // start catch_benchmark.cpp
  4679. namespace Catch {
  4680. auto BenchmarkLooper::getResolution() -> uint64_t {
  4681. return getEstimatedClockResolution() * getCurrentContext().getConfig()->benchmarkResolutionMultiple();
  4682. }
  4683. void BenchmarkLooper::reportStart() {
  4684. getResultCapture().benchmarkStarting( { m_name } );
  4685. }
  4686. auto BenchmarkLooper::needsMoreIterations() -> bool {
  4687. auto elapsed = m_timer.getElapsedNanoseconds();
  4688. // Exponentially increasing iterations until we're confident in our timer resolution
  4689. if( elapsed < m_resolution ) {
  4690. m_iterationsToRun *= 10;
  4691. return true;
  4692. }
  4693. getResultCapture().benchmarkEnded( { { m_name }, m_count, elapsed } );
  4694. return false;
  4695. }
  4696. } // end namespace Catch
  4697. // end catch_benchmark.cpp
  4698. // start catch_capture_matchers.cpp
  4699. namespace Catch {
  4700. using StringMatcher = Matchers::Impl::MatcherBase<std::string>;
  4701. // This is the general overload that takes a any string matcher
  4702. // There is another overload, in catch_assertionhandler.h/.cpp, that only takes a string and infers
  4703. // the Equals matcher (so the header does not mention matchers)
  4704. void handleExceptionMatchExpr( AssertionHandler& handler, StringMatcher const& matcher, StringRef const& matcherString ) {
  4705. std::string exceptionMessage = Catch::translateActiveException();
  4706. MatchExpr<std::string, StringMatcher const&> expr( exceptionMessage, matcher, matcherString );
  4707. handler.handleExpr( expr );
  4708. }
  4709. } // namespace Catch
  4710. // end catch_capture_matchers.cpp
  4711. // start catch_commandline.cpp
  4712. // start catch_commandline.h
  4713. // start catch_clara.h
  4714. // Use Catch's value for console width (store Clara's off to the side, if present)
  4715. #ifdef CLARA_CONFIG_CONSOLE_WIDTH
  4716. #define CATCH_TEMP_CLARA_CONFIG_CONSOLE_WIDTH CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH
  4717. #undef CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH
  4718. #endif
  4719. #define CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH CATCH_CONFIG_CONSOLE_WIDTH-1
  4720. #ifdef __clang__
  4721. #pragma clang diagnostic push
  4722. #pragma clang diagnostic ignored "-Wweak-vtables"
  4723. #pragma clang diagnostic ignored "-Wexit-time-destructors"
  4724. #pragma clang diagnostic ignored "-Wshadow"
  4725. #endif
  4726. // start clara.hpp
  4727. // Copyright 2017 Two Blue Cubes Ltd. All rights reserved.
  4728. //
  4729. // Distributed under the Boost Software License, Version 1.0. (See accompanying
  4730. // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
  4731. //
  4732. // See https://github.com/philsquared/Clara for more details
  4733. // Clara v1.1.5
  4734. #ifndef CATCH_CLARA_CONFIG_CONSOLE_WIDTH
  4735. #define CATCH_CLARA_CONFIG_CONSOLE_WIDTH 80
  4736. #endif
  4737. #ifndef CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH
  4738. #define CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH CATCH_CLARA_CONFIG_CONSOLE_WIDTH
  4739. #endif
  4740. #ifndef CLARA_CONFIG_OPTIONAL_TYPE
  4741. #ifdef __has_include
  4742. #if __has_include(<optional>) && __cplusplus >= 201703L
  4743. #include <optional>
  4744. #define CLARA_CONFIG_OPTIONAL_TYPE std::optional
  4745. #endif
  4746. #endif
  4747. #endif
  4748. // ----------- #included from clara_textflow.hpp -----------
  4749. // TextFlowCpp
  4750. //
  4751. // A single-header library for wrapping and laying out basic text, by Phil Nash
  4752. //
  4753. // Distributed under the Boost Software License, Version 1.0. (See accompanying
  4754. // file LICENSE.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
  4755. //
  4756. // This project is hosted at https://github.com/philsquared/textflowcpp
  4757. #include <cassert>
  4758. #include <ostream>
  4759. #include <sstream>
  4760. #include <vector>
  4761. #ifndef CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH
  4762. #define CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH 80
  4763. #endif
  4764. namespace Catch {
  4765. namespace clara {
  4766. namespace TextFlow {
  4767. inline auto isWhitespace(char c) -> bool {
  4768. static std::string chars = " \t\n\r";
  4769. return chars.find(c) != std::string::npos;
  4770. }
  4771. inline auto isBreakableBefore(char c) -> bool {
  4772. static std::string chars = "[({<|";
  4773. return chars.find(c) != std::string::npos;
  4774. }
  4775. inline auto isBreakableAfter(char c) -> bool {
  4776. static std::string chars = "])}>.,:;*+-=&/\\";
  4777. return chars.find(c) != std::string::npos;
  4778. }
  4779. class Columns;
  4780. class Column {
  4781. std::vector<std::string> m_strings;
  4782. size_t m_width = CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH;
  4783. size_t m_indent = 0;
  4784. size_t m_initialIndent = std::string::npos;
  4785. public:
  4786. class iterator {
  4787. friend Column;
  4788. Column const& m_column;
  4789. size_t m_stringIndex = 0;
  4790. size_t m_pos = 0;
  4791. size_t m_len = 0;
  4792. size_t m_end = 0;
  4793. bool m_suffix = false;
  4794. iterator(Column const& column, size_t stringIndex)
  4795. : m_column(column),
  4796. m_stringIndex(stringIndex) {}
  4797. auto line() const -> std::string const& { return m_column.m_strings[m_stringIndex]; }
  4798. auto isBoundary(size_t at) const -> bool {
  4799. assert(at > 0);
  4800. assert(at <= line().size());
  4801. return at == line().size() ||
  4802. (isWhitespace(line()[at]) && !isWhitespace(line()[at - 1])) ||
  4803. isBreakableBefore(line()[at]) ||
  4804. isBreakableAfter(line()[at - 1]);
  4805. }
  4806. void calcLength() {
  4807. assert(m_stringIndex < m_column.m_strings.size());
  4808. m_suffix = false;
  4809. auto width = m_column.m_width - indent();
  4810. m_end = m_pos;
  4811. while (m_end < line().size() && line()[m_end] != '\n')
  4812. ++m_end;
  4813. if (m_end < m_pos + width) {
  4814. m_len = m_end - m_pos;
  4815. } else {
  4816. size_t len = width;
  4817. while (len > 0 && !isBoundary(m_pos + len))
  4818. --len;
  4819. while (len > 0 && isWhitespace(line()[m_pos + len - 1]))
  4820. --len;
  4821. if (len > 0) {
  4822. m_len = len;
  4823. } else {
  4824. m_suffix = true;
  4825. m_len = width - 1;
  4826. }
  4827. }
  4828. }
  4829. auto indent() const -> size_t {
  4830. auto initial = m_pos == 0 && m_stringIndex == 0 ? m_column.m_initialIndent : std::string::npos;
  4831. return initial == std::string::npos ? m_column.m_indent : initial;
  4832. }
  4833. auto addIndentAndSuffix(std::string const &plain) const -> std::string {
  4834. return std::string(indent(), ' ') + (m_suffix ? plain + "-" : plain);
  4835. }
  4836. public:
  4837. using difference_type = std::ptrdiff_t;
  4838. using value_type = std::string;
  4839. using pointer = value_type * ;
  4840. using reference = value_type & ;
  4841. using iterator_category = std::forward_iterator_tag;
  4842. explicit iterator(Column const& column) : m_column(column) {
  4843. assert(m_column.m_width > m_column.m_indent);
  4844. assert(m_column.m_initialIndent == std::string::npos || m_column.m_width > m_column.m_initialIndent);
  4845. calcLength();
  4846. if (m_len == 0)
  4847. m_stringIndex++; // Empty string
  4848. }
  4849. auto operator *() const -> std::string {
  4850. assert(m_stringIndex < m_column.m_strings.size());
  4851. assert(m_pos <= m_end);
  4852. return addIndentAndSuffix(line().substr(m_pos, m_len));
  4853. }
  4854. auto operator ++() -> iterator& {
  4855. m_pos += m_len;
  4856. if (m_pos < line().size() && line()[m_pos] == '\n')
  4857. m_pos += 1;
  4858. else
  4859. while (m_pos < line().size() && isWhitespace(line()[m_pos]))
  4860. ++m_pos;
  4861. if (m_pos == line().size()) {
  4862. m_pos = 0;
  4863. ++m_stringIndex;
  4864. }
  4865. if (m_stringIndex < m_column.m_strings.size())
  4866. calcLength();
  4867. return *this;
  4868. }
  4869. auto operator ++(int) -> iterator {
  4870. iterator prev(*this);
  4871. operator++();
  4872. return prev;
  4873. }
  4874. auto operator ==(iterator const& other) const -> bool {
  4875. return
  4876. m_pos == other.m_pos &&
  4877. m_stringIndex == other.m_stringIndex &&
  4878. &m_column == &other.m_column;
  4879. }
  4880. auto operator !=(iterator const& other) const -> bool {
  4881. return !operator==(other);
  4882. }
  4883. };
  4884. using const_iterator = iterator;
  4885. explicit Column(std::string const& text) { m_strings.push_back(text); }
  4886. auto width(size_t newWidth) -> Column& {
  4887. assert(newWidth > 0);
  4888. m_width = newWidth;
  4889. return *this;
  4890. }
  4891. auto indent(size_t newIndent) -> Column& {
  4892. m_indent = newIndent;
  4893. return *this;
  4894. }
  4895. auto initialIndent(size_t newIndent) -> Column& {
  4896. m_initialIndent = newIndent;
  4897. return *this;
  4898. }
  4899. auto width() const -> size_t { return m_width; }
  4900. auto begin() const -> iterator { return iterator(*this); }
  4901. auto end() const -> iterator { return { *this, m_strings.size() }; }
  4902. inline friend std::ostream& operator << (std::ostream& os, Column const& col) {
  4903. bool first = true;
  4904. for (auto line : col) {
  4905. if (first)
  4906. first = false;
  4907. else
  4908. os << "\n";
  4909. os << line;
  4910. }
  4911. return os;
  4912. }
  4913. auto operator + (Column const& other)->Columns;
  4914. auto toString() const -> std::string {
  4915. std::ostringstream oss;
  4916. oss << *this;
  4917. return oss.str();
  4918. }
  4919. };
  4920. class Spacer : public Column {
  4921. public:
  4922. explicit Spacer(size_t spaceWidth) : Column("") {
  4923. width(spaceWidth);
  4924. }
  4925. };
  4926. class Columns {
  4927. std::vector<Column> m_columns;
  4928. public:
  4929. class iterator {
  4930. friend Columns;
  4931. struct EndTag {};
  4932. std::vector<Column> const& m_columns;
  4933. std::vector<Column::iterator> m_iterators;
  4934. size_t m_activeIterators;
  4935. iterator(Columns const& columns, EndTag)
  4936. : m_columns(columns.m_columns),
  4937. m_activeIterators(0) {
  4938. m_iterators.reserve(m_columns.size());
  4939. for (auto const& col : m_columns)
  4940. m_iterators.push_back(col.end());
  4941. }
  4942. public:
  4943. using difference_type = std::ptrdiff_t;
  4944. using value_type = std::string;
  4945. using pointer = value_type * ;
  4946. using reference = value_type & ;
  4947. using iterator_category = std::forward_iterator_tag;
  4948. explicit iterator(Columns const& columns)
  4949. : m_columns(columns.m_columns),
  4950. m_activeIterators(m_columns.size()) {
  4951. m_iterators.reserve(m_columns.size());
  4952. for (auto const& col : m_columns)
  4953. m_iterators.push_back(col.begin());
  4954. }
  4955. auto operator ==(iterator const& other) const -> bool {
  4956. return m_iterators == other.m_iterators;
  4957. }
  4958. auto operator !=(iterator const& other) const -> bool {
  4959. return m_iterators != other.m_iterators;
  4960. }
  4961. auto operator *() const -> std::string {
  4962. std::string row, padding;
  4963. for (size_t i = 0; i < m_columns.size(); ++i) {
  4964. auto width = m_columns[i].width();
  4965. if (m_iterators[i] != m_columns[i].end()) {
  4966. std::string col = *m_iterators[i];
  4967. row += padding + col;
  4968. if (col.size() < width)
  4969. padding = std::string(width - col.size(), ' ');
  4970. else
  4971. padding = "";
  4972. } else {
  4973. padding += std::string(width, ' ');
  4974. }
  4975. }
  4976. return row;
  4977. }
  4978. auto operator ++() -> iterator& {
  4979. for (size_t i = 0; i < m_columns.size(); ++i) {
  4980. if (m_iterators[i] != m_columns[i].end())
  4981. ++m_iterators[i];
  4982. }
  4983. return *this;
  4984. }
  4985. auto operator ++(int) -> iterator {
  4986. iterator prev(*this);
  4987. operator++();
  4988. return prev;
  4989. }
  4990. };
  4991. using const_iterator = iterator;
  4992. auto begin() const -> iterator { return iterator(*this); }
  4993. auto end() const -> iterator { return { *this, iterator::EndTag() }; }
  4994. auto operator += (Column const& col) -> Columns& {
  4995. m_columns.push_back(col);
  4996. return *this;
  4997. }
  4998. auto operator + (Column const& col) -> Columns {
  4999. Columns combined = *this;
  5000. combined += col;
  5001. return combined;
  5002. }
  5003. inline friend std::ostream& operator << (std::ostream& os, Columns const& cols) {
  5004. bool first = true;
  5005. for (auto line : cols) {
  5006. if (first)
  5007. first = false;
  5008. else
  5009. os << "\n";
  5010. os << line;
  5011. }
  5012. return os;
  5013. }
  5014. auto toString() const -> std::string {
  5015. std::ostringstream oss;
  5016. oss << *this;
  5017. return oss.str();
  5018. }
  5019. };
  5020. inline auto Column::operator + (Column const& other) -> Columns {
  5021. Columns cols;
  5022. cols += *this;
  5023. cols += other;
  5024. return cols;
  5025. }
  5026. }
  5027. }
  5028. }
  5029. // ----------- end of #include from clara_textflow.hpp -----------
  5030. // ........... back in clara.hpp
  5031. #include <string>
  5032. #include <memory>
  5033. #include <set>
  5034. #include <algorithm>
  5035. #if !defined(CATCH_PLATFORM_WINDOWS) && ( defined(WIN32) || defined(__WIN32__) || defined(_WIN32) || defined(_MSC_VER) )
  5036. #define CATCH_PLATFORM_WINDOWS
  5037. #endif
  5038. namespace Catch { namespace clara {
  5039. namespace detail {
  5040. // Traits for extracting arg and return type of lambdas (for single argument lambdas)
  5041. template<typename L>
  5042. struct UnaryLambdaTraits : UnaryLambdaTraits<decltype( &L::operator() )> {};
  5043. template<typename ClassT, typename ReturnT, typename... Args>
  5044. struct UnaryLambdaTraits<ReturnT( ClassT::* )( Args... ) const> {
  5045. static const bool isValid = false;
  5046. };
  5047. template<typename ClassT, typename ReturnT, typename ArgT>
  5048. struct UnaryLambdaTraits<ReturnT( ClassT::* )( ArgT ) const> {
  5049. static const bool isValid = true;
  5050. using ArgType = typename std::remove_const<typename std::remove_reference<ArgT>::type>::type;
  5051. using ReturnType = ReturnT;
  5052. };
  5053. class TokenStream;
  5054. // Transport for raw args (copied from main args, or supplied via init list for testing)
  5055. class Args {
  5056. friend TokenStream;
  5057. std::string m_exeName;
  5058. std::vector<std::string> m_args;
  5059. public:
  5060. Args( int argc, char const* const* argv )
  5061. : m_exeName(argv[0]),
  5062. m_args(argv + 1, argv + argc) {}
  5063. Args( std::initializer_list<std::string> args )
  5064. : m_exeName( *args.begin() ),
  5065. m_args( args.begin()+1, args.end() )
  5066. {}
  5067. auto exeName() const -> std::string {
  5068. return m_exeName;
  5069. }
  5070. };
  5071. // Wraps a token coming from a token stream. These may not directly correspond to strings as a single string
  5072. // may encode an option + its argument if the : or = form is used
  5073. enum class TokenType {
  5074. Option, Argument
  5075. };
  5076. struct Token {
  5077. TokenType type;
  5078. std::string token;
  5079. };
  5080. inline auto isOptPrefix( char c ) -> bool {
  5081. return c == '-'
  5082. #ifdef CATCH_PLATFORM_WINDOWS
  5083. || c == '/'
  5084. #endif
  5085. ;
  5086. }
  5087. // Abstracts iterators into args as a stream of tokens, with option arguments uniformly handled
  5088. class TokenStream {
  5089. using Iterator = std::vector<std::string>::const_iterator;
  5090. Iterator it;
  5091. Iterator itEnd;
  5092. std::vector<Token> m_tokenBuffer;
  5093. void loadBuffer() {
  5094. m_tokenBuffer.resize( 0 );
  5095. // Skip any empty strings
  5096. while( it != itEnd && it->empty() )
  5097. ++it;
  5098. if( it != itEnd ) {
  5099. auto const &next = *it;
  5100. if( isOptPrefix( next[0] ) ) {
  5101. auto delimiterPos = next.find_first_of( " :=" );
  5102. if( delimiterPos != std::string::npos ) {
  5103. m_tokenBuffer.push_back( { TokenType::Option, next.substr( 0, delimiterPos ) } );
  5104. m_tokenBuffer.push_back( { TokenType::Argument, next.substr( delimiterPos + 1 ) } );
  5105. } else {
  5106. if( next[1] != '-' && next.size() > 2 ) {
  5107. std::string opt = "- ";
  5108. for( size_t i = 1; i < next.size(); ++i ) {
  5109. opt[1] = next[i];
  5110. m_tokenBuffer.push_back( { TokenType::Option, opt } );
  5111. }
  5112. } else {
  5113. m_tokenBuffer.push_back( { TokenType::Option, next } );
  5114. }
  5115. }
  5116. } else {
  5117. m_tokenBuffer.push_back( { TokenType::Argument, next } );
  5118. }
  5119. }
  5120. }
  5121. public:
  5122. explicit TokenStream( Args const &args ) : TokenStream( args.m_args.begin(), args.m_args.end() ) {}
  5123. TokenStream( Iterator it, Iterator itEnd ) : it( it ), itEnd( itEnd ) {
  5124. loadBuffer();
  5125. }
  5126. explicit operator bool() const {
  5127. return !m_tokenBuffer.empty() || it != itEnd;
  5128. }
  5129. auto count() const -> size_t { return m_tokenBuffer.size() + (itEnd - it); }
  5130. auto operator*() const -> Token {
  5131. assert( !m_tokenBuffer.empty() );
  5132. return m_tokenBuffer.front();
  5133. }
  5134. auto operator->() const -> Token const * {
  5135. assert( !m_tokenBuffer.empty() );
  5136. return &m_tokenBuffer.front();
  5137. }
  5138. auto operator++() -> TokenStream & {
  5139. if( m_tokenBuffer.size() >= 2 ) {
  5140. m_tokenBuffer.erase( m_tokenBuffer.begin() );
  5141. } else {
  5142. if( it != itEnd )
  5143. ++it;
  5144. loadBuffer();
  5145. }
  5146. return *this;
  5147. }
  5148. };
  5149. class ResultBase {
  5150. public:
  5151. enum Type {
  5152. Ok, LogicError, RuntimeError
  5153. };
  5154. protected:
  5155. ResultBase( Type type ) : m_type( type ) {}
  5156. virtual ~ResultBase() = default;
  5157. virtual void enforceOk() const = 0;
  5158. Type m_type;
  5159. };
  5160. template<typename T>
  5161. class ResultValueBase : public ResultBase {
  5162. public:
  5163. auto value() const -> T const & {
  5164. enforceOk();
  5165. return m_value;
  5166. }
  5167. protected:
  5168. ResultValueBase( Type type ) : ResultBase( type ) {}
  5169. ResultValueBase( ResultValueBase const &other ) : ResultBase( other ) {
  5170. if( m_type == ResultBase::Ok )
  5171. new( &m_value ) T( other.m_value );
  5172. }
  5173. ResultValueBase( Type, T const &value ) : ResultBase( Ok ) {
  5174. new( &m_value ) T( value );
  5175. }
  5176. auto operator=( ResultValueBase const &other ) -> ResultValueBase & {
  5177. if( m_type == ResultBase::Ok )
  5178. m_value.~T();
  5179. ResultBase::operator=(other);
  5180. if( m_type == ResultBase::Ok )
  5181. new( &m_value ) T( other.m_value );
  5182. return *this;
  5183. }
  5184. ~ResultValueBase() override {
  5185. if( m_type == Ok )
  5186. m_value.~T();
  5187. }
  5188. union {
  5189. T m_value;
  5190. };
  5191. };
  5192. template<>
  5193. class ResultValueBase<void> : public ResultBase {
  5194. protected:
  5195. using ResultBase::ResultBase;
  5196. };
  5197. template<typename T = void>
  5198. class BasicResult : public ResultValueBase<T> {
  5199. public:
  5200. template<typename U>
  5201. explicit BasicResult( BasicResult<U> const &other )
  5202. : ResultValueBase<T>( other.type() ),
  5203. m_errorMessage( other.errorMessage() )
  5204. {
  5205. assert( type() != ResultBase::Ok );
  5206. }
  5207. template<typename U>
  5208. static auto ok( U const &value ) -> BasicResult { return { ResultBase::Ok, value }; }
  5209. static auto ok() -> BasicResult { return { ResultBase::Ok }; }
  5210. static auto logicError( std::string const &message ) -> BasicResult { return { ResultBase::LogicError, message }; }
  5211. static auto runtimeError( std::string const &message ) -> BasicResult { return { ResultBase::RuntimeError, message }; }
  5212. explicit operator bool() const { return m_type == ResultBase::Ok; }
  5213. auto type() const -> ResultBase::Type { return m_type; }
  5214. auto errorMessage() const -> std::string { return m_errorMessage; }
  5215. protected:
  5216. void enforceOk() const override {
  5217. // Errors shouldn't reach this point, but if they do
  5218. // the actual error message will be in m_errorMessage
  5219. assert( m_type != ResultBase::LogicError );
  5220. assert( m_type != ResultBase::RuntimeError );
  5221. if( m_type != ResultBase::Ok )
  5222. std::abort();
  5223. }
  5224. std::string m_errorMessage; // Only populated if resultType is an error
  5225. BasicResult( ResultBase::Type type, std::string const &message )
  5226. : ResultValueBase<T>(type),
  5227. m_errorMessage(message)
  5228. {
  5229. assert( m_type != ResultBase::Ok );
  5230. }
  5231. using ResultValueBase<T>::ResultValueBase;
  5232. using ResultBase::m_type;
  5233. };
  5234. enum class ParseResultType {
  5235. Matched, NoMatch, ShortCircuitAll, ShortCircuitSame
  5236. };
  5237. class ParseState {
  5238. public:
  5239. ParseState( ParseResultType type, TokenStream const &remainingTokens )
  5240. : m_type(type),
  5241. m_remainingTokens( remainingTokens )
  5242. {}
  5243. auto type() const -> ParseResultType { return m_type; }
  5244. auto remainingTokens() const -> TokenStream { return m_remainingTokens; }
  5245. private:
  5246. ParseResultType m_type;
  5247. TokenStream m_remainingTokens;
  5248. };
  5249. using Result = BasicResult<void>;
  5250. using ParserResult = BasicResult<ParseResultType>;
  5251. using InternalParseResult = BasicResult<ParseState>;
  5252. struct HelpColumns {
  5253. std::string left;
  5254. std::string right;
  5255. };
  5256. template<typename T>
  5257. inline auto convertInto( std::string const &source, T& target ) -> ParserResult {
  5258. std::stringstream ss;
  5259. ss << source;
  5260. ss >> target;
  5261. if( ss.fail() )
  5262. return ParserResult::runtimeError( "Unable to convert '" + source + "' to destination type" );
  5263. else
  5264. return ParserResult::ok( ParseResultType::Matched );
  5265. }
  5266. inline auto convertInto( std::string const &source, std::string& target ) -> ParserResult {
  5267. target = source;
  5268. return ParserResult::ok( ParseResultType::Matched );
  5269. }
  5270. inline auto convertInto( std::string const &source, bool &target ) -> ParserResult {
  5271. std::string srcLC = source;
  5272. std::transform( srcLC.begin(), srcLC.end(), srcLC.begin(), []( char c ) { return static_cast<char>( ::tolower(c) ); } );
  5273. if (srcLC == "y" || srcLC == "1" || srcLC == "true" || srcLC == "yes" || srcLC == "on")
  5274. target = true;
  5275. else if (srcLC == "n" || srcLC == "0" || srcLC == "false" || srcLC == "no" || srcLC == "off")
  5276. target = false;
  5277. else
  5278. return ParserResult::runtimeError( "Expected a boolean value but did not recognise: '" + source + "'" );
  5279. return ParserResult::ok( ParseResultType::Matched );
  5280. }
  5281. #ifdef CLARA_CONFIG_OPTIONAL_TYPE
  5282. template<typename T>
  5283. inline auto convertInto( std::string const &source, CLARA_CONFIG_OPTIONAL_TYPE<T>& target ) -> ParserResult {
  5284. T temp;
  5285. auto result = convertInto( source, temp );
  5286. if( result )
  5287. target = std::move(temp);
  5288. return result;
  5289. }
  5290. #endif // CLARA_CONFIG_OPTIONAL_TYPE
  5291. struct NonCopyable {
  5292. NonCopyable() = default;
  5293. NonCopyable( NonCopyable const & ) = delete;
  5294. NonCopyable( NonCopyable && ) = delete;
  5295. NonCopyable &operator=( NonCopyable const & ) = delete;
  5296. NonCopyable &operator=( NonCopyable && ) = delete;
  5297. };
  5298. struct BoundRef : NonCopyable {
  5299. virtual ~BoundRef() = default;
  5300. virtual auto isContainer() const -> bool { return false; }
  5301. virtual auto isFlag() const -> bool { return false; }
  5302. };
  5303. struct BoundValueRefBase : BoundRef {
  5304. virtual auto setValue( std::string const &arg ) -> ParserResult = 0;
  5305. };
  5306. struct BoundFlagRefBase : BoundRef {
  5307. virtual auto setFlag( bool flag ) -> ParserResult = 0;
  5308. virtual auto isFlag() const -> bool { return true; }
  5309. };
  5310. template<typename T>
  5311. struct BoundValueRef : BoundValueRefBase {
  5312. T &m_ref;
  5313. explicit BoundValueRef( T &ref ) : m_ref( ref ) {}
  5314. auto setValue( std::string const &arg ) -> ParserResult override {
  5315. return convertInto( arg, m_ref );
  5316. }
  5317. };
  5318. template<typename T>
  5319. struct BoundValueRef<std::vector<T>> : BoundValueRefBase {
  5320. std::vector<T> &m_ref;
  5321. explicit BoundValueRef( std::vector<T> &ref ) : m_ref( ref ) {}
  5322. auto isContainer() const -> bool override { return true; }
  5323. auto setValue( std::string const &arg ) -> ParserResult override {
  5324. T temp;
  5325. auto result = convertInto( arg, temp );
  5326. if( result )
  5327. m_ref.push_back( temp );
  5328. return result;
  5329. }
  5330. };
  5331. struct BoundFlagRef : BoundFlagRefBase {
  5332. bool &m_ref;
  5333. explicit BoundFlagRef( bool &ref ) : m_ref( ref ) {}
  5334. auto setFlag( bool flag ) -> ParserResult override {
  5335. m_ref = flag;
  5336. return ParserResult::ok( ParseResultType::Matched );
  5337. }
  5338. };
  5339. template<typename ReturnType>
  5340. struct LambdaInvoker {
  5341. static_assert( std::is_same<ReturnType, ParserResult>::value, "Lambda must return void or clara::ParserResult" );
  5342. template<typename L, typename ArgType>
  5343. static auto invoke( L const &lambda, ArgType const &arg ) -> ParserResult {
  5344. return lambda( arg );
  5345. }
  5346. };
  5347. template<>
  5348. struct LambdaInvoker<void> {
  5349. template<typename L, typename ArgType>
  5350. static auto invoke( L const &lambda, ArgType const &arg ) -> ParserResult {
  5351. lambda( arg );
  5352. return ParserResult::ok( ParseResultType::Matched );
  5353. }
  5354. };
  5355. template<typename ArgType, typename L>
  5356. inline auto invokeLambda( L const &lambda, std::string const &arg ) -> ParserResult {
  5357. ArgType temp{};
  5358. auto result = convertInto( arg, temp );
  5359. return !result
  5360. ? result
  5361. : LambdaInvoker<typename UnaryLambdaTraits<L>::ReturnType>::invoke( lambda, temp );
  5362. }
  5363. template<typename L>
  5364. struct BoundLambda : BoundValueRefBase {
  5365. L m_lambda;
  5366. static_assert( UnaryLambdaTraits<L>::isValid, "Supplied lambda must take exactly one argument" );
  5367. explicit BoundLambda( L const &lambda ) : m_lambda( lambda ) {}
  5368. auto setValue( std::string const &arg ) -> ParserResult override {
  5369. return invokeLambda<typename UnaryLambdaTraits<L>::ArgType>( m_lambda, arg );
  5370. }
  5371. };
  5372. template<typename L>
  5373. struct BoundFlagLambda : BoundFlagRefBase {
  5374. L m_lambda;
  5375. static_assert( UnaryLambdaTraits<L>::isValid, "Supplied lambda must take exactly one argument" );
  5376. static_assert( std::is_same<typename UnaryLambdaTraits<L>::ArgType, bool>::value, "flags must be boolean" );
  5377. explicit BoundFlagLambda( L const &lambda ) : m_lambda( lambda ) {}
  5378. auto setFlag( bool flag ) -> ParserResult override {
  5379. return LambdaInvoker<typename UnaryLambdaTraits<L>::ReturnType>::invoke( m_lambda, flag );
  5380. }
  5381. };
  5382. enum class Optionality { Optional, Required };
  5383. struct Parser;
  5384. class ParserBase {
  5385. public:
  5386. virtual ~ParserBase() = default;
  5387. virtual auto validate() const -> Result { return Result::ok(); }
  5388. virtual auto parse( std::string const& exeName, TokenStream const &tokens) const -> InternalParseResult = 0;
  5389. virtual auto cardinality() const -> size_t { return 1; }
  5390. auto parse( Args const &args ) const -> InternalParseResult {
  5391. return parse( args.exeName(), TokenStream( args ) );
  5392. }
  5393. };
  5394. template<typename DerivedT>
  5395. class ComposableParserImpl : public ParserBase {
  5396. public:
  5397. template<typename T>
  5398. auto operator|( T const &other ) const -> Parser;
  5399. template<typename T>
  5400. auto operator+( T const &other ) const -> Parser;
  5401. };
  5402. // Common code and state for Args and Opts
  5403. template<typename DerivedT>
  5404. class ParserRefImpl : public ComposableParserImpl<DerivedT> {
  5405. protected:
  5406. Optionality m_optionality = Optionality::Optional;
  5407. std::shared_ptr<BoundRef> m_ref;
  5408. std::string m_hint;
  5409. std::string m_description;
  5410. explicit ParserRefImpl( std::shared_ptr<BoundRef> const &ref ) : m_ref( ref ) {}
  5411. public:
  5412. template<typename T>
  5413. ParserRefImpl( T &ref, std::string const &hint )
  5414. : m_ref( std::make_shared<BoundValueRef<T>>( ref ) ),
  5415. m_hint( hint )
  5416. {}
  5417. template<typename LambdaT>
  5418. ParserRefImpl( LambdaT const &ref, std::string const &hint )
  5419. : m_ref( std::make_shared<BoundLambda<LambdaT>>( ref ) ),
  5420. m_hint(hint)
  5421. {}
  5422. auto operator()( std::string const &description ) -> DerivedT & {
  5423. m_description = description;
  5424. return static_cast<DerivedT &>( *this );
  5425. }
  5426. auto optional() -> DerivedT & {
  5427. m_optionality = Optionality::Optional;
  5428. return static_cast<DerivedT &>( *this );
  5429. };
  5430. auto required() -> DerivedT & {
  5431. m_optionality = Optionality::Required;
  5432. return static_cast<DerivedT &>( *this );
  5433. };
  5434. auto isOptional() const -> bool {
  5435. return m_optionality == Optionality::Optional;
  5436. }
  5437. auto cardinality() const -> size_t override {
  5438. if( m_ref->isContainer() )
  5439. return 0;
  5440. else
  5441. return 1;
  5442. }
  5443. auto hint() const -> std::string { return m_hint; }
  5444. };
  5445. class ExeName : public ComposableParserImpl<ExeName> {
  5446. std::shared_ptr<std::string> m_name;
  5447. std::shared_ptr<BoundValueRefBase> m_ref;
  5448. template<typename LambdaT>
  5449. static auto makeRef(LambdaT const &lambda) -> std::shared_ptr<BoundValueRefBase> {
  5450. return std::make_shared<BoundLambda<LambdaT>>( lambda) ;
  5451. }
  5452. public:
  5453. ExeName() : m_name( std::make_shared<std::string>( "<executable>" ) ) {}
  5454. explicit ExeName( std::string &ref ) : ExeName() {
  5455. m_ref = std::make_shared<BoundValueRef<std::string>>( ref );
  5456. }
  5457. template<typename LambdaT>
  5458. explicit ExeName( LambdaT const& lambda ) : ExeName() {
  5459. m_ref = std::make_shared<BoundLambda<LambdaT>>( lambda );
  5460. }
  5461. // The exe name is not parsed out of the normal tokens, but is handled specially
  5462. auto parse( std::string const&, TokenStream const &tokens ) const -> InternalParseResult override {
  5463. return InternalParseResult::ok( ParseState( ParseResultType::NoMatch, tokens ) );
  5464. }
  5465. auto name() const -> std::string { return *m_name; }
  5466. auto set( std::string const& newName ) -> ParserResult {
  5467. auto lastSlash = newName.find_last_of( "\\/" );
  5468. auto filename = ( lastSlash == std::string::npos )
  5469. ? newName
  5470. : newName.substr( lastSlash+1 );
  5471. *m_name = filename;
  5472. if( m_ref )
  5473. return m_ref->setValue( filename );
  5474. else
  5475. return ParserResult::ok( ParseResultType::Matched );
  5476. }
  5477. };
  5478. class Arg : public ParserRefImpl<Arg> {
  5479. public:
  5480. using ParserRefImpl::ParserRefImpl;
  5481. auto parse( std::string const &, TokenStream const &tokens ) const -> InternalParseResult override {
  5482. auto validationResult = validate();
  5483. if( !validationResult )
  5484. return InternalParseResult( validationResult );
  5485. auto remainingTokens = tokens;
  5486. auto const &token = *remainingTokens;
  5487. if( token.type != TokenType::Argument )
  5488. return InternalParseResult::ok( ParseState( ParseResultType::NoMatch, remainingTokens ) );
  5489. assert( !m_ref->isFlag() );
  5490. auto valueRef = static_cast<detail::BoundValueRefBase*>( m_ref.get() );
  5491. auto result = valueRef->setValue( remainingTokens->token );
  5492. if( !result )
  5493. return InternalParseResult( result );
  5494. else
  5495. return InternalParseResult::ok( ParseState( ParseResultType::Matched, ++remainingTokens ) );
  5496. }
  5497. };
  5498. inline auto normaliseOpt( std::string const &optName ) -> std::string {
  5499. #ifdef CATCH_PLATFORM_WINDOWS
  5500. if( optName[0] == '/' )
  5501. return "-" + optName.substr( 1 );
  5502. else
  5503. #endif
  5504. return optName;
  5505. }
  5506. class Opt : public ParserRefImpl<Opt> {
  5507. protected:
  5508. std::vector<std::string> m_optNames;
  5509. public:
  5510. template<typename LambdaT>
  5511. explicit Opt( LambdaT const &ref ) : ParserRefImpl( std::make_shared<BoundFlagLambda<LambdaT>>( ref ) ) {}
  5512. explicit Opt( bool &ref ) : ParserRefImpl( std::make_shared<BoundFlagRef>( ref ) ) {}
  5513. template<typename LambdaT>
  5514. Opt( LambdaT const &ref, std::string const &hint ) : ParserRefImpl( ref, hint ) {}
  5515. template<typename T>
  5516. Opt( T &ref, std::string const &hint ) : ParserRefImpl( ref, hint ) {}
  5517. auto operator[]( std::string const &optName ) -> Opt & {
  5518. m_optNames.push_back( optName );
  5519. return *this;
  5520. }
  5521. auto getHelpColumns() const -> std::vector<HelpColumns> {
  5522. std::ostringstream oss;
  5523. bool first = true;
  5524. for( auto const &opt : m_optNames ) {
  5525. if (first)
  5526. first = false;
  5527. else
  5528. oss << ", ";
  5529. oss << opt;
  5530. }
  5531. if( !m_hint.empty() )
  5532. oss << " <" << m_hint << ">";
  5533. return { { oss.str(), m_description } };
  5534. }
  5535. auto isMatch( std::string const &optToken ) const -> bool {
  5536. auto normalisedToken = normaliseOpt( optToken );
  5537. for( auto const &name : m_optNames ) {
  5538. if( normaliseOpt( name ) == normalisedToken )
  5539. return true;
  5540. }
  5541. return false;
  5542. }
  5543. using ParserBase::parse;
  5544. auto parse( std::string const&, TokenStream const &tokens ) const -> InternalParseResult override {
  5545. auto validationResult = validate();
  5546. if( !validationResult )
  5547. return InternalParseResult( validationResult );
  5548. auto remainingTokens = tokens;
  5549. if( remainingTokens && remainingTokens->type == TokenType::Option ) {
  5550. auto const &token = *remainingTokens;
  5551. if( isMatch(token.token ) ) {
  5552. if( m_ref->isFlag() ) {
  5553. auto flagRef = static_cast<detail::BoundFlagRefBase*>( m_ref.get() );
  5554. auto result = flagRef->setFlag( true );
  5555. if( !result )
  5556. return InternalParseResult( result );
  5557. if( result.value() == ParseResultType::ShortCircuitAll )
  5558. return InternalParseResult::ok( ParseState( result.value(), remainingTokens ) );
  5559. } else {
  5560. auto valueRef = static_cast<detail::BoundValueRefBase*>( m_ref.get() );
  5561. ++remainingTokens;
  5562. if( !remainingTokens )
  5563. return InternalParseResult::runtimeError( "Expected argument following " + token.token );
  5564. auto const &argToken = *remainingTokens;
  5565. if( argToken.type != TokenType::Argument )
  5566. return InternalParseResult::runtimeError( "Expected argument following " + token.token );
  5567. auto result = valueRef->setValue( argToken.token );
  5568. if( !result )
  5569. return InternalParseResult( result );
  5570. if( result.value() == ParseResultType::ShortCircuitAll )
  5571. return InternalParseResult::ok( ParseState( result.value(), remainingTokens ) );
  5572. }
  5573. return InternalParseResult::ok( ParseState( ParseResultType::Matched, ++remainingTokens ) );
  5574. }
  5575. }
  5576. return InternalParseResult::ok( ParseState( ParseResultType::NoMatch, remainingTokens ) );
  5577. }
  5578. auto validate() const -> Result override {
  5579. if( m_optNames.empty() )
  5580. return Result::logicError( "No options supplied to Opt" );
  5581. for( auto const &name : m_optNames ) {
  5582. if( name.empty() )
  5583. return Result::logicError( "Option name cannot be empty" );
  5584. #ifdef CATCH_PLATFORM_WINDOWS
  5585. if( name[0] != '-' && name[0] != '/' )
  5586. return Result::logicError( "Option name must begin with '-' or '/'" );
  5587. #else
  5588. if( name[0] != '-' )
  5589. return Result::logicError( "Option name must begin with '-'" );
  5590. #endif
  5591. }
  5592. return ParserRefImpl::validate();
  5593. }
  5594. };
  5595. struct Help : Opt {
  5596. Help( bool &showHelpFlag )
  5597. : Opt([&]( bool flag ) {
  5598. showHelpFlag = flag;
  5599. return ParserResult::ok( ParseResultType::ShortCircuitAll );
  5600. })
  5601. {
  5602. static_cast<Opt &>( *this )
  5603. ("display usage information")
  5604. ["-?"]["-h"]["--help"]
  5605. .optional();
  5606. }
  5607. };
  5608. struct Parser : ParserBase {
  5609. mutable ExeName m_exeName;
  5610. std::vector<Opt> m_options;
  5611. std::vector<Arg> m_args;
  5612. auto operator|=( ExeName const &exeName ) -> Parser & {
  5613. m_exeName = exeName;
  5614. return *this;
  5615. }
  5616. auto operator|=( Arg const &arg ) -> Parser & {
  5617. m_args.push_back(arg);
  5618. return *this;
  5619. }
  5620. auto operator|=( Opt const &opt ) -> Parser & {
  5621. m_options.push_back(opt);
  5622. return *this;
  5623. }
  5624. auto operator|=( Parser const &other ) -> Parser & {
  5625. m_options.insert(m_options.end(), other.m_options.begin(), other.m_options.end());
  5626. m_args.insert(m_args.end(), other.m_args.begin(), other.m_args.end());
  5627. return *this;
  5628. }
  5629. template<typename T>
  5630. auto operator|( T const &other ) const -> Parser {
  5631. return Parser( *this ) |= other;
  5632. }
  5633. // Forward deprecated interface with '+' instead of '|'
  5634. template<typename T>
  5635. auto operator+=( T const &other ) -> Parser & { return operator|=( other ); }
  5636. template<typename T>
  5637. auto operator+( T const &other ) const -> Parser { return operator|( other ); }
  5638. auto getHelpColumns() const -> std::vector<HelpColumns> {
  5639. std::vector<HelpColumns> cols;
  5640. for (auto const &o : m_options) {
  5641. auto childCols = o.getHelpColumns();
  5642. cols.insert( cols.end(), childCols.begin(), childCols.end() );
  5643. }
  5644. return cols;
  5645. }
  5646. void writeToStream( std::ostream &os ) const {
  5647. if (!m_exeName.name().empty()) {
  5648. os << "usage:\n" << " " << m_exeName.name() << " ";
  5649. bool required = true, first = true;
  5650. for( auto const &arg : m_args ) {
  5651. if (first)
  5652. first = false;
  5653. else
  5654. os << " ";
  5655. if( arg.isOptional() && required ) {
  5656. os << "[";
  5657. required = false;
  5658. }
  5659. os << "<" << arg.hint() << ">";
  5660. if( arg.cardinality() == 0 )
  5661. os << " ... ";
  5662. }
  5663. if( !required )
  5664. os << "]";
  5665. if( !m_options.empty() )
  5666. os << " options";
  5667. os << "\n\nwhere options are:" << std::endl;
  5668. }
  5669. auto rows = getHelpColumns();
  5670. size_t consoleWidth = CATCH_CLARA_CONFIG_CONSOLE_WIDTH;
  5671. size_t optWidth = 0;
  5672. for( auto const &cols : rows )
  5673. optWidth = (std::max)(optWidth, cols.left.size() + 2);
  5674. optWidth = (std::min)(optWidth, consoleWidth/2);
  5675. for( auto const &cols : rows ) {
  5676. auto row =
  5677. TextFlow::Column( cols.left ).width( optWidth ).indent( 2 ) +
  5678. TextFlow::Spacer(4) +
  5679. TextFlow::Column( cols.right ).width( consoleWidth - 7 - optWidth );
  5680. os << row << std::endl;
  5681. }
  5682. }
  5683. friend auto operator<<( std::ostream &os, Parser const &parser ) -> std::ostream& {
  5684. parser.writeToStream( os );
  5685. return os;
  5686. }
  5687. auto validate() const -> Result override {
  5688. for( auto const &opt : m_options ) {
  5689. auto result = opt.validate();
  5690. if( !result )
  5691. return result;
  5692. }
  5693. for( auto const &arg : m_args ) {
  5694. auto result = arg.validate();
  5695. if( !result )
  5696. return result;
  5697. }
  5698. return Result::ok();
  5699. }
  5700. using ParserBase::parse;
  5701. auto parse( std::string const& exeName, TokenStream const &tokens ) const -> InternalParseResult override {
  5702. struct ParserInfo {
  5703. ParserBase const* parser = nullptr;
  5704. size_t count = 0;
  5705. };
  5706. const size_t totalParsers = m_options.size() + m_args.size();
  5707. assert( totalParsers < 512 );
  5708. // ParserInfo parseInfos[totalParsers]; // <-- this is what we really want to do
  5709. ParserInfo parseInfos[512];
  5710. {
  5711. size_t i = 0;
  5712. for (auto const &opt : m_options) parseInfos[i++].parser = &opt;
  5713. for (auto const &arg : m_args) parseInfos[i++].parser = &arg;
  5714. }
  5715. m_exeName.set( exeName );
  5716. auto result = InternalParseResult::ok( ParseState( ParseResultType::NoMatch, tokens ) );
  5717. while( result.value().remainingTokens() ) {
  5718. bool tokenParsed = false;
  5719. for( size_t i = 0; i < totalParsers; ++i ) {
  5720. auto& parseInfo = parseInfos[i];
  5721. if( parseInfo.parser->cardinality() == 0 || parseInfo.count < parseInfo.parser->cardinality() ) {
  5722. result = parseInfo.parser->parse(exeName, result.value().remainingTokens());
  5723. if (!result)
  5724. return result;
  5725. if (result.value().type() != ParseResultType::NoMatch) {
  5726. tokenParsed = true;
  5727. ++parseInfo.count;
  5728. break;
  5729. }
  5730. }
  5731. }
  5732. if( result.value().type() == ParseResultType::ShortCircuitAll )
  5733. return result;
  5734. if( !tokenParsed )
  5735. return InternalParseResult::runtimeError( "Unrecognised token: " + result.value().remainingTokens()->token );
  5736. }
  5737. // !TBD Check missing required options
  5738. return result;
  5739. }
  5740. };
  5741. template<typename DerivedT>
  5742. template<typename T>
  5743. auto ComposableParserImpl<DerivedT>::operator|( T const &other ) const -> Parser {
  5744. return Parser() | static_cast<DerivedT const &>( *this ) | other;
  5745. }
  5746. } // namespace detail
  5747. // A Combined parser
  5748. using detail::Parser;
  5749. // A parser for options
  5750. using detail::Opt;
  5751. // A parser for arguments
  5752. using detail::Arg;
  5753. // Wrapper for argc, argv from main()
  5754. using detail::Args;
  5755. // Specifies the name of the executable
  5756. using detail::ExeName;
  5757. // Convenience wrapper for option parser that specifies the help option
  5758. using detail::Help;
  5759. // enum of result types from a parse
  5760. using detail::ParseResultType;
  5761. // Result type for parser operation
  5762. using detail::ParserResult;
  5763. }} // namespace Catch::clara
  5764. // end clara.hpp
  5765. #ifdef __clang__
  5766. #pragma clang diagnostic pop
  5767. #endif
  5768. // Restore Clara's value for console width, if present
  5769. #ifdef CATCH_TEMP_CLARA_CONFIG_CONSOLE_WIDTH
  5770. #define CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH CATCH_TEMP_CLARA_CONFIG_CONSOLE_WIDTH
  5771. #undef CATCH_TEMP_CLARA_CONFIG_CONSOLE_WIDTH
  5772. #endif
  5773. // end catch_clara.h
  5774. namespace Catch {
  5775. clara::Parser makeCommandLineParser( ConfigData& config );
  5776. } // end namespace Catch
  5777. // end catch_commandline.h
  5778. #include <fstream>
  5779. #include <ctime>
  5780. namespace Catch {
  5781. clara::Parser makeCommandLineParser( ConfigData& config ) {
  5782. using namespace clara;
  5783. auto const setWarning = [&]( std::string const& warning ) {
  5784. auto warningSet = [&]() {
  5785. if( warning == "NoAssertions" )
  5786. return WarnAbout::NoAssertions;
  5787. if ( warning == "NoTests" )
  5788. return WarnAbout::NoTests;
  5789. return WarnAbout::Nothing;
  5790. }();
  5791. if (warningSet == WarnAbout::Nothing)
  5792. return ParserResult::runtimeError( "Unrecognised warning: '" + warning + "'" );
  5793. config.warnings = static_cast<WarnAbout::What>( config.warnings | warningSet );
  5794. return ParserResult::ok( ParseResultType::Matched );
  5795. };
  5796. auto const loadTestNamesFromFile = [&]( std::string const& filename ) {
  5797. std::ifstream f( filename.c_str() );
  5798. if( !f.is_open() )
  5799. return ParserResult::runtimeError( "Unable to load input file: '" + filename + "'" );
  5800. std::string line;
  5801. while( std::getline( f, line ) ) {
  5802. line = trim(line);
  5803. if( !line.empty() && !startsWith( line, '#' ) ) {
  5804. if( !startsWith( line, '"' ) )
  5805. line = '"' + line + '"';
  5806. config.testsOrTags.push_back( line + ',' );
  5807. }
  5808. }
  5809. return ParserResult::ok( ParseResultType::Matched );
  5810. };
  5811. auto const setTestOrder = [&]( std::string const& order ) {
  5812. if( startsWith( "declared", order ) )
  5813. config.runOrder = RunTests::InDeclarationOrder;
  5814. else if( startsWith( "lexical", order ) )
  5815. config.runOrder = RunTests::InLexicographicalOrder;
  5816. else if( startsWith( "random", order ) )
  5817. config.runOrder = RunTests::InRandomOrder;
  5818. else
  5819. return clara::ParserResult::runtimeError( "Unrecognised ordering: '" + order + "'" );
  5820. return ParserResult::ok( ParseResultType::Matched );
  5821. };
  5822. auto const setRngSeed = [&]( std::string const& seed ) {
  5823. if( seed != "time" )
  5824. return clara::detail::convertInto( seed, config.rngSeed );
  5825. config.rngSeed = static_cast<unsigned int>( std::time(nullptr) );
  5826. return ParserResult::ok( ParseResultType::Matched );
  5827. };
  5828. auto const setColourUsage = [&]( std::string const& useColour ) {
  5829. auto mode = toLower( useColour );
  5830. if( mode == "yes" )
  5831. config.useColour = UseColour::Yes;
  5832. else if( mode == "no" )
  5833. config.useColour = UseColour::No;
  5834. else if( mode == "auto" )
  5835. config.useColour = UseColour::Auto;
  5836. else
  5837. return ParserResult::runtimeError( "colour mode must be one of: auto, yes or no. '" + useColour + "' not recognised" );
  5838. return ParserResult::ok( ParseResultType::Matched );
  5839. };
  5840. auto const setWaitForKeypress = [&]( std::string const& keypress ) {
  5841. auto keypressLc = toLower( keypress );
  5842. if( keypressLc == "start" )
  5843. config.waitForKeypress = WaitForKeypress::BeforeStart;
  5844. else if( keypressLc == "exit" )
  5845. config.waitForKeypress = WaitForKeypress::BeforeExit;
  5846. else if( keypressLc == "both" )
  5847. config.waitForKeypress = WaitForKeypress::BeforeStartAndExit;
  5848. else
  5849. return ParserResult::runtimeError( "keypress argument must be one of: start, exit or both. '" + keypress + "' not recognised" );
  5850. return ParserResult::ok( ParseResultType::Matched );
  5851. };
  5852. auto const setVerbosity = [&]( std::string const& verbosity ) {
  5853. auto lcVerbosity = toLower( verbosity );
  5854. if( lcVerbosity == "quiet" )
  5855. config.verbosity = Verbosity::Quiet;
  5856. else if( lcVerbosity == "normal" )
  5857. config.verbosity = Verbosity::Normal;
  5858. else if( lcVerbosity == "high" )
  5859. config.verbosity = Verbosity::High;
  5860. else
  5861. return ParserResult::runtimeError( "Unrecognised verbosity, '" + verbosity + "'" );
  5862. return ParserResult::ok( ParseResultType::Matched );
  5863. };
  5864. auto const setReporter = [&]( std::string const& reporter ) {
  5865. IReporterRegistry::FactoryMap const& factories = getRegistryHub().getReporterRegistry().getFactories();
  5866. auto lcReporter = toLower( reporter );
  5867. auto result = factories.find( lcReporter );
  5868. if( factories.end() != result )
  5869. config.reporterName = lcReporter;
  5870. else
  5871. return ParserResult::runtimeError( "Unrecognized reporter, '" + reporter + "'. Check available with --list-reporters" );
  5872. return ParserResult::ok( ParseResultType::Matched );
  5873. };
  5874. auto cli
  5875. = ExeName( config.processName )
  5876. | Help( config.showHelp )
  5877. | Opt( config.listTests )
  5878. ["-l"]["--list-tests"]
  5879. ( "list all/matching test cases" )
  5880. | Opt( config.listTags )
  5881. ["-t"]["--list-tags"]
  5882. ( "list all/matching tags" )
  5883. | Opt( config.showSuccessfulTests )
  5884. ["-s"]["--success"]
  5885. ( "include successful tests in output" )
  5886. | Opt( config.shouldDebugBreak )
  5887. ["-b"]["--break"]
  5888. ( "break into debugger on failure" )
  5889. | Opt( config.noThrow )
  5890. ["-e"]["--nothrow"]
  5891. ( "skip exception tests" )
  5892. | Opt( config.showInvisibles )
  5893. ["-i"]["--invisibles"]
  5894. ( "show invisibles (tabs, newlines)" )
  5895. | Opt( config.outputFilename, "filename" )
  5896. ["-o"]["--out"]
  5897. ( "output filename" )
  5898. | Opt( setReporter, "name" )
  5899. ["-r"]["--reporter"]
  5900. ( "reporter to use (defaults to console)" )
  5901. | Opt( config.name, "name" )
  5902. ["-n"]["--name"]
  5903. ( "suite name" )
  5904. | Opt( [&]( bool ){ config.abortAfter = 1; } )
  5905. ["-a"]["--abort"]
  5906. ( "abort at first failure" )
  5907. | Opt( [&]( int x ){ config.abortAfter = x; }, "no. failures" )
  5908. ["-x"]["--abortx"]
  5909. ( "abort after x failures" )
  5910. | Opt( setWarning, "warning name" )
  5911. ["-w"]["--warn"]
  5912. ( "enable warnings" )
  5913. | Opt( [&]( bool flag ) { config.showDurations = flag ? ShowDurations::Always : ShowDurations::Never; }, "yes|no" )
  5914. ["-d"]["--durations"]
  5915. ( "show test durations" )
  5916. | Opt( loadTestNamesFromFile, "filename" )
  5917. ["-f"]["--input-file"]
  5918. ( "load test names to run from a file" )
  5919. | Opt( config.filenamesAsTags )
  5920. ["-#"]["--filenames-as-tags"]
  5921. ( "adds a tag for the filename" )
  5922. | Opt( config.sectionsToRun, "section name" )
  5923. ["-c"]["--section"]
  5924. ( "specify section to run" )
  5925. | Opt( setVerbosity, "quiet|normal|high" )
  5926. ["-v"]["--verbosity"]
  5927. ( "set output verbosity" )
  5928. | Opt( config.listTestNamesOnly )
  5929. ["--list-test-names-only"]
  5930. ( "list all/matching test cases names only" )
  5931. | Opt( config.listReporters )
  5932. ["--list-reporters"]
  5933. ( "list all reporters" )
  5934. | Opt( setTestOrder, "decl|lex|rand" )
  5935. ["--order"]
  5936. ( "test case order (defaults to decl)" )
  5937. | Opt( setRngSeed, "'time'|number" )
  5938. ["--rng-seed"]
  5939. ( "set a specific seed for random numbers" )
  5940. | Opt( setColourUsage, "yes|no" )
  5941. ["--use-colour"]
  5942. ( "should output be colourised" )
  5943. | Opt( config.libIdentify )
  5944. ["--libidentify"]
  5945. ( "report name and version according to libidentify standard" )
  5946. | Opt( setWaitForKeypress, "start|exit|both" )
  5947. ["--wait-for-keypress"]
  5948. ( "waits for a keypress before exiting" )
  5949. | Opt( config.benchmarkResolutionMultiple, "multiplier" )
  5950. ["--benchmark-resolution-multiple"]
  5951. ( "multiple of clock resolution to run benchmarks" )
  5952. | Arg( config.testsOrTags, "test name|pattern|tags" )
  5953. ( "which test or tests to use" );
  5954. return cli;
  5955. }
  5956. } // end namespace Catch
  5957. // end catch_commandline.cpp
  5958. // start catch_common.cpp
  5959. #include <cstring>
  5960. #include <ostream>
  5961. namespace Catch {
  5962. bool SourceLineInfo::empty() const noexcept {
  5963. return file[0] == '\0';
  5964. }
  5965. bool SourceLineInfo::operator == ( SourceLineInfo const& other ) const noexcept {
  5966. return line == other.line && (file == other.file || std::strcmp(file, other.file) == 0);
  5967. }
  5968. bool SourceLineInfo::operator < ( SourceLineInfo const& other ) const noexcept {
  5969. // We can assume that the same file will usually have the same pointer.
  5970. // Thus, if the pointers are the same, there is no point in calling the strcmp
  5971. return line < other.line || ( line == other.line && file != other.file && (std::strcmp(file, other.file) < 0));
  5972. }
  5973. std::ostream& operator << ( std::ostream& os, SourceLineInfo const& info ) {
  5974. #ifndef __GNUG__
  5975. os << info.file << '(' << info.line << ')';
  5976. #else
  5977. os << info.file << ':' << info.line;
  5978. #endif
  5979. return os;
  5980. }
  5981. std::string StreamEndStop::operator+() const {
  5982. return std::string();
  5983. }
  5984. NonCopyable::NonCopyable() = default;
  5985. NonCopyable::~NonCopyable() = default;
  5986. }
  5987. // end catch_common.cpp
  5988. // start catch_config.cpp
  5989. namespace Catch {
  5990. Config::Config( ConfigData const& data )
  5991. : m_data( data ),
  5992. m_stream( openStream() )
  5993. {
  5994. TestSpecParser parser(ITagAliasRegistry::get());
  5995. if (data.testsOrTags.empty()) {
  5996. parser.parse("~[.]"); // All not hidden tests
  5997. }
  5998. else {
  5999. m_hasTestFilters = true;
  6000. for( auto const& testOrTags : data.testsOrTags )
  6001. parser.parse( testOrTags );
  6002. }
  6003. m_testSpec = parser.testSpec();
  6004. }
  6005. std::string const& Config::getFilename() const {
  6006. return m_data.outputFilename ;
  6007. }
  6008. bool Config::listTests() const { return m_data.listTests; }
  6009. bool Config::listTestNamesOnly() const { return m_data.listTestNamesOnly; }
  6010. bool Config::listTags() const { return m_data.listTags; }
  6011. bool Config::listReporters() const { return m_data.listReporters; }
  6012. std::string Config::getProcessName() const { return m_data.processName; }
  6013. std::string const& Config::getReporterName() const { return m_data.reporterName; }
  6014. std::vector<std::string> const& Config::getTestsOrTags() const { return m_data.testsOrTags; }
  6015. std::vector<std::string> const& Config::getSectionsToRun() const { return m_data.sectionsToRun; }
  6016. TestSpec const& Config::testSpec() const { return m_testSpec; }
  6017. bool Config::hasTestFilters() const { return m_hasTestFilters; }
  6018. bool Config::showHelp() const { return m_data.showHelp; }
  6019. // IConfig interface
  6020. bool Config::allowThrows() const { return !m_data.noThrow; }
  6021. std::ostream& Config::stream() const { return m_stream->stream(); }
  6022. std::string Config::name() const { return m_data.name.empty() ? m_data.processName : m_data.name; }
  6023. bool Config::includeSuccessfulResults() const { return m_data.showSuccessfulTests; }
  6024. bool Config::warnAboutMissingAssertions() const { return !!(m_data.warnings & WarnAbout::NoAssertions); }
  6025. bool Config::warnAboutNoTests() const { return !!(m_data.warnings & WarnAbout::NoTests); }
  6026. ShowDurations::OrNot Config::showDurations() const { return m_data.showDurations; }
  6027. RunTests::InWhatOrder Config::runOrder() const { return m_data.runOrder; }
  6028. unsigned int Config::rngSeed() const { return m_data.rngSeed; }
  6029. int Config::benchmarkResolutionMultiple() const { return m_data.benchmarkResolutionMultiple; }
  6030. UseColour::YesOrNo Config::useColour() const { return m_data.useColour; }
  6031. bool Config::shouldDebugBreak() const { return m_data.shouldDebugBreak; }
  6032. int Config::abortAfter() const { return m_data.abortAfter; }
  6033. bool Config::showInvisibles() const { return m_data.showInvisibles; }
  6034. Verbosity Config::verbosity() const { return m_data.verbosity; }
  6035. IStream const* Config::openStream() {
  6036. return Catch::makeStream(m_data.outputFilename);
  6037. }
  6038. } // end namespace Catch
  6039. // end catch_config.cpp
  6040. // start catch_console_colour.cpp
  6041. #if defined(__clang__)
  6042. # pragma clang diagnostic push
  6043. # pragma clang diagnostic ignored "-Wexit-time-destructors"
  6044. #endif
  6045. // start catch_errno_guard.h
  6046. namespace Catch {
  6047. class ErrnoGuard {
  6048. public:
  6049. ErrnoGuard();
  6050. ~ErrnoGuard();
  6051. private:
  6052. int m_oldErrno;
  6053. };
  6054. }
  6055. // end catch_errno_guard.h
  6056. #include <sstream>
  6057. namespace Catch {
  6058. namespace {
  6059. struct IColourImpl {
  6060. virtual ~IColourImpl() = default;
  6061. virtual void use( Colour::Code _colourCode ) = 0;
  6062. };
  6063. struct NoColourImpl : IColourImpl {
  6064. void use( Colour::Code ) {}
  6065. static IColourImpl* instance() {
  6066. static NoColourImpl s_instance;
  6067. return &s_instance;
  6068. }
  6069. };
  6070. } // anon namespace
  6071. } // namespace Catch
  6072. #if !defined( CATCH_CONFIG_COLOUR_NONE ) && !defined( CATCH_CONFIG_COLOUR_WINDOWS ) && !defined( CATCH_CONFIG_COLOUR_ANSI )
  6073. # ifdef CATCH_PLATFORM_WINDOWS
  6074. # define CATCH_CONFIG_COLOUR_WINDOWS
  6075. # else
  6076. # define CATCH_CONFIG_COLOUR_ANSI
  6077. # endif
  6078. #endif
  6079. #if defined ( CATCH_CONFIG_COLOUR_WINDOWS ) /////////////////////////////////////////
  6080. namespace Catch {
  6081. namespace {
  6082. class Win32ColourImpl : public IColourImpl {
  6083. public:
  6084. Win32ColourImpl() : stdoutHandle( GetStdHandle(STD_OUTPUT_HANDLE) )
  6085. {
  6086. CONSOLE_SCREEN_BUFFER_INFO csbiInfo;
  6087. GetConsoleScreenBufferInfo( stdoutHandle, &csbiInfo );
  6088. originalForegroundAttributes = csbiInfo.wAttributes & ~( BACKGROUND_GREEN | BACKGROUND_RED | BACKGROUND_BLUE | BACKGROUND_INTENSITY );
  6089. originalBackgroundAttributes = csbiInfo.wAttributes & ~( FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_BLUE | FOREGROUND_INTENSITY );
  6090. }
  6091. virtual void use( Colour::Code _colourCode ) override {
  6092. switch( _colourCode ) {
  6093. case Colour::None: return setTextAttribute( originalForegroundAttributes );
  6094. case Colour::White: return setTextAttribute( FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_BLUE );
  6095. case Colour::Red: return setTextAttribute( FOREGROUND_RED );
  6096. case Colour::Green: return setTextAttribute( FOREGROUND_GREEN );
  6097. case Colour::Blue: return setTextAttribute( FOREGROUND_BLUE );
  6098. case Colour::Cyan: return setTextAttribute( FOREGROUND_BLUE | FOREGROUND_GREEN );
  6099. case Colour::Yellow: return setTextAttribute( FOREGROUND_RED | FOREGROUND_GREEN );
  6100. case Colour::Grey: return setTextAttribute( 0 );
  6101. case Colour::LightGrey: return setTextAttribute( FOREGROUND_INTENSITY );
  6102. case Colour::BrightRed: return setTextAttribute( FOREGROUND_INTENSITY | FOREGROUND_RED );
  6103. case Colour::BrightGreen: return setTextAttribute( FOREGROUND_INTENSITY | FOREGROUND_GREEN );
  6104. case Colour::BrightWhite: return setTextAttribute( FOREGROUND_INTENSITY | FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_BLUE );
  6105. case Colour::BrightYellow: return setTextAttribute( FOREGROUND_INTENSITY | FOREGROUND_RED | FOREGROUND_GREEN );
  6106. case Colour::Bright: CATCH_INTERNAL_ERROR( "not a colour" );
  6107. default:
  6108. CATCH_ERROR( "Unknown colour requested" );
  6109. }
  6110. }
  6111. private:
  6112. void setTextAttribute( WORD _textAttribute ) {
  6113. SetConsoleTextAttribute( stdoutHandle, _textAttribute | originalBackgroundAttributes );
  6114. }
  6115. HANDLE stdoutHandle;
  6116. WORD originalForegroundAttributes;
  6117. WORD originalBackgroundAttributes;
  6118. };
  6119. IColourImpl* platformColourInstance() {
  6120. static Win32ColourImpl s_instance;
  6121. IConfigPtr config = getCurrentContext().getConfig();
  6122. UseColour::YesOrNo colourMode = config
  6123. ? config->useColour()
  6124. : UseColour::Auto;
  6125. if( colourMode == UseColour::Auto )
  6126. colourMode = UseColour::Yes;
  6127. return colourMode == UseColour::Yes
  6128. ? &s_instance
  6129. : NoColourImpl::instance();
  6130. }
  6131. } // end anon namespace
  6132. } // end namespace Catch
  6133. #elif defined( CATCH_CONFIG_COLOUR_ANSI ) //////////////////////////////////////
  6134. #include <unistd.h>
  6135. namespace Catch {
  6136. namespace {
  6137. // use POSIX/ ANSI console terminal codes
  6138. // Thanks to Adam Strzelecki for original contribution
  6139. // (http://github.com/nanoant)
  6140. // https://github.com/philsquared/Catch/pull/131
  6141. class PosixColourImpl : public IColourImpl {
  6142. public:
  6143. virtual void use( Colour::Code _colourCode ) override {
  6144. switch( _colourCode ) {
  6145. case Colour::None:
  6146. case Colour::White: return setColour( "[0m" );
  6147. case Colour::Red: return setColour( "[0;31m" );
  6148. case Colour::Green: return setColour( "[0;32m" );
  6149. case Colour::Blue: return setColour( "[0;34m" );
  6150. case Colour::Cyan: return setColour( "[0;36m" );
  6151. case Colour::Yellow: return setColour( "[0;33m" );
  6152. case Colour::Grey: return setColour( "[1;30m" );
  6153. case Colour::LightGrey: return setColour( "[0;37m" );
  6154. case Colour::BrightRed: return setColour( "[1;31m" );
  6155. case Colour::BrightGreen: return setColour( "[1;32m" );
  6156. case Colour::BrightWhite: return setColour( "[1;37m" );
  6157. case Colour::BrightYellow: return setColour( "[1;33m" );
  6158. case Colour::Bright: CATCH_INTERNAL_ERROR( "not a colour" );
  6159. default: CATCH_INTERNAL_ERROR( "Unknown colour requested" );
  6160. }
  6161. }
  6162. static IColourImpl* instance() {
  6163. static PosixColourImpl s_instance;
  6164. return &s_instance;
  6165. }
  6166. private:
  6167. void setColour( const char* _escapeCode ) {
  6168. Catch::cout() << '\033' << _escapeCode;
  6169. }
  6170. };
  6171. bool useColourOnPlatform() {
  6172. return
  6173. #ifdef CATCH_PLATFORM_MAC
  6174. !isDebuggerActive() &&
  6175. #endif
  6176. #if !(defined(__DJGPP__) && defined(__STRICT_ANSI__))
  6177. isatty(STDOUT_FILENO)
  6178. #else
  6179. false
  6180. #endif
  6181. ;
  6182. }
  6183. IColourImpl* platformColourInstance() {
  6184. ErrnoGuard guard;
  6185. IConfigPtr config = getCurrentContext().getConfig();
  6186. UseColour::YesOrNo colourMode = config
  6187. ? config->useColour()
  6188. : UseColour::Auto;
  6189. if( colourMode == UseColour::Auto )
  6190. colourMode = useColourOnPlatform()
  6191. ? UseColour::Yes
  6192. : UseColour::No;
  6193. return colourMode == UseColour::Yes
  6194. ? PosixColourImpl::instance()
  6195. : NoColourImpl::instance();
  6196. }
  6197. } // end anon namespace
  6198. } // end namespace Catch
  6199. #else // not Windows or ANSI ///////////////////////////////////////////////
  6200. namespace Catch {
  6201. static IColourImpl* platformColourInstance() { return NoColourImpl::instance(); }
  6202. } // end namespace Catch
  6203. #endif // Windows/ ANSI/ None
  6204. namespace Catch {
  6205. Colour::Colour( Code _colourCode ) { use( _colourCode ); }
  6206. Colour::Colour( Colour&& rhs ) noexcept {
  6207. m_moved = rhs.m_moved;
  6208. rhs.m_moved = true;
  6209. }
  6210. Colour& Colour::operator=( Colour&& rhs ) noexcept {
  6211. m_moved = rhs.m_moved;
  6212. rhs.m_moved = true;
  6213. return *this;
  6214. }
  6215. Colour::~Colour(){ if( !m_moved ) use( None ); }
  6216. void Colour::use( Code _colourCode ) {
  6217. static IColourImpl* impl = platformColourInstance();
  6218. impl->use( _colourCode );
  6219. }
  6220. std::ostream& operator << ( std::ostream& os, Colour const& ) {
  6221. return os;
  6222. }
  6223. } // end namespace Catch
  6224. #if defined(__clang__)
  6225. # pragma clang diagnostic pop
  6226. #endif
  6227. // end catch_console_colour.cpp
  6228. // start catch_context.cpp
  6229. namespace Catch {
  6230. class Context : public IMutableContext, NonCopyable {
  6231. public: // IContext
  6232. virtual IResultCapture* getResultCapture() override {
  6233. return m_resultCapture;
  6234. }
  6235. virtual IRunner* getRunner() override {
  6236. return m_runner;
  6237. }
  6238. virtual IConfigPtr const& getConfig() const override {
  6239. return m_config;
  6240. }
  6241. virtual ~Context() override;
  6242. public: // IMutableContext
  6243. virtual void setResultCapture( IResultCapture* resultCapture ) override {
  6244. m_resultCapture = resultCapture;
  6245. }
  6246. virtual void setRunner( IRunner* runner ) override {
  6247. m_runner = runner;
  6248. }
  6249. virtual void setConfig( IConfigPtr const& config ) override {
  6250. m_config = config;
  6251. }
  6252. friend IMutableContext& getCurrentMutableContext();
  6253. private:
  6254. IConfigPtr m_config;
  6255. IRunner* m_runner = nullptr;
  6256. IResultCapture* m_resultCapture = nullptr;
  6257. };
  6258. IMutableContext *IMutableContext::currentContext = nullptr;
  6259. void IMutableContext::createContext()
  6260. {
  6261. currentContext = new Context();
  6262. }
  6263. void cleanUpContext() {
  6264. delete IMutableContext::currentContext;
  6265. IMutableContext::currentContext = nullptr;
  6266. }
  6267. IContext::~IContext() = default;
  6268. IMutableContext::~IMutableContext() = default;
  6269. Context::~Context() = default;
  6270. }
  6271. // end catch_context.cpp
  6272. // start catch_debug_console.cpp
  6273. // start catch_debug_console.h
  6274. #include <string>
  6275. namespace Catch {
  6276. void writeToDebugConsole( std::string const& text );
  6277. }
  6278. // end catch_debug_console.h
  6279. #ifdef CATCH_PLATFORM_WINDOWS
  6280. namespace Catch {
  6281. void writeToDebugConsole( std::string const& text ) {
  6282. ::OutputDebugStringA( text.c_str() );
  6283. }
  6284. }
  6285. #else
  6286. namespace Catch {
  6287. void writeToDebugConsole( std::string const& text ) {
  6288. // !TBD: Need a version for Mac/ XCode and other IDEs
  6289. Catch::cout() << text;
  6290. }
  6291. }
  6292. #endif // Platform
  6293. // end catch_debug_console.cpp
  6294. // start catch_debugger.cpp
  6295. #ifdef CATCH_PLATFORM_MAC
  6296. # include <assert.h>
  6297. # include <stdbool.h>
  6298. # include <sys/types.h>
  6299. # include <unistd.h>
  6300. # include <sys/sysctl.h>
  6301. # include <cstddef>
  6302. # include <ostream>
  6303. namespace Catch {
  6304. // The following function is taken directly from the following technical note:
  6305. // http://developer.apple.com/library/mac/#qa/qa2004/qa1361.html
  6306. // Returns true if the current process is being debugged (either
  6307. // running under the debugger or has a debugger attached post facto).
  6308. bool isDebuggerActive(){
  6309. int mib[4];
  6310. struct kinfo_proc info;
  6311. std::size_t size;
  6312. // Initialize the flags so that, if sysctl fails for some bizarre
  6313. // reason, we get a predictable result.
  6314. info.kp_proc.p_flag = 0;
  6315. // Initialize mib, which tells sysctl the info we want, in this case
  6316. // we're looking for information about a specific process ID.
  6317. mib[0] = CTL_KERN;
  6318. mib[1] = KERN_PROC;
  6319. mib[2] = KERN_PROC_PID;
  6320. mib[3] = getpid();
  6321. // Call sysctl.
  6322. size = sizeof(info);
  6323. if( sysctl(mib, sizeof(mib) / sizeof(*mib), &info, &size, nullptr, 0) != 0 ) {
  6324. Catch::cerr() << "\n** Call to sysctl failed - unable to determine if debugger is active **\n" << std::endl;
  6325. return false;
  6326. }
  6327. // We're being debugged if the P_TRACED flag is set.
  6328. return ( (info.kp_proc.p_flag & P_TRACED) != 0 );
  6329. }
  6330. } // namespace Catch
  6331. #elif defined(CATCH_PLATFORM_LINUX)
  6332. #include <fstream>
  6333. #include <string>
  6334. namespace Catch{
  6335. // The standard POSIX way of detecting a debugger is to attempt to
  6336. // ptrace() the process, but this needs to be done from a child and not
  6337. // this process itself to still allow attaching to this process later
  6338. // if wanted, so is rather heavy. Under Linux we have the PID of the
  6339. // "debugger" (which doesn't need to be gdb, of course, it could also
  6340. // be strace, for example) in /proc/$PID/status, so just get it from
  6341. // there instead.
  6342. bool isDebuggerActive(){
  6343. // Libstdc++ has a bug, where std::ifstream sets errno to 0
  6344. // This way our users can properly assert over errno values
  6345. ErrnoGuard guard;
  6346. std::ifstream in("/proc/self/status");
  6347. for( std::string line; std::getline(in, line); ) {
  6348. static const int PREFIX_LEN = 11;
  6349. if( line.compare(0, PREFIX_LEN, "TracerPid:\t") == 0 ) {
  6350. // We're traced if the PID is not 0 and no other PID starts
  6351. // with 0 digit, so it's enough to check for just a single
  6352. // character.
  6353. return line.length() > PREFIX_LEN && line[PREFIX_LEN] != '0';
  6354. }
  6355. }
  6356. return false;
  6357. }
  6358. } // namespace Catch
  6359. #elif defined(_MSC_VER)
  6360. extern "C" __declspec(dllimport) int __stdcall IsDebuggerPresent();
  6361. namespace Catch {
  6362. bool isDebuggerActive() {
  6363. return IsDebuggerPresent() != 0;
  6364. }
  6365. }
  6366. #elif defined(__MINGW32__)
  6367. extern "C" __declspec(dllimport) int __stdcall IsDebuggerPresent();
  6368. namespace Catch {
  6369. bool isDebuggerActive() {
  6370. return IsDebuggerPresent() != 0;
  6371. }
  6372. }
  6373. #else
  6374. namespace Catch {
  6375. bool isDebuggerActive() { return false; }
  6376. }
  6377. #endif // Platform
  6378. // end catch_debugger.cpp
  6379. // start catch_decomposer.cpp
  6380. namespace Catch {
  6381. ITransientExpression::~ITransientExpression() = default;
  6382. void formatReconstructedExpression( std::ostream &os, std::string const& lhs, StringRef op, std::string const& rhs ) {
  6383. if( lhs.size() + rhs.size() < 40 &&
  6384. lhs.find('\n') == std::string::npos &&
  6385. rhs.find('\n') == std::string::npos )
  6386. os << lhs << " " << op << " " << rhs;
  6387. else
  6388. os << lhs << "\n" << op << "\n" << rhs;
  6389. }
  6390. }
  6391. // end catch_decomposer.cpp
  6392. // start catch_enforce.cpp
  6393. namespace Catch {
  6394. #if defined(CATCH_CONFIG_DISABLE_EXCEPTIONS) && !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS_CUSTOM_HANDLER)
  6395. [[noreturn]]
  6396. void throw_exception(std::exception const& e) {
  6397. Catch::cerr() << "Catch will terminate because it needed to throw an exception.\n"
  6398. << "The message was: " << e.what() << '\n';
  6399. std::terminate();
  6400. }
  6401. #endif
  6402. } // namespace Catch;
  6403. // end catch_enforce.cpp
  6404. // start catch_errno_guard.cpp
  6405. #include <cerrno>
  6406. namespace Catch {
  6407. ErrnoGuard::ErrnoGuard():m_oldErrno(errno){}
  6408. ErrnoGuard::~ErrnoGuard() { errno = m_oldErrno; }
  6409. }
  6410. // end catch_errno_guard.cpp
  6411. // start catch_exception_translator_registry.cpp
  6412. // start catch_exception_translator_registry.h
  6413. #include <vector>
  6414. #include <string>
  6415. #include <memory>
  6416. namespace Catch {
  6417. class ExceptionTranslatorRegistry : public IExceptionTranslatorRegistry {
  6418. public:
  6419. ~ExceptionTranslatorRegistry();
  6420. virtual void registerTranslator( const IExceptionTranslator* translator );
  6421. virtual std::string translateActiveException() const override;
  6422. std::string tryTranslators() const;
  6423. private:
  6424. std::vector<std::unique_ptr<IExceptionTranslator const>> m_translators;
  6425. };
  6426. }
  6427. // end catch_exception_translator_registry.h
  6428. #ifdef __OBJC__
  6429. #import "Foundation/Foundation.h"
  6430. #endif
  6431. namespace Catch {
  6432. ExceptionTranslatorRegistry::~ExceptionTranslatorRegistry() {
  6433. }
  6434. void ExceptionTranslatorRegistry::registerTranslator( const IExceptionTranslator* translator ) {
  6435. m_translators.push_back( std::unique_ptr<const IExceptionTranslator>( translator ) );
  6436. }
  6437. #if !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
  6438. std::string ExceptionTranslatorRegistry::translateActiveException() const {
  6439. try {
  6440. #ifdef __OBJC__
  6441. // In Objective-C try objective-c exceptions first
  6442. @try {
  6443. return tryTranslators();
  6444. }
  6445. @catch (NSException *exception) {
  6446. return Catch::Detail::stringify( [exception description] );
  6447. }
  6448. #else
  6449. // Compiling a mixed mode project with MSVC means that CLR
  6450. // exceptions will be caught in (...) as well. However, these
  6451. // do not fill-in std::current_exception and thus lead to crash
  6452. // when attempting rethrow.
  6453. // /EHa switch also causes structured exceptions to be caught
  6454. // here, but they fill-in current_exception properly, so
  6455. // at worst the output should be a little weird, instead of
  6456. // causing a crash.
  6457. if (std::current_exception() == nullptr) {
  6458. return "Non C++ exception. Possibly a CLR exception.";
  6459. }
  6460. return tryTranslators();
  6461. #endif
  6462. }
  6463. catch( TestFailureException& ) {
  6464. std::rethrow_exception(std::current_exception());
  6465. }
  6466. catch( std::exception& ex ) {
  6467. return ex.what();
  6468. }
  6469. catch( std::string& msg ) {
  6470. return msg;
  6471. }
  6472. catch( const char* msg ) {
  6473. return msg;
  6474. }
  6475. catch(...) {
  6476. return "Unknown exception";
  6477. }
  6478. }
  6479. #else // ^^ Exceptions are enabled // Exceptions are disabled vv
  6480. std::string ExceptionTranslatorRegistry::translateActiveException() const {
  6481. CATCH_INTERNAL_ERROR("Attempted to translate active exception under CATCH_CONFIG_DISABLE_EXCEPTIONS!");
  6482. }
  6483. #endif
  6484. std::string ExceptionTranslatorRegistry::tryTranslators() const {
  6485. if( m_translators.empty() )
  6486. std::rethrow_exception(std::current_exception());
  6487. else
  6488. return m_translators[0]->translate( m_translators.begin()+1, m_translators.end() );
  6489. }
  6490. }
  6491. // end catch_exception_translator_registry.cpp
  6492. // start catch_fatal_condition.cpp
  6493. #if defined(__GNUC__)
  6494. # pragma GCC diagnostic push
  6495. # pragma GCC diagnostic ignored "-Wmissing-field-initializers"
  6496. #endif
  6497. #if defined( CATCH_CONFIG_WINDOWS_SEH ) || defined( CATCH_CONFIG_POSIX_SIGNALS )
  6498. namespace {
  6499. // Report the error condition
  6500. void reportFatal( char const * const message ) {
  6501. Catch::getCurrentContext().getResultCapture()->handleFatalErrorCondition( message );
  6502. }
  6503. }
  6504. #endif // signals/SEH handling
  6505. #if defined( CATCH_CONFIG_WINDOWS_SEH )
  6506. namespace Catch {
  6507. struct SignalDefs { DWORD id; const char* name; };
  6508. // There is no 1-1 mapping between signals and windows exceptions.
  6509. // Windows can easily distinguish between SO and SigSegV,
  6510. // but SigInt, SigTerm, etc are handled differently.
  6511. static SignalDefs signalDefs[] = {
  6512. { EXCEPTION_ILLEGAL_INSTRUCTION, "SIGILL - Illegal instruction signal" },
  6513. { EXCEPTION_STACK_OVERFLOW, "SIGSEGV - Stack overflow" },
  6514. { EXCEPTION_ACCESS_VIOLATION, "SIGSEGV - Segmentation violation signal" },
  6515. { EXCEPTION_INT_DIVIDE_BY_ZERO, "Divide by zero error" },
  6516. };
  6517. LONG CALLBACK FatalConditionHandler::handleVectoredException(PEXCEPTION_POINTERS ExceptionInfo) {
  6518. for (auto const& def : signalDefs) {
  6519. if (ExceptionInfo->ExceptionRecord->ExceptionCode == def.id) {
  6520. reportFatal(def.name);
  6521. }
  6522. }
  6523. // If its not an exception we care about, pass it along.
  6524. // This stops us from eating debugger breaks etc.
  6525. return EXCEPTION_CONTINUE_SEARCH;
  6526. }
  6527. FatalConditionHandler::FatalConditionHandler() {
  6528. isSet = true;
  6529. // 32k seems enough for Catch to handle stack overflow,
  6530. // but the value was found experimentally, so there is no strong guarantee
  6531. guaranteeSize = 32 * 1024;
  6532. exceptionHandlerHandle = nullptr;
  6533. // Register as first handler in current chain
  6534. exceptionHandlerHandle = AddVectoredExceptionHandler(1, handleVectoredException);
  6535. // Pass in guarantee size to be filled
  6536. SetThreadStackGuarantee(&guaranteeSize);
  6537. }
  6538. void FatalConditionHandler::reset() {
  6539. if (isSet) {
  6540. RemoveVectoredExceptionHandler(exceptionHandlerHandle);
  6541. SetThreadStackGuarantee(&guaranteeSize);
  6542. exceptionHandlerHandle = nullptr;
  6543. isSet = false;
  6544. }
  6545. }
  6546. FatalConditionHandler::~FatalConditionHandler() {
  6547. reset();
  6548. }
  6549. bool FatalConditionHandler::isSet = false;
  6550. ULONG FatalConditionHandler::guaranteeSize = 0;
  6551. PVOID FatalConditionHandler::exceptionHandlerHandle = nullptr;
  6552. } // namespace Catch
  6553. #elif defined( CATCH_CONFIG_POSIX_SIGNALS )
  6554. namespace Catch {
  6555. struct SignalDefs {
  6556. int id;
  6557. const char* name;
  6558. };
  6559. // 32kb for the alternate stack seems to be sufficient. However, this value
  6560. // is experimentally determined, so that's not guaranteed.
  6561. constexpr static std::size_t sigStackSize = 32768 >= MINSIGSTKSZ ? 32768 : MINSIGSTKSZ;
  6562. static SignalDefs signalDefs[] = {
  6563. { SIGINT, "SIGINT - Terminal interrupt signal" },
  6564. { SIGILL, "SIGILL - Illegal instruction signal" },
  6565. { SIGFPE, "SIGFPE - Floating point error signal" },
  6566. { SIGSEGV, "SIGSEGV - Segmentation violation signal" },
  6567. { SIGTERM, "SIGTERM - Termination request signal" },
  6568. { SIGABRT, "SIGABRT - Abort (abnormal termination) signal" }
  6569. };
  6570. void FatalConditionHandler::handleSignal( int sig ) {
  6571. char const * name = "<unknown signal>";
  6572. for (auto const& def : signalDefs) {
  6573. if (sig == def.id) {
  6574. name = def.name;
  6575. break;
  6576. }
  6577. }
  6578. reset();
  6579. reportFatal(name);
  6580. raise( sig );
  6581. }
  6582. FatalConditionHandler::FatalConditionHandler() {
  6583. isSet = true;
  6584. stack_t sigStack;
  6585. sigStack.ss_sp = altStackMem;
  6586. sigStack.ss_size = sigStackSize;
  6587. sigStack.ss_flags = 0;
  6588. sigaltstack(&sigStack, &oldSigStack);
  6589. struct sigaction sa = { };
  6590. sa.sa_handler = handleSignal;
  6591. sa.sa_flags = SA_ONSTACK;
  6592. for (std::size_t i = 0; i < sizeof(signalDefs)/sizeof(SignalDefs); ++i) {
  6593. sigaction(signalDefs[i].id, &sa, &oldSigActions[i]);
  6594. }
  6595. }
  6596. FatalConditionHandler::~FatalConditionHandler() {
  6597. reset();
  6598. }
  6599. void FatalConditionHandler::reset() {
  6600. if( isSet ) {
  6601. // Set signals back to previous values -- hopefully nobody overwrote them in the meantime
  6602. for( std::size_t i = 0; i < sizeof(signalDefs)/sizeof(SignalDefs); ++i ) {
  6603. sigaction(signalDefs[i].id, &oldSigActions[i], nullptr);
  6604. }
  6605. // Return the old stack
  6606. sigaltstack(&oldSigStack, nullptr);
  6607. isSet = false;
  6608. }
  6609. }
  6610. bool FatalConditionHandler::isSet = false;
  6611. struct sigaction FatalConditionHandler::oldSigActions[sizeof(signalDefs)/sizeof(SignalDefs)] = {};
  6612. stack_t FatalConditionHandler::oldSigStack = {};
  6613. char FatalConditionHandler::altStackMem[sigStackSize] = {};
  6614. } // namespace Catch
  6615. #else
  6616. namespace Catch {
  6617. void FatalConditionHandler::reset() {}
  6618. }
  6619. #endif // signals/SEH handling
  6620. #if defined(__GNUC__)
  6621. # pragma GCC diagnostic pop
  6622. #endif
  6623. // end catch_fatal_condition.cpp
  6624. // start catch_generators.cpp
  6625. // start catch_random_number_generator.h
  6626. #include <algorithm>
  6627. #include <random>
  6628. namespace Catch {
  6629. struct IConfig;
  6630. std::mt19937& rng();
  6631. void seedRng( IConfig const& config );
  6632. unsigned int rngSeed();
  6633. }
  6634. // end catch_random_number_generator.h
  6635. #include <limits>
  6636. #include <set>
  6637. namespace Catch {
  6638. IGeneratorTracker::~IGeneratorTracker() {}
  6639. namespace Generators {
  6640. GeneratorBase::~GeneratorBase() {}
  6641. std::vector<size_t> randomiseIndices( size_t selectionSize, size_t sourceSize ) {
  6642. assert( selectionSize <= sourceSize );
  6643. std::vector<size_t> indices;
  6644. indices.reserve( selectionSize );
  6645. std::uniform_int_distribution<size_t> uid( 0, sourceSize-1 );
  6646. std::set<size_t> seen;
  6647. // !TBD: improve this algorithm
  6648. while( indices.size() < selectionSize ) {
  6649. auto index = uid( rng() );
  6650. if( seen.insert( index ).second )
  6651. indices.push_back( index );
  6652. }
  6653. return indices;
  6654. }
  6655. auto acquireGeneratorTracker( SourceLineInfo const& lineInfo ) -> IGeneratorTracker& {
  6656. return getResultCapture().acquireGeneratorTracker( lineInfo );
  6657. }
  6658. template<>
  6659. auto all<int>() -> Generator<int> {
  6660. return range( std::numeric_limits<int>::min(), std::numeric_limits<int>::max() );
  6661. }
  6662. } // namespace Generators
  6663. } // namespace Catch
  6664. // end catch_generators.cpp
  6665. // start catch_interfaces_capture.cpp
  6666. namespace Catch {
  6667. IResultCapture::~IResultCapture() = default;
  6668. }
  6669. // end catch_interfaces_capture.cpp
  6670. // start catch_interfaces_config.cpp
  6671. namespace Catch {
  6672. IConfig::~IConfig() = default;
  6673. }
  6674. // end catch_interfaces_config.cpp
  6675. // start catch_interfaces_exception.cpp
  6676. namespace Catch {
  6677. IExceptionTranslator::~IExceptionTranslator() = default;
  6678. IExceptionTranslatorRegistry::~IExceptionTranslatorRegistry() = default;
  6679. }
  6680. // end catch_interfaces_exception.cpp
  6681. // start catch_interfaces_registry_hub.cpp
  6682. namespace Catch {
  6683. IRegistryHub::~IRegistryHub() = default;
  6684. IMutableRegistryHub::~IMutableRegistryHub() = default;
  6685. }
  6686. // end catch_interfaces_registry_hub.cpp
  6687. // start catch_interfaces_reporter.cpp
  6688. // start catch_reporter_listening.h
  6689. namespace Catch {
  6690. class ListeningReporter : public IStreamingReporter {
  6691. using Reporters = std::vector<IStreamingReporterPtr>;
  6692. Reporters m_listeners;
  6693. IStreamingReporterPtr m_reporter = nullptr;
  6694. ReporterPreferences m_preferences;
  6695. public:
  6696. ListeningReporter();
  6697. void addListener( IStreamingReporterPtr&& listener );
  6698. void addReporter( IStreamingReporterPtr&& reporter );
  6699. public: // IStreamingReporter
  6700. ReporterPreferences getPreferences() const override;
  6701. void noMatchingTestCases( std::string const& spec ) override;
  6702. static std::set<Verbosity> getSupportedVerbosities();
  6703. void benchmarkStarting( BenchmarkInfo const& benchmarkInfo ) override;
  6704. void benchmarkEnded( BenchmarkStats const& benchmarkStats ) override;
  6705. void testRunStarting( TestRunInfo const& testRunInfo ) override;
  6706. void testGroupStarting( GroupInfo const& groupInfo ) override;
  6707. void testCaseStarting( TestCaseInfo const& testInfo ) override;
  6708. void sectionStarting( SectionInfo const& sectionInfo ) override;
  6709. void assertionStarting( AssertionInfo const& assertionInfo ) override;
  6710. // The return value indicates if the messages buffer should be cleared:
  6711. bool assertionEnded( AssertionStats const& assertionStats ) override;
  6712. void sectionEnded( SectionStats const& sectionStats ) override;
  6713. void testCaseEnded( TestCaseStats const& testCaseStats ) override;
  6714. void testGroupEnded( TestGroupStats const& testGroupStats ) override;
  6715. void testRunEnded( TestRunStats const& testRunStats ) override;
  6716. void skipTest( TestCaseInfo const& testInfo ) override;
  6717. bool isMulti() const override;
  6718. };
  6719. } // end namespace Catch
  6720. // end catch_reporter_listening.h
  6721. namespace Catch {
  6722. ReporterConfig::ReporterConfig( IConfigPtr const& _fullConfig )
  6723. : m_stream( &_fullConfig->stream() ), m_fullConfig( _fullConfig ) {}
  6724. ReporterConfig::ReporterConfig( IConfigPtr const& _fullConfig, std::ostream& _stream )
  6725. : m_stream( &_stream ), m_fullConfig( _fullConfig ) {}
  6726. std::ostream& ReporterConfig::stream() const { return *m_stream; }
  6727. IConfigPtr ReporterConfig::fullConfig() const { return m_fullConfig; }
  6728. TestRunInfo::TestRunInfo( std::string const& _name ) : name( _name ) {}
  6729. GroupInfo::GroupInfo( std::string const& _name,
  6730. std::size_t _groupIndex,
  6731. std::size_t _groupsCount )
  6732. : name( _name ),
  6733. groupIndex( _groupIndex ),
  6734. groupsCounts( _groupsCount )
  6735. {}
  6736. AssertionStats::AssertionStats( AssertionResult const& _assertionResult,
  6737. std::vector<MessageInfo> const& _infoMessages,
  6738. Totals const& _totals )
  6739. : assertionResult( _assertionResult ),
  6740. infoMessages( _infoMessages ),
  6741. totals( _totals )
  6742. {
  6743. assertionResult.m_resultData.lazyExpression.m_transientExpression = _assertionResult.m_resultData.lazyExpression.m_transientExpression;
  6744. if( assertionResult.hasMessage() ) {
  6745. // Copy message into messages list.
  6746. // !TBD This should have been done earlier, somewhere
  6747. MessageBuilder builder( assertionResult.getTestMacroName(), assertionResult.getSourceInfo(), assertionResult.getResultType() );
  6748. builder << assertionResult.getMessage();
  6749. builder.m_info.message = builder.m_stream.str();
  6750. infoMessages.push_back( builder.m_info );
  6751. }
  6752. }
  6753. AssertionStats::~AssertionStats() = default;
  6754. SectionStats::SectionStats( SectionInfo const& _sectionInfo,
  6755. Counts const& _assertions,
  6756. double _durationInSeconds,
  6757. bool _missingAssertions )
  6758. : sectionInfo( _sectionInfo ),
  6759. assertions( _assertions ),
  6760. durationInSeconds( _durationInSeconds ),
  6761. missingAssertions( _missingAssertions )
  6762. {}
  6763. SectionStats::~SectionStats() = default;
  6764. TestCaseStats::TestCaseStats( TestCaseInfo const& _testInfo,
  6765. Totals const& _totals,
  6766. std::string const& _stdOut,
  6767. std::string const& _stdErr,
  6768. bool _aborting )
  6769. : testInfo( _testInfo ),
  6770. totals( _totals ),
  6771. stdOut( _stdOut ),
  6772. stdErr( _stdErr ),
  6773. aborting( _aborting )
  6774. {}
  6775. TestCaseStats::~TestCaseStats() = default;
  6776. TestGroupStats::TestGroupStats( GroupInfo const& _groupInfo,
  6777. Totals const& _totals,
  6778. bool _aborting )
  6779. : groupInfo( _groupInfo ),
  6780. totals( _totals ),
  6781. aborting( _aborting )
  6782. {}
  6783. TestGroupStats::TestGroupStats( GroupInfo const& _groupInfo )
  6784. : groupInfo( _groupInfo ),
  6785. aborting( false )
  6786. {}
  6787. TestGroupStats::~TestGroupStats() = default;
  6788. TestRunStats::TestRunStats( TestRunInfo const& _runInfo,
  6789. Totals const& _totals,
  6790. bool _aborting )
  6791. : runInfo( _runInfo ),
  6792. totals( _totals ),
  6793. aborting( _aborting )
  6794. {}
  6795. TestRunStats::~TestRunStats() = default;
  6796. void IStreamingReporter::fatalErrorEncountered( StringRef ) {}
  6797. bool IStreamingReporter::isMulti() const { return false; }
  6798. IReporterFactory::~IReporterFactory() = default;
  6799. IReporterRegistry::~IReporterRegistry() = default;
  6800. } // end namespace Catch
  6801. // end catch_interfaces_reporter.cpp
  6802. // start catch_interfaces_runner.cpp
  6803. namespace Catch {
  6804. IRunner::~IRunner() = default;
  6805. }
  6806. // end catch_interfaces_runner.cpp
  6807. // start catch_interfaces_testcase.cpp
  6808. namespace Catch {
  6809. ITestInvoker::~ITestInvoker() = default;
  6810. ITestCaseRegistry::~ITestCaseRegistry() = default;
  6811. }
  6812. // end catch_interfaces_testcase.cpp
  6813. // start catch_leak_detector.cpp
  6814. #ifdef CATCH_CONFIG_WINDOWS_CRTDBG
  6815. #include <crtdbg.h>
  6816. namespace Catch {
  6817. LeakDetector::LeakDetector() {
  6818. int flag = _CrtSetDbgFlag(_CRTDBG_REPORT_FLAG);
  6819. flag |= _CRTDBG_LEAK_CHECK_DF;
  6820. flag |= _CRTDBG_ALLOC_MEM_DF;
  6821. _CrtSetDbgFlag(flag);
  6822. _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE | _CRTDBG_MODE_DEBUG);
  6823. _CrtSetReportFile(_CRT_WARN, _CRTDBG_FILE_STDERR);
  6824. // Change this to leaking allocation's number to break there
  6825. _CrtSetBreakAlloc(-1);
  6826. }
  6827. }
  6828. #else
  6829. Catch::LeakDetector::LeakDetector() {}
  6830. #endif
  6831. Catch::LeakDetector::~LeakDetector() {
  6832. Catch::cleanUp();
  6833. }
  6834. // end catch_leak_detector.cpp
  6835. // start catch_list.cpp
  6836. // start catch_list.h
  6837. #include <set>
  6838. namespace Catch {
  6839. std::size_t listTests( Config const& config );
  6840. std::size_t listTestsNamesOnly( Config const& config );
  6841. struct TagInfo {
  6842. void add( std::string const& spelling );
  6843. std::string all() const;
  6844. std::set<std::string> spellings;
  6845. std::size_t count = 0;
  6846. };
  6847. std::size_t listTags( Config const& config );
  6848. std::size_t listReporters();
  6849. Option<std::size_t> list( Config const& config );
  6850. } // end namespace Catch
  6851. // end catch_list.h
  6852. // start catch_text.h
  6853. namespace Catch {
  6854. using namespace clara::TextFlow;
  6855. }
  6856. // end catch_text.h
  6857. #include <limits>
  6858. #include <algorithm>
  6859. #include <iomanip>
  6860. namespace Catch {
  6861. std::size_t listTests( Config const& config ) {
  6862. TestSpec testSpec = config.testSpec();
  6863. if( config.hasTestFilters() )
  6864. Catch::cout() << "Matching test cases:\n";
  6865. else {
  6866. Catch::cout() << "All available test cases:\n";
  6867. }
  6868. auto matchedTestCases = filterTests( getAllTestCasesSorted( config ), testSpec, config );
  6869. for( auto const& testCaseInfo : matchedTestCases ) {
  6870. Colour::Code colour = testCaseInfo.isHidden()
  6871. ? Colour::SecondaryText
  6872. : Colour::None;
  6873. Colour colourGuard( colour );
  6874. Catch::cout() << Column( testCaseInfo.name ).initialIndent( 2 ).indent( 4 ) << "\n";
  6875. if( config.verbosity() >= Verbosity::High ) {
  6876. Catch::cout() << Column( Catch::Detail::stringify( testCaseInfo.lineInfo ) ).indent(4) << std::endl;
  6877. std::string description = testCaseInfo.description;
  6878. if( description.empty() )
  6879. description = "(NO DESCRIPTION)";
  6880. Catch::cout() << Column( description ).indent(4) << std::endl;
  6881. }
  6882. if( !testCaseInfo.tags.empty() )
  6883. Catch::cout() << Column( testCaseInfo.tagsAsString() ).indent( 6 ) << "\n";
  6884. }
  6885. if( !config.hasTestFilters() )
  6886. Catch::cout() << pluralise( matchedTestCases.size(), "test case" ) << '\n' << std::endl;
  6887. else
  6888. Catch::cout() << pluralise( matchedTestCases.size(), "matching test case" ) << '\n' << std::endl;
  6889. return matchedTestCases.size();
  6890. }
  6891. std::size_t listTestsNamesOnly( Config const& config ) {
  6892. TestSpec testSpec = config.testSpec();
  6893. std::size_t matchedTests = 0;
  6894. std::vector<TestCase> matchedTestCases = filterTests( getAllTestCasesSorted( config ), testSpec, config );
  6895. for( auto const& testCaseInfo : matchedTestCases ) {
  6896. matchedTests++;
  6897. if( startsWith( testCaseInfo.name, '#' ) )
  6898. Catch::cout() << '"' << testCaseInfo.name << '"';
  6899. else
  6900. Catch::cout() << testCaseInfo.name;
  6901. if ( config.verbosity() >= Verbosity::High )
  6902. Catch::cout() << "\t@" << testCaseInfo.lineInfo;
  6903. Catch::cout() << std::endl;
  6904. }
  6905. return matchedTests;
  6906. }
  6907. void TagInfo::add( std::string const& spelling ) {
  6908. ++count;
  6909. spellings.insert( spelling );
  6910. }
  6911. std::string TagInfo::all() const {
  6912. std::string out;
  6913. for( auto const& spelling : spellings )
  6914. out += "[" + spelling + "]";
  6915. return out;
  6916. }
  6917. std::size_t listTags( Config const& config ) {
  6918. TestSpec testSpec = config.testSpec();
  6919. if( config.hasTestFilters() )
  6920. Catch::cout() << "Tags for matching test cases:\n";
  6921. else {
  6922. Catch::cout() << "All available tags:\n";
  6923. }
  6924. std::map<std::string, TagInfo> tagCounts;
  6925. std::vector<TestCase> matchedTestCases = filterTests( getAllTestCasesSorted( config ), testSpec, config );
  6926. for( auto const& testCase : matchedTestCases ) {
  6927. for( auto const& tagName : testCase.getTestCaseInfo().tags ) {
  6928. std::string lcaseTagName = toLower( tagName );
  6929. auto countIt = tagCounts.find( lcaseTagName );
  6930. if( countIt == tagCounts.end() )
  6931. countIt = tagCounts.insert( std::make_pair( lcaseTagName, TagInfo() ) ).first;
  6932. countIt->second.add( tagName );
  6933. }
  6934. }
  6935. for( auto const& tagCount : tagCounts ) {
  6936. ReusableStringStream rss;
  6937. rss << " " << std::setw(2) << tagCount.second.count << " ";
  6938. auto str = rss.str();
  6939. auto wrapper = Column( tagCount.second.all() )
  6940. .initialIndent( 0 )
  6941. .indent( str.size() )
  6942. .width( CATCH_CONFIG_CONSOLE_WIDTH-10 );
  6943. Catch::cout() << str << wrapper << '\n';
  6944. }
  6945. Catch::cout() << pluralise( tagCounts.size(), "tag" ) << '\n' << std::endl;
  6946. return tagCounts.size();
  6947. }
  6948. std::size_t listReporters() {
  6949. Catch::cout() << "Available reporters:\n";
  6950. IReporterRegistry::FactoryMap const& factories = getRegistryHub().getReporterRegistry().getFactories();
  6951. std::size_t maxNameLen = 0;
  6952. for( auto const& factoryKvp : factories )
  6953. maxNameLen = (std::max)( maxNameLen, factoryKvp.first.size() );
  6954. for( auto const& factoryKvp : factories ) {
  6955. Catch::cout()
  6956. << Column( factoryKvp.first + ":" )
  6957. .indent(2)
  6958. .width( 5+maxNameLen )
  6959. + Column( factoryKvp.second->getDescription() )
  6960. .initialIndent(0)
  6961. .indent(2)
  6962. .width( CATCH_CONFIG_CONSOLE_WIDTH - maxNameLen-8 )
  6963. << "\n";
  6964. }
  6965. Catch::cout() << std::endl;
  6966. return factories.size();
  6967. }
  6968. Option<std::size_t> list( Config const& config ) {
  6969. Option<std::size_t> listedCount;
  6970. if( config.listTests() )
  6971. listedCount = listedCount.valueOr(0) + listTests( config );
  6972. if( config.listTestNamesOnly() )
  6973. listedCount = listedCount.valueOr(0) + listTestsNamesOnly( config );
  6974. if( config.listTags() )
  6975. listedCount = listedCount.valueOr(0) + listTags( config );
  6976. if( config.listReporters() )
  6977. listedCount = listedCount.valueOr(0) + listReporters();
  6978. return listedCount;
  6979. }
  6980. } // end namespace Catch
  6981. // end catch_list.cpp
  6982. // start catch_matchers.cpp
  6983. namespace Catch {
  6984. namespace Matchers {
  6985. namespace Impl {
  6986. std::string MatcherUntypedBase::toString() const {
  6987. if( m_cachedToString.empty() )
  6988. m_cachedToString = describe();
  6989. return m_cachedToString;
  6990. }
  6991. MatcherUntypedBase::~MatcherUntypedBase() = default;
  6992. } // namespace Impl
  6993. } // namespace Matchers
  6994. using namespace Matchers;
  6995. using Matchers::Impl::MatcherBase;
  6996. } // namespace Catch
  6997. // end catch_matchers.cpp
  6998. // start catch_matchers_floating.cpp
  6999. // start catch_polyfills.hpp
  7000. namespace Catch {
  7001. bool isnan(float f);
  7002. bool isnan(double d);
  7003. }
  7004. // end catch_polyfills.hpp
  7005. // start catch_to_string.hpp
  7006. #include <string>
  7007. namespace Catch {
  7008. template <typename T>
  7009. std::string to_string(T const& t) {
  7010. #if defined(CATCH_CONFIG_CPP11_TO_STRING)
  7011. return std::to_string(t);
  7012. #else
  7013. ReusableStringStream rss;
  7014. rss << t;
  7015. return rss.str();
  7016. #endif
  7017. }
  7018. } // end namespace Catch
  7019. // end catch_to_string.hpp
  7020. #include <cstdlib>
  7021. #include <cstdint>
  7022. #include <cstring>
  7023. namespace Catch {
  7024. namespace Matchers {
  7025. namespace Floating {
  7026. enum class FloatingPointKind : uint8_t {
  7027. Float,
  7028. Double
  7029. };
  7030. }
  7031. }
  7032. }
  7033. namespace {
  7034. template <typename T>
  7035. struct Converter;
  7036. template <>
  7037. struct Converter<float> {
  7038. static_assert(sizeof(float) == sizeof(int32_t), "Important ULP matcher assumption violated");
  7039. Converter(float f) {
  7040. std::memcpy(&i, &f, sizeof(f));
  7041. }
  7042. int32_t i;
  7043. };
  7044. template <>
  7045. struct Converter<double> {
  7046. static_assert(sizeof(double) == sizeof(int64_t), "Important ULP matcher assumption violated");
  7047. Converter(double d) {
  7048. std::memcpy(&i, &d, sizeof(d));
  7049. }
  7050. int64_t i;
  7051. };
  7052. template <typename T>
  7053. auto convert(T t) -> Converter<T> {
  7054. return Converter<T>(t);
  7055. }
  7056. template <typename FP>
  7057. bool almostEqualUlps(FP lhs, FP rhs, int maxUlpDiff) {
  7058. // Comparison with NaN should always be false.
  7059. // This way we can rule it out before getting into the ugly details
  7060. if (Catch::isnan(lhs) || Catch::isnan(rhs)) {
  7061. return false;
  7062. }
  7063. auto lc = convert(lhs);
  7064. auto rc = convert(rhs);
  7065. if ((lc.i < 0) != (rc.i < 0)) {
  7066. // Potentially we can have +0 and -0
  7067. return lhs == rhs;
  7068. }
  7069. auto ulpDiff = std::abs(lc.i - rc.i);
  7070. return ulpDiff <= maxUlpDiff;
  7071. }
  7072. }
  7073. namespace Catch {
  7074. namespace Matchers {
  7075. namespace Floating {
  7076. WithinAbsMatcher::WithinAbsMatcher(double target, double margin)
  7077. :m_target{ target }, m_margin{ margin } {
  7078. CATCH_ENFORCE(margin >= 0, "Invalid margin: " << margin << '.'
  7079. << " Margin has to be non-negative.");
  7080. }
  7081. // Performs equivalent check of std::fabs(lhs - rhs) <= margin
  7082. // But without the subtraction to allow for INFINITY in comparison
  7083. bool WithinAbsMatcher::match(double const& matchee) const {
  7084. return (matchee + m_margin >= m_target) && (m_target + m_margin >= matchee);
  7085. }
  7086. std::string WithinAbsMatcher::describe() const {
  7087. return "is within " + ::Catch::Detail::stringify(m_margin) + " of " + ::Catch::Detail::stringify(m_target);
  7088. }
  7089. WithinUlpsMatcher::WithinUlpsMatcher(double target, int ulps, FloatingPointKind baseType)
  7090. :m_target{ target }, m_ulps{ ulps }, m_type{ baseType } {
  7091. CATCH_ENFORCE(ulps >= 0, "Invalid ULP setting: " << ulps << '.'
  7092. << " ULPs have to be non-negative.");
  7093. }
  7094. #if defined(__clang__)
  7095. #pragma clang diagnostic push
  7096. // Clang <3.5 reports on the default branch in the switch below
  7097. #pragma clang diagnostic ignored "-Wunreachable-code"
  7098. #endif
  7099. bool WithinUlpsMatcher::match(double const& matchee) const {
  7100. switch (m_type) {
  7101. case FloatingPointKind::Float:
  7102. return almostEqualUlps<float>(static_cast<float>(matchee), static_cast<float>(m_target), m_ulps);
  7103. case FloatingPointKind::Double:
  7104. return almostEqualUlps<double>(matchee, m_target, m_ulps);
  7105. default:
  7106. CATCH_INTERNAL_ERROR( "Unknown FloatingPointKind value" );
  7107. }
  7108. }
  7109. #if defined(__clang__)
  7110. #pragma clang diagnostic pop
  7111. #endif
  7112. std::string WithinUlpsMatcher::describe() const {
  7113. return "is within " + Catch::to_string(m_ulps) + " ULPs of " + ::Catch::Detail::stringify(m_target) + ((m_type == FloatingPointKind::Float)? "f" : "");
  7114. }
  7115. }// namespace Floating
  7116. Floating::WithinUlpsMatcher WithinULP(double target, int maxUlpDiff) {
  7117. return Floating::WithinUlpsMatcher(target, maxUlpDiff, Floating::FloatingPointKind::Double);
  7118. }
  7119. Floating::WithinUlpsMatcher WithinULP(float target, int maxUlpDiff) {
  7120. return Floating::WithinUlpsMatcher(target, maxUlpDiff, Floating::FloatingPointKind::Float);
  7121. }
  7122. Floating::WithinAbsMatcher WithinAbs(double target, double margin) {
  7123. return Floating::WithinAbsMatcher(target, margin);
  7124. }
  7125. } // namespace Matchers
  7126. } // namespace Catch
  7127. // end catch_matchers_floating.cpp
  7128. // start catch_matchers_generic.cpp
  7129. std::string Catch::Matchers::Generic::Detail::finalizeDescription(const std::string& desc) {
  7130. if (desc.empty()) {
  7131. return "matches undescribed predicate";
  7132. } else {
  7133. return "matches predicate: \"" + desc + '"';
  7134. }
  7135. }
  7136. // end catch_matchers_generic.cpp
  7137. // start catch_matchers_string.cpp
  7138. #include <regex>
  7139. namespace Catch {
  7140. namespace Matchers {
  7141. namespace StdString {
  7142. CasedString::CasedString( std::string const& str, CaseSensitive::Choice caseSensitivity )
  7143. : m_caseSensitivity( caseSensitivity ),
  7144. m_str( adjustString( str ) )
  7145. {}
  7146. std::string CasedString::adjustString( std::string const& str ) const {
  7147. return m_caseSensitivity == CaseSensitive::No
  7148. ? toLower( str )
  7149. : str;
  7150. }
  7151. std::string CasedString::caseSensitivitySuffix() const {
  7152. return m_caseSensitivity == CaseSensitive::No
  7153. ? " (case insensitive)"
  7154. : std::string();
  7155. }
  7156. StringMatcherBase::StringMatcherBase( std::string const& operation, CasedString const& comparator )
  7157. : m_comparator( comparator ),
  7158. m_operation( operation ) {
  7159. }
  7160. std::string StringMatcherBase::describe() const {
  7161. std::string description;
  7162. description.reserve(5 + m_operation.size() + m_comparator.m_str.size() +
  7163. m_comparator.caseSensitivitySuffix().size());
  7164. description += m_operation;
  7165. description += ": \"";
  7166. description += m_comparator.m_str;
  7167. description += "\"";
  7168. description += m_comparator.caseSensitivitySuffix();
  7169. return description;
  7170. }
  7171. EqualsMatcher::EqualsMatcher( CasedString const& comparator ) : StringMatcherBase( "equals", comparator ) {}
  7172. bool EqualsMatcher::match( std::string const& source ) const {
  7173. return m_comparator.adjustString( source ) == m_comparator.m_str;
  7174. }
  7175. ContainsMatcher::ContainsMatcher( CasedString const& comparator ) : StringMatcherBase( "contains", comparator ) {}
  7176. bool ContainsMatcher::match( std::string const& source ) const {
  7177. return contains( m_comparator.adjustString( source ), m_comparator.m_str );
  7178. }
  7179. StartsWithMatcher::StartsWithMatcher( CasedString const& comparator ) : StringMatcherBase( "starts with", comparator ) {}
  7180. bool StartsWithMatcher::match( std::string const& source ) const {
  7181. return startsWith( m_comparator.adjustString( source ), m_comparator.m_str );
  7182. }
  7183. EndsWithMatcher::EndsWithMatcher( CasedString const& comparator ) : StringMatcherBase( "ends with", comparator ) {}
  7184. bool EndsWithMatcher::match( std::string const& source ) const {
  7185. return endsWith( m_comparator.adjustString( source ), m_comparator.m_str );
  7186. }
  7187. RegexMatcher::RegexMatcher(std::string regex, CaseSensitive::Choice caseSensitivity): m_regex(std::move(regex)), m_caseSensitivity(caseSensitivity) {}
  7188. bool RegexMatcher::match(std::string const& matchee) const {
  7189. auto flags = std::regex::ECMAScript; // ECMAScript is the default syntax option anyway
  7190. if (m_caseSensitivity == CaseSensitive::Choice::No) {
  7191. flags |= std::regex::icase;
  7192. }
  7193. auto reg = std::regex(m_regex, flags);
  7194. return std::regex_match(matchee, reg);
  7195. }
  7196. std::string RegexMatcher::describe() const {
  7197. return "matches " + ::Catch::Detail::stringify(m_regex) + ((m_caseSensitivity == CaseSensitive::Choice::Yes)? " case sensitively" : " case insensitively");
  7198. }
  7199. } // namespace StdString
  7200. StdString::EqualsMatcher Equals( std::string const& str, CaseSensitive::Choice caseSensitivity ) {
  7201. return StdString::EqualsMatcher( StdString::CasedString( str, caseSensitivity) );
  7202. }
  7203. StdString::ContainsMatcher Contains( std::string const& str, CaseSensitive::Choice caseSensitivity ) {
  7204. return StdString::ContainsMatcher( StdString::CasedString( str, caseSensitivity) );
  7205. }
  7206. StdString::EndsWithMatcher EndsWith( std::string const& str, CaseSensitive::Choice caseSensitivity ) {
  7207. return StdString::EndsWithMatcher( StdString::CasedString( str, caseSensitivity) );
  7208. }
  7209. StdString::StartsWithMatcher StartsWith( std::string const& str, CaseSensitive::Choice caseSensitivity ) {
  7210. return StdString::StartsWithMatcher( StdString::CasedString( str, caseSensitivity) );
  7211. }
  7212. StdString::RegexMatcher Matches(std::string const& regex, CaseSensitive::Choice caseSensitivity) {
  7213. return StdString::RegexMatcher(regex, caseSensitivity);
  7214. }
  7215. } // namespace Matchers
  7216. } // namespace Catch
  7217. // end catch_matchers_string.cpp
  7218. // start catch_message.cpp
  7219. // start catch_uncaught_exceptions.h
  7220. namespace Catch {
  7221. bool uncaught_exceptions();
  7222. } // end namespace Catch
  7223. // end catch_uncaught_exceptions.h
  7224. #include <cassert>
  7225. #include <stack>
  7226. namespace Catch {
  7227. MessageInfo::MessageInfo( StringRef const& _macroName,
  7228. SourceLineInfo const& _lineInfo,
  7229. ResultWas::OfType _type )
  7230. : macroName( _macroName ),
  7231. lineInfo( _lineInfo ),
  7232. type( _type ),
  7233. sequence( ++globalCount )
  7234. {}
  7235. bool MessageInfo::operator==( MessageInfo const& other ) const {
  7236. return sequence == other.sequence;
  7237. }
  7238. bool MessageInfo::operator<( MessageInfo const& other ) const {
  7239. return sequence < other.sequence;
  7240. }
  7241. // This may need protecting if threading support is added
  7242. unsigned int MessageInfo::globalCount = 0;
  7243. ////////////////////////////////////////////////////////////////////////////
  7244. Catch::MessageBuilder::MessageBuilder( StringRef const& macroName,
  7245. SourceLineInfo const& lineInfo,
  7246. ResultWas::OfType type )
  7247. :m_info(macroName, lineInfo, type) {}
  7248. ////////////////////////////////////////////////////////////////////////////
  7249. ScopedMessage::ScopedMessage( MessageBuilder const& builder )
  7250. : m_info( builder.m_info )
  7251. {
  7252. m_info.message = builder.m_stream.str();
  7253. getResultCapture().pushScopedMessage( m_info );
  7254. }
  7255. ScopedMessage::~ScopedMessage() {
  7256. if ( !uncaught_exceptions() ){
  7257. getResultCapture().popScopedMessage(m_info);
  7258. }
  7259. }
  7260. Capturer::Capturer( StringRef macroName, SourceLineInfo const& lineInfo, ResultWas::OfType resultType, StringRef names ) {
  7261. auto trimmed = [&] (size_t start, size_t end) {
  7262. while (names[start] == ',' || isspace(names[start])) {
  7263. ++start;
  7264. }
  7265. while (names[end] == ',' || isspace(names[end])) {
  7266. --end;
  7267. }
  7268. return names.substr(start, end - start + 1);
  7269. };
  7270. size_t start = 0;
  7271. std::stack<char> openings;
  7272. for (size_t pos = 0; pos < names.size(); ++pos) {
  7273. char c = names[pos];
  7274. switch (c) {
  7275. case '[':
  7276. case '{':
  7277. case '(':
  7278. // It is basically impossible to disambiguate between
  7279. // comparison and start of template args in this context
  7280. // case '<':
  7281. openings.push(c);
  7282. break;
  7283. case ']':
  7284. case '}':
  7285. case ')':
  7286. // case '>':
  7287. openings.pop();
  7288. break;
  7289. case ',':
  7290. if (start != pos && openings.size() == 0) {
  7291. m_messages.emplace_back(macroName, lineInfo, resultType);
  7292. m_messages.back().message = trimmed(start, pos);
  7293. m_messages.back().message += " := ";
  7294. start = pos;
  7295. }
  7296. }
  7297. }
  7298. assert(openings.size() == 0 && "Mismatched openings");
  7299. m_messages.emplace_back(macroName, lineInfo, resultType);
  7300. m_messages.back().message = trimmed(start, names.size() - 1);
  7301. m_messages.back().message += " := ";
  7302. }
  7303. Capturer::~Capturer() {
  7304. if ( !uncaught_exceptions() ){
  7305. assert( m_captured == m_messages.size() );
  7306. for( size_t i = 0; i < m_captured; ++i )
  7307. m_resultCapture.popScopedMessage( m_messages[i] );
  7308. }
  7309. }
  7310. void Capturer::captureValue( size_t index, std::string const& value ) {
  7311. assert( index < m_messages.size() );
  7312. m_messages[index].message += value;
  7313. m_resultCapture.pushScopedMessage( m_messages[index] );
  7314. m_captured++;
  7315. }
  7316. } // end namespace Catch
  7317. // end catch_message.cpp
  7318. // start catch_output_redirect.cpp
  7319. // start catch_output_redirect.h
  7320. #ifndef TWOBLUECUBES_CATCH_OUTPUT_REDIRECT_H
  7321. #define TWOBLUECUBES_CATCH_OUTPUT_REDIRECT_H
  7322. #include <cstdio>
  7323. #include <iosfwd>
  7324. #include <string>
  7325. namespace Catch {
  7326. class RedirectedStream {
  7327. std::ostream& m_originalStream;
  7328. std::ostream& m_redirectionStream;
  7329. std::streambuf* m_prevBuf;
  7330. public:
  7331. RedirectedStream( std::ostream& originalStream, std::ostream& redirectionStream );
  7332. ~RedirectedStream();
  7333. };
  7334. class RedirectedStdOut {
  7335. ReusableStringStream m_rss;
  7336. RedirectedStream m_cout;
  7337. public:
  7338. RedirectedStdOut();
  7339. auto str() const -> std::string;
  7340. };
  7341. // StdErr has two constituent streams in C++, std::cerr and std::clog
  7342. // This means that we need to redirect 2 streams into 1 to keep proper
  7343. // order of writes
  7344. class RedirectedStdErr {
  7345. ReusableStringStream m_rss;
  7346. RedirectedStream m_cerr;
  7347. RedirectedStream m_clog;
  7348. public:
  7349. RedirectedStdErr();
  7350. auto str() const -> std::string;
  7351. };
  7352. #if defined(CATCH_CONFIG_NEW_CAPTURE)
  7353. // Windows's implementation of std::tmpfile is terrible (it tries
  7354. // to create a file inside system folder, thus requiring elevated
  7355. // privileges for the binary), so we have to use tmpnam(_s) and
  7356. // create the file ourselves there.
  7357. class TempFile {
  7358. public:
  7359. TempFile(TempFile const&) = delete;
  7360. TempFile& operator=(TempFile const&) = delete;
  7361. TempFile(TempFile&&) = delete;
  7362. TempFile& operator=(TempFile&&) = delete;
  7363. TempFile();
  7364. ~TempFile();
  7365. std::FILE* getFile();
  7366. std::string getContents();
  7367. private:
  7368. std::FILE* m_file = nullptr;
  7369. #if defined(_MSC_VER)
  7370. char m_buffer[L_tmpnam] = { 0 };
  7371. #endif
  7372. };
  7373. class OutputRedirect {
  7374. public:
  7375. OutputRedirect(OutputRedirect const&) = delete;
  7376. OutputRedirect& operator=(OutputRedirect const&) = delete;
  7377. OutputRedirect(OutputRedirect&&) = delete;
  7378. OutputRedirect& operator=(OutputRedirect&&) = delete;
  7379. OutputRedirect(std::string& stdout_dest, std::string& stderr_dest);
  7380. ~OutputRedirect();
  7381. private:
  7382. int m_originalStdout = -1;
  7383. int m_originalStderr = -1;
  7384. TempFile m_stdoutFile;
  7385. TempFile m_stderrFile;
  7386. std::string& m_stdoutDest;
  7387. std::string& m_stderrDest;
  7388. };
  7389. #endif
  7390. } // end namespace Catch
  7391. #endif // TWOBLUECUBES_CATCH_OUTPUT_REDIRECT_H
  7392. // end catch_output_redirect.h
  7393. #include <cstdio>
  7394. #include <cstring>
  7395. #include <fstream>
  7396. #include <sstream>
  7397. #include <stdexcept>
  7398. #if defined(CATCH_CONFIG_NEW_CAPTURE)
  7399. #if defined(_MSC_VER)
  7400. #include <io.h> //_dup and _dup2
  7401. #define dup _dup
  7402. #define dup2 _dup2
  7403. #define fileno _fileno
  7404. #else
  7405. #include <unistd.h> // dup and dup2
  7406. #endif
  7407. #endif
  7408. namespace Catch {
  7409. RedirectedStream::RedirectedStream( std::ostream& originalStream, std::ostream& redirectionStream )
  7410. : m_originalStream( originalStream ),
  7411. m_redirectionStream( redirectionStream ),
  7412. m_prevBuf( m_originalStream.rdbuf() )
  7413. {
  7414. m_originalStream.rdbuf( m_redirectionStream.rdbuf() );
  7415. }
  7416. RedirectedStream::~RedirectedStream() {
  7417. m_originalStream.rdbuf( m_prevBuf );
  7418. }
  7419. RedirectedStdOut::RedirectedStdOut() : m_cout( Catch::cout(), m_rss.get() ) {}
  7420. auto RedirectedStdOut::str() const -> std::string { return m_rss.str(); }
  7421. RedirectedStdErr::RedirectedStdErr()
  7422. : m_cerr( Catch::cerr(), m_rss.get() ),
  7423. m_clog( Catch::clog(), m_rss.get() )
  7424. {}
  7425. auto RedirectedStdErr::str() const -> std::string { return m_rss.str(); }
  7426. #if defined(CATCH_CONFIG_NEW_CAPTURE)
  7427. #if defined(_MSC_VER)
  7428. TempFile::TempFile() {
  7429. if (tmpnam_s(m_buffer)) {
  7430. CATCH_RUNTIME_ERROR("Could not get a temp filename");
  7431. }
  7432. if (fopen_s(&m_file, m_buffer, "w")) {
  7433. char buffer[100];
  7434. if (strerror_s(buffer, errno)) {
  7435. CATCH_RUNTIME_ERROR("Could not translate errno to a string");
  7436. }
  7437. CATCH_RUNTIME_ERROR("Coul dnot open the temp file: '" << m_buffer << "' because: " << buffer);
  7438. }
  7439. }
  7440. #else
  7441. TempFile::TempFile() {
  7442. m_file = std::tmpfile();
  7443. if (!m_file) {
  7444. CATCH_RUNTIME_ERROR("Could not create a temp file.");
  7445. }
  7446. }
  7447. #endif
  7448. TempFile::~TempFile() {
  7449. // TBD: What to do about errors here?
  7450. std::fclose(m_file);
  7451. // We manually create the file on Windows only, on Linux
  7452. // it will be autodeleted
  7453. #if defined(_MSC_VER)
  7454. std::remove(m_buffer);
  7455. #endif
  7456. }
  7457. FILE* TempFile::getFile() {
  7458. return m_file;
  7459. }
  7460. std::string TempFile::getContents() {
  7461. std::stringstream sstr;
  7462. char buffer[100] = {};
  7463. std::rewind(m_file);
  7464. while (std::fgets(buffer, sizeof(buffer), m_file)) {
  7465. sstr << buffer;
  7466. }
  7467. return sstr.str();
  7468. }
  7469. OutputRedirect::OutputRedirect(std::string& stdout_dest, std::string& stderr_dest) :
  7470. m_originalStdout(dup(1)),
  7471. m_originalStderr(dup(2)),
  7472. m_stdoutDest(stdout_dest),
  7473. m_stderrDest(stderr_dest) {
  7474. dup2(fileno(m_stdoutFile.getFile()), 1);
  7475. dup2(fileno(m_stderrFile.getFile()), 2);
  7476. }
  7477. OutputRedirect::~OutputRedirect() {
  7478. Catch::cout() << std::flush;
  7479. fflush(stdout);
  7480. // Since we support overriding these streams, we flush cerr
  7481. // even though std::cerr is unbuffered
  7482. Catch::cerr() << std::flush;
  7483. Catch::clog() << std::flush;
  7484. fflush(stderr);
  7485. dup2(m_originalStdout, 1);
  7486. dup2(m_originalStderr, 2);
  7487. m_stdoutDest += m_stdoutFile.getContents();
  7488. m_stderrDest += m_stderrFile.getContents();
  7489. }
  7490. #endif // CATCH_CONFIG_NEW_CAPTURE
  7491. } // namespace Catch
  7492. #if defined(CATCH_CONFIG_NEW_CAPTURE)
  7493. #if defined(_MSC_VER)
  7494. #undef dup
  7495. #undef dup2
  7496. #undef fileno
  7497. #endif
  7498. #endif
  7499. // end catch_output_redirect.cpp
  7500. // start catch_polyfills.cpp
  7501. #include <cmath>
  7502. namespace Catch {
  7503. #if !defined(CATCH_CONFIG_POLYFILL_ISNAN)
  7504. bool isnan(float f) {
  7505. return std::isnan(f);
  7506. }
  7507. bool isnan(double d) {
  7508. return std::isnan(d);
  7509. }
  7510. #else
  7511. // For now we only use this for embarcadero
  7512. bool isnan(float f) {
  7513. return std::_isnan(f);
  7514. }
  7515. bool isnan(double d) {
  7516. return std::_isnan(d);
  7517. }
  7518. #endif
  7519. } // end namespace Catch
  7520. // end catch_polyfills.cpp
  7521. // start catch_random_number_generator.cpp
  7522. namespace Catch {
  7523. std::mt19937& rng() {
  7524. static std::mt19937 s_rng;
  7525. return s_rng;
  7526. }
  7527. void seedRng( IConfig const& config ) {
  7528. if( config.rngSeed() != 0 ) {
  7529. std::srand( config.rngSeed() );
  7530. rng().seed( config.rngSeed() );
  7531. }
  7532. }
  7533. unsigned int rngSeed() {
  7534. return getCurrentContext().getConfig()->rngSeed();
  7535. }
  7536. }
  7537. // end catch_random_number_generator.cpp
  7538. // start catch_registry_hub.cpp
  7539. // start catch_test_case_registry_impl.h
  7540. #include <vector>
  7541. #include <set>
  7542. #include <algorithm>
  7543. #include <ios>
  7544. namespace Catch {
  7545. class TestCase;
  7546. struct IConfig;
  7547. std::vector<TestCase> sortTests( IConfig const& config, std::vector<TestCase> const& unsortedTestCases );
  7548. bool matchTest( TestCase const& testCase, TestSpec const& testSpec, IConfig const& config );
  7549. void enforceNoDuplicateTestCases( std::vector<TestCase> const& functions );
  7550. std::vector<TestCase> filterTests( std::vector<TestCase> const& testCases, TestSpec const& testSpec, IConfig const& config );
  7551. std::vector<TestCase> const& getAllTestCasesSorted( IConfig const& config );
  7552. class TestRegistry : public ITestCaseRegistry {
  7553. public:
  7554. virtual ~TestRegistry() = default;
  7555. virtual void registerTest( TestCase const& testCase );
  7556. std::vector<TestCase> const& getAllTests() const override;
  7557. std::vector<TestCase> const& getAllTestsSorted( IConfig const& config ) const override;
  7558. private:
  7559. std::vector<TestCase> m_functions;
  7560. mutable RunTests::InWhatOrder m_currentSortOrder = RunTests::InDeclarationOrder;
  7561. mutable std::vector<TestCase> m_sortedFunctions;
  7562. std::size_t m_unnamedCount = 0;
  7563. std::ios_base::Init m_ostreamInit; // Forces cout/ cerr to be initialised
  7564. };
  7565. ///////////////////////////////////////////////////////////////////////////
  7566. class TestInvokerAsFunction : public ITestInvoker {
  7567. void(*m_testAsFunction)();
  7568. public:
  7569. TestInvokerAsFunction( void(*testAsFunction)() ) noexcept;
  7570. void invoke() const override;
  7571. };
  7572. std::string extractClassName( StringRef const& classOrQualifiedMethodName );
  7573. ///////////////////////////////////////////////////////////////////////////
  7574. } // end namespace Catch
  7575. // end catch_test_case_registry_impl.h
  7576. // start catch_reporter_registry.h
  7577. #include <map>
  7578. namespace Catch {
  7579. class ReporterRegistry : public IReporterRegistry {
  7580. public:
  7581. ~ReporterRegistry() override;
  7582. IStreamingReporterPtr create( std::string const& name, IConfigPtr const& config ) const override;
  7583. void registerReporter( std::string const& name, IReporterFactoryPtr const& factory );
  7584. void registerListener( IReporterFactoryPtr const& factory );
  7585. FactoryMap const& getFactories() const override;
  7586. Listeners const& getListeners() const override;
  7587. private:
  7588. FactoryMap m_factories;
  7589. Listeners m_listeners;
  7590. };
  7591. }
  7592. // end catch_reporter_registry.h
  7593. // start catch_tag_alias_registry.h
  7594. // start catch_tag_alias.h
  7595. #include <string>
  7596. namespace Catch {
  7597. struct TagAlias {
  7598. TagAlias(std::string const& _tag, SourceLineInfo _lineInfo);
  7599. std::string tag;
  7600. SourceLineInfo lineInfo;
  7601. };
  7602. } // end namespace Catch
  7603. // end catch_tag_alias.h
  7604. #include <map>
  7605. namespace Catch {
  7606. class TagAliasRegistry : public ITagAliasRegistry {
  7607. public:
  7608. ~TagAliasRegistry() override;
  7609. TagAlias const* find( std::string const& alias ) const override;
  7610. std::string expandAliases( std::string const& unexpandedTestSpec ) const override;
  7611. void add( std::string const& alias, std::string const& tag, SourceLineInfo const& lineInfo );
  7612. private:
  7613. std::map<std::string, TagAlias> m_registry;
  7614. };
  7615. } // end namespace Catch
  7616. // end catch_tag_alias_registry.h
  7617. // start catch_startup_exception_registry.h
  7618. #include <vector>
  7619. #include <exception>
  7620. namespace Catch {
  7621. class StartupExceptionRegistry {
  7622. public:
  7623. void add(std::exception_ptr const& exception) noexcept;
  7624. std::vector<std::exception_ptr> const& getExceptions() const noexcept;
  7625. private:
  7626. std::vector<std::exception_ptr> m_exceptions;
  7627. };
  7628. } // end namespace Catch
  7629. // end catch_startup_exception_registry.h
  7630. // start catch_singletons.hpp
  7631. namespace Catch {
  7632. struct ISingleton {
  7633. virtual ~ISingleton();
  7634. };
  7635. void addSingleton( ISingleton* singleton );
  7636. void cleanupSingletons();
  7637. template<typename SingletonImplT, typename InterfaceT = SingletonImplT, typename MutableInterfaceT = InterfaceT>
  7638. class Singleton : SingletonImplT, public ISingleton {
  7639. static auto getInternal() -> Singleton* {
  7640. static Singleton* s_instance = nullptr;
  7641. if( !s_instance ) {
  7642. s_instance = new Singleton;
  7643. addSingleton( s_instance );
  7644. }
  7645. return s_instance;
  7646. }
  7647. public:
  7648. static auto get() -> InterfaceT const& {
  7649. return *getInternal();
  7650. }
  7651. static auto getMutable() -> MutableInterfaceT& {
  7652. return *getInternal();
  7653. }
  7654. };
  7655. } // namespace Catch
  7656. // end catch_singletons.hpp
  7657. namespace Catch {
  7658. namespace {
  7659. class RegistryHub : public IRegistryHub, public IMutableRegistryHub,
  7660. private NonCopyable {
  7661. public: // IRegistryHub
  7662. RegistryHub() = default;
  7663. IReporterRegistry const& getReporterRegistry() const override {
  7664. return m_reporterRegistry;
  7665. }
  7666. ITestCaseRegistry const& getTestCaseRegistry() const override {
  7667. return m_testCaseRegistry;
  7668. }
  7669. IExceptionTranslatorRegistry const& getExceptionTranslatorRegistry() const override {
  7670. return m_exceptionTranslatorRegistry;
  7671. }
  7672. ITagAliasRegistry const& getTagAliasRegistry() const override {
  7673. return m_tagAliasRegistry;
  7674. }
  7675. StartupExceptionRegistry const& getStartupExceptionRegistry() const override {
  7676. return m_exceptionRegistry;
  7677. }
  7678. public: // IMutableRegistryHub
  7679. void registerReporter( std::string const& name, IReporterFactoryPtr const& factory ) override {
  7680. m_reporterRegistry.registerReporter( name, factory );
  7681. }
  7682. void registerListener( IReporterFactoryPtr const& factory ) override {
  7683. m_reporterRegistry.registerListener( factory );
  7684. }
  7685. void registerTest( TestCase const& testInfo ) override {
  7686. m_testCaseRegistry.registerTest( testInfo );
  7687. }
  7688. void registerTranslator( const IExceptionTranslator* translator ) override {
  7689. m_exceptionTranslatorRegistry.registerTranslator( translator );
  7690. }
  7691. void registerTagAlias( std::string const& alias, std::string const& tag, SourceLineInfo const& lineInfo ) override {
  7692. m_tagAliasRegistry.add( alias, tag, lineInfo );
  7693. }
  7694. void registerStartupException() noexcept override {
  7695. m_exceptionRegistry.add(std::current_exception());
  7696. }
  7697. private:
  7698. TestRegistry m_testCaseRegistry;
  7699. ReporterRegistry m_reporterRegistry;
  7700. ExceptionTranslatorRegistry m_exceptionTranslatorRegistry;
  7701. TagAliasRegistry m_tagAliasRegistry;
  7702. StartupExceptionRegistry m_exceptionRegistry;
  7703. };
  7704. }
  7705. using RegistryHubSingleton = Singleton<RegistryHub, IRegistryHub, IMutableRegistryHub>;
  7706. IRegistryHub const& getRegistryHub() {
  7707. return RegistryHubSingleton::get();
  7708. }
  7709. IMutableRegistryHub& getMutableRegistryHub() {
  7710. return RegistryHubSingleton::getMutable();
  7711. }
  7712. void cleanUp() {
  7713. cleanupSingletons();
  7714. cleanUpContext();
  7715. }
  7716. std::string translateActiveException() {
  7717. return getRegistryHub().getExceptionTranslatorRegistry().translateActiveException();
  7718. }
  7719. } // end namespace Catch
  7720. // end catch_registry_hub.cpp
  7721. // start catch_reporter_registry.cpp
  7722. namespace Catch {
  7723. ReporterRegistry::~ReporterRegistry() = default;
  7724. IStreamingReporterPtr ReporterRegistry::create( std::string const& name, IConfigPtr const& config ) const {
  7725. auto it = m_factories.find( name );
  7726. if( it == m_factories.end() )
  7727. return nullptr;
  7728. return it->second->create( ReporterConfig( config ) );
  7729. }
  7730. void ReporterRegistry::registerReporter( std::string const& name, IReporterFactoryPtr const& factory ) {
  7731. m_factories.emplace(name, factory);
  7732. }
  7733. void ReporterRegistry::registerListener( IReporterFactoryPtr const& factory ) {
  7734. m_listeners.push_back( factory );
  7735. }
  7736. IReporterRegistry::FactoryMap const& ReporterRegistry::getFactories() const {
  7737. return m_factories;
  7738. }
  7739. IReporterRegistry::Listeners const& ReporterRegistry::getListeners() const {
  7740. return m_listeners;
  7741. }
  7742. }
  7743. // end catch_reporter_registry.cpp
  7744. // start catch_result_type.cpp
  7745. namespace Catch {
  7746. bool isOk( ResultWas::OfType resultType ) {
  7747. return ( resultType & ResultWas::FailureBit ) == 0;
  7748. }
  7749. bool isJustInfo( int flags ) {
  7750. return flags == ResultWas::Info;
  7751. }
  7752. ResultDisposition::Flags operator | ( ResultDisposition::Flags lhs, ResultDisposition::Flags rhs ) {
  7753. return static_cast<ResultDisposition::Flags>( static_cast<int>( lhs ) | static_cast<int>( rhs ) );
  7754. }
  7755. bool shouldContinueOnFailure( int flags ) { return ( flags & ResultDisposition::ContinueOnFailure ) != 0; }
  7756. bool shouldSuppressFailure( int flags ) { return ( flags & ResultDisposition::SuppressFail ) != 0; }
  7757. } // end namespace Catch
  7758. // end catch_result_type.cpp
  7759. // start catch_run_context.cpp
  7760. #include <cassert>
  7761. #include <algorithm>
  7762. #include <sstream>
  7763. namespace Catch {
  7764. namespace Generators {
  7765. struct GeneratorTracker : TestCaseTracking::TrackerBase, IGeneratorTracker {
  7766. size_t m_index = static_cast<size_t>( -1 );
  7767. GeneratorBasePtr m_generator;
  7768. GeneratorTracker( TestCaseTracking::NameAndLocation const& nameAndLocation, TrackerContext& ctx, ITracker* parent )
  7769. : TrackerBase( nameAndLocation, ctx, parent )
  7770. {}
  7771. ~GeneratorTracker();
  7772. static GeneratorTracker& acquire( TrackerContext& ctx, TestCaseTracking::NameAndLocation const& nameAndLocation ) {
  7773. std::shared_ptr<GeneratorTracker> tracker;
  7774. ITracker& currentTracker = ctx.currentTracker();
  7775. if( TestCaseTracking::ITrackerPtr childTracker = currentTracker.findChild( nameAndLocation ) ) {
  7776. assert( childTracker );
  7777. assert( childTracker->isIndexTracker() );
  7778. tracker = std::static_pointer_cast<GeneratorTracker>( childTracker );
  7779. }
  7780. else {
  7781. tracker = std::make_shared<GeneratorTracker>( nameAndLocation, ctx, &currentTracker );
  7782. currentTracker.addChild( tracker );
  7783. }
  7784. if( !ctx.completedCycle() && !tracker->isComplete() ) {
  7785. if( tracker->m_runState != ExecutingChildren && tracker->m_runState != NeedsAnotherRun )
  7786. tracker->moveNext();
  7787. tracker->open();
  7788. }
  7789. return *tracker;
  7790. }
  7791. void moveNext() {
  7792. m_index++;
  7793. m_children.clear();
  7794. }
  7795. // TrackerBase interface
  7796. bool isIndexTracker() const override { return true; }
  7797. auto hasGenerator() const -> bool override {
  7798. return !!m_generator;
  7799. }
  7800. void close() override {
  7801. TrackerBase::close();
  7802. if( m_runState == CompletedSuccessfully && m_index < m_generator->size()-1 )
  7803. m_runState = Executing;
  7804. }
  7805. // IGeneratorTracker interface
  7806. auto getGenerator() const -> GeneratorBasePtr const& override {
  7807. return m_generator;
  7808. }
  7809. void setGenerator( GeneratorBasePtr&& generator ) override {
  7810. m_generator = std::move( generator );
  7811. }
  7812. auto getIndex() const -> size_t override {
  7813. return m_index;
  7814. }
  7815. };
  7816. GeneratorTracker::~GeneratorTracker() {}
  7817. }
  7818. RunContext::RunContext(IConfigPtr const& _config, IStreamingReporterPtr&& reporter)
  7819. : m_runInfo(_config->name()),
  7820. m_context(getCurrentMutableContext()),
  7821. m_config(_config),
  7822. m_reporter(std::move(reporter)),
  7823. m_lastAssertionInfo{ StringRef(), SourceLineInfo("",0), StringRef(), ResultDisposition::Normal },
  7824. m_includeSuccessfulResults( m_config->includeSuccessfulResults() || m_reporter->getPreferences().shouldReportAllAssertions )
  7825. {
  7826. m_context.setRunner(this);
  7827. m_context.setConfig(m_config);
  7828. m_context.setResultCapture(this);
  7829. m_reporter->testRunStarting(m_runInfo);
  7830. }
  7831. RunContext::~RunContext() {
  7832. m_reporter->testRunEnded(TestRunStats(m_runInfo, m_totals, aborting()));
  7833. }
  7834. void RunContext::testGroupStarting(std::string const& testSpec, std::size_t groupIndex, std::size_t groupsCount) {
  7835. m_reporter->testGroupStarting(GroupInfo(testSpec, groupIndex, groupsCount));
  7836. }
  7837. void RunContext::testGroupEnded(std::string const& testSpec, Totals const& totals, std::size_t groupIndex, std::size_t groupsCount) {
  7838. m_reporter->testGroupEnded(TestGroupStats(GroupInfo(testSpec, groupIndex, groupsCount), totals, aborting()));
  7839. }
  7840. Totals RunContext::runTest(TestCase const& testCase) {
  7841. Totals prevTotals = m_totals;
  7842. std::string redirectedCout;
  7843. std::string redirectedCerr;
  7844. auto const& testInfo = testCase.getTestCaseInfo();
  7845. m_reporter->testCaseStarting(testInfo);
  7846. m_activeTestCase = &testCase;
  7847. ITracker& rootTracker = m_trackerContext.startRun();
  7848. assert(rootTracker.isSectionTracker());
  7849. static_cast<SectionTracker&>(rootTracker).addInitialFilters(m_config->getSectionsToRun());
  7850. do {
  7851. m_trackerContext.startCycle();
  7852. m_testCaseTracker = &SectionTracker::acquire(m_trackerContext, TestCaseTracking::NameAndLocation(testInfo.name, testInfo.lineInfo));
  7853. runCurrentTest(redirectedCout, redirectedCerr);
  7854. } while (!m_testCaseTracker->isSuccessfullyCompleted() && !aborting());
  7855. Totals deltaTotals = m_totals.delta(prevTotals);
  7856. if (testInfo.expectedToFail() && deltaTotals.testCases.passed > 0) {
  7857. deltaTotals.assertions.failed++;
  7858. deltaTotals.testCases.passed--;
  7859. deltaTotals.testCases.failed++;
  7860. }
  7861. m_totals.testCases += deltaTotals.testCases;
  7862. m_reporter->testCaseEnded(TestCaseStats(testInfo,
  7863. deltaTotals,
  7864. redirectedCout,
  7865. redirectedCerr,
  7866. aborting()));
  7867. m_activeTestCase = nullptr;
  7868. m_testCaseTracker = nullptr;
  7869. return deltaTotals;
  7870. }
  7871. IConfigPtr RunContext::config() const {
  7872. return m_config;
  7873. }
  7874. IStreamingReporter& RunContext::reporter() const {
  7875. return *m_reporter;
  7876. }
  7877. void RunContext::assertionEnded(AssertionResult const & result) {
  7878. if (result.getResultType() == ResultWas::Ok) {
  7879. m_totals.assertions.passed++;
  7880. m_lastAssertionPassed = true;
  7881. } else if (!result.isOk()) {
  7882. m_lastAssertionPassed = false;
  7883. if( m_activeTestCase->getTestCaseInfo().okToFail() )
  7884. m_totals.assertions.failedButOk++;
  7885. else
  7886. m_totals.assertions.failed++;
  7887. }
  7888. else {
  7889. m_lastAssertionPassed = true;
  7890. }
  7891. // We have no use for the return value (whether messages should be cleared), because messages were made scoped
  7892. // and should be let to clear themselves out.
  7893. static_cast<void>(m_reporter->assertionEnded(AssertionStats(result, m_messages, m_totals)));
  7894. // Reset working state
  7895. resetAssertionInfo();
  7896. m_lastResult = result;
  7897. }
  7898. void RunContext::resetAssertionInfo() {
  7899. m_lastAssertionInfo.macroName = StringRef();
  7900. m_lastAssertionInfo.capturedExpression = "{Unknown expression after the reported line}"_sr;
  7901. }
  7902. bool RunContext::sectionStarted(SectionInfo const & sectionInfo, Counts & assertions) {
  7903. ITracker& sectionTracker = SectionTracker::acquire(m_trackerContext, TestCaseTracking::NameAndLocation(sectionInfo.name, sectionInfo.lineInfo));
  7904. if (!sectionTracker.isOpen())
  7905. return false;
  7906. m_activeSections.push_back(&sectionTracker);
  7907. m_lastAssertionInfo.lineInfo = sectionInfo.lineInfo;
  7908. m_reporter->sectionStarting(sectionInfo);
  7909. assertions = m_totals.assertions;
  7910. return true;
  7911. }
  7912. auto RunContext::acquireGeneratorTracker( SourceLineInfo const& lineInfo ) -> IGeneratorTracker& {
  7913. using namespace Generators;
  7914. GeneratorTracker& tracker = GeneratorTracker::acquire( m_trackerContext, TestCaseTracking::NameAndLocation( "generator", lineInfo ) );
  7915. assert( tracker.isOpen() );
  7916. m_lastAssertionInfo.lineInfo = lineInfo;
  7917. return tracker;
  7918. }
  7919. bool RunContext::testForMissingAssertions(Counts& assertions) {
  7920. if (assertions.total() != 0)
  7921. return false;
  7922. if (!m_config->warnAboutMissingAssertions())
  7923. return false;
  7924. if (m_trackerContext.currentTracker().hasChildren())
  7925. return false;
  7926. m_totals.assertions.failed++;
  7927. assertions.failed++;
  7928. return true;
  7929. }
  7930. void RunContext::sectionEnded(SectionEndInfo const & endInfo) {
  7931. Counts assertions = m_totals.assertions - endInfo.prevAssertions;
  7932. bool missingAssertions = testForMissingAssertions(assertions);
  7933. if (!m_activeSections.empty()) {
  7934. m_activeSections.back()->close();
  7935. m_activeSections.pop_back();
  7936. }
  7937. m_reporter->sectionEnded(SectionStats(endInfo.sectionInfo, assertions, endInfo.durationInSeconds, missingAssertions));
  7938. m_messages.clear();
  7939. }
  7940. void RunContext::sectionEndedEarly(SectionEndInfo const & endInfo) {
  7941. if (m_unfinishedSections.empty())
  7942. m_activeSections.back()->fail();
  7943. else
  7944. m_activeSections.back()->close();
  7945. m_activeSections.pop_back();
  7946. m_unfinishedSections.push_back(endInfo);
  7947. }
  7948. void RunContext::benchmarkStarting( BenchmarkInfo const& info ) {
  7949. m_reporter->benchmarkStarting( info );
  7950. }
  7951. void RunContext::benchmarkEnded( BenchmarkStats const& stats ) {
  7952. m_reporter->benchmarkEnded( stats );
  7953. }
  7954. void RunContext::pushScopedMessage(MessageInfo const & message) {
  7955. m_messages.push_back(message);
  7956. }
  7957. void RunContext::popScopedMessage(MessageInfo const & message) {
  7958. m_messages.erase(std::remove(m_messages.begin(), m_messages.end(), message), m_messages.end());
  7959. }
  7960. std::string RunContext::getCurrentTestName() const {
  7961. return m_activeTestCase
  7962. ? m_activeTestCase->getTestCaseInfo().name
  7963. : std::string();
  7964. }
  7965. const AssertionResult * RunContext::getLastResult() const {
  7966. return &(*m_lastResult);
  7967. }
  7968. void RunContext::exceptionEarlyReported() {
  7969. m_shouldReportUnexpected = false;
  7970. }
  7971. void RunContext::handleFatalErrorCondition( StringRef message ) {
  7972. // First notify reporter that bad things happened
  7973. m_reporter->fatalErrorEncountered(message);
  7974. // Don't rebuild the result -- the stringification itself can cause more fatal errors
  7975. // Instead, fake a result data.
  7976. AssertionResultData tempResult( ResultWas::FatalErrorCondition, { false } );
  7977. tempResult.message = message;
  7978. AssertionResult result(m_lastAssertionInfo, tempResult);
  7979. assertionEnded(result);
  7980. handleUnfinishedSections();
  7981. // Recreate section for test case (as we will lose the one that was in scope)
  7982. auto const& testCaseInfo = m_activeTestCase->getTestCaseInfo();
  7983. SectionInfo testCaseSection(testCaseInfo.lineInfo, testCaseInfo.name);
  7984. Counts assertions;
  7985. assertions.failed = 1;
  7986. SectionStats testCaseSectionStats(testCaseSection, assertions, 0, false);
  7987. m_reporter->sectionEnded(testCaseSectionStats);
  7988. auto const& testInfo = m_activeTestCase->getTestCaseInfo();
  7989. Totals deltaTotals;
  7990. deltaTotals.testCases.failed = 1;
  7991. deltaTotals.assertions.failed = 1;
  7992. m_reporter->testCaseEnded(TestCaseStats(testInfo,
  7993. deltaTotals,
  7994. std::string(),
  7995. std::string(),
  7996. false));
  7997. m_totals.testCases.failed++;
  7998. testGroupEnded(std::string(), m_totals, 1, 1);
  7999. m_reporter->testRunEnded(TestRunStats(m_runInfo, m_totals, false));
  8000. }
  8001. bool RunContext::lastAssertionPassed() {
  8002. return m_lastAssertionPassed;
  8003. }
  8004. void RunContext::assertionPassed() {
  8005. m_lastAssertionPassed = true;
  8006. ++m_totals.assertions.passed;
  8007. resetAssertionInfo();
  8008. }
  8009. bool RunContext::aborting() const {
  8010. return m_totals.assertions.failed >= static_cast<std::size_t>(m_config->abortAfter());
  8011. }
  8012. void RunContext::runCurrentTest(std::string & redirectedCout, std::string & redirectedCerr) {
  8013. auto const& testCaseInfo = m_activeTestCase->getTestCaseInfo();
  8014. SectionInfo testCaseSection(testCaseInfo.lineInfo, testCaseInfo.name);
  8015. m_reporter->sectionStarting(testCaseSection);
  8016. Counts prevAssertions = m_totals.assertions;
  8017. double duration = 0;
  8018. m_shouldReportUnexpected = true;
  8019. m_lastAssertionInfo = { "TEST_CASE"_sr, testCaseInfo.lineInfo, StringRef(), ResultDisposition::Normal };
  8020. seedRng(*m_config);
  8021. Timer timer;
  8022. CATCH_TRY {
  8023. if (m_reporter->getPreferences().shouldRedirectStdOut) {
  8024. #if !defined(CATCH_CONFIG_EXPERIMENTAL_REDIRECT)
  8025. RedirectedStdOut redirectedStdOut;
  8026. RedirectedStdErr redirectedStdErr;
  8027. timer.start();
  8028. invokeActiveTestCase();
  8029. redirectedCout += redirectedStdOut.str();
  8030. redirectedCerr += redirectedStdErr.str();
  8031. #else
  8032. OutputRedirect r(redirectedCout, redirectedCerr);
  8033. timer.start();
  8034. invokeActiveTestCase();
  8035. #endif
  8036. } else {
  8037. timer.start();
  8038. invokeActiveTestCase();
  8039. }
  8040. duration = timer.getElapsedSeconds();
  8041. } CATCH_CATCH_ANON (TestFailureException&) {
  8042. // This just means the test was aborted due to failure
  8043. } CATCH_CATCH_ALL {
  8044. // Under CATCH_CONFIG_FAST_COMPILE, unexpected exceptions under REQUIRE assertions
  8045. // are reported without translation at the point of origin.
  8046. if( m_shouldReportUnexpected ) {
  8047. AssertionReaction dummyReaction;
  8048. handleUnexpectedInflightException( m_lastAssertionInfo, translateActiveException(), dummyReaction );
  8049. }
  8050. }
  8051. Counts assertions = m_totals.assertions - prevAssertions;
  8052. bool missingAssertions = testForMissingAssertions(assertions);
  8053. m_testCaseTracker->close();
  8054. handleUnfinishedSections();
  8055. m_messages.clear();
  8056. SectionStats testCaseSectionStats(testCaseSection, assertions, duration, missingAssertions);
  8057. m_reporter->sectionEnded(testCaseSectionStats);
  8058. }
  8059. void RunContext::invokeActiveTestCase() {
  8060. FatalConditionHandler fatalConditionHandler; // Handle signals
  8061. m_activeTestCase->invoke();
  8062. fatalConditionHandler.reset();
  8063. }
  8064. void RunContext::handleUnfinishedSections() {
  8065. // If sections ended prematurely due to an exception we stored their
  8066. // infos here so we can tear them down outside the unwind process.
  8067. for (auto it = m_unfinishedSections.rbegin(),
  8068. itEnd = m_unfinishedSections.rend();
  8069. it != itEnd;
  8070. ++it)
  8071. sectionEnded(*it);
  8072. m_unfinishedSections.clear();
  8073. }
  8074. void RunContext::handleExpr(
  8075. AssertionInfo const& info,
  8076. ITransientExpression const& expr,
  8077. AssertionReaction& reaction
  8078. ) {
  8079. m_reporter->assertionStarting( info );
  8080. bool negated = isFalseTest( info.resultDisposition );
  8081. bool result = expr.getResult() != negated;
  8082. if( result ) {
  8083. if (!m_includeSuccessfulResults) {
  8084. assertionPassed();
  8085. }
  8086. else {
  8087. reportExpr(info, ResultWas::Ok, &expr, negated);
  8088. }
  8089. }
  8090. else {
  8091. reportExpr(info, ResultWas::ExpressionFailed, &expr, negated );
  8092. populateReaction( reaction );
  8093. }
  8094. }
  8095. void RunContext::reportExpr(
  8096. AssertionInfo const &info,
  8097. ResultWas::OfType resultType,
  8098. ITransientExpression const *expr,
  8099. bool negated ) {
  8100. m_lastAssertionInfo = info;
  8101. AssertionResultData data( resultType, LazyExpression( negated ) );
  8102. AssertionResult assertionResult{ info, data };
  8103. assertionResult.m_resultData.lazyExpression.m_transientExpression = expr;
  8104. assertionEnded( assertionResult );
  8105. }
  8106. void RunContext::handleMessage(
  8107. AssertionInfo const& info,
  8108. ResultWas::OfType resultType,
  8109. StringRef const& message,
  8110. AssertionReaction& reaction
  8111. ) {
  8112. m_reporter->assertionStarting( info );
  8113. m_lastAssertionInfo = info;
  8114. AssertionResultData data( resultType, LazyExpression( false ) );
  8115. data.message = message;
  8116. AssertionResult assertionResult{ m_lastAssertionInfo, data };
  8117. assertionEnded( assertionResult );
  8118. if( !assertionResult.isOk() )
  8119. populateReaction( reaction );
  8120. }
  8121. void RunContext::handleUnexpectedExceptionNotThrown(
  8122. AssertionInfo const& info,
  8123. AssertionReaction& reaction
  8124. ) {
  8125. handleNonExpr(info, Catch::ResultWas::DidntThrowException, reaction);
  8126. }
  8127. void RunContext::handleUnexpectedInflightException(
  8128. AssertionInfo const& info,
  8129. std::string const& message,
  8130. AssertionReaction& reaction
  8131. ) {
  8132. m_lastAssertionInfo = info;
  8133. AssertionResultData data( ResultWas::ThrewException, LazyExpression( false ) );
  8134. data.message = message;
  8135. AssertionResult assertionResult{ info, data };
  8136. assertionEnded( assertionResult );
  8137. populateReaction( reaction );
  8138. }
  8139. void RunContext::populateReaction( AssertionReaction& reaction ) {
  8140. reaction.shouldDebugBreak = m_config->shouldDebugBreak();
  8141. reaction.shouldThrow = aborting() || (m_lastAssertionInfo.resultDisposition & ResultDisposition::Normal);
  8142. }
  8143. void RunContext::handleIncomplete(
  8144. AssertionInfo const& info
  8145. ) {
  8146. m_lastAssertionInfo = info;
  8147. AssertionResultData data( ResultWas::ThrewException, LazyExpression( false ) );
  8148. data.message = "Exception translation was disabled by CATCH_CONFIG_FAST_COMPILE";
  8149. AssertionResult assertionResult{ info, data };
  8150. assertionEnded( assertionResult );
  8151. }
  8152. void RunContext::handleNonExpr(
  8153. AssertionInfo const &info,
  8154. ResultWas::OfType resultType,
  8155. AssertionReaction &reaction
  8156. ) {
  8157. m_lastAssertionInfo = info;
  8158. AssertionResultData data( resultType, LazyExpression( false ) );
  8159. AssertionResult assertionResult{ info, data };
  8160. assertionEnded( assertionResult );
  8161. if( !assertionResult.isOk() )
  8162. populateReaction( reaction );
  8163. }
  8164. IResultCapture& getResultCapture() {
  8165. if (auto* capture = getCurrentContext().getResultCapture())
  8166. return *capture;
  8167. else
  8168. CATCH_INTERNAL_ERROR("No result capture instance");
  8169. }
  8170. }
  8171. // end catch_run_context.cpp
  8172. // start catch_section.cpp
  8173. namespace Catch {
  8174. Section::Section( SectionInfo const& info )
  8175. : m_info( info ),
  8176. m_sectionIncluded( getResultCapture().sectionStarted( m_info, m_assertions ) )
  8177. {
  8178. m_timer.start();
  8179. }
  8180. Section::~Section() {
  8181. if( m_sectionIncluded ) {
  8182. SectionEndInfo endInfo{ m_info, m_assertions, m_timer.getElapsedSeconds() };
  8183. if( uncaught_exceptions() )
  8184. getResultCapture().sectionEndedEarly( endInfo );
  8185. else
  8186. getResultCapture().sectionEnded( endInfo );
  8187. }
  8188. }
  8189. // This indicates whether the section should be executed or not
  8190. Section::operator bool() const {
  8191. return m_sectionIncluded;
  8192. }
  8193. } // end namespace Catch
  8194. // end catch_section.cpp
  8195. // start catch_section_info.cpp
  8196. namespace Catch {
  8197. SectionInfo::SectionInfo
  8198. ( SourceLineInfo const& _lineInfo,
  8199. std::string const& _name )
  8200. : name( _name ),
  8201. lineInfo( _lineInfo )
  8202. {}
  8203. } // end namespace Catch
  8204. // end catch_section_info.cpp
  8205. // start catch_session.cpp
  8206. // start catch_session.h
  8207. #include <memory>
  8208. namespace Catch {
  8209. class Session : NonCopyable {
  8210. public:
  8211. Session();
  8212. ~Session() override;
  8213. void showHelp() const;
  8214. void libIdentify();
  8215. int applyCommandLine( int argc, char const * const * argv );
  8216. #if defined(CATCH_CONFIG_WCHAR) && defined(WIN32) && defined(UNICODE)
  8217. int applyCommandLine( int argc, wchar_t const * const * argv );
  8218. #endif
  8219. void useConfigData( ConfigData const& configData );
  8220. template<typename CharT>
  8221. int run(int argc, CharT const * const argv[]) {
  8222. if (m_startupExceptions)
  8223. return 1;
  8224. int returnCode = applyCommandLine(argc, argv);
  8225. if (returnCode == 0)
  8226. returnCode = run();
  8227. return returnCode;
  8228. }
  8229. int run();
  8230. clara::Parser const& cli() const;
  8231. void cli( clara::Parser const& newParser );
  8232. ConfigData& configData();
  8233. Config& config();
  8234. private:
  8235. int runInternal();
  8236. clara::Parser m_cli;
  8237. ConfigData m_configData;
  8238. std::shared_ptr<Config> m_config;
  8239. bool m_startupExceptions = false;
  8240. };
  8241. } // end namespace Catch
  8242. // end catch_session.h
  8243. // start catch_version.h
  8244. #include <iosfwd>
  8245. namespace Catch {
  8246. // Versioning information
  8247. struct Version {
  8248. Version( Version const& ) = delete;
  8249. Version& operator=( Version const& ) = delete;
  8250. Version( unsigned int _majorVersion,
  8251. unsigned int _minorVersion,
  8252. unsigned int _patchNumber,
  8253. char const * const _branchName,
  8254. unsigned int _buildNumber );
  8255. unsigned int const majorVersion;
  8256. unsigned int const minorVersion;
  8257. unsigned int const patchNumber;
  8258. // buildNumber is only used if branchName is not null
  8259. char const * const branchName;
  8260. unsigned int const buildNumber;
  8261. friend std::ostream& operator << ( std::ostream& os, Version const& version );
  8262. };
  8263. Version const& libraryVersion();
  8264. }
  8265. // end catch_version.h
  8266. #include <cstdlib>
  8267. #include <iomanip>
  8268. namespace Catch {
  8269. namespace {
  8270. const int MaxExitCode = 255;
  8271. IStreamingReporterPtr createReporter(std::string const& reporterName, IConfigPtr const& config) {
  8272. auto reporter = Catch::getRegistryHub().getReporterRegistry().create(reporterName, config);
  8273. CATCH_ENFORCE(reporter, "No reporter registered with name: '" << reporterName << "'");
  8274. return reporter;
  8275. }
  8276. IStreamingReporterPtr makeReporter(std::shared_ptr<Config> const& config) {
  8277. if (Catch::getRegistryHub().getReporterRegistry().getListeners().empty()) {
  8278. return createReporter(config->getReporterName(), config);
  8279. }
  8280. auto multi = std::unique_ptr<ListeningReporter>(new ListeningReporter);
  8281. auto const& listeners = Catch::getRegistryHub().getReporterRegistry().getListeners();
  8282. for (auto const& listener : listeners) {
  8283. multi->addListener(listener->create(Catch::ReporterConfig(config)));
  8284. }
  8285. multi->addReporter(createReporter(config->getReporterName(), config));
  8286. return std::move(multi);
  8287. }
  8288. Catch::Totals runTests(std::shared_ptr<Config> const& config) {
  8289. auto reporter = makeReporter(config);
  8290. RunContext context(config, std::move(reporter));
  8291. Totals totals;
  8292. context.testGroupStarting(config->name(), 1, 1);
  8293. TestSpec testSpec = config->testSpec();
  8294. auto const& allTestCases = getAllTestCasesSorted(*config);
  8295. for (auto const& testCase : allTestCases) {
  8296. if (!context.aborting() && matchTest(testCase, testSpec, *config))
  8297. totals += context.runTest(testCase);
  8298. else
  8299. context.reporter().skipTest(testCase);
  8300. }
  8301. if (config->warnAboutNoTests() && totals.testCases.total() == 0) {
  8302. ReusableStringStream testConfig;
  8303. bool first = true;
  8304. for (const auto& input : config->getTestsOrTags()) {
  8305. if (!first) { testConfig << ' '; }
  8306. first = false;
  8307. testConfig << input;
  8308. }
  8309. context.reporter().noMatchingTestCases(testConfig.str());
  8310. totals.error = -1;
  8311. }
  8312. context.testGroupEnded(config->name(), totals, 1, 1);
  8313. return totals;
  8314. }
  8315. void applyFilenamesAsTags(Catch::IConfig const& config) {
  8316. auto& tests = const_cast<std::vector<TestCase>&>(getAllTestCasesSorted(config));
  8317. for (auto& testCase : tests) {
  8318. auto tags = testCase.tags;
  8319. std::string filename = testCase.lineInfo.file;
  8320. auto lastSlash = filename.find_last_of("\\/");
  8321. if (lastSlash != std::string::npos) {
  8322. filename.erase(0, lastSlash);
  8323. filename[0] = '#';
  8324. }
  8325. auto lastDot = filename.find_last_of('.');
  8326. if (lastDot != std::string::npos) {
  8327. filename.erase(lastDot);
  8328. }
  8329. tags.push_back(std::move(filename));
  8330. setTags(testCase, tags);
  8331. }
  8332. }
  8333. } // anon namespace
  8334. Session::Session() {
  8335. static bool alreadyInstantiated = false;
  8336. if( alreadyInstantiated ) {
  8337. CATCH_TRY { CATCH_INTERNAL_ERROR( "Only one instance of Catch::Session can ever be used" ); }
  8338. CATCH_CATCH_ALL { getMutableRegistryHub().registerStartupException(); }
  8339. }
  8340. // There cannot be exceptions at startup in no-exception mode.
  8341. #if !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
  8342. const auto& exceptions = getRegistryHub().getStartupExceptionRegistry().getExceptions();
  8343. if ( !exceptions.empty() ) {
  8344. m_startupExceptions = true;
  8345. Colour colourGuard( Colour::Red );
  8346. Catch::cerr() << "Errors occurred during startup!" << '\n';
  8347. // iterate over all exceptions and notify user
  8348. for ( const auto& ex_ptr : exceptions ) {
  8349. try {
  8350. std::rethrow_exception(ex_ptr);
  8351. } catch ( std::exception const& ex ) {
  8352. Catch::cerr() << Column( ex.what() ).indent(2) << '\n';
  8353. }
  8354. }
  8355. }
  8356. #endif
  8357. alreadyInstantiated = true;
  8358. m_cli = makeCommandLineParser( m_configData );
  8359. }
  8360. Session::~Session() {
  8361. Catch::cleanUp();
  8362. }
  8363. void Session::showHelp() const {
  8364. Catch::cout()
  8365. << "\nCatch v" << libraryVersion() << "\n"
  8366. << m_cli << std::endl
  8367. << "For more detailed usage please see the project docs\n" << std::endl;
  8368. }
  8369. void Session::libIdentify() {
  8370. Catch::cout()
  8371. << std::left << std::setw(16) << "description: " << "A Catch test executable\n"
  8372. << std::left << std::setw(16) << "category: " << "testframework\n"
  8373. << std::left << std::setw(16) << "framework: " << "Catch Test\n"
  8374. << std::left << std::setw(16) << "version: " << libraryVersion() << std::endl;
  8375. }
  8376. int Session::applyCommandLine( int argc, char const * const * argv ) {
  8377. if( m_startupExceptions )
  8378. return 1;
  8379. auto result = m_cli.parse( clara::Args( argc, argv ) );
  8380. if( !result ) {
  8381. Catch::cerr()
  8382. << Colour( Colour::Red )
  8383. << "\nError(s) in input:\n"
  8384. << Column( result.errorMessage() ).indent( 2 )
  8385. << "\n\n";
  8386. Catch::cerr() << "Run with -? for usage\n" << std::endl;
  8387. return MaxExitCode;
  8388. }
  8389. if( m_configData.showHelp )
  8390. showHelp();
  8391. if( m_configData.libIdentify )
  8392. libIdentify();
  8393. m_config.reset();
  8394. return 0;
  8395. }
  8396. #if defined(CATCH_CONFIG_WCHAR) && defined(WIN32) && defined(UNICODE)
  8397. int Session::applyCommandLine( int argc, wchar_t const * const * argv ) {
  8398. char **utf8Argv = new char *[ argc ];
  8399. for ( int i = 0; i < argc; ++i ) {
  8400. int bufSize = WideCharToMultiByte( CP_UTF8, 0, argv[i], -1, NULL, 0, NULL, NULL );
  8401. utf8Argv[ i ] = new char[ bufSize ];
  8402. WideCharToMultiByte( CP_UTF8, 0, argv[i], -1, utf8Argv[i], bufSize, NULL, NULL );
  8403. }
  8404. int returnCode = applyCommandLine( argc, utf8Argv );
  8405. for ( int i = 0; i < argc; ++i )
  8406. delete [] utf8Argv[ i ];
  8407. delete [] utf8Argv;
  8408. return returnCode;
  8409. }
  8410. #endif
  8411. void Session::useConfigData( ConfigData const& configData ) {
  8412. m_configData = configData;
  8413. m_config.reset();
  8414. }
  8415. int Session::run() {
  8416. if( ( m_configData.waitForKeypress & WaitForKeypress::BeforeStart ) != 0 ) {
  8417. Catch::cout() << "...waiting for enter/ return before starting" << std::endl;
  8418. static_cast<void>(std::getchar());
  8419. }
  8420. int exitCode = runInternal();
  8421. if( ( m_configData.waitForKeypress & WaitForKeypress::BeforeExit ) != 0 ) {
  8422. Catch::cout() << "...waiting for enter/ return before exiting, with code: " << exitCode << std::endl;
  8423. static_cast<void>(std::getchar());
  8424. }
  8425. return exitCode;
  8426. }
  8427. clara::Parser const& Session::cli() const {
  8428. return m_cli;
  8429. }
  8430. void Session::cli( clara::Parser const& newParser ) {
  8431. m_cli = newParser;
  8432. }
  8433. ConfigData& Session::configData() {
  8434. return m_configData;
  8435. }
  8436. Config& Session::config() {
  8437. if( !m_config )
  8438. m_config = std::make_shared<Config>( m_configData );
  8439. return *m_config;
  8440. }
  8441. int Session::runInternal() {
  8442. if( m_startupExceptions )
  8443. return 1;
  8444. if (m_configData.showHelp || m_configData.libIdentify) {
  8445. return 0;
  8446. }
  8447. CATCH_TRY {
  8448. config(); // Force config to be constructed
  8449. seedRng( *m_config );
  8450. if( m_configData.filenamesAsTags )
  8451. applyFilenamesAsTags( *m_config );
  8452. // Handle list request
  8453. if( Option<std::size_t> listed = list( config() ) )
  8454. return static_cast<int>( *listed );
  8455. auto totals = runTests( m_config );
  8456. // Note that on unices only the lower 8 bits are usually used, clamping
  8457. // the return value to 255 prevents false negative when some multiple
  8458. // of 256 tests has failed
  8459. return (std::min) (MaxExitCode, (std::max) (totals.error, static_cast<int>(totals.assertions.failed)));
  8460. }
  8461. #if !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
  8462. catch( std::exception& ex ) {
  8463. Catch::cerr() << ex.what() << std::endl;
  8464. return MaxExitCode;
  8465. }
  8466. #endif
  8467. }
  8468. } // end namespace Catch
  8469. // end catch_session.cpp
  8470. // start catch_singletons.cpp
  8471. #include <vector>
  8472. namespace Catch {
  8473. namespace {
  8474. static auto getSingletons() -> std::vector<ISingleton*>*& {
  8475. static std::vector<ISingleton*>* g_singletons = nullptr;
  8476. if( !g_singletons )
  8477. g_singletons = new std::vector<ISingleton*>();
  8478. return g_singletons;
  8479. }
  8480. }
  8481. ISingleton::~ISingleton() {}
  8482. void addSingleton(ISingleton* singleton ) {
  8483. getSingletons()->push_back( singleton );
  8484. }
  8485. void cleanupSingletons() {
  8486. auto& singletons = getSingletons();
  8487. for( auto singleton : *singletons )
  8488. delete singleton;
  8489. delete singletons;
  8490. singletons = nullptr;
  8491. }
  8492. } // namespace Catch
  8493. // end catch_singletons.cpp
  8494. // start catch_startup_exception_registry.cpp
  8495. namespace Catch {
  8496. void StartupExceptionRegistry::add( std::exception_ptr const& exception ) noexcept {
  8497. CATCH_TRY {
  8498. m_exceptions.push_back(exception);
  8499. } CATCH_CATCH_ALL {
  8500. // If we run out of memory during start-up there's really not a lot more we can do about it
  8501. std::terminate();
  8502. }
  8503. }
  8504. std::vector<std::exception_ptr> const& StartupExceptionRegistry::getExceptions() const noexcept {
  8505. return m_exceptions;
  8506. }
  8507. } // end namespace Catch
  8508. // end catch_startup_exception_registry.cpp
  8509. // start catch_stream.cpp
  8510. #include <cstdio>
  8511. #include <iostream>
  8512. #include <fstream>
  8513. #include <sstream>
  8514. #include <vector>
  8515. #include <memory>
  8516. namespace Catch {
  8517. Catch::IStream::~IStream() = default;
  8518. namespace detail { namespace {
  8519. template<typename WriterF, std::size_t bufferSize=256>
  8520. class StreamBufImpl : public std::streambuf {
  8521. char data[bufferSize];
  8522. WriterF m_writer;
  8523. public:
  8524. StreamBufImpl() {
  8525. setp( data, data + sizeof(data) );
  8526. }
  8527. ~StreamBufImpl() noexcept {
  8528. StreamBufImpl::sync();
  8529. }
  8530. private:
  8531. int overflow( int c ) override {
  8532. sync();
  8533. if( c != EOF ) {
  8534. if( pbase() == epptr() )
  8535. m_writer( std::string( 1, static_cast<char>( c ) ) );
  8536. else
  8537. sputc( static_cast<char>( c ) );
  8538. }
  8539. return 0;
  8540. }
  8541. int sync() override {
  8542. if( pbase() != pptr() ) {
  8543. m_writer( std::string( pbase(), static_cast<std::string::size_type>( pptr() - pbase() ) ) );
  8544. setp( pbase(), epptr() );
  8545. }
  8546. return 0;
  8547. }
  8548. };
  8549. ///////////////////////////////////////////////////////////////////////////
  8550. struct OutputDebugWriter {
  8551. void operator()( std::string const&str ) {
  8552. writeToDebugConsole( str );
  8553. }
  8554. };
  8555. ///////////////////////////////////////////////////////////////////////////
  8556. class FileStream : public IStream {
  8557. mutable std::ofstream m_ofs;
  8558. public:
  8559. FileStream( StringRef filename ) {
  8560. m_ofs.open( filename.c_str() );
  8561. CATCH_ENFORCE( !m_ofs.fail(), "Unable to open file: '" << filename << "'" );
  8562. }
  8563. ~FileStream() override = default;
  8564. public: // IStream
  8565. std::ostream& stream() const override {
  8566. return m_ofs;
  8567. }
  8568. };
  8569. ///////////////////////////////////////////////////////////////////////////
  8570. class CoutStream : public IStream {
  8571. mutable std::ostream m_os;
  8572. public:
  8573. // Store the streambuf from cout up-front because
  8574. // cout may get redirected when running tests
  8575. CoutStream() : m_os( Catch::cout().rdbuf() ) {}
  8576. ~CoutStream() override = default;
  8577. public: // IStream
  8578. std::ostream& stream() const override { return m_os; }
  8579. };
  8580. ///////////////////////////////////////////////////////////////////////////
  8581. class DebugOutStream : public IStream {
  8582. std::unique_ptr<StreamBufImpl<OutputDebugWriter>> m_streamBuf;
  8583. mutable std::ostream m_os;
  8584. public:
  8585. DebugOutStream()
  8586. : m_streamBuf( new StreamBufImpl<OutputDebugWriter>() ),
  8587. m_os( m_streamBuf.get() )
  8588. {}
  8589. ~DebugOutStream() override = default;
  8590. public: // IStream
  8591. std::ostream& stream() const override { return m_os; }
  8592. };
  8593. }} // namespace anon::detail
  8594. ///////////////////////////////////////////////////////////////////////////
  8595. auto makeStream( StringRef const &filename ) -> IStream const* {
  8596. if( filename.empty() )
  8597. return new detail::CoutStream();
  8598. else if( filename[0] == '%' ) {
  8599. if( filename == "%debug" )
  8600. return new detail::DebugOutStream();
  8601. else
  8602. CATCH_ERROR( "Unrecognised stream: '" << filename << "'" );
  8603. }
  8604. else
  8605. return new detail::FileStream( filename );
  8606. }
  8607. // This class encapsulates the idea of a pool of ostringstreams that can be reused.
  8608. struct StringStreams {
  8609. std::vector<std::unique_ptr<std::ostringstream>> m_streams;
  8610. std::vector<std::size_t> m_unused;
  8611. std::ostringstream m_referenceStream; // Used for copy state/ flags from
  8612. auto add() -> std::size_t {
  8613. if( m_unused.empty() ) {
  8614. m_streams.push_back( std::unique_ptr<std::ostringstream>( new std::ostringstream ) );
  8615. return m_streams.size()-1;
  8616. }
  8617. else {
  8618. auto index = m_unused.back();
  8619. m_unused.pop_back();
  8620. return index;
  8621. }
  8622. }
  8623. void release( std::size_t index ) {
  8624. m_streams[index]->copyfmt( m_referenceStream ); // Restore initial flags and other state
  8625. m_unused.push_back(index);
  8626. }
  8627. };
  8628. ReusableStringStream::ReusableStringStream()
  8629. : m_index( Singleton<StringStreams>::getMutable().add() ),
  8630. m_oss( Singleton<StringStreams>::getMutable().m_streams[m_index].get() )
  8631. {}
  8632. ReusableStringStream::~ReusableStringStream() {
  8633. static_cast<std::ostringstream*>( m_oss )->str("");
  8634. m_oss->clear();
  8635. Singleton<StringStreams>::getMutable().release( m_index );
  8636. }
  8637. auto ReusableStringStream::str() const -> std::string {
  8638. return static_cast<std::ostringstream*>( m_oss )->str();
  8639. }
  8640. ///////////////////////////////////////////////////////////////////////////
  8641. #ifndef CATCH_CONFIG_NOSTDOUT // If you #define this you must implement these functions
  8642. std::ostream& cout() { return std::cout; }
  8643. std::ostream& cerr() { return std::cerr; }
  8644. std::ostream& clog() { return std::clog; }
  8645. #endif
  8646. }
  8647. // end catch_stream.cpp
  8648. // start catch_string_manip.cpp
  8649. #include <algorithm>
  8650. #include <ostream>
  8651. #include <cstring>
  8652. #include <cctype>
  8653. namespace Catch {
  8654. namespace {
  8655. char toLowerCh(char c) {
  8656. return static_cast<char>( std::tolower( c ) );
  8657. }
  8658. }
  8659. bool startsWith( std::string const& s, std::string const& prefix ) {
  8660. return s.size() >= prefix.size() && std::equal(prefix.begin(), prefix.end(), s.begin());
  8661. }
  8662. bool startsWith( std::string const& s, char prefix ) {
  8663. return !s.empty() && s[0] == prefix;
  8664. }
  8665. bool endsWith( std::string const& s, std::string const& suffix ) {
  8666. return s.size() >= suffix.size() && std::equal(suffix.rbegin(), suffix.rend(), s.rbegin());
  8667. }
  8668. bool endsWith( std::string const& s, char suffix ) {
  8669. return !s.empty() && s[s.size()-1] == suffix;
  8670. }
  8671. bool contains( std::string const& s, std::string const& infix ) {
  8672. return s.find( infix ) != std::string::npos;
  8673. }
  8674. void toLowerInPlace( std::string& s ) {
  8675. std::transform( s.begin(), s.end(), s.begin(), toLowerCh );
  8676. }
  8677. std::string toLower( std::string const& s ) {
  8678. std::string lc = s;
  8679. toLowerInPlace( lc );
  8680. return lc;
  8681. }
  8682. std::string trim( std::string const& str ) {
  8683. static char const* whitespaceChars = "\n\r\t ";
  8684. std::string::size_type start = str.find_first_not_of( whitespaceChars );
  8685. std::string::size_type end = str.find_last_not_of( whitespaceChars );
  8686. return start != std::string::npos ? str.substr( start, 1+end-start ) : std::string();
  8687. }
  8688. bool replaceInPlace( std::string& str, std::string const& replaceThis, std::string const& withThis ) {
  8689. bool replaced = false;
  8690. std::size_t i = str.find( replaceThis );
  8691. while( i != std::string::npos ) {
  8692. replaced = true;
  8693. str = str.substr( 0, i ) + withThis + str.substr( i+replaceThis.size() );
  8694. if( i < str.size()-withThis.size() )
  8695. i = str.find( replaceThis, i+withThis.size() );
  8696. else
  8697. i = std::string::npos;
  8698. }
  8699. return replaced;
  8700. }
  8701. pluralise::pluralise( std::size_t count, std::string const& label )
  8702. : m_count( count ),
  8703. m_label( label )
  8704. {}
  8705. std::ostream& operator << ( std::ostream& os, pluralise const& pluraliser ) {
  8706. os << pluraliser.m_count << ' ' << pluraliser.m_label;
  8707. if( pluraliser.m_count != 1 )
  8708. os << 's';
  8709. return os;
  8710. }
  8711. }
  8712. // end catch_string_manip.cpp
  8713. // start catch_stringref.cpp
  8714. #if defined(__clang__)
  8715. # pragma clang diagnostic push
  8716. # pragma clang diagnostic ignored "-Wexit-time-destructors"
  8717. #endif
  8718. #include <ostream>
  8719. #include <cstring>
  8720. #include <cstdint>
  8721. namespace {
  8722. const uint32_t byte_2_lead = 0xC0;
  8723. const uint32_t byte_3_lead = 0xE0;
  8724. const uint32_t byte_4_lead = 0xF0;
  8725. }
  8726. namespace Catch {
  8727. StringRef::StringRef( char const* rawChars ) noexcept
  8728. : StringRef( rawChars, static_cast<StringRef::size_type>(std::strlen(rawChars) ) )
  8729. {}
  8730. StringRef::operator std::string() const {
  8731. return std::string( m_start, m_size );
  8732. }
  8733. void StringRef::swap( StringRef& other ) noexcept {
  8734. std::swap( m_start, other.m_start );
  8735. std::swap( m_size, other.m_size );
  8736. std::swap( m_data, other.m_data );
  8737. }
  8738. auto StringRef::c_str() const -> char const* {
  8739. if( isSubstring() )
  8740. const_cast<StringRef*>( this )->takeOwnership();
  8741. return m_start;
  8742. }
  8743. auto StringRef::currentData() const noexcept -> char const* {
  8744. return m_start;
  8745. }
  8746. auto StringRef::isOwned() const noexcept -> bool {
  8747. return m_data != nullptr;
  8748. }
  8749. auto StringRef::isSubstring() const noexcept -> bool {
  8750. return m_start[m_size] != '\0';
  8751. }
  8752. void StringRef::takeOwnership() {
  8753. if( !isOwned() ) {
  8754. m_data = new char[m_size+1];
  8755. memcpy( m_data, m_start, m_size );
  8756. m_data[m_size] = '\0';
  8757. m_start = m_data;
  8758. }
  8759. }
  8760. auto StringRef::substr( size_type start, size_type size ) const noexcept -> StringRef {
  8761. if( start < m_size )
  8762. return StringRef( m_start+start, size );
  8763. else
  8764. return StringRef();
  8765. }
  8766. auto StringRef::operator == ( StringRef const& other ) const noexcept -> bool {
  8767. return
  8768. size() == other.size() &&
  8769. (std::strncmp( m_start, other.m_start, size() ) == 0);
  8770. }
  8771. auto StringRef::operator != ( StringRef const& other ) const noexcept -> bool {
  8772. return !operator==( other );
  8773. }
  8774. auto StringRef::operator[](size_type index) const noexcept -> char {
  8775. return m_start[index];
  8776. }
  8777. auto StringRef::numberOfCharacters() const noexcept -> size_type {
  8778. size_type noChars = m_size;
  8779. // Make adjustments for uft encodings
  8780. for( size_type i=0; i < m_size; ++i ) {
  8781. char c = m_start[i];
  8782. if( ( c & byte_2_lead ) == byte_2_lead ) {
  8783. noChars--;
  8784. if (( c & byte_3_lead ) == byte_3_lead )
  8785. noChars--;
  8786. if( ( c & byte_4_lead ) == byte_4_lead )
  8787. noChars--;
  8788. }
  8789. }
  8790. return noChars;
  8791. }
  8792. auto operator + ( StringRef const& lhs, StringRef const& rhs ) -> std::string {
  8793. std::string str;
  8794. str.reserve( lhs.size() + rhs.size() );
  8795. str += lhs;
  8796. str += rhs;
  8797. return str;
  8798. }
  8799. auto operator + ( StringRef const& lhs, const char* rhs ) -> std::string {
  8800. return std::string( lhs ) + std::string( rhs );
  8801. }
  8802. auto operator + ( char const* lhs, StringRef const& rhs ) -> std::string {
  8803. return std::string( lhs ) + std::string( rhs );
  8804. }
  8805. auto operator << ( std::ostream& os, StringRef const& str ) -> std::ostream& {
  8806. return os.write(str.currentData(), str.size());
  8807. }
  8808. auto operator+=( std::string& lhs, StringRef const& rhs ) -> std::string& {
  8809. lhs.append(rhs.currentData(), rhs.size());
  8810. return lhs;
  8811. }
  8812. } // namespace Catch
  8813. #if defined(__clang__)
  8814. # pragma clang diagnostic pop
  8815. #endif
  8816. // end catch_stringref.cpp
  8817. // start catch_tag_alias.cpp
  8818. namespace Catch {
  8819. TagAlias::TagAlias(std::string const & _tag, SourceLineInfo _lineInfo): tag(_tag), lineInfo(_lineInfo) {}
  8820. }
  8821. // end catch_tag_alias.cpp
  8822. // start catch_tag_alias_autoregistrar.cpp
  8823. namespace Catch {
  8824. RegistrarForTagAliases::RegistrarForTagAliases(char const* alias, char const* tag, SourceLineInfo const& lineInfo) {
  8825. CATCH_TRY {
  8826. getMutableRegistryHub().registerTagAlias(alias, tag, lineInfo);
  8827. } CATCH_CATCH_ALL {
  8828. // Do not throw when constructing global objects, instead register the exception to be processed later
  8829. getMutableRegistryHub().registerStartupException();
  8830. }
  8831. }
  8832. }
  8833. // end catch_tag_alias_autoregistrar.cpp
  8834. // start catch_tag_alias_registry.cpp
  8835. #include <sstream>
  8836. namespace Catch {
  8837. TagAliasRegistry::~TagAliasRegistry() {}
  8838. TagAlias const* TagAliasRegistry::find( std::string const& alias ) const {
  8839. auto it = m_registry.find( alias );
  8840. if( it != m_registry.end() )
  8841. return &(it->second);
  8842. else
  8843. return nullptr;
  8844. }
  8845. std::string TagAliasRegistry::expandAliases( std::string const& unexpandedTestSpec ) const {
  8846. std::string expandedTestSpec = unexpandedTestSpec;
  8847. for( auto const& registryKvp : m_registry ) {
  8848. std::size_t pos = expandedTestSpec.find( registryKvp.first );
  8849. if( pos != std::string::npos ) {
  8850. expandedTestSpec = expandedTestSpec.substr( 0, pos ) +
  8851. registryKvp.second.tag +
  8852. expandedTestSpec.substr( pos + registryKvp.first.size() );
  8853. }
  8854. }
  8855. return expandedTestSpec;
  8856. }
  8857. void TagAliasRegistry::add( std::string const& alias, std::string const& tag, SourceLineInfo const& lineInfo ) {
  8858. CATCH_ENFORCE( startsWith(alias, "[@") && endsWith(alias, ']'),
  8859. "error: tag alias, '" << alias << "' is not of the form [@alias name].\n" << lineInfo );
  8860. CATCH_ENFORCE( m_registry.insert(std::make_pair(alias, TagAlias(tag, lineInfo))).second,
  8861. "error: tag alias, '" << alias << "' already registered.\n"
  8862. << "\tFirst seen at: " << find(alias)->lineInfo << "\n"
  8863. << "\tRedefined at: " << lineInfo );
  8864. }
  8865. ITagAliasRegistry::~ITagAliasRegistry() {}
  8866. ITagAliasRegistry const& ITagAliasRegistry::get() {
  8867. return getRegistryHub().getTagAliasRegistry();
  8868. }
  8869. } // end namespace Catch
  8870. // end catch_tag_alias_registry.cpp
  8871. // start catch_test_case_info.cpp
  8872. #include <cctype>
  8873. #include <exception>
  8874. #include <algorithm>
  8875. #include <sstream>
  8876. namespace Catch {
  8877. namespace {
  8878. TestCaseInfo::SpecialProperties parseSpecialTag( std::string const& tag ) {
  8879. if( startsWith( tag, '.' ) ||
  8880. tag == "!hide" )
  8881. return TestCaseInfo::IsHidden;
  8882. else if( tag == "!throws" )
  8883. return TestCaseInfo::Throws;
  8884. else if( tag == "!shouldfail" )
  8885. return TestCaseInfo::ShouldFail;
  8886. else if( tag == "!mayfail" )
  8887. return TestCaseInfo::MayFail;
  8888. else if( tag == "!nonportable" )
  8889. return TestCaseInfo::NonPortable;
  8890. else if( tag == "!benchmark" )
  8891. return static_cast<TestCaseInfo::SpecialProperties>( TestCaseInfo::Benchmark | TestCaseInfo::IsHidden );
  8892. else
  8893. return TestCaseInfo::None;
  8894. }
  8895. bool isReservedTag( std::string const& tag ) {
  8896. return parseSpecialTag( tag ) == TestCaseInfo::None && tag.size() > 0 && !std::isalnum( static_cast<unsigned char>(tag[0]) );
  8897. }
  8898. void enforceNotReservedTag( std::string const& tag, SourceLineInfo const& _lineInfo ) {
  8899. CATCH_ENFORCE( !isReservedTag(tag),
  8900. "Tag name: [" << tag << "] is not allowed.\n"
  8901. << "Tag names starting with non alpha-numeric characters are reserved\n"
  8902. << _lineInfo );
  8903. }
  8904. }
  8905. TestCase makeTestCase( ITestInvoker* _testCase,
  8906. std::string const& _className,
  8907. NameAndTags const& nameAndTags,
  8908. SourceLineInfo const& _lineInfo )
  8909. {
  8910. bool isHidden = false;
  8911. // Parse out tags
  8912. std::vector<std::string> tags;
  8913. std::string desc, tag;
  8914. bool inTag = false;
  8915. std::string _descOrTags = nameAndTags.tags;
  8916. for (char c : _descOrTags) {
  8917. if( !inTag ) {
  8918. if( c == '[' )
  8919. inTag = true;
  8920. else
  8921. desc += c;
  8922. }
  8923. else {
  8924. if( c == ']' ) {
  8925. TestCaseInfo::SpecialProperties prop = parseSpecialTag( tag );
  8926. if( ( prop & TestCaseInfo::IsHidden ) != 0 )
  8927. isHidden = true;
  8928. else if( prop == TestCaseInfo::None )
  8929. enforceNotReservedTag( tag, _lineInfo );
  8930. tags.push_back( tag );
  8931. tag.clear();
  8932. inTag = false;
  8933. }
  8934. else
  8935. tag += c;
  8936. }
  8937. }
  8938. if( isHidden ) {
  8939. tags.push_back( "." );
  8940. }
  8941. TestCaseInfo info( nameAndTags.name, _className, desc, tags, _lineInfo );
  8942. return TestCase( _testCase, std::move(info) );
  8943. }
  8944. void setTags( TestCaseInfo& testCaseInfo, std::vector<std::string> tags ) {
  8945. std::sort(begin(tags), end(tags));
  8946. tags.erase(std::unique(begin(tags), end(tags)), end(tags));
  8947. testCaseInfo.lcaseTags.clear();
  8948. for( auto const& tag : tags ) {
  8949. std::string lcaseTag = toLower( tag );
  8950. testCaseInfo.properties = static_cast<TestCaseInfo::SpecialProperties>( testCaseInfo.properties | parseSpecialTag( lcaseTag ) );
  8951. testCaseInfo.lcaseTags.push_back( lcaseTag );
  8952. }
  8953. testCaseInfo.tags = std::move(tags);
  8954. }
  8955. TestCaseInfo::TestCaseInfo( std::string const& _name,
  8956. std::string const& _className,
  8957. std::string const& _description,
  8958. std::vector<std::string> const& _tags,
  8959. SourceLineInfo const& _lineInfo )
  8960. : name( _name ),
  8961. className( _className ),
  8962. description( _description ),
  8963. lineInfo( _lineInfo ),
  8964. properties( None )
  8965. {
  8966. setTags( *this, _tags );
  8967. }
  8968. bool TestCaseInfo::isHidden() const {
  8969. return ( properties & IsHidden ) != 0;
  8970. }
  8971. bool TestCaseInfo::throws() const {
  8972. return ( properties & Throws ) != 0;
  8973. }
  8974. bool TestCaseInfo::okToFail() const {
  8975. return ( properties & (ShouldFail | MayFail ) ) != 0;
  8976. }
  8977. bool TestCaseInfo::expectedToFail() const {
  8978. return ( properties & (ShouldFail ) ) != 0;
  8979. }
  8980. std::string TestCaseInfo::tagsAsString() const {
  8981. std::string ret;
  8982. // '[' and ']' per tag
  8983. std::size_t full_size = 2 * tags.size();
  8984. for (const auto& tag : tags) {
  8985. full_size += tag.size();
  8986. }
  8987. ret.reserve(full_size);
  8988. for (const auto& tag : tags) {
  8989. ret.push_back('[');
  8990. ret.append(tag);
  8991. ret.push_back(']');
  8992. }
  8993. return ret;
  8994. }
  8995. TestCase::TestCase( ITestInvoker* testCase, TestCaseInfo&& info ) : TestCaseInfo( std::move(info) ), test( testCase ) {}
  8996. TestCase TestCase::withName( std::string const& _newName ) const {
  8997. TestCase other( *this );
  8998. other.name = _newName;
  8999. return other;
  9000. }
  9001. void TestCase::invoke() const {
  9002. test->invoke();
  9003. }
  9004. bool TestCase::operator == ( TestCase const& other ) const {
  9005. return test.get() == other.test.get() &&
  9006. name == other.name &&
  9007. className == other.className;
  9008. }
  9009. bool TestCase::operator < ( TestCase const& other ) const {
  9010. return name < other.name;
  9011. }
  9012. TestCaseInfo const& TestCase::getTestCaseInfo() const
  9013. {
  9014. return *this;
  9015. }
  9016. } // end namespace Catch
  9017. // end catch_test_case_info.cpp
  9018. // start catch_test_case_registry_impl.cpp
  9019. #include <sstream>
  9020. namespace Catch {
  9021. std::vector<TestCase> sortTests( IConfig const& config, std::vector<TestCase> const& unsortedTestCases ) {
  9022. std::vector<TestCase> sorted = unsortedTestCases;
  9023. switch( config.runOrder() ) {
  9024. case RunTests::InLexicographicalOrder:
  9025. std::sort( sorted.begin(), sorted.end() );
  9026. break;
  9027. case RunTests::InRandomOrder:
  9028. seedRng( config );
  9029. std::shuffle( sorted.begin(), sorted.end(), rng() );
  9030. break;
  9031. case RunTests::InDeclarationOrder:
  9032. // already in declaration order
  9033. break;
  9034. }
  9035. return sorted;
  9036. }
  9037. bool matchTest( TestCase const& testCase, TestSpec const& testSpec, IConfig const& config ) {
  9038. return testSpec.matches( testCase ) && ( config.allowThrows() || !testCase.throws() );
  9039. }
  9040. void enforceNoDuplicateTestCases( std::vector<TestCase> const& functions ) {
  9041. std::set<TestCase> seenFunctions;
  9042. for( auto const& function : functions ) {
  9043. auto prev = seenFunctions.insert( function );
  9044. CATCH_ENFORCE( prev.second,
  9045. "error: TEST_CASE( \"" << function.name << "\" ) already defined.\n"
  9046. << "\tFirst seen at " << prev.first->getTestCaseInfo().lineInfo << "\n"
  9047. << "\tRedefined at " << function.getTestCaseInfo().lineInfo );
  9048. }
  9049. }
  9050. std::vector<TestCase> filterTests( std::vector<TestCase> const& testCases, TestSpec const& testSpec, IConfig const& config ) {
  9051. std::vector<TestCase> filtered;
  9052. filtered.reserve( testCases.size() );
  9053. for( auto const& testCase : testCases )
  9054. if( matchTest( testCase, testSpec, config ) )
  9055. filtered.push_back( testCase );
  9056. return filtered;
  9057. }
  9058. std::vector<TestCase> const& getAllTestCasesSorted( IConfig const& config ) {
  9059. return getRegistryHub().getTestCaseRegistry().getAllTestsSorted( config );
  9060. }
  9061. void TestRegistry::registerTest( TestCase const& testCase ) {
  9062. std::string name = testCase.getTestCaseInfo().name;
  9063. if( name.empty() ) {
  9064. ReusableStringStream rss;
  9065. rss << "Anonymous test case " << ++m_unnamedCount;
  9066. return registerTest( testCase.withName( rss.str() ) );
  9067. }
  9068. m_functions.push_back( testCase );
  9069. }
  9070. std::vector<TestCase> const& TestRegistry::getAllTests() const {
  9071. return m_functions;
  9072. }
  9073. std::vector<TestCase> const& TestRegistry::getAllTestsSorted( IConfig const& config ) const {
  9074. if( m_sortedFunctions.empty() )
  9075. enforceNoDuplicateTestCases( m_functions );
  9076. if( m_currentSortOrder != config.runOrder() || m_sortedFunctions.empty() ) {
  9077. m_sortedFunctions = sortTests( config, m_functions );
  9078. m_currentSortOrder = config.runOrder();
  9079. }
  9080. return m_sortedFunctions;
  9081. }
  9082. ///////////////////////////////////////////////////////////////////////////
  9083. TestInvokerAsFunction::TestInvokerAsFunction( void(*testAsFunction)() ) noexcept : m_testAsFunction( testAsFunction ) {}
  9084. void TestInvokerAsFunction::invoke() const {
  9085. m_testAsFunction();
  9086. }
  9087. std::string extractClassName( StringRef const& classOrQualifiedMethodName ) {
  9088. std::string className = classOrQualifiedMethodName;
  9089. if( startsWith( className, '&' ) )
  9090. {
  9091. std::size_t lastColons = className.rfind( "::" );
  9092. std::size_t penultimateColons = className.rfind( "::", lastColons-1 );
  9093. if( penultimateColons == std::string::npos )
  9094. penultimateColons = 1;
  9095. className = className.substr( penultimateColons, lastColons-penultimateColons );
  9096. }
  9097. return className;
  9098. }
  9099. } // end namespace Catch
  9100. // end catch_test_case_registry_impl.cpp
  9101. // start catch_test_case_tracker.cpp
  9102. #include <algorithm>
  9103. #include <cassert>
  9104. #include <stdexcept>
  9105. #include <memory>
  9106. #include <sstream>
  9107. #if defined(__clang__)
  9108. # pragma clang diagnostic push
  9109. # pragma clang diagnostic ignored "-Wexit-time-destructors"
  9110. #endif
  9111. namespace Catch {
  9112. namespace TestCaseTracking {
  9113. NameAndLocation::NameAndLocation( std::string const& _name, SourceLineInfo const& _location )
  9114. : name( _name ),
  9115. location( _location )
  9116. {}
  9117. ITracker::~ITracker() = default;
  9118. TrackerContext& TrackerContext::instance() {
  9119. static TrackerContext s_instance;
  9120. return s_instance;
  9121. }
  9122. ITracker& TrackerContext::startRun() {
  9123. m_rootTracker = std::make_shared<SectionTracker>( NameAndLocation( "{root}", CATCH_INTERNAL_LINEINFO ), *this, nullptr );
  9124. m_currentTracker = nullptr;
  9125. m_runState = Executing;
  9126. return *m_rootTracker;
  9127. }
  9128. void TrackerContext::endRun() {
  9129. m_rootTracker.reset();
  9130. m_currentTracker = nullptr;
  9131. m_runState = NotStarted;
  9132. }
  9133. void TrackerContext::startCycle() {
  9134. m_currentTracker = m_rootTracker.get();
  9135. m_runState = Executing;
  9136. }
  9137. void TrackerContext::completeCycle() {
  9138. m_runState = CompletedCycle;
  9139. }
  9140. bool TrackerContext::completedCycle() const {
  9141. return m_runState == CompletedCycle;
  9142. }
  9143. ITracker& TrackerContext::currentTracker() {
  9144. return *m_currentTracker;
  9145. }
  9146. void TrackerContext::setCurrentTracker( ITracker* tracker ) {
  9147. m_currentTracker = tracker;
  9148. }
  9149. TrackerBase::TrackerBase( NameAndLocation const& nameAndLocation, TrackerContext& ctx, ITracker* parent )
  9150. : m_nameAndLocation( nameAndLocation ),
  9151. m_ctx( ctx ),
  9152. m_parent( parent )
  9153. {}
  9154. NameAndLocation const& TrackerBase::nameAndLocation() const {
  9155. return m_nameAndLocation;
  9156. }
  9157. bool TrackerBase::isComplete() const {
  9158. return m_runState == CompletedSuccessfully || m_runState == Failed;
  9159. }
  9160. bool TrackerBase::isSuccessfullyCompleted() const {
  9161. return m_runState == CompletedSuccessfully;
  9162. }
  9163. bool TrackerBase::isOpen() const {
  9164. return m_runState != NotStarted && !isComplete();
  9165. }
  9166. bool TrackerBase::hasChildren() const {
  9167. return !m_children.empty();
  9168. }
  9169. void TrackerBase::addChild( ITrackerPtr const& child ) {
  9170. m_children.push_back( child );
  9171. }
  9172. ITrackerPtr TrackerBase::findChild( NameAndLocation const& nameAndLocation ) {
  9173. auto it = std::find_if( m_children.begin(), m_children.end(),
  9174. [&nameAndLocation]( ITrackerPtr const& tracker ){
  9175. return
  9176. tracker->nameAndLocation().location == nameAndLocation.location &&
  9177. tracker->nameAndLocation().name == nameAndLocation.name;
  9178. } );
  9179. return( it != m_children.end() )
  9180. ? *it
  9181. : nullptr;
  9182. }
  9183. ITracker& TrackerBase::parent() {
  9184. assert( m_parent ); // Should always be non-null except for root
  9185. return *m_parent;
  9186. }
  9187. void TrackerBase::openChild() {
  9188. if( m_runState != ExecutingChildren ) {
  9189. m_runState = ExecutingChildren;
  9190. if( m_parent )
  9191. m_parent->openChild();
  9192. }
  9193. }
  9194. bool TrackerBase::isSectionTracker() const { return false; }
  9195. bool TrackerBase::isIndexTracker() const { return false; }
  9196. void TrackerBase::open() {
  9197. m_runState = Executing;
  9198. moveToThis();
  9199. if( m_parent )
  9200. m_parent->openChild();
  9201. }
  9202. void TrackerBase::close() {
  9203. // Close any still open children (e.g. generators)
  9204. while( &m_ctx.currentTracker() != this )
  9205. m_ctx.currentTracker().close();
  9206. switch( m_runState ) {
  9207. case NeedsAnotherRun:
  9208. break;
  9209. case Executing:
  9210. m_runState = CompletedSuccessfully;
  9211. break;
  9212. case ExecutingChildren:
  9213. if( m_children.empty() || m_children.back()->isComplete() )
  9214. m_runState = CompletedSuccessfully;
  9215. break;
  9216. case NotStarted:
  9217. case CompletedSuccessfully:
  9218. case Failed:
  9219. CATCH_INTERNAL_ERROR( "Illogical state: " << m_runState );
  9220. default:
  9221. CATCH_INTERNAL_ERROR( "Unknown state: " << m_runState );
  9222. }
  9223. moveToParent();
  9224. m_ctx.completeCycle();
  9225. }
  9226. void TrackerBase::fail() {
  9227. m_runState = Failed;
  9228. if( m_parent )
  9229. m_parent->markAsNeedingAnotherRun();
  9230. moveToParent();
  9231. m_ctx.completeCycle();
  9232. }
  9233. void TrackerBase::markAsNeedingAnotherRun() {
  9234. m_runState = NeedsAnotherRun;
  9235. }
  9236. void TrackerBase::moveToParent() {
  9237. assert( m_parent );
  9238. m_ctx.setCurrentTracker( m_parent );
  9239. }
  9240. void TrackerBase::moveToThis() {
  9241. m_ctx.setCurrentTracker( this );
  9242. }
  9243. SectionTracker::SectionTracker( NameAndLocation const& nameAndLocation, TrackerContext& ctx, ITracker* parent )
  9244. : TrackerBase( nameAndLocation, ctx, parent )
  9245. {
  9246. if( parent ) {
  9247. while( !parent->isSectionTracker() )
  9248. parent = &parent->parent();
  9249. SectionTracker& parentSection = static_cast<SectionTracker&>( *parent );
  9250. addNextFilters( parentSection.m_filters );
  9251. }
  9252. }
  9253. bool SectionTracker::isSectionTracker() const { return true; }
  9254. SectionTracker& SectionTracker::acquire( TrackerContext& ctx, NameAndLocation const& nameAndLocation ) {
  9255. std::shared_ptr<SectionTracker> section;
  9256. ITracker& currentTracker = ctx.currentTracker();
  9257. if( ITrackerPtr childTracker = currentTracker.findChild( nameAndLocation ) ) {
  9258. assert( childTracker );
  9259. assert( childTracker->isSectionTracker() );
  9260. section = std::static_pointer_cast<SectionTracker>( childTracker );
  9261. }
  9262. else {
  9263. section = std::make_shared<SectionTracker>( nameAndLocation, ctx, &currentTracker );
  9264. currentTracker.addChild( section );
  9265. }
  9266. if( !ctx.completedCycle() )
  9267. section->tryOpen();
  9268. return *section;
  9269. }
  9270. void SectionTracker::tryOpen() {
  9271. if( !isComplete() && (m_filters.empty() || m_filters[0].empty() || m_filters[0] == m_nameAndLocation.name ) )
  9272. open();
  9273. }
  9274. void SectionTracker::addInitialFilters( std::vector<std::string> const& filters ) {
  9275. if( !filters.empty() ) {
  9276. m_filters.push_back(""); // Root - should never be consulted
  9277. m_filters.push_back(""); // Test Case - not a section filter
  9278. m_filters.insert( m_filters.end(), filters.begin(), filters.end() );
  9279. }
  9280. }
  9281. void SectionTracker::addNextFilters( std::vector<std::string> const& filters ) {
  9282. if( filters.size() > 1 )
  9283. m_filters.insert( m_filters.end(), ++filters.begin(), filters.end() );
  9284. }
  9285. IndexTracker::IndexTracker( NameAndLocation const& nameAndLocation, TrackerContext& ctx, ITracker* parent, int size )
  9286. : TrackerBase( nameAndLocation, ctx, parent ),
  9287. m_size( size )
  9288. {}
  9289. bool IndexTracker::isIndexTracker() const { return true; }
  9290. IndexTracker& IndexTracker::acquire( TrackerContext& ctx, NameAndLocation const& nameAndLocation, int size ) {
  9291. std::shared_ptr<IndexTracker> tracker;
  9292. ITracker& currentTracker = ctx.currentTracker();
  9293. if( ITrackerPtr childTracker = currentTracker.findChild( nameAndLocation ) ) {
  9294. assert( childTracker );
  9295. assert( childTracker->isIndexTracker() );
  9296. tracker = std::static_pointer_cast<IndexTracker>( childTracker );
  9297. }
  9298. else {
  9299. tracker = std::make_shared<IndexTracker>( nameAndLocation, ctx, &currentTracker, size );
  9300. currentTracker.addChild( tracker );
  9301. }
  9302. if( !ctx.completedCycle() && !tracker->isComplete() ) {
  9303. if( tracker->m_runState != ExecutingChildren && tracker->m_runState != NeedsAnotherRun )
  9304. tracker->moveNext();
  9305. tracker->open();
  9306. }
  9307. return *tracker;
  9308. }
  9309. int IndexTracker::index() const { return m_index; }
  9310. void IndexTracker::moveNext() {
  9311. m_index++;
  9312. m_children.clear();
  9313. }
  9314. void IndexTracker::close() {
  9315. TrackerBase::close();
  9316. if( m_runState == CompletedSuccessfully && m_index < m_size-1 )
  9317. m_runState = Executing;
  9318. }
  9319. } // namespace TestCaseTracking
  9320. using TestCaseTracking::ITracker;
  9321. using TestCaseTracking::TrackerContext;
  9322. using TestCaseTracking::SectionTracker;
  9323. using TestCaseTracking::IndexTracker;
  9324. } // namespace Catch
  9325. #if defined(__clang__)
  9326. # pragma clang diagnostic pop
  9327. #endif
  9328. // end catch_test_case_tracker.cpp
  9329. // start catch_test_registry.cpp
  9330. namespace Catch {
  9331. auto makeTestInvoker( void(*testAsFunction)() ) noexcept -> ITestInvoker* {
  9332. return new(std::nothrow) TestInvokerAsFunction( testAsFunction );
  9333. }
  9334. NameAndTags::NameAndTags( StringRef const& name_ , StringRef const& tags_ ) noexcept : name( name_ ), tags( tags_ ) {}
  9335. AutoReg::AutoReg( ITestInvoker* invoker, SourceLineInfo const& lineInfo, StringRef const& classOrMethod, NameAndTags const& nameAndTags ) noexcept {
  9336. CATCH_TRY {
  9337. getMutableRegistryHub()
  9338. .registerTest(
  9339. makeTestCase(
  9340. invoker,
  9341. extractClassName( classOrMethod ),
  9342. nameAndTags,
  9343. lineInfo));
  9344. } CATCH_CATCH_ALL {
  9345. // Do not throw when constructing global objects, instead register the exception to be processed later
  9346. getMutableRegistryHub().registerStartupException();
  9347. }
  9348. }
  9349. AutoReg::~AutoReg() = default;
  9350. }
  9351. // end catch_test_registry.cpp
  9352. // start catch_test_spec.cpp
  9353. #include <algorithm>
  9354. #include <string>
  9355. #include <vector>
  9356. #include <memory>
  9357. namespace Catch {
  9358. TestSpec::Pattern::~Pattern() = default;
  9359. TestSpec::NamePattern::~NamePattern() = default;
  9360. TestSpec::TagPattern::~TagPattern() = default;
  9361. TestSpec::ExcludedPattern::~ExcludedPattern() = default;
  9362. TestSpec::NamePattern::NamePattern( std::string const& name )
  9363. : m_wildcardPattern( toLower( name ), CaseSensitive::No )
  9364. {}
  9365. bool TestSpec::NamePattern::matches( TestCaseInfo const& testCase ) const {
  9366. return m_wildcardPattern.matches( toLower( testCase.name ) );
  9367. }
  9368. TestSpec::TagPattern::TagPattern( std::string const& tag ) : m_tag( toLower( tag ) ) {}
  9369. bool TestSpec::TagPattern::matches( TestCaseInfo const& testCase ) const {
  9370. return std::find(begin(testCase.lcaseTags),
  9371. end(testCase.lcaseTags),
  9372. m_tag) != end(testCase.lcaseTags);
  9373. }
  9374. TestSpec::ExcludedPattern::ExcludedPattern( PatternPtr const& underlyingPattern ) : m_underlyingPattern( underlyingPattern ) {}
  9375. bool TestSpec::ExcludedPattern::matches( TestCaseInfo const& testCase ) const { return !m_underlyingPattern->matches( testCase ); }
  9376. bool TestSpec::Filter::matches( TestCaseInfo const& testCase ) const {
  9377. // All patterns in a filter must match for the filter to be a match
  9378. for( auto const& pattern : m_patterns ) {
  9379. if( !pattern->matches( testCase ) )
  9380. return false;
  9381. }
  9382. return true;
  9383. }
  9384. bool TestSpec::hasFilters() const {
  9385. return !m_filters.empty();
  9386. }
  9387. bool TestSpec::matches( TestCaseInfo const& testCase ) const {
  9388. // A TestSpec matches if any filter matches
  9389. for( auto const& filter : m_filters )
  9390. if( filter.matches( testCase ) )
  9391. return true;
  9392. return false;
  9393. }
  9394. }
  9395. // end catch_test_spec.cpp
  9396. // start catch_test_spec_parser.cpp
  9397. namespace Catch {
  9398. TestSpecParser::TestSpecParser( ITagAliasRegistry const& tagAliases ) : m_tagAliases( &tagAliases ) {}
  9399. TestSpecParser& TestSpecParser::parse( std::string const& arg ) {
  9400. m_mode = None;
  9401. m_exclusion = false;
  9402. m_start = std::string::npos;
  9403. m_arg = m_tagAliases->expandAliases( arg );
  9404. m_escapeChars.clear();
  9405. for( m_pos = 0; m_pos < m_arg.size(); ++m_pos )
  9406. visitChar( m_arg[m_pos] );
  9407. if( m_mode == Name )
  9408. addPattern<TestSpec::NamePattern>();
  9409. return *this;
  9410. }
  9411. TestSpec TestSpecParser::testSpec() {
  9412. addFilter();
  9413. return m_testSpec;
  9414. }
  9415. void TestSpecParser::visitChar( char c ) {
  9416. if( m_mode == None ) {
  9417. switch( c ) {
  9418. case ' ': return;
  9419. case '~': m_exclusion = true; return;
  9420. case '[': return startNewMode( Tag, ++m_pos );
  9421. case '"': return startNewMode( QuotedName, ++m_pos );
  9422. case '\\': return escape();
  9423. default: startNewMode( Name, m_pos ); break;
  9424. }
  9425. }
  9426. if( m_mode == Name ) {
  9427. if( c == ',' ) {
  9428. addPattern<TestSpec::NamePattern>();
  9429. addFilter();
  9430. }
  9431. else if( c == '[' ) {
  9432. if( subString() == "exclude:" )
  9433. m_exclusion = true;
  9434. else
  9435. addPattern<TestSpec::NamePattern>();
  9436. startNewMode( Tag, ++m_pos );
  9437. }
  9438. else if( c == '\\' )
  9439. escape();
  9440. }
  9441. else if( m_mode == EscapedName )
  9442. m_mode = Name;
  9443. else if( m_mode == QuotedName && c == '"' )
  9444. addPattern<TestSpec::NamePattern>();
  9445. else if( m_mode == Tag && c == ']' )
  9446. addPattern<TestSpec::TagPattern>();
  9447. }
  9448. void TestSpecParser::startNewMode( Mode mode, std::size_t start ) {
  9449. m_mode = mode;
  9450. m_start = start;
  9451. }
  9452. void TestSpecParser::escape() {
  9453. if( m_mode == None )
  9454. m_start = m_pos;
  9455. m_mode = EscapedName;
  9456. m_escapeChars.push_back( m_pos );
  9457. }
  9458. std::string TestSpecParser::subString() const { return m_arg.substr( m_start, m_pos - m_start ); }
  9459. void TestSpecParser::addFilter() {
  9460. if( !m_currentFilter.m_patterns.empty() ) {
  9461. m_testSpec.m_filters.push_back( m_currentFilter );
  9462. m_currentFilter = TestSpec::Filter();
  9463. }
  9464. }
  9465. TestSpec parseTestSpec( std::string const& arg ) {
  9466. return TestSpecParser( ITagAliasRegistry::get() ).parse( arg ).testSpec();
  9467. }
  9468. } // namespace Catch
  9469. // end catch_test_spec_parser.cpp
  9470. // start catch_timer.cpp
  9471. #include <chrono>
  9472. static const uint64_t nanosecondsInSecond = 1000000000;
  9473. namespace Catch {
  9474. auto getCurrentNanosecondsSinceEpoch() -> uint64_t {
  9475. return std::chrono::duration_cast<std::chrono::nanoseconds>( std::chrono::high_resolution_clock::now().time_since_epoch() ).count();
  9476. }
  9477. namespace {
  9478. auto estimateClockResolution() -> uint64_t {
  9479. uint64_t sum = 0;
  9480. static const uint64_t iterations = 1000000;
  9481. auto startTime = getCurrentNanosecondsSinceEpoch();
  9482. for( std::size_t i = 0; i < iterations; ++i ) {
  9483. uint64_t ticks;
  9484. uint64_t baseTicks = getCurrentNanosecondsSinceEpoch();
  9485. do {
  9486. ticks = getCurrentNanosecondsSinceEpoch();
  9487. } while( ticks == baseTicks );
  9488. auto delta = ticks - baseTicks;
  9489. sum += delta;
  9490. // If we have been calibrating for over 3 seconds -- the clock
  9491. // is terrible and we should move on.
  9492. // TBD: How to signal that the measured resolution is probably wrong?
  9493. if (ticks > startTime + 3 * nanosecondsInSecond) {
  9494. return sum / i;
  9495. }
  9496. }
  9497. // We're just taking the mean, here. To do better we could take the std. dev and exclude outliers
  9498. // - and potentially do more iterations if there's a high variance.
  9499. return sum/iterations;
  9500. }
  9501. }
  9502. auto getEstimatedClockResolution() -> uint64_t {
  9503. static auto s_resolution = estimateClockResolution();
  9504. return s_resolution;
  9505. }
  9506. void Timer::start() {
  9507. m_nanoseconds = getCurrentNanosecondsSinceEpoch();
  9508. }
  9509. auto Timer::getElapsedNanoseconds() const -> uint64_t {
  9510. return getCurrentNanosecondsSinceEpoch() - m_nanoseconds;
  9511. }
  9512. auto Timer::getElapsedMicroseconds() const -> uint64_t {
  9513. return getElapsedNanoseconds()/1000;
  9514. }
  9515. auto Timer::getElapsedMilliseconds() const -> unsigned int {
  9516. return static_cast<unsigned int>(getElapsedMicroseconds()/1000);
  9517. }
  9518. auto Timer::getElapsedSeconds() const -> double {
  9519. return getElapsedMicroseconds()/1000000.0;
  9520. }
  9521. } // namespace Catch
  9522. // end catch_timer.cpp
  9523. // start catch_tostring.cpp
  9524. #if defined(__clang__)
  9525. # pragma clang diagnostic push
  9526. # pragma clang diagnostic ignored "-Wexit-time-destructors"
  9527. # pragma clang diagnostic ignored "-Wglobal-constructors"
  9528. #endif
  9529. // Enable specific decls locally
  9530. #if !defined(CATCH_CONFIG_ENABLE_CHRONO_STRINGMAKER)
  9531. #define CATCH_CONFIG_ENABLE_CHRONO_STRINGMAKER
  9532. #endif
  9533. #include <cmath>
  9534. #include <iomanip>
  9535. namespace Catch {
  9536. namespace Detail {
  9537. const std::string unprintableString = "{?}";
  9538. namespace {
  9539. const int hexThreshold = 255;
  9540. struct Endianness {
  9541. enum Arch { Big, Little };
  9542. static Arch which() {
  9543. union _{
  9544. int asInt;
  9545. char asChar[sizeof (int)];
  9546. } u;
  9547. u.asInt = 1;
  9548. return ( u.asChar[sizeof(int)-1] == 1 ) ? Big : Little;
  9549. }
  9550. };
  9551. }
  9552. std::string rawMemoryToString( const void *object, std::size_t size ) {
  9553. // Reverse order for little endian architectures
  9554. int i = 0, end = static_cast<int>( size ), inc = 1;
  9555. if( Endianness::which() == Endianness::Little ) {
  9556. i = end-1;
  9557. end = inc = -1;
  9558. }
  9559. unsigned char const *bytes = static_cast<unsigned char const *>(object);
  9560. ReusableStringStream rss;
  9561. rss << "0x" << std::setfill('0') << std::hex;
  9562. for( ; i != end; i += inc )
  9563. rss << std::setw(2) << static_cast<unsigned>(bytes[i]);
  9564. return rss.str();
  9565. }
  9566. }
  9567. template<typename T>
  9568. std::string fpToString( T value, int precision ) {
  9569. if (Catch::isnan(value)) {
  9570. return "nan";
  9571. }
  9572. ReusableStringStream rss;
  9573. rss << std::setprecision( precision )
  9574. << std::fixed
  9575. << value;
  9576. std::string d = rss.str();
  9577. std::size_t i = d.find_last_not_of( '0' );
  9578. if( i != std::string::npos && i != d.size()-1 ) {
  9579. if( d[i] == '.' )
  9580. i++;
  9581. d = d.substr( 0, i+1 );
  9582. }
  9583. return d;
  9584. }
  9585. //// ======================================================= ////
  9586. //
  9587. // Out-of-line defs for full specialization of StringMaker
  9588. //
  9589. //// ======================================================= ////
  9590. std::string StringMaker<std::string>::convert(const std::string& str) {
  9591. if (!getCurrentContext().getConfig()->showInvisibles()) {
  9592. return '"' + str + '"';
  9593. }
  9594. std::string s("\"");
  9595. for (char c : str) {
  9596. switch (c) {
  9597. case '\n':
  9598. s.append("\\n");
  9599. break;
  9600. case '\t':
  9601. s.append("\\t");
  9602. break;
  9603. default:
  9604. s.push_back(c);
  9605. break;
  9606. }
  9607. }
  9608. s.append("\"");
  9609. return s;
  9610. }
  9611. #ifdef CATCH_CONFIG_CPP17_STRING_VIEW
  9612. std::string StringMaker<std::string_view>::convert(std::string_view str) {
  9613. return ::Catch::Detail::stringify(std::string{ str });
  9614. }
  9615. #endif
  9616. std::string StringMaker<char const*>::convert(char const* str) {
  9617. if (str) {
  9618. return ::Catch::Detail::stringify(std::string{ str });
  9619. } else {
  9620. return{ "{null string}" };
  9621. }
  9622. }
  9623. std::string StringMaker<char*>::convert(char* str) {
  9624. if (str) {
  9625. return ::Catch::Detail::stringify(std::string{ str });
  9626. } else {
  9627. return{ "{null string}" };
  9628. }
  9629. }
  9630. #ifdef CATCH_CONFIG_WCHAR
  9631. std::string StringMaker<std::wstring>::convert(const std::wstring& wstr) {
  9632. std::string s;
  9633. s.reserve(wstr.size());
  9634. for (auto c : wstr) {
  9635. s += (c <= 0xff) ? static_cast<char>(c) : '?';
  9636. }
  9637. return ::Catch::Detail::stringify(s);
  9638. }
  9639. # ifdef CATCH_CONFIG_CPP17_STRING_VIEW
  9640. std::string StringMaker<std::wstring_view>::convert(std::wstring_view str) {
  9641. return StringMaker<std::wstring>::convert(std::wstring(str));
  9642. }
  9643. # endif
  9644. std::string StringMaker<wchar_t const*>::convert(wchar_t const * str) {
  9645. if (str) {
  9646. return ::Catch::Detail::stringify(std::wstring{ str });
  9647. } else {
  9648. return{ "{null string}" };
  9649. }
  9650. }
  9651. std::string StringMaker<wchar_t *>::convert(wchar_t * str) {
  9652. if (str) {
  9653. return ::Catch::Detail::stringify(std::wstring{ str });
  9654. } else {
  9655. return{ "{null string}" };
  9656. }
  9657. }
  9658. #endif
  9659. std::string StringMaker<int>::convert(int value) {
  9660. return ::Catch::Detail::stringify(static_cast<long long>(value));
  9661. }
  9662. std::string StringMaker<long>::convert(long value) {
  9663. return ::Catch::Detail::stringify(static_cast<long long>(value));
  9664. }
  9665. std::string StringMaker<long long>::convert(long long value) {
  9666. ReusableStringStream rss;
  9667. rss << value;
  9668. if (value > Detail::hexThreshold) {
  9669. rss << " (0x" << std::hex << value << ')';
  9670. }
  9671. return rss.str();
  9672. }
  9673. std::string StringMaker<unsigned int>::convert(unsigned int value) {
  9674. return ::Catch::Detail::stringify(static_cast<unsigned long long>(value));
  9675. }
  9676. std::string StringMaker<unsigned long>::convert(unsigned long value) {
  9677. return ::Catch::Detail::stringify(static_cast<unsigned long long>(value));
  9678. }
  9679. std::string StringMaker<unsigned long long>::convert(unsigned long long value) {
  9680. ReusableStringStream rss;
  9681. rss << value;
  9682. if (value > Detail::hexThreshold) {
  9683. rss << " (0x" << std::hex << value << ')';
  9684. }
  9685. return rss.str();
  9686. }
  9687. std::string StringMaker<bool>::convert(bool b) {
  9688. return b ? "true" : "false";
  9689. }
  9690. std::string StringMaker<signed char>::convert(signed char value) {
  9691. if (value == '\r') {
  9692. return "'\\r'";
  9693. } else if (value == '\f') {
  9694. return "'\\f'";
  9695. } else if (value == '\n') {
  9696. return "'\\n'";
  9697. } else if (value == '\t') {
  9698. return "'\\t'";
  9699. } else if ('\0' <= value && value < ' ') {
  9700. return ::Catch::Detail::stringify(static_cast<unsigned int>(value));
  9701. } else {
  9702. char chstr[] = "' '";
  9703. chstr[1] = value;
  9704. return chstr;
  9705. }
  9706. }
  9707. std::string StringMaker<char>::convert(char c) {
  9708. return ::Catch::Detail::stringify(static_cast<signed char>(c));
  9709. }
  9710. std::string StringMaker<unsigned char>::convert(unsigned char c) {
  9711. return ::Catch::Detail::stringify(static_cast<char>(c));
  9712. }
  9713. std::string StringMaker<std::nullptr_t>::convert(std::nullptr_t) {
  9714. return "nullptr";
  9715. }
  9716. std::string StringMaker<float>::convert(float value) {
  9717. return fpToString(value, 5) + 'f';
  9718. }
  9719. std::string StringMaker<double>::convert(double value) {
  9720. return fpToString(value, 10);
  9721. }
  9722. std::string ratio_string<std::atto>::symbol() { return "a"; }
  9723. std::string ratio_string<std::femto>::symbol() { return "f"; }
  9724. std::string ratio_string<std::pico>::symbol() { return "p"; }
  9725. std::string ratio_string<std::nano>::symbol() { return "n"; }
  9726. std::string ratio_string<std::micro>::symbol() { return "u"; }
  9727. std::string ratio_string<std::milli>::symbol() { return "m"; }
  9728. } // end namespace Catch
  9729. #if defined(__clang__)
  9730. # pragma clang diagnostic pop
  9731. #endif
  9732. // end catch_tostring.cpp
  9733. // start catch_totals.cpp
  9734. namespace Catch {
  9735. Counts Counts::operator - ( Counts const& other ) const {
  9736. Counts diff;
  9737. diff.passed = passed - other.passed;
  9738. diff.failed = failed - other.failed;
  9739. diff.failedButOk = failedButOk - other.failedButOk;
  9740. return diff;
  9741. }
  9742. Counts& Counts::operator += ( Counts const& other ) {
  9743. passed += other.passed;
  9744. failed += other.failed;
  9745. failedButOk += other.failedButOk;
  9746. return *this;
  9747. }
  9748. std::size_t Counts::total() const {
  9749. return passed + failed + failedButOk;
  9750. }
  9751. bool Counts::allPassed() const {
  9752. return failed == 0 && failedButOk == 0;
  9753. }
  9754. bool Counts::allOk() const {
  9755. return failed == 0;
  9756. }
  9757. Totals Totals::operator - ( Totals const& other ) const {
  9758. Totals diff;
  9759. diff.assertions = assertions - other.assertions;
  9760. diff.testCases = testCases - other.testCases;
  9761. return diff;
  9762. }
  9763. Totals& Totals::operator += ( Totals const& other ) {
  9764. assertions += other.assertions;
  9765. testCases += other.testCases;
  9766. return *this;
  9767. }
  9768. Totals Totals::delta( Totals const& prevTotals ) const {
  9769. Totals diff = *this - prevTotals;
  9770. if( diff.assertions.failed > 0 )
  9771. ++diff.testCases.failed;
  9772. else if( diff.assertions.failedButOk > 0 )
  9773. ++diff.testCases.failedButOk;
  9774. else
  9775. ++diff.testCases.passed;
  9776. return diff;
  9777. }
  9778. }
  9779. // end catch_totals.cpp
  9780. // start catch_uncaught_exceptions.cpp
  9781. #include <exception>
  9782. namespace Catch {
  9783. bool uncaught_exceptions() {
  9784. #if defined(CATCH_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS)
  9785. return std::uncaught_exceptions() > 0;
  9786. #else
  9787. return std::uncaught_exception();
  9788. #endif
  9789. }
  9790. } // end namespace Catch
  9791. // end catch_uncaught_exceptions.cpp
  9792. // start catch_version.cpp
  9793. #include <ostream>
  9794. namespace Catch {
  9795. Version::Version
  9796. ( unsigned int _majorVersion,
  9797. unsigned int _minorVersion,
  9798. unsigned int _patchNumber,
  9799. char const * const _branchName,
  9800. unsigned int _buildNumber )
  9801. : majorVersion( _majorVersion ),
  9802. minorVersion( _minorVersion ),
  9803. patchNumber( _patchNumber ),
  9804. branchName( _branchName ),
  9805. buildNumber( _buildNumber )
  9806. {}
  9807. std::ostream& operator << ( std::ostream& os, Version const& version ) {
  9808. os << version.majorVersion << '.'
  9809. << version.minorVersion << '.'
  9810. << version.patchNumber;
  9811. // branchName is never null -> 0th char is \0 if it is empty
  9812. if (version.branchName[0]) {
  9813. os << '-' << version.branchName
  9814. << '.' << version.buildNumber;
  9815. }
  9816. return os;
  9817. }
  9818. Version const& libraryVersion() {
  9819. static Version version( 2, 5, 0, "", 0 );
  9820. return version;
  9821. }
  9822. }
  9823. // end catch_version.cpp
  9824. // start catch_wildcard_pattern.cpp
  9825. #include <sstream>
  9826. namespace Catch {
  9827. WildcardPattern::WildcardPattern( std::string const& pattern,
  9828. CaseSensitive::Choice caseSensitivity )
  9829. : m_caseSensitivity( caseSensitivity ),
  9830. m_pattern( adjustCase( pattern ) )
  9831. {
  9832. if( startsWith( m_pattern, '*' ) ) {
  9833. m_pattern = m_pattern.substr( 1 );
  9834. m_wildcard = WildcardAtStart;
  9835. }
  9836. if( endsWith( m_pattern, '*' ) ) {
  9837. m_pattern = m_pattern.substr( 0, m_pattern.size()-1 );
  9838. m_wildcard = static_cast<WildcardPosition>( m_wildcard | WildcardAtEnd );
  9839. }
  9840. }
  9841. bool WildcardPattern::matches( std::string const& str ) const {
  9842. switch( m_wildcard ) {
  9843. case NoWildcard:
  9844. return m_pattern == adjustCase( str );
  9845. case WildcardAtStart:
  9846. return endsWith( adjustCase( str ), m_pattern );
  9847. case WildcardAtEnd:
  9848. return startsWith( adjustCase( str ), m_pattern );
  9849. case WildcardAtBothEnds:
  9850. return contains( adjustCase( str ), m_pattern );
  9851. default:
  9852. CATCH_INTERNAL_ERROR( "Unknown enum" );
  9853. }
  9854. }
  9855. std::string WildcardPattern::adjustCase( std::string const& str ) const {
  9856. return m_caseSensitivity == CaseSensitive::No ? toLower( str ) : str;
  9857. }
  9858. }
  9859. // end catch_wildcard_pattern.cpp
  9860. // start catch_xmlwriter.cpp
  9861. #include <iomanip>
  9862. using uchar = unsigned char;
  9863. namespace Catch {
  9864. namespace {
  9865. size_t trailingBytes(unsigned char c) {
  9866. if ((c & 0xE0) == 0xC0) {
  9867. return 2;
  9868. }
  9869. if ((c & 0xF0) == 0xE0) {
  9870. return 3;
  9871. }
  9872. if ((c & 0xF8) == 0xF0) {
  9873. return 4;
  9874. }
  9875. CATCH_INTERNAL_ERROR("Invalid multibyte utf-8 start byte encountered");
  9876. }
  9877. uint32_t headerValue(unsigned char c) {
  9878. if ((c & 0xE0) == 0xC0) {
  9879. return c & 0x1F;
  9880. }
  9881. if ((c & 0xF0) == 0xE0) {
  9882. return c & 0x0F;
  9883. }
  9884. if ((c & 0xF8) == 0xF0) {
  9885. return c & 0x07;
  9886. }
  9887. CATCH_INTERNAL_ERROR("Invalid multibyte utf-8 start byte encountered");
  9888. }
  9889. void hexEscapeChar(std::ostream& os, unsigned char c) {
  9890. os << "\\x"
  9891. << std::uppercase << std::hex << std::setfill('0') << std::setw(2)
  9892. << static_cast<int>(c);
  9893. }
  9894. } // anonymous namespace
  9895. XmlEncode::XmlEncode( std::string const& str, ForWhat forWhat )
  9896. : m_str( str ),
  9897. m_forWhat( forWhat )
  9898. {}
  9899. void XmlEncode::encodeTo( std::ostream& os ) const {
  9900. // Apostrophe escaping not necessary if we always use " to write attributes
  9901. // (see: http://www.w3.org/TR/xml/#syntax)
  9902. for( std::size_t idx = 0; idx < m_str.size(); ++ idx ) {
  9903. uchar c = m_str[idx];
  9904. switch (c) {
  9905. case '<': os << "&lt;"; break;
  9906. case '&': os << "&amp;"; break;
  9907. case '>':
  9908. // See: http://www.w3.org/TR/xml/#syntax
  9909. if (idx > 2 && m_str[idx - 1] == ']' && m_str[idx - 2] == ']')
  9910. os << "&gt;";
  9911. else
  9912. os << c;
  9913. break;
  9914. case '\"':
  9915. if (m_forWhat == ForAttributes)
  9916. os << "&quot;";
  9917. else
  9918. os << c;
  9919. break;
  9920. default:
  9921. // Check for control characters and invalid utf-8
  9922. // Escape control characters in standard ascii
  9923. // see http://stackoverflow.com/questions/404107/why-are-control-characters-illegal-in-xml-1-0
  9924. if (c < 0x09 || (c > 0x0D && c < 0x20) || c == 0x7F) {
  9925. hexEscapeChar(os, c);
  9926. break;
  9927. }
  9928. // Plain ASCII: Write it to stream
  9929. if (c < 0x7F) {
  9930. os << c;
  9931. break;
  9932. }
  9933. // UTF-8 territory
  9934. // Check if the encoding is valid and if it is not, hex escape bytes.
  9935. // Important: We do not check the exact decoded values for validity, only the encoding format
  9936. // First check that this bytes is a valid lead byte:
  9937. // This means that it is not encoded as 1111 1XXX
  9938. // Or as 10XX XXXX
  9939. if (c < 0xC0 ||
  9940. c >= 0xF8) {
  9941. hexEscapeChar(os, c);
  9942. break;
  9943. }
  9944. auto encBytes = trailingBytes(c);
  9945. // Are there enough bytes left to avoid accessing out-of-bounds memory?
  9946. if (idx + encBytes - 1 >= m_str.size()) {
  9947. hexEscapeChar(os, c);
  9948. break;
  9949. }
  9950. // The header is valid, check data
  9951. // The next encBytes bytes must together be a valid utf-8
  9952. // This means: bitpattern 10XX XXXX and the extracted value is sane (ish)
  9953. bool valid = true;
  9954. uint32_t value = headerValue(c);
  9955. for (std::size_t n = 1; n < encBytes; ++n) {
  9956. uchar nc = m_str[idx + n];
  9957. valid &= ((nc & 0xC0) == 0x80);
  9958. value = (value << 6) | (nc & 0x3F);
  9959. }
  9960. if (
  9961. // Wrong bit pattern of following bytes
  9962. (!valid) ||
  9963. // Overlong encodings
  9964. (value < 0x80) ||
  9965. (0x80 <= value && value < 0x800 && encBytes > 2) ||
  9966. (0x800 < value && value < 0x10000 && encBytes > 3) ||
  9967. // Encoded value out of range
  9968. (value >= 0x110000)
  9969. ) {
  9970. hexEscapeChar(os, c);
  9971. break;
  9972. }
  9973. // If we got here, this is in fact a valid(ish) utf-8 sequence
  9974. for (std::size_t n = 0; n < encBytes; ++n) {
  9975. os << m_str[idx + n];
  9976. }
  9977. idx += encBytes - 1;
  9978. break;
  9979. }
  9980. }
  9981. }
  9982. std::ostream& operator << ( std::ostream& os, XmlEncode const& xmlEncode ) {
  9983. xmlEncode.encodeTo( os );
  9984. return os;
  9985. }
  9986. XmlWriter::ScopedElement::ScopedElement( XmlWriter* writer )
  9987. : m_writer( writer )
  9988. {}
  9989. XmlWriter::ScopedElement::ScopedElement( ScopedElement&& other ) noexcept
  9990. : m_writer( other.m_writer ){
  9991. other.m_writer = nullptr;
  9992. }
  9993. XmlWriter::ScopedElement& XmlWriter::ScopedElement::operator=( ScopedElement&& other ) noexcept {
  9994. if ( m_writer ) {
  9995. m_writer->endElement();
  9996. }
  9997. m_writer = other.m_writer;
  9998. other.m_writer = nullptr;
  9999. return *this;
  10000. }
  10001. XmlWriter::ScopedElement::~ScopedElement() {
  10002. if( m_writer )
  10003. m_writer->endElement();
  10004. }
  10005. XmlWriter::ScopedElement& XmlWriter::ScopedElement::writeText( std::string const& text, bool indent ) {
  10006. m_writer->writeText( text, indent );
  10007. return *this;
  10008. }
  10009. XmlWriter::XmlWriter( std::ostream& os ) : m_os( os )
  10010. {
  10011. writeDeclaration();
  10012. }
  10013. XmlWriter::~XmlWriter() {
  10014. while( !m_tags.empty() )
  10015. endElement();
  10016. }
  10017. XmlWriter& XmlWriter::startElement( std::string const& name ) {
  10018. ensureTagClosed();
  10019. newlineIfNecessary();
  10020. m_os << m_indent << '<' << name;
  10021. m_tags.push_back( name );
  10022. m_indent += " ";
  10023. m_tagIsOpen = true;
  10024. return *this;
  10025. }
  10026. XmlWriter::ScopedElement XmlWriter::scopedElement( std::string const& name ) {
  10027. ScopedElement scoped( this );
  10028. startElement( name );
  10029. return scoped;
  10030. }
  10031. XmlWriter& XmlWriter::endElement() {
  10032. newlineIfNecessary();
  10033. m_indent = m_indent.substr( 0, m_indent.size()-2 );
  10034. if( m_tagIsOpen ) {
  10035. m_os << "/>";
  10036. m_tagIsOpen = false;
  10037. }
  10038. else {
  10039. m_os << m_indent << "</" << m_tags.back() << ">";
  10040. }
  10041. m_os << std::endl;
  10042. m_tags.pop_back();
  10043. return *this;
  10044. }
  10045. XmlWriter& XmlWriter::writeAttribute( std::string const& name, std::string const& attribute ) {
  10046. if( !name.empty() && !attribute.empty() )
  10047. m_os << ' ' << name << "=\"" << XmlEncode( attribute, XmlEncode::ForAttributes ) << '"';
  10048. return *this;
  10049. }
  10050. XmlWriter& XmlWriter::writeAttribute( std::string const& name, bool attribute ) {
  10051. m_os << ' ' << name << "=\"" << ( attribute ? "true" : "false" ) << '"';
  10052. return *this;
  10053. }
  10054. XmlWriter& XmlWriter::writeText( std::string const& text, bool indent ) {
  10055. if( !text.empty() ){
  10056. bool tagWasOpen = m_tagIsOpen;
  10057. ensureTagClosed();
  10058. if( tagWasOpen && indent )
  10059. m_os << m_indent;
  10060. m_os << XmlEncode( text );
  10061. m_needsNewline = true;
  10062. }
  10063. return *this;
  10064. }
  10065. XmlWriter& XmlWriter::writeComment( std::string const& text ) {
  10066. ensureTagClosed();
  10067. m_os << m_indent << "<!--" << text << "-->";
  10068. m_needsNewline = true;
  10069. return *this;
  10070. }
  10071. void XmlWriter::writeStylesheetRef( std::string const& url ) {
  10072. m_os << "<?xml-stylesheet type=\"text/xsl\" href=\"" << url << "\"?>\n";
  10073. }
  10074. XmlWriter& XmlWriter::writeBlankLine() {
  10075. ensureTagClosed();
  10076. m_os << '\n';
  10077. return *this;
  10078. }
  10079. void XmlWriter::ensureTagClosed() {
  10080. if( m_tagIsOpen ) {
  10081. m_os << ">" << std::endl;
  10082. m_tagIsOpen = false;
  10083. }
  10084. }
  10085. void XmlWriter::writeDeclaration() {
  10086. m_os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
  10087. }
  10088. void XmlWriter::newlineIfNecessary() {
  10089. if( m_needsNewline ) {
  10090. m_os << std::endl;
  10091. m_needsNewline = false;
  10092. }
  10093. }
  10094. }
  10095. // end catch_xmlwriter.cpp
  10096. // start catch_reporter_bases.cpp
  10097. #include <cstring>
  10098. #include <cfloat>
  10099. #include <cstdio>
  10100. #include <cassert>
  10101. #include <memory>
  10102. namespace Catch {
  10103. void prepareExpandedExpression(AssertionResult& result) {
  10104. result.getExpandedExpression();
  10105. }
  10106. // Because formatting using c++ streams is stateful, drop down to C is required
  10107. // Alternatively we could use stringstream, but its performance is... not good.
  10108. std::string getFormattedDuration( double duration ) {
  10109. // Max exponent + 1 is required to represent the whole part
  10110. // + 1 for decimal point
  10111. // + 3 for the 3 decimal places
  10112. // + 1 for null terminator
  10113. const std::size_t maxDoubleSize = DBL_MAX_10_EXP + 1 + 1 + 3 + 1;
  10114. char buffer[maxDoubleSize];
  10115. // Save previous errno, to prevent sprintf from overwriting it
  10116. ErrnoGuard guard;
  10117. #ifdef _MSC_VER
  10118. sprintf_s(buffer, "%.3f", duration);
  10119. #else
  10120. sprintf(buffer, "%.3f", duration);
  10121. #endif
  10122. return std::string(buffer);
  10123. }
  10124. TestEventListenerBase::TestEventListenerBase(ReporterConfig const & _config)
  10125. :StreamingReporterBase(_config) {}
  10126. std::set<Verbosity> TestEventListenerBase::getSupportedVerbosities() {
  10127. return { Verbosity::Quiet, Verbosity::Normal, Verbosity::High };
  10128. }
  10129. void TestEventListenerBase::assertionStarting(AssertionInfo const &) {}
  10130. bool TestEventListenerBase::assertionEnded(AssertionStats const &) {
  10131. return false;
  10132. }
  10133. } // end namespace Catch
  10134. // end catch_reporter_bases.cpp
  10135. // start catch_reporter_compact.cpp
  10136. namespace {
  10137. #ifdef CATCH_PLATFORM_MAC
  10138. const char* failedString() { return "FAILED"; }
  10139. const char* passedString() { return "PASSED"; }
  10140. #else
  10141. const char* failedString() { return "failed"; }
  10142. const char* passedString() { return "passed"; }
  10143. #endif
  10144. // Colour::LightGrey
  10145. Catch::Colour::Code dimColour() { return Catch::Colour::FileName; }
  10146. std::string bothOrAll( std::size_t count ) {
  10147. return count == 1 ? std::string() :
  10148. count == 2 ? "both " : "all " ;
  10149. }
  10150. } // anon namespace
  10151. namespace Catch {
  10152. namespace {
  10153. // Colour, message variants:
  10154. // - white: No tests ran.
  10155. // - red: Failed [both/all] N test cases, failed [both/all] M assertions.
  10156. // - white: Passed [both/all] N test cases (no assertions).
  10157. // - red: Failed N tests cases, failed M assertions.
  10158. // - green: Passed [both/all] N tests cases with M assertions.
  10159. void printTotals(std::ostream& out, const Totals& totals) {
  10160. if (totals.testCases.total() == 0) {
  10161. out << "No tests ran.";
  10162. } else if (totals.testCases.failed == totals.testCases.total()) {
  10163. Colour colour(Colour::ResultError);
  10164. const std::string qualify_assertions_failed =
  10165. totals.assertions.failed == totals.assertions.total() ?
  10166. bothOrAll(totals.assertions.failed) : std::string();
  10167. out <<
  10168. "Failed " << bothOrAll(totals.testCases.failed)
  10169. << pluralise(totals.testCases.failed, "test case") << ", "
  10170. "failed " << qualify_assertions_failed <<
  10171. pluralise(totals.assertions.failed, "assertion") << '.';
  10172. } else if (totals.assertions.total() == 0) {
  10173. out <<
  10174. "Passed " << bothOrAll(totals.testCases.total())
  10175. << pluralise(totals.testCases.total(), "test case")
  10176. << " (no assertions).";
  10177. } else if (totals.assertions.failed) {
  10178. Colour colour(Colour::ResultError);
  10179. out <<
  10180. "Failed " << pluralise(totals.testCases.failed, "test case") << ", "
  10181. "failed " << pluralise(totals.assertions.failed, "assertion") << '.';
  10182. } else {
  10183. Colour colour(Colour::ResultSuccess);
  10184. out <<
  10185. "Passed " << bothOrAll(totals.testCases.passed)
  10186. << pluralise(totals.testCases.passed, "test case") <<
  10187. " with " << pluralise(totals.assertions.passed, "assertion") << '.';
  10188. }
  10189. }
  10190. // Implementation of CompactReporter formatting
  10191. class AssertionPrinter {
  10192. public:
  10193. AssertionPrinter& operator= (AssertionPrinter const&) = delete;
  10194. AssertionPrinter(AssertionPrinter const&) = delete;
  10195. AssertionPrinter(std::ostream& _stream, AssertionStats const& _stats, bool _printInfoMessages)
  10196. : stream(_stream)
  10197. , result(_stats.assertionResult)
  10198. , messages(_stats.infoMessages)
  10199. , itMessage(_stats.infoMessages.begin())
  10200. , printInfoMessages(_printInfoMessages) {}
  10201. void print() {
  10202. printSourceInfo();
  10203. itMessage = messages.begin();
  10204. switch (result.getResultType()) {
  10205. case ResultWas::Ok:
  10206. printResultType(Colour::ResultSuccess, passedString());
  10207. printOriginalExpression();
  10208. printReconstructedExpression();
  10209. if (!result.hasExpression())
  10210. printRemainingMessages(Colour::None);
  10211. else
  10212. printRemainingMessages();
  10213. break;
  10214. case ResultWas::ExpressionFailed:
  10215. if (result.isOk())
  10216. printResultType(Colour::ResultSuccess, failedString() + std::string(" - but was ok"));
  10217. else
  10218. printResultType(Colour::Error, failedString());
  10219. printOriginalExpression();
  10220. printReconstructedExpression();
  10221. printRemainingMessages();
  10222. break;
  10223. case ResultWas::ThrewException:
  10224. printResultType(Colour::Error, failedString());
  10225. printIssue("unexpected exception with message:");
  10226. printMessage();
  10227. printExpressionWas();
  10228. printRemainingMessages();
  10229. break;
  10230. case ResultWas::FatalErrorCondition:
  10231. printResultType(Colour::Error, failedString());
  10232. printIssue("fatal error condition with message:");
  10233. printMessage();
  10234. printExpressionWas();
  10235. printRemainingMessages();
  10236. break;
  10237. case ResultWas::DidntThrowException:
  10238. printResultType(Colour::Error, failedString());
  10239. printIssue("expected exception, got none");
  10240. printExpressionWas();
  10241. printRemainingMessages();
  10242. break;
  10243. case ResultWas::Info:
  10244. printResultType(Colour::None, "info");
  10245. printMessage();
  10246. printRemainingMessages();
  10247. break;
  10248. case ResultWas::Warning:
  10249. printResultType(Colour::None, "warning");
  10250. printMessage();
  10251. printRemainingMessages();
  10252. break;
  10253. case ResultWas::ExplicitFailure:
  10254. printResultType(Colour::Error, failedString());
  10255. printIssue("explicitly");
  10256. printRemainingMessages(Colour::None);
  10257. break;
  10258. // These cases are here to prevent compiler warnings
  10259. case ResultWas::Unknown:
  10260. case ResultWas::FailureBit:
  10261. case ResultWas::Exception:
  10262. printResultType(Colour::Error, "** internal error **");
  10263. break;
  10264. }
  10265. }
  10266. private:
  10267. void printSourceInfo() const {
  10268. Colour colourGuard(Colour::FileName);
  10269. stream << result.getSourceInfo() << ':';
  10270. }
  10271. void printResultType(Colour::Code colour, std::string const& passOrFail) const {
  10272. if (!passOrFail.empty()) {
  10273. {
  10274. Colour colourGuard(colour);
  10275. stream << ' ' << passOrFail;
  10276. }
  10277. stream << ':';
  10278. }
  10279. }
  10280. void printIssue(std::string const& issue) const {
  10281. stream << ' ' << issue;
  10282. }
  10283. void printExpressionWas() {
  10284. if (result.hasExpression()) {
  10285. stream << ';';
  10286. {
  10287. Colour colour(dimColour());
  10288. stream << " expression was:";
  10289. }
  10290. printOriginalExpression();
  10291. }
  10292. }
  10293. void printOriginalExpression() const {
  10294. if (result.hasExpression()) {
  10295. stream << ' ' << result.getExpression();
  10296. }
  10297. }
  10298. void printReconstructedExpression() const {
  10299. if (result.hasExpandedExpression()) {
  10300. {
  10301. Colour colour(dimColour());
  10302. stream << " for: ";
  10303. }
  10304. stream << result.getExpandedExpression();
  10305. }
  10306. }
  10307. void printMessage() {
  10308. if (itMessage != messages.end()) {
  10309. stream << " '" << itMessage->message << '\'';
  10310. ++itMessage;
  10311. }
  10312. }
  10313. void printRemainingMessages(Colour::Code colour = dimColour()) {
  10314. if (itMessage == messages.end())
  10315. return;
  10316. // using messages.end() directly yields (or auto) compilation error:
  10317. std::vector<MessageInfo>::const_iterator itEnd = messages.end();
  10318. const std::size_t N = static_cast<std::size_t>(std::distance(itMessage, itEnd));
  10319. {
  10320. Colour colourGuard(colour);
  10321. stream << " with " << pluralise(N, "message") << ':';
  10322. }
  10323. for (; itMessage != itEnd; ) {
  10324. // If this assertion is a warning ignore any INFO messages
  10325. if (printInfoMessages || itMessage->type != ResultWas::Info) {
  10326. stream << " '" << itMessage->message << '\'';
  10327. if (++itMessage != itEnd) {
  10328. Colour colourGuard(dimColour());
  10329. stream << " and";
  10330. }
  10331. }
  10332. }
  10333. }
  10334. private:
  10335. std::ostream& stream;
  10336. AssertionResult const& result;
  10337. std::vector<MessageInfo> messages;
  10338. std::vector<MessageInfo>::const_iterator itMessage;
  10339. bool printInfoMessages;
  10340. };
  10341. } // anon namespace
  10342. std::string CompactReporter::getDescription() {
  10343. return "Reports test results on a single line, suitable for IDEs";
  10344. }
  10345. ReporterPreferences CompactReporter::getPreferences() const {
  10346. return m_reporterPrefs;
  10347. }
  10348. void CompactReporter::noMatchingTestCases( std::string const& spec ) {
  10349. stream << "No test cases matched '" << spec << '\'' << std::endl;
  10350. }
  10351. void CompactReporter::assertionStarting( AssertionInfo const& ) {}
  10352. bool CompactReporter::assertionEnded( AssertionStats const& _assertionStats ) {
  10353. AssertionResult const& result = _assertionStats.assertionResult;
  10354. bool printInfoMessages = true;
  10355. // Drop out if result was successful and we're not printing those
  10356. if( !m_config->includeSuccessfulResults() && result.isOk() ) {
  10357. if( result.getResultType() != ResultWas::Warning )
  10358. return false;
  10359. printInfoMessages = false;
  10360. }
  10361. AssertionPrinter printer( stream, _assertionStats, printInfoMessages );
  10362. printer.print();
  10363. stream << std::endl;
  10364. return true;
  10365. }
  10366. void CompactReporter::sectionEnded(SectionStats const& _sectionStats) {
  10367. if (m_config->showDurations() == ShowDurations::Always) {
  10368. stream << getFormattedDuration(_sectionStats.durationInSeconds) << " s: " << _sectionStats.sectionInfo.name << std::endl;
  10369. }
  10370. }
  10371. void CompactReporter::testRunEnded( TestRunStats const& _testRunStats ) {
  10372. printTotals( stream, _testRunStats.totals );
  10373. stream << '\n' << std::endl;
  10374. StreamingReporterBase::testRunEnded( _testRunStats );
  10375. }
  10376. CompactReporter::~CompactReporter() {}
  10377. CATCH_REGISTER_REPORTER( "compact", CompactReporter )
  10378. } // end namespace Catch
  10379. // end catch_reporter_compact.cpp
  10380. // start catch_reporter_console.cpp
  10381. #include <cfloat>
  10382. #include <cstdio>
  10383. #if defined(_MSC_VER)
  10384. #pragma warning(push)
  10385. #pragma warning(disable:4061) // Not all labels are EXPLICITLY handled in switch
  10386. // Note that 4062 (not all labels are handled
  10387. // and default is missing) is enabled
  10388. #endif
  10389. namespace Catch {
  10390. namespace {
  10391. // Formatter impl for ConsoleReporter
  10392. class ConsoleAssertionPrinter {
  10393. public:
  10394. ConsoleAssertionPrinter& operator= (ConsoleAssertionPrinter const&) = delete;
  10395. ConsoleAssertionPrinter(ConsoleAssertionPrinter const&) = delete;
  10396. ConsoleAssertionPrinter(std::ostream& _stream, AssertionStats const& _stats, bool _printInfoMessages)
  10397. : stream(_stream),
  10398. stats(_stats),
  10399. result(_stats.assertionResult),
  10400. colour(Colour::None),
  10401. message(result.getMessage()),
  10402. messages(_stats.infoMessages),
  10403. printInfoMessages(_printInfoMessages) {
  10404. switch (result.getResultType()) {
  10405. case ResultWas::Ok:
  10406. colour = Colour::Success;
  10407. passOrFail = "PASSED";
  10408. //if( result.hasMessage() )
  10409. if (_stats.infoMessages.size() == 1)
  10410. messageLabel = "with message";
  10411. if (_stats.infoMessages.size() > 1)
  10412. messageLabel = "with messages";
  10413. break;
  10414. case ResultWas::ExpressionFailed:
  10415. if (result.isOk()) {
  10416. colour = Colour::Success;
  10417. passOrFail = "FAILED - but was ok";
  10418. } else {
  10419. colour = Colour::Error;
  10420. passOrFail = "FAILED";
  10421. }
  10422. if (_stats.infoMessages.size() == 1)
  10423. messageLabel = "with message";
  10424. if (_stats.infoMessages.size() > 1)
  10425. messageLabel = "with messages";
  10426. break;
  10427. case ResultWas::ThrewException:
  10428. colour = Colour::Error;
  10429. passOrFail = "FAILED";
  10430. messageLabel = "due to unexpected exception with ";
  10431. if (_stats.infoMessages.size() == 1)
  10432. messageLabel += "message";
  10433. if (_stats.infoMessages.size() > 1)
  10434. messageLabel += "messages";
  10435. break;
  10436. case ResultWas::FatalErrorCondition:
  10437. colour = Colour::Error;
  10438. passOrFail = "FAILED";
  10439. messageLabel = "due to a fatal error condition";
  10440. break;
  10441. case ResultWas::DidntThrowException:
  10442. colour = Colour::Error;
  10443. passOrFail = "FAILED";
  10444. messageLabel = "because no exception was thrown where one was expected";
  10445. break;
  10446. case ResultWas::Info:
  10447. messageLabel = "info";
  10448. break;
  10449. case ResultWas::Warning:
  10450. messageLabel = "warning";
  10451. break;
  10452. case ResultWas::ExplicitFailure:
  10453. passOrFail = "FAILED";
  10454. colour = Colour::Error;
  10455. if (_stats.infoMessages.size() == 1)
  10456. messageLabel = "explicitly with message";
  10457. if (_stats.infoMessages.size() > 1)
  10458. messageLabel = "explicitly with messages";
  10459. break;
  10460. // These cases are here to prevent compiler warnings
  10461. case ResultWas::Unknown:
  10462. case ResultWas::FailureBit:
  10463. case ResultWas::Exception:
  10464. passOrFail = "** internal error **";
  10465. colour = Colour::Error;
  10466. break;
  10467. }
  10468. }
  10469. void print() const {
  10470. printSourceInfo();
  10471. if (stats.totals.assertions.total() > 0) {
  10472. printResultType();
  10473. printOriginalExpression();
  10474. printReconstructedExpression();
  10475. } else {
  10476. stream << '\n';
  10477. }
  10478. printMessage();
  10479. }
  10480. private:
  10481. void printResultType() const {
  10482. if (!passOrFail.empty()) {
  10483. Colour colourGuard(colour);
  10484. stream << passOrFail << ":\n";
  10485. }
  10486. }
  10487. void printOriginalExpression() const {
  10488. if (result.hasExpression()) {
  10489. Colour colourGuard(Colour::OriginalExpression);
  10490. stream << " ";
  10491. stream << result.getExpressionInMacro();
  10492. stream << '\n';
  10493. }
  10494. }
  10495. void printReconstructedExpression() const {
  10496. if (result.hasExpandedExpression()) {
  10497. stream << "with expansion:\n";
  10498. Colour colourGuard(Colour::ReconstructedExpression);
  10499. stream << Column(result.getExpandedExpression()).indent(2) << '\n';
  10500. }
  10501. }
  10502. void printMessage() const {
  10503. if (!messageLabel.empty())
  10504. stream << messageLabel << ':' << '\n';
  10505. for (auto const& msg : messages) {
  10506. // If this assertion is a warning ignore any INFO messages
  10507. if (printInfoMessages || msg.type != ResultWas::Info)
  10508. stream << Column(msg.message).indent(2) << '\n';
  10509. }
  10510. }
  10511. void printSourceInfo() const {
  10512. Colour colourGuard(Colour::FileName);
  10513. stream << result.getSourceInfo() << ": ";
  10514. }
  10515. std::ostream& stream;
  10516. AssertionStats const& stats;
  10517. AssertionResult const& result;
  10518. Colour::Code colour;
  10519. std::string passOrFail;
  10520. std::string messageLabel;
  10521. std::string message;
  10522. std::vector<MessageInfo> messages;
  10523. bool printInfoMessages;
  10524. };
  10525. std::size_t makeRatio(std::size_t number, std::size_t total) {
  10526. std::size_t ratio = total > 0 ? CATCH_CONFIG_CONSOLE_WIDTH * number / total : 0;
  10527. return (ratio == 0 && number > 0) ? 1 : ratio;
  10528. }
  10529. std::size_t& findMax(std::size_t& i, std::size_t& j, std::size_t& k) {
  10530. if (i > j && i > k)
  10531. return i;
  10532. else if (j > k)
  10533. return j;
  10534. else
  10535. return k;
  10536. }
  10537. struct ColumnInfo {
  10538. enum Justification { Left, Right };
  10539. std::string name;
  10540. int width;
  10541. Justification justification;
  10542. };
  10543. struct ColumnBreak {};
  10544. struct RowBreak {};
  10545. class Duration {
  10546. enum class Unit {
  10547. Auto,
  10548. Nanoseconds,
  10549. Microseconds,
  10550. Milliseconds,
  10551. Seconds,
  10552. Minutes
  10553. };
  10554. static const uint64_t s_nanosecondsInAMicrosecond = 1000;
  10555. static const uint64_t s_nanosecondsInAMillisecond = 1000 * s_nanosecondsInAMicrosecond;
  10556. static const uint64_t s_nanosecondsInASecond = 1000 * s_nanosecondsInAMillisecond;
  10557. static const uint64_t s_nanosecondsInAMinute = 60 * s_nanosecondsInASecond;
  10558. uint64_t m_inNanoseconds;
  10559. Unit m_units;
  10560. public:
  10561. explicit Duration(uint64_t inNanoseconds, Unit units = Unit::Auto)
  10562. : m_inNanoseconds(inNanoseconds),
  10563. m_units(units) {
  10564. if (m_units == Unit::Auto) {
  10565. if (m_inNanoseconds < s_nanosecondsInAMicrosecond)
  10566. m_units = Unit::Nanoseconds;
  10567. else if (m_inNanoseconds < s_nanosecondsInAMillisecond)
  10568. m_units = Unit::Microseconds;
  10569. else if (m_inNanoseconds < s_nanosecondsInASecond)
  10570. m_units = Unit::Milliseconds;
  10571. else if (m_inNanoseconds < s_nanosecondsInAMinute)
  10572. m_units = Unit::Seconds;
  10573. else
  10574. m_units = Unit::Minutes;
  10575. }
  10576. }
  10577. auto value() const -> double {
  10578. switch (m_units) {
  10579. case Unit::Microseconds:
  10580. return m_inNanoseconds / static_cast<double>(s_nanosecondsInAMicrosecond);
  10581. case Unit::Milliseconds:
  10582. return m_inNanoseconds / static_cast<double>(s_nanosecondsInAMillisecond);
  10583. case Unit::Seconds:
  10584. return m_inNanoseconds / static_cast<double>(s_nanosecondsInASecond);
  10585. case Unit::Minutes:
  10586. return m_inNanoseconds / static_cast<double>(s_nanosecondsInAMinute);
  10587. default:
  10588. return static_cast<double>(m_inNanoseconds);
  10589. }
  10590. }
  10591. auto unitsAsString() const -> std::string {
  10592. switch (m_units) {
  10593. case Unit::Nanoseconds:
  10594. return "ns";
  10595. case Unit::Microseconds:
  10596. return "µs";
  10597. case Unit::Milliseconds:
  10598. return "ms";
  10599. case Unit::Seconds:
  10600. return "s";
  10601. case Unit::Minutes:
  10602. return "m";
  10603. default:
  10604. return "** internal error **";
  10605. }
  10606. }
  10607. friend auto operator << (std::ostream& os, Duration const& duration) -> std::ostream& {
  10608. return os << duration.value() << " " << duration.unitsAsString();
  10609. }
  10610. };
  10611. } // end anon namespace
  10612. class TablePrinter {
  10613. std::ostream& m_os;
  10614. std::vector<ColumnInfo> m_columnInfos;
  10615. std::ostringstream m_oss;
  10616. int m_currentColumn = -1;
  10617. bool m_isOpen = false;
  10618. public:
  10619. TablePrinter( std::ostream& os, std::vector<ColumnInfo> columnInfos )
  10620. : m_os( os ),
  10621. m_columnInfos( std::move( columnInfos ) ) {}
  10622. auto columnInfos() const -> std::vector<ColumnInfo> const& {
  10623. return m_columnInfos;
  10624. }
  10625. void open() {
  10626. if (!m_isOpen) {
  10627. m_isOpen = true;
  10628. *this << RowBreak();
  10629. for (auto const& info : m_columnInfos)
  10630. *this << info.name << ColumnBreak();
  10631. *this << RowBreak();
  10632. m_os << Catch::getLineOfChars<'-'>() << "\n";
  10633. }
  10634. }
  10635. void close() {
  10636. if (m_isOpen) {
  10637. *this << RowBreak();
  10638. m_os << std::endl;
  10639. m_isOpen = false;
  10640. }
  10641. }
  10642. template<typename T>
  10643. friend TablePrinter& operator << (TablePrinter& tp, T const& value) {
  10644. tp.m_oss << value;
  10645. return tp;
  10646. }
  10647. friend TablePrinter& operator << (TablePrinter& tp, ColumnBreak) {
  10648. auto colStr = tp.m_oss.str();
  10649. // This takes account of utf8 encodings
  10650. auto strSize = Catch::StringRef(colStr).numberOfCharacters();
  10651. tp.m_oss.str("");
  10652. tp.open();
  10653. if (tp.m_currentColumn == static_cast<int>(tp.m_columnInfos.size() - 1)) {
  10654. tp.m_currentColumn = -1;
  10655. tp.m_os << "\n";
  10656. }
  10657. tp.m_currentColumn++;
  10658. auto colInfo = tp.m_columnInfos[tp.m_currentColumn];
  10659. auto padding = (strSize + 2 < static_cast<std::size_t>(colInfo.width))
  10660. ? std::string(colInfo.width - (strSize + 2), ' ')
  10661. : std::string();
  10662. if (colInfo.justification == ColumnInfo::Left)
  10663. tp.m_os << colStr << padding << " ";
  10664. else
  10665. tp.m_os << padding << colStr << " ";
  10666. return tp;
  10667. }
  10668. friend TablePrinter& operator << (TablePrinter& tp, RowBreak) {
  10669. if (tp.m_currentColumn > 0) {
  10670. tp.m_os << "\n";
  10671. tp.m_currentColumn = -1;
  10672. }
  10673. return tp;
  10674. }
  10675. };
  10676. ConsoleReporter::ConsoleReporter(ReporterConfig const& config)
  10677. : StreamingReporterBase(config),
  10678. m_tablePrinter(new TablePrinter(config.stream(),
  10679. {
  10680. { "benchmark name", CATCH_CONFIG_CONSOLE_WIDTH - 32, ColumnInfo::Left },
  10681. { "iters", 8, ColumnInfo::Right },
  10682. { "elapsed ns", 14, ColumnInfo::Right },
  10683. { "average", 14, ColumnInfo::Right }
  10684. })) {}
  10685. ConsoleReporter::~ConsoleReporter() = default;
  10686. std::string ConsoleReporter::getDescription() {
  10687. return "Reports test results as plain lines of text";
  10688. }
  10689. void ConsoleReporter::noMatchingTestCases(std::string const& spec) {
  10690. stream << "No test cases matched '" << spec << '\'' << std::endl;
  10691. }
  10692. void ConsoleReporter::assertionStarting(AssertionInfo const&) {}
  10693. bool ConsoleReporter::assertionEnded(AssertionStats const& _assertionStats) {
  10694. AssertionResult const& result = _assertionStats.assertionResult;
  10695. bool includeResults = m_config->includeSuccessfulResults() || !result.isOk();
  10696. // Drop out if result was successful but we're not printing them.
  10697. if (!includeResults && result.getResultType() != ResultWas::Warning)
  10698. return false;
  10699. lazyPrint();
  10700. ConsoleAssertionPrinter printer(stream, _assertionStats, includeResults);
  10701. printer.print();
  10702. stream << std::endl;
  10703. return true;
  10704. }
  10705. void ConsoleReporter::sectionStarting(SectionInfo const& _sectionInfo) {
  10706. m_headerPrinted = false;
  10707. StreamingReporterBase::sectionStarting(_sectionInfo);
  10708. }
  10709. void ConsoleReporter::sectionEnded(SectionStats const& _sectionStats) {
  10710. m_tablePrinter->close();
  10711. if (_sectionStats.missingAssertions) {
  10712. lazyPrint();
  10713. Colour colour(Colour::ResultError);
  10714. if (m_sectionStack.size() > 1)
  10715. stream << "\nNo assertions in section";
  10716. else
  10717. stream << "\nNo assertions in test case";
  10718. stream << " '" << _sectionStats.sectionInfo.name << "'\n" << std::endl;
  10719. }
  10720. if (m_config->showDurations() == ShowDurations::Always) {
  10721. stream << getFormattedDuration(_sectionStats.durationInSeconds) << " s: " << _sectionStats.sectionInfo.name << std::endl;
  10722. }
  10723. if (m_headerPrinted) {
  10724. m_headerPrinted = false;
  10725. }
  10726. StreamingReporterBase::sectionEnded(_sectionStats);
  10727. }
  10728. void ConsoleReporter::benchmarkStarting(BenchmarkInfo const& info) {
  10729. lazyPrintWithoutClosingBenchmarkTable();
  10730. auto nameCol = Column( info.name ).width( static_cast<std::size_t>( m_tablePrinter->columnInfos()[0].width - 2 ) );
  10731. bool firstLine = true;
  10732. for (auto line : nameCol) {
  10733. if (!firstLine)
  10734. (*m_tablePrinter) << ColumnBreak() << ColumnBreak() << ColumnBreak();
  10735. else
  10736. firstLine = false;
  10737. (*m_tablePrinter) << line << ColumnBreak();
  10738. }
  10739. }
  10740. void ConsoleReporter::benchmarkEnded(BenchmarkStats const& stats) {
  10741. Duration average(stats.elapsedTimeInNanoseconds / stats.iterations);
  10742. (*m_tablePrinter)
  10743. << stats.iterations << ColumnBreak()
  10744. << stats.elapsedTimeInNanoseconds << ColumnBreak()
  10745. << average << ColumnBreak();
  10746. }
  10747. void ConsoleReporter::testCaseEnded(TestCaseStats const& _testCaseStats) {
  10748. m_tablePrinter->close();
  10749. StreamingReporterBase::testCaseEnded(_testCaseStats);
  10750. m_headerPrinted = false;
  10751. }
  10752. void ConsoleReporter::testGroupEnded(TestGroupStats const& _testGroupStats) {
  10753. if (currentGroupInfo.used) {
  10754. printSummaryDivider();
  10755. stream << "Summary for group '" << _testGroupStats.groupInfo.name << "':\n";
  10756. printTotals(_testGroupStats.totals);
  10757. stream << '\n' << std::endl;
  10758. }
  10759. StreamingReporterBase::testGroupEnded(_testGroupStats);
  10760. }
  10761. void ConsoleReporter::testRunEnded(TestRunStats const& _testRunStats) {
  10762. printTotalsDivider(_testRunStats.totals);
  10763. printTotals(_testRunStats.totals);
  10764. stream << std::endl;
  10765. StreamingReporterBase::testRunEnded(_testRunStats);
  10766. }
  10767. void ConsoleReporter::lazyPrint() {
  10768. m_tablePrinter->close();
  10769. lazyPrintWithoutClosingBenchmarkTable();
  10770. }
  10771. void ConsoleReporter::lazyPrintWithoutClosingBenchmarkTable() {
  10772. if (!currentTestRunInfo.used)
  10773. lazyPrintRunInfo();
  10774. if (!currentGroupInfo.used)
  10775. lazyPrintGroupInfo();
  10776. if (!m_headerPrinted) {
  10777. printTestCaseAndSectionHeader();
  10778. m_headerPrinted = true;
  10779. }
  10780. }
  10781. void ConsoleReporter::lazyPrintRunInfo() {
  10782. stream << '\n' << getLineOfChars<'~'>() << '\n';
  10783. Colour colour(Colour::SecondaryText);
  10784. stream << currentTestRunInfo->name
  10785. << " is a Catch v" << libraryVersion() << " host application.\n"
  10786. << "Run with -? for options\n\n";
  10787. if (m_config->rngSeed() != 0)
  10788. stream << "Randomness seeded to: " << m_config->rngSeed() << "\n\n";
  10789. currentTestRunInfo.used = true;
  10790. }
  10791. void ConsoleReporter::lazyPrintGroupInfo() {
  10792. if (!currentGroupInfo->name.empty() && currentGroupInfo->groupsCounts > 1) {
  10793. printClosedHeader("Group: " + currentGroupInfo->name);
  10794. currentGroupInfo.used = true;
  10795. }
  10796. }
  10797. void ConsoleReporter::printTestCaseAndSectionHeader() {
  10798. assert(!m_sectionStack.empty());
  10799. printOpenHeader(currentTestCaseInfo->name);
  10800. if (m_sectionStack.size() > 1) {
  10801. Colour colourGuard(Colour::Headers);
  10802. auto
  10803. it = m_sectionStack.begin() + 1, // Skip first section (test case)
  10804. itEnd = m_sectionStack.end();
  10805. for (; it != itEnd; ++it)
  10806. printHeaderString(it->name, 2);
  10807. }
  10808. SourceLineInfo lineInfo = m_sectionStack.back().lineInfo;
  10809. if (!lineInfo.empty()) {
  10810. stream << getLineOfChars<'-'>() << '\n';
  10811. Colour colourGuard(Colour::FileName);
  10812. stream << lineInfo << '\n';
  10813. }
  10814. stream << getLineOfChars<'.'>() << '\n' << std::endl;
  10815. }
  10816. void ConsoleReporter::printClosedHeader(std::string const& _name) {
  10817. printOpenHeader(_name);
  10818. stream << getLineOfChars<'.'>() << '\n';
  10819. }
  10820. void ConsoleReporter::printOpenHeader(std::string const& _name) {
  10821. stream << getLineOfChars<'-'>() << '\n';
  10822. {
  10823. Colour colourGuard(Colour::Headers);
  10824. printHeaderString(_name);
  10825. }
  10826. }
  10827. // if string has a : in first line will set indent to follow it on
  10828. // subsequent lines
  10829. void ConsoleReporter::printHeaderString(std::string const& _string, std::size_t indent) {
  10830. std::size_t i = _string.find(": ");
  10831. if (i != std::string::npos)
  10832. i += 2;
  10833. else
  10834. i = 0;
  10835. stream << Column(_string).indent(indent + i).initialIndent(indent) << '\n';
  10836. }
  10837. struct SummaryColumn {
  10838. SummaryColumn( std::string _label, Colour::Code _colour )
  10839. : label( std::move( _label ) ),
  10840. colour( _colour ) {}
  10841. SummaryColumn addRow( std::size_t count ) {
  10842. ReusableStringStream rss;
  10843. rss << count;
  10844. std::string row = rss.str();
  10845. for (auto& oldRow : rows) {
  10846. while (oldRow.size() < row.size())
  10847. oldRow = ' ' + oldRow;
  10848. while (oldRow.size() > row.size())
  10849. row = ' ' + row;
  10850. }
  10851. rows.push_back(row);
  10852. return *this;
  10853. }
  10854. std::string label;
  10855. Colour::Code colour;
  10856. std::vector<std::string> rows;
  10857. };
  10858. void ConsoleReporter::printTotals( Totals const& totals ) {
  10859. if (totals.testCases.total() == 0) {
  10860. stream << Colour(Colour::Warning) << "No tests ran\n";
  10861. } else if (totals.assertions.total() > 0 && totals.testCases.allPassed()) {
  10862. stream << Colour(Colour::ResultSuccess) << "All tests passed";
  10863. stream << " ("
  10864. << pluralise(totals.assertions.passed, "assertion") << " in "
  10865. << pluralise(totals.testCases.passed, "test case") << ')'
  10866. << '\n';
  10867. } else {
  10868. std::vector<SummaryColumn> columns;
  10869. columns.push_back(SummaryColumn("", Colour::None)
  10870. .addRow(totals.testCases.total())
  10871. .addRow(totals.assertions.total()));
  10872. columns.push_back(SummaryColumn("passed", Colour::Success)
  10873. .addRow(totals.testCases.passed)
  10874. .addRow(totals.assertions.passed));
  10875. columns.push_back(SummaryColumn("failed", Colour::ResultError)
  10876. .addRow(totals.testCases.failed)
  10877. .addRow(totals.assertions.failed));
  10878. columns.push_back(SummaryColumn("failed as expected", Colour::ResultExpectedFailure)
  10879. .addRow(totals.testCases.failedButOk)
  10880. .addRow(totals.assertions.failedButOk));
  10881. printSummaryRow("test cases", columns, 0);
  10882. printSummaryRow("assertions", columns, 1);
  10883. }
  10884. }
  10885. void ConsoleReporter::printSummaryRow(std::string const& label, std::vector<SummaryColumn> const& cols, std::size_t row) {
  10886. for (auto col : cols) {
  10887. std::string value = col.rows[row];
  10888. if (col.label.empty()) {
  10889. stream << label << ": ";
  10890. if (value != "0")
  10891. stream << value;
  10892. else
  10893. stream << Colour(Colour::Warning) << "- none -";
  10894. } else if (value != "0") {
  10895. stream << Colour(Colour::LightGrey) << " | ";
  10896. stream << Colour(col.colour)
  10897. << value << ' ' << col.label;
  10898. }
  10899. }
  10900. stream << '\n';
  10901. }
  10902. void ConsoleReporter::printTotalsDivider(Totals const& totals) {
  10903. if (totals.testCases.total() > 0) {
  10904. std::size_t failedRatio = makeRatio(totals.testCases.failed, totals.testCases.total());
  10905. std::size_t failedButOkRatio = makeRatio(totals.testCases.failedButOk, totals.testCases.total());
  10906. std::size_t passedRatio = makeRatio(totals.testCases.passed, totals.testCases.total());
  10907. while (failedRatio + failedButOkRatio + passedRatio < CATCH_CONFIG_CONSOLE_WIDTH - 1)
  10908. findMax(failedRatio, failedButOkRatio, passedRatio)++;
  10909. while (failedRatio + failedButOkRatio + passedRatio > CATCH_CONFIG_CONSOLE_WIDTH - 1)
  10910. findMax(failedRatio, failedButOkRatio, passedRatio)--;
  10911. stream << Colour(Colour::Error) << std::string(failedRatio, '=');
  10912. stream << Colour(Colour::ResultExpectedFailure) << std::string(failedButOkRatio, '=');
  10913. if (totals.testCases.allPassed())
  10914. stream << Colour(Colour::ResultSuccess) << std::string(passedRatio, '=');
  10915. else
  10916. stream << Colour(Colour::Success) << std::string(passedRatio, '=');
  10917. } else {
  10918. stream << Colour(Colour::Warning) << std::string(CATCH_CONFIG_CONSOLE_WIDTH - 1, '=');
  10919. }
  10920. stream << '\n';
  10921. }
  10922. void ConsoleReporter::printSummaryDivider() {
  10923. stream << getLineOfChars<'-'>() << '\n';
  10924. }
  10925. CATCH_REGISTER_REPORTER("console", ConsoleReporter)
  10926. } // end namespace Catch
  10927. #if defined(_MSC_VER)
  10928. #pragma warning(pop)
  10929. #endif
  10930. // end catch_reporter_console.cpp
  10931. // start catch_reporter_junit.cpp
  10932. #include <cassert>
  10933. #include <sstream>
  10934. #include <ctime>
  10935. #include <algorithm>
  10936. namespace Catch {
  10937. namespace {
  10938. std::string getCurrentTimestamp() {
  10939. // Beware, this is not reentrant because of backward compatibility issues
  10940. // Also, UTC only, again because of backward compatibility (%z is C++11)
  10941. time_t rawtime;
  10942. std::time(&rawtime);
  10943. auto const timeStampSize = sizeof("2017-01-16T17:06:45Z");
  10944. #ifdef _MSC_VER
  10945. std::tm timeInfo = {};
  10946. gmtime_s(&timeInfo, &rawtime);
  10947. #else
  10948. std::tm* timeInfo;
  10949. timeInfo = std::gmtime(&rawtime);
  10950. #endif
  10951. char timeStamp[timeStampSize];
  10952. const char * const fmt = "%Y-%m-%dT%H:%M:%SZ";
  10953. #ifdef _MSC_VER
  10954. std::strftime(timeStamp, timeStampSize, fmt, &timeInfo);
  10955. #else
  10956. std::strftime(timeStamp, timeStampSize, fmt, timeInfo);
  10957. #endif
  10958. return std::string(timeStamp);
  10959. }
  10960. std::string fileNameTag(const std::vector<std::string> &tags) {
  10961. auto it = std::find_if(begin(tags),
  10962. end(tags),
  10963. [] (std::string const& tag) {return tag.front() == '#'; });
  10964. if (it != tags.end())
  10965. return it->substr(1);
  10966. return std::string();
  10967. }
  10968. } // anonymous namespace
  10969. JunitReporter::JunitReporter( ReporterConfig const& _config )
  10970. : CumulativeReporterBase( _config ),
  10971. xml( _config.stream() )
  10972. {
  10973. m_reporterPrefs.shouldRedirectStdOut = true;
  10974. m_reporterPrefs.shouldReportAllAssertions = true;
  10975. }
  10976. JunitReporter::~JunitReporter() {}
  10977. std::string JunitReporter::getDescription() {
  10978. return "Reports test results in an XML format that looks like Ant's junitreport target";
  10979. }
  10980. void JunitReporter::noMatchingTestCases( std::string const& /*spec*/ ) {}
  10981. void JunitReporter::testRunStarting( TestRunInfo const& runInfo ) {
  10982. CumulativeReporterBase::testRunStarting( runInfo );
  10983. xml.startElement( "testsuites" );
  10984. }
  10985. void JunitReporter::testGroupStarting( GroupInfo const& groupInfo ) {
  10986. suiteTimer.start();
  10987. stdOutForSuite.clear();
  10988. stdErrForSuite.clear();
  10989. unexpectedExceptions = 0;
  10990. CumulativeReporterBase::testGroupStarting( groupInfo );
  10991. }
  10992. void JunitReporter::testCaseStarting( TestCaseInfo const& testCaseInfo ) {
  10993. m_okToFail = testCaseInfo.okToFail();
  10994. }
  10995. bool JunitReporter::assertionEnded( AssertionStats const& assertionStats ) {
  10996. if( assertionStats.assertionResult.getResultType() == ResultWas::ThrewException && !m_okToFail )
  10997. unexpectedExceptions++;
  10998. return CumulativeReporterBase::assertionEnded( assertionStats );
  10999. }
  11000. void JunitReporter::testCaseEnded( TestCaseStats const& testCaseStats ) {
  11001. stdOutForSuite += testCaseStats.stdOut;
  11002. stdErrForSuite += testCaseStats.stdErr;
  11003. CumulativeReporterBase::testCaseEnded( testCaseStats );
  11004. }
  11005. void JunitReporter::testGroupEnded( TestGroupStats const& testGroupStats ) {
  11006. double suiteTime = suiteTimer.getElapsedSeconds();
  11007. CumulativeReporterBase::testGroupEnded( testGroupStats );
  11008. writeGroup( *m_testGroups.back(), suiteTime );
  11009. }
  11010. void JunitReporter::testRunEndedCumulative() {
  11011. xml.endElement();
  11012. }
  11013. void JunitReporter::writeGroup( TestGroupNode const& groupNode, double suiteTime ) {
  11014. XmlWriter::ScopedElement e = xml.scopedElement( "testsuite" );
  11015. TestGroupStats const& stats = groupNode.value;
  11016. xml.writeAttribute( "name", stats.groupInfo.name );
  11017. xml.writeAttribute( "errors", unexpectedExceptions );
  11018. xml.writeAttribute( "failures", stats.totals.assertions.failed-unexpectedExceptions );
  11019. xml.writeAttribute( "tests", stats.totals.assertions.total() );
  11020. xml.writeAttribute( "hostname", "tbd" ); // !TBD
  11021. if( m_config->showDurations() == ShowDurations::Never )
  11022. xml.writeAttribute( "time", "" );
  11023. else
  11024. xml.writeAttribute( "time", suiteTime );
  11025. xml.writeAttribute( "timestamp", getCurrentTimestamp() );
  11026. // Write test cases
  11027. for( auto const& child : groupNode.children )
  11028. writeTestCase( *child );
  11029. xml.scopedElement( "system-out" ).writeText( trim( stdOutForSuite ), false );
  11030. xml.scopedElement( "system-err" ).writeText( trim( stdErrForSuite ), false );
  11031. }
  11032. void JunitReporter::writeTestCase( TestCaseNode const& testCaseNode ) {
  11033. TestCaseStats const& stats = testCaseNode.value;
  11034. // All test cases have exactly one section - which represents the
  11035. // test case itself. That section may have 0-n nested sections
  11036. assert( testCaseNode.children.size() == 1 );
  11037. SectionNode const& rootSection = *testCaseNode.children.front();
  11038. std::string className = stats.testInfo.className;
  11039. if( className.empty() ) {
  11040. className = fileNameTag(stats.testInfo.tags);
  11041. if ( className.empty() )
  11042. className = "global";
  11043. }
  11044. if ( !m_config->name().empty() )
  11045. className = m_config->name() + "." + className;
  11046. writeSection( className, "", rootSection );
  11047. }
  11048. void JunitReporter::writeSection( std::string const& className,
  11049. std::string const& rootName,
  11050. SectionNode const& sectionNode ) {
  11051. std::string name = trim( sectionNode.stats.sectionInfo.name );
  11052. if( !rootName.empty() )
  11053. name = rootName + '/' + name;
  11054. if( !sectionNode.assertions.empty() ||
  11055. !sectionNode.stdOut.empty() ||
  11056. !sectionNode.stdErr.empty() ) {
  11057. XmlWriter::ScopedElement e = xml.scopedElement( "testcase" );
  11058. if( className.empty() ) {
  11059. xml.writeAttribute( "classname", name );
  11060. xml.writeAttribute( "name", "root" );
  11061. }
  11062. else {
  11063. xml.writeAttribute( "classname", className );
  11064. xml.writeAttribute( "name", name );
  11065. }
  11066. xml.writeAttribute( "time", ::Catch::Detail::stringify( sectionNode.stats.durationInSeconds ) );
  11067. writeAssertions( sectionNode );
  11068. if( !sectionNode.stdOut.empty() )
  11069. xml.scopedElement( "system-out" ).writeText( trim( sectionNode.stdOut ), false );
  11070. if( !sectionNode.stdErr.empty() )
  11071. xml.scopedElement( "system-err" ).writeText( trim( sectionNode.stdErr ), false );
  11072. }
  11073. for( auto const& childNode : sectionNode.childSections )
  11074. if( className.empty() )
  11075. writeSection( name, "", *childNode );
  11076. else
  11077. writeSection( className, name, *childNode );
  11078. }
  11079. void JunitReporter::writeAssertions( SectionNode const& sectionNode ) {
  11080. for( auto const& assertion : sectionNode.assertions )
  11081. writeAssertion( assertion );
  11082. }
  11083. void JunitReporter::writeAssertion( AssertionStats const& stats ) {
  11084. AssertionResult const& result = stats.assertionResult;
  11085. if( !result.isOk() ) {
  11086. std::string elementName;
  11087. switch( result.getResultType() ) {
  11088. case ResultWas::ThrewException:
  11089. case ResultWas::FatalErrorCondition:
  11090. elementName = "error";
  11091. break;
  11092. case ResultWas::ExplicitFailure:
  11093. elementName = "failure";
  11094. break;
  11095. case ResultWas::ExpressionFailed:
  11096. elementName = "failure";
  11097. break;
  11098. case ResultWas::DidntThrowException:
  11099. elementName = "failure";
  11100. break;
  11101. // We should never see these here:
  11102. case ResultWas::Info:
  11103. case ResultWas::Warning:
  11104. case ResultWas::Ok:
  11105. case ResultWas::Unknown:
  11106. case ResultWas::FailureBit:
  11107. case ResultWas::Exception:
  11108. elementName = "internalError";
  11109. break;
  11110. }
  11111. XmlWriter::ScopedElement e = xml.scopedElement( elementName );
  11112. xml.writeAttribute( "message", result.getExpandedExpression() );
  11113. xml.writeAttribute( "type", result.getTestMacroName() );
  11114. ReusableStringStream rss;
  11115. if( !result.getMessage().empty() )
  11116. rss << result.getMessage() << '\n';
  11117. for( auto const& msg : stats.infoMessages )
  11118. if( msg.type == ResultWas::Info )
  11119. rss << msg.message << '\n';
  11120. rss << "at " << result.getSourceInfo();
  11121. xml.writeText( rss.str(), false );
  11122. }
  11123. }
  11124. CATCH_REGISTER_REPORTER( "junit", JunitReporter )
  11125. } // end namespace Catch
  11126. // end catch_reporter_junit.cpp
  11127. // start catch_reporter_listening.cpp
  11128. #include <cassert>
  11129. namespace Catch {
  11130. ListeningReporter::ListeningReporter() {
  11131. // We will assume that listeners will always want all assertions
  11132. m_preferences.shouldReportAllAssertions = true;
  11133. }
  11134. void ListeningReporter::addListener( IStreamingReporterPtr&& listener ) {
  11135. m_listeners.push_back( std::move( listener ) );
  11136. }
  11137. void ListeningReporter::addReporter(IStreamingReporterPtr&& reporter) {
  11138. assert(!m_reporter && "Listening reporter can wrap only 1 real reporter");
  11139. m_reporter = std::move( reporter );
  11140. m_preferences.shouldRedirectStdOut = m_reporter->getPreferences().shouldRedirectStdOut;
  11141. }
  11142. ReporterPreferences ListeningReporter::getPreferences() const {
  11143. return m_preferences;
  11144. }
  11145. std::set<Verbosity> ListeningReporter::getSupportedVerbosities() {
  11146. return std::set<Verbosity>{ };
  11147. }
  11148. void ListeningReporter::noMatchingTestCases( std::string const& spec ) {
  11149. for ( auto const& listener : m_listeners ) {
  11150. listener->noMatchingTestCases( spec );
  11151. }
  11152. m_reporter->noMatchingTestCases( spec );
  11153. }
  11154. void ListeningReporter::benchmarkStarting( BenchmarkInfo const& benchmarkInfo ) {
  11155. for ( auto const& listener : m_listeners ) {
  11156. listener->benchmarkStarting( benchmarkInfo );
  11157. }
  11158. m_reporter->benchmarkStarting( benchmarkInfo );
  11159. }
  11160. void ListeningReporter::benchmarkEnded( BenchmarkStats const& benchmarkStats ) {
  11161. for ( auto const& listener : m_listeners ) {
  11162. listener->benchmarkEnded( benchmarkStats );
  11163. }
  11164. m_reporter->benchmarkEnded( benchmarkStats );
  11165. }
  11166. void ListeningReporter::testRunStarting( TestRunInfo const& testRunInfo ) {
  11167. for ( auto const& listener : m_listeners ) {
  11168. listener->testRunStarting( testRunInfo );
  11169. }
  11170. m_reporter->testRunStarting( testRunInfo );
  11171. }
  11172. void ListeningReporter::testGroupStarting( GroupInfo const& groupInfo ) {
  11173. for ( auto const& listener : m_listeners ) {
  11174. listener->testGroupStarting( groupInfo );
  11175. }
  11176. m_reporter->testGroupStarting( groupInfo );
  11177. }
  11178. void ListeningReporter::testCaseStarting( TestCaseInfo const& testInfo ) {
  11179. for ( auto const& listener : m_listeners ) {
  11180. listener->testCaseStarting( testInfo );
  11181. }
  11182. m_reporter->testCaseStarting( testInfo );
  11183. }
  11184. void ListeningReporter::sectionStarting( SectionInfo const& sectionInfo ) {
  11185. for ( auto const& listener : m_listeners ) {
  11186. listener->sectionStarting( sectionInfo );
  11187. }
  11188. m_reporter->sectionStarting( sectionInfo );
  11189. }
  11190. void ListeningReporter::assertionStarting( AssertionInfo const& assertionInfo ) {
  11191. for ( auto const& listener : m_listeners ) {
  11192. listener->assertionStarting( assertionInfo );
  11193. }
  11194. m_reporter->assertionStarting( assertionInfo );
  11195. }
  11196. // The return value indicates if the messages buffer should be cleared:
  11197. bool ListeningReporter::assertionEnded( AssertionStats const& assertionStats ) {
  11198. for( auto const& listener : m_listeners ) {
  11199. static_cast<void>( listener->assertionEnded( assertionStats ) );
  11200. }
  11201. return m_reporter->assertionEnded( assertionStats );
  11202. }
  11203. void ListeningReporter::sectionEnded( SectionStats const& sectionStats ) {
  11204. for ( auto const& listener : m_listeners ) {
  11205. listener->sectionEnded( sectionStats );
  11206. }
  11207. m_reporter->sectionEnded( sectionStats );
  11208. }
  11209. void ListeningReporter::testCaseEnded( TestCaseStats const& testCaseStats ) {
  11210. for ( auto const& listener : m_listeners ) {
  11211. listener->testCaseEnded( testCaseStats );
  11212. }
  11213. m_reporter->testCaseEnded( testCaseStats );
  11214. }
  11215. void ListeningReporter::testGroupEnded( TestGroupStats const& testGroupStats ) {
  11216. for ( auto const& listener : m_listeners ) {
  11217. listener->testGroupEnded( testGroupStats );
  11218. }
  11219. m_reporter->testGroupEnded( testGroupStats );
  11220. }
  11221. void ListeningReporter::testRunEnded( TestRunStats const& testRunStats ) {
  11222. for ( auto const& listener : m_listeners ) {
  11223. listener->testRunEnded( testRunStats );
  11224. }
  11225. m_reporter->testRunEnded( testRunStats );
  11226. }
  11227. void ListeningReporter::skipTest( TestCaseInfo const& testInfo ) {
  11228. for ( auto const& listener : m_listeners ) {
  11229. listener->skipTest( testInfo );
  11230. }
  11231. m_reporter->skipTest( testInfo );
  11232. }
  11233. bool ListeningReporter::isMulti() const {
  11234. return true;
  11235. }
  11236. } // end namespace Catch
  11237. // end catch_reporter_listening.cpp
  11238. // start catch_reporter_xml.cpp
  11239. #if defined(_MSC_VER)
  11240. #pragma warning(push)
  11241. #pragma warning(disable:4061) // Not all labels are EXPLICITLY handled in switch
  11242. // Note that 4062 (not all labels are handled
  11243. // and default is missing) is enabled
  11244. #endif
  11245. namespace Catch {
  11246. XmlReporter::XmlReporter( ReporterConfig const& _config )
  11247. : StreamingReporterBase( _config ),
  11248. m_xml(_config.stream())
  11249. {
  11250. m_reporterPrefs.shouldRedirectStdOut = true;
  11251. m_reporterPrefs.shouldReportAllAssertions = true;
  11252. }
  11253. XmlReporter::~XmlReporter() = default;
  11254. std::string XmlReporter::getDescription() {
  11255. return "Reports test results as an XML document";
  11256. }
  11257. std::string XmlReporter::getStylesheetRef() const {
  11258. return std::string();
  11259. }
  11260. void XmlReporter::writeSourceInfo( SourceLineInfo const& sourceInfo ) {
  11261. m_xml
  11262. .writeAttribute( "filename", sourceInfo.file )
  11263. .writeAttribute( "line", sourceInfo.line );
  11264. }
  11265. void XmlReporter::noMatchingTestCases( std::string const& s ) {
  11266. StreamingReporterBase::noMatchingTestCases( s );
  11267. }
  11268. void XmlReporter::testRunStarting( TestRunInfo const& testInfo ) {
  11269. StreamingReporterBase::testRunStarting( testInfo );
  11270. std::string stylesheetRef = getStylesheetRef();
  11271. if( !stylesheetRef.empty() )
  11272. m_xml.writeStylesheetRef( stylesheetRef );
  11273. m_xml.startElement( "Catch" );
  11274. if( !m_config->name().empty() )
  11275. m_xml.writeAttribute( "name", m_config->name() );
  11276. if( m_config->rngSeed() != 0 )
  11277. m_xml.scopedElement( "Randomness" )
  11278. .writeAttribute( "seed", m_config->rngSeed() );
  11279. }
  11280. void XmlReporter::testGroupStarting( GroupInfo const& groupInfo ) {
  11281. StreamingReporterBase::testGroupStarting( groupInfo );
  11282. m_xml.startElement( "Group" )
  11283. .writeAttribute( "name", groupInfo.name );
  11284. }
  11285. void XmlReporter::testCaseStarting( TestCaseInfo const& testInfo ) {
  11286. StreamingReporterBase::testCaseStarting(testInfo);
  11287. m_xml.startElement( "TestCase" )
  11288. .writeAttribute( "name", trim( testInfo.name ) )
  11289. .writeAttribute( "description", testInfo.description )
  11290. .writeAttribute( "tags", testInfo.tagsAsString() );
  11291. writeSourceInfo( testInfo.lineInfo );
  11292. if ( m_config->showDurations() == ShowDurations::Always )
  11293. m_testCaseTimer.start();
  11294. m_xml.ensureTagClosed();
  11295. }
  11296. void XmlReporter::sectionStarting( SectionInfo const& sectionInfo ) {
  11297. StreamingReporterBase::sectionStarting( sectionInfo );
  11298. if( m_sectionDepth++ > 0 ) {
  11299. m_xml.startElement( "Section" )
  11300. .writeAttribute( "name", trim( sectionInfo.name ) );
  11301. writeSourceInfo( sectionInfo.lineInfo );
  11302. m_xml.ensureTagClosed();
  11303. }
  11304. }
  11305. void XmlReporter::assertionStarting( AssertionInfo const& ) { }
  11306. bool XmlReporter::assertionEnded( AssertionStats const& assertionStats ) {
  11307. AssertionResult const& result = assertionStats.assertionResult;
  11308. bool includeResults = m_config->includeSuccessfulResults() || !result.isOk();
  11309. if( includeResults || result.getResultType() == ResultWas::Warning ) {
  11310. // Print any info messages in <Info> tags.
  11311. for( auto const& msg : assertionStats.infoMessages ) {
  11312. if( msg.type == ResultWas::Info && includeResults ) {
  11313. m_xml.scopedElement( "Info" )
  11314. .writeText( msg.message );
  11315. } else if ( msg.type == ResultWas::Warning ) {
  11316. m_xml.scopedElement( "Warning" )
  11317. .writeText( msg.message );
  11318. }
  11319. }
  11320. }
  11321. // Drop out if result was successful but we're not printing them.
  11322. if( !includeResults && result.getResultType() != ResultWas::Warning )
  11323. return true;
  11324. // Print the expression if there is one.
  11325. if( result.hasExpression() ) {
  11326. m_xml.startElement( "Expression" )
  11327. .writeAttribute( "success", result.succeeded() )
  11328. .writeAttribute( "type", result.getTestMacroName() );
  11329. writeSourceInfo( result.getSourceInfo() );
  11330. m_xml.scopedElement( "Original" )
  11331. .writeText( result.getExpression() );
  11332. m_xml.scopedElement( "Expanded" )
  11333. .writeText( result.getExpandedExpression() );
  11334. }
  11335. // And... Print a result applicable to each result type.
  11336. switch( result.getResultType() ) {
  11337. case ResultWas::ThrewException:
  11338. m_xml.startElement( "Exception" );
  11339. writeSourceInfo( result.getSourceInfo() );
  11340. m_xml.writeText( result.getMessage() );
  11341. m_xml.endElement();
  11342. break;
  11343. case ResultWas::FatalErrorCondition:
  11344. m_xml.startElement( "FatalErrorCondition" );
  11345. writeSourceInfo( result.getSourceInfo() );
  11346. m_xml.writeText( result.getMessage() );
  11347. m_xml.endElement();
  11348. break;
  11349. case ResultWas::Info:
  11350. m_xml.scopedElement( "Info" )
  11351. .writeText( result.getMessage() );
  11352. break;
  11353. case ResultWas::Warning:
  11354. // Warning will already have been written
  11355. break;
  11356. case ResultWas::ExplicitFailure:
  11357. m_xml.startElement( "Failure" );
  11358. writeSourceInfo( result.getSourceInfo() );
  11359. m_xml.writeText( result.getMessage() );
  11360. m_xml.endElement();
  11361. break;
  11362. default:
  11363. break;
  11364. }
  11365. if( result.hasExpression() )
  11366. m_xml.endElement();
  11367. return true;
  11368. }
  11369. void XmlReporter::sectionEnded( SectionStats const& sectionStats ) {
  11370. StreamingReporterBase::sectionEnded( sectionStats );
  11371. if( --m_sectionDepth > 0 ) {
  11372. XmlWriter::ScopedElement e = m_xml.scopedElement( "OverallResults" );
  11373. e.writeAttribute( "successes", sectionStats.assertions.passed );
  11374. e.writeAttribute( "failures", sectionStats.assertions.failed );
  11375. e.writeAttribute( "expectedFailures", sectionStats.assertions.failedButOk );
  11376. if ( m_config->showDurations() == ShowDurations::Always )
  11377. e.writeAttribute( "durationInSeconds", sectionStats.durationInSeconds );
  11378. m_xml.endElement();
  11379. }
  11380. }
  11381. void XmlReporter::testCaseEnded( TestCaseStats const& testCaseStats ) {
  11382. StreamingReporterBase::testCaseEnded( testCaseStats );
  11383. XmlWriter::ScopedElement e = m_xml.scopedElement( "OverallResult" );
  11384. e.writeAttribute( "success", testCaseStats.totals.assertions.allOk() );
  11385. if ( m_config->showDurations() == ShowDurations::Always )
  11386. e.writeAttribute( "durationInSeconds", m_testCaseTimer.getElapsedSeconds() );
  11387. if( !testCaseStats.stdOut.empty() )
  11388. m_xml.scopedElement( "StdOut" ).writeText( trim( testCaseStats.stdOut ), false );
  11389. if( !testCaseStats.stdErr.empty() )
  11390. m_xml.scopedElement( "StdErr" ).writeText( trim( testCaseStats.stdErr ), false );
  11391. m_xml.endElement();
  11392. }
  11393. void XmlReporter::testGroupEnded( TestGroupStats const& testGroupStats ) {
  11394. StreamingReporterBase::testGroupEnded( testGroupStats );
  11395. // TODO: Check testGroupStats.aborting and act accordingly.
  11396. m_xml.scopedElement( "OverallResults" )
  11397. .writeAttribute( "successes", testGroupStats.totals.assertions.passed )
  11398. .writeAttribute( "failures", testGroupStats.totals.assertions.failed )
  11399. .writeAttribute( "expectedFailures", testGroupStats.totals.assertions.failedButOk );
  11400. m_xml.endElement();
  11401. }
  11402. void XmlReporter::testRunEnded( TestRunStats const& testRunStats ) {
  11403. StreamingReporterBase::testRunEnded( testRunStats );
  11404. m_xml.scopedElement( "OverallResults" )
  11405. .writeAttribute( "successes", testRunStats.totals.assertions.passed )
  11406. .writeAttribute( "failures", testRunStats.totals.assertions.failed )
  11407. .writeAttribute( "expectedFailures", testRunStats.totals.assertions.failedButOk );
  11408. m_xml.endElement();
  11409. }
  11410. CATCH_REGISTER_REPORTER( "xml", XmlReporter )
  11411. } // end namespace Catch
  11412. #if defined(_MSC_VER)
  11413. #pragma warning(pop)
  11414. #endif
  11415. // end catch_reporter_xml.cpp
  11416. namespace Catch {
  11417. LeakDetector leakDetector;
  11418. }
  11419. #ifdef __clang__
  11420. #pragma clang diagnostic pop
  11421. #endif
  11422. // end catch_impl.hpp
  11423. #endif
  11424. #ifdef CATCH_CONFIG_MAIN
  11425. // start catch_default_main.hpp
  11426. #ifndef __OBJC__
  11427. #if defined(CATCH_CONFIG_WCHAR) && defined(WIN32) && defined(_UNICODE) && !defined(DO_NOT_USE_WMAIN)
  11428. // Standard C/C++ Win32 Unicode wmain entry point
  11429. extern "C" int wmain (int argc, wchar_t * argv[], wchar_t * []) {
  11430. #else
  11431. // Standard C/C++ main entry point
  11432. int main (int argc, char * argv[]) {
  11433. #endif
  11434. return Catch::Session().run( argc, argv );
  11435. }
  11436. #else // __OBJC__
  11437. // Objective-C entry point
  11438. int main (int argc, char * const argv[]) {
  11439. #if !CATCH_ARC_ENABLED
  11440. NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
  11441. #endif
  11442. Catch::registerTestMethods();
  11443. int result = Catch::Session().run( argc, (char**)argv );
  11444. #if !CATCH_ARC_ENABLED
  11445. [pool drain];
  11446. #endif
  11447. return result;
  11448. }
  11449. #endif // __OBJC__
  11450. // end catch_default_main.hpp
  11451. #endif
  11452. #if !defined(CATCH_CONFIG_IMPL_ONLY)
  11453. #ifdef CLARA_CONFIG_MAIN_NOT_DEFINED
  11454. # undef CLARA_CONFIG_MAIN
  11455. #endif
  11456. #if !defined(CATCH_CONFIG_DISABLE)
  11457. //////
  11458. // If this config identifier is defined then all CATCH macros are prefixed with CATCH_
  11459. #ifdef CATCH_CONFIG_PREFIX_ALL
  11460. #define CATCH_REQUIRE( ... ) INTERNAL_CATCH_TEST( "CATCH_REQUIRE", Catch::ResultDisposition::Normal, __VA_ARGS__ )
  11461. #define CATCH_REQUIRE_FALSE( ... ) INTERNAL_CATCH_TEST( "CATCH_REQUIRE_FALSE", Catch::ResultDisposition::Normal | Catch::ResultDisposition::FalseTest, __VA_ARGS__ )
  11462. #define CATCH_REQUIRE_THROWS( ... ) INTERNAL_CATCH_THROWS( "CATCH_REQUIRE_THROWS", Catch::ResultDisposition::Normal, "", __VA_ARGS__ )
  11463. #define CATCH_REQUIRE_THROWS_AS( expr, exceptionType ) INTERNAL_CATCH_THROWS_AS( "CATCH_REQUIRE_THROWS_AS", exceptionType, Catch::ResultDisposition::Normal, expr )
  11464. #define CATCH_REQUIRE_THROWS_WITH( expr, matcher ) INTERNAL_CATCH_THROWS_STR_MATCHES( "CATCH_REQUIRE_THROWS_WITH", Catch::ResultDisposition::Normal, matcher, expr )
  11465. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  11466. #define CATCH_REQUIRE_THROWS_MATCHES( expr, exceptionType, matcher ) INTERNAL_CATCH_THROWS_MATCHES( "CATCH_REQUIRE_THROWS_MATCHES", exceptionType, Catch::ResultDisposition::Normal, matcher, expr )
  11467. #endif// CATCH_CONFIG_DISABLE_MATCHERS
  11468. #define CATCH_REQUIRE_NOTHROW( ... ) INTERNAL_CATCH_NO_THROW( "CATCH_REQUIRE_NOTHROW", Catch::ResultDisposition::Normal, __VA_ARGS__ )
  11469. #define CATCH_CHECK( ... ) INTERNAL_CATCH_TEST( "CATCH_CHECK", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  11470. #define CATCH_CHECK_FALSE( ... ) INTERNAL_CATCH_TEST( "CATCH_CHECK_FALSE", Catch::ResultDisposition::ContinueOnFailure | Catch::ResultDisposition::FalseTest, __VA_ARGS__ )
  11471. #define CATCH_CHECKED_IF( ... ) INTERNAL_CATCH_IF( "CATCH_CHECKED_IF", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  11472. #define CATCH_CHECKED_ELSE( ... ) INTERNAL_CATCH_ELSE( "CATCH_CHECKED_ELSE", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  11473. #define CATCH_CHECK_NOFAIL( ... ) INTERNAL_CATCH_TEST( "CATCH_CHECK_NOFAIL", Catch::ResultDisposition::ContinueOnFailure | Catch::ResultDisposition::SuppressFail, __VA_ARGS__ )
  11474. #define CATCH_CHECK_THROWS( ... ) INTERNAL_CATCH_THROWS( "CATCH_CHECK_THROWS", Catch::ResultDisposition::ContinueOnFailure, "", __VA_ARGS__ )
  11475. #define CATCH_CHECK_THROWS_AS( expr, exceptionType ) INTERNAL_CATCH_THROWS_AS( "CATCH_CHECK_THROWS_AS", exceptionType, Catch::ResultDisposition::ContinueOnFailure, expr )
  11476. #define CATCH_CHECK_THROWS_WITH( expr, matcher ) INTERNAL_CATCH_THROWS_STR_MATCHES( "CATCH_CHECK_THROWS_WITH", Catch::ResultDisposition::ContinueOnFailure, matcher, expr )
  11477. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  11478. #define CATCH_CHECK_THROWS_MATCHES( expr, exceptionType, matcher ) INTERNAL_CATCH_THROWS_MATCHES( "CATCH_CHECK_THROWS_MATCHES", exceptionType, Catch::ResultDisposition::ContinueOnFailure, matcher, expr )
  11479. #endif // CATCH_CONFIG_DISABLE_MATCHERS
  11480. #define CATCH_CHECK_NOTHROW( ... ) INTERNAL_CATCH_NO_THROW( "CATCH_CHECK_NOTHROW", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  11481. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  11482. #define CATCH_CHECK_THAT( arg, matcher ) INTERNAL_CHECK_THAT( "CATCH_CHECK_THAT", matcher, Catch::ResultDisposition::ContinueOnFailure, arg )
  11483. #define CATCH_REQUIRE_THAT( arg, matcher ) INTERNAL_CHECK_THAT( "CATCH_REQUIRE_THAT", matcher, Catch::ResultDisposition::Normal, arg )
  11484. #endif // CATCH_CONFIG_DISABLE_MATCHERS
  11485. #define CATCH_INFO( msg ) INTERNAL_CATCH_INFO( "CATCH_INFO", msg )
  11486. #define CATCH_WARN( msg ) INTERNAL_CATCH_MSG( "CATCH_WARN", Catch::ResultWas::Warning, Catch::ResultDisposition::ContinueOnFailure, msg )
  11487. #define CATCH_CAPTURE( ... ) INTERNAL_CATCH_CAPTURE( INTERNAL_CATCH_UNIQUE_NAME(capturer), "CATCH_CAPTURE",__VA_ARGS__ )
  11488. #define CATCH_TEST_CASE( ... ) INTERNAL_CATCH_TESTCASE( __VA_ARGS__ )
  11489. #define CATCH_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEST_CASE_METHOD( className, __VA_ARGS__ )
  11490. #define CATCH_METHOD_AS_TEST_CASE( method, ... ) INTERNAL_CATCH_METHOD_AS_TEST_CASE( method, __VA_ARGS__ )
  11491. #define CATCH_REGISTER_TEST_CASE( Function, ... ) INTERNAL_CATCH_REGISTER_TESTCASE( Function, __VA_ARGS__ )
  11492. #define CATCH_SECTION( ... ) INTERNAL_CATCH_SECTION( __VA_ARGS__ )
  11493. #define CATCH_DYNAMIC_SECTION( ... ) INTERNAL_CATCH_DYNAMIC_SECTION( __VA_ARGS__ )
  11494. #define CATCH_FAIL( ... ) INTERNAL_CATCH_MSG( "CATCH_FAIL", Catch::ResultWas::ExplicitFailure, Catch::ResultDisposition::Normal, __VA_ARGS__ )
  11495. #define CATCH_FAIL_CHECK( ... ) INTERNAL_CATCH_MSG( "CATCH_FAIL_CHECK", Catch::ResultWas::ExplicitFailure, Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  11496. #define CATCH_SUCCEED( ... ) INTERNAL_CATCH_MSG( "CATCH_SUCCEED", Catch::ResultWas::Ok, Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  11497. #define CATCH_ANON_TEST_CASE() INTERNAL_CATCH_TESTCASE()
  11498. #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
  11499. #define CATCH_TEMPLATE_TEST_CASE( ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE( __VA_ARGS__ )
  11500. #define CATCH_TEMPLATE_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ )
  11501. #else
  11502. #define CATCH_TEMPLATE_TEST_CASE( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE( __VA_ARGS__ ) )
  11503. #define CATCH_TEMPLATE_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ ) )
  11504. #endif
  11505. #if !defined(CATCH_CONFIG_RUNTIME_STATIC_REQUIRE)
  11506. #define CATCH_STATIC_REQUIRE( ... ) static_assert( __VA_ARGS__ , #__VA_ARGS__ ); CATCH_SUCCEED( #__VA_ARGS__ )
  11507. #define CATCH_STATIC_REQUIRE_FALSE( ... ) static_assert( !(__VA_ARGS__), "!(" #__VA_ARGS__ ")" ); CATCH_SUCCEED( #__VA_ARGS__ )
  11508. #else
  11509. #define CATCH_STATIC_REQUIRE( ... ) CATCH_REQUIRE( __VA_ARGS__ )
  11510. #define CATCH_STATIC_REQUIRE_FALSE( ... ) CATCH_REQUIRE_FALSE( __VA_ARGS__ )
  11511. #endif
  11512. // "BDD-style" convenience wrappers
  11513. #define CATCH_SCENARIO( ... ) CATCH_TEST_CASE( "Scenario: " __VA_ARGS__ )
  11514. #define CATCH_SCENARIO_METHOD( className, ... ) INTERNAL_CATCH_TEST_CASE_METHOD( className, "Scenario: " __VA_ARGS__ )
  11515. #define CATCH_GIVEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " Given: " << desc )
  11516. #define CATCH_AND_GIVEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( "And given: " << desc )
  11517. #define CATCH_WHEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " When: " << desc )
  11518. #define CATCH_AND_WHEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " And when: " << desc )
  11519. #define CATCH_THEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " Then: " << desc )
  11520. #define CATCH_AND_THEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " And: " << desc )
  11521. // If CATCH_CONFIG_PREFIX_ALL is not defined then the CATCH_ prefix is not required
  11522. #else
  11523. #define REQUIRE( ... ) INTERNAL_CATCH_TEST( "REQUIRE", Catch::ResultDisposition::Normal, __VA_ARGS__ )
  11524. #define REQUIRE_FALSE( ... ) INTERNAL_CATCH_TEST( "REQUIRE_FALSE", Catch::ResultDisposition::Normal | Catch::ResultDisposition::FalseTest, __VA_ARGS__ )
  11525. #define REQUIRE_THROWS( ... ) INTERNAL_CATCH_THROWS( "REQUIRE_THROWS", Catch::ResultDisposition::Normal, __VA_ARGS__ )
  11526. #define REQUIRE_THROWS_AS( expr, exceptionType ) INTERNAL_CATCH_THROWS_AS( "REQUIRE_THROWS_AS", exceptionType, Catch::ResultDisposition::Normal, expr )
  11527. #define REQUIRE_THROWS_WITH( expr, matcher ) INTERNAL_CATCH_THROWS_STR_MATCHES( "REQUIRE_THROWS_WITH", Catch::ResultDisposition::Normal, matcher, expr )
  11528. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  11529. #define REQUIRE_THROWS_MATCHES( expr, exceptionType, matcher ) INTERNAL_CATCH_THROWS_MATCHES( "REQUIRE_THROWS_MATCHES", exceptionType, Catch::ResultDisposition::Normal, matcher, expr )
  11530. #endif // CATCH_CONFIG_DISABLE_MATCHERS
  11531. #define REQUIRE_NOTHROW( ... ) INTERNAL_CATCH_NO_THROW( "REQUIRE_NOTHROW", Catch::ResultDisposition::Normal, __VA_ARGS__ )
  11532. #define CHECK( ... ) INTERNAL_CATCH_TEST( "CHECK", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  11533. #define CHECK_FALSE( ... ) INTERNAL_CATCH_TEST( "CHECK_FALSE", Catch::ResultDisposition::ContinueOnFailure | Catch::ResultDisposition::FalseTest, __VA_ARGS__ )
  11534. #define CHECKED_IF( ... ) INTERNAL_CATCH_IF( "CHECKED_IF", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  11535. #define CHECKED_ELSE( ... ) INTERNAL_CATCH_ELSE( "CHECKED_ELSE", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  11536. #define CHECK_NOFAIL( ... ) INTERNAL_CATCH_TEST( "CHECK_NOFAIL", Catch::ResultDisposition::ContinueOnFailure | Catch::ResultDisposition::SuppressFail, __VA_ARGS__ )
  11537. #define CHECK_THROWS( ... ) INTERNAL_CATCH_THROWS( "CHECK_THROWS", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  11538. #define CHECK_THROWS_AS( expr, exceptionType ) INTERNAL_CATCH_THROWS_AS( "CHECK_THROWS_AS", exceptionType, Catch::ResultDisposition::ContinueOnFailure, expr )
  11539. #define CHECK_THROWS_WITH( expr, matcher ) INTERNAL_CATCH_THROWS_STR_MATCHES( "CHECK_THROWS_WITH", Catch::ResultDisposition::ContinueOnFailure, matcher, expr )
  11540. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  11541. #define CHECK_THROWS_MATCHES( expr, exceptionType, matcher ) INTERNAL_CATCH_THROWS_MATCHES( "CHECK_THROWS_MATCHES", exceptionType, Catch::ResultDisposition::ContinueOnFailure, matcher, expr )
  11542. #endif // CATCH_CONFIG_DISABLE_MATCHERS
  11543. #define CHECK_NOTHROW( ... ) INTERNAL_CATCH_NO_THROW( "CHECK_NOTHROW", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  11544. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  11545. #define CHECK_THAT( arg, matcher ) INTERNAL_CHECK_THAT( "CHECK_THAT", matcher, Catch::ResultDisposition::ContinueOnFailure, arg )
  11546. #define REQUIRE_THAT( arg, matcher ) INTERNAL_CHECK_THAT( "REQUIRE_THAT", matcher, Catch::ResultDisposition::Normal, arg )
  11547. #endif // CATCH_CONFIG_DISABLE_MATCHERS
  11548. #define INFO( msg ) INTERNAL_CATCH_INFO( "INFO", msg )
  11549. #define WARN( msg ) INTERNAL_CATCH_MSG( "WARN", Catch::ResultWas::Warning, Catch::ResultDisposition::ContinueOnFailure, msg )
  11550. #define CAPTURE( ... ) INTERNAL_CATCH_CAPTURE( INTERNAL_CATCH_UNIQUE_NAME(capturer), "CAPTURE",__VA_ARGS__ )
  11551. #define TEST_CASE( ... ) INTERNAL_CATCH_TESTCASE( __VA_ARGS__ )
  11552. #define TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEST_CASE_METHOD( className, __VA_ARGS__ )
  11553. #define METHOD_AS_TEST_CASE( method, ... ) INTERNAL_CATCH_METHOD_AS_TEST_CASE( method, __VA_ARGS__ )
  11554. #define REGISTER_TEST_CASE( Function, ... ) INTERNAL_CATCH_REGISTER_TESTCASE( Function, __VA_ARGS__ )
  11555. #define SECTION( ... ) INTERNAL_CATCH_SECTION( __VA_ARGS__ )
  11556. #define DYNAMIC_SECTION( ... ) INTERNAL_CATCH_DYNAMIC_SECTION( __VA_ARGS__ )
  11557. #define FAIL( ... ) INTERNAL_CATCH_MSG( "FAIL", Catch::ResultWas::ExplicitFailure, Catch::ResultDisposition::Normal, __VA_ARGS__ )
  11558. #define FAIL_CHECK( ... ) INTERNAL_CATCH_MSG( "FAIL_CHECK", Catch::ResultWas::ExplicitFailure, Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  11559. #define SUCCEED( ... ) INTERNAL_CATCH_MSG( "SUCCEED", Catch::ResultWas::Ok, Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  11560. #define ANON_TEST_CASE() INTERNAL_CATCH_TESTCASE()
  11561. #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
  11562. #define TEMPLATE_TEST_CASE( ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE( __VA_ARGS__ )
  11563. #define TEMPLATE_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ )
  11564. #else
  11565. #define TEMPLATE_TEST_CASE( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE( __VA_ARGS__ ) )
  11566. #define TEMPLATE_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ ) )
  11567. #endif
  11568. #if !defined(CATCH_CONFIG_RUNTIME_STATIC_REQUIRE)
  11569. #define STATIC_REQUIRE( ... ) static_assert( __VA_ARGS__, #__VA_ARGS__ ); SUCCEED( #__VA_ARGS__ )
  11570. #define STATIC_REQUIRE_FALSE( ... ) static_assert( !(__VA_ARGS__), "!(" #__VA_ARGS__ ")" ); SUCCEED( "!(" #__VA_ARGS__ ")" )
  11571. #else
  11572. #define STATIC_REQUIRE( ... ) REQUIRE( __VA_ARGS__ )
  11573. #define STATIC_REQUIRE_FALSE( ... ) REQUIRE_FALSE( __VA_ARGS__ )
  11574. #endif
  11575. #endif
  11576. #define CATCH_TRANSLATE_EXCEPTION( signature ) INTERNAL_CATCH_TRANSLATE_EXCEPTION( signature )
  11577. // "BDD-style" convenience wrappers
  11578. #define SCENARIO( ... ) TEST_CASE( "Scenario: " __VA_ARGS__ )
  11579. #define SCENARIO_METHOD( className, ... ) INTERNAL_CATCH_TEST_CASE_METHOD( className, "Scenario: " __VA_ARGS__ )
  11580. #define GIVEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " Given: " << desc )
  11581. #define AND_GIVEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( "And given: " << desc )
  11582. #define WHEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " When: " << desc )
  11583. #define AND_WHEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " And when: " << desc )
  11584. #define THEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " Then: " << desc )
  11585. #define AND_THEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " And: " << desc )
  11586. using Catch::Detail::Approx;
  11587. #else // CATCH_CONFIG_DISABLE
  11588. //////
  11589. // If this config identifier is defined then all CATCH macros are prefixed with CATCH_
  11590. #ifdef CATCH_CONFIG_PREFIX_ALL
  11591. #define CATCH_REQUIRE( ... ) (void)(0)
  11592. #define CATCH_REQUIRE_FALSE( ... ) (void)(0)
  11593. #define CATCH_REQUIRE_THROWS( ... ) (void)(0)
  11594. #define CATCH_REQUIRE_THROWS_AS( expr, exceptionType ) (void)(0)
  11595. #define CATCH_REQUIRE_THROWS_WITH( expr, matcher ) (void)(0)
  11596. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  11597. #define CATCH_REQUIRE_THROWS_MATCHES( expr, exceptionType, matcher ) (void)(0)
  11598. #endif// CATCH_CONFIG_DISABLE_MATCHERS
  11599. #define CATCH_REQUIRE_NOTHROW( ... ) (void)(0)
  11600. #define CATCH_CHECK( ... ) (void)(0)
  11601. #define CATCH_CHECK_FALSE( ... ) (void)(0)
  11602. #define CATCH_CHECKED_IF( ... ) if (__VA_ARGS__)
  11603. #define CATCH_CHECKED_ELSE( ... ) if (!(__VA_ARGS__))
  11604. #define CATCH_CHECK_NOFAIL( ... ) (void)(0)
  11605. #define CATCH_CHECK_THROWS( ... ) (void)(0)
  11606. #define CATCH_CHECK_THROWS_AS( expr, exceptionType ) (void)(0)
  11607. #define CATCH_CHECK_THROWS_WITH( expr, matcher ) (void)(0)
  11608. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  11609. #define CATCH_CHECK_THROWS_MATCHES( expr, exceptionType, matcher ) (void)(0)
  11610. #endif // CATCH_CONFIG_DISABLE_MATCHERS
  11611. #define CATCH_CHECK_NOTHROW( ... ) (void)(0)
  11612. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  11613. #define CATCH_CHECK_THAT( arg, matcher ) (void)(0)
  11614. #define CATCH_REQUIRE_THAT( arg, matcher ) (void)(0)
  11615. #endif // CATCH_CONFIG_DISABLE_MATCHERS
  11616. #define CATCH_INFO( msg ) (void)(0)
  11617. #define CATCH_WARN( msg ) (void)(0)
  11618. #define CATCH_CAPTURE( msg ) (void)(0)
  11619. #define CATCH_TEST_CASE( ... ) INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ))
  11620. #define CATCH_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ))
  11621. #define CATCH_METHOD_AS_TEST_CASE( method, ... )
  11622. #define CATCH_REGISTER_TEST_CASE( Function, ... ) (void)(0)
  11623. #define CATCH_SECTION( ... )
  11624. #define CATCH_DYNAMIC_SECTION( ... )
  11625. #define CATCH_FAIL( ... ) (void)(0)
  11626. #define CATCH_FAIL_CHECK( ... ) (void)(0)
  11627. #define CATCH_SUCCEED( ... ) (void)(0)
  11628. #define CATCH_ANON_TEST_CASE() INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ))
  11629. #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
  11630. #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____ ) )
  11631. #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 )
  11632. #else
  11633. #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____ ) ) )
  11634. #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 ) )
  11635. #endif
  11636. // "BDD-style" convenience wrappers
  11637. #define CATCH_SCENARIO( ... ) INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ))
  11638. #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 )
  11639. #define CATCH_GIVEN( desc )
  11640. #define CATCH_AND_GIVEN( desc )
  11641. #define CATCH_WHEN( desc )
  11642. #define CATCH_AND_WHEN( desc )
  11643. #define CATCH_THEN( desc )
  11644. #define CATCH_AND_THEN( desc )
  11645. #define CATCH_STATIC_REQUIRE( ... ) (void)(0)
  11646. #define CATCH_STATIC_REQUIRE_FALSE( ... ) (void)(0)
  11647. // If CATCH_CONFIG_PREFIX_ALL is not defined then the CATCH_ prefix is not required
  11648. #else
  11649. #define REQUIRE( ... ) (void)(0)
  11650. #define REQUIRE_FALSE( ... ) (void)(0)
  11651. #define REQUIRE_THROWS( ... ) (void)(0)
  11652. #define REQUIRE_THROWS_AS( expr, exceptionType ) (void)(0)
  11653. #define REQUIRE_THROWS_WITH( expr, matcher ) (void)(0)
  11654. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  11655. #define REQUIRE_THROWS_MATCHES( expr, exceptionType, matcher ) (void)(0)
  11656. #endif // CATCH_CONFIG_DISABLE_MATCHERS
  11657. #define REQUIRE_NOTHROW( ... ) (void)(0)
  11658. #define CHECK( ... ) (void)(0)
  11659. #define CHECK_FALSE( ... ) (void)(0)
  11660. #define CHECKED_IF( ... ) if (__VA_ARGS__)
  11661. #define CHECKED_ELSE( ... ) if (!(__VA_ARGS__))
  11662. #define CHECK_NOFAIL( ... ) (void)(0)
  11663. #define CHECK_THROWS( ... ) (void)(0)
  11664. #define CHECK_THROWS_AS( expr, exceptionType ) (void)(0)
  11665. #define CHECK_THROWS_WITH( expr, matcher ) (void)(0)
  11666. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  11667. #define CHECK_THROWS_MATCHES( expr, exceptionType, matcher ) (void)(0)
  11668. #endif // CATCH_CONFIG_DISABLE_MATCHERS
  11669. #define CHECK_NOTHROW( ... ) (void)(0)
  11670. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  11671. #define CHECK_THAT( arg, matcher ) (void)(0)
  11672. #define REQUIRE_THAT( arg, matcher ) (void)(0)
  11673. #endif // CATCH_CONFIG_DISABLE_MATCHERS
  11674. #define INFO( msg ) (void)(0)
  11675. #define WARN( msg ) (void)(0)
  11676. #define CAPTURE( msg ) (void)(0)
  11677. #define TEST_CASE( ... ) INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ))
  11678. #define TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ))
  11679. #define METHOD_AS_TEST_CASE( method, ... )
  11680. #define REGISTER_TEST_CASE( Function, ... ) (void)(0)
  11681. #define SECTION( ... )
  11682. #define DYNAMIC_SECTION( ... )
  11683. #define FAIL( ... ) (void)(0)
  11684. #define FAIL_CHECK( ... ) (void)(0)
  11685. #define SUCCEED( ... ) (void)(0)
  11686. #define ANON_TEST_CASE() INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ))
  11687. #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
  11688. #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____ ) )
  11689. #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 )
  11690. #else
  11691. #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____ ) ) )
  11692. #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 ) )
  11693. #endif
  11694. #define STATIC_REQUIRE( ... ) (void)(0)
  11695. #define STATIC_REQUIRE_FALSE( ... ) (void)(0)
  11696. #endif
  11697. #define CATCH_TRANSLATE_EXCEPTION( signature ) INTERNAL_CATCH_TRANSLATE_EXCEPTION_NO_REG( INTERNAL_CATCH_UNIQUE_NAME( catch_internal_ExceptionTranslator ), signature )
  11698. // "BDD-style" convenience wrappers
  11699. #define SCENARIO( ... ) INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ) )
  11700. #define SCENARIO_METHOD( className, ... ) INTERNAL_CATCH_TESTCASE_METHOD_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ), className )
  11701. #define GIVEN( desc )
  11702. #define AND_GIVEN( desc )
  11703. #define WHEN( desc )
  11704. #define AND_WHEN( desc )
  11705. #define THEN( desc )
  11706. #define AND_THEN( desc )
  11707. using Catch::Detail::Approx;
  11708. #endif
  11709. #endif // ! CATCH_CONFIG_IMPL_ONLY
  11710. // start catch_reenable_warnings.h
  11711. #ifdef __clang__
  11712. # ifdef __ICC // icpc defines the __clang__ macro
  11713. # pragma warning(pop)
  11714. # else
  11715. # pragma clang diagnostic pop
  11716. # endif
  11717. #elif defined __GNUC__
  11718. # pragma GCC diagnostic pop
  11719. #endif
  11720. // end catch_reenable_warnings.h
  11721. // end catch.hpp
  11722. #endif // TWOBLUECUBES_SINGLE_INCLUDE_CATCH_HPP_INCLUDED