Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

14698 rindas
496KB

  1. /*
  2. * Catch v2.6.1
  3. * Generated: 2019-02-12 19:52:52.262497
  4. * ----------------------------------------------------------
  5. * This file has been merged from multiple headers. Please don't edit it directly
  6. * Copyright (c) 2019 Two Blue Cubes Ltd. All rights reserved.
  7. *
  8. * Distributed under the Boost Software License, Version 1.0. (See accompanying
  9. * file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
  10. */
  11. #ifndef TWOBLUECUBES_SINGLE_INCLUDE_CATCH_HPP_INCLUDED
  12. #define TWOBLUECUBES_SINGLE_INCLUDE_CATCH_HPP_INCLUDED
  13. // start catch.hpp
  14. #define CATCH_VERSION_MAJOR 2
  15. #define CATCH_VERSION_MINOR 6
  16. #define CATCH_VERSION_PATCH 1
  17. #ifdef __clang__
  18. # pragma clang system_header
  19. #elif defined __GNUC__
  20. # pragma GCC system_header
  21. #endif
  22. // start catch_suppress_warnings.h
  23. #ifdef __clang__
  24. # ifdef __ICC // icpc defines the __clang__ macro
  25. # pragma warning(push)
  26. # pragma warning(disable: 161 1682)
  27. # else // __ICC
  28. # pragma clang diagnostic push
  29. # pragma clang diagnostic ignored "-Wpadded"
  30. # pragma clang diagnostic ignored "-Wswitch-enum"
  31. # pragma clang diagnostic ignored "-Wcovered-switch-default"
  32. # endif
  33. #elif defined __GNUC__
  34. // Because REQUIREs trigger GCC's -Wparentheses, and because still
  35. // supported version of g++ have only buggy support for _Pragmas,
  36. // Wparentheses have to be suppressed globally.
  37. # pragma GCC diagnostic ignored "-Wparentheses" // See #674 for details
  38. # pragma GCC diagnostic push
  39. # pragma GCC diagnostic ignored "-Wunused-variable"
  40. # pragma GCC diagnostic ignored "-Wpadded"
  41. #endif
  42. // end catch_suppress_warnings.h
  43. #if defined(CATCH_CONFIG_MAIN) || defined(CATCH_CONFIG_RUNNER)
  44. # define CATCH_IMPL
  45. # define CATCH_CONFIG_ALL_PARTS
  46. #endif
  47. // In the impl file, we want to have access to all parts of the headers
  48. // Can also be used to sanely support PCHs
  49. #if defined(CATCH_CONFIG_ALL_PARTS)
  50. # define CATCH_CONFIG_EXTERNAL_INTERFACES
  51. # if defined(CATCH_CONFIG_DISABLE_MATCHERS)
  52. # undef CATCH_CONFIG_DISABLE_MATCHERS
  53. # endif
  54. # if !defined(CATCH_CONFIG_ENABLE_CHRONO_STRINGMAKER)
  55. # define CATCH_CONFIG_ENABLE_CHRONO_STRINGMAKER
  56. # endif
  57. #endif
  58. #if !defined(CATCH_CONFIG_IMPL_ONLY)
  59. // start catch_platform.h
  60. #ifdef __APPLE__
  61. # include <TargetConditionals.h>
  62. # if TARGET_OS_OSX == 1
  63. # define CATCH_PLATFORM_MAC
  64. # elif TARGET_OS_IPHONE == 1
  65. # define CATCH_PLATFORM_IPHONE
  66. # endif
  67. #elif defined(linux) || defined(__linux) || defined(__linux__)
  68. # define CATCH_PLATFORM_LINUX
  69. #elif defined(WIN32) || defined(__WIN32__) || defined(_WIN32) || defined(_MSC_VER) || defined(__MINGW32__)
  70. # define CATCH_PLATFORM_WINDOWS
  71. #endif
  72. // end catch_platform.h
  73. #ifdef CATCH_IMPL
  74. # ifndef CLARA_CONFIG_MAIN
  75. # define CLARA_CONFIG_MAIN_NOT_DEFINED
  76. # define CLARA_CONFIG_MAIN
  77. # endif
  78. #endif
  79. // start catch_user_interfaces.h
  80. namespace Catch {
  81. unsigned int rngSeed();
  82. }
  83. // end catch_user_interfaces.h
  84. // start catch_tag_alias_autoregistrar.h
  85. // start catch_common.h
  86. // start catch_compiler_capabilities.h
  87. // Detect a number of compiler features - by compiler
  88. // The following features are defined:
  89. //
  90. // CATCH_CONFIG_COUNTER : is the __COUNTER__ macro supported?
  91. // CATCH_CONFIG_WINDOWS_SEH : is Windows SEH supported?
  92. // CATCH_CONFIG_POSIX_SIGNALS : are POSIX signals supported?
  93. // CATCH_CONFIG_DISABLE_EXCEPTIONS : Are exceptions enabled?
  94. // ****************
  95. // Note to maintainers: if new toggles are added please document them
  96. // in configuration.md, too
  97. // ****************
  98. // In general each macro has a _NO_<feature name> form
  99. // (e.g. CATCH_CONFIG_NO_POSIX_SIGNALS) which disables the feature.
  100. // Many features, at point of detection, define an _INTERNAL_ macro, so they
  101. // can be combined, en-mass, with the _NO_ forms later.
  102. #ifdef __cplusplus
  103. # if (__cplusplus >= 201402L) || (defined(_MSVC_LANG) && _MSVC_LANG >= 201402L)
  104. # define CATCH_CPP14_OR_GREATER
  105. # endif
  106. # if (__cplusplus >= 201703L) || (defined(_MSVC_LANG) && _MSVC_LANG >= 201703L)
  107. # define CATCH_CPP17_OR_GREATER
  108. # endif
  109. #endif
  110. #if defined(CATCH_CPP17_OR_GREATER)
  111. # define CATCH_INTERNAL_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS
  112. #endif
  113. #ifdef __clang__
  114. # define CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
  115. _Pragma( "clang diagnostic push" ) \
  116. _Pragma( "clang diagnostic ignored \"-Wexit-time-destructors\"" ) \
  117. _Pragma( "clang diagnostic ignored \"-Wglobal-constructors\"")
  118. # define CATCH_INTERNAL_UNSUPPRESS_GLOBALS_WARNINGS \
  119. _Pragma( "clang diagnostic pop" )
  120. # define CATCH_INTERNAL_SUPPRESS_PARENTHESES_WARNINGS \
  121. _Pragma( "clang diagnostic push" ) \
  122. _Pragma( "clang diagnostic ignored \"-Wparentheses\"" )
  123. # define CATCH_INTERNAL_UNSUPPRESS_PARENTHESES_WARNINGS \
  124. _Pragma( "clang diagnostic pop" )
  125. # define CATCH_INTERNAL_SUPPRESS_UNUSED_WARNINGS \
  126. _Pragma( "clang diagnostic push" ) \
  127. _Pragma( "clang diagnostic ignored \"-Wunused-variable\"" )
  128. # define CATCH_INTERNAL_UNSUPPRESS_UNUSED_WARNINGS \
  129. _Pragma( "clang diagnostic pop" )
  130. #endif // __clang__
  131. ////////////////////////////////////////////////////////////////////////////////
  132. // Assume that non-Windows platforms support posix signals by default
  133. #if !defined(CATCH_PLATFORM_WINDOWS)
  134. #define CATCH_INTERNAL_CONFIG_POSIX_SIGNALS
  135. #endif
  136. ////////////////////////////////////////////////////////////////////////////////
  137. // We know some environments not to support full POSIX signals
  138. #if defined(__CYGWIN__) || defined(__QNX__) || defined(__EMSCRIPTEN__) || defined(__DJGPP__)
  139. #define CATCH_INTERNAL_CONFIG_NO_POSIX_SIGNALS
  140. #endif
  141. #ifdef __OS400__
  142. # define CATCH_INTERNAL_CONFIG_NO_POSIX_SIGNALS
  143. # define CATCH_CONFIG_COLOUR_NONE
  144. #endif
  145. ////////////////////////////////////////////////////////////////////////////////
  146. // Android somehow still does not support std::to_string
  147. #if defined(__ANDROID__)
  148. # define CATCH_INTERNAL_CONFIG_NO_CPP11_TO_STRING
  149. #endif
  150. ////////////////////////////////////////////////////////////////////////////////
  151. // Not all Windows environments support SEH properly
  152. #if defined(__MINGW32__)
  153. # define CATCH_INTERNAL_CONFIG_NO_WINDOWS_SEH
  154. #endif
  155. ////////////////////////////////////////////////////////////////////////////////
  156. // PS4
  157. #if defined(__ORBIS__)
  158. # define CATCH_INTERNAL_CONFIG_NO_NEW_CAPTURE
  159. #endif
  160. ////////////////////////////////////////////////////////////////////////////////
  161. // Cygwin
  162. #ifdef __CYGWIN__
  163. // Required for some versions of Cygwin to declare gettimeofday
  164. // see: http://stackoverflow.com/questions/36901803/gettimeofday-not-declared-in-this-scope-cygwin
  165. # define _BSD_SOURCE
  166. // some versions of cygwin (most) do not support std::to_string. Use the libstd check.
  167. // https://gcc.gnu.org/onlinedocs/gcc-4.8.2/libstdc++/api/a01053_source.html line 2812-2813
  168. # if !((__cplusplus >= 201103L) && defined(_GLIBCXX_USE_C99) \
  169. && !defined(_GLIBCXX_HAVE_BROKEN_VSWPRINTF))
  170. # define CATCH_INTERNAL_CONFIG_NO_CPP11_TO_STRING
  171. # endif
  172. #endif // __CYGWIN__
  173. ////////////////////////////////////////////////////////////////////////////////
  174. // Visual C++
  175. #ifdef _MSC_VER
  176. # if _MSC_VER >= 1900 // Visual Studio 2015 or newer
  177. # define CATCH_INTERNAL_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS
  178. # endif
  179. // Universal Windows platform does not support SEH
  180. // Or console colours (or console at all...)
  181. # if defined(WINAPI_FAMILY) && (WINAPI_FAMILY == WINAPI_FAMILY_APP)
  182. # define CATCH_CONFIG_COLOUR_NONE
  183. # else
  184. # define CATCH_INTERNAL_CONFIG_WINDOWS_SEH
  185. # endif
  186. // MSVC traditional preprocessor needs some workaround for __VA_ARGS__
  187. // _MSVC_TRADITIONAL == 0 means new conformant preprocessor
  188. // _MSVC_TRADITIONAL == 1 means old traditional non-conformant preprocessor
  189. # if !defined(_MSVC_TRADITIONAL) || (defined(_MSVC_TRADITIONAL) && _MSVC_TRADITIONAL)
  190. # define CATCH_INTERNAL_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
  191. # endif
  192. #endif // _MSC_VER
  193. ////////////////////////////////////////////////////////////////////////////////
  194. // Check if we are compiled with -fno-exceptions or equivalent
  195. #if defined(__EXCEPTIONS) || defined(__cpp_exceptions) || defined(_CPPUNWIND)
  196. # define CATCH_INTERNAL_CONFIG_EXCEPTIONS_ENABLED
  197. #endif
  198. ////////////////////////////////////////////////////////////////////////////////
  199. // DJGPP
  200. #ifdef __DJGPP__
  201. # define CATCH_INTERNAL_CONFIG_NO_WCHAR
  202. #endif // __DJGPP__
  203. ////////////////////////////////////////////////////////////////////////////////
  204. // Embarcadero C++Build
  205. #if defined(__BORLANDC__)
  206. #define CATCH_INTERNAL_CONFIG_POLYFILL_ISNAN
  207. #endif
  208. ////////////////////////////////////////////////////////////////////////////////
  209. // Use of __COUNTER__ is suppressed during code analysis in
  210. // CLion/AppCode 2017.2.x and former, because __COUNTER__ is not properly
  211. // handled by it.
  212. // Otherwise all supported compilers support COUNTER macro,
  213. // but user still might want to turn it off
  214. #if ( !defined(__JETBRAINS_IDE__) || __JETBRAINS_IDE__ >= 20170300L )
  215. #define CATCH_INTERNAL_CONFIG_COUNTER
  216. #endif
  217. ////////////////////////////////////////////////////////////////////////////////
  218. // Check if string_view is available and usable
  219. // The check is split apart to work around v140 (VS2015) preprocessor issue...
  220. #if defined(__has_include)
  221. #if __has_include(<string_view>) && defined(CATCH_CPP17_OR_GREATER)
  222. # define CATCH_INTERNAL_CONFIG_CPP17_STRING_VIEW
  223. #endif
  224. #endif
  225. ////////////////////////////////////////////////////////////////////////////////
  226. // Check if optional is available and usable
  227. #if defined(__has_include)
  228. # if __has_include(<optional>) && defined(CATCH_CPP17_OR_GREATER)
  229. # define CATCH_INTERNAL_CONFIG_CPP17_OPTIONAL
  230. # endif // __has_include(<optional>) && defined(CATCH_CPP17_OR_GREATER)
  231. #endif // __has_include
  232. ////////////////////////////////////////////////////////////////////////////////
  233. // Check if variant is available and usable
  234. #if defined(__has_include)
  235. # if __has_include(<variant>) && defined(CATCH_CPP17_OR_GREATER)
  236. # if defined(__clang__) && (__clang_major__ < 8)
  237. // work around clang bug with libstdc++ https://bugs.llvm.org/show_bug.cgi?id=31852
  238. // fix should be in clang 8, workaround in libstdc++ 8.2
  239. # include <ciso646>
  240. # if defined(__GLIBCXX__) && defined(_GLIBCXX_RELEASE) && (_GLIBCXX_RELEASE < 9)
  241. # define CATCH_CONFIG_NO_CPP17_VARIANT
  242. # else
  243. # define CATCH_INTERNAL_CONFIG_CPP17_VARIANT
  244. # endif // defined(__GLIBCXX__) && defined(_GLIBCXX_RELEASE) && (_GLIBCXX_RELEASE < 9)
  245. # else
  246. # define CATCH_INTERNAL_CONFIG_CPP17_VARIANT
  247. # endif // defined(__clang__) && (__clang_major__ < 8)
  248. # endif // __has_include(<variant>) && defined(CATCH_CPP17_OR_GREATER)
  249. #endif // __has_include
  250. #if defined(CATCH_INTERNAL_CONFIG_COUNTER) && !defined(CATCH_CONFIG_NO_COUNTER) && !defined(CATCH_CONFIG_COUNTER)
  251. # define CATCH_CONFIG_COUNTER
  252. #endif
  253. #if defined(CATCH_INTERNAL_CONFIG_WINDOWS_SEH) && !defined(CATCH_CONFIG_NO_WINDOWS_SEH) && !defined(CATCH_CONFIG_WINDOWS_SEH) && !defined(CATCH_INTERNAL_CONFIG_NO_WINDOWS_SEH)
  254. # define CATCH_CONFIG_WINDOWS_SEH
  255. #endif
  256. // This is set by default, because we assume that unix compilers are posix-signal-compatible by default.
  257. #if defined(CATCH_INTERNAL_CONFIG_POSIX_SIGNALS) && !defined(CATCH_INTERNAL_CONFIG_NO_POSIX_SIGNALS) && !defined(CATCH_CONFIG_NO_POSIX_SIGNALS) && !defined(CATCH_CONFIG_POSIX_SIGNALS)
  258. # define CATCH_CONFIG_POSIX_SIGNALS
  259. #endif
  260. // This is set by default, because we assume that compilers with no wchar_t support are just rare exceptions.
  261. #if !defined(CATCH_INTERNAL_CONFIG_NO_WCHAR) && !defined(CATCH_CONFIG_NO_WCHAR) && !defined(CATCH_CONFIG_WCHAR)
  262. # define CATCH_CONFIG_WCHAR
  263. #endif
  264. #if !defined(CATCH_INTERNAL_CONFIG_NO_CPP11_TO_STRING) && !defined(CATCH_CONFIG_NO_CPP11_TO_STRING) && !defined(CATCH_CONFIG_CPP11_TO_STRING)
  265. # define CATCH_CONFIG_CPP11_TO_STRING
  266. #endif
  267. #if defined(CATCH_INTERNAL_CONFIG_CPP17_OPTIONAL) && !defined(CATCH_CONFIG_NO_CPP17_OPTIONAL) && !defined(CATCH_CONFIG_CPP17_OPTIONAL)
  268. # define CATCH_CONFIG_CPP17_OPTIONAL
  269. #endif
  270. #if defined(CATCH_INTERNAL_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS) && !defined(CATCH_CONFIG_NO_CPP17_UNCAUGHT_EXCEPTIONS) && !defined(CATCH_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS)
  271. # define CATCH_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS
  272. #endif
  273. #if defined(CATCH_INTERNAL_CONFIG_CPP17_STRING_VIEW) && !defined(CATCH_CONFIG_NO_CPP17_STRING_VIEW) && !defined(CATCH_CONFIG_CPP17_STRING_VIEW)
  274. # define CATCH_CONFIG_CPP17_STRING_VIEW
  275. #endif
  276. #if defined(CATCH_INTERNAL_CONFIG_CPP17_VARIANT) && !defined(CATCH_CONFIG_NO_CPP17_VARIANT) && !defined(CATCH_CONFIG_CPP17_VARIANT)
  277. # define CATCH_CONFIG_CPP17_VARIANT
  278. #endif
  279. #if defined(CATCH_CONFIG_EXPERIMENTAL_REDIRECT)
  280. # define CATCH_INTERNAL_CONFIG_NEW_CAPTURE
  281. #endif
  282. #if defined(CATCH_INTERNAL_CONFIG_NEW_CAPTURE) && !defined(CATCH_INTERNAL_CONFIG_NO_NEW_CAPTURE) && !defined(CATCH_CONFIG_NO_NEW_CAPTURE) && !defined(CATCH_CONFIG_NEW_CAPTURE)
  283. # define CATCH_CONFIG_NEW_CAPTURE
  284. #endif
  285. #if !defined(CATCH_INTERNAL_CONFIG_EXCEPTIONS_ENABLED) && !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
  286. # define CATCH_CONFIG_DISABLE_EXCEPTIONS
  287. #endif
  288. #if defined(CATCH_INTERNAL_CONFIG_POLYFILL_ISNAN) && !defined(CATCH_CONFIG_NO_POLYFILL_ISNAN) && !defined(CATCH_CONFIG_POLYFILL_ISNAN)
  289. # define CATCH_CONFIG_POLYFILL_ISNAN
  290. #endif
  291. #if !defined(CATCH_INTERNAL_SUPPRESS_PARENTHESES_WARNINGS)
  292. # define CATCH_INTERNAL_SUPPRESS_PARENTHESES_WARNINGS
  293. # define CATCH_INTERNAL_UNSUPPRESS_PARENTHESES_WARNINGS
  294. #endif
  295. #if !defined(CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS)
  296. # define CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS
  297. # define CATCH_INTERNAL_UNSUPPRESS_GLOBALS_WARNINGS
  298. #endif
  299. #if !defined(CATCH_INTERNAL_SUPPRESS_UNUSED_WARNINGS)
  300. # define CATCH_INTERNAL_SUPPRESS_UNUSED_WARNINGS
  301. # define CATCH_INTERNAL_UNSUPPRESS_UNUSED_WARNINGS
  302. #endif
  303. #if defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
  304. #define CATCH_TRY if ((true))
  305. #define CATCH_CATCH_ALL if ((false))
  306. #define CATCH_CATCH_ANON(type) if ((false))
  307. #else
  308. #define CATCH_TRY try
  309. #define CATCH_CATCH_ALL catch (...)
  310. #define CATCH_CATCH_ANON(type) catch (type)
  311. #endif
  312. #if defined(CATCH_INTERNAL_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR) && !defined(CATCH_CONFIG_NO_TRADITIONAL_MSVC_PREPROCESSOR) && !defined(CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR)
  313. #define CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
  314. #endif
  315. // end catch_compiler_capabilities.h
  316. #define INTERNAL_CATCH_UNIQUE_NAME_LINE2( name, line ) name##line
  317. #define INTERNAL_CATCH_UNIQUE_NAME_LINE( name, line ) INTERNAL_CATCH_UNIQUE_NAME_LINE2( name, line )
  318. #ifdef CATCH_CONFIG_COUNTER
  319. # define INTERNAL_CATCH_UNIQUE_NAME( name ) INTERNAL_CATCH_UNIQUE_NAME_LINE( name, __COUNTER__ )
  320. #else
  321. # define INTERNAL_CATCH_UNIQUE_NAME( name ) INTERNAL_CATCH_UNIQUE_NAME_LINE( name, __LINE__ )
  322. #endif
  323. #include <iosfwd>
  324. #include <string>
  325. #include <cstdint>
  326. // We need a dummy global operator<< so we can bring it into Catch namespace later
  327. struct Catch_global_namespace_dummy {};
  328. std::ostream& operator<<(std::ostream&, Catch_global_namespace_dummy);
  329. namespace Catch {
  330. struct CaseSensitive { enum Choice {
  331. Yes,
  332. No
  333. }; };
  334. class NonCopyable {
  335. NonCopyable( NonCopyable const& ) = delete;
  336. NonCopyable( NonCopyable && ) = delete;
  337. NonCopyable& operator = ( NonCopyable const& ) = delete;
  338. NonCopyable& operator = ( NonCopyable && ) = delete;
  339. protected:
  340. NonCopyable();
  341. virtual ~NonCopyable();
  342. };
  343. struct SourceLineInfo {
  344. SourceLineInfo() = delete;
  345. SourceLineInfo( char const* _file, std::size_t _line ) noexcept
  346. : file( _file ),
  347. line( _line )
  348. {}
  349. SourceLineInfo( SourceLineInfo const& other ) = default;
  350. SourceLineInfo& operator = ( SourceLineInfo const& ) = default;
  351. SourceLineInfo( SourceLineInfo&& ) noexcept = default;
  352. SourceLineInfo& operator = ( SourceLineInfo&& ) noexcept = default;
  353. bool empty() const noexcept;
  354. bool operator == ( SourceLineInfo const& other ) const noexcept;
  355. bool operator < ( SourceLineInfo const& other ) const noexcept;
  356. char const* file;
  357. std::size_t line;
  358. };
  359. std::ostream& operator << ( std::ostream& os, SourceLineInfo const& info );
  360. // Bring in operator<< from global namespace into Catch namespace
  361. // This is necessary because the overload of operator<< above makes
  362. // lookup stop at namespace Catch
  363. using ::operator<<;
  364. // Use this in variadic streaming macros to allow
  365. // >> +StreamEndStop
  366. // as well as
  367. // >> stuff +StreamEndStop
  368. struct StreamEndStop {
  369. std::string operator+() const;
  370. };
  371. template<typename T>
  372. T const& operator + ( T const& value, StreamEndStop ) {
  373. return value;
  374. }
  375. }
  376. #define CATCH_INTERNAL_LINEINFO \
  377. ::Catch::SourceLineInfo( __FILE__, static_cast<std::size_t>( __LINE__ ) )
  378. // end catch_common.h
  379. namespace Catch {
  380. struct RegistrarForTagAliases {
  381. RegistrarForTagAliases( char const* alias, char const* tag, SourceLineInfo const& lineInfo );
  382. };
  383. } // end namespace Catch
  384. #define CATCH_REGISTER_TAG_ALIAS( alias, spec ) \
  385. CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
  386. namespace{ Catch::RegistrarForTagAliases INTERNAL_CATCH_UNIQUE_NAME( AutoRegisterTagAlias )( alias, spec, CATCH_INTERNAL_LINEINFO ); } \
  387. CATCH_INTERNAL_UNSUPPRESS_GLOBALS_WARNINGS
  388. // end catch_tag_alias_autoregistrar.h
  389. // start catch_test_registry.h
  390. // start catch_interfaces_testcase.h
  391. #include <vector>
  392. namespace Catch {
  393. class TestSpec;
  394. struct ITestInvoker {
  395. virtual void invoke () const = 0;
  396. virtual ~ITestInvoker();
  397. };
  398. class TestCase;
  399. struct IConfig;
  400. struct ITestCaseRegistry {
  401. virtual ~ITestCaseRegistry();
  402. virtual std::vector<TestCase> const& getAllTests() const = 0;
  403. virtual std::vector<TestCase> const& getAllTestsSorted( IConfig const& config ) const = 0;
  404. };
  405. bool matchTest( TestCase const& testCase, TestSpec const& testSpec, IConfig const& config );
  406. std::vector<TestCase> filterTests( std::vector<TestCase> const& testCases, TestSpec const& testSpec, IConfig const& config );
  407. std::vector<TestCase> const& getAllTestCasesSorted( IConfig const& config );
  408. }
  409. // end catch_interfaces_testcase.h
  410. // start catch_stringref.h
  411. #include <cstddef>
  412. #include <string>
  413. #include <iosfwd>
  414. namespace Catch {
  415. /// A non-owning string class (similar to the forthcoming std::string_view)
  416. /// Note that, because a StringRef may be a substring of another string,
  417. /// it may not be null terminated. c_str() must return a null terminated
  418. /// string, however, and so the StringRef will internally take ownership
  419. /// (taking a copy), if necessary. In theory this ownership is not externally
  420. /// visible - but it does mean (substring) StringRefs should not be shared between
  421. /// threads.
  422. class StringRef {
  423. public:
  424. using size_type = std::size_t;
  425. private:
  426. friend struct StringRefTestAccess;
  427. char const* m_start;
  428. size_type m_size;
  429. char* m_data = nullptr;
  430. void takeOwnership();
  431. static constexpr char const* const s_empty = "";
  432. public: // construction/ assignment
  433. StringRef() noexcept
  434. : StringRef( s_empty, 0 )
  435. {}
  436. StringRef( StringRef const& other ) noexcept
  437. : m_start( other.m_start ),
  438. m_size( other.m_size )
  439. {}
  440. StringRef( StringRef&& other ) noexcept
  441. : m_start( other.m_start ),
  442. m_size( other.m_size ),
  443. m_data( other.m_data )
  444. {
  445. other.m_data = nullptr;
  446. }
  447. StringRef( char const* rawChars ) noexcept;
  448. StringRef( char const* rawChars, size_type size ) noexcept
  449. : m_start( rawChars ),
  450. m_size( size )
  451. {}
  452. StringRef( std::string const& stdString ) noexcept
  453. : m_start( stdString.c_str() ),
  454. m_size( stdString.size() )
  455. {}
  456. ~StringRef() noexcept {
  457. delete[] m_data;
  458. }
  459. auto operator = ( StringRef const &other ) noexcept -> StringRef& {
  460. delete[] m_data;
  461. m_data = nullptr;
  462. m_start = other.m_start;
  463. m_size = other.m_size;
  464. return *this;
  465. }
  466. operator std::string() const;
  467. void swap( StringRef& other ) noexcept;
  468. public: // operators
  469. auto operator == ( StringRef const& other ) const noexcept -> bool;
  470. auto operator != ( StringRef const& other ) const noexcept -> bool;
  471. auto operator[] ( size_type index ) const noexcept -> char;
  472. public: // named queries
  473. auto empty() const noexcept -> bool {
  474. return m_size == 0;
  475. }
  476. auto size() const noexcept -> size_type {
  477. return m_size;
  478. }
  479. auto numberOfCharacters() const noexcept -> size_type;
  480. auto c_str() const -> char const*;
  481. public: // substrings and searches
  482. auto substr( size_type start, size_type size ) const noexcept -> StringRef;
  483. // Returns the current start pointer.
  484. // Note that the pointer can change when if the StringRef is a substring
  485. auto currentData() const noexcept -> char const*;
  486. private: // ownership queries - may not be consistent between calls
  487. auto isOwned() const noexcept -> bool;
  488. auto isSubstring() const noexcept -> bool;
  489. };
  490. auto operator + ( StringRef const& lhs, StringRef const& rhs ) -> std::string;
  491. auto operator + ( StringRef const& lhs, char const* rhs ) -> std::string;
  492. auto operator + ( char const* lhs, StringRef const& rhs ) -> std::string;
  493. auto operator += ( std::string& lhs, StringRef const& sr ) -> std::string&;
  494. auto operator << ( std::ostream& os, StringRef const& sr ) -> std::ostream&;
  495. inline auto operator "" _sr( char const* rawChars, std::size_t size ) noexcept -> StringRef {
  496. return StringRef( rawChars, size );
  497. }
  498. } // namespace Catch
  499. inline auto operator "" _catch_sr( char const* rawChars, std::size_t size ) noexcept -> Catch::StringRef {
  500. return Catch::StringRef( rawChars, size );
  501. }
  502. // end catch_stringref.h
  503. // start catch_type_traits.hpp
  504. #include <type_traits>
  505. namespace Catch{
  506. #ifdef CATCH_CPP17_OR_GREATER
  507. template <typename...>
  508. inline constexpr auto is_unique = std::true_type{};
  509. template <typename T, typename... Rest>
  510. inline constexpr auto is_unique<T, Rest...> = std::bool_constant<
  511. (!std::is_same_v<T, Rest> && ...) && is_unique<Rest...>
  512. >{};
  513. #else
  514. template <typename...>
  515. struct is_unique : std::true_type{};
  516. template <typename T0, typename T1, typename... Rest>
  517. struct is_unique<T0, T1, Rest...> : std::integral_constant
  518. <bool,
  519. !std::is_same<T0, T1>::value
  520. && is_unique<T0, Rest...>::value
  521. && is_unique<T1, Rest...>::value
  522. >{};
  523. #endif
  524. }
  525. // end catch_type_traits.hpp
  526. // start catch_preprocessor.hpp
  527. #define CATCH_RECURSION_LEVEL0(...) __VA_ARGS__
  528. #define CATCH_RECURSION_LEVEL1(...) CATCH_RECURSION_LEVEL0(CATCH_RECURSION_LEVEL0(CATCH_RECURSION_LEVEL0(__VA_ARGS__)))
  529. #define CATCH_RECURSION_LEVEL2(...) CATCH_RECURSION_LEVEL1(CATCH_RECURSION_LEVEL1(CATCH_RECURSION_LEVEL1(__VA_ARGS__)))
  530. #define CATCH_RECURSION_LEVEL3(...) CATCH_RECURSION_LEVEL2(CATCH_RECURSION_LEVEL2(CATCH_RECURSION_LEVEL2(__VA_ARGS__)))
  531. #define CATCH_RECURSION_LEVEL4(...) CATCH_RECURSION_LEVEL3(CATCH_RECURSION_LEVEL3(CATCH_RECURSION_LEVEL3(__VA_ARGS__)))
  532. #define CATCH_RECURSION_LEVEL5(...) CATCH_RECURSION_LEVEL4(CATCH_RECURSION_LEVEL4(CATCH_RECURSION_LEVEL4(__VA_ARGS__)))
  533. #ifdef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
  534. #define INTERNAL_CATCH_EXPAND_VARGS(...) __VA_ARGS__
  535. // MSVC needs more evaluations
  536. #define CATCH_RECURSION_LEVEL6(...) CATCH_RECURSION_LEVEL5(CATCH_RECURSION_LEVEL5(CATCH_RECURSION_LEVEL5(__VA_ARGS__)))
  537. #define CATCH_RECURSE(...) CATCH_RECURSION_LEVEL6(CATCH_RECURSION_LEVEL6(__VA_ARGS__))
  538. #else
  539. #define CATCH_RECURSE(...) CATCH_RECURSION_LEVEL5(__VA_ARGS__)
  540. #endif
  541. #define CATCH_REC_END(...)
  542. #define CATCH_REC_OUT
  543. #define CATCH_EMPTY()
  544. #define CATCH_DEFER(id) id CATCH_EMPTY()
  545. #define CATCH_REC_GET_END2() 0, CATCH_REC_END
  546. #define CATCH_REC_GET_END1(...) CATCH_REC_GET_END2
  547. #define CATCH_REC_GET_END(...) CATCH_REC_GET_END1
  548. #define CATCH_REC_NEXT0(test, next, ...) next CATCH_REC_OUT
  549. #define CATCH_REC_NEXT1(test, next) CATCH_DEFER ( CATCH_REC_NEXT0 ) ( test, next, 0)
  550. #define CATCH_REC_NEXT(test, next) CATCH_REC_NEXT1(CATCH_REC_GET_END test, next)
  551. #define CATCH_REC_LIST0(f, x, peek, ...) , f(x) CATCH_DEFER ( CATCH_REC_NEXT(peek, CATCH_REC_LIST1) ) ( f, peek, __VA_ARGS__ )
  552. #define CATCH_REC_LIST1(f, x, peek, ...) , f(x) CATCH_DEFER ( CATCH_REC_NEXT(peek, CATCH_REC_LIST0) ) ( f, peek, __VA_ARGS__ )
  553. #define CATCH_REC_LIST2(f, x, peek, ...) f(x) CATCH_DEFER ( CATCH_REC_NEXT(peek, CATCH_REC_LIST1) ) ( f, peek, __VA_ARGS__ )
  554. #define CATCH_REC_LIST0_UD(f, userdata, x, peek, ...) , f(userdata, x) CATCH_DEFER ( CATCH_REC_NEXT(peek, CATCH_REC_LIST1_UD) ) ( f, userdata, peek, __VA_ARGS__ )
  555. #define CATCH_REC_LIST1_UD(f, userdata, x, peek, ...) , f(userdata, x) CATCH_DEFER ( CATCH_REC_NEXT(peek, CATCH_REC_LIST0_UD) ) ( f, userdata, peek, __VA_ARGS__ )
  556. #define CATCH_REC_LIST2_UD(f, userdata, x, peek, ...) f(userdata, x) CATCH_DEFER ( CATCH_REC_NEXT(peek, CATCH_REC_LIST1_UD) ) ( f, userdata, peek, __VA_ARGS__ )
  557. // Applies the function macro `f` to each of the remaining parameters, inserts commas between the results,
  558. // and passes userdata as the first parameter to each invocation,
  559. // e.g. CATCH_REC_LIST_UD(f, x, a, b, c) evaluates to f(x, a), f(x, b), f(x, c)
  560. #define CATCH_REC_LIST_UD(f, userdata, ...) CATCH_RECURSE(CATCH_REC_LIST2_UD(f, userdata, __VA_ARGS__, ()()(), ()()(), ()()(), 0))
  561. #define CATCH_REC_LIST(f, ...) CATCH_RECURSE(CATCH_REC_LIST2(f, __VA_ARGS__, ()()(), ()()(), ()()(), 0))
  562. #define INTERNAL_CATCH_EXPAND1(param) INTERNAL_CATCH_EXPAND2(param)
  563. #define INTERNAL_CATCH_EXPAND2(...) INTERNAL_CATCH_NO## __VA_ARGS__
  564. #define INTERNAL_CATCH_DEF(...) INTERNAL_CATCH_DEF __VA_ARGS__
  565. #define INTERNAL_CATCH_NOINTERNAL_CATCH_DEF
  566. #define INTERNAL_CATCH_REMOVE_PARENS(...) INTERNAL_CATCH_EXPAND1(INTERNAL_CATCH_DEF __VA_ARGS__)
  567. #define INTERNAL_CATCH_TEMPLATE_UNIQUE_NAME2(Name, ...) INTERNAL_CATCH_TEMPLATE_UNIQUE_NAME3(Name, __VA_ARGS__)
  568. #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
  569. #define INTERNAL_CATCH_TEMPLATE_UNIQUE_NAME3(Name,...) Name " - " #__VA_ARGS__
  570. #define INTERNAL_CATCH_TEMPLATE_UNIQUE_NAME(Name,...) INTERNAL_CATCH_TEMPLATE_UNIQUE_NAME2(Name, INTERNAL_CATCH_REMOVE_PARENS(__VA_ARGS__))
  571. #else
  572. // MSVC is adding extra space and needs more calls to properly remove ()
  573. #define INTERNAL_CATCH_TEMPLATE_UNIQUE_NAME3(Name,...) Name " -" #__VA_ARGS__
  574. #define INTERNAL_CATCH_TEMPLATE_UNIQUE_NAME1(Name, ...) INTERNAL_CATCH_TEMPLATE_UNIQUE_NAME2(Name, __VA_ARGS__)
  575. #define INTERNAL_CATCH_TEMPLATE_UNIQUE_NAME(Name, ...) INTERNAL_CATCH_TEMPLATE_UNIQUE_NAME1(Name, INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_REMOVE_PARENS(__VA_ARGS__)))
  576. #endif
  577. #define INTERNAL_CATCH_MAKE_TYPE_LIST(types) TypeList<INTERNAL_CATCH_REMOVE_PARENS(types)>
  578. #define INTERNAL_CATCH_MAKE_TYPE_LISTS_FROM_TYPES(types)\
  579. CATCH_REC_LIST(INTERNAL_CATCH_MAKE_TYPE_LIST,INTERNAL_CATCH_REMOVE_PARENS(types))
  580. // end catch_preprocessor.hpp
  581. // start catch_meta.hpp
  582. #include <type_traits>
  583. template< typename... >
  584. struct TypeList{};
  585. template< typename... >
  586. struct append;
  587. template< template<typename...> class L1
  588. , typename...E1
  589. , template<typename...> class L2
  590. , typename...E2
  591. >
  592. struct append< L1<E1...>, L2<E2...> >
  593. {
  594. using type = L1<E1..., E2...>;
  595. };
  596. template< template<typename...> class L1
  597. , typename...E1
  598. , template<typename...> class L2
  599. , typename...E2
  600. , typename...Rest
  601. >
  602. struct append< L1<E1...>, L2<E2...>, Rest...>
  603. {
  604. using type = typename append< L1<E1..., E2...>, Rest... >::type;
  605. };
  606. template< template<typename...> class
  607. , typename...
  608. >
  609. struct rewrap;
  610. template< template<typename...> class Container
  611. , template<typename...> class List
  612. , typename...elems
  613. >
  614. struct rewrap<Container, List<elems...>>
  615. {
  616. using type = TypeList< Container< elems... > >;
  617. };
  618. template< template<typename...> class Container
  619. , template<typename...> class List
  620. , class...Elems
  621. , typename...Elements>
  622. struct rewrap<Container, List<Elems...>, Elements...>
  623. {
  624. using type = typename append<TypeList<Container<Elems...>>, typename rewrap<Container, Elements...>::type>::type;
  625. };
  626. template< template<typename...> class...Containers >
  627. struct combine
  628. {
  629. template< typename...Types >
  630. struct with_types
  631. {
  632. template< template <typename...> class Final >
  633. struct into
  634. {
  635. using type = typename append<Final<>, typename rewrap<Containers, Types...>::type...>::type;
  636. };
  637. };
  638. };
  639. template<typename T>
  640. struct always_false : std::false_type {};
  641. // end catch_meta.hpp
  642. namespace Catch {
  643. template<typename C>
  644. class TestInvokerAsMethod : public ITestInvoker {
  645. void (C::*m_testAsMethod)();
  646. public:
  647. TestInvokerAsMethod( void (C::*testAsMethod)() ) noexcept : m_testAsMethod( testAsMethod ) {}
  648. void invoke() const override {
  649. C obj;
  650. (obj.*m_testAsMethod)();
  651. }
  652. };
  653. auto makeTestInvoker( void(*testAsFunction)() ) noexcept -> ITestInvoker*;
  654. template<typename C>
  655. auto makeTestInvoker( void (C::*testAsMethod)() ) noexcept -> ITestInvoker* {
  656. return new(std::nothrow) TestInvokerAsMethod<C>( testAsMethod );
  657. }
  658. struct NameAndTags {
  659. NameAndTags( StringRef const& name_ = StringRef(), StringRef const& tags_ = StringRef() ) noexcept;
  660. StringRef name;
  661. StringRef tags;
  662. };
  663. struct AutoReg : NonCopyable {
  664. AutoReg( ITestInvoker* invoker, SourceLineInfo const& lineInfo, StringRef const& classOrMethod, NameAndTags const& nameAndTags ) noexcept;
  665. ~AutoReg();
  666. };
  667. } // end namespace Catch
  668. #if defined(CATCH_CONFIG_DISABLE)
  669. #define INTERNAL_CATCH_TESTCASE_NO_REGISTRATION( TestName, ... ) \
  670. static void TestName()
  671. #define INTERNAL_CATCH_TESTCASE_METHOD_NO_REGISTRATION( TestName, ClassName, ... ) \
  672. namespace{ \
  673. struct TestName : INTERNAL_CATCH_REMOVE_PARENS(ClassName) { \
  674. void test(); \
  675. }; \
  676. } \
  677. void TestName::test()
  678. #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION( TestName, ... ) \
  679. template<typename TestType> \
  680. static void TestName()
  681. #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION( TestName, ClassName, ... ) \
  682. namespace{ \
  683. template<typename TestType> \
  684. struct TestName : INTERNAL_CATCH_REMOVE_PARENS(ClassName <TestType>) { \
  685. void test(); \
  686. }; \
  687. } \
  688. template<typename TestType> \
  689. void TestName::test()
  690. #endif
  691. ///////////////////////////////////////////////////////////////////////////////
  692. #define INTERNAL_CATCH_TESTCASE2( TestName, ... ) \
  693. static void TestName(); \
  694. CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
  695. namespace{ Catch::AutoReg INTERNAL_CATCH_UNIQUE_NAME( autoRegistrar )( Catch::makeTestInvoker( &TestName ), CATCH_INTERNAL_LINEINFO, Catch::StringRef(), Catch::NameAndTags{ __VA_ARGS__ } ); } /* NOLINT */ \
  696. CATCH_INTERNAL_UNSUPPRESS_GLOBALS_WARNINGS \
  697. static void TestName()
  698. #define INTERNAL_CATCH_TESTCASE( ... ) \
  699. INTERNAL_CATCH_TESTCASE2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ), __VA_ARGS__ )
  700. ///////////////////////////////////////////////////////////////////////////////
  701. #define INTERNAL_CATCH_METHOD_AS_TEST_CASE( QualifiedMethod, ... ) \
  702. CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
  703. namespace{ Catch::AutoReg INTERNAL_CATCH_UNIQUE_NAME( autoRegistrar )( Catch::makeTestInvoker( &QualifiedMethod ), CATCH_INTERNAL_LINEINFO, "&" #QualifiedMethod, Catch::NameAndTags{ __VA_ARGS__ } ); } /* NOLINT */ \
  704. CATCH_INTERNAL_UNSUPPRESS_GLOBALS_WARNINGS
  705. ///////////////////////////////////////////////////////////////////////////////
  706. #define INTERNAL_CATCH_TEST_CASE_METHOD2( TestName, ClassName, ... )\
  707. CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
  708. namespace{ \
  709. struct TestName : INTERNAL_CATCH_REMOVE_PARENS(ClassName) { \
  710. void test(); \
  711. }; \
  712. Catch::AutoReg INTERNAL_CATCH_UNIQUE_NAME( autoRegistrar ) ( Catch::makeTestInvoker( &TestName::test ), CATCH_INTERNAL_LINEINFO, #ClassName, Catch::NameAndTags{ __VA_ARGS__ } ); /* NOLINT */ \
  713. } \
  714. CATCH_INTERNAL_UNSUPPRESS_GLOBALS_WARNINGS \
  715. void TestName::test()
  716. #define INTERNAL_CATCH_TEST_CASE_METHOD( ClassName, ... ) \
  717. INTERNAL_CATCH_TEST_CASE_METHOD2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ), ClassName, __VA_ARGS__ )
  718. ///////////////////////////////////////////////////////////////////////////////
  719. #define INTERNAL_CATCH_REGISTER_TESTCASE( Function, ... ) \
  720. CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
  721. Catch::AutoReg INTERNAL_CATCH_UNIQUE_NAME( autoRegistrar )( Catch::makeTestInvoker( Function ), CATCH_INTERNAL_LINEINFO, Catch::StringRef(), Catch::NameAndTags{ __VA_ARGS__ } ); /* NOLINT */ \
  722. CATCH_INTERNAL_UNSUPPRESS_GLOBALS_WARNINGS
  723. ///////////////////////////////////////////////////////////////////////////////
  724. #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_2(TestName, TestFunc, Name, Tags, ... )\
  725. CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
  726. template<typename TestType> \
  727. static void TestFunc();\
  728. namespace {\
  729. template<typename...Types> \
  730. struct TestName{\
  731. template<typename...Ts> \
  732. TestName(Ts...names){\
  733. CATCH_INTERNAL_CHECK_UNIQUE_TYPES(CATCH_REC_LIST(INTERNAL_CATCH_REMOVE_PARENS, __VA_ARGS__)) \
  734. using expander = int[];\
  735. (void)expander{(Catch::AutoReg( Catch::makeTestInvoker( &TestFunc<Types> ), CATCH_INTERNAL_LINEINFO, Catch::StringRef(), Catch::NameAndTags{ names, Tags } ), 0)... };/* NOLINT */ \
  736. }\
  737. };\
  738. INTERNAL_CATCH_TEMPLATE_REGISTRY_INITIATE(TestName, Name, __VA_ARGS__) \
  739. }\
  740. CATCH_INTERNAL_UNSUPPRESS_GLOBALS_WARNINGS \
  741. template<typename TestType> \
  742. static void TestFunc()
  743. #if defined(CATCH_CPP17_OR_GREATER)
  744. #define CATCH_INTERNAL_CHECK_UNIQUE_TYPES(...) static_assert(Catch::is_unique<__VA_ARGS__>,"Duplicate type detected in declaration of template test case");
  745. #else
  746. #define CATCH_INTERNAL_CHECK_UNIQUE_TYPES(...) static_assert(Catch::is_unique<__VA_ARGS__>::value,"Duplicate type detected in declaration of template test case");
  747. #endif
  748. #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
  749. #define INTERNAL_CATCH_TEMPLATE_TEST_CASE(Name, Tags, ...) \
  750. 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__ )
  751. #else
  752. #define INTERNAL_CATCH_TEMPLATE_TEST_CASE(Name, Tags, ...) \
  753. 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__ ) )
  754. #endif
  755. #define INTERNAL_CATCH_TEMPLATE_REGISTRY_INITIATE(TestName, Name, ...)\
  756. static int INTERNAL_CATCH_UNIQUE_NAME( globalRegistrar ) = [](){\
  757. TestName<CATCH_REC_LIST(INTERNAL_CATCH_REMOVE_PARENS, __VA_ARGS__)>(CATCH_REC_LIST_UD(INTERNAL_CATCH_TEMPLATE_UNIQUE_NAME,Name, __VA_ARGS__));\
  758. return 0;\
  759. }();
  760. #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE2(TestName, TestFuncName, Name, Tags, TmplTypes, TypesList) \
  761. CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
  762. template<typename TestType> static void TestFuncName(); \
  763. namespace { \
  764. template<typename... Types> \
  765. struct TestName { \
  766. TestName() { \
  767. CATCH_INTERNAL_CHECK_UNIQUE_TYPES(Types...) \
  768. int index = 0; \
  769. using expander = int[]; \
  770. (void)expander{(Catch::AutoReg( Catch::makeTestInvoker( &TestFuncName<Types> ), CATCH_INTERNAL_LINEINFO, Catch::StringRef(), Catch::NameAndTags{ Name " - " + Catch::StringMaker<int>::convert(index++), Tags } ), 0)... };/* NOLINT */ \
  771. } \
  772. }; \
  773. static int INTERNAL_CATCH_UNIQUE_NAME( globalRegistrar ) = [](){ \
  774. using TestInit = combine<INTERNAL_CATCH_REMOVE_PARENS(TmplTypes)> \
  775. ::with_types<INTERNAL_CATCH_MAKE_TYPE_LISTS_FROM_TYPES(TypesList)>::into<TestName>::type; \
  776. TestInit(); \
  777. return 0; \
  778. }(); \
  779. } \
  780. CATCH_INTERNAL_UNSUPPRESS_GLOBALS_WARNINGS \
  781. template<typename TestType> \
  782. static void TestFuncName()
  783. #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
  784. #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE(Name, Tags, ...)\
  785. INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE2(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____F_U_N_C____ ),Name,Tags,__VA_ARGS__)
  786. #else
  787. #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE(Name, Tags, ...)\
  788. INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____F_U_N_C____ ), Name, Tags, __VA_ARGS__ ) )
  789. #endif
  790. #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_2( TestNameClass, TestName, ClassName, Name, Tags, ... ) \
  791. CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
  792. namespace{ \
  793. template<typename TestType> \
  794. struct TestName : INTERNAL_CATCH_REMOVE_PARENS(ClassName <TestType>) { \
  795. void test();\
  796. };\
  797. template<typename...Types> \
  798. struct TestNameClass{\
  799. template<typename...Ts> \
  800. TestNameClass(Ts...names){\
  801. CATCH_INTERNAL_CHECK_UNIQUE_TYPES(CATCH_REC_LIST(INTERNAL_CATCH_REMOVE_PARENS, __VA_ARGS__)) \
  802. using expander = int[];\
  803. (void)expander{(Catch::AutoReg( Catch::makeTestInvoker( &TestName<Types>::test ), CATCH_INTERNAL_LINEINFO, #ClassName, Catch::NameAndTags{ names, Tags } ), 0)... };/* NOLINT */ \
  804. }\
  805. };\
  806. INTERNAL_CATCH_TEMPLATE_REGISTRY_INITIATE(TestNameClass, Name, __VA_ARGS__)\
  807. }\
  808. CATCH_INTERNAL_UNSUPPRESS_GLOBALS_WARNINGS\
  809. template<typename TestType> \
  810. void TestName<TestType>::test()
  811. #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
  812. #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD( ClassName, Name, Tags,... ) \
  813. 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__ )
  814. #else
  815. #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD( ClassName, Name, Tags,... ) \
  816. 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__ ) )
  817. #endif
  818. #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_2(TestNameClass, TestName, ClassName, Name, Tags, TmplTypes, TypesList)\
  819. CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
  820. template<typename TestType> \
  821. struct TestName : INTERNAL_CATCH_REMOVE_PARENS(ClassName <TestType>) { \
  822. void test();\
  823. };\
  824. namespace {\
  825. template<typename...Types>\
  826. struct TestNameClass{\
  827. TestNameClass(){\
  828. CATCH_INTERNAL_CHECK_UNIQUE_TYPES(Types...)\
  829. int index = 0;\
  830. using expander = int[];\
  831. (void)expander{(Catch::AutoReg( Catch::makeTestInvoker( &TestName<Types>::test ), CATCH_INTERNAL_LINEINFO, #ClassName, Catch::NameAndTags{ Name " - " + Catch::StringMaker<int>::convert(index++), Tags } ), 0)... };/* NOLINT */ \
  832. }\
  833. };\
  834. static int INTERNAL_CATCH_UNIQUE_NAME( globalRegistrar ) = [](){\
  835. using TestInit = combine<INTERNAL_CATCH_REMOVE_PARENS(TmplTypes)>\
  836. ::with_types<INTERNAL_CATCH_MAKE_TYPE_LISTS_FROM_TYPES(TypesList)>::into<TestNameClass>::type;\
  837. TestInit();\
  838. return 0;\
  839. }(); \
  840. }\
  841. CATCH_INTERNAL_UNSUPPRESS_GLOBALS_WARNINGS \
  842. template<typename TestType> \
  843. void TestName<TestType>::test()
  844. #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
  845. #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( ClassName, Name, Tags, ... )\
  846. INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____F_U_N_C____ ), ClassName, Name, Tags, __VA_ARGS__ )
  847. #else
  848. #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( ClassName, Name, Tags, ... )\
  849. INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____F_U_N_C____ ), ClassName, Name, Tags, __VA_ARGS__ ) )
  850. #endif
  851. // end catch_test_registry.h
  852. // start catch_capture.hpp
  853. // start catch_assertionhandler.h
  854. // start catch_assertioninfo.h
  855. // start catch_result_type.h
  856. namespace Catch {
  857. // ResultWas::OfType enum
  858. struct ResultWas { enum OfType {
  859. Unknown = -1,
  860. Ok = 0,
  861. Info = 1,
  862. Warning = 2,
  863. FailureBit = 0x10,
  864. ExpressionFailed = FailureBit | 1,
  865. ExplicitFailure = FailureBit | 2,
  866. Exception = 0x100 | FailureBit,
  867. ThrewException = Exception | 1,
  868. DidntThrowException = Exception | 2,
  869. FatalErrorCondition = 0x200 | FailureBit
  870. }; };
  871. bool isOk( ResultWas::OfType resultType );
  872. bool isJustInfo( int flags );
  873. // ResultDisposition::Flags enum
  874. struct ResultDisposition { enum Flags {
  875. Normal = 0x01,
  876. ContinueOnFailure = 0x02, // Failures fail test, but execution continues
  877. FalseTest = 0x04, // Prefix expression with !
  878. SuppressFail = 0x08 // Failures are reported but do not fail the test
  879. }; };
  880. ResultDisposition::Flags operator | ( ResultDisposition::Flags lhs, ResultDisposition::Flags rhs );
  881. bool shouldContinueOnFailure( int flags );
  882. inline bool isFalseTest( int flags ) { return ( flags & ResultDisposition::FalseTest ) != 0; }
  883. bool shouldSuppressFailure( int flags );
  884. } // end namespace Catch
  885. // end catch_result_type.h
  886. namespace Catch {
  887. struct AssertionInfo
  888. {
  889. StringRef macroName;
  890. SourceLineInfo lineInfo;
  891. StringRef capturedExpression;
  892. ResultDisposition::Flags resultDisposition;
  893. // We want to delete this constructor but a compiler bug in 4.8 means
  894. // the struct is then treated as non-aggregate
  895. //AssertionInfo() = delete;
  896. };
  897. } // end namespace Catch
  898. // end catch_assertioninfo.h
  899. // start catch_decomposer.h
  900. // start catch_tostring.h
  901. #include <vector>
  902. #include <cstddef>
  903. #include <type_traits>
  904. #include <string>
  905. // start catch_stream.h
  906. #include <iosfwd>
  907. #include <cstddef>
  908. #include <ostream>
  909. namespace Catch {
  910. std::ostream& cout();
  911. std::ostream& cerr();
  912. std::ostream& clog();
  913. class StringRef;
  914. struct IStream {
  915. virtual ~IStream();
  916. virtual std::ostream& stream() const = 0;
  917. };
  918. auto makeStream( StringRef const &filename ) -> IStream const*;
  919. class ReusableStringStream {
  920. std::size_t m_index;
  921. std::ostream* m_oss;
  922. public:
  923. ReusableStringStream();
  924. ~ReusableStringStream();
  925. auto str() const -> std::string;
  926. template<typename T>
  927. auto operator << ( T const& value ) -> ReusableStringStream& {
  928. *m_oss << value;
  929. return *this;
  930. }
  931. auto get() -> std::ostream& { return *m_oss; }
  932. };
  933. }
  934. // end catch_stream.h
  935. #ifdef CATCH_CONFIG_CPP17_STRING_VIEW
  936. #include <string_view>
  937. #endif
  938. #ifdef __OBJC__
  939. // start catch_objc_arc.hpp
  940. #import <Foundation/Foundation.h>
  941. #ifdef __has_feature
  942. #define CATCH_ARC_ENABLED __has_feature(objc_arc)
  943. #else
  944. #define CATCH_ARC_ENABLED 0
  945. #endif
  946. void arcSafeRelease( NSObject* obj );
  947. id performOptionalSelector( id obj, SEL sel );
  948. #if !CATCH_ARC_ENABLED
  949. inline void arcSafeRelease( NSObject* obj ) {
  950. [obj release];
  951. }
  952. inline id performOptionalSelector( id obj, SEL sel ) {
  953. if( [obj respondsToSelector: sel] )
  954. return [obj performSelector: sel];
  955. return nil;
  956. }
  957. #define CATCH_UNSAFE_UNRETAINED
  958. #define CATCH_ARC_STRONG
  959. #else
  960. inline void arcSafeRelease( NSObject* ){}
  961. inline id performOptionalSelector( id obj, SEL sel ) {
  962. #ifdef __clang__
  963. #pragma clang diagnostic push
  964. #pragma clang diagnostic ignored "-Warc-performSelector-leaks"
  965. #endif
  966. if( [obj respondsToSelector: sel] )
  967. return [obj performSelector: sel];
  968. #ifdef __clang__
  969. #pragma clang diagnostic pop
  970. #endif
  971. return nil;
  972. }
  973. #define CATCH_UNSAFE_UNRETAINED __unsafe_unretained
  974. #define CATCH_ARC_STRONG __strong
  975. #endif
  976. // end catch_objc_arc.hpp
  977. #endif
  978. #ifdef _MSC_VER
  979. #pragma warning(push)
  980. #pragma warning(disable:4180) // We attempt to stream a function (address) by const&, which MSVC complains about but is harmless
  981. #endif
  982. namespace Catch {
  983. namespace Detail {
  984. extern const std::string unprintableString;
  985. std::string rawMemoryToString( const void *object, std::size_t size );
  986. template<typename T>
  987. std::string rawMemoryToString( const T& object ) {
  988. return rawMemoryToString( &object, sizeof(object) );
  989. }
  990. template<typename T>
  991. class IsStreamInsertable {
  992. template<typename SS, typename TT>
  993. static auto test(int)
  994. -> decltype(std::declval<SS&>() << std::declval<TT>(), std::true_type());
  995. template<typename, typename>
  996. static auto test(...)->std::false_type;
  997. public:
  998. static const bool value = decltype(test<std::ostream, const T&>(0))::value;
  999. };
  1000. template<typename E>
  1001. std::string convertUnknownEnumToString( E e );
  1002. template<typename T>
  1003. typename std::enable_if<
  1004. !std::is_enum<T>::value && !std::is_base_of<std::exception, T>::value,
  1005. std::string>::type convertUnstreamable( T const& ) {
  1006. return Detail::unprintableString;
  1007. }
  1008. template<typename T>
  1009. typename std::enable_if<
  1010. !std::is_enum<T>::value && std::is_base_of<std::exception, T>::value,
  1011. std::string>::type convertUnstreamable(T const& ex) {
  1012. return ex.what();
  1013. }
  1014. template<typename T>
  1015. typename std::enable_if<
  1016. std::is_enum<T>::value
  1017. , std::string>::type convertUnstreamable( T const& value ) {
  1018. return convertUnknownEnumToString( value );
  1019. }
  1020. #if defined(_MANAGED)
  1021. //! Convert a CLR string to a utf8 std::string
  1022. template<typename T>
  1023. std::string clrReferenceToString( T^ ref ) {
  1024. if (ref == nullptr)
  1025. return std::string("null");
  1026. auto bytes = System::Text::Encoding::UTF8->GetBytes(ref->ToString());
  1027. cli::pin_ptr<System::Byte> p = &bytes[0];
  1028. return std::string(reinterpret_cast<char const *>(p), bytes->Length);
  1029. }
  1030. #endif
  1031. } // namespace Detail
  1032. // If we decide for C++14, change these to enable_if_ts
  1033. template <typename T, typename = void>
  1034. struct StringMaker {
  1035. template <typename Fake = T>
  1036. static
  1037. typename std::enable_if<::Catch::Detail::IsStreamInsertable<Fake>::value, std::string>::type
  1038. convert(const Fake& value) {
  1039. ReusableStringStream rss;
  1040. // NB: call using the function-like syntax to avoid ambiguity with
  1041. // user-defined templated operator<< under clang.
  1042. rss.operator<<(value);
  1043. return rss.str();
  1044. }
  1045. template <typename Fake = T>
  1046. static
  1047. typename std::enable_if<!::Catch::Detail::IsStreamInsertable<Fake>::value, std::string>::type
  1048. convert( const Fake& value ) {
  1049. #if !defined(CATCH_CONFIG_FALLBACK_STRINGIFIER)
  1050. return Detail::convertUnstreamable(value);
  1051. #else
  1052. return CATCH_CONFIG_FALLBACK_STRINGIFIER(value);
  1053. #endif
  1054. }
  1055. };
  1056. namespace Detail {
  1057. // This function dispatches all stringification requests inside of Catch.
  1058. // Should be preferably called fully qualified, like ::Catch::Detail::stringify
  1059. template <typename T>
  1060. std::string stringify(const T& e) {
  1061. return ::Catch::StringMaker<typename std::remove_cv<typename std::remove_reference<T>::type>::type>::convert(e);
  1062. }
  1063. template<typename E>
  1064. std::string convertUnknownEnumToString( E e ) {
  1065. return ::Catch::Detail::stringify(static_cast<typename std::underlying_type<E>::type>(e));
  1066. }
  1067. #if defined(_MANAGED)
  1068. template <typename T>
  1069. std::string stringify( T^ e ) {
  1070. return ::Catch::StringMaker<T^>::convert(e);
  1071. }
  1072. #endif
  1073. } // namespace Detail
  1074. // Some predefined specializations
  1075. template<>
  1076. struct StringMaker<std::string> {
  1077. static std::string convert(const std::string& str);
  1078. };
  1079. #ifdef CATCH_CONFIG_CPP17_STRING_VIEW
  1080. template<>
  1081. struct StringMaker<std::string_view> {
  1082. static std::string convert(std::string_view str);
  1083. };
  1084. #endif
  1085. template<>
  1086. struct StringMaker<char const *> {
  1087. static std::string convert(char const * str);
  1088. };
  1089. template<>
  1090. struct StringMaker<char *> {
  1091. static std::string convert(char * str);
  1092. };
  1093. #ifdef CATCH_CONFIG_WCHAR
  1094. template<>
  1095. struct StringMaker<std::wstring> {
  1096. static std::string convert(const std::wstring& wstr);
  1097. };
  1098. # ifdef CATCH_CONFIG_CPP17_STRING_VIEW
  1099. template<>
  1100. struct StringMaker<std::wstring_view> {
  1101. static std::string convert(std::wstring_view str);
  1102. };
  1103. # endif
  1104. template<>
  1105. struct StringMaker<wchar_t const *> {
  1106. static std::string convert(wchar_t const * str);
  1107. };
  1108. template<>
  1109. struct StringMaker<wchar_t *> {
  1110. static std::string convert(wchar_t * str);
  1111. };
  1112. #endif
  1113. // TBD: Should we use `strnlen` to ensure that we don't go out of the buffer,
  1114. // while keeping string semantics?
  1115. template<int SZ>
  1116. struct StringMaker<char[SZ]> {
  1117. static std::string convert(char const* str) {
  1118. return ::Catch::Detail::stringify(std::string{ str });
  1119. }
  1120. };
  1121. template<int SZ>
  1122. struct StringMaker<signed char[SZ]> {
  1123. static std::string convert(signed char const* str) {
  1124. return ::Catch::Detail::stringify(std::string{ reinterpret_cast<char const *>(str) });
  1125. }
  1126. };
  1127. template<int SZ>
  1128. struct StringMaker<unsigned char[SZ]> {
  1129. static std::string convert(unsigned char const* str) {
  1130. return ::Catch::Detail::stringify(std::string{ reinterpret_cast<char const *>(str) });
  1131. }
  1132. };
  1133. template<>
  1134. struct StringMaker<int> {
  1135. static std::string convert(int value);
  1136. };
  1137. template<>
  1138. struct StringMaker<long> {
  1139. static std::string convert(long value);
  1140. };
  1141. template<>
  1142. struct StringMaker<long long> {
  1143. static std::string convert(long long value);
  1144. };
  1145. template<>
  1146. struct StringMaker<unsigned int> {
  1147. static std::string convert(unsigned int value);
  1148. };
  1149. template<>
  1150. struct StringMaker<unsigned long> {
  1151. static std::string convert(unsigned long value);
  1152. };
  1153. template<>
  1154. struct StringMaker<unsigned long long> {
  1155. static std::string convert(unsigned long long value);
  1156. };
  1157. template<>
  1158. struct StringMaker<bool> {
  1159. static std::string convert(bool b);
  1160. };
  1161. template<>
  1162. struct StringMaker<char> {
  1163. static std::string convert(char c);
  1164. };
  1165. template<>
  1166. struct StringMaker<signed char> {
  1167. static std::string convert(signed char c);
  1168. };
  1169. template<>
  1170. struct StringMaker<unsigned char> {
  1171. static std::string convert(unsigned char c);
  1172. };
  1173. template<>
  1174. struct StringMaker<std::nullptr_t> {
  1175. static std::string convert(std::nullptr_t);
  1176. };
  1177. template<>
  1178. struct StringMaker<float> {
  1179. static std::string convert(float value);
  1180. };
  1181. template<>
  1182. struct StringMaker<double> {
  1183. static std::string convert(double value);
  1184. };
  1185. template <typename T>
  1186. struct StringMaker<T*> {
  1187. template <typename U>
  1188. static std::string convert(U* p) {
  1189. if (p) {
  1190. return ::Catch::Detail::rawMemoryToString(p);
  1191. } else {
  1192. return "nullptr";
  1193. }
  1194. }
  1195. };
  1196. template <typename R, typename C>
  1197. struct StringMaker<R C::*> {
  1198. static std::string convert(R C::* p) {
  1199. if (p) {
  1200. return ::Catch::Detail::rawMemoryToString(p);
  1201. } else {
  1202. return "nullptr";
  1203. }
  1204. }
  1205. };
  1206. #if defined(_MANAGED)
  1207. template <typename T>
  1208. struct StringMaker<T^> {
  1209. static std::string convert( T^ ref ) {
  1210. return ::Catch::Detail::clrReferenceToString(ref);
  1211. }
  1212. };
  1213. #endif
  1214. namespace Detail {
  1215. template<typename InputIterator>
  1216. std::string rangeToString(InputIterator first, InputIterator last) {
  1217. ReusableStringStream rss;
  1218. rss << "{ ";
  1219. if (first != last) {
  1220. rss << ::Catch::Detail::stringify(*first);
  1221. for (++first; first != last; ++first)
  1222. rss << ", " << ::Catch::Detail::stringify(*first);
  1223. }
  1224. rss << " }";
  1225. return rss.str();
  1226. }
  1227. }
  1228. #ifdef __OBJC__
  1229. template<>
  1230. struct StringMaker<NSString*> {
  1231. static std::string convert(NSString * nsstring) {
  1232. if (!nsstring)
  1233. return "nil";
  1234. return std::string("@") + [nsstring UTF8String];
  1235. }
  1236. };
  1237. template<>
  1238. struct StringMaker<NSObject*> {
  1239. static std::string convert(NSObject* nsObject) {
  1240. return ::Catch::Detail::stringify([nsObject description]);
  1241. }
  1242. };
  1243. namespace Detail {
  1244. inline std::string stringify( NSString* nsstring ) {
  1245. return StringMaker<NSString*>::convert( nsstring );
  1246. }
  1247. } // namespace Detail
  1248. #endif // __OBJC__
  1249. } // namespace Catch
  1250. //////////////////////////////////////////////////////
  1251. // Separate std-lib types stringification, so it can be selectively enabled
  1252. // This means that we do not bring in
  1253. #if defined(CATCH_CONFIG_ENABLE_ALL_STRINGMAKERS)
  1254. # define CATCH_CONFIG_ENABLE_PAIR_STRINGMAKER
  1255. # define CATCH_CONFIG_ENABLE_TUPLE_STRINGMAKER
  1256. # define CATCH_CONFIG_ENABLE_VARIANT_STRINGMAKER
  1257. # define CATCH_CONFIG_ENABLE_CHRONO_STRINGMAKER
  1258. # define CATCH_CONFIG_ENABLE_OPTIONAL_STRINGMAKER
  1259. #endif
  1260. // Separate std::pair specialization
  1261. #if defined(CATCH_CONFIG_ENABLE_PAIR_STRINGMAKER)
  1262. #include <utility>
  1263. namespace Catch {
  1264. template<typename T1, typename T2>
  1265. struct StringMaker<std::pair<T1, T2> > {
  1266. static std::string convert(const std::pair<T1, T2>& pair) {
  1267. ReusableStringStream rss;
  1268. rss << "{ "
  1269. << ::Catch::Detail::stringify(pair.first)
  1270. << ", "
  1271. << ::Catch::Detail::stringify(pair.second)
  1272. << " }";
  1273. return rss.str();
  1274. }
  1275. };
  1276. }
  1277. #endif // CATCH_CONFIG_ENABLE_PAIR_STRINGMAKER
  1278. #if defined(CATCH_CONFIG_ENABLE_OPTIONAL_STRINGMAKER) && defined(CATCH_CONFIG_CPP17_OPTIONAL)
  1279. #include <optional>
  1280. namespace Catch {
  1281. template<typename T>
  1282. struct StringMaker<std::optional<T> > {
  1283. static std::string convert(const std::optional<T>& optional) {
  1284. ReusableStringStream rss;
  1285. if (optional.has_value()) {
  1286. rss << ::Catch::Detail::stringify(*optional);
  1287. } else {
  1288. rss << "{ }";
  1289. }
  1290. return rss.str();
  1291. }
  1292. };
  1293. }
  1294. #endif // CATCH_CONFIG_ENABLE_OPTIONAL_STRINGMAKER
  1295. // Separate std::tuple specialization
  1296. #if defined(CATCH_CONFIG_ENABLE_TUPLE_STRINGMAKER)
  1297. #include <tuple>
  1298. namespace Catch {
  1299. namespace Detail {
  1300. template<
  1301. typename Tuple,
  1302. std::size_t N = 0,
  1303. bool = (N < std::tuple_size<Tuple>::value)
  1304. >
  1305. struct TupleElementPrinter {
  1306. static void print(const Tuple& tuple, std::ostream& os) {
  1307. os << (N ? ", " : " ")
  1308. << ::Catch::Detail::stringify(std::get<N>(tuple));
  1309. TupleElementPrinter<Tuple, N + 1>::print(tuple, os);
  1310. }
  1311. };
  1312. template<
  1313. typename Tuple,
  1314. std::size_t N
  1315. >
  1316. struct TupleElementPrinter<Tuple, N, false> {
  1317. static void print(const Tuple&, std::ostream&) {}
  1318. };
  1319. }
  1320. template<typename ...Types>
  1321. struct StringMaker<std::tuple<Types...>> {
  1322. static std::string convert(const std::tuple<Types...>& tuple) {
  1323. ReusableStringStream rss;
  1324. rss << '{';
  1325. Detail::TupleElementPrinter<std::tuple<Types...>>::print(tuple, rss.get());
  1326. rss << " }";
  1327. return rss.str();
  1328. }
  1329. };
  1330. }
  1331. #endif // CATCH_CONFIG_ENABLE_TUPLE_STRINGMAKER
  1332. #if defined(CATCH_CONFIG_ENABLE_VARIANT_STRINGMAKER) && defined(CATCH_CONFIG_CPP17_VARIANT)
  1333. #include <variant>
  1334. namespace Catch {
  1335. template<>
  1336. struct StringMaker<std::monostate> {
  1337. static std::string convert(const std::monostate&) {
  1338. return "{ }";
  1339. }
  1340. };
  1341. template<typename... Elements>
  1342. struct StringMaker<std::variant<Elements...>> {
  1343. static std::string convert(const std::variant<Elements...>& variant) {
  1344. if (variant.valueless_by_exception()) {
  1345. return "{valueless variant}";
  1346. } else {
  1347. return std::visit(
  1348. [](const auto& value) {
  1349. return ::Catch::Detail::stringify(value);
  1350. },
  1351. variant
  1352. );
  1353. }
  1354. }
  1355. };
  1356. }
  1357. #endif // CATCH_CONFIG_ENABLE_VARIANT_STRINGMAKER
  1358. namespace Catch {
  1359. struct not_this_one {}; // Tag type for detecting which begin/ end are being selected
  1360. // Import begin/ end from std here so they are considered alongside the fallback (...) overloads in this namespace
  1361. using std::begin;
  1362. using std::end;
  1363. not_this_one begin( ... );
  1364. not_this_one end( ... );
  1365. template <typename T>
  1366. struct is_range {
  1367. static const bool value =
  1368. !std::is_same<decltype(begin(std::declval<T>())), not_this_one>::value &&
  1369. !std::is_same<decltype(end(std::declval<T>())), not_this_one>::value;
  1370. };
  1371. #if defined(_MANAGED) // Managed types are never ranges
  1372. template <typename T>
  1373. struct is_range<T^> {
  1374. static const bool value = false;
  1375. };
  1376. #endif
  1377. template<typename Range>
  1378. std::string rangeToString( Range const& range ) {
  1379. return ::Catch::Detail::rangeToString( begin( range ), end( range ) );
  1380. }
  1381. // Handle vector<bool> specially
  1382. template<typename Allocator>
  1383. std::string rangeToString( std::vector<bool, Allocator> const& v ) {
  1384. ReusableStringStream rss;
  1385. rss << "{ ";
  1386. bool first = true;
  1387. for( bool b : v ) {
  1388. if( first )
  1389. first = false;
  1390. else
  1391. rss << ", ";
  1392. rss << ::Catch::Detail::stringify( b );
  1393. }
  1394. rss << " }";
  1395. return rss.str();
  1396. }
  1397. template<typename R>
  1398. struct StringMaker<R, typename std::enable_if<is_range<R>::value && !::Catch::Detail::IsStreamInsertable<R>::value>::type> {
  1399. static std::string convert( R const& range ) {
  1400. return rangeToString( range );
  1401. }
  1402. };
  1403. template <typename T, int SZ>
  1404. struct StringMaker<T[SZ]> {
  1405. static std::string convert(T const(&arr)[SZ]) {
  1406. return rangeToString(arr);
  1407. }
  1408. };
  1409. } // namespace Catch
  1410. // Separate std::chrono::duration specialization
  1411. #if defined(CATCH_CONFIG_ENABLE_CHRONO_STRINGMAKER)
  1412. #include <ctime>
  1413. #include <ratio>
  1414. #include <chrono>
  1415. namespace Catch {
  1416. template <class Ratio>
  1417. struct ratio_string {
  1418. static std::string symbol();
  1419. };
  1420. template <class Ratio>
  1421. std::string ratio_string<Ratio>::symbol() {
  1422. Catch::ReusableStringStream rss;
  1423. rss << '[' << Ratio::num << '/'
  1424. << Ratio::den << ']';
  1425. return rss.str();
  1426. }
  1427. template <>
  1428. struct ratio_string<std::atto> {
  1429. static std::string symbol();
  1430. };
  1431. template <>
  1432. struct ratio_string<std::femto> {
  1433. static std::string symbol();
  1434. };
  1435. template <>
  1436. struct ratio_string<std::pico> {
  1437. static std::string symbol();
  1438. };
  1439. template <>
  1440. struct ratio_string<std::nano> {
  1441. static std::string symbol();
  1442. };
  1443. template <>
  1444. struct ratio_string<std::micro> {
  1445. static std::string symbol();
  1446. };
  1447. template <>
  1448. struct ratio_string<std::milli> {
  1449. static std::string symbol();
  1450. };
  1451. ////////////
  1452. // std::chrono::duration specializations
  1453. template<typename Value, typename Ratio>
  1454. struct StringMaker<std::chrono::duration<Value, Ratio>> {
  1455. static std::string convert(std::chrono::duration<Value, Ratio> const& duration) {
  1456. ReusableStringStream rss;
  1457. rss << duration.count() << ' ' << ratio_string<Ratio>::symbol() << 's';
  1458. return rss.str();
  1459. }
  1460. };
  1461. template<typename Value>
  1462. struct StringMaker<std::chrono::duration<Value, std::ratio<1>>> {
  1463. static std::string convert(std::chrono::duration<Value, std::ratio<1>> const& duration) {
  1464. ReusableStringStream rss;
  1465. rss << duration.count() << " s";
  1466. return rss.str();
  1467. }
  1468. };
  1469. template<typename Value>
  1470. struct StringMaker<std::chrono::duration<Value, std::ratio<60>>> {
  1471. static std::string convert(std::chrono::duration<Value, std::ratio<60>> const& duration) {
  1472. ReusableStringStream rss;
  1473. rss << duration.count() << " m";
  1474. return rss.str();
  1475. }
  1476. };
  1477. template<typename Value>
  1478. struct StringMaker<std::chrono::duration<Value, std::ratio<3600>>> {
  1479. static std::string convert(std::chrono::duration<Value, std::ratio<3600>> const& duration) {
  1480. ReusableStringStream rss;
  1481. rss << duration.count() << " h";
  1482. return rss.str();
  1483. }
  1484. };
  1485. ////////////
  1486. // std::chrono::time_point specialization
  1487. // Generic time_point cannot be specialized, only std::chrono::time_point<system_clock>
  1488. template<typename Clock, typename Duration>
  1489. struct StringMaker<std::chrono::time_point<Clock, Duration>> {
  1490. static std::string convert(std::chrono::time_point<Clock, Duration> const& time_point) {
  1491. return ::Catch::Detail::stringify(time_point.time_since_epoch()) + " since epoch";
  1492. }
  1493. };
  1494. // std::chrono::time_point<system_clock> specialization
  1495. template<typename Duration>
  1496. struct StringMaker<std::chrono::time_point<std::chrono::system_clock, Duration>> {
  1497. static std::string convert(std::chrono::time_point<std::chrono::system_clock, Duration> const& time_point) {
  1498. auto converted = std::chrono::system_clock::to_time_t(time_point);
  1499. #ifdef _MSC_VER
  1500. std::tm timeInfo = {};
  1501. gmtime_s(&timeInfo, &converted);
  1502. #else
  1503. std::tm* timeInfo = std::gmtime(&converted);
  1504. #endif
  1505. auto const timeStampSize = sizeof("2017-01-16T17:06:45Z");
  1506. char timeStamp[timeStampSize];
  1507. const char * const fmt = "%Y-%m-%dT%H:%M:%SZ";
  1508. #ifdef _MSC_VER
  1509. std::strftime(timeStamp, timeStampSize, fmt, &timeInfo);
  1510. #else
  1511. std::strftime(timeStamp, timeStampSize, fmt, timeInfo);
  1512. #endif
  1513. return std::string(timeStamp);
  1514. }
  1515. };
  1516. }
  1517. #endif // CATCH_CONFIG_ENABLE_CHRONO_STRINGMAKER
  1518. #ifdef _MSC_VER
  1519. #pragma warning(pop)
  1520. #endif
  1521. // end catch_tostring.h
  1522. #include <iosfwd>
  1523. #ifdef _MSC_VER
  1524. #pragma warning(push)
  1525. #pragma warning(disable:4389) // '==' : signed/unsigned mismatch
  1526. #pragma warning(disable:4018) // more "signed/unsigned mismatch"
  1527. #pragma warning(disable:4312) // Converting int to T* using reinterpret_cast (issue on x64 platform)
  1528. #pragma warning(disable:4180) // qualifier applied to function type has no meaning
  1529. #pragma warning(disable:4800) // Forcing result to true or false
  1530. #endif
  1531. namespace Catch {
  1532. struct ITransientExpression {
  1533. auto isBinaryExpression() const -> bool { return m_isBinaryExpression; }
  1534. auto getResult() const -> bool { return m_result; }
  1535. virtual void streamReconstructedExpression( std::ostream &os ) const = 0;
  1536. ITransientExpression( bool isBinaryExpression, bool result )
  1537. : m_isBinaryExpression( isBinaryExpression ),
  1538. m_result( result )
  1539. {}
  1540. // We don't actually need a virtual destructor, but many static analysers
  1541. // complain if it's not here :-(
  1542. virtual ~ITransientExpression();
  1543. bool m_isBinaryExpression;
  1544. bool m_result;
  1545. };
  1546. void formatReconstructedExpression( std::ostream &os, std::string const& lhs, StringRef op, std::string const& rhs );
  1547. template<typename LhsT, typename RhsT>
  1548. class BinaryExpr : public ITransientExpression {
  1549. LhsT m_lhs;
  1550. StringRef m_op;
  1551. RhsT m_rhs;
  1552. void streamReconstructedExpression( std::ostream &os ) const override {
  1553. formatReconstructedExpression
  1554. ( os, Catch::Detail::stringify( m_lhs ), m_op, Catch::Detail::stringify( m_rhs ) );
  1555. }
  1556. public:
  1557. BinaryExpr( bool comparisonResult, LhsT lhs, StringRef op, RhsT rhs )
  1558. : ITransientExpression{ true, comparisonResult },
  1559. m_lhs( lhs ),
  1560. m_op( op ),
  1561. m_rhs( rhs )
  1562. {}
  1563. template<typename T>
  1564. auto operator && ( T ) const -> BinaryExpr<LhsT, RhsT const&> const {
  1565. static_assert(always_false<T>::value,
  1566. "chained comparisons are not supported inside assertions, "
  1567. "wrap the expression inside parentheses, or decompose it");
  1568. }
  1569. template<typename T>
  1570. auto operator || ( T ) const -> BinaryExpr<LhsT, RhsT const&> const {
  1571. static_assert(always_false<T>::value,
  1572. "chained comparisons are not supported inside assertions, "
  1573. "wrap the expression inside parentheses, or decompose it");
  1574. }
  1575. template<typename T>
  1576. auto operator == ( T ) const -> BinaryExpr<LhsT, RhsT const&> const {
  1577. static_assert(always_false<T>::value,
  1578. "chained comparisons are not supported inside assertions, "
  1579. "wrap the expression inside parentheses, or decompose it");
  1580. }
  1581. template<typename T>
  1582. auto operator != ( T ) const -> BinaryExpr<LhsT, RhsT const&> const {
  1583. static_assert(always_false<T>::value,
  1584. "chained comparisons are not supported inside assertions, "
  1585. "wrap the expression inside parentheses, or decompose it");
  1586. }
  1587. template<typename T>
  1588. auto operator > ( T ) const -> BinaryExpr<LhsT, RhsT const&> const {
  1589. static_assert(always_false<T>::value,
  1590. "chained comparisons are not supported inside assertions, "
  1591. "wrap the expression inside parentheses, or decompose it");
  1592. }
  1593. template<typename T>
  1594. auto operator < ( T ) const -> BinaryExpr<LhsT, RhsT const&> const {
  1595. static_assert(always_false<T>::value,
  1596. "chained comparisons are not supported inside assertions, "
  1597. "wrap the expression inside parentheses, or decompose it");
  1598. }
  1599. template<typename T>
  1600. auto operator >= ( T ) const -> BinaryExpr<LhsT, RhsT const&> const {
  1601. static_assert(always_false<T>::value,
  1602. "chained comparisons are not supported inside assertions, "
  1603. "wrap the expression inside parentheses, or decompose it");
  1604. }
  1605. template<typename T>
  1606. auto operator <= ( T ) const -> BinaryExpr<LhsT, RhsT const&> const {
  1607. static_assert(always_false<T>::value,
  1608. "chained comparisons are not supported inside assertions, "
  1609. "wrap the expression inside parentheses, or decompose it");
  1610. }
  1611. };
  1612. template<typename LhsT>
  1613. class UnaryExpr : public ITransientExpression {
  1614. LhsT m_lhs;
  1615. void streamReconstructedExpression( std::ostream &os ) const override {
  1616. os << Catch::Detail::stringify( m_lhs );
  1617. }
  1618. public:
  1619. explicit UnaryExpr( LhsT lhs )
  1620. : ITransientExpression{ false, static_cast<bool>(lhs) },
  1621. m_lhs( lhs )
  1622. {}
  1623. };
  1624. // Specialised comparison functions to handle equality comparisons between ints and pointers (NULL deduces as an int)
  1625. template<typename LhsT, typename RhsT>
  1626. auto compareEqual( LhsT const& lhs, RhsT const& rhs ) -> bool { return static_cast<bool>(lhs == rhs); }
  1627. template<typename T>
  1628. auto compareEqual( T* const& lhs, int rhs ) -> bool { return lhs == reinterpret_cast<void const*>( rhs ); }
  1629. template<typename T>
  1630. auto compareEqual( T* const& lhs, long rhs ) -> bool { return lhs == reinterpret_cast<void const*>( rhs ); }
  1631. template<typename T>
  1632. auto compareEqual( int lhs, T* const& rhs ) -> bool { return reinterpret_cast<void const*>( lhs ) == rhs; }
  1633. template<typename T>
  1634. auto compareEqual( long lhs, T* const& rhs ) -> bool { return reinterpret_cast<void const*>( lhs ) == rhs; }
  1635. template<typename LhsT, typename RhsT>
  1636. auto compareNotEqual( LhsT const& lhs, RhsT&& rhs ) -> bool { return static_cast<bool>(lhs != rhs); }
  1637. template<typename T>
  1638. auto compareNotEqual( T* const& lhs, int rhs ) -> bool { return lhs != reinterpret_cast<void const*>( rhs ); }
  1639. template<typename T>
  1640. auto compareNotEqual( T* const& lhs, long rhs ) -> bool { return lhs != reinterpret_cast<void const*>( rhs ); }
  1641. template<typename T>
  1642. auto compareNotEqual( int lhs, T* const& rhs ) -> bool { return reinterpret_cast<void const*>( lhs ) != rhs; }
  1643. template<typename T>
  1644. auto compareNotEqual( long lhs, T* const& rhs ) -> bool { return reinterpret_cast<void const*>( lhs ) != rhs; }
  1645. template<typename LhsT>
  1646. class ExprLhs {
  1647. LhsT m_lhs;
  1648. public:
  1649. explicit ExprLhs( LhsT lhs ) : m_lhs( lhs ) {}
  1650. template<typename RhsT>
  1651. auto operator == ( RhsT const& rhs ) -> BinaryExpr<LhsT, RhsT const&> const {
  1652. return { compareEqual( m_lhs, rhs ), m_lhs, "==", rhs };
  1653. }
  1654. auto operator == ( bool rhs ) -> BinaryExpr<LhsT, bool> const {
  1655. return { m_lhs == rhs, m_lhs, "==", rhs };
  1656. }
  1657. template<typename RhsT>
  1658. auto operator != ( RhsT const& rhs ) -> BinaryExpr<LhsT, RhsT const&> const {
  1659. return { compareNotEqual( m_lhs, rhs ), m_lhs, "!=", rhs };
  1660. }
  1661. auto operator != ( bool rhs ) -> BinaryExpr<LhsT, bool> const {
  1662. return { m_lhs != rhs, m_lhs, "!=", rhs };
  1663. }
  1664. template<typename RhsT>
  1665. auto operator > ( RhsT const& rhs ) -> BinaryExpr<LhsT, RhsT const&> const {
  1666. return { static_cast<bool>(m_lhs > rhs), m_lhs, ">", rhs };
  1667. }
  1668. template<typename RhsT>
  1669. auto operator < ( RhsT const& rhs ) -> BinaryExpr<LhsT, RhsT const&> const {
  1670. return { static_cast<bool>(m_lhs < rhs), m_lhs, "<", rhs };
  1671. }
  1672. template<typename RhsT>
  1673. auto operator >= ( RhsT const& rhs ) -> BinaryExpr<LhsT, RhsT const&> const {
  1674. return { static_cast<bool>(m_lhs >= rhs), m_lhs, ">=", rhs };
  1675. }
  1676. template<typename RhsT>
  1677. auto operator <= ( RhsT const& rhs ) -> BinaryExpr<LhsT, RhsT const&> const {
  1678. return { static_cast<bool>(m_lhs <= rhs), m_lhs, "<=", rhs };
  1679. }
  1680. template<typename RhsT>
  1681. auto operator && ( RhsT const& ) -> BinaryExpr<LhsT, RhsT const&> const {
  1682. static_assert(always_false<RhsT>::value,
  1683. "operator&& is not supported inside assertions, "
  1684. "wrap the expression inside parentheses, or decompose it");
  1685. }
  1686. template<typename RhsT>
  1687. auto operator || ( RhsT const& ) -> BinaryExpr<LhsT, RhsT const&> const {
  1688. static_assert(always_false<RhsT>::value,
  1689. "operator|| is not supported inside assertions, "
  1690. "wrap the expression inside parentheses, or decompose it");
  1691. }
  1692. auto makeUnaryExpr() const -> UnaryExpr<LhsT> {
  1693. return UnaryExpr<LhsT>{ m_lhs };
  1694. }
  1695. };
  1696. void handleExpression( ITransientExpression const& expr );
  1697. template<typename T>
  1698. void handleExpression( ExprLhs<T> const& expr ) {
  1699. handleExpression( expr.makeUnaryExpr() );
  1700. }
  1701. struct Decomposer {
  1702. template<typename T>
  1703. auto operator <= ( T const& lhs ) -> ExprLhs<T const&> {
  1704. return ExprLhs<T const&>{ lhs };
  1705. }
  1706. auto operator <=( bool value ) -> ExprLhs<bool> {
  1707. return ExprLhs<bool>{ value };
  1708. }
  1709. };
  1710. } // end namespace Catch
  1711. #ifdef _MSC_VER
  1712. #pragma warning(pop)
  1713. #endif
  1714. // end catch_decomposer.h
  1715. // start catch_interfaces_capture.h
  1716. #include <string>
  1717. namespace Catch {
  1718. class AssertionResult;
  1719. struct AssertionInfo;
  1720. struct SectionInfo;
  1721. struct SectionEndInfo;
  1722. struct MessageInfo;
  1723. struct Counts;
  1724. struct BenchmarkInfo;
  1725. struct BenchmarkStats;
  1726. struct AssertionReaction;
  1727. struct SourceLineInfo;
  1728. struct ITransientExpression;
  1729. struct IGeneratorTracker;
  1730. struct IResultCapture {
  1731. virtual ~IResultCapture();
  1732. virtual bool sectionStarted( SectionInfo const& sectionInfo,
  1733. Counts& assertions ) = 0;
  1734. virtual void sectionEnded( SectionEndInfo const& endInfo ) = 0;
  1735. virtual void sectionEndedEarly( SectionEndInfo const& endInfo ) = 0;
  1736. virtual auto acquireGeneratorTracker( SourceLineInfo const& lineInfo ) -> IGeneratorTracker& = 0;
  1737. virtual void benchmarkStarting( BenchmarkInfo const& info ) = 0;
  1738. virtual void benchmarkEnded( BenchmarkStats const& stats ) = 0;
  1739. virtual void pushScopedMessage( MessageInfo const& message ) = 0;
  1740. virtual void popScopedMessage( MessageInfo const& message ) = 0;
  1741. virtual void handleFatalErrorCondition( StringRef message ) = 0;
  1742. virtual void handleExpr
  1743. ( AssertionInfo const& info,
  1744. ITransientExpression const& expr,
  1745. AssertionReaction& reaction ) = 0;
  1746. virtual void handleMessage
  1747. ( AssertionInfo const& info,
  1748. ResultWas::OfType resultType,
  1749. StringRef const& message,
  1750. AssertionReaction& reaction ) = 0;
  1751. virtual void handleUnexpectedExceptionNotThrown
  1752. ( AssertionInfo const& info,
  1753. AssertionReaction& reaction ) = 0;
  1754. virtual void handleUnexpectedInflightException
  1755. ( AssertionInfo const& info,
  1756. std::string const& message,
  1757. AssertionReaction& reaction ) = 0;
  1758. virtual void handleIncomplete
  1759. ( AssertionInfo const& info ) = 0;
  1760. virtual void handleNonExpr
  1761. ( AssertionInfo const &info,
  1762. ResultWas::OfType resultType,
  1763. AssertionReaction &reaction ) = 0;
  1764. virtual bool lastAssertionPassed() = 0;
  1765. virtual void assertionPassed() = 0;
  1766. // Deprecated, do not use:
  1767. virtual std::string getCurrentTestName() const = 0;
  1768. virtual const AssertionResult* getLastResult() const = 0;
  1769. virtual void exceptionEarlyReported() = 0;
  1770. };
  1771. IResultCapture& getResultCapture();
  1772. }
  1773. // end catch_interfaces_capture.h
  1774. namespace Catch {
  1775. struct TestFailureException{};
  1776. struct AssertionResultData;
  1777. struct IResultCapture;
  1778. class RunContext;
  1779. class LazyExpression {
  1780. friend class AssertionHandler;
  1781. friend struct AssertionStats;
  1782. friend class RunContext;
  1783. ITransientExpression const* m_transientExpression = nullptr;
  1784. bool m_isNegated;
  1785. public:
  1786. LazyExpression( bool isNegated );
  1787. LazyExpression( LazyExpression const& other );
  1788. LazyExpression& operator = ( LazyExpression const& ) = delete;
  1789. explicit operator bool() const;
  1790. friend auto operator << ( std::ostream& os, LazyExpression const& lazyExpr ) -> std::ostream&;
  1791. };
  1792. struct AssertionReaction {
  1793. bool shouldDebugBreak = false;
  1794. bool shouldThrow = false;
  1795. };
  1796. class AssertionHandler {
  1797. AssertionInfo m_assertionInfo;
  1798. AssertionReaction m_reaction;
  1799. bool m_completed = false;
  1800. IResultCapture& m_resultCapture;
  1801. public:
  1802. AssertionHandler
  1803. ( StringRef const& macroName,
  1804. SourceLineInfo const& lineInfo,
  1805. StringRef capturedExpression,
  1806. ResultDisposition::Flags resultDisposition );
  1807. ~AssertionHandler() {
  1808. if ( !m_completed ) {
  1809. m_resultCapture.handleIncomplete( m_assertionInfo );
  1810. }
  1811. }
  1812. template<typename T>
  1813. void handleExpr( ExprLhs<T> const& expr ) {
  1814. handleExpr( expr.makeUnaryExpr() );
  1815. }
  1816. void handleExpr( ITransientExpression const& expr );
  1817. void handleMessage(ResultWas::OfType resultType, StringRef const& message);
  1818. void handleExceptionThrownAsExpected();
  1819. void handleUnexpectedExceptionNotThrown();
  1820. void handleExceptionNotThrownAsExpected();
  1821. void handleThrowingCallSkipped();
  1822. void handleUnexpectedInflightException();
  1823. void complete();
  1824. void setCompleted();
  1825. // query
  1826. auto allowThrows() const -> bool;
  1827. };
  1828. void handleExceptionMatchExpr( AssertionHandler& handler, std::string const& str, StringRef const& matcherString );
  1829. } // namespace Catch
  1830. // end catch_assertionhandler.h
  1831. // start catch_message.h
  1832. #include <string>
  1833. #include <vector>
  1834. namespace Catch {
  1835. struct MessageInfo {
  1836. MessageInfo( StringRef const& _macroName,
  1837. SourceLineInfo const& _lineInfo,
  1838. ResultWas::OfType _type );
  1839. StringRef macroName;
  1840. std::string message;
  1841. SourceLineInfo lineInfo;
  1842. ResultWas::OfType type;
  1843. unsigned int sequence;
  1844. bool operator == ( MessageInfo const& other ) const;
  1845. bool operator < ( MessageInfo const& other ) const;
  1846. private:
  1847. static unsigned int globalCount;
  1848. };
  1849. struct MessageStream {
  1850. template<typename T>
  1851. MessageStream& operator << ( T const& value ) {
  1852. m_stream << value;
  1853. return *this;
  1854. }
  1855. ReusableStringStream m_stream;
  1856. };
  1857. struct MessageBuilder : MessageStream {
  1858. MessageBuilder( StringRef const& macroName,
  1859. SourceLineInfo const& lineInfo,
  1860. ResultWas::OfType type );
  1861. template<typename T>
  1862. MessageBuilder& operator << ( T const& value ) {
  1863. m_stream << value;
  1864. return *this;
  1865. }
  1866. MessageInfo m_info;
  1867. };
  1868. class ScopedMessage {
  1869. public:
  1870. explicit ScopedMessage( MessageBuilder const& builder );
  1871. ~ScopedMessage();
  1872. MessageInfo m_info;
  1873. };
  1874. class Capturer {
  1875. std::vector<MessageInfo> m_messages;
  1876. IResultCapture& m_resultCapture = getResultCapture();
  1877. size_t m_captured = 0;
  1878. public:
  1879. Capturer( StringRef macroName, SourceLineInfo const& lineInfo, ResultWas::OfType resultType, StringRef names );
  1880. ~Capturer();
  1881. void captureValue( size_t index, std::string const& value );
  1882. template<typename T>
  1883. void captureValues( size_t index, T const& value ) {
  1884. captureValue( index, Catch::Detail::stringify( value ) );
  1885. }
  1886. template<typename T, typename... Ts>
  1887. void captureValues( size_t index, T const& value, Ts const&... values ) {
  1888. captureValue( index, Catch::Detail::stringify(value) );
  1889. captureValues( index+1, values... );
  1890. }
  1891. };
  1892. } // end namespace Catch
  1893. // end catch_message.h
  1894. #if !defined(CATCH_CONFIG_DISABLE)
  1895. #if !defined(CATCH_CONFIG_DISABLE_STRINGIFICATION)
  1896. #define CATCH_INTERNAL_STRINGIFY(...) #__VA_ARGS__
  1897. #else
  1898. #define CATCH_INTERNAL_STRINGIFY(...) "Disabled by CATCH_CONFIG_DISABLE_STRINGIFICATION"
  1899. #endif
  1900. #if defined(CATCH_CONFIG_FAST_COMPILE) || defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
  1901. ///////////////////////////////////////////////////////////////////////////////
  1902. // Another way to speed-up compilation is to omit local try-catch for REQUIRE*
  1903. // macros.
  1904. #define INTERNAL_CATCH_TRY
  1905. #define INTERNAL_CATCH_CATCH( capturer )
  1906. #else // CATCH_CONFIG_FAST_COMPILE
  1907. #define INTERNAL_CATCH_TRY try
  1908. #define INTERNAL_CATCH_CATCH( handler ) catch(...) { handler.handleUnexpectedInflightException(); }
  1909. #endif
  1910. #define INTERNAL_CATCH_REACT( handler ) handler.complete();
  1911. ///////////////////////////////////////////////////////////////////////////////
  1912. #define INTERNAL_CATCH_TEST( macroName, resultDisposition, ... ) \
  1913. do { \
  1914. Catch::AssertionHandler catchAssertionHandler( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(__VA_ARGS__), resultDisposition ); \
  1915. INTERNAL_CATCH_TRY { \
  1916. CATCH_INTERNAL_SUPPRESS_PARENTHESES_WARNINGS \
  1917. catchAssertionHandler.handleExpr( Catch::Decomposer() <= __VA_ARGS__ ); \
  1918. CATCH_INTERNAL_UNSUPPRESS_PARENTHESES_WARNINGS \
  1919. } INTERNAL_CATCH_CATCH( catchAssertionHandler ) \
  1920. INTERNAL_CATCH_REACT( catchAssertionHandler ) \
  1921. } 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
  1922. // The double negation silences MSVC's C4800 warning, the static_cast forces short-circuit evaluation if the type has overloaded &&.
  1923. ///////////////////////////////////////////////////////////////////////////////
  1924. #define INTERNAL_CATCH_IF( macroName, resultDisposition, ... ) \
  1925. INTERNAL_CATCH_TEST( macroName, resultDisposition, __VA_ARGS__ ); \
  1926. if( Catch::getResultCapture().lastAssertionPassed() )
  1927. ///////////////////////////////////////////////////////////////////////////////
  1928. #define INTERNAL_CATCH_ELSE( macroName, resultDisposition, ... ) \
  1929. INTERNAL_CATCH_TEST( macroName, resultDisposition, __VA_ARGS__ ); \
  1930. if( !Catch::getResultCapture().lastAssertionPassed() )
  1931. ///////////////////////////////////////////////////////////////////////////////
  1932. #define INTERNAL_CATCH_NO_THROW( macroName, resultDisposition, ... ) \
  1933. do { \
  1934. Catch::AssertionHandler catchAssertionHandler( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(__VA_ARGS__), resultDisposition ); \
  1935. try { \
  1936. static_cast<void>(__VA_ARGS__); \
  1937. catchAssertionHandler.handleExceptionNotThrownAsExpected(); \
  1938. } \
  1939. catch( ... ) { \
  1940. catchAssertionHandler.handleUnexpectedInflightException(); \
  1941. } \
  1942. INTERNAL_CATCH_REACT( catchAssertionHandler ) \
  1943. } while( false )
  1944. ///////////////////////////////////////////////////////////////////////////////
  1945. #define INTERNAL_CATCH_THROWS( macroName, resultDisposition, ... ) \
  1946. do { \
  1947. Catch::AssertionHandler catchAssertionHandler( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(__VA_ARGS__), resultDisposition); \
  1948. if( catchAssertionHandler.allowThrows() ) \
  1949. try { \
  1950. static_cast<void>(__VA_ARGS__); \
  1951. catchAssertionHandler.handleUnexpectedExceptionNotThrown(); \
  1952. } \
  1953. catch( ... ) { \
  1954. catchAssertionHandler.handleExceptionThrownAsExpected(); \
  1955. } \
  1956. else \
  1957. catchAssertionHandler.handleThrowingCallSkipped(); \
  1958. INTERNAL_CATCH_REACT( catchAssertionHandler ) \
  1959. } while( false )
  1960. ///////////////////////////////////////////////////////////////////////////////
  1961. #define INTERNAL_CATCH_THROWS_AS( macroName, exceptionType, resultDisposition, expr ) \
  1962. do { \
  1963. Catch::AssertionHandler catchAssertionHandler( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(expr) ", " CATCH_INTERNAL_STRINGIFY(exceptionType), resultDisposition ); \
  1964. if( catchAssertionHandler.allowThrows() ) \
  1965. try { \
  1966. static_cast<void>(expr); \
  1967. catchAssertionHandler.handleUnexpectedExceptionNotThrown(); \
  1968. } \
  1969. catch( exceptionType const& ) { \
  1970. catchAssertionHandler.handleExceptionThrownAsExpected(); \
  1971. } \
  1972. catch( ... ) { \
  1973. catchAssertionHandler.handleUnexpectedInflightException(); \
  1974. } \
  1975. else \
  1976. catchAssertionHandler.handleThrowingCallSkipped(); \
  1977. INTERNAL_CATCH_REACT( catchAssertionHandler ) \
  1978. } while( false )
  1979. ///////////////////////////////////////////////////////////////////////////////
  1980. #define INTERNAL_CATCH_MSG( macroName, messageType, resultDisposition, ... ) \
  1981. do { \
  1982. Catch::AssertionHandler catchAssertionHandler( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, Catch::StringRef(), resultDisposition ); \
  1983. catchAssertionHandler.handleMessage( messageType, ( Catch::MessageStream() << __VA_ARGS__ + ::Catch::StreamEndStop() ).m_stream.str() ); \
  1984. INTERNAL_CATCH_REACT( catchAssertionHandler ) \
  1985. } while( false )
  1986. ///////////////////////////////////////////////////////////////////////////////
  1987. #define INTERNAL_CATCH_CAPTURE( varName, macroName, ... ) \
  1988. auto varName = Catch::Capturer( macroName, CATCH_INTERNAL_LINEINFO, Catch::ResultWas::Info, #__VA_ARGS__ ); \
  1989. varName.captureValues( 0, __VA_ARGS__ )
  1990. ///////////////////////////////////////////////////////////////////////////////
  1991. #define INTERNAL_CATCH_INFO( macroName, log ) \
  1992. Catch::ScopedMessage INTERNAL_CATCH_UNIQUE_NAME( scopedMessage )( Catch::MessageBuilder( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, Catch::ResultWas::Info ) << log );
  1993. ///////////////////////////////////////////////////////////////////////////////
  1994. // Although this is matcher-based, it can be used with just a string
  1995. #define INTERNAL_CATCH_THROWS_STR_MATCHES( macroName, resultDisposition, matcher, ... ) \
  1996. do { \
  1997. Catch::AssertionHandler catchAssertionHandler( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(__VA_ARGS__) ", " CATCH_INTERNAL_STRINGIFY(matcher), resultDisposition ); \
  1998. if( catchAssertionHandler.allowThrows() ) \
  1999. try { \
  2000. static_cast<void>(__VA_ARGS__); \
  2001. catchAssertionHandler.handleUnexpectedExceptionNotThrown(); \
  2002. } \
  2003. catch( ... ) { \
  2004. Catch::handleExceptionMatchExpr( catchAssertionHandler, matcher, #matcher##_catch_sr ); \
  2005. } \
  2006. else \
  2007. catchAssertionHandler.handleThrowingCallSkipped(); \
  2008. INTERNAL_CATCH_REACT( catchAssertionHandler ) \
  2009. } while( false )
  2010. #endif // CATCH_CONFIG_DISABLE
  2011. // end catch_capture.hpp
  2012. // start catch_section.h
  2013. // start catch_section_info.h
  2014. // start catch_totals.h
  2015. #include <cstddef>
  2016. namespace Catch {
  2017. struct Counts {
  2018. Counts operator - ( Counts const& other ) const;
  2019. Counts& operator += ( Counts const& other );
  2020. std::size_t total() const;
  2021. bool allPassed() const;
  2022. bool allOk() const;
  2023. std::size_t passed = 0;
  2024. std::size_t failed = 0;
  2025. std::size_t failedButOk = 0;
  2026. };
  2027. struct Totals {
  2028. Totals operator - ( Totals const& other ) const;
  2029. Totals& operator += ( Totals const& other );
  2030. Totals delta( Totals const& prevTotals ) const;
  2031. int error = 0;
  2032. Counts assertions;
  2033. Counts testCases;
  2034. };
  2035. }
  2036. // end catch_totals.h
  2037. #include <string>
  2038. namespace Catch {
  2039. struct SectionInfo {
  2040. SectionInfo
  2041. ( SourceLineInfo const& _lineInfo,
  2042. std::string const& _name );
  2043. // Deprecated
  2044. SectionInfo
  2045. ( SourceLineInfo const& _lineInfo,
  2046. std::string const& _name,
  2047. std::string const& ) : SectionInfo( _lineInfo, _name ) {}
  2048. std::string name;
  2049. std::string description; // !Deprecated: this will always be empty
  2050. SourceLineInfo lineInfo;
  2051. };
  2052. struct SectionEndInfo {
  2053. SectionInfo sectionInfo;
  2054. Counts prevAssertions;
  2055. double durationInSeconds;
  2056. };
  2057. } // end namespace Catch
  2058. // end catch_section_info.h
  2059. // start catch_timer.h
  2060. #include <cstdint>
  2061. namespace Catch {
  2062. auto getCurrentNanosecondsSinceEpoch() -> uint64_t;
  2063. auto getEstimatedClockResolution() -> uint64_t;
  2064. class Timer {
  2065. uint64_t m_nanoseconds = 0;
  2066. public:
  2067. void start();
  2068. auto getElapsedNanoseconds() const -> uint64_t;
  2069. auto getElapsedMicroseconds() const -> uint64_t;
  2070. auto getElapsedMilliseconds() const -> unsigned int;
  2071. auto getElapsedSeconds() const -> double;
  2072. };
  2073. } // namespace Catch
  2074. // end catch_timer.h
  2075. #include <string>
  2076. namespace Catch {
  2077. class Section : NonCopyable {
  2078. public:
  2079. Section( SectionInfo const& info );
  2080. ~Section();
  2081. // This indicates whether the section should be executed or not
  2082. explicit operator bool() const;
  2083. private:
  2084. SectionInfo m_info;
  2085. std::string m_name;
  2086. Counts m_assertions;
  2087. bool m_sectionIncluded;
  2088. Timer m_timer;
  2089. };
  2090. } // end namespace Catch
  2091. #define INTERNAL_CATCH_SECTION( ... ) \
  2092. CATCH_INTERNAL_SUPPRESS_UNUSED_WARNINGS \
  2093. if( Catch::Section const& INTERNAL_CATCH_UNIQUE_NAME( catch_internal_Section ) = Catch::SectionInfo( CATCH_INTERNAL_LINEINFO, __VA_ARGS__ ) ) \
  2094. CATCH_INTERNAL_UNSUPPRESS_UNUSED_WARNINGS
  2095. #define INTERNAL_CATCH_DYNAMIC_SECTION( ... ) \
  2096. CATCH_INTERNAL_SUPPRESS_UNUSED_WARNINGS \
  2097. if( Catch::Section const& INTERNAL_CATCH_UNIQUE_NAME( catch_internal_Section ) = Catch::SectionInfo( CATCH_INTERNAL_LINEINFO, (Catch::ReusableStringStream() << __VA_ARGS__).str() ) ) \
  2098. CATCH_INTERNAL_UNSUPPRESS_UNUSED_WARNINGS
  2099. // end catch_section.h
  2100. // start catch_benchmark.h
  2101. #include <cstdint>
  2102. #include <string>
  2103. namespace Catch {
  2104. class BenchmarkLooper {
  2105. std::string m_name;
  2106. std::size_t m_count = 0;
  2107. std::size_t m_iterationsToRun = 1;
  2108. uint64_t m_resolution;
  2109. Timer m_timer;
  2110. static auto getResolution() -> uint64_t;
  2111. public:
  2112. // Keep most of this inline as it's on the code path that is being timed
  2113. BenchmarkLooper( StringRef name )
  2114. : m_name( name ),
  2115. m_resolution( getResolution() )
  2116. {
  2117. reportStart();
  2118. m_timer.start();
  2119. }
  2120. explicit operator bool() {
  2121. if( m_count < m_iterationsToRun )
  2122. return true;
  2123. return needsMoreIterations();
  2124. }
  2125. void increment() {
  2126. ++m_count;
  2127. }
  2128. void reportStart();
  2129. auto needsMoreIterations() -> bool;
  2130. };
  2131. } // end namespace Catch
  2132. #define BENCHMARK( name ) \
  2133. for( Catch::BenchmarkLooper looper( name ); looper; looper.increment() )
  2134. // end catch_benchmark.h
  2135. // start catch_interfaces_exception.h
  2136. // start catch_interfaces_registry_hub.h
  2137. #include <string>
  2138. #include <memory>
  2139. namespace Catch {
  2140. class TestCase;
  2141. struct ITestCaseRegistry;
  2142. struct IExceptionTranslatorRegistry;
  2143. struct IExceptionTranslator;
  2144. struct IReporterRegistry;
  2145. struct IReporterFactory;
  2146. struct ITagAliasRegistry;
  2147. class StartupExceptionRegistry;
  2148. using IReporterFactoryPtr = std::shared_ptr<IReporterFactory>;
  2149. struct IRegistryHub {
  2150. virtual ~IRegistryHub();
  2151. virtual IReporterRegistry const& getReporterRegistry() const = 0;
  2152. virtual ITestCaseRegistry const& getTestCaseRegistry() const = 0;
  2153. virtual ITagAliasRegistry const& getTagAliasRegistry() const = 0;
  2154. virtual IExceptionTranslatorRegistry const& getExceptionTranslatorRegistry() const = 0;
  2155. virtual StartupExceptionRegistry const& getStartupExceptionRegistry() const = 0;
  2156. };
  2157. struct IMutableRegistryHub {
  2158. virtual ~IMutableRegistryHub();
  2159. virtual void registerReporter( std::string const& name, IReporterFactoryPtr const& factory ) = 0;
  2160. virtual void registerListener( IReporterFactoryPtr const& factory ) = 0;
  2161. virtual void registerTest( TestCase const& testInfo ) = 0;
  2162. virtual void registerTranslator( const IExceptionTranslator* translator ) = 0;
  2163. virtual void registerTagAlias( std::string const& alias, std::string const& tag, SourceLineInfo const& lineInfo ) = 0;
  2164. virtual void registerStartupException() noexcept = 0;
  2165. };
  2166. IRegistryHub const& getRegistryHub();
  2167. IMutableRegistryHub& getMutableRegistryHub();
  2168. void cleanUp();
  2169. std::string translateActiveException();
  2170. }
  2171. // end catch_interfaces_registry_hub.h
  2172. #if defined(CATCH_CONFIG_DISABLE)
  2173. #define INTERNAL_CATCH_TRANSLATE_EXCEPTION_NO_REG( translatorName, signature) \
  2174. static std::string translatorName( signature )
  2175. #endif
  2176. #include <exception>
  2177. #include <string>
  2178. #include <vector>
  2179. namespace Catch {
  2180. using exceptionTranslateFunction = std::string(*)();
  2181. struct IExceptionTranslator;
  2182. using ExceptionTranslators = std::vector<std::unique_ptr<IExceptionTranslator const>>;
  2183. struct IExceptionTranslator {
  2184. virtual ~IExceptionTranslator();
  2185. virtual std::string translate( ExceptionTranslators::const_iterator it, ExceptionTranslators::const_iterator itEnd ) const = 0;
  2186. };
  2187. struct IExceptionTranslatorRegistry {
  2188. virtual ~IExceptionTranslatorRegistry();
  2189. virtual std::string translateActiveException() const = 0;
  2190. };
  2191. class ExceptionTranslatorRegistrar {
  2192. template<typename T>
  2193. class ExceptionTranslator : public IExceptionTranslator {
  2194. public:
  2195. ExceptionTranslator( std::string(*translateFunction)( T& ) )
  2196. : m_translateFunction( translateFunction )
  2197. {}
  2198. std::string translate( ExceptionTranslators::const_iterator it, ExceptionTranslators::const_iterator itEnd ) const override {
  2199. try {
  2200. if( it == itEnd )
  2201. std::rethrow_exception(std::current_exception());
  2202. else
  2203. return (*it)->translate( it+1, itEnd );
  2204. }
  2205. catch( T& ex ) {
  2206. return m_translateFunction( ex );
  2207. }
  2208. }
  2209. protected:
  2210. std::string(*m_translateFunction)( T& );
  2211. };
  2212. public:
  2213. template<typename T>
  2214. ExceptionTranslatorRegistrar( std::string(*translateFunction)( T& ) ) {
  2215. getMutableRegistryHub().registerTranslator
  2216. ( new ExceptionTranslator<T>( translateFunction ) );
  2217. }
  2218. };
  2219. }
  2220. ///////////////////////////////////////////////////////////////////////////////
  2221. #define INTERNAL_CATCH_TRANSLATE_EXCEPTION2( translatorName, signature ) \
  2222. static std::string translatorName( signature ); \
  2223. CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
  2224. namespace{ Catch::ExceptionTranslatorRegistrar INTERNAL_CATCH_UNIQUE_NAME( catch_internal_ExceptionRegistrar )( &translatorName ); } \
  2225. CATCH_INTERNAL_UNSUPPRESS_GLOBALS_WARNINGS \
  2226. static std::string translatorName( signature )
  2227. #define INTERNAL_CATCH_TRANSLATE_EXCEPTION( signature ) INTERNAL_CATCH_TRANSLATE_EXCEPTION2( INTERNAL_CATCH_UNIQUE_NAME( catch_internal_ExceptionTranslator ), signature )
  2228. // end catch_interfaces_exception.h
  2229. // start catch_approx.h
  2230. #include <type_traits>
  2231. namespace Catch {
  2232. namespace Detail {
  2233. class Approx {
  2234. private:
  2235. bool equalityComparisonImpl(double other) const;
  2236. // Validates the new margin (margin >= 0)
  2237. // out-of-line to avoid including stdexcept in the header
  2238. void setMargin(double margin);
  2239. // Validates the new epsilon (0 < epsilon < 1)
  2240. // out-of-line to avoid including stdexcept in the header
  2241. void setEpsilon(double epsilon);
  2242. public:
  2243. explicit Approx ( double value );
  2244. static Approx custom();
  2245. Approx operator-() const;
  2246. template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
  2247. Approx operator()( T const& value ) {
  2248. Approx approx( static_cast<double>(value) );
  2249. approx.m_epsilon = m_epsilon;
  2250. approx.m_margin = m_margin;
  2251. approx.m_scale = m_scale;
  2252. return approx;
  2253. }
  2254. template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
  2255. explicit Approx( T const& value ): Approx(static_cast<double>(value))
  2256. {}
  2257. template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
  2258. friend bool operator == ( const T& lhs, Approx const& rhs ) {
  2259. auto lhs_v = static_cast<double>(lhs);
  2260. return rhs.equalityComparisonImpl(lhs_v);
  2261. }
  2262. template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
  2263. friend bool operator == ( Approx const& lhs, const T& rhs ) {
  2264. return operator==( rhs, lhs );
  2265. }
  2266. template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
  2267. friend bool operator != ( T const& lhs, Approx const& rhs ) {
  2268. return !operator==( lhs, rhs );
  2269. }
  2270. template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
  2271. friend bool operator != ( Approx const& lhs, T const& rhs ) {
  2272. return !operator==( rhs, lhs );
  2273. }
  2274. template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
  2275. friend bool operator <= ( T const& lhs, Approx const& rhs ) {
  2276. return static_cast<double>(lhs) < rhs.m_value || lhs == rhs;
  2277. }
  2278. template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
  2279. friend bool operator <= ( Approx const& lhs, T const& rhs ) {
  2280. return lhs.m_value < static_cast<double>(rhs) || lhs == rhs;
  2281. }
  2282. template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
  2283. friend bool operator >= ( T const& lhs, Approx const& rhs ) {
  2284. return static_cast<double>(lhs) > rhs.m_value || lhs == rhs;
  2285. }
  2286. template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
  2287. friend bool operator >= ( Approx const& lhs, T const& rhs ) {
  2288. return lhs.m_value > static_cast<double>(rhs) || lhs == rhs;
  2289. }
  2290. template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
  2291. Approx& epsilon( T const& newEpsilon ) {
  2292. double epsilonAsDouble = static_cast<double>(newEpsilon);
  2293. setEpsilon(epsilonAsDouble);
  2294. return *this;
  2295. }
  2296. template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
  2297. Approx& margin( T const& newMargin ) {
  2298. double marginAsDouble = static_cast<double>(newMargin);
  2299. setMargin(marginAsDouble);
  2300. return *this;
  2301. }
  2302. template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
  2303. Approx& scale( T const& newScale ) {
  2304. m_scale = static_cast<double>(newScale);
  2305. return *this;
  2306. }
  2307. std::string toString() const;
  2308. private:
  2309. double m_epsilon;
  2310. double m_margin;
  2311. double m_scale;
  2312. double m_value;
  2313. };
  2314. } // end namespace Detail
  2315. namespace literals {
  2316. Detail::Approx operator "" _a(long double val);
  2317. Detail::Approx operator "" _a(unsigned long long val);
  2318. } // end namespace literals
  2319. template<>
  2320. struct StringMaker<Catch::Detail::Approx> {
  2321. static std::string convert(Catch::Detail::Approx const& value);
  2322. };
  2323. } // end namespace Catch
  2324. // end catch_approx.h
  2325. // start catch_string_manip.h
  2326. #include <string>
  2327. #include <iosfwd>
  2328. namespace Catch {
  2329. bool startsWith( std::string const& s, std::string const& prefix );
  2330. bool startsWith( std::string const& s, char prefix );
  2331. bool endsWith( std::string const& s, std::string const& suffix );
  2332. bool endsWith( std::string const& s, char suffix );
  2333. bool contains( std::string const& s, std::string const& infix );
  2334. void toLowerInPlace( std::string& s );
  2335. std::string toLower( std::string const& s );
  2336. std::string trim( std::string const& str );
  2337. bool replaceInPlace( std::string& str, std::string const& replaceThis, std::string const& withThis );
  2338. struct pluralise {
  2339. pluralise( std::size_t count, std::string const& label );
  2340. friend std::ostream& operator << ( std::ostream& os, pluralise const& pluraliser );
  2341. std::size_t m_count;
  2342. std::string m_label;
  2343. };
  2344. }
  2345. // end catch_string_manip.h
  2346. #ifndef CATCH_CONFIG_DISABLE_MATCHERS
  2347. // start catch_capture_matchers.h
  2348. // start catch_matchers.h
  2349. #include <string>
  2350. #include <vector>
  2351. namespace Catch {
  2352. namespace Matchers {
  2353. namespace Impl {
  2354. template<typename ArgT> struct MatchAllOf;
  2355. template<typename ArgT> struct MatchAnyOf;
  2356. template<typename ArgT> struct MatchNotOf;
  2357. class MatcherUntypedBase {
  2358. public:
  2359. MatcherUntypedBase() = default;
  2360. MatcherUntypedBase ( MatcherUntypedBase const& ) = default;
  2361. MatcherUntypedBase& operator = ( MatcherUntypedBase const& ) = delete;
  2362. std::string toString() const;
  2363. protected:
  2364. virtual ~MatcherUntypedBase();
  2365. virtual std::string describe() const = 0;
  2366. mutable std::string m_cachedToString;
  2367. };
  2368. #ifdef __clang__
  2369. # pragma clang diagnostic push
  2370. # pragma clang diagnostic ignored "-Wnon-virtual-dtor"
  2371. #endif
  2372. template<typename ObjectT>
  2373. struct MatcherMethod {
  2374. virtual bool match( ObjectT const& arg ) const = 0;
  2375. };
  2376. #ifdef __clang__
  2377. # pragma clang diagnostic pop
  2378. #endif
  2379. template<typename T>
  2380. struct MatcherBase : MatcherUntypedBase, MatcherMethod<T> {
  2381. MatchAllOf<T> operator && ( MatcherBase const& other ) const;
  2382. MatchAnyOf<T> operator || ( MatcherBase const& other ) const;
  2383. MatchNotOf<T> operator ! () const;
  2384. };
  2385. template<typename ArgT>
  2386. struct MatchAllOf : MatcherBase<ArgT> {
  2387. bool match( ArgT const& arg ) const override {
  2388. for( auto matcher : m_matchers ) {
  2389. if (!matcher->match(arg))
  2390. return false;
  2391. }
  2392. return true;
  2393. }
  2394. std::string describe() const override {
  2395. std::string description;
  2396. description.reserve( 4 + m_matchers.size()*32 );
  2397. description += "( ";
  2398. bool first = true;
  2399. for( auto matcher : m_matchers ) {
  2400. if( first )
  2401. first = false;
  2402. else
  2403. description += " and ";
  2404. description += matcher->toString();
  2405. }
  2406. description += " )";
  2407. return description;
  2408. }
  2409. MatchAllOf<ArgT>& operator && ( MatcherBase<ArgT> const& other ) {
  2410. m_matchers.push_back( &other );
  2411. return *this;
  2412. }
  2413. std::vector<MatcherBase<ArgT> const*> m_matchers;
  2414. };
  2415. template<typename ArgT>
  2416. struct MatchAnyOf : MatcherBase<ArgT> {
  2417. bool match( ArgT const& arg ) const override {
  2418. for( auto matcher : m_matchers ) {
  2419. if (matcher->match(arg))
  2420. return true;
  2421. }
  2422. return false;
  2423. }
  2424. std::string describe() const override {
  2425. std::string description;
  2426. description.reserve( 4 + m_matchers.size()*32 );
  2427. description += "( ";
  2428. bool first = true;
  2429. for( auto matcher : m_matchers ) {
  2430. if( first )
  2431. first = false;
  2432. else
  2433. description += " or ";
  2434. description += matcher->toString();
  2435. }
  2436. description += " )";
  2437. return description;
  2438. }
  2439. MatchAnyOf<ArgT>& operator || ( MatcherBase<ArgT> const& other ) {
  2440. m_matchers.push_back( &other );
  2441. return *this;
  2442. }
  2443. std::vector<MatcherBase<ArgT> const*> m_matchers;
  2444. };
  2445. template<typename ArgT>
  2446. struct MatchNotOf : MatcherBase<ArgT> {
  2447. MatchNotOf( MatcherBase<ArgT> const& underlyingMatcher ) : m_underlyingMatcher( underlyingMatcher ) {}
  2448. bool match( ArgT const& arg ) const override {
  2449. return !m_underlyingMatcher.match( arg );
  2450. }
  2451. std::string describe() const override {
  2452. return "not " + m_underlyingMatcher.toString();
  2453. }
  2454. MatcherBase<ArgT> const& m_underlyingMatcher;
  2455. };
  2456. template<typename T>
  2457. MatchAllOf<T> MatcherBase<T>::operator && ( MatcherBase const& other ) const {
  2458. return MatchAllOf<T>() && *this && other;
  2459. }
  2460. template<typename T>
  2461. MatchAnyOf<T> MatcherBase<T>::operator || ( MatcherBase const& other ) const {
  2462. return MatchAnyOf<T>() || *this || other;
  2463. }
  2464. template<typename T>
  2465. MatchNotOf<T> MatcherBase<T>::operator ! () const {
  2466. return MatchNotOf<T>( *this );
  2467. }
  2468. } // namespace Impl
  2469. } // namespace Matchers
  2470. using namespace Matchers;
  2471. using Matchers::Impl::MatcherBase;
  2472. } // namespace Catch
  2473. // end catch_matchers.h
  2474. // start catch_matchers_floating.h
  2475. #include <type_traits>
  2476. #include <cmath>
  2477. namespace Catch {
  2478. namespace Matchers {
  2479. namespace Floating {
  2480. enum class FloatingPointKind : uint8_t;
  2481. struct WithinAbsMatcher : MatcherBase<double> {
  2482. WithinAbsMatcher(double target, double margin);
  2483. bool match(double const& matchee) const override;
  2484. std::string describe() const override;
  2485. private:
  2486. double m_target;
  2487. double m_margin;
  2488. };
  2489. struct WithinUlpsMatcher : MatcherBase<double> {
  2490. WithinUlpsMatcher(double target, int ulps, FloatingPointKind baseType);
  2491. bool match(double const& matchee) const override;
  2492. std::string describe() const override;
  2493. private:
  2494. double m_target;
  2495. int m_ulps;
  2496. FloatingPointKind m_type;
  2497. };
  2498. } // namespace Floating
  2499. // The following functions create the actual matcher objects.
  2500. // This allows the types to be inferred
  2501. Floating::WithinUlpsMatcher WithinULP(double target, int maxUlpDiff);
  2502. Floating::WithinUlpsMatcher WithinULP(float target, int maxUlpDiff);
  2503. Floating::WithinAbsMatcher WithinAbs(double target, double margin);
  2504. } // namespace Matchers
  2505. } // namespace Catch
  2506. // end catch_matchers_floating.h
  2507. // start catch_matchers_generic.hpp
  2508. #include <functional>
  2509. #include <string>
  2510. namespace Catch {
  2511. namespace Matchers {
  2512. namespace Generic {
  2513. namespace Detail {
  2514. std::string finalizeDescription(const std::string& desc);
  2515. }
  2516. template <typename T>
  2517. class PredicateMatcher : public MatcherBase<T> {
  2518. std::function<bool(T const&)> m_predicate;
  2519. std::string m_description;
  2520. public:
  2521. PredicateMatcher(std::function<bool(T const&)> const& elem, std::string const& descr)
  2522. :m_predicate(std::move(elem)),
  2523. m_description(Detail::finalizeDescription(descr))
  2524. {}
  2525. bool match( T const& item ) const override {
  2526. return m_predicate(item);
  2527. }
  2528. std::string describe() const override {
  2529. return m_description;
  2530. }
  2531. };
  2532. } // namespace Generic
  2533. // The following functions create the actual matcher objects.
  2534. // The user has to explicitly specify type to the function, because
  2535. // infering std::function<bool(T const&)> is hard (but possible) and
  2536. // requires a lot of TMP.
  2537. template<typename T>
  2538. Generic::PredicateMatcher<T> Predicate(std::function<bool(T const&)> const& predicate, std::string const& description = "") {
  2539. return Generic::PredicateMatcher<T>(predicate, description);
  2540. }
  2541. } // namespace Matchers
  2542. } // namespace Catch
  2543. // end catch_matchers_generic.hpp
  2544. // start catch_matchers_string.h
  2545. #include <string>
  2546. namespace Catch {
  2547. namespace Matchers {
  2548. namespace StdString {
  2549. struct CasedString
  2550. {
  2551. CasedString( std::string const& str, CaseSensitive::Choice caseSensitivity );
  2552. std::string adjustString( std::string const& str ) const;
  2553. std::string caseSensitivitySuffix() const;
  2554. CaseSensitive::Choice m_caseSensitivity;
  2555. std::string m_str;
  2556. };
  2557. struct StringMatcherBase : MatcherBase<std::string> {
  2558. StringMatcherBase( std::string const& operation, CasedString const& comparator );
  2559. std::string describe() const override;
  2560. CasedString m_comparator;
  2561. std::string m_operation;
  2562. };
  2563. struct EqualsMatcher : StringMatcherBase {
  2564. EqualsMatcher( CasedString const& comparator );
  2565. bool match( std::string const& source ) const override;
  2566. };
  2567. struct ContainsMatcher : StringMatcherBase {
  2568. ContainsMatcher( CasedString const& comparator );
  2569. bool match( std::string const& source ) const override;
  2570. };
  2571. struct StartsWithMatcher : StringMatcherBase {
  2572. StartsWithMatcher( CasedString const& comparator );
  2573. bool match( std::string const& source ) const override;
  2574. };
  2575. struct EndsWithMatcher : StringMatcherBase {
  2576. EndsWithMatcher( CasedString const& comparator );
  2577. bool match( std::string const& source ) const override;
  2578. };
  2579. struct RegexMatcher : MatcherBase<std::string> {
  2580. RegexMatcher( std::string regex, CaseSensitive::Choice caseSensitivity );
  2581. bool match( std::string const& matchee ) const override;
  2582. std::string describe() const override;
  2583. private:
  2584. std::string m_regex;
  2585. CaseSensitive::Choice m_caseSensitivity;
  2586. };
  2587. } // namespace StdString
  2588. // The following functions create the actual matcher objects.
  2589. // This allows the types to be inferred
  2590. StdString::EqualsMatcher Equals( std::string const& str, CaseSensitive::Choice caseSensitivity = CaseSensitive::Yes );
  2591. StdString::ContainsMatcher Contains( std::string const& str, CaseSensitive::Choice caseSensitivity = CaseSensitive::Yes );
  2592. StdString::EndsWithMatcher EndsWith( std::string const& str, CaseSensitive::Choice caseSensitivity = CaseSensitive::Yes );
  2593. StdString::StartsWithMatcher StartsWith( std::string const& str, CaseSensitive::Choice caseSensitivity = CaseSensitive::Yes );
  2594. StdString::RegexMatcher Matches( std::string const& regex, CaseSensitive::Choice caseSensitivity = CaseSensitive::Yes );
  2595. } // namespace Matchers
  2596. } // namespace Catch
  2597. // end catch_matchers_string.h
  2598. // start catch_matchers_vector.h
  2599. #include <algorithm>
  2600. namespace Catch {
  2601. namespace Matchers {
  2602. namespace Vector {
  2603. namespace Detail {
  2604. template <typename InputIterator, typename T>
  2605. size_t count(InputIterator first, InputIterator last, T const& item) {
  2606. size_t cnt = 0;
  2607. for (; first != last; ++first) {
  2608. if (*first == item) {
  2609. ++cnt;
  2610. }
  2611. }
  2612. return cnt;
  2613. }
  2614. template <typename InputIterator, typename T>
  2615. bool contains(InputIterator first, InputIterator last, T const& item) {
  2616. for (; first != last; ++first) {
  2617. if (*first == item) {
  2618. return true;
  2619. }
  2620. }
  2621. return false;
  2622. }
  2623. }
  2624. template<typename T>
  2625. struct ContainsElementMatcher : MatcherBase<std::vector<T>> {
  2626. ContainsElementMatcher(T const &comparator) : m_comparator( comparator) {}
  2627. bool match(std::vector<T> const &v) const override {
  2628. for (auto const& el : v) {
  2629. if (el == m_comparator) {
  2630. return true;
  2631. }
  2632. }
  2633. return false;
  2634. }
  2635. std::string describe() const override {
  2636. return "Contains: " + ::Catch::Detail::stringify( m_comparator );
  2637. }
  2638. T const& m_comparator;
  2639. };
  2640. template<typename T>
  2641. struct ContainsMatcher : MatcherBase<std::vector<T>> {
  2642. ContainsMatcher(std::vector<T> const &comparator) : m_comparator( comparator ) {}
  2643. bool match(std::vector<T> const &v) const override {
  2644. // !TBD: see note in EqualsMatcher
  2645. if (m_comparator.size() > v.size())
  2646. return false;
  2647. for (auto const& comparator : m_comparator) {
  2648. auto present = false;
  2649. for (const auto& el : v) {
  2650. if (el == comparator) {
  2651. present = true;
  2652. break;
  2653. }
  2654. }
  2655. if (!present) {
  2656. return false;
  2657. }
  2658. }
  2659. return true;
  2660. }
  2661. std::string describe() const override {
  2662. return "Contains: " + ::Catch::Detail::stringify( m_comparator );
  2663. }
  2664. std::vector<T> const& m_comparator;
  2665. };
  2666. template<typename T>
  2667. struct EqualsMatcher : MatcherBase<std::vector<T>> {
  2668. EqualsMatcher(std::vector<T> const &comparator) : m_comparator( comparator ) {}
  2669. bool match(std::vector<T> const &v) const override {
  2670. // !TBD: This currently works if all elements can be compared using !=
  2671. // - a more general approach would be via a compare template that defaults
  2672. // to using !=. but could be specialised for, e.g. std::vector<T> etc
  2673. // - then just call that directly
  2674. if (m_comparator.size() != v.size())
  2675. return false;
  2676. for (std::size_t i = 0; i < v.size(); ++i)
  2677. if (m_comparator[i] != v[i])
  2678. return false;
  2679. return true;
  2680. }
  2681. std::string describe() const override {
  2682. return "Equals: " + ::Catch::Detail::stringify( m_comparator );
  2683. }
  2684. std::vector<T> const& m_comparator;
  2685. };
  2686. template<typename T>
  2687. struct UnorderedEqualsMatcher : MatcherBase<std::vector<T>> {
  2688. UnorderedEqualsMatcher(std::vector<T> const& target) : m_target(target) {}
  2689. bool match(std::vector<T> const& vec) const override {
  2690. // Note: This is a reimplementation of std::is_permutation,
  2691. // because I don't want to include <algorithm> inside the common path
  2692. if (m_target.size() != vec.size()) {
  2693. return false;
  2694. }
  2695. auto lfirst = m_target.begin(), llast = m_target.end();
  2696. auto rfirst = vec.begin(), rlast = vec.end();
  2697. // Cut common prefix to optimize checking of permuted parts
  2698. while (lfirst != llast && *lfirst == *rfirst) {
  2699. ++lfirst; ++rfirst;
  2700. }
  2701. if (lfirst == llast) {
  2702. return true;
  2703. }
  2704. for (auto mid = lfirst; mid != llast; ++mid) {
  2705. // Skip already counted items
  2706. if (Detail::contains(lfirst, mid, *mid)) {
  2707. continue;
  2708. }
  2709. size_t num_vec = Detail::count(rfirst, rlast, *mid);
  2710. if (num_vec == 0 || Detail::count(lfirst, llast, *mid) != num_vec) {
  2711. return false;
  2712. }
  2713. }
  2714. return true;
  2715. }
  2716. std::string describe() const override {
  2717. return "UnorderedEquals: " + ::Catch::Detail::stringify(m_target);
  2718. }
  2719. private:
  2720. std::vector<T> const& m_target;
  2721. };
  2722. } // namespace Vector
  2723. // The following functions create the actual matcher objects.
  2724. // This allows the types to be inferred
  2725. template<typename T>
  2726. Vector::ContainsMatcher<T> Contains( std::vector<T> const& comparator ) {
  2727. return Vector::ContainsMatcher<T>( comparator );
  2728. }
  2729. template<typename T>
  2730. Vector::ContainsElementMatcher<T> VectorContains( T const& comparator ) {
  2731. return Vector::ContainsElementMatcher<T>( comparator );
  2732. }
  2733. template<typename T>
  2734. Vector::EqualsMatcher<T> Equals( std::vector<T> const& comparator ) {
  2735. return Vector::EqualsMatcher<T>( comparator );
  2736. }
  2737. template<typename T>
  2738. Vector::UnorderedEqualsMatcher<T> UnorderedEquals(std::vector<T> const& target) {
  2739. return Vector::UnorderedEqualsMatcher<T>(target);
  2740. }
  2741. } // namespace Matchers
  2742. } // namespace Catch
  2743. // end catch_matchers_vector.h
  2744. namespace Catch {
  2745. template<typename ArgT, typename MatcherT>
  2746. class MatchExpr : public ITransientExpression {
  2747. ArgT const& m_arg;
  2748. MatcherT m_matcher;
  2749. StringRef m_matcherString;
  2750. public:
  2751. MatchExpr( ArgT const& arg, MatcherT const& matcher, StringRef const& matcherString )
  2752. : ITransientExpression{ true, matcher.match( arg ) },
  2753. m_arg( arg ),
  2754. m_matcher( matcher ),
  2755. m_matcherString( matcherString )
  2756. {}
  2757. void streamReconstructedExpression( std::ostream &os ) const override {
  2758. auto matcherAsString = m_matcher.toString();
  2759. os << Catch::Detail::stringify( m_arg ) << ' ';
  2760. if( matcherAsString == Detail::unprintableString )
  2761. os << m_matcherString;
  2762. else
  2763. os << matcherAsString;
  2764. }
  2765. };
  2766. using StringMatcher = Matchers::Impl::MatcherBase<std::string>;
  2767. void handleExceptionMatchExpr( AssertionHandler& handler, StringMatcher const& matcher, StringRef const& matcherString );
  2768. template<typename ArgT, typename MatcherT>
  2769. auto makeMatchExpr( ArgT const& arg, MatcherT const& matcher, StringRef const& matcherString ) -> MatchExpr<ArgT, MatcherT> {
  2770. return MatchExpr<ArgT, MatcherT>( arg, matcher, matcherString );
  2771. }
  2772. } // namespace Catch
  2773. ///////////////////////////////////////////////////////////////////////////////
  2774. #define INTERNAL_CHECK_THAT( macroName, matcher, resultDisposition, arg ) \
  2775. do { \
  2776. Catch::AssertionHandler catchAssertionHandler( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(arg) ", " CATCH_INTERNAL_STRINGIFY(matcher), resultDisposition ); \
  2777. INTERNAL_CATCH_TRY { \
  2778. catchAssertionHandler.handleExpr( Catch::makeMatchExpr( arg, matcher, #matcher##_catch_sr ) ); \
  2779. } INTERNAL_CATCH_CATCH( catchAssertionHandler ) \
  2780. INTERNAL_CATCH_REACT( catchAssertionHandler ) \
  2781. } while( false )
  2782. ///////////////////////////////////////////////////////////////////////////////
  2783. #define INTERNAL_CATCH_THROWS_MATCHES( macroName, exceptionType, resultDisposition, matcher, ... ) \
  2784. do { \
  2785. Catch::AssertionHandler catchAssertionHandler( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(__VA_ARGS__) ", " CATCH_INTERNAL_STRINGIFY(exceptionType) ", " CATCH_INTERNAL_STRINGIFY(matcher), resultDisposition ); \
  2786. if( catchAssertionHandler.allowThrows() ) \
  2787. try { \
  2788. static_cast<void>(__VA_ARGS__ ); \
  2789. catchAssertionHandler.handleUnexpectedExceptionNotThrown(); \
  2790. } \
  2791. catch( exceptionType const& ex ) { \
  2792. catchAssertionHandler.handleExpr( Catch::makeMatchExpr( ex, matcher, #matcher##_catch_sr ) ); \
  2793. } \
  2794. catch( ... ) { \
  2795. catchAssertionHandler.handleUnexpectedInflightException(); \
  2796. } \
  2797. else \
  2798. catchAssertionHandler.handleThrowingCallSkipped(); \
  2799. INTERNAL_CATCH_REACT( catchAssertionHandler ) \
  2800. } while( false )
  2801. // end catch_capture_matchers.h
  2802. #endif
  2803. // start catch_generators.hpp
  2804. // start catch_interfaces_generatortracker.h
  2805. #include <memory>
  2806. namespace Catch {
  2807. namespace Generators {
  2808. class GeneratorUntypedBase {
  2809. public:
  2810. GeneratorUntypedBase() = default;
  2811. virtual ~GeneratorUntypedBase();
  2812. // Attempts to move the generator to the next element
  2813. //
  2814. // Returns true iff the move succeeded (and a valid element
  2815. // can be retrieved).
  2816. virtual bool next() = 0;
  2817. };
  2818. using GeneratorBasePtr = std::unique_ptr<GeneratorUntypedBase>;
  2819. } // namespace Generators
  2820. struct IGeneratorTracker {
  2821. virtual ~IGeneratorTracker();
  2822. virtual auto hasGenerator() const -> bool = 0;
  2823. virtual auto getGenerator() const -> Generators::GeneratorBasePtr const& = 0;
  2824. virtual void setGenerator( Generators::GeneratorBasePtr&& generator ) = 0;
  2825. };
  2826. } // namespace Catch
  2827. // end catch_interfaces_generatortracker.h
  2828. // start catch_enforce.h
  2829. #include <stdexcept>
  2830. namespace Catch {
  2831. #if !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
  2832. template <typename Ex>
  2833. [[noreturn]]
  2834. void throw_exception(Ex const& e) {
  2835. throw e;
  2836. }
  2837. #else // ^^ Exceptions are enabled // Exceptions are disabled vv
  2838. [[noreturn]]
  2839. void throw_exception(std::exception const& e);
  2840. #endif
  2841. } // namespace Catch;
  2842. #define CATCH_PREPARE_EXCEPTION( type, msg ) \
  2843. type( ( Catch::ReusableStringStream() << msg ).str() )
  2844. #define CATCH_INTERNAL_ERROR( msg ) \
  2845. Catch::throw_exception(CATCH_PREPARE_EXCEPTION( std::logic_error, CATCH_INTERNAL_LINEINFO << ": Internal Catch error: " << msg))
  2846. #define CATCH_ERROR( msg ) \
  2847. Catch::throw_exception(CATCH_PREPARE_EXCEPTION( std::domain_error, msg ))
  2848. #define CATCH_RUNTIME_ERROR( msg ) \
  2849. Catch::throw_exception(CATCH_PREPARE_EXCEPTION( std::runtime_error, msg ))
  2850. #define CATCH_ENFORCE( condition, msg ) \
  2851. do{ if( !(condition) ) CATCH_ERROR( msg ); } while(false)
  2852. // end catch_enforce.h
  2853. #include <memory>
  2854. #include <vector>
  2855. #include <cassert>
  2856. #include <utility>
  2857. #include <exception>
  2858. namespace Catch {
  2859. class GeneratorException : public std::exception {
  2860. const char* const m_msg = "";
  2861. public:
  2862. GeneratorException(const char* msg):
  2863. m_msg(msg)
  2864. {}
  2865. const char* what() const noexcept override final;
  2866. };
  2867. namespace Generators {
  2868. // !TBD move this into its own location?
  2869. namespace pf{
  2870. template<typename T, typename... Args>
  2871. std::unique_ptr<T> make_unique( Args&&... args ) {
  2872. return std::unique_ptr<T>(new T(std::forward<Args>(args)...));
  2873. }
  2874. }
  2875. template<typename T>
  2876. struct IGenerator : GeneratorUntypedBase {
  2877. virtual ~IGenerator() = default;
  2878. // Returns the current element of the generator
  2879. //
  2880. // \Precondition The generator is either freshly constructed,
  2881. // or the last call to `next()` returned true
  2882. virtual T const& get() const = 0;
  2883. using type = T;
  2884. };
  2885. template<typename T>
  2886. class SingleValueGenerator final : public IGenerator<T> {
  2887. T m_value;
  2888. public:
  2889. SingleValueGenerator(T const& value) : m_value( value ) {}
  2890. SingleValueGenerator(T&& value) : m_value(std::move(value)) {}
  2891. T const& get() const override {
  2892. return m_value;
  2893. }
  2894. bool next() override {
  2895. return false;
  2896. }
  2897. };
  2898. template<typename T>
  2899. class FixedValuesGenerator final : public IGenerator<T> {
  2900. std::vector<T> m_values;
  2901. size_t m_idx = 0;
  2902. public:
  2903. FixedValuesGenerator( std::initializer_list<T> values ) : m_values( values ) {}
  2904. T const& get() const override {
  2905. return m_values[m_idx];
  2906. }
  2907. bool next() override {
  2908. ++m_idx;
  2909. return m_idx < m_values.size();
  2910. }
  2911. };
  2912. template <typename T>
  2913. class GeneratorWrapper final {
  2914. std::unique_ptr<IGenerator<T>> m_generator;
  2915. public:
  2916. GeneratorWrapper(std::unique_ptr<IGenerator<T>> generator):
  2917. m_generator(std::move(generator))
  2918. {}
  2919. T const& get() const {
  2920. return m_generator->get();
  2921. }
  2922. bool next() {
  2923. return m_generator->next();
  2924. }
  2925. };
  2926. template <typename T>
  2927. GeneratorWrapper<T> value(T&& value) {
  2928. return GeneratorWrapper<T>(pf::make_unique<SingleValueGenerator<T>>(std::forward<T>(value)));
  2929. }
  2930. template <typename T>
  2931. GeneratorWrapper<T> values(std::initializer_list<T> values) {
  2932. return GeneratorWrapper<T>(pf::make_unique<FixedValuesGenerator<T>>(values));
  2933. }
  2934. template<typename T>
  2935. class Generators : public IGenerator<T> {
  2936. std::vector<GeneratorWrapper<T>> m_generators;
  2937. size_t m_current = 0;
  2938. void populate(GeneratorWrapper<T>&& generator) {
  2939. m_generators.emplace_back(std::move(generator));
  2940. }
  2941. void populate(T&& val) {
  2942. m_generators.emplace_back(value(std::move(val)));
  2943. }
  2944. template<typename U>
  2945. void populate(U&& val) {
  2946. populate(T(std::move(val)));
  2947. }
  2948. template<typename U, typename... Gs>
  2949. void populate(U&& valueOrGenerator, Gs... moreGenerators) {
  2950. populate(std::forward<U>(valueOrGenerator));
  2951. populate(std::forward<Gs>(moreGenerators)...);
  2952. }
  2953. public:
  2954. template <typename... Gs>
  2955. Generators(Gs... moreGenerators) {
  2956. m_generators.reserve(sizeof...(Gs));
  2957. populate(std::forward<Gs>(moreGenerators)...);
  2958. }
  2959. T const& get() const override {
  2960. return m_generators[m_current].get();
  2961. }
  2962. bool next() override {
  2963. if (m_current >= m_generators.size()) {
  2964. return false;
  2965. }
  2966. const bool current_status = m_generators[m_current].next();
  2967. if (!current_status) {
  2968. ++m_current;
  2969. }
  2970. return m_current < m_generators.size();
  2971. }
  2972. };
  2973. template<typename... Ts>
  2974. GeneratorWrapper<std::tuple<Ts...>> table( std::initializer_list<std::tuple<typename std::decay<Ts>::type...>> tuples ) {
  2975. return values<std::tuple<Ts...>>( tuples );
  2976. }
  2977. // Tag type to signal that a generator sequence should convert arguments to a specific type
  2978. template <typename T>
  2979. struct as {};
  2980. template<typename T, typename... Gs>
  2981. auto makeGenerators( GeneratorWrapper<T>&& generator, Gs... moreGenerators ) -> Generators<T> {
  2982. return Generators<T>(std::move(generator), std::forward<Gs>(moreGenerators)...);
  2983. }
  2984. template<typename T>
  2985. auto makeGenerators( GeneratorWrapper<T>&& generator ) -> Generators<T> {
  2986. return Generators<T>(std::move(generator));
  2987. }
  2988. template<typename T, typename... Gs>
  2989. auto makeGenerators( T&& val, Gs... moreGenerators ) -> Generators<T> {
  2990. return makeGenerators( value( std::forward<T>( val ) ), std::forward<Gs>( moreGenerators )... );
  2991. }
  2992. template<typename T, typename U, typename... Gs>
  2993. auto makeGenerators( as<T>, U&& val, Gs... moreGenerators ) -> Generators<T> {
  2994. return makeGenerators( value( T( std::forward<U>( val ) ) ), std::forward<Gs>( moreGenerators )... );
  2995. }
  2996. template <typename T>
  2997. class TakeGenerator : public IGenerator<T> {
  2998. GeneratorWrapper<T> m_generator;
  2999. size_t m_returned = 0;
  3000. size_t m_target;
  3001. public:
  3002. TakeGenerator(size_t target, GeneratorWrapper<T>&& generator):
  3003. m_generator(std::move(generator)),
  3004. m_target(target)
  3005. {
  3006. assert(target != 0 && "Empty generators are not allowed");
  3007. }
  3008. T const& get() const override {
  3009. return m_generator.get();
  3010. }
  3011. bool next() override {
  3012. ++m_returned;
  3013. if (m_returned >= m_target) {
  3014. return false;
  3015. }
  3016. const auto success = m_generator.next();
  3017. // If the underlying generator does not contain enough values
  3018. // then we cut short as well
  3019. if (!success) {
  3020. m_returned = m_target;
  3021. }
  3022. return success;
  3023. }
  3024. };
  3025. template <typename T>
  3026. GeneratorWrapper<T> take(size_t target, GeneratorWrapper<T>&& generator) {
  3027. return GeneratorWrapper<T>(pf::make_unique<TakeGenerator<T>>(target, std::move(generator)));
  3028. }
  3029. template <typename T, typename Predicate>
  3030. class FilterGenerator : public IGenerator<T> {
  3031. GeneratorWrapper<T> m_generator;
  3032. Predicate m_predicate;
  3033. public:
  3034. template <typename P = Predicate>
  3035. FilterGenerator(P&& pred, GeneratorWrapper<T>&& generator):
  3036. m_generator(std::move(generator)),
  3037. m_predicate(std::forward<P>(pred))
  3038. {
  3039. if (!m_predicate(m_generator.get())) {
  3040. // It might happen that there are no values that pass the
  3041. // filter. In that case we throw an exception.
  3042. auto has_initial_value = next();
  3043. if (!has_initial_value) {
  3044. Catch::throw_exception(GeneratorException("No valid value found in filtered generator"));
  3045. }
  3046. }
  3047. }
  3048. T const& get() const override {
  3049. return m_generator.get();
  3050. }
  3051. bool next() override {
  3052. bool success = m_generator.next();
  3053. if (!success) {
  3054. return false;
  3055. }
  3056. while (!m_predicate(m_generator.get()) && (success = m_generator.next()) == true);
  3057. return success;
  3058. }
  3059. };
  3060. template <typename T, typename Predicate>
  3061. GeneratorWrapper<T> filter(Predicate&& pred, GeneratorWrapper<T>&& generator) {
  3062. return GeneratorWrapper<T>(std::unique_ptr<IGenerator<T>>(pf::make_unique<FilterGenerator<T, Predicate>>(std::forward<Predicate>(pred), std::move(generator))));
  3063. }
  3064. template <typename T>
  3065. class RepeatGenerator : public IGenerator<T> {
  3066. GeneratorWrapper<T> m_generator;
  3067. mutable std::vector<T> m_returned;
  3068. size_t m_target_repeats;
  3069. size_t m_current_repeat = 0;
  3070. size_t m_repeat_index = 0;
  3071. public:
  3072. RepeatGenerator(size_t repeats, GeneratorWrapper<T>&& generator):
  3073. m_generator(std::move(generator)),
  3074. m_target_repeats(repeats)
  3075. {
  3076. assert(m_target_repeats > 0 && "Repeat generator must repeat at least once");
  3077. }
  3078. T const& get() const override {
  3079. if (m_current_repeat == 0) {
  3080. m_returned.push_back(m_generator.get());
  3081. return m_returned.back();
  3082. }
  3083. return m_returned[m_repeat_index];
  3084. }
  3085. bool next() override {
  3086. // There are 2 basic cases:
  3087. // 1) We are still reading the generator
  3088. // 2) We are reading our own cache
  3089. // In the first case, we need to poke the underlying generator.
  3090. // If it happily moves, we are left in that state, otherwise it is time to start reading from our cache
  3091. if (m_current_repeat == 0) {
  3092. const auto success = m_generator.next();
  3093. if (!success) {
  3094. ++m_current_repeat;
  3095. }
  3096. return m_current_repeat < m_target_repeats;
  3097. }
  3098. // In the second case, we need to move indices forward and check that we haven't run up against the end
  3099. ++m_repeat_index;
  3100. if (m_repeat_index == m_returned.size()) {
  3101. m_repeat_index = 0;
  3102. ++m_current_repeat;
  3103. }
  3104. return m_current_repeat < m_target_repeats;
  3105. }
  3106. };
  3107. template <typename T>
  3108. GeneratorWrapper<T> repeat(size_t repeats, GeneratorWrapper<T>&& generator) {
  3109. return GeneratorWrapper<T>(pf::make_unique<RepeatGenerator<T>>(repeats, std::move(generator)));
  3110. }
  3111. template <typename T, typename U, typename Func>
  3112. class MapGenerator : public IGenerator<T> {
  3113. // TBD: provide static assert for mapping function, for friendly error message
  3114. GeneratorWrapper<U> m_generator;
  3115. Func m_function;
  3116. // To avoid returning dangling reference, we have to save the values
  3117. T m_cache;
  3118. public:
  3119. template <typename F2 = Func>
  3120. MapGenerator(F2&& function, GeneratorWrapper<U>&& generator) :
  3121. m_generator(std::move(generator)),
  3122. m_function(std::forward<F2>(function)),
  3123. m_cache(m_function(m_generator.get()))
  3124. {}
  3125. T const& get() const override {
  3126. return m_cache;
  3127. }
  3128. bool next() override {
  3129. const auto success = m_generator.next();
  3130. if (success) {
  3131. m_cache = m_function(m_generator.get());
  3132. }
  3133. return success;
  3134. }
  3135. };
  3136. template <typename T, typename U, typename Func>
  3137. GeneratorWrapper<T> map(Func&& function, GeneratorWrapper<U>&& generator) {
  3138. return GeneratorWrapper<T>(
  3139. pf::make_unique<MapGenerator<T, U, Func>>(std::forward<Func>(function), std::move(generator))
  3140. );
  3141. }
  3142. template <typename T, typename Func>
  3143. GeneratorWrapper<T> map(Func&& function, GeneratorWrapper<T>&& generator) {
  3144. return GeneratorWrapper<T>(
  3145. pf::make_unique<MapGenerator<T, T, Func>>(std::forward<Func>(function), std::move(generator))
  3146. );
  3147. }
  3148. auto acquireGeneratorTracker( SourceLineInfo const& lineInfo ) -> IGeneratorTracker&;
  3149. template<typename L>
  3150. // Note: The type after -> is weird, because VS2015 cannot parse
  3151. // the expression used in the typedef inside, when it is in
  3152. // return type. Yeah, ¯\_(ツ)_/¯
  3153. auto generate( SourceLineInfo const& lineInfo, L const& generatorExpression ) -> decltype(std::declval<decltype(generatorExpression())>().get()) {
  3154. using UnderlyingType = typename decltype(generatorExpression())::type;
  3155. IGeneratorTracker& tracker = acquireGeneratorTracker( lineInfo );
  3156. if (!tracker.hasGenerator()) {
  3157. tracker.setGenerator(pf::make_unique<Generators<UnderlyingType>>(generatorExpression()));
  3158. }
  3159. auto const& generator = static_cast<IGenerator<UnderlyingType> const&>( *tracker.getGenerator() );
  3160. return generator.get();
  3161. }
  3162. } // namespace Generators
  3163. } // namespace Catch
  3164. #define GENERATE( ... ) \
  3165. Catch::Generators::generate( CATCH_INTERNAL_LINEINFO, []{ using namespace Catch::Generators; return makeGenerators( __VA_ARGS__ ); } )
  3166. // end catch_generators.hpp
  3167. // These files are included here so the single_include script doesn't put them
  3168. // in the conditionally compiled sections
  3169. // start catch_test_case_info.h
  3170. #include <string>
  3171. #include <vector>
  3172. #include <memory>
  3173. #ifdef __clang__
  3174. #pragma clang diagnostic push
  3175. #pragma clang diagnostic ignored "-Wpadded"
  3176. #endif
  3177. namespace Catch {
  3178. struct ITestInvoker;
  3179. struct TestCaseInfo {
  3180. enum SpecialProperties{
  3181. None = 0,
  3182. IsHidden = 1 << 1,
  3183. ShouldFail = 1 << 2,
  3184. MayFail = 1 << 3,
  3185. Throws = 1 << 4,
  3186. NonPortable = 1 << 5,
  3187. Benchmark = 1 << 6
  3188. };
  3189. TestCaseInfo( std::string const& _name,
  3190. std::string const& _className,
  3191. std::string const& _description,
  3192. std::vector<std::string> const& _tags,
  3193. SourceLineInfo const& _lineInfo );
  3194. friend void setTags( TestCaseInfo& testCaseInfo, std::vector<std::string> tags );
  3195. bool isHidden() const;
  3196. bool throws() const;
  3197. bool okToFail() const;
  3198. bool expectedToFail() const;
  3199. std::string tagsAsString() const;
  3200. std::string name;
  3201. std::string className;
  3202. std::string description;
  3203. std::vector<std::string> tags;
  3204. std::vector<std::string> lcaseTags;
  3205. SourceLineInfo lineInfo;
  3206. SpecialProperties properties;
  3207. };
  3208. class TestCase : public TestCaseInfo {
  3209. public:
  3210. TestCase( ITestInvoker* testCase, TestCaseInfo&& info );
  3211. TestCase withName( std::string const& _newName ) const;
  3212. void invoke() const;
  3213. TestCaseInfo const& getTestCaseInfo() const;
  3214. bool operator == ( TestCase const& other ) const;
  3215. bool operator < ( TestCase const& other ) const;
  3216. private:
  3217. std::shared_ptr<ITestInvoker> test;
  3218. };
  3219. TestCase makeTestCase( ITestInvoker* testCase,
  3220. std::string const& className,
  3221. NameAndTags const& nameAndTags,
  3222. SourceLineInfo const& lineInfo );
  3223. }
  3224. #ifdef __clang__
  3225. #pragma clang diagnostic pop
  3226. #endif
  3227. // end catch_test_case_info.h
  3228. // start catch_interfaces_runner.h
  3229. namespace Catch {
  3230. struct IRunner {
  3231. virtual ~IRunner();
  3232. virtual bool aborting() const = 0;
  3233. };
  3234. }
  3235. // end catch_interfaces_runner.h
  3236. #ifdef __OBJC__
  3237. // start catch_objc.hpp
  3238. #import <objc/runtime.h>
  3239. #include <string>
  3240. // NB. Any general catch headers included here must be included
  3241. // in catch.hpp first to make sure they are included by the single
  3242. // header for non obj-usage
  3243. ///////////////////////////////////////////////////////////////////////////////
  3244. // This protocol is really only here for (self) documenting purposes, since
  3245. // all its methods are optional.
  3246. @protocol OcFixture
  3247. @optional
  3248. -(void) setUp;
  3249. -(void) tearDown;
  3250. @end
  3251. namespace Catch {
  3252. class OcMethod : public ITestInvoker {
  3253. public:
  3254. OcMethod( Class cls, SEL sel ) : m_cls( cls ), m_sel( sel ) {}
  3255. virtual void invoke() const {
  3256. id obj = [[m_cls alloc] init];
  3257. performOptionalSelector( obj, @selector(setUp) );
  3258. performOptionalSelector( obj, m_sel );
  3259. performOptionalSelector( obj, @selector(tearDown) );
  3260. arcSafeRelease( obj );
  3261. }
  3262. private:
  3263. virtual ~OcMethod() {}
  3264. Class m_cls;
  3265. SEL m_sel;
  3266. };
  3267. namespace Detail{
  3268. inline std::string getAnnotation( Class cls,
  3269. std::string const& annotationName,
  3270. std::string const& testCaseName ) {
  3271. NSString* selStr = [[NSString alloc] initWithFormat:@"Catch_%s_%s", annotationName.c_str(), testCaseName.c_str()];
  3272. SEL sel = NSSelectorFromString( selStr );
  3273. arcSafeRelease( selStr );
  3274. id value = performOptionalSelector( cls, sel );
  3275. if( value )
  3276. return [(NSString*)value UTF8String];
  3277. return "";
  3278. }
  3279. }
  3280. inline std::size_t registerTestMethods() {
  3281. std::size_t noTestMethods = 0;
  3282. int noClasses = objc_getClassList( nullptr, 0 );
  3283. Class* classes = (CATCH_UNSAFE_UNRETAINED Class *)malloc( sizeof(Class) * noClasses);
  3284. objc_getClassList( classes, noClasses );
  3285. for( int c = 0; c < noClasses; c++ ) {
  3286. Class cls = classes[c];
  3287. {
  3288. u_int count;
  3289. Method* methods = class_copyMethodList( cls, &count );
  3290. for( u_int m = 0; m < count ; m++ ) {
  3291. SEL selector = method_getName(methods[m]);
  3292. std::string methodName = sel_getName(selector);
  3293. if( startsWith( methodName, "Catch_TestCase_" ) ) {
  3294. std::string testCaseName = methodName.substr( 15 );
  3295. std::string name = Detail::getAnnotation( cls, "Name", testCaseName );
  3296. std::string desc = Detail::getAnnotation( cls, "Description", testCaseName );
  3297. const char* className = class_getName( cls );
  3298. getMutableRegistryHub().registerTest( makeTestCase( new OcMethod( cls, selector ), className, NameAndTags( name.c_str(), desc.c_str() ), SourceLineInfo("",0) ) );
  3299. noTestMethods++;
  3300. }
  3301. }
  3302. free(methods);
  3303. }
  3304. }
  3305. return noTestMethods;
  3306. }
  3307. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  3308. namespace Matchers {
  3309. namespace Impl {
  3310. namespace NSStringMatchers {
  3311. struct StringHolder : MatcherBase<NSString*>{
  3312. StringHolder( NSString* substr ) : m_substr( [substr copy] ){}
  3313. StringHolder( StringHolder const& other ) : m_substr( [other.m_substr copy] ){}
  3314. StringHolder() {
  3315. arcSafeRelease( m_substr );
  3316. }
  3317. bool match( NSString* arg ) const override {
  3318. return false;
  3319. }
  3320. NSString* CATCH_ARC_STRONG m_substr;
  3321. };
  3322. struct Equals : StringHolder {
  3323. Equals( NSString* substr ) : StringHolder( substr ){}
  3324. bool match( NSString* str ) const override {
  3325. return (str != nil || m_substr == nil ) &&
  3326. [str isEqualToString:m_substr];
  3327. }
  3328. std::string describe() const override {
  3329. return "equals string: " + Catch::Detail::stringify( m_substr );
  3330. }
  3331. };
  3332. struct Contains : StringHolder {
  3333. Contains( NSString* substr ) : StringHolder( substr ){}
  3334. bool match( NSString* str ) const {
  3335. return (str != nil || m_substr == nil ) &&
  3336. [str rangeOfString:m_substr].location != NSNotFound;
  3337. }
  3338. std::string describe() const override {
  3339. return "contains string: " + Catch::Detail::stringify( m_substr );
  3340. }
  3341. };
  3342. struct StartsWith : StringHolder {
  3343. StartsWith( NSString* substr ) : StringHolder( substr ){}
  3344. bool match( NSString* str ) const override {
  3345. return (str != nil || m_substr == nil ) &&
  3346. [str rangeOfString:m_substr].location == 0;
  3347. }
  3348. std::string describe() const override {
  3349. return "starts with: " + Catch::Detail::stringify( m_substr );
  3350. }
  3351. };
  3352. struct EndsWith : StringHolder {
  3353. EndsWith( NSString* substr ) : StringHolder( substr ){}
  3354. bool match( NSString* str ) const override {
  3355. return (str != nil || m_substr == nil ) &&
  3356. [str rangeOfString:m_substr].location == [str length] - [m_substr length];
  3357. }
  3358. std::string describe() const override {
  3359. return "ends with: " + Catch::Detail::stringify( m_substr );
  3360. }
  3361. };
  3362. } // namespace NSStringMatchers
  3363. } // namespace Impl
  3364. inline Impl::NSStringMatchers::Equals
  3365. Equals( NSString* substr ){ return Impl::NSStringMatchers::Equals( substr ); }
  3366. inline Impl::NSStringMatchers::Contains
  3367. Contains( NSString* substr ){ return Impl::NSStringMatchers::Contains( substr ); }
  3368. inline Impl::NSStringMatchers::StartsWith
  3369. StartsWith( NSString* substr ){ return Impl::NSStringMatchers::StartsWith( substr ); }
  3370. inline Impl::NSStringMatchers::EndsWith
  3371. EndsWith( NSString* substr ){ return Impl::NSStringMatchers::EndsWith( substr ); }
  3372. } // namespace Matchers
  3373. using namespace Matchers;
  3374. #endif // CATCH_CONFIG_DISABLE_MATCHERS
  3375. } // namespace Catch
  3376. ///////////////////////////////////////////////////////////////////////////////
  3377. #define OC_MAKE_UNIQUE_NAME( root, uniqueSuffix ) root##uniqueSuffix
  3378. #define OC_TEST_CASE2( name, desc, uniqueSuffix ) \
  3379. +(NSString*) OC_MAKE_UNIQUE_NAME( Catch_Name_test_, uniqueSuffix ) \
  3380. { \
  3381. return @ name; \
  3382. } \
  3383. +(NSString*) OC_MAKE_UNIQUE_NAME( Catch_Description_test_, uniqueSuffix ) \
  3384. { \
  3385. return @ desc; \
  3386. } \
  3387. -(void) OC_MAKE_UNIQUE_NAME( Catch_TestCase_test_, uniqueSuffix )
  3388. #define OC_TEST_CASE( name, desc ) OC_TEST_CASE2( name, desc, __LINE__ )
  3389. // end catch_objc.hpp
  3390. #endif
  3391. #ifdef CATCH_CONFIG_EXTERNAL_INTERFACES
  3392. // start catch_external_interfaces.h
  3393. // start catch_reporter_bases.hpp
  3394. // start catch_interfaces_reporter.h
  3395. // start catch_config.hpp
  3396. // start catch_test_spec_parser.h
  3397. #ifdef __clang__
  3398. #pragma clang diagnostic push
  3399. #pragma clang diagnostic ignored "-Wpadded"
  3400. #endif
  3401. // start catch_test_spec.h
  3402. #ifdef __clang__
  3403. #pragma clang diagnostic push
  3404. #pragma clang diagnostic ignored "-Wpadded"
  3405. #endif
  3406. // start catch_wildcard_pattern.h
  3407. namespace Catch
  3408. {
  3409. class WildcardPattern {
  3410. enum WildcardPosition {
  3411. NoWildcard = 0,
  3412. WildcardAtStart = 1,
  3413. WildcardAtEnd = 2,
  3414. WildcardAtBothEnds = WildcardAtStart | WildcardAtEnd
  3415. };
  3416. public:
  3417. WildcardPattern( std::string const& pattern, CaseSensitive::Choice caseSensitivity );
  3418. virtual ~WildcardPattern() = default;
  3419. virtual bool matches( std::string const& str ) const;
  3420. private:
  3421. std::string adjustCase( std::string const& str ) const;
  3422. CaseSensitive::Choice m_caseSensitivity;
  3423. WildcardPosition m_wildcard = NoWildcard;
  3424. std::string m_pattern;
  3425. };
  3426. }
  3427. // end catch_wildcard_pattern.h
  3428. #include <string>
  3429. #include <vector>
  3430. #include <memory>
  3431. namespace Catch {
  3432. class TestSpec {
  3433. struct Pattern {
  3434. virtual ~Pattern();
  3435. virtual bool matches( TestCaseInfo const& testCase ) const = 0;
  3436. };
  3437. using PatternPtr = std::shared_ptr<Pattern>;
  3438. class NamePattern : public Pattern {
  3439. public:
  3440. NamePattern( std::string const& name );
  3441. virtual ~NamePattern();
  3442. virtual bool matches( TestCaseInfo const& testCase ) const override;
  3443. private:
  3444. WildcardPattern m_wildcardPattern;
  3445. };
  3446. class TagPattern : public Pattern {
  3447. public:
  3448. TagPattern( std::string const& tag );
  3449. virtual ~TagPattern();
  3450. virtual bool matches( TestCaseInfo const& testCase ) const override;
  3451. private:
  3452. std::string m_tag;
  3453. };
  3454. class ExcludedPattern : public Pattern {
  3455. public:
  3456. ExcludedPattern( PatternPtr const& underlyingPattern );
  3457. virtual ~ExcludedPattern();
  3458. virtual bool matches( TestCaseInfo const& testCase ) const override;
  3459. private:
  3460. PatternPtr m_underlyingPattern;
  3461. };
  3462. struct Filter {
  3463. std::vector<PatternPtr> m_patterns;
  3464. bool matches( TestCaseInfo const& testCase ) const;
  3465. };
  3466. public:
  3467. bool hasFilters() const;
  3468. bool matches( TestCaseInfo const& testCase ) const;
  3469. private:
  3470. std::vector<Filter> m_filters;
  3471. friend class TestSpecParser;
  3472. };
  3473. }
  3474. #ifdef __clang__
  3475. #pragma clang diagnostic pop
  3476. #endif
  3477. // end catch_test_spec.h
  3478. // start catch_interfaces_tag_alias_registry.h
  3479. #include <string>
  3480. namespace Catch {
  3481. struct TagAlias;
  3482. struct ITagAliasRegistry {
  3483. virtual ~ITagAliasRegistry();
  3484. // Nullptr if not present
  3485. virtual TagAlias const* find( std::string const& alias ) const = 0;
  3486. virtual std::string expandAliases( std::string const& unexpandedTestSpec ) const = 0;
  3487. static ITagAliasRegistry const& get();
  3488. };
  3489. } // end namespace Catch
  3490. // end catch_interfaces_tag_alias_registry.h
  3491. namespace Catch {
  3492. class TestSpecParser {
  3493. enum Mode{ None, Name, QuotedName, Tag, EscapedName };
  3494. Mode m_mode = None;
  3495. bool m_exclusion = false;
  3496. std::size_t m_start = std::string::npos, m_pos = 0;
  3497. std::string m_arg;
  3498. std::vector<std::size_t> m_escapeChars;
  3499. TestSpec::Filter m_currentFilter;
  3500. TestSpec m_testSpec;
  3501. ITagAliasRegistry const* m_tagAliases = nullptr;
  3502. public:
  3503. TestSpecParser( ITagAliasRegistry const& tagAliases );
  3504. TestSpecParser& parse( std::string const& arg );
  3505. TestSpec testSpec();
  3506. private:
  3507. void visitChar( char c );
  3508. void startNewMode( Mode mode, std::size_t start );
  3509. void escape();
  3510. std::string subString() const;
  3511. template<typename T>
  3512. void addPattern() {
  3513. std::string token = subString();
  3514. for( std::size_t i = 0; i < m_escapeChars.size(); ++i )
  3515. token = token.substr( 0, m_escapeChars[i]-m_start-i ) + token.substr( m_escapeChars[i]-m_start-i+1 );
  3516. m_escapeChars.clear();
  3517. if( startsWith( token, "exclude:" ) ) {
  3518. m_exclusion = true;
  3519. token = token.substr( 8 );
  3520. }
  3521. if( !token.empty() ) {
  3522. TestSpec::PatternPtr pattern = std::make_shared<T>( token );
  3523. if( m_exclusion )
  3524. pattern = std::make_shared<TestSpec::ExcludedPattern>( pattern );
  3525. m_currentFilter.m_patterns.push_back( pattern );
  3526. }
  3527. m_exclusion = false;
  3528. m_mode = None;
  3529. }
  3530. void addFilter();
  3531. };
  3532. TestSpec parseTestSpec( std::string const& arg );
  3533. } // namespace Catch
  3534. #ifdef __clang__
  3535. #pragma clang diagnostic pop
  3536. #endif
  3537. // end catch_test_spec_parser.h
  3538. // start catch_interfaces_config.h
  3539. #include <iosfwd>
  3540. #include <string>
  3541. #include <vector>
  3542. #include <memory>
  3543. namespace Catch {
  3544. enum class Verbosity {
  3545. Quiet = 0,
  3546. Normal,
  3547. High
  3548. };
  3549. struct WarnAbout { enum What {
  3550. Nothing = 0x00,
  3551. NoAssertions = 0x01,
  3552. NoTests = 0x02
  3553. }; };
  3554. struct ShowDurations { enum OrNot {
  3555. DefaultForReporter,
  3556. Always,
  3557. Never
  3558. }; };
  3559. struct RunTests { enum InWhatOrder {
  3560. InDeclarationOrder,
  3561. InLexicographicalOrder,
  3562. InRandomOrder
  3563. }; };
  3564. struct UseColour { enum YesOrNo {
  3565. Auto,
  3566. Yes,
  3567. No
  3568. }; };
  3569. struct WaitForKeypress { enum When {
  3570. Never,
  3571. BeforeStart = 1,
  3572. BeforeExit = 2,
  3573. BeforeStartAndExit = BeforeStart | BeforeExit
  3574. }; };
  3575. class TestSpec;
  3576. struct IConfig : NonCopyable {
  3577. virtual ~IConfig();
  3578. virtual bool allowThrows() const = 0;
  3579. virtual std::ostream& stream() const = 0;
  3580. virtual std::string name() const = 0;
  3581. virtual bool includeSuccessfulResults() const = 0;
  3582. virtual bool shouldDebugBreak() const = 0;
  3583. virtual bool warnAboutMissingAssertions() const = 0;
  3584. virtual bool warnAboutNoTests() const = 0;
  3585. virtual int abortAfter() const = 0;
  3586. virtual bool showInvisibles() const = 0;
  3587. virtual ShowDurations::OrNot showDurations() const = 0;
  3588. virtual TestSpec const& testSpec() const = 0;
  3589. virtual bool hasTestFilters() const = 0;
  3590. virtual RunTests::InWhatOrder runOrder() const = 0;
  3591. virtual unsigned int rngSeed() const = 0;
  3592. virtual int benchmarkResolutionMultiple() const = 0;
  3593. virtual UseColour::YesOrNo useColour() const = 0;
  3594. virtual std::vector<std::string> const& getSectionsToRun() const = 0;
  3595. virtual Verbosity verbosity() const = 0;
  3596. };
  3597. using IConfigPtr = std::shared_ptr<IConfig const>;
  3598. }
  3599. // end catch_interfaces_config.h
  3600. // Libstdc++ doesn't like incomplete classes for unique_ptr
  3601. #include <memory>
  3602. #include <vector>
  3603. #include <string>
  3604. #ifndef CATCH_CONFIG_CONSOLE_WIDTH
  3605. #define CATCH_CONFIG_CONSOLE_WIDTH 80
  3606. #endif
  3607. namespace Catch {
  3608. struct IStream;
  3609. struct ConfigData {
  3610. bool listTests = false;
  3611. bool listTags = false;
  3612. bool listReporters = false;
  3613. bool listTestNamesOnly = false;
  3614. bool showSuccessfulTests = false;
  3615. bool shouldDebugBreak = false;
  3616. bool noThrow = false;
  3617. bool showHelp = false;
  3618. bool showInvisibles = false;
  3619. bool filenamesAsTags = false;
  3620. bool libIdentify = false;
  3621. int abortAfter = -1;
  3622. unsigned int rngSeed = 0;
  3623. int benchmarkResolutionMultiple = 100;
  3624. Verbosity verbosity = Verbosity::Normal;
  3625. WarnAbout::What warnings = WarnAbout::Nothing;
  3626. ShowDurations::OrNot showDurations = ShowDurations::DefaultForReporter;
  3627. RunTests::InWhatOrder runOrder = RunTests::InDeclarationOrder;
  3628. UseColour::YesOrNo useColour = UseColour::Auto;
  3629. WaitForKeypress::When waitForKeypress = WaitForKeypress::Never;
  3630. std::string outputFilename;
  3631. std::string name;
  3632. std::string processName;
  3633. #ifndef CATCH_CONFIG_DEFAULT_REPORTER
  3634. #define CATCH_CONFIG_DEFAULT_REPORTER "console"
  3635. #endif
  3636. std::string reporterName = CATCH_CONFIG_DEFAULT_REPORTER;
  3637. #undef CATCH_CONFIG_DEFAULT_REPORTER
  3638. std::vector<std::string> testsOrTags;
  3639. std::vector<std::string> sectionsToRun;
  3640. };
  3641. class Config : public IConfig {
  3642. public:
  3643. Config() = default;
  3644. Config( ConfigData const& data );
  3645. virtual ~Config() = default;
  3646. std::string const& getFilename() const;
  3647. bool listTests() const;
  3648. bool listTestNamesOnly() const;
  3649. bool listTags() const;
  3650. bool listReporters() const;
  3651. std::string getProcessName() const;
  3652. std::string const& getReporterName() const;
  3653. std::vector<std::string> const& getTestsOrTags() const;
  3654. std::vector<std::string> const& getSectionsToRun() const override;
  3655. virtual TestSpec const& testSpec() const override;
  3656. bool hasTestFilters() const override;
  3657. bool showHelp() const;
  3658. // IConfig interface
  3659. bool allowThrows() const override;
  3660. std::ostream& stream() const override;
  3661. std::string name() const override;
  3662. bool includeSuccessfulResults() const override;
  3663. bool warnAboutMissingAssertions() const override;
  3664. bool warnAboutNoTests() const override;
  3665. ShowDurations::OrNot showDurations() const override;
  3666. RunTests::InWhatOrder runOrder() const override;
  3667. unsigned int rngSeed() const override;
  3668. int benchmarkResolutionMultiple() const override;
  3669. UseColour::YesOrNo useColour() const override;
  3670. bool shouldDebugBreak() const override;
  3671. int abortAfter() const override;
  3672. bool showInvisibles() const override;
  3673. Verbosity verbosity() const override;
  3674. private:
  3675. IStream const* openStream();
  3676. ConfigData m_data;
  3677. std::unique_ptr<IStream const> m_stream;
  3678. TestSpec m_testSpec;
  3679. bool m_hasTestFilters = false;
  3680. };
  3681. } // end namespace Catch
  3682. // end catch_config.hpp
  3683. // start catch_assertionresult.h
  3684. #include <string>
  3685. namespace Catch {
  3686. struct AssertionResultData
  3687. {
  3688. AssertionResultData() = delete;
  3689. AssertionResultData( ResultWas::OfType _resultType, LazyExpression const& _lazyExpression );
  3690. std::string message;
  3691. mutable std::string reconstructedExpression;
  3692. LazyExpression lazyExpression;
  3693. ResultWas::OfType resultType;
  3694. std::string reconstructExpression() const;
  3695. };
  3696. class AssertionResult {
  3697. public:
  3698. AssertionResult() = delete;
  3699. AssertionResult( AssertionInfo const& info, AssertionResultData const& data );
  3700. bool isOk() const;
  3701. bool succeeded() const;
  3702. ResultWas::OfType getResultType() const;
  3703. bool hasExpression() const;
  3704. bool hasMessage() const;
  3705. std::string getExpression() const;
  3706. std::string getExpressionInMacro() const;
  3707. bool hasExpandedExpression() const;
  3708. std::string getExpandedExpression() const;
  3709. std::string getMessage() const;
  3710. SourceLineInfo getSourceInfo() const;
  3711. StringRef getTestMacroName() const;
  3712. //protected:
  3713. AssertionInfo m_info;
  3714. AssertionResultData m_resultData;
  3715. };
  3716. } // end namespace Catch
  3717. // end catch_assertionresult.h
  3718. // start catch_option.hpp
  3719. namespace Catch {
  3720. // An optional type
  3721. template<typename T>
  3722. class Option {
  3723. public:
  3724. Option() : nullableValue( nullptr ) {}
  3725. Option( T const& _value )
  3726. : nullableValue( new( storage ) T( _value ) )
  3727. {}
  3728. Option( Option const& _other )
  3729. : nullableValue( _other ? new( storage ) T( *_other ) : nullptr )
  3730. {}
  3731. ~Option() {
  3732. reset();
  3733. }
  3734. Option& operator= ( Option const& _other ) {
  3735. if( &_other != this ) {
  3736. reset();
  3737. if( _other )
  3738. nullableValue = new( storage ) T( *_other );
  3739. }
  3740. return *this;
  3741. }
  3742. Option& operator = ( T const& _value ) {
  3743. reset();
  3744. nullableValue = new( storage ) T( _value );
  3745. return *this;
  3746. }
  3747. void reset() {
  3748. if( nullableValue )
  3749. nullableValue->~T();
  3750. nullableValue = nullptr;
  3751. }
  3752. T& operator*() { return *nullableValue; }
  3753. T const& operator*() const { return *nullableValue; }
  3754. T* operator->() { return nullableValue; }
  3755. const T* operator->() const { return nullableValue; }
  3756. T valueOr( T const& defaultValue ) const {
  3757. return nullableValue ? *nullableValue : defaultValue;
  3758. }
  3759. bool some() const { return nullableValue != nullptr; }
  3760. bool none() const { return nullableValue == nullptr; }
  3761. bool operator !() const { return nullableValue == nullptr; }
  3762. explicit operator bool() const {
  3763. return some();
  3764. }
  3765. private:
  3766. T *nullableValue;
  3767. alignas(alignof(T)) char storage[sizeof(T)];
  3768. };
  3769. } // end namespace Catch
  3770. // end catch_option.hpp
  3771. #include <string>
  3772. #include <iosfwd>
  3773. #include <map>
  3774. #include <set>
  3775. #include <memory>
  3776. namespace Catch {
  3777. struct ReporterConfig {
  3778. explicit ReporterConfig( IConfigPtr const& _fullConfig );
  3779. ReporterConfig( IConfigPtr const& _fullConfig, std::ostream& _stream );
  3780. std::ostream& stream() const;
  3781. IConfigPtr fullConfig() const;
  3782. private:
  3783. std::ostream* m_stream;
  3784. IConfigPtr m_fullConfig;
  3785. };
  3786. struct ReporterPreferences {
  3787. bool shouldRedirectStdOut = false;
  3788. bool shouldReportAllAssertions = false;
  3789. };
  3790. template<typename T>
  3791. struct LazyStat : Option<T> {
  3792. LazyStat& operator=( T const& _value ) {
  3793. Option<T>::operator=( _value );
  3794. used = false;
  3795. return *this;
  3796. }
  3797. void reset() {
  3798. Option<T>::reset();
  3799. used = false;
  3800. }
  3801. bool used = false;
  3802. };
  3803. struct TestRunInfo {
  3804. TestRunInfo( std::string const& _name );
  3805. std::string name;
  3806. };
  3807. struct GroupInfo {
  3808. GroupInfo( std::string const& _name,
  3809. std::size_t _groupIndex,
  3810. std::size_t _groupsCount );
  3811. std::string name;
  3812. std::size_t groupIndex;
  3813. std::size_t groupsCounts;
  3814. };
  3815. struct AssertionStats {
  3816. AssertionStats( AssertionResult const& _assertionResult,
  3817. std::vector<MessageInfo> const& _infoMessages,
  3818. Totals const& _totals );
  3819. AssertionStats( AssertionStats const& ) = default;
  3820. AssertionStats( AssertionStats && ) = default;
  3821. AssertionStats& operator = ( AssertionStats const& ) = default;
  3822. AssertionStats& operator = ( AssertionStats && ) = default;
  3823. virtual ~AssertionStats();
  3824. AssertionResult assertionResult;
  3825. std::vector<MessageInfo> infoMessages;
  3826. Totals totals;
  3827. };
  3828. struct SectionStats {
  3829. SectionStats( SectionInfo const& _sectionInfo,
  3830. Counts const& _assertions,
  3831. double _durationInSeconds,
  3832. bool _missingAssertions );
  3833. SectionStats( SectionStats const& ) = default;
  3834. SectionStats( SectionStats && ) = default;
  3835. SectionStats& operator = ( SectionStats const& ) = default;
  3836. SectionStats& operator = ( SectionStats && ) = default;
  3837. virtual ~SectionStats();
  3838. SectionInfo sectionInfo;
  3839. Counts assertions;
  3840. double durationInSeconds;
  3841. bool missingAssertions;
  3842. };
  3843. struct TestCaseStats {
  3844. TestCaseStats( TestCaseInfo const& _testInfo,
  3845. Totals const& _totals,
  3846. std::string const& _stdOut,
  3847. std::string const& _stdErr,
  3848. bool _aborting );
  3849. TestCaseStats( TestCaseStats const& ) = default;
  3850. TestCaseStats( TestCaseStats && ) = default;
  3851. TestCaseStats& operator = ( TestCaseStats const& ) = default;
  3852. TestCaseStats& operator = ( TestCaseStats && ) = default;
  3853. virtual ~TestCaseStats();
  3854. TestCaseInfo testInfo;
  3855. Totals totals;
  3856. std::string stdOut;
  3857. std::string stdErr;
  3858. bool aborting;
  3859. };
  3860. struct TestGroupStats {
  3861. TestGroupStats( GroupInfo const& _groupInfo,
  3862. Totals const& _totals,
  3863. bool _aborting );
  3864. TestGroupStats( GroupInfo const& _groupInfo );
  3865. TestGroupStats( TestGroupStats const& ) = default;
  3866. TestGroupStats( TestGroupStats && ) = default;
  3867. TestGroupStats& operator = ( TestGroupStats const& ) = default;
  3868. TestGroupStats& operator = ( TestGroupStats && ) = default;
  3869. virtual ~TestGroupStats();
  3870. GroupInfo groupInfo;
  3871. Totals totals;
  3872. bool aborting;
  3873. };
  3874. struct TestRunStats {
  3875. TestRunStats( TestRunInfo const& _runInfo,
  3876. Totals const& _totals,
  3877. bool _aborting );
  3878. TestRunStats( TestRunStats const& ) = default;
  3879. TestRunStats( TestRunStats && ) = default;
  3880. TestRunStats& operator = ( TestRunStats const& ) = default;
  3881. TestRunStats& operator = ( TestRunStats && ) = default;
  3882. virtual ~TestRunStats();
  3883. TestRunInfo runInfo;
  3884. Totals totals;
  3885. bool aborting;
  3886. };
  3887. struct BenchmarkInfo {
  3888. std::string name;
  3889. };
  3890. struct BenchmarkStats {
  3891. BenchmarkInfo info;
  3892. std::size_t iterations;
  3893. uint64_t elapsedTimeInNanoseconds;
  3894. };
  3895. struct IStreamingReporter {
  3896. virtual ~IStreamingReporter() = default;
  3897. // Implementing class must also provide the following static methods:
  3898. // static std::string getDescription();
  3899. // static std::set<Verbosity> getSupportedVerbosities()
  3900. virtual ReporterPreferences getPreferences() const = 0;
  3901. virtual void noMatchingTestCases( std::string const& spec ) = 0;
  3902. virtual void testRunStarting( TestRunInfo const& testRunInfo ) = 0;
  3903. virtual void testGroupStarting( GroupInfo const& groupInfo ) = 0;
  3904. virtual void testCaseStarting( TestCaseInfo const& testInfo ) = 0;
  3905. virtual void sectionStarting( SectionInfo const& sectionInfo ) = 0;
  3906. // *** experimental ***
  3907. virtual void benchmarkStarting( BenchmarkInfo const& ) {}
  3908. virtual void assertionStarting( AssertionInfo const& assertionInfo ) = 0;
  3909. // The return value indicates if the messages buffer should be cleared:
  3910. virtual bool assertionEnded( AssertionStats const& assertionStats ) = 0;
  3911. // *** experimental ***
  3912. virtual void benchmarkEnded( BenchmarkStats const& ) {}
  3913. virtual void sectionEnded( SectionStats const& sectionStats ) = 0;
  3914. virtual void testCaseEnded( TestCaseStats const& testCaseStats ) = 0;
  3915. virtual void testGroupEnded( TestGroupStats const& testGroupStats ) = 0;
  3916. virtual void testRunEnded( TestRunStats const& testRunStats ) = 0;
  3917. virtual void skipTest( TestCaseInfo const& testInfo ) = 0;
  3918. // Default empty implementation provided
  3919. virtual void fatalErrorEncountered( StringRef name );
  3920. virtual bool isMulti() const;
  3921. };
  3922. using IStreamingReporterPtr = std::unique_ptr<IStreamingReporter>;
  3923. struct IReporterFactory {
  3924. virtual ~IReporterFactory();
  3925. virtual IStreamingReporterPtr create( ReporterConfig const& config ) const = 0;
  3926. virtual std::string getDescription() const = 0;
  3927. };
  3928. using IReporterFactoryPtr = std::shared_ptr<IReporterFactory>;
  3929. struct IReporterRegistry {
  3930. using FactoryMap = std::map<std::string, IReporterFactoryPtr>;
  3931. using Listeners = std::vector<IReporterFactoryPtr>;
  3932. virtual ~IReporterRegistry();
  3933. virtual IStreamingReporterPtr create( std::string const& name, IConfigPtr const& config ) const = 0;
  3934. virtual FactoryMap const& getFactories() const = 0;
  3935. virtual Listeners const& getListeners() const = 0;
  3936. };
  3937. } // end namespace Catch
  3938. // end catch_interfaces_reporter.h
  3939. #include <algorithm>
  3940. #include <cstring>
  3941. #include <cfloat>
  3942. #include <cstdio>
  3943. #include <cassert>
  3944. #include <memory>
  3945. #include <ostream>
  3946. namespace Catch {
  3947. void prepareExpandedExpression(AssertionResult& result);
  3948. // Returns double formatted as %.3f (format expected on output)
  3949. std::string getFormattedDuration( double duration );
  3950. template<typename DerivedT>
  3951. struct StreamingReporterBase : IStreamingReporter {
  3952. StreamingReporterBase( ReporterConfig const& _config )
  3953. : m_config( _config.fullConfig() ),
  3954. stream( _config.stream() )
  3955. {
  3956. m_reporterPrefs.shouldRedirectStdOut = false;
  3957. if( !DerivedT::getSupportedVerbosities().count( m_config->verbosity() ) )
  3958. CATCH_ERROR( "Verbosity level not supported by this reporter" );
  3959. }
  3960. ReporterPreferences getPreferences() const override {
  3961. return m_reporterPrefs;
  3962. }
  3963. static std::set<Verbosity> getSupportedVerbosities() {
  3964. return { Verbosity::Normal };
  3965. }
  3966. ~StreamingReporterBase() override = default;
  3967. void noMatchingTestCases(std::string const&) override {}
  3968. void testRunStarting(TestRunInfo const& _testRunInfo) override {
  3969. currentTestRunInfo = _testRunInfo;
  3970. }
  3971. void testGroupStarting(GroupInfo const& _groupInfo) override {
  3972. currentGroupInfo = _groupInfo;
  3973. }
  3974. void testCaseStarting(TestCaseInfo const& _testInfo) override {
  3975. currentTestCaseInfo = _testInfo;
  3976. }
  3977. void sectionStarting(SectionInfo const& _sectionInfo) override {
  3978. m_sectionStack.push_back(_sectionInfo);
  3979. }
  3980. void sectionEnded(SectionStats const& /* _sectionStats */) override {
  3981. m_sectionStack.pop_back();
  3982. }
  3983. void testCaseEnded(TestCaseStats const& /* _testCaseStats */) override {
  3984. currentTestCaseInfo.reset();
  3985. }
  3986. void testGroupEnded(TestGroupStats const& /* _testGroupStats */) override {
  3987. currentGroupInfo.reset();
  3988. }
  3989. void testRunEnded(TestRunStats const& /* _testRunStats */) override {
  3990. currentTestCaseInfo.reset();
  3991. currentGroupInfo.reset();
  3992. currentTestRunInfo.reset();
  3993. }
  3994. void skipTest(TestCaseInfo const&) override {
  3995. // Don't do anything with this by default.
  3996. // It can optionally be overridden in the derived class.
  3997. }
  3998. IConfigPtr m_config;
  3999. std::ostream& stream;
  4000. LazyStat<TestRunInfo> currentTestRunInfo;
  4001. LazyStat<GroupInfo> currentGroupInfo;
  4002. LazyStat<TestCaseInfo> currentTestCaseInfo;
  4003. std::vector<SectionInfo> m_sectionStack;
  4004. ReporterPreferences m_reporterPrefs;
  4005. };
  4006. template<typename DerivedT>
  4007. struct CumulativeReporterBase : IStreamingReporter {
  4008. template<typename T, typename ChildNodeT>
  4009. struct Node {
  4010. explicit Node( T const& _value ) : value( _value ) {}
  4011. virtual ~Node() {}
  4012. using ChildNodes = std::vector<std::shared_ptr<ChildNodeT>>;
  4013. T value;
  4014. ChildNodes children;
  4015. };
  4016. struct SectionNode {
  4017. explicit SectionNode(SectionStats const& _stats) : stats(_stats) {}
  4018. virtual ~SectionNode() = default;
  4019. bool operator == (SectionNode const& other) const {
  4020. return stats.sectionInfo.lineInfo == other.stats.sectionInfo.lineInfo;
  4021. }
  4022. bool operator == (std::shared_ptr<SectionNode> const& other) const {
  4023. return operator==(*other);
  4024. }
  4025. SectionStats stats;
  4026. using ChildSections = std::vector<std::shared_ptr<SectionNode>>;
  4027. using Assertions = std::vector<AssertionStats>;
  4028. ChildSections childSections;
  4029. Assertions assertions;
  4030. std::string stdOut;
  4031. std::string stdErr;
  4032. };
  4033. struct BySectionInfo {
  4034. BySectionInfo( SectionInfo const& other ) : m_other( other ) {}
  4035. BySectionInfo( BySectionInfo const& other ) : m_other( other.m_other ) {}
  4036. bool operator() (std::shared_ptr<SectionNode> const& node) const {
  4037. return ((node->stats.sectionInfo.name == m_other.name) &&
  4038. (node->stats.sectionInfo.lineInfo == m_other.lineInfo));
  4039. }
  4040. void operator=(BySectionInfo const&) = delete;
  4041. private:
  4042. SectionInfo const& m_other;
  4043. };
  4044. using TestCaseNode = Node<TestCaseStats, SectionNode>;
  4045. using TestGroupNode = Node<TestGroupStats, TestCaseNode>;
  4046. using TestRunNode = Node<TestRunStats, TestGroupNode>;
  4047. CumulativeReporterBase( ReporterConfig const& _config )
  4048. : m_config( _config.fullConfig() ),
  4049. stream( _config.stream() )
  4050. {
  4051. m_reporterPrefs.shouldRedirectStdOut = false;
  4052. if( !DerivedT::getSupportedVerbosities().count( m_config->verbosity() ) )
  4053. CATCH_ERROR( "Verbosity level not supported by this reporter" );
  4054. }
  4055. ~CumulativeReporterBase() override = default;
  4056. ReporterPreferences getPreferences() const override {
  4057. return m_reporterPrefs;
  4058. }
  4059. static std::set<Verbosity> getSupportedVerbosities() {
  4060. return { Verbosity::Normal };
  4061. }
  4062. void testRunStarting( TestRunInfo const& ) override {}
  4063. void testGroupStarting( GroupInfo const& ) override {}
  4064. void testCaseStarting( TestCaseInfo const& ) override {}
  4065. void sectionStarting( SectionInfo const& sectionInfo ) override {
  4066. SectionStats incompleteStats( sectionInfo, Counts(), 0, false );
  4067. std::shared_ptr<SectionNode> node;
  4068. if( m_sectionStack.empty() ) {
  4069. if( !m_rootSection )
  4070. m_rootSection = std::make_shared<SectionNode>( incompleteStats );
  4071. node = m_rootSection;
  4072. }
  4073. else {
  4074. SectionNode& parentNode = *m_sectionStack.back();
  4075. auto it =
  4076. std::find_if( parentNode.childSections.begin(),
  4077. parentNode.childSections.end(),
  4078. BySectionInfo( sectionInfo ) );
  4079. if( it == parentNode.childSections.end() ) {
  4080. node = std::make_shared<SectionNode>( incompleteStats );
  4081. parentNode.childSections.push_back( node );
  4082. }
  4083. else
  4084. node = *it;
  4085. }
  4086. m_sectionStack.push_back( node );
  4087. m_deepestSection = std::move(node);
  4088. }
  4089. void assertionStarting(AssertionInfo const&) override {}
  4090. bool assertionEnded(AssertionStats const& assertionStats) override {
  4091. assert(!m_sectionStack.empty());
  4092. // AssertionResult holds a pointer to a temporary DecomposedExpression,
  4093. // which getExpandedExpression() calls to build the expression string.
  4094. // Our section stack copy of the assertionResult will likely outlive the
  4095. // temporary, so it must be expanded or discarded now to avoid calling
  4096. // a destroyed object later.
  4097. prepareExpandedExpression(const_cast<AssertionResult&>( assertionStats.assertionResult ) );
  4098. SectionNode& sectionNode = *m_sectionStack.back();
  4099. sectionNode.assertions.push_back(assertionStats);
  4100. return true;
  4101. }
  4102. void sectionEnded(SectionStats const& sectionStats) override {
  4103. assert(!m_sectionStack.empty());
  4104. SectionNode& node = *m_sectionStack.back();
  4105. node.stats = sectionStats;
  4106. m_sectionStack.pop_back();
  4107. }
  4108. void testCaseEnded(TestCaseStats const& testCaseStats) override {
  4109. auto node = std::make_shared<TestCaseNode>(testCaseStats);
  4110. assert(m_sectionStack.size() == 0);
  4111. node->children.push_back(m_rootSection);
  4112. m_testCases.push_back(node);
  4113. m_rootSection.reset();
  4114. assert(m_deepestSection);
  4115. m_deepestSection->stdOut = testCaseStats.stdOut;
  4116. m_deepestSection->stdErr = testCaseStats.stdErr;
  4117. }
  4118. void testGroupEnded(TestGroupStats const& testGroupStats) override {
  4119. auto node = std::make_shared<TestGroupNode>(testGroupStats);
  4120. node->children.swap(m_testCases);
  4121. m_testGroups.push_back(node);
  4122. }
  4123. void testRunEnded(TestRunStats const& testRunStats) override {
  4124. auto node = std::make_shared<TestRunNode>(testRunStats);
  4125. node->children.swap(m_testGroups);
  4126. m_testRuns.push_back(node);
  4127. testRunEndedCumulative();
  4128. }
  4129. virtual void testRunEndedCumulative() = 0;
  4130. void skipTest(TestCaseInfo const&) override {}
  4131. IConfigPtr m_config;
  4132. std::ostream& stream;
  4133. std::vector<AssertionStats> m_assertions;
  4134. std::vector<std::vector<std::shared_ptr<SectionNode>>> m_sections;
  4135. std::vector<std::shared_ptr<TestCaseNode>> m_testCases;
  4136. std::vector<std::shared_ptr<TestGroupNode>> m_testGroups;
  4137. std::vector<std::shared_ptr<TestRunNode>> m_testRuns;
  4138. std::shared_ptr<SectionNode> m_rootSection;
  4139. std::shared_ptr<SectionNode> m_deepestSection;
  4140. std::vector<std::shared_ptr<SectionNode>> m_sectionStack;
  4141. ReporterPreferences m_reporterPrefs;
  4142. };
  4143. template<char C>
  4144. char const* getLineOfChars() {
  4145. static char line[CATCH_CONFIG_CONSOLE_WIDTH] = {0};
  4146. if( !*line ) {
  4147. std::memset( line, C, CATCH_CONFIG_CONSOLE_WIDTH-1 );
  4148. line[CATCH_CONFIG_CONSOLE_WIDTH-1] = 0;
  4149. }
  4150. return line;
  4151. }
  4152. struct TestEventListenerBase : StreamingReporterBase<TestEventListenerBase> {
  4153. TestEventListenerBase( ReporterConfig const& _config );
  4154. static std::set<Verbosity> getSupportedVerbosities();
  4155. void assertionStarting(AssertionInfo const&) override;
  4156. bool assertionEnded(AssertionStats const&) override;
  4157. };
  4158. } // end namespace Catch
  4159. // end catch_reporter_bases.hpp
  4160. // start catch_console_colour.h
  4161. namespace Catch {
  4162. struct Colour {
  4163. enum Code {
  4164. None = 0,
  4165. White,
  4166. Red,
  4167. Green,
  4168. Blue,
  4169. Cyan,
  4170. Yellow,
  4171. Grey,
  4172. Bright = 0x10,
  4173. BrightRed = Bright | Red,
  4174. BrightGreen = Bright | Green,
  4175. LightGrey = Bright | Grey,
  4176. BrightWhite = Bright | White,
  4177. BrightYellow = Bright | Yellow,
  4178. // By intention
  4179. FileName = LightGrey,
  4180. Warning = BrightYellow,
  4181. ResultError = BrightRed,
  4182. ResultSuccess = BrightGreen,
  4183. ResultExpectedFailure = Warning,
  4184. Error = BrightRed,
  4185. Success = Green,
  4186. OriginalExpression = Cyan,
  4187. ReconstructedExpression = BrightYellow,
  4188. SecondaryText = LightGrey,
  4189. Headers = White
  4190. };
  4191. // Use constructed object for RAII guard
  4192. Colour( Code _colourCode );
  4193. Colour( Colour&& other ) noexcept;
  4194. Colour& operator=( Colour&& other ) noexcept;
  4195. ~Colour();
  4196. // Use static method for one-shot changes
  4197. static void use( Code _colourCode );
  4198. private:
  4199. bool m_moved = false;
  4200. };
  4201. std::ostream& operator << ( std::ostream& os, Colour const& );
  4202. } // end namespace Catch
  4203. // end catch_console_colour.h
  4204. // start catch_reporter_registrars.hpp
  4205. namespace Catch {
  4206. template<typename T>
  4207. class ReporterRegistrar {
  4208. class ReporterFactory : public IReporterFactory {
  4209. virtual IStreamingReporterPtr create( ReporterConfig const& config ) const override {
  4210. return std::unique_ptr<T>( new T( config ) );
  4211. }
  4212. virtual std::string getDescription() const override {
  4213. return T::getDescription();
  4214. }
  4215. };
  4216. public:
  4217. explicit ReporterRegistrar( std::string const& name ) {
  4218. getMutableRegistryHub().registerReporter( name, std::make_shared<ReporterFactory>() );
  4219. }
  4220. };
  4221. template<typename T>
  4222. class ListenerRegistrar {
  4223. class ListenerFactory : public IReporterFactory {
  4224. virtual IStreamingReporterPtr create( ReporterConfig const& config ) const override {
  4225. return std::unique_ptr<T>( new T( config ) );
  4226. }
  4227. virtual std::string getDescription() const override {
  4228. return std::string();
  4229. }
  4230. };
  4231. public:
  4232. ListenerRegistrar() {
  4233. getMutableRegistryHub().registerListener( std::make_shared<ListenerFactory>() );
  4234. }
  4235. };
  4236. }
  4237. #if !defined(CATCH_CONFIG_DISABLE)
  4238. #define CATCH_REGISTER_REPORTER( name, reporterType ) \
  4239. CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
  4240. namespace{ Catch::ReporterRegistrar<reporterType> catch_internal_RegistrarFor##reporterType( name ); } \
  4241. CATCH_INTERNAL_UNSUPPRESS_GLOBALS_WARNINGS
  4242. #define CATCH_REGISTER_LISTENER( listenerType ) \
  4243. CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
  4244. namespace{ Catch::ListenerRegistrar<listenerType> catch_internal_RegistrarFor##listenerType; } \
  4245. CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS
  4246. #else // CATCH_CONFIG_DISABLE
  4247. #define CATCH_REGISTER_REPORTER(name, reporterType)
  4248. #define CATCH_REGISTER_LISTENER(listenerType)
  4249. #endif // CATCH_CONFIG_DISABLE
  4250. // end catch_reporter_registrars.hpp
  4251. // Allow users to base their work off existing reporters
  4252. // start catch_reporter_compact.h
  4253. namespace Catch {
  4254. struct CompactReporter : StreamingReporterBase<CompactReporter> {
  4255. using StreamingReporterBase::StreamingReporterBase;
  4256. ~CompactReporter() override;
  4257. static std::string getDescription();
  4258. ReporterPreferences getPreferences() const override;
  4259. void noMatchingTestCases(std::string const& spec) override;
  4260. void assertionStarting(AssertionInfo const&) override;
  4261. bool assertionEnded(AssertionStats const& _assertionStats) override;
  4262. void sectionEnded(SectionStats const& _sectionStats) override;
  4263. void testRunEnded(TestRunStats const& _testRunStats) override;
  4264. };
  4265. } // end namespace Catch
  4266. // end catch_reporter_compact.h
  4267. // start catch_reporter_console.h
  4268. #if defined(_MSC_VER)
  4269. #pragma warning(push)
  4270. #pragma warning(disable:4061) // Not all labels are EXPLICITLY handled in switch
  4271. // Note that 4062 (not all labels are handled
  4272. // and default is missing) is enabled
  4273. #endif
  4274. namespace Catch {
  4275. // Fwd decls
  4276. struct SummaryColumn;
  4277. class TablePrinter;
  4278. struct ConsoleReporter : StreamingReporterBase<ConsoleReporter> {
  4279. std::unique_ptr<TablePrinter> m_tablePrinter;
  4280. ConsoleReporter(ReporterConfig const& config);
  4281. ~ConsoleReporter() override;
  4282. static std::string getDescription();
  4283. void noMatchingTestCases(std::string const& spec) override;
  4284. void assertionStarting(AssertionInfo const&) override;
  4285. bool assertionEnded(AssertionStats const& _assertionStats) override;
  4286. void sectionStarting(SectionInfo const& _sectionInfo) override;
  4287. void sectionEnded(SectionStats const& _sectionStats) override;
  4288. void benchmarkStarting(BenchmarkInfo const& info) override;
  4289. void benchmarkEnded(BenchmarkStats const& stats) override;
  4290. void testCaseEnded(TestCaseStats const& _testCaseStats) override;
  4291. void testGroupEnded(TestGroupStats const& _testGroupStats) override;
  4292. void testRunEnded(TestRunStats const& _testRunStats) override;
  4293. private:
  4294. void lazyPrint();
  4295. void lazyPrintWithoutClosingBenchmarkTable();
  4296. void lazyPrintRunInfo();
  4297. void lazyPrintGroupInfo();
  4298. void printTestCaseAndSectionHeader();
  4299. void printClosedHeader(std::string const& _name);
  4300. void printOpenHeader(std::string const& _name);
  4301. // if string has a : in first line will set indent to follow it on
  4302. // subsequent lines
  4303. void printHeaderString(std::string const& _string, std::size_t indent = 0);
  4304. void printTotals(Totals const& totals);
  4305. void printSummaryRow(std::string const& label, std::vector<SummaryColumn> const& cols, std::size_t row);
  4306. void printTotalsDivider(Totals const& totals);
  4307. void printSummaryDivider();
  4308. private:
  4309. bool m_headerPrinted = false;
  4310. };
  4311. } // end namespace Catch
  4312. #if defined(_MSC_VER)
  4313. #pragma warning(pop)
  4314. #endif
  4315. // end catch_reporter_console.h
  4316. // start catch_reporter_junit.h
  4317. // start catch_xmlwriter.h
  4318. #include <vector>
  4319. namespace Catch {
  4320. class XmlEncode {
  4321. public:
  4322. enum ForWhat { ForTextNodes, ForAttributes };
  4323. XmlEncode( std::string const& str, ForWhat forWhat = ForTextNodes );
  4324. void encodeTo( std::ostream& os ) const;
  4325. friend std::ostream& operator << ( std::ostream& os, XmlEncode const& xmlEncode );
  4326. private:
  4327. std::string m_str;
  4328. ForWhat m_forWhat;
  4329. };
  4330. class XmlWriter {
  4331. public:
  4332. class ScopedElement {
  4333. public:
  4334. ScopedElement( XmlWriter* writer );
  4335. ScopedElement( ScopedElement&& other ) noexcept;
  4336. ScopedElement& operator=( ScopedElement&& other ) noexcept;
  4337. ~ScopedElement();
  4338. ScopedElement& writeText( std::string const& text, bool indent = true );
  4339. template<typename T>
  4340. ScopedElement& writeAttribute( std::string const& name, T const& attribute ) {
  4341. m_writer->writeAttribute( name, attribute );
  4342. return *this;
  4343. }
  4344. private:
  4345. mutable XmlWriter* m_writer = nullptr;
  4346. };
  4347. XmlWriter( std::ostream& os = Catch::cout() );
  4348. ~XmlWriter();
  4349. XmlWriter( XmlWriter const& ) = delete;
  4350. XmlWriter& operator=( XmlWriter const& ) = delete;
  4351. XmlWriter& startElement( std::string const& name );
  4352. ScopedElement scopedElement( std::string const& name );
  4353. XmlWriter& endElement();
  4354. XmlWriter& writeAttribute( std::string const& name, std::string const& attribute );
  4355. XmlWriter& writeAttribute( std::string const& name, bool attribute );
  4356. template<typename T>
  4357. XmlWriter& writeAttribute( std::string const& name, T const& attribute ) {
  4358. ReusableStringStream rss;
  4359. rss << attribute;
  4360. return writeAttribute( name, rss.str() );
  4361. }
  4362. XmlWriter& writeText( std::string const& text, bool indent = true );
  4363. XmlWriter& writeComment( std::string const& text );
  4364. void writeStylesheetRef( std::string const& url );
  4365. XmlWriter& writeBlankLine();
  4366. void ensureTagClosed();
  4367. private:
  4368. void writeDeclaration();
  4369. void newlineIfNecessary();
  4370. bool m_tagIsOpen = false;
  4371. bool m_needsNewline = false;
  4372. std::vector<std::string> m_tags;
  4373. std::string m_indent;
  4374. std::ostream& m_os;
  4375. };
  4376. }
  4377. // end catch_xmlwriter.h
  4378. namespace Catch {
  4379. class JunitReporter : public CumulativeReporterBase<JunitReporter> {
  4380. public:
  4381. JunitReporter(ReporterConfig const& _config);
  4382. ~JunitReporter() override;
  4383. static std::string getDescription();
  4384. void noMatchingTestCases(std::string const& /*spec*/) override;
  4385. void testRunStarting(TestRunInfo const& runInfo) override;
  4386. void testGroupStarting(GroupInfo const& groupInfo) override;
  4387. void testCaseStarting(TestCaseInfo const& testCaseInfo) override;
  4388. bool assertionEnded(AssertionStats const& assertionStats) override;
  4389. void testCaseEnded(TestCaseStats const& testCaseStats) override;
  4390. void testGroupEnded(TestGroupStats const& testGroupStats) override;
  4391. void testRunEndedCumulative() override;
  4392. void writeGroup(TestGroupNode const& groupNode, double suiteTime);
  4393. void writeTestCase(TestCaseNode const& testCaseNode);
  4394. void writeSection(std::string const& className,
  4395. std::string const& rootName,
  4396. SectionNode const& sectionNode);
  4397. void writeAssertions(SectionNode const& sectionNode);
  4398. void writeAssertion(AssertionStats const& stats);
  4399. XmlWriter xml;
  4400. Timer suiteTimer;
  4401. std::string stdOutForSuite;
  4402. std::string stdErrForSuite;
  4403. unsigned int unexpectedExceptions = 0;
  4404. bool m_okToFail = false;
  4405. };
  4406. } // end namespace Catch
  4407. // end catch_reporter_junit.h
  4408. // start catch_reporter_xml.h
  4409. namespace Catch {
  4410. class XmlReporter : public StreamingReporterBase<XmlReporter> {
  4411. public:
  4412. XmlReporter(ReporterConfig const& _config);
  4413. ~XmlReporter() override;
  4414. static std::string getDescription();
  4415. virtual std::string getStylesheetRef() const;
  4416. void writeSourceInfo(SourceLineInfo const& sourceInfo);
  4417. public: // StreamingReporterBase
  4418. void noMatchingTestCases(std::string const& s) override;
  4419. void testRunStarting(TestRunInfo const& testInfo) override;
  4420. void testGroupStarting(GroupInfo const& groupInfo) override;
  4421. void testCaseStarting(TestCaseInfo const& testInfo) override;
  4422. void sectionStarting(SectionInfo const& sectionInfo) override;
  4423. void assertionStarting(AssertionInfo const&) override;
  4424. bool assertionEnded(AssertionStats const& assertionStats) override;
  4425. void sectionEnded(SectionStats const& sectionStats) override;
  4426. void testCaseEnded(TestCaseStats const& testCaseStats) override;
  4427. void testGroupEnded(TestGroupStats const& testGroupStats) override;
  4428. void testRunEnded(TestRunStats const& testRunStats) override;
  4429. private:
  4430. Timer m_testCaseTimer;
  4431. XmlWriter m_xml;
  4432. int m_sectionDepth = 0;
  4433. };
  4434. } // end namespace Catch
  4435. // end catch_reporter_xml.h
  4436. // end catch_external_interfaces.h
  4437. #endif
  4438. #endif // ! CATCH_CONFIG_IMPL_ONLY
  4439. #ifdef CATCH_IMPL
  4440. // start catch_impl.hpp
  4441. #ifdef __clang__
  4442. #pragma clang diagnostic push
  4443. #pragma clang diagnostic ignored "-Wweak-vtables"
  4444. #endif
  4445. // Keep these here for external reporters
  4446. // start catch_test_case_tracker.h
  4447. #include <string>
  4448. #include <vector>
  4449. #include <memory>
  4450. namespace Catch {
  4451. namespace TestCaseTracking {
  4452. struct NameAndLocation {
  4453. std::string name;
  4454. SourceLineInfo location;
  4455. NameAndLocation( std::string const& _name, SourceLineInfo const& _location );
  4456. };
  4457. struct ITracker;
  4458. using ITrackerPtr = std::shared_ptr<ITracker>;
  4459. struct ITracker {
  4460. virtual ~ITracker();
  4461. // static queries
  4462. virtual NameAndLocation const& nameAndLocation() const = 0;
  4463. // dynamic queries
  4464. virtual bool isComplete() const = 0; // Successfully completed or failed
  4465. virtual bool isSuccessfullyCompleted() const = 0;
  4466. virtual bool isOpen() const = 0; // Started but not complete
  4467. virtual bool hasChildren() const = 0;
  4468. virtual ITracker& parent() = 0;
  4469. // actions
  4470. virtual void close() = 0; // Successfully complete
  4471. virtual void fail() = 0;
  4472. virtual void markAsNeedingAnotherRun() = 0;
  4473. virtual void addChild( ITrackerPtr const& child ) = 0;
  4474. virtual ITrackerPtr findChild( NameAndLocation const& nameAndLocation ) = 0;
  4475. virtual void openChild() = 0;
  4476. // Debug/ checking
  4477. virtual bool isSectionTracker() const = 0;
  4478. virtual bool isGeneratorTracker() const = 0;
  4479. };
  4480. class TrackerContext {
  4481. enum RunState {
  4482. NotStarted,
  4483. Executing,
  4484. CompletedCycle
  4485. };
  4486. ITrackerPtr m_rootTracker;
  4487. ITracker* m_currentTracker = nullptr;
  4488. RunState m_runState = NotStarted;
  4489. public:
  4490. static TrackerContext& instance();
  4491. ITracker& startRun();
  4492. void endRun();
  4493. void startCycle();
  4494. void completeCycle();
  4495. bool completedCycle() const;
  4496. ITracker& currentTracker();
  4497. void setCurrentTracker( ITracker* tracker );
  4498. };
  4499. class TrackerBase : public ITracker {
  4500. protected:
  4501. enum CycleState {
  4502. NotStarted,
  4503. Executing,
  4504. ExecutingChildren,
  4505. NeedsAnotherRun,
  4506. CompletedSuccessfully,
  4507. Failed
  4508. };
  4509. using Children = std::vector<ITrackerPtr>;
  4510. NameAndLocation m_nameAndLocation;
  4511. TrackerContext& m_ctx;
  4512. ITracker* m_parent;
  4513. Children m_children;
  4514. CycleState m_runState = NotStarted;
  4515. public:
  4516. TrackerBase( NameAndLocation const& nameAndLocation, TrackerContext& ctx, ITracker* parent );
  4517. NameAndLocation const& nameAndLocation() const override;
  4518. bool isComplete() const override;
  4519. bool isSuccessfullyCompleted() const override;
  4520. bool isOpen() const override;
  4521. bool hasChildren() const override;
  4522. void addChild( ITrackerPtr const& child ) override;
  4523. ITrackerPtr findChild( NameAndLocation const& nameAndLocation ) override;
  4524. ITracker& parent() override;
  4525. void openChild() override;
  4526. bool isSectionTracker() const override;
  4527. bool isGeneratorTracker() const override;
  4528. void open();
  4529. void close() override;
  4530. void fail() override;
  4531. void markAsNeedingAnotherRun() override;
  4532. private:
  4533. void moveToParent();
  4534. void moveToThis();
  4535. };
  4536. class SectionTracker : public TrackerBase {
  4537. std::vector<std::string> m_filters;
  4538. public:
  4539. SectionTracker( NameAndLocation const& nameAndLocation, TrackerContext& ctx, ITracker* parent );
  4540. bool isSectionTracker() const override;
  4541. bool isComplete() const override;
  4542. static SectionTracker& acquire( TrackerContext& ctx, NameAndLocation const& nameAndLocation );
  4543. void tryOpen();
  4544. void addInitialFilters( std::vector<std::string> const& filters );
  4545. void addNextFilters( std::vector<std::string> const& filters );
  4546. };
  4547. } // namespace TestCaseTracking
  4548. using TestCaseTracking::ITracker;
  4549. using TestCaseTracking::TrackerContext;
  4550. using TestCaseTracking::SectionTracker;
  4551. } // namespace Catch
  4552. // end catch_test_case_tracker.h
  4553. // start catch_leak_detector.h
  4554. namespace Catch {
  4555. struct LeakDetector {
  4556. LeakDetector();
  4557. ~LeakDetector();
  4558. };
  4559. }
  4560. // end catch_leak_detector.h
  4561. // Cpp files will be included in the single-header file here
  4562. // start catch_approx.cpp
  4563. #include <cmath>
  4564. #include <limits>
  4565. namespace {
  4566. // Performs equivalent check of std::fabs(lhs - rhs) <= margin
  4567. // But without the subtraction to allow for INFINITY in comparison
  4568. bool marginComparison(double lhs, double rhs, double margin) {
  4569. return (lhs + margin >= rhs) && (rhs + margin >= lhs);
  4570. }
  4571. }
  4572. namespace Catch {
  4573. namespace Detail {
  4574. Approx::Approx ( double value )
  4575. : m_epsilon( std::numeric_limits<float>::epsilon()*100 ),
  4576. m_margin( 0.0 ),
  4577. m_scale( 0.0 ),
  4578. m_value( value )
  4579. {}
  4580. Approx Approx::custom() {
  4581. return Approx( 0 );
  4582. }
  4583. Approx Approx::operator-() const {
  4584. auto temp(*this);
  4585. temp.m_value = -temp.m_value;
  4586. return temp;
  4587. }
  4588. std::string Approx::toString() const {
  4589. ReusableStringStream rss;
  4590. rss << "Approx( " << ::Catch::Detail::stringify( m_value ) << " )";
  4591. return rss.str();
  4592. }
  4593. bool Approx::equalityComparisonImpl(const double other) const {
  4594. // First try with fixed margin, then compute margin based on epsilon, scale and Approx's value
  4595. // Thanks to Richard Harris for his help refining the scaled margin value
  4596. return marginComparison(m_value, other, m_margin) || marginComparison(m_value, other, m_epsilon * (m_scale + std::fabs(m_value)));
  4597. }
  4598. void Approx::setMargin(double margin) {
  4599. CATCH_ENFORCE(margin >= 0,
  4600. "Invalid Approx::margin: " << margin << '.'
  4601. << " Approx::Margin has to be non-negative.");
  4602. m_margin = margin;
  4603. }
  4604. void Approx::setEpsilon(double epsilon) {
  4605. CATCH_ENFORCE(epsilon >= 0 && epsilon <= 1.0,
  4606. "Invalid Approx::epsilon: " << epsilon << '.'
  4607. << " Approx::epsilon has to be in [0, 1]");
  4608. m_epsilon = epsilon;
  4609. }
  4610. } // end namespace Detail
  4611. namespace literals {
  4612. Detail::Approx operator "" _a(long double val) {
  4613. return Detail::Approx(val);
  4614. }
  4615. Detail::Approx operator "" _a(unsigned long long val) {
  4616. return Detail::Approx(val);
  4617. }
  4618. } // end namespace literals
  4619. std::string StringMaker<Catch::Detail::Approx>::convert(Catch::Detail::Approx const& value) {
  4620. return value.toString();
  4621. }
  4622. } // end namespace Catch
  4623. // end catch_approx.cpp
  4624. // start catch_assertionhandler.cpp
  4625. // start catch_context.h
  4626. #include <memory>
  4627. namespace Catch {
  4628. struct IResultCapture;
  4629. struct IRunner;
  4630. struct IConfig;
  4631. struct IMutableContext;
  4632. using IConfigPtr = std::shared_ptr<IConfig const>;
  4633. struct IContext
  4634. {
  4635. virtual ~IContext();
  4636. virtual IResultCapture* getResultCapture() = 0;
  4637. virtual IRunner* getRunner() = 0;
  4638. virtual IConfigPtr const& getConfig() const = 0;
  4639. };
  4640. struct IMutableContext : IContext
  4641. {
  4642. virtual ~IMutableContext();
  4643. virtual void setResultCapture( IResultCapture* resultCapture ) = 0;
  4644. virtual void setRunner( IRunner* runner ) = 0;
  4645. virtual void setConfig( IConfigPtr const& config ) = 0;
  4646. private:
  4647. static IMutableContext *currentContext;
  4648. friend IMutableContext& getCurrentMutableContext();
  4649. friend void cleanUpContext();
  4650. static void createContext();
  4651. };
  4652. inline IMutableContext& getCurrentMutableContext()
  4653. {
  4654. if( !IMutableContext::currentContext )
  4655. IMutableContext::createContext();
  4656. return *IMutableContext::currentContext;
  4657. }
  4658. inline IContext& getCurrentContext()
  4659. {
  4660. return getCurrentMutableContext();
  4661. }
  4662. void cleanUpContext();
  4663. }
  4664. // end catch_context.h
  4665. // start catch_debugger.h
  4666. namespace Catch {
  4667. bool isDebuggerActive();
  4668. }
  4669. #ifdef CATCH_PLATFORM_MAC
  4670. #define CATCH_TRAP() __asm__("int $3\n" : : ) /* NOLINT */
  4671. #elif defined(CATCH_PLATFORM_LINUX)
  4672. // If we can use inline assembler, do it because this allows us to break
  4673. // directly at the location of the failing check instead of breaking inside
  4674. // raise() called from it, i.e. one stack frame below.
  4675. #if defined(__GNUC__) && (defined(__i386) || defined(__x86_64))
  4676. #define CATCH_TRAP() asm volatile ("int $3") /* NOLINT */
  4677. #else // Fall back to the generic way.
  4678. #include <signal.h>
  4679. #define CATCH_TRAP() raise(SIGTRAP)
  4680. #endif
  4681. #elif defined(_MSC_VER)
  4682. #define CATCH_TRAP() __debugbreak()
  4683. #elif defined(__MINGW32__)
  4684. extern "C" __declspec(dllimport) void __stdcall DebugBreak();
  4685. #define CATCH_TRAP() DebugBreak()
  4686. #endif
  4687. #ifdef CATCH_TRAP
  4688. #define CATCH_BREAK_INTO_DEBUGGER() []{ if( Catch::isDebuggerActive() ) { CATCH_TRAP(); } }()
  4689. #else
  4690. #define CATCH_BREAK_INTO_DEBUGGER() []{}()
  4691. #endif
  4692. // end catch_debugger.h
  4693. // start catch_run_context.h
  4694. // start catch_fatal_condition.h
  4695. // start catch_windows_h_proxy.h
  4696. #if defined(CATCH_PLATFORM_WINDOWS)
  4697. #if !defined(NOMINMAX) && !defined(CATCH_CONFIG_NO_NOMINMAX)
  4698. # define CATCH_DEFINED_NOMINMAX
  4699. # define NOMINMAX
  4700. #endif
  4701. #if !defined(WIN32_LEAN_AND_MEAN) && !defined(CATCH_CONFIG_NO_WIN32_LEAN_AND_MEAN)
  4702. # define CATCH_DEFINED_WIN32_LEAN_AND_MEAN
  4703. # define WIN32_LEAN_AND_MEAN
  4704. #endif
  4705. #ifdef __AFXDLL
  4706. #include <AfxWin.h>
  4707. #else
  4708. #include <windows.h>
  4709. #endif
  4710. #ifdef CATCH_DEFINED_NOMINMAX
  4711. # undef NOMINMAX
  4712. #endif
  4713. #ifdef CATCH_DEFINED_WIN32_LEAN_AND_MEAN
  4714. # undef WIN32_LEAN_AND_MEAN
  4715. #endif
  4716. #endif // defined(CATCH_PLATFORM_WINDOWS)
  4717. // end catch_windows_h_proxy.h
  4718. #if defined( CATCH_CONFIG_WINDOWS_SEH )
  4719. namespace Catch {
  4720. struct FatalConditionHandler {
  4721. static LONG CALLBACK handleVectoredException(PEXCEPTION_POINTERS ExceptionInfo);
  4722. FatalConditionHandler();
  4723. static void reset();
  4724. ~FatalConditionHandler();
  4725. private:
  4726. static bool isSet;
  4727. static ULONG guaranteeSize;
  4728. static PVOID exceptionHandlerHandle;
  4729. };
  4730. } // namespace Catch
  4731. #elif defined ( CATCH_CONFIG_POSIX_SIGNALS )
  4732. #include <signal.h>
  4733. namespace Catch {
  4734. struct FatalConditionHandler {
  4735. static bool isSet;
  4736. static struct sigaction oldSigActions[];
  4737. static stack_t oldSigStack;
  4738. static char altStackMem[];
  4739. static void handleSignal( int sig );
  4740. FatalConditionHandler();
  4741. ~FatalConditionHandler();
  4742. static void reset();
  4743. };
  4744. } // namespace Catch
  4745. #else
  4746. namespace Catch {
  4747. struct FatalConditionHandler {
  4748. void reset();
  4749. };
  4750. }
  4751. #endif
  4752. // end catch_fatal_condition.h
  4753. #include <string>
  4754. namespace Catch {
  4755. struct IMutableContext;
  4756. ///////////////////////////////////////////////////////////////////////////
  4757. class RunContext : public IResultCapture, public IRunner {
  4758. public:
  4759. RunContext( RunContext const& ) = delete;
  4760. RunContext& operator =( RunContext const& ) = delete;
  4761. explicit RunContext( IConfigPtr const& _config, IStreamingReporterPtr&& reporter );
  4762. ~RunContext() override;
  4763. void testGroupStarting( std::string const& testSpec, std::size_t groupIndex, std::size_t groupsCount );
  4764. void testGroupEnded( std::string const& testSpec, Totals const& totals, std::size_t groupIndex, std::size_t groupsCount );
  4765. Totals runTest(TestCase const& testCase);
  4766. IConfigPtr config() const;
  4767. IStreamingReporter& reporter() const;
  4768. public: // IResultCapture
  4769. // Assertion handlers
  4770. void handleExpr
  4771. ( AssertionInfo const& info,
  4772. ITransientExpression const& expr,
  4773. AssertionReaction& reaction ) override;
  4774. void handleMessage
  4775. ( AssertionInfo const& info,
  4776. ResultWas::OfType resultType,
  4777. StringRef const& message,
  4778. AssertionReaction& reaction ) override;
  4779. void handleUnexpectedExceptionNotThrown
  4780. ( AssertionInfo const& info,
  4781. AssertionReaction& reaction ) override;
  4782. void handleUnexpectedInflightException
  4783. ( AssertionInfo const& info,
  4784. std::string const& message,
  4785. AssertionReaction& reaction ) override;
  4786. void handleIncomplete
  4787. ( AssertionInfo const& info ) override;
  4788. void handleNonExpr
  4789. ( AssertionInfo const &info,
  4790. ResultWas::OfType resultType,
  4791. AssertionReaction &reaction ) override;
  4792. bool sectionStarted( SectionInfo const& sectionInfo, Counts& assertions ) override;
  4793. void sectionEnded( SectionEndInfo const& endInfo ) override;
  4794. void sectionEndedEarly( SectionEndInfo const& endInfo ) override;
  4795. auto acquireGeneratorTracker( SourceLineInfo const& lineInfo ) -> IGeneratorTracker& override;
  4796. void benchmarkStarting( BenchmarkInfo const& info ) override;
  4797. void benchmarkEnded( BenchmarkStats const& stats ) override;
  4798. void pushScopedMessage( MessageInfo const& message ) override;
  4799. void popScopedMessage( MessageInfo const& message ) override;
  4800. std::string getCurrentTestName() const override;
  4801. const AssertionResult* getLastResult() const override;
  4802. void exceptionEarlyReported() override;
  4803. void handleFatalErrorCondition( StringRef message ) override;
  4804. bool lastAssertionPassed() override;
  4805. void assertionPassed() override;
  4806. public:
  4807. // !TBD We need to do this another way!
  4808. bool aborting() const final;
  4809. private:
  4810. void runCurrentTest( std::string& redirectedCout, std::string& redirectedCerr );
  4811. void invokeActiveTestCase();
  4812. void resetAssertionInfo();
  4813. bool testForMissingAssertions( Counts& assertions );
  4814. void assertionEnded( AssertionResult const& result );
  4815. void reportExpr
  4816. ( AssertionInfo const &info,
  4817. ResultWas::OfType resultType,
  4818. ITransientExpression const *expr,
  4819. bool negated );
  4820. void populateReaction( AssertionReaction& reaction );
  4821. private:
  4822. void handleUnfinishedSections();
  4823. TestRunInfo m_runInfo;
  4824. IMutableContext& m_context;
  4825. TestCase const* m_activeTestCase = nullptr;
  4826. ITracker* m_testCaseTracker = nullptr;
  4827. Option<AssertionResult> m_lastResult;
  4828. IConfigPtr m_config;
  4829. Totals m_totals;
  4830. IStreamingReporterPtr m_reporter;
  4831. std::vector<MessageInfo> m_messages;
  4832. AssertionInfo m_lastAssertionInfo;
  4833. std::vector<SectionEndInfo> m_unfinishedSections;
  4834. std::vector<ITracker*> m_activeSections;
  4835. TrackerContext m_trackerContext;
  4836. bool m_lastAssertionPassed = false;
  4837. bool m_shouldReportUnexpected = true;
  4838. bool m_includeSuccessfulResults;
  4839. };
  4840. } // end namespace Catch
  4841. // end catch_run_context.h
  4842. namespace Catch {
  4843. namespace {
  4844. auto operator <<( std::ostream& os, ITransientExpression const& expr ) -> std::ostream& {
  4845. expr.streamReconstructedExpression( os );
  4846. return os;
  4847. }
  4848. }
  4849. LazyExpression::LazyExpression( bool isNegated )
  4850. : m_isNegated( isNegated )
  4851. {}
  4852. LazyExpression::LazyExpression( LazyExpression const& other ) : m_isNegated( other.m_isNegated ) {}
  4853. LazyExpression::operator bool() const {
  4854. return m_transientExpression != nullptr;
  4855. }
  4856. auto operator << ( std::ostream& os, LazyExpression const& lazyExpr ) -> std::ostream& {
  4857. if( lazyExpr.m_isNegated )
  4858. os << "!";
  4859. if( lazyExpr ) {
  4860. if( lazyExpr.m_isNegated && lazyExpr.m_transientExpression->isBinaryExpression() )
  4861. os << "(" << *lazyExpr.m_transientExpression << ")";
  4862. else
  4863. os << *lazyExpr.m_transientExpression;
  4864. }
  4865. else {
  4866. os << "{** error - unchecked empty expression requested **}";
  4867. }
  4868. return os;
  4869. }
  4870. AssertionHandler::AssertionHandler
  4871. ( StringRef const& macroName,
  4872. SourceLineInfo const& lineInfo,
  4873. StringRef capturedExpression,
  4874. ResultDisposition::Flags resultDisposition )
  4875. : m_assertionInfo{ macroName, lineInfo, capturedExpression, resultDisposition },
  4876. m_resultCapture( getResultCapture() )
  4877. {}
  4878. void AssertionHandler::handleExpr( ITransientExpression const& expr ) {
  4879. m_resultCapture.handleExpr( m_assertionInfo, expr, m_reaction );
  4880. }
  4881. void AssertionHandler::handleMessage(ResultWas::OfType resultType, StringRef const& message) {
  4882. m_resultCapture.handleMessage( m_assertionInfo, resultType, message, m_reaction );
  4883. }
  4884. auto AssertionHandler::allowThrows() const -> bool {
  4885. return getCurrentContext().getConfig()->allowThrows();
  4886. }
  4887. void AssertionHandler::complete() {
  4888. setCompleted();
  4889. if( m_reaction.shouldDebugBreak ) {
  4890. // If you find your debugger stopping you here then go one level up on the
  4891. // call-stack for the code that caused it (typically a failed assertion)
  4892. // (To go back to the test and change execution, jump over the throw, next)
  4893. CATCH_BREAK_INTO_DEBUGGER();
  4894. }
  4895. if (m_reaction.shouldThrow) {
  4896. #if !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
  4897. throw Catch::TestFailureException();
  4898. #else
  4899. CATCH_ERROR( "Test failure requires aborting test!" );
  4900. #endif
  4901. }
  4902. }
  4903. void AssertionHandler::setCompleted() {
  4904. m_completed = true;
  4905. }
  4906. void AssertionHandler::handleUnexpectedInflightException() {
  4907. m_resultCapture.handleUnexpectedInflightException( m_assertionInfo, Catch::translateActiveException(), m_reaction );
  4908. }
  4909. void AssertionHandler::handleExceptionThrownAsExpected() {
  4910. m_resultCapture.handleNonExpr(m_assertionInfo, ResultWas::Ok, m_reaction);
  4911. }
  4912. void AssertionHandler::handleExceptionNotThrownAsExpected() {
  4913. m_resultCapture.handleNonExpr(m_assertionInfo, ResultWas::Ok, m_reaction);
  4914. }
  4915. void AssertionHandler::handleUnexpectedExceptionNotThrown() {
  4916. m_resultCapture.handleUnexpectedExceptionNotThrown( m_assertionInfo, m_reaction );
  4917. }
  4918. void AssertionHandler::handleThrowingCallSkipped() {
  4919. m_resultCapture.handleNonExpr(m_assertionInfo, ResultWas::Ok, m_reaction);
  4920. }
  4921. // This is the overload that takes a string and infers the Equals matcher from it
  4922. // The more general overload, that takes any string matcher, is in catch_capture_matchers.cpp
  4923. void handleExceptionMatchExpr( AssertionHandler& handler, std::string const& str, StringRef const& matcherString ) {
  4924. handleExceptionMatchExpr( handler, Matchers::Equals( str ), matcherString );
  4925. }
  4926. } // namespace Catch
  4927. // end catch_assertionhandler.cpp
  4928. // start catch_assertionresult.cpp
  4929. namespace Catch {
  4930. AssertionResultData::AssertionResultData(ResultWas::OfType _resultType, LazyExpression const & _lazyExpression):
  4931. lazyExpression(_lazyExpression),
  4932. resultType(_resultType) {}
  4933. std::string AssertionResultData::reconstructExpression() const {
  4934. if( reconstructedExpression.empty() ) {
  4935. if( lazyExpression ) {
  4936. ReusableStringStream rss;
  4937. rss << lazyExpression;
  4938. reconstructedExpression = rss.str();
  4939. }
  4940. }
  4941. return reconstructedExpression;
  4942. }
  4943. AssertionResult::AssertionResult( AssertionInfo const& info, AssertionResultData const& data )
  4944. : m_info( info ),
  4945. m_resultData( data )
  4946. {}
  4947. // Result was a success
  4948. bool AssertionResult::succeeded() const {
  4949. return Catch::isOk( m_resultData.resultType );
  4950. }
  4951. // Result was a success, or failure is suppressed
  4952. bool AssertionResult::isOk() const {
  4953. return Catch::isOk( m_resultData.resultType ) || shouldSuppressFailure( m_info.resultDisposition );
  4954. }
  4955. ResultWas::OfType AssertionResult::getResultType() const {
  4956. return m_resultData.resultType;
  4957. }
  4958. bool AssertionResult::hasExpression() const {
  4959. return m_info.capturedExpression[0] != 0;
  4960. }
  4961. bool AssertionResult::hasMessage() const {
  4962. return !m_resultData.message.empty();
  4963. }
  4964. std::string AssertionResult::getExpression() const {
  4965. if( isFalseTest( m_info.resultDisposition ) )
  4966. return "!(" + m_info.capturedExpression + ")";
  4967. else
  4968. return m_info.capturedExpression;
  4969. }
  4970. std::string AssertionResult::getExpressionInMacro() const {
  4971. std::string expr;
  4972. if( m_info.macroName[0] == 0 )
  4973. expr = m_info.capturedExpression;
  4974. else {
  4975. expr.reserve( m_info.macroName.size() + m_info.capturedExpression.size() + 4 );
  4976. expr += m_info.macroName;
  4977. expr += "( ";
  4978. expr += m_info.capturedExpression;
  4979. expr += " )";
  4980. }
  4981. return expr;
  4982. }
  4983. bool AssertionResult::hasExpandedExpression() const {
  4984. return hasExpression() && getExpandedExpression() != getExpression();
  4985. }
  4986. std::string AssertionResult::getExpandedExpression() const {
  4987. std::string expr = m_resultData.reconstructExpression();
  4988. return expr.empty()
  4989. ? getExpression()
  4990. : expr;
  4991. }
  4992. std::string AssertionResult::getMessage() const {
  4993. return m_resultData.message;
  4994. }
  4995. SourceLineInfo AssertionResult::getSourceInfo() const {
  4996. return m_info.lineInfo;
  4997. }
  4998. StringRef AssertionResult::getTestMacroName() const {
  4999. return m_info.macroName;
  5000. }
  5001. } // end namespace Catch
  5002. // end catch_assertionresult.cpp
  5003. // start catch_benchmark.cpp
  5004. namespace Catch {
  5005. auto BenchmarkLooper::getResolution() -> uint64_t {
  5006. return getEstimatedClockResolution() * getCurrentContext().getConfig()->benchmarkResolutionMultiple();
  5007. }
  5008. void BenchmarkLooper::reportStart() {
  5009. getResultCapture().benchmarkStarting( { m_name } );
  5010. }
  5011. auto BenchmarkLooper::needsMoreIterations() -> bool {
  5012. auto elapsed = m_timer.getElapsedNanoseconds();
  5013. // Exponentially increasing iterations until we're confident in our timer resolution
  5014. if( elapsed < m_resolution ) {
  5015. m_iterationsToRun *= 10;
  5016. return true;
  5017. }
  5018. getResultCapture().benchmarkEnded( { { m_name }, m_count, elapsed } );
  5019. return false;
  5020. }
  5021. } // end namespace Catch
  5022. // end catch_benchmark.cpp
  5023. // start catch_capture_matchers.cpp
  5024. namespace Catch {
  5025. using StringMatcher = Matchers::Impl::MatcherBase<std::string>;
  5026. // This is the general overload that takes a any string matcher
  5027. // There is another overload, in catch_assertionhandler.h/.cpp, that only takes a string and infers
  5028. // the Equals matcher (so the header does not mention matchers)
  5029. void handleExceptionMatchExpr( AssertionHandler& handler, StringMatcher const& matcher, StringRef const& matcherString ) {
  5030. std::string exceptionMessage = Catch::translateActiveException();
  5031. MatchExpr<std::string, StringMatcher const&> expr( exceptionMessage, matcher, matcherString );
  5032. handler.handleExpr( expr );
  5033. }
  5034. } // namespace Catch
  5035. // end catch_capture_matchers.cpp
  5036. // start catch_commandline.cpp
  5037. // start catch_commandline.h
  5038. // start catch_clara.h
  5039. // Use Catch's value for console width (store Clara's off to the side, if present)
  5040. #ifdef CLARA_CONFIG_CONSOLE_WIDTH
  5041. #define CATCH_TEMP_CLARA_CONFIG_CONSOLE_WIDTH CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH
  5042. #undef CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH
  5043. #endif
  5044. #define CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH CATCH_CONFIG_CONSOLE_WIDTH-1
  5045. #ifdef __clang__
  5046. #pragma clang diagnostic push
  5047. #pragma clang diagnostic ignored "-Wweak-vtables"
  5048. #pragma clang diagnostic ignored "-Wexit-time-destructors"
  5049. #pragma clang diagnostic ignored "-Wshadow"
  5050. #endif
  5051. // start clara.hpp
  5052. // Copyright 2017 Two Blue Cubes Ltd. All rights reserved.
  5053. //
  5054. // Distributed under the Boost Software License, Version 1.0. (See accompanying
  5055. // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
  5056. //
  5057. // See https://github.com/philsquared/Clara for more details
  5058. // Clara v1.1.5
  5059. #ifndef CATCH_CLARA_CONFIG_CONSOLE_WIDTH
  5060. #define CATCH_CLARA_CONFIG_CONSOLE_WIDTH 80
  5061. #endif
  5062. #ifndef CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH
  5063. #define CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH CATCH_CLARA_CONFIG_CONSOLE_WIDTH
  5064. #endif
  5065. #ifndef CLARA_CONFIG_OPTIONAL_TYPE
  5066. #ifdef __has_include
  5067. #if __has_include(<optional>) && __cplusplus >= 201703L
  5068. #include <optional>
  5069. #define CLARA_CONFIG_OPTIONAL_TYPE std::optional
  5070. #endif
  5071. #endif
  5072. #endif
  5073. // ----------- #included from clara_textflow.hpp -----------
  5074. // TextFlowCpp
  5075. //
  5076. // A single-header library for wrapping and laying out basic text, by Phil Nash
  5077. //
  5078. // Distributed under the Boost Software License, Version 1.0. (See accompanying
  5079. // file LICENSE.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
  5080. //
  5081. // This project is hosted at https://github.com/philsquared/textflowcpp
  5082. #include <cassert>
  5083. #include <ostream>
  5084. #include <sstream>
  5085. #include <vector>
  5086. #ifndef CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH
  5087. #define CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH 80
  5088. #endif
  5089. namespace Catch {
  5090. namespace clara {
  5091. namespace TextFlow {
  5092. inline auto isWhitespace(char c) -> bool {
  5093. static std::string chars = " \t\n\r";
  5094. return chars.find(c) != std::string::npos;
  5095. }
  5096. inline auto isBreakableBefore(char c) -> bool {
  5097. static std::string chars = "[({<|";
  5098. return chars.find(c) != std::string::npos;
  5099. }
  5100. inline auto isBreakableAfter(char c) -> bool {
  5101. static std::string chars = "])}>.,:;*+-=&/\\";
  5102. return chars.find(c) != std::string::npos;
  5103. }
  5104. class Columns;
  5105. class Column {
  5106. std::vector<std::string> m_strings;
  5107. size_t m_width = CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH;
  5108. size_t m_indent = 0;
  5109. size_t m_initialIndent = std::string::npos;
  5110. public:
  5111. class iterator {
  5112. friend Column;
  5113. Column const& m_column;
  5114. size_t m_stringIndex = 0;
  5115. size_t m_pos = 0;
  5116. size_t m_len = 0;
  5117. size_t m_end = 0;
  5118. bool m_suffix = false;
  5119. iterator(Column const& column, size_t stringIndex)
  5120. : m_column(column),
  5121. m_stringIndex(stringIndex) {}
  5122. auto line() const -> std::string const& { return m_column.m_strings[m_stringIndex]; }
  5123. auto isBoundary(size_t at) const -> bool {
  5124. assert(at > 0);
  5125. assert(at <= line().size());
  5126. return at == line().size() ||
  5127. (isWhitespace(line()[at]) && !isWhitespace(line()[at - 1])) ||
  5128. isBreakableBefore(line()[at]) ||
  5129. isBreakableAfter(line()[at - 1]);
  5130. }
  5131. void calcLength() {
  5132. assert(m_stringIndex < m_column.m_strings.size());
  5133. m_suffix = false;
  5134. auto width = m_column.m_width - indent();
  5135. m_end = m_pos;
  5136. while (m_end < line().size() && line()[m_end] != '\n')
  5137. ++m_end;
  5138. if (m_end < m_pos + width) {
  5139. m_len = m_end - m_pos;
  5140. } else {
  5141. size_t len = width;
  5142. while (len > 0 && !isBoundary(m_pos + len))
  5143. --len;
  5144. while (len > 0 && isWhitespace(line()[m_pos + len - 1]))
  5145. --len;
  5146. if (len > 0) {
  5147. m_len = len;
  5148. } else {
  5149. m_suffix = true;
  5150. m_len = width - 1;
  5151. }
  5152. }
  5153. }
  5154. auto indent() const -> size_t {
  5155. auto initial = m_pos == 0 && m_stringIndex == 0 ? m_column.m_initialIndent : std::string::npos;
  5156. return initial == std::string::npos ? m_column.m_indent : initial;
  5157. }
  5158. auto addIndentAndSuffix(std::string const &plain) const -> std::string {
  5159. return std::string(indent(), ' ') + (m_suffix ? plain + "-" : plain);
  5160. }
  5161. public:
  5162. using difference_type = std::ptrdiff_t;
  5163. using value_type = std::string;
  5164. using pointer = value_type * ;
  5165. using reference = value_type & ;
  5166. using iterator_category = std::forward_iterator_tag;
  5167. explicit iterator(Column const& column) : m_column(column) {
  5168. assert(m_column.m_width > m_column.m_indent);
  5169. assert(m_column.m_initialIndent == std::string::npos || m_column.m_width > m_column.m_initialIndent);
  5170. calcLength();
  5171. if (m_len == 0)
  5172. m_stringIndex++; // Empty string
  5173. }
  5174. auto operator *() const -> std::string {
  5175. assert(m_stringIndex < m_column.m_strings.size());
  5176. assert(m_pos <= m_end);
  5177. return addIndentAndSuffix(line().substr(m_pos, m_len));
  5178. }
  5179. auto operator ++() -> iterator& {
  5180. m_pos += m_len;
  5181. if (m_pos < line().size() && line()[m_pos] == '\n')
  5182. m_pos += 1;
  5183. else
  5184. while (m_pos < line().size() && isWhitespace(line()[m_pos]))
  5185. ++m_pos;
  5186. if (m_pos == line().size()) {
  5187. m_pos = 0;
  5188. ++m_stringIndex;
  5189. }
  5190. if (m_stringIndex < m_column.m_strings.size())
  5191. calcLength();
  5192. return *this;
  5193. }
  5194. auto operator ++(int) -> iterator {
  5195. iterator prev(*this);
  5196. operator++();
  5197. return prev;
  5198. }
  5199. auto operator ==(iterator const& other) const -> bool {
  5200. return
  5201. m_pos == other.m_pos &&
  5202. m_stringIndex == other.m_stringIndex &&
  5203. &m_column == &other.m_column;
  5204. }
  5205. auto operator !=(iterator const& other) const -> bool {
  5206. return !operator==(other);
  5207. }
  5208. };
  5209. using const_iterator = iterator;
  5210. explicit Column(std::string const& text) { m_strings.push_back(text); }
  5211. auto width(size_t newWidth) -> Column& {
  5212. assert(newWidth > 0);
  5213. m_width = newWidth;
  5214. return *this;
  5215. }
  5216. auto indent(size_t newIndent) -> Column& {
  5217. m_indent = newIndent;
  5218. return *this;
  5219. }
  5220. auto initialIndent(size_t newIndent) -> Column& {
  5221. m_initialIndent = newIndent;
  5222. return *this;
  5223. }
  5224. auto width() const -> size_t { return m_width; }
  5225. auto begin() const -> iterator { return iterator(*this); }
  5226. auto end() const -> iterator { return { *this, m_strings.size() }; }
  5227. inline friend std::ostream& operator << (std::ostream& os, Column const& col) {
  5228. bool first = true;
  5229. for (auto line : col) {
  5230. if (first)
  5231. first = false;
  5232. else
  5233. os << "\n";
  5234. os << line;
  5235. }
  5236. return os;
  5237. }
  5238. auto operator + (Column const& other)->Columns;
  5239. auto toString() const -> std::string {
  5240. std::ostringstream oss;
  5241. oss << *this;
  5242. return oss.str();
  5243. }
  5244. };
  5245. class Spacer : public Column {
  5246. public:
  5247. explicit Spacer(size_t spaceWidth) : Column("") {
  5248. width(spaceWidth);
  5249. }
  5250. };
  5251. class Columns {
  5252. std::vector<Column> m_columns;
  5253. public:
  5254. class iterator {
  5255. friend Columns;
  5256. struct EndTag {};
  5257. std::vector<Column> const& m_columns;
  5258. std::vector<Column::iterator> m_iterators;
  5259. size_t m_activeIterators;
  5260. iterator(Columns const& columns, EndTag)
  5261. : m_columns(columns.m_columns),
  5262. m_activeIterators(0) {
  5263. m_iterators.reserve(m_columns.size());
  5264. for (auto const& col : m_columns)
  5265. m_iterators.push_back(col.end());
  5266. }
  5267. public:
  5268. using difference_type = std::ptrdiff_t;
  5269. using value_type = std::string;
  5270. using pointer = value_type * ;
  5271. using reference = value_type & ;
  5272. using iterator_category = std::forward_iterator_tag;
  5273. explicit iterator(Columns const& columns)
  5274. : m_columns(columns.m_columns),
  5275. m_activeIterators(m_columns.size()) {
  5276. m_iterators.reserve(m_columns.size());
  5277. for (auto const& col : m_columns)
  5278. m_iterators.push_back(col.begin());
  5279. }
  5280. auto operator ==(iterator const& other) const -> bool {
  5281. return m_iterators == other.m_iterators;
  5282. }
  5283. auto operator !=(iterator const& other) const -> bool {
  5284. return m_iterators != other.m_iterators;
  5285. }
  5286. auto operator *() const -> std::string {
  5287. std::string row, padding;
  5288. for (size_t i = 0; i < m_columns.size(); ++i) {
  5289. auto width = m_columns[i].width();
  5290. if (m_iterators[i] != m_columns[i].end()) {
  5291. std::string col = *m_iterators[i];
  5292. row += padding + col;
  5293. if (col.size() < width)
  5294. padding = std::string(width - col.size(), ' ');
  5295. else
  5296. padding = "";
  5297. } else {
  5298. padding += std::string(width, ' ');
  5299. }
  5300. }
  5301. return row;
  5302. }
  5303. auto operator ++() -> iterator& {
  5304. for (size_t i = 0; i < m_columns.size(); ++i) {
  5305. if (m_iterators[i] != m_columns[i].end())
  5306. ++m_iterators[i];
  5307. }
  5308. return *this;
  5309. }
  5310. auto operator ++(int) -> iterator {
  5311. iterator prev(*this);
  5312. operator++();
  5313. return prev;
  5314. }
  5315. };
  5316. using const_iterator = iterator;
  5317. auto begin() const -> iterator { return iterator(*this); }
  5318. auto end() const -> iterator { return { *this, iterator::EndTag() }; }
  5319. auto operator += (Column const& col) -> Columns& {
  5320. m_columns.push_back(col);
  5321. return *this;
  5322. }
  5323. auto operator + (Column const& col) -> Columns {
  5324. Columns combined = *this;
  5325. combined += col;
  5326. return combined;
  5327. }
  5328. inline friend std::ostream& operator << (std::ostream& os, Columns const& cols) {
  5329. bool first = true;
  5330. for (auto line : cols) {
  5331. if (first)
  5332. first = false;
  5333. else
  5334. os << "\n";
  5335. os << line;
  5336. }
  5337. return os;
  5338. }
  5339. auto toString() const -> std::string {
  5340. std::ostringstream oss;
  5341. oss << *this;
  5342. return oss.str();
  5343. }
  5344. };
  5345. inline auto Column::operator + (Column const& other) -> Columns {
  5346. Columns cols;
  5347. cols += *this;
  5348. cols += other;
  5349. return cols;
  5350. }
  5351. }
  5352. }
  5353. }
  5354. // ----------- end of #include from clara_textflow.hpp -----------
  5355. // ........... back in clara.hpp
  5356. #include <string>
  5357. #include <memory>
  5358. #include <set>
  5359. #include <algorithm>
  5360. #if !defined(CATCH_PLATFORM_WINDOWS) && ( defined(WIN32) || defined(__WIN32__) || defined(_WIN32) || defined(_MSC_VER) )
  5361. #define CATCH_PLATFORM_WINDOWS
  5362. #endif
  5363. namespace Catch { namespace clara {
  5364. namespace detail {
  5365. // Traits for extracting arg and return type of lambdas (for single argument lambdas)
  5366. template<typename L>
  5367. struct UnaryLambdaTraits : UnaryLambdaTraits<decltype( &L::operator() )> {};
  5368. template<typename ClassT, typename ReturnT, typename... Args>
  5369. struct UnaryLambdaTraits<ReturnT( ClassT::* )( Args... ) const> {
  5370. static const bool isValid = false;
  5371. };
  5372. template<typename ClassT, typename ReturnT, typename ArgT>
  5373. struct UnaryLambdaTraits<ReturnT( ClassT::* )( ArgT ) const> {
  5374. static const bool isValid = true;
  5375. using ArgType = typename std::remove_const<typename std::remove_reference<ArgT>::type>::type;
  5376. using ReturnType = ReturnT;
  5377. };
  5378. class TokenStream;
  5379. // Transport for raw args (copied from main args, or supplied via init list for testing)
  5380. class Args {
  5381. friend TokenStream;
  5382. std::string m_exeName;
  5383. std::vector<std::string> m_args;
  5384. public:
  5385. Args( int argc, char const* const* argv )
  5386. : m_exeName(argv[0]),
  5387. m_args(argv + 1, argv + argc) {}
  5388. Args( std::initializer_list<std::string> args )
  5389. : m_exeName( *args.begin() ),
  5390. m_args( args.begin()+1, args.end() )
  5391. {}
  5392. auto exeName() const -> std::string {
  5393. return m_exeName;
  5394. }
  5395. };
  5396. // Wraps a token coming from a token stream. These may not directly correspond to strings as a single string
  5397. // may encode an option + its argument if the : or = form is used
  5398. enum class TokenType {
  5399. Option, Argument
  5400. };
  5401. struct Token {
  5402. TokenType type;
  5403. std::string token;
  5404. };
  5405. inline auto isOptPrefix( char c ) -> bool {
  5406. return c == '-'
  5407. #ifdef CATCH_PLATFORM_WINDOWS
  5408. || c == '/'
  5409. #endif
  5410. ;
  5411. }
  5412. // Abstracts iterators into args as a stream of tokens, with option arguments uniformly handled
  5413. class TokenStream {
  5414. using Iterator = std::vector<std::string>::const_iterator;
  5415. Iterator it;
  5416. Iterator itEnd;
  5417. std::vector<Token> m_tokenBuffer;
  5418. void loadBuffer() {
  5419. m_tokenBuffer.resize( 0 );
  5420. // Skip any empty strings
  5421. while( it != itEnd && it->empty() )
  5422. ++it;
  5423. if( it != itEnd ) {
  5424. auto const &next = *it;
  5425. if( isOptPrefix( next[0] ) ) {
  5426. auto delimiterPos = next.find_first_of( " :=" );
  5427. if( delimiterPos != std::string::npos ) {
  5428. m_tokenBuffer.push_back( { TokenType::Option, next.substr( 0, delimiterPos ) } );
  5429. m_tokenBuffer.push_back( { TokenType::Argument, next.substr( delimiterPos + 1 ) } );
  5430. } else {
  5431. if( next[1] != '-' && next.size() > 2 ) {
  5432. std::string opt = "- ";
  5433. for( size_t i = 1; i < next.size(); ++i ) {
  5434. opt[1] = next[i];
  5435. m_tokenBuffer.push_back( { TokenType::Option, opt } );
  5436. }
  5437. } else {
  5438. m_tokenBuffer.push_back( { TokenType::Option, next } );
  5439. }
  5440. }
  5441. } else {
  5442. m_tokenBuffer.push_back( { TokenType::Argument, next } );
  5443. }
  5444. }
  5445. }
  5446. public:
  5447. explicit TokenStream( Args const &args ) : TokenStream( args.m_args.begin(), args.m_args.end() ) {}
  5448. TokenStream( Iterator it, Iterator itEnd ) : it( it ), itEnd( itEnd ) {
  5449. loadBuffer();
  5450. }
  5451. explicit operator bool() const {
  5452. return !m_tokenBuffer.empty() || it != itEnd;
  5453. }
  5454. auto count() const -> size_t { return m_tokenBuffer.size() + (itEnd - it); }
  5455. auto operator*() const -> Token {
  5456. assert( !m_tokenBuffer.empty() );
  5457. return m_tokenBuffer.front();
  5458. }
  5459. auto operator->() const -> Token const * {
  5460. assert( !m_tokenBuffer.empty() );
  5461. return &m_tokenBuffer.front();
  5462. }
  5463. auto operator++() -> TokenStream & {
  5464. if( m_tokenBuffer.size() >= 2 ) {
  5465. m_tokenBuffer.erase( m_tokenBuffer.begin() );
  5466. } else {
  5467. if( it != itEnd )
  5468. ++it;
  5469. loadBuffer();
  5470. }
  5471. return *this;
  5472. }
  5473. };
  5474. class ResultBase {
  5475. public:
  5476. enum Type {
  5477. Ok, LogicError, RuntimeError
  5478. };
  5479. protected:
  5480. ResultBase( Type type ) : m_type( type ) {}
  5481. virtual ~ResultBase() = default;
  5482. virtual void enforceOk() const = 0;
  5483. Type m_type;
  5484. };
  5485. template<typename T>
  5486. class ResultValueBase : public ResultBase {
  5487. public:
  5488. auto value() const -> T const & {
  5489. enforceOk();
  5490. return m_value;
  5491. }
  5492. protected:
  5493. ResultValueBase( Type type ) : ResultBase( type ) {}
  5494. ResultValueBase( ResultValueBase const &other ) : ResultBase( other ) {
  5495. if( m_type == ResultBase::Ok )
  5496. new( &m_value ) T( other.m_value );
  5497. }
  5498. ResultValueBase( Type, T const &value ) : ResultBase( Ok ) {
  5499. new( &m_value ) T( value );
  5500. }
  5501. auto operator=( ResultValueBase const &other ) -> ResultValueBase & {
  5502. if( m_type == ResultBase::Ok )
  5503. m_value.~T();
  5504. ResultBase::operator=(other);
  5505. if( m_type == ResultBase::Ok )
  5506. new( &m_value ) T( other.m_value );
  5507. return *this;
  5508. }
  5509. ~ResultValueBase() override {
  5510. if( m_type == Ok )
  5511. m_value.~T();
  5512. }
  5513. union {
  5514. T m_value;
  5515. };
  5516. };
  5517. template<>
  5518. class ResultValueBase<void> : public ResultBase {
  5519. protected:
  5520. using ResultBase::ResultBase;
  5521. };
  5522. template<typename T = void>
  5523. class BasicResult : public ResultValueBase<T> {
  5524. public:
  5525. template<typename U>
  5526. explicit BasicResult( BasicResult<U> const &other )
  5527. : ResultValueBase<T>( other.type() ),
  5528. m_errorMessage( other.errorMessage() )
  5529. {
  5530. assert( type() != ResultBase::Ok );
  5531. }
  5532. template<typename U>
  5533. static auto ok( U const &value ) -> BasicResult { return { ResultBase::Ok, value }; }
  5534. static auto ok() -> BasicResult { return { ResultBase::Ok }; }
  5535. static auto logicError( std::string const &message ) -> BasicResult { return { ResultBase::LogicError, message }; }
  5536. static auto runtimeError( std::string const &message ) -> BasicResult { return { ResultBase::RuntimeError, message }; }
  5537. explicit operator bool() const { return m_type == ResultBase::Ok; }
  5538. auto type() const -> ResultBase::Type { return m_type; }
  5539. auto errorMessage() const -> std::string { return m_errorMessage; }
  5540. protected:
  5541. void enforceOk() const override {
  5542. // Errors shouldn't reach this point, but if they do
  5543. // the actual error message will be in m_errorMessage
  5544. assert( m_type != ResultBase::LogicError );
  5545. assert( m_type != ResultBase::RuntimeError );
  5546. if( m_type != ResultBase::Ok )
  5547. std::abort();
  5548. }
  5549. std::string m_errorMessage; // Only populated if resultType is an error
  5550. BasicResult( ResultBase::Type type, std::string const &message )
  5551. : ResultValueBase<T>(type),
  5552. m_errorMessage(message)
  5553. {
  5554. assert( m_type != ResultBase::Ok );
  5555. }
  5556. using ResultValueBase<T>::ResultValueBase;
  5557. using ResultBase::m_type;
  5558. };
  5559. enum class ParseResultType {
  5560. Matched, NoMatch, ShortCircuitAll, ShortCircuitSame
  5561. };
  5562. class ParseState {
  5563. public:
  5564. ParseState( ParseResultType type, TokenStream const &remainingTokens )
  5565. : m_type(type),
  5566. m_remainingTokens( remainingTokens )
  5567. {}
  5568. auto type() const -> ParseResultType { return m_type; }
  5569. auto remainingTokens() const -> TokenStream { return m_remainingTokens; }
  5570. private:
  5571. ParseResultType m_type;
  5572. TokenStream m_remainingTokens;
  5573. };
  5574. using Result = BasicResult<void>;
  5575. using ParserResult = BasicResult<ParseResultType>;
  5576. using InternalParseResult = BasicResult<ParseState>;
  5577. struct HelpColumns {
  5578. std::string left;
  5579. std::string right;
  5580. };
  5581. template<typename T>
  5582. inline auto convertInto( std::string const &source, T& target ) -> ParserResult {
  5583. std::stringstream ss;
  5584. ss << source;
  5585. ss >> target;
  5586. if( ss.fail() )
  5587. return ParserResult::runtimeError( "Unable to convert '" + source + "' to destination type" );
  5588. else
  5589. return ParserResult::ok( ParseResultType::Matched );
  5590. }
  5591. inline auto convertInto( std::string const &source, std::string& target ) -> ParserResult {
  5592. target = source;
  5593. return ParserResult::ok( ParseResultType::Matched );
  5594. }
  5595. inline auto convertInto( std::string const &source, bool &target ) -> ParserResult {
  5596. std::string srcLC = source;
  5597. std::transform( srcLC.begin(), srcLC.end(), srcLC.begin(), []( char c ) { return static_cast<char>( ::tolower(c) ); } );
  5598. if (srcLC == "y" || srcLC == "1" || srcLC == "true" || srcLC == "yes" || srcLC == "on")
  5599. target = true;
  5600. else if (srcLC == "n" || srcLC == "0" || srcLC == "false" || srcLC == "no" || srcLC == "off")
  5601. target = false;
  5602. else
  5603. return ParserResult::runtimeError( "Expected a boolean value but did not recognise: '" + source + "'" );
  5604. return ParserResult::ok( ParseResultType::Matched );
  5605. }
  5606. #ifdef CLARA_CONFIG_OPTIONAL_TYPE
  5607. template<typename T>
  5608. inline auto convertInto( std::string const &source, CLARA_CONFIG_OPTIONAL_TYPE<T>& target ) -> ParserResult {
  5609. T temp;
  5610. auto result = convertInto( source, temp );
  5611. if( result )
  5612. target = std::move(temp);
  5613. return result;
  5614. }
  5615. #endif // CLARA_CONFIG_OPTIONAL_TYPE
  5616. struct NonCopyable {
  5617. NonCopyable() = default;
  5618. NonCopyable( NonCopyable const & ) = delete;
  5619. NonCopyable( NonCopyable && ) = delete;
  5620. NonCopyable &operator=( NonCopyable const & ) = delete;
  5621. NonCopyable &operator=( NonCopyable && ) = delete;
  5622. };
  5623. struct BoundRef : NonCopyable {
  5624. virtual ~BoundRef() = default;
  5625. virtual auto isContainer() const -> bool { return false; }
  5626. virtual auto isFlag() const -> bool { return false; }
  5627. };
  5628. struct BoundValueRefBase : BoundRef {
  5629. virtual auto setValue( std::string const &arg ) -> ParserResult = 0;
  5630. };
  5631. struct BoundFlagRefBase : BoundRef {
  5632. virtual auto setFlag( bool flag ) -> ParserResult = 0;
  5633. virtual auto isFlag() const -> bool { return true; }
  5634. };
  5635. template<typename T>
  5636. struct BoundValueRef : BoundValueRefBase {
  5637. T &m_ref;
  5638. explicit BoundValueRef( T &ref ) : m_ref( ref ) {}
  5639. auto setValue( std::string const &arg ) -> ParserResult override {
  5640. return convertInto( arg, m_ref );
  5641. }
  5642. };
  5643. template<typename T>
  5644. struct BoundValueRef<std::vector<T>> : BoundValueRefBase {
  5645. std::vector<T> &m_ref;
  5646. explicit BoundValueRef( std::vector<T> &ref ) : m_ref( ref ) {}
  5647. auto isContainer() const -> bool override { return true; }
  5648. auto setValue( std::string const &arg ) -> ParserResult override {
  5649. T temp;
  5650. auto result = convertInto( arg, temp );
  5651. if( result )
  5652. m_ref.push_back( temp );
  5653. return result;
  5654. }
  5655. };
  5656. struct BoundFlagRef : BoundFlagRefBase {
  5657. bool &m_ref;
  5658. explicit BoundFlagRef( bool &ref ) : m_ref( ref ) {}
  5659. auto setFlag( bool flag ) -> ParserResult override {
  5660. m_ref = flag;
  5661. return ParserResult::ok( ParseResultType::Matched );
  5662. }
  5663. };
  5664. template<typename ReturnType>
  5665. struct LambdaInvoker {
  5666. static_assert( std::is_same<ReturnType, ParserResult>::value, "Lambda must return void or clara::ParserResult" );
  5667. template<typename L, typename ArgType>
  5668. static auto invoke( L const &lambda, ArgType const &arg ) -> ParserResult {
  5669. return lambda( arg );
  5670. }
  5671. };
  5672. template<>
  5673. struct LambdaInvoker<void> {
  5674. template<typename L, typename ArgType>
  5675. static auto invoke( L const &lambda, ArgType const &arg ) -> ParserResult {
  5676. lambda( arg );
  5677. return ParserResult::ok( ParseResultType::Matched );
  5678. }
  5679. };
  5680. template<typename ArgType, typename L>
  5681. inline auto invokeLambda( L const &lambda, std::string const &arg ) -> ParserResult {
  5682. ArgType temp{};
  5683. auto result = convertInto( arg, temp );
  5684. return !result
  5685. ? result
  5686. : LambdaInvoker<typename UnaryLambdaTraits<L>::ReturnType>::invoke( lambda, temp );
  5687. }
  5688. template<typename L>
  5689. struct BoundLambda : BoundValueRefBase {
  5690. L m_lambda;
  5691. static_assert( UnaryLambdaTraits<L>::isValid, "Supplied lambda must take exactly one argument" );
  5692. explicit BoundLambda( L const &lambda ) : m_lambda( lambda ) {}
  5693. auto setValue( std::string const &arg ) -> ParserResult override {
  5694. return invokeLambda<typename UnaryLambdaTraits<L>::ArgType>( m_lambda, arg );
  5695. }
  5696. };
  5697. template<typename L>
  5698. struct BoundFlagLambda : BoundFlagRefBase {
  5699. L m_lambda;
  5700. static_assert( UnaryLambdaTraits<L>::isValid, "Supplied lambda must take exactly one argument" );
  5701. static_assert( std::is_same<typename UnaryLambdaTraits<L>::ArgType, bool>::value, "flags must be boolean" );
  5702. explicit BoundFlagLambda( L const &lambda ) : m_lambda( lambda ) {}
  5703. auto setFlag( bool flag ) -> ParserResult override {
  5704. return LambdaInvoker<typename UnaryLambdaTraits<L>::ReturnType>::invoke( m_lambda, flag );
  5705. }
  5706. };
  5707. enum class Optionality { Optional, Required };
  5708. struct Parser;
  5709. class ParserBase {
  5710. public:
  5711. virtual ~ParserBase() = default;
  5712. virtual auto validate() const -> Result { return Result::ok(); }
  5713. virtual auto parse( std::string const& exeName, TokenStream const &tokens) const -> InternalParseResult = 0;
  5714. virtual auto cardinality() const -> size_t { return 1; }
  5715. auto parse( Args const &args ) const -> InternalParseResult {
  5716. return parse( args.exeName(), TokenStream( args ) );
  5717. }
  5718. };
  5719. template<typename DerivedT>
  5720. class ComposableParserImpl : public ParserBase {
  5721. public:
  5722. template<typename T>
  5723. auto operator|( T const &other ) const -> Parser;
  5724. template<typename T>
  5725. auto operator+( T const &other ) const -> Parser;
  5726. };
  5727. // Common code and state for Args and Opts
  5728. template<typename DerivedT>
  5729. class ParserRefImpl : public ComposableParserImpl<DerivedT> {
  5730. protected:
  5731. Optionality m_optionality = Optionality::Optional;
  5732. std::shared_ptr<BoundRef> m_ref;
  5733. std::string m_hint;
  5734. std::string m_description;
  5735. explicit ParserRefImpl( std::shared_ptr<BoundRef> const &ref ) : m_ref( ref ) {}
  5736. public:
  5737. template<typename T>
  5738. ParserRefImpl( T &ref, std::string const &hint )
  5739. : m_ref( std::make_shared<BoundValueRef<T>>( ref ) ),
  5740. m_hint( hint )
  5741. {}
  5742. template<typename LambdaT>
  5743. ParserRefImpl( LambdaT const &ref, std::string const &hint )
  5744. : m_ref( std::make_shared<BoundLambda<LambdaT>>( ref ) ),
  5745. m_hint(hint)
  5746. {}
  5747. auto operator()( std::string const &description ) -> DerivedT & {
  5748. m_description = description;
  5749. return static_cast<DerivedT &>( *this );
  5750. }
  5751. auto optional() -> DerivedT & {
  5752. m_optionality = Optionality::Optional;
  5753. return static_cast<DerivedT &>( *this );
  5754. };
  5755. auto required() -> DerivedT & {
  5756. m_optionality = Optionality::Required;
  5757. return static_cast<DerivedT &>( *this );
  5758. };
  5759. auto isOptional() const -> bool {
  5760. return m_optionality == Optionality::Optional;
  5761. }
  5762. auto cardinality() const -> size_t override {
  5763. if( m_ref->isContainer() )
  5764. return 0;
  5765. else
  5766. return 1;
  5767. }
  5768. auto hint() const -> std::string { return m_hint; }
  5769. };
  5770. class ExeName : public ComposableParserImpl<ExeName> {
  5771. std::shared_ptr<std::string> m_name;
  5772. std::shared_ptr<BoundValueRefBase> m_ref;
  5773. template<typename LambdaT>
  5774. static auto makeRef(LambdaT const &lambda) -> std::shared_ptr<BoundValueRefBase> {
  5775. return std::make_shared<BoundLambda<LambdaT>>( lambda) ;
  5776. }
  5777. public:
  5778. ExeName() : m_name( std::make_shared<std::string>( "<executable>" ) ) {}
  5779. explicit ExeName( std::string &ref ) : ExeName() {
  5780. m_ref = std::make_shared<BoundValueRef<std::string>>( ref );
  5781. }
  5782. template<typename LambdaT>
  5783. explicit ExeName( LambdaT const& lambda ) : ExeName() {
  5784. m_ref = std::make_shared<BoundLambda<LambdaT>>( lambda );
  5785. }
  5786. // The exe name is not parsed out of the normal tokens, but is handled specially
  5787. auto parse( std::string const&, TokenStream const &tokens ) const -> InternalParseResult override {
  5788. return InternalParseResult::ok( ParseState( ParseResultType::NoMatch, tokens ) );
  5789. }
  5790. auto name() const -> std::string { return *m_name; }
  5791. auto set( std::string const& newName ) -> ParserResult {
  5792. auto lastSlash = newName.find_last_of( "\\/" );
  5793. auto filename = ( lastSlash == std::string::npos )
  5794. ? newName
  5795. : newName.substr( lastSlash+1 );
  5796. *m_name = filename;
  5797. if( m_ref )
  5798. return m_ref->setValue( filename );
  5799. else
  5800. return ParserResult::ok( ParseResultType::Matched );
  5801. }
  5802. };
  5803. class Arg : public ParserRefImpl<Arg> {
  5804. public:
  5805. using ParserRefImpl::ParserRefImpl;
  5806. auto parse( std::string const &, TokenStream const &tokens ) const -> InternalParseResult override {
  5807. auto validationResult = validate();
  5808. if( !validationResult )
  5809. return InternalParseResult( validationResult );
  5810. auto remainingTokens = tokens;
  5811. auto const &token = *remainingTokens;
  5812. if( token.type != TokenType::Argument )
  5813. return InternalParseResult::ok( ParseState( ParseResultType::NoMatch, remainingTokens ) );
  5814. assert( !m_ref->isFlag() );
  5815. auto valueRef = static_cast<detail::BoundValueRefBase*>( m_ref.get() );
  5816. auto result = valueRef->setValue( remainingTokens->token );
  5817. if( !result )
  5818. return InternalParseResult( result );
  5819. else
  5820. return InternalParseResult::ok( ParseState( ParseResultType::Matched, ++remainingTokens ) );
  5821. }
  5822. };
  5823. inline auto normaliseOpt( std::string const &optName ) -> std::string {
  5824. #ifdef CATCH_PLATFORM_WINDOWS
  5825. if( optName[0] == '/' )
  5826. return "-" + optName.substr( 1 );
  5827. else
  5828. #endif
  5829. return optName;
  5830. }
  5831. class Opt : public ParserRefImpl<Opt> {
  5832. protected:
  5833. std::vector<std::string> m_optNames;
  5834. public:
  5835. template<typename LambdaT>
  5836. explicit Opt( LambdaT const &ref ) : ParserRefImpl( std::make_shared<BoundFlagLambda<LambdaT>>( ref ) ) {}
  5837. explicit Opt( bool &ref ) : ParserRefImpl( std::make_shared<BoundFlagRef>( ref ) ) {}
  5838. template<typename LambdaT>
  5839. Opt( LambdaT const &ref, std::string const &hint ) : ParserRefImpl( ref, hint ) {}
  5840. template<typename T>
  5841. Opt( T &ref, std::string const &hint ) : ParserRefImpl( ref, hint ) {}
  5842. auto operator[]( std::string const &optName ) -> Opt & {
  5843. m_optNames.push_back( optName );
  5844. return *this;
  5845. }
  5846. auto getHelpColumns() const -> std::vector<HelpColumns> {
  5847. std::ostringstream oss;
  5848. bool first = true;
  5849. for( auto const &opt : m_optNames ) {
  5850. if (first)
  5851. first = false;
  5852. else
  5853. oss << ", ";
  5854. oss << opt;
  5855. }
  5856. if( !m_hint.empty() )
  5857. oss << " <" << m_hint << ">";
  5858. return { { oss.str(), m_description } };
  5859. }
  5860. auto isMatch( std::string const &optToken ) const -> bool {
  5861. auto normalisedToken = normaliseOpt( optToken );
  5862. for( auto const &name : m_optNames ) {
  5863. if( normaliseOpt( name ) == normalisedToken )
  5864. return true;
  5865. }
  5866. return false;
  5867. }
  5868. using ParserBase::parse;
  5869. auto parse( std::string const&, TokenStream const &tokens ) const -> InternalParseResult override {
  5870. auto validationResult = validate();
  5871. if( !validationResult )
  5872. return InternalParseResult( validationResult );
  5873. auto remainingTokens = tokens;
  5874. if( remainingTokens && remainingTokens->type == TokenType::Option ) {
  5875. auto const &token = *remainingTokens;
  5876. if( isMatch(token.token ) ) {
  5877. if( m_ref->isFlag() ) {
  5878. auto flagRef = static_cast<detail::BoundFlagRefBase*>( m_ref.get() );
  5879. auto result = flagRef->setFlag( true );
  5880. if( !result )
  5881. return InternalParseResult( result );
  5882. if( result.value() == ParseResultType::ShortCircuitAll )
  5883. return InternalParseResult::ok( ParseState( result.value(), remainingTokens ) );
  5884. } else {
  5885. auto valueRef = static_cast<detail::BoundValueRefBase*>( m_ref.get() );
  5886. ++remainingTokens;
  5887. if( !remainingTokens )
  5888. return InternalParseResult::runtimeError( "Expected argument following " + token.token );
  5889. auto const &argToken = *remainingTokens;
  5890. if( argToken.type != TokenType::Argument )
  5891. return InternalParseResult::runtimeError( "Expected argument following " + token.token );
  5892. auto result = valueRef->setValue( argToken.token );
  5893. if( !result )
  5894. return InternalParseResult( result );
  5895. if( result.value() == ParseResultType::ShortCircuitAll )
  5896. return InternalParseResult::ok( ParseState( result.value(), remainingTokens ) );
  5897. }
  5898. return InternalParseResult::ok( ParseState( ParseResultType::Matched, ++remainingTokens ) );
  5899. }
  5900. }
  5901. return InternalParseResult::ok( ParseState( ParseResultType::NoMatch, remainingTokens ) );
  5902. }
  5903. auto validate() const -> Result override {
  5904. if( m_optNames.empty() )
  5905. return Result::logicError( "No options supplied to Opt" );
  5906. for( auto const &name : m_optNames ) {
  5907. if( name.empty() )
  5908. return Result::logicError( "Option name cannot be empty" );
  5909. #ifdef CATCH_PLATFORM_WINDOWS
  5910. if( name[0] != '-' && name[0] != '/' )
  5911. return Result::logicError( "Option name must begin with '-' or '/'" );
  5912. #else
  5913. if( name[0] != '-' )
  5914. return Result::logicError( "Option name must begin with '-'" );
  5915. #endif
  5916. }
  5917. return ParserRefImpl::validate();
  5918. }
  5919. };
  5920. struct Help : Opt {
  5921. Help( bool &showHelpFlag )
  5922. : Opt([&]( bool flag ) {
  5923. showHelpFlag = flag;
  5924. return ParserResult::ok( ParseResultType::ShortCircuitAll );
  5925. })
  5926. {
  5927. static_cast<Opt &>( *this )
  5928. ("display usage information")
  5929. ["-?"]["-h"]["--help"]
  5930. .optional();
  5931. }
  5932. };
  5933. struct Parser : ParserBase {
  5934. mutable ExeName m_exeName;
  5935. std::vector<Opt> m_options;
  5936. std::vector<Arg> m_args;
  5937. auto operator|=( ExeName const &exeName ) -> Parser & {
  5938. m_exeName = exeName;
  5939. return *this;
  5940. }
  5941. auto operator|=( Arg const &arg ) -> Parser & {
  5942. m_args.push_back(arg);
  5943. return *this;
  5944. }
  5945. auto operator|=( Opt const &opt ) -> Parser & {
  5946. m_options.push_back(opt);
  5947. return *this;
  5948. }
  5949. auto operator|=( Parser const &other ) -> Parser & {
  5950. m_options.insert(m_options.end(), other.m_options.begin(), other.m_options.end());
  5951. m_args.insert(m_args.end(), other.m_args.begin(), other.m_args.end());
  5952. return *this;
  5953. }
  5954. template<typename T>
  5955. auto operator|( T const &other ) const -> Parser {
  5956. return Parser( *this ) |= other;
  5957. }
  5958. // Forward deprecated interface with '+' instead of '|'
  5959. template<typename T>
  5960. auto operator+=( T const &other ) -> Parser & { return operator|=( other ); }
  5961. template<typename T>
  5962. auto operator+( T const &other ) const -> Parser { return operator|( other ); }
  5963. auto getHelpColumns() const -> std::vector<HelpColumns> {
  5964. std::vector<HelpColumns> cols;
  5965. for (auto const &o : m_options) {
  5966. auto childCols = o.getHelpColumns();
  5967. cols.insert( cols.end(), childCols.begin(), childCols.end() );
  5968. }
  5969. return cols;
  5970. }
  5971. void writeToStream( std::ostream &os ) const {
  5972. if (!m_exeName.name().empty()) {
  5973. os << "usage:\n" << " " << m_exeName.name() << " ";
  5974. bool required = true, first = true;
  5975. for( auto const &arg : m_args ) {
  5976. if (first)
  5977. first = false;
  5978. else
  5979. os << " ";
  5980. if( arg.isOptional() && required ) {
  5981. os << "[";
  5982. required = false;
  5983. }
  5984. os << "<" << arg.hint() << ">";
  5985. if( arg.cardinality() == 0 )
  5986. os << " ... ";
  5987. }
  5988. if( !required )
  5989. os << "]";
  5990. if( !m_options.empty() )
  5991. os << " options";
  5992. os << "\n\nwhere options are:" << std::endl;
  5993. }
  5994. auto rows = getHelpColumns();
  5995. size_t consoleWidth = CATCH_CLARA_CONFIG_CONSOLE_WIDTH;
  5996. size_t optWidth = 0;
  5997. for( auto const &cols : rows )
  5998. optWidth = (std::max)(optWidth, cols.left.size() + 2);
  5999. optWidth = (std::min)(optWidth, consoleWidth/2);
  6000. for( auto const &cols : rows ) {
  6001. auto row =
  6002. TextFlow::Column( cols.left ).width( optWidth ).indent( 2 ) +
  6003. TextFlow::Spacer(4) +
  6004. TextFlow::Column( cols.right ).width( consoleWidth - 7 - optWidth );
  6005. os << row << std::endl;
  6006. }
  6007. }
  6008. friend auto operator<<( std::ostream &os, Parser const &parser ) -> std::ostream& {
  6009. parser.writeToStream( os );
  6010. return os;
  6011. }
  6012. auto validate() const -> Result override {
  6013. for( auto const &opt : m_options ) {
  6014. auto result = opt.validate();
  6015. if( !result )
  6016. return result;
  6017. }
  6018. for( auto const &arg : m_args ) {
  6019. auto result = arg.validate();
  6020. if( !result )
  6021. return result;
  6022. }
  6023. return Result::ok();
  6024. }
  6025. using ParserBase::parse;
  6026. auto parse( std::string const& exeName, TokenStream const &tokens ) const -> InternalParseResult override {
  6027. struct ParserInfo {
  6028. ParserBase const* parser = nullptr;
  6029. size_t count = 0;
  6030. };
  6031. const size_t totalParsers = m_options.size() + m_args.size();
  6032. assert( totalParsers < 512 );
  6033. // ParserInfo parseInfos[totalParsers]; // <-- this is what we really want to do
  6034. ParserInfo parseInfos[512];
  6035. {
  6036. size_t i = 0;
  6037. for (auto const &opt : m_options) parseInfos[i++].parser = &opt;
  6038. for (auto const &arg : m_args) parseInfos[i++].parser = &arg;
  6039. }
  6040. m_exeName.set( exeName );
  6041. auto result = InternalParseResult::ok( ParseState( ParseResultType::NoMatch, tokens ) );
  6042. while( result.value().remainingTokens() ) {
  6043. bool tokenParsed = false;
  6044. for( size_t i = 0; i < totalParsers; ++i ) {
  6045. auto& parseInfo = parseInfos[i];
  6046. if( parseInfo.parser->cardinality() == 0 || parseInfo.count < parseInfo.parser->cardinality() ) {
  6047. result = parseInfo.parser->parse(exeName, result.value().remainingTokens());
  6048. if (!result)
  6049. return result;
  6050. if (result.value().type() != ParseResultType::NoMatch) {
  6051. tokenParsed = true;
  6052. ++parseInfo.count;
  6053. break;
  6054. }
  6055. }
  6056. }
  6057. if( result.value().type() == ParseResultType::ShortCircuitAll )
  6058. return result;
  6059. if( !tokenParsed )
  6060. return InternalParseResult::runtimeError( "Unrecognised token: " + result.value().remainingTokens()->token );
  6061. }
  6062. // !TBD Check missing required options
  6063. return result;
  6064. }
  6065. };
  6066. template<typename DerivedT>
  6067. template<typename T>
  6068. auto ComposableParserImpl<DerivedT>::operator|( T const &other ) const -> Parser {
  6069. return Parser() | static_cast<DerivedT const &>( *this ) | other;
  6070. }
  6071. } // namespace detail
  6072. // A Combined parser
  6073. using detail::Parser;
  6074. // A parser for options
  6075. using detail::Opt;
  6076. // A parser for arguments
  6077. using detail::Arg;
  6078. // Wrapper for argc, argv from main()
  6079. using detail::Args;
  6080. // Specifies the name of the executable
  6081. using detail::ExeName;
  6082. // Convenience wrapper for option parser that specifies the help option
  6083. using detail::Help;
  6084. // enum of result types from a parse
  6085. using detail::ParseResultType;
  6086. // Result type for parser operation
  6087. using detail::ParserResult;
  6088. }} // namespace Catch::clara
  6089. // end clara.hpp
  6090. #ifdef __clang__
  6091. #pragma clang diagnostic pop
  6092. #endif
  6093. // Restore Clara's value for console width, if present
  6094. #ifdef CATCH_TEMP_CLARA_CONFIG_CONSOLE_WIDTH
  6095. #define CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH CATCH_TEMP_CLARA_CONFIG_CONSOLE_WIDTH
  6096. #undef CATCH_TEMP_CLARA_CONFIG_CONSOLE_WIDTH
  6097. #endif
  6098. // end catch_clara.h
  6099. namespace Catch {
  6100. clara::Parser makeCommandLineParser( ConfigData& config );
  6101. } // end namespace Catch
  6102. // end catch_commandline.h
  6103. #include <fstream>
  6104. #include <ctime>
  6105. namespace Catch {
  6106. clara::Parser makeCommandLineParser( ConfigData& config ) {
  6107. using namespace clara;
  6108. auto const setWarning = [&]( std::string const& warning ) {
  6109. auto warningSet = [&]() {
  6110. if( warning == "NoAssertions" )
  6111. return WarnAbout::NoAssertions;
  6112. if ( warning == "NoTests" )
  6113. return WarnAbout::NoTests;
  6114. return WarnAbout::Nothing;
  6115. }();
  6116. if (warningSet == WarnAbout::Nothing)
  6117. return ParserResult::runtimeError( "Unrecognised warning: '" + warning + "'" );
  6118. config.warnings = static_cast<WarnAbout::What>( config.warnings | warningSet );
  6119. return ParserResult::ok( ParseResultType::Matched );
  6120. };
  6121. auto const loadTestNamesFromFile = [&]( std::string const& filename ) {
  6122. std::ifstream f( filename.c_str() );
  6123. if( !f.is_open() )
  6124. return ParserResult::runtimeError( "Unable to load input file: '" + filename + "'" );
  6125. std::string line;
  6126. while( std::getline( f, line ) ) {
  6127. line = trim(line);
  6128. if( !line.empty() && !startsWith( line, '#' ) ) {
  6129. if( !startsWith( line, '"' ) )
  6130. line = '"' + line + '"';
  6131. config.testsOrTags.push_back( line + ',' );
  6132. }
  6133. }
  6134. return ParserResult::ok( ParseResultType::Matched );
  6135. };
  6136. auto const setTestOrder = [&]( std::string const& order ) {
  6137. if( startsWith( "declared", order ) )
  6138. config.runOrder = RunTests::InDeclarationOrder;
  6139. else if( startsWith( "lexical", order ) )
  6140. config.runOrder = RunTests::InLexicographicalOrder;
  6141. else if( startsWith( "random", order ) )
  6142. config.runOrder = RunTests::InRandomOrder;
  6143. else
  6144. return clara::ParserResult::runtimeError( "Unrecognised ordering: '" + order + "'" );
  6145. return ParserResult::ok( ParseResultType::Matched );
  6146. };
  6147. auto const setRngSeed = [&]( std::string const& seed ) {
  6148. if( seed != "time" )
  6149. return clara::detail::convertInto( seed, config.rngSeed );
  6150. config.rngSeed = static_cast<unsigned int>( std::time(nullptr) );
  6151. return ParserResult::ok( ParseResultType::Matched );
  6152. };
  6153. auto const setColourUsage = [&]( std::string const& useColour ) {
  6154. auto mode = toLower( useColour );
  6155. if( mode == "yes" )
  6156. config.useColour = UseColour::Yes;
  6157. else if( mode == "no" )
  6158. config.useColour = UseColour::No;
  6159. else if( mode == "auto" )
  6160. config.useColour = UseColour::Auto;
  6161. else
  6162. return ParserResult::runtimeError( "colour mode must be one of: auto, yes or no. '" + useColour + "' not recognised" );
  6163. return ParserResult::ok( ParseResultType::Matched );
  6164. };
  6165. auto const setWaitForKeypress = [&]( std::string const& keypress ) {
  6166. auto keypressLc = toLower( keypress );
  6167. if( keypressLc == "start" )
  6168. config.waitForKeypress = WaitForKeypress::BeforeStart;
  6169. else if( keypressLc == "exit" )
  6170. config.waitForKeypress = WaitForKeypress::BeforeExit;
  6171. else if( keypressLc == "both" )
  6172. config.waitForKeypress = WaitForKeypress::BeforeStartAndExit;
  6173. else
  6174. return ParserResult::runtimeError( "keypress argument must be one of: start, exit or both. '" + keypress + "' not recognised" );
  6175. return ParserResult::ok( ParseResultType::Matched );
  6176. };
  6177. auto const setVerbosity = [&]( std::string const& verbosity ) {
  6178. auto lcVerbosity = toLower( verbosity );
  6179. if( lcVerbosity == "quiet" )
  6180. config.verbosity = Verbosity::Quiet;
  6181. else if( lcVerbosity == "normal" )
  6182. config.verbosity = Verbosity::Normal;
  6183. else if( lcVerbosity == "high" )
  6184. config.verbosity = Verbosity::High;
  6185. else
  6186. return ParserResult::runtimeError( "Unrecognised verbosity, '" + verbosity + "'" );
  6187. return ParserResult::ok( ParseResultType::Matched );
  6188. };
  6189. auto const setReporter = [&]( std::string const& reporter ) {
  6190. IReporterRegistry::FactoryMap const& factories = getRegistryHub().getReporterRegistry().getFactories();
  6191. auto lcReporter = toLower( reporter );
  6192. auto result = factories.find( lcReporter );
  6193. if( factories.end() != result )
  6194. config.reporterName = lcReporter;
  6195. else
  6196. return ParserResult::runtimeError( "Unrecognized reporter, '" + reporter + "'. Check available with --list-reporters" );
  6197. return ParserResult::ok( ParseResultType::Matched );
  6198. };
  6199. auto cli
  6200. = ExeName( config.processName )
  6201. | Help( config.showHelp )
  6202. | Opt( config.listTests )
  6203. ["-l"]["--list-tests"]
  6204. ( "list all/matching test cases" )
  6205. | Opt( config.listTags )
  6206. ["-t"]["--list-tags"]
  6207. ( "list all/matching tags" )
  6208. | Opt( config.showSuccessfulTests )
  6209. ["-s"]["--success"]
  6210. ( "include successful tests in output" )
  6211. | Opt( config.shouldDebugBreak )
  6212. ["-b"]["--break"]
  6213. ( "break into debugger on failure" )
  6214. | Opt( config.noThrow )
  6215. ["-e"]["--nothrow"]
  6216. ( "skip exception tests" )
  6217. | Opt( config.showInvisibles )
  6218. ["-i"]["--invisibles"]
  6219. ( "show invisibles (tabs, newlines)" )
  6220. | Opt( config.outputFilename, "filename" )
  6221. ["-o"]["--out"]
  6222. ( "output filename" )
  6223. | Opt( setReporter, "name" )
  6224. ["-r"]["--reporter"]
  6225. ( "reporter to use (defaults to console)" )
  6226. | Opt( config.name, "name" )
  6227. ["-n"]["--name"]
  6228. ( "suite name" )
  6229. | Opt( [&]( bool ){ config.abortAfter = 1; } )
  6230. ["-a"]["--abort"]
  6231. ( "abort at first failure" )
  6232. | Opt( [&]( int x ){ config.abortAfter = x; }, "no. failures" )
  6233. ["-x"]["--abortx"]
  6234. ( "abort after x failures" )
  6235. | Opt( setWarning, "warning name" )
  6236. ["-w"]["--warn"]
  6237. ( "enable warnings" )
  6238. | Opt( [&]( bool flag ) { config.showDurations = flag ? ShowDurations::Always : ShowDurations::Never; }, "yes|no" )
  6239. ["-d"]["--durations"]
  6240. ( "show test durations" )
  6241. | Opt( loadTestNamesFromFile, "filename" )
  6242. ["-f"]["--input-file"]
  6243. ( "load test names to run from a file" )
  6244. | Opt( config.filenamesAsTags )
  6245. ["-#"]["--filenames-as-tags"]
  6246. ( "adds a tag for the filename" )
  6247. | Opt( config.sectionsToRun, "section name" )
  6248. ["-c"]["--section"]
  6249. ( "specify section to run" )
  6250. | Opt( setVerbosity, "quiet|normal|high" )
  6251. ["-v"]["--verbosity"]
  6252. ( "set output verbosity" )
  6253. | Opt( config.listTestNamesOnly )
  6254. ["--list-test-names-only"]
  6255. ( "list all/matching test cases names only" )
  6256. | Opt( config.listReporters )
  6257. ["--list-reporters"]
  6258. ( "list all reporters" )
  6259. | Opt( setTestOrder, "decl|lex|rand" )
  6260. ["--order"]
  6261. ( "test case order (defaults to decl)" )
  6262. | Opt( setRngSeed, "'time'|number" )
  6263. ["--rng-seed"]
  6264. ( "set a specific seed for random numbers" )
  6265. | Opt( setColourUsage, "yes|no" )
  6266. ["--use-colour"]
  6267. ( "should output be colourised" )
  6268. | Opt( config.libIdentify )
  6269. ["--libidentify"]
  6270. ( "report name and version according to libidentify standard" )
  6271. | Opt( setWaitForKeypress, "start|exit|both" )
  6272. ["--wait-for-keypress"]
  6273. ( "waits for a keypress before exiting" )
  6274. | Opt( config.benchmarkResolutionMultiple, "multiplier" )
  6275. ["--benchmark-resolution-multiple"]
  6276. ( "multiple of clock resolution to run benchmarks" )
  6277. | Arg( config.testsOrTags, "test name|pattern|tags" )
  6278. ( "which test or tests to use" );
  6279. return cli;
  6280. }
  6281. } // end namespace Catch
  6282. // end catch_commandline.cpp
  6283. // start catch_common.cpp
  6284. #include <cstring>
  6285. #include <ostream>
  6286. namespace Catch {
  6287. bool SourceLineInfo::empty() const noexcept {
  6288. return file[0] == '\0';
  6289. }
  6290. bool SourceLineInfo::operator == ( SourceLineInfo const& other ) const noexcept {
  6291. return line == other.line && (file == other.file || std::strcmp(file, other.file) == 0);
  6292. }
  6293. bool SourceLineInfo::operator < ( SourceLineInfo const& other ) const noexcept {
  6294. // We can assume that the same file will usually have the same pointer.
  6295. // Thus, if the pointers are the same, there is no point in calling the strcmp
  6296. return line < other.line || ( line == other.line && file != other.file && (std::strcmp(file, other.file) < 0));
  6297. }
  6298. std::ostream& operator << ( std::ostream& os, SourceLineInfo const& info ) {
  6299. #ifndef __GNUG__
  6300. os << info.file << '(' << info.line << ')';
  6301. #else
  6302. os << info.file << ':' << info.line;
  6303. #endif
  6304. return os;
  6305. }
  6306. std::string StreamEndStop::operator+() const {
  6307. return std::string();
  6308. }
  6309. NonCopyable::NonCopyable() = default;
  6310. NonCopyable::~NonCopyable() = default;
  6311. }
  6312. // end catch_common.cpp
  6313. // start catch_config.cpp
  6314. namespace Catch {
  6315. Config::Config( ConfigData const& data )
  6316. : m_data( data ),
  6317. m_stream( openStream() )
  6318. {
  6319. TestSpecParser parser(ITagAliasRegistry::get());
  6320. if (data.testsOrTags.empty()) {
  6321. parser.parse("~[.]"); // All not hidden tests
  6322. }
  6323. else {
  6324. m_hasTestFilters = true;
  6325. for( auto const& testOrTags : data.testsOrTags )
  6326. parser.parse( testOrTags );
  6327. }
  6328. m_testSpec = parser.testSpec();
  6329. }
  6330. std::string const& Config::getFilename() const {
  6331. return m_data.outputFilename ;
  6332. }
  6333. bool Config::listTests() const { return m_data.listTests; }
  6334. bool Config::listTestNamesOnly() const { return m_data.listTestNamesOnly; }
  6335. bool Config::listTags() const { return m_data.listTags; }
  6336. bool Config::listReporters() const { return m_data.listReporters; }
  6337. std::string Config::getProcessName() const { return m_data.processName; }
  6338. std::string const& Config::getReporterName() const { return m_data.reporterName; }
  6339. std::vector<std::string> const& Config::getTestsOrTags() const { return m_data.testsOrTags; }
  6340. std::vector<std::string> const& Config::getSectionsToRun() const { return m_data.sectionsToRun; }
  6341. TestSpec const& Config::testSpec() const { return m_testSpec; }
  6342. bool Config::hasTestFilters() const { return m_hasTestFilters; }
  6343. bool Config::showHelp() const { return m_data.showHelp; }
  6344. // IConfig interface
  6345. bool Config::allowThrows() const { return !m_data.noThrow; }
  6346. std::ostream& Config::stream() const { return m_stream->stream(); }
  6347. std::string Config::name() const { return m_data.name.empty() ? m_data.processName : m_data.name; }
  6348. bool Config::includeSuccessfulResults() const { return m_data.showSuccessfulTests; }
  6349. bool Config::warnAboutMissingAssertions() const { return !!(m_data.warnings & WarnAbout::NoAssertions); }
  6350. bool Config::warnAboutNoTests() const { return !!(m_data.warnings & WarnAbout::NoTests); }
  6351. ShowDurations::OrNot Config::showDurations() const { return m_data.showDurations; }
  6352. RunTests::InWhatOrder Config::runOrder() const { return m_data.runOrder; }
  6353. unsigned int Config::rngSeed() const { return m_data.rngSeed; }
  6354. int Config::benchmarkResolutionMultiple() const { return m_data.benchmarkResolutionMultiple; }
  6355. UseColour::YesOrNo Config::useColour() const { return m_data.useColour; }
  6356. bool Config::shouldDebugBreak() const { return m_data.shouldDebugBreak; }
  6357. int Config::abortAfter() const { return m_data.abortAfter; }
  6358. bool Config::showInvisibles() const { return m_data.showInvisibles; }
  6359. Verbosity Config::verbosity() const { return m_data.verbosity; }
  6360. IStream const* Config::openStream() {
  6361. return Catch::makeStream(m_data.outputFilename);
  6362. }
  6363. } // end namespace Catch
  6364. // end catch_config.cpp
  6365. // start catch_console_colour.cpp
  6366. #if defined(__clang__)
  6367. # pragma clang diagnostic push
  6368. # pragma clang diagnostic ignored "-Wexit-time-destructors"
  6369. #endif
  6370. // start catch_errno_guard.h
  6371. namespace Catch {
  6372. class ErrnoGuard {
  6373. public:
  6374. ErrnoGuard();
  6375. ~ErrnoGuard();
  6376. private:
  6377. int m_oldErrno;
  6378. };
  6379. }
  6380. // end catch_errno_guard.h
  6381. #include <sstream>
  6382. namespace Catch {
  6383. namespace {
  6384. struct IColourImpl {
  6385. virtual ~IColourImpl() = default;
  6386. virtual void use( Colour::Code _colourCode ) = 0;
  6387. };
  6388. struct NoColourImpl : IColourImpl {
  6389. void use( Colour::Code ) {}
  6390. static IColourImpl* instance() {
  6391. static NoColourImpl s_instance;
  6392. return &s_instance;
  6393. }
  6394. };
  6395. } // anon namespace
  6396. } // namespace Catch
  6397. #if !defined( CATCH_CONFIG_COLOUR_NONE ) && !defined( CATCH_CONFIG_COLOUR_WINDOWS ) && !defined( CATCH_CONFIG_COLOUR_ANSI )
  6398. # ifdef CATCH_PLATFORM_WINDOWS
  6399. # define CATCH_CONFIG_COLOUR_WINDOWS
  6400. # else
  6401. # define CATCH_CONFIG_COLOUR_ANSI
  6402. # endif
  6403. #endif
  6404. #if defined ( CATCH_CONFIG_COLOUR_WINDOWS ) /////////////////////////////////////////
  6405. namespace Catch {
  6406. namespace {
  6407. class Win32ColourImpl : public IColourImpl {
  6408. public:
  6409. Win32ColourImpl() : stdoutHandle( GetStdHandle(STD_OUTPUT_HANDLE) )
  6410. {
  6411. CONSOLE_SCREEN_BUFFER_INFO csbiInfo;
  6412. GetConsoleScreenBufferInfo( stdoutHandle, &csbiInfo );
  6413. originalForegroundAttributes = csbiInfo.wAttributes & ~( BACKGROUND_GREEN | BACKGROUND_RED | BACKGROUND_BLUE | BACKGROUND_INTENSITY );
  6414. originalBackgroundAttributes = csbiInfo.wAttributes & ~( FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_BLUE | FOREGROUND_INTENSITY );
  6415. }
  6416. virtual void use( Colour::Code _colourCode ) override {
  6417. switch( _colourCode ) {
  6418. case Colour::None: return setTextAttribute( originalForegroundAttributes );
  6419. case Colour::White: return setTextAttribute( FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_BLUE );
  6420. case Colour::Red: return setTextAttribute( FOREGROUND_RED );
  6421. case Colour::Green: return setTextAttribute( FOREGROUND_GREEN );
  6422. case Colour::Blue: return setTextAttribute( FOREGROUND_BLUE );
  6423. case Colour::Cyan: return setTextAttribute( FOREGROUND_BLUE | FOREGROUND_GREEN );
  6424. case Colour::Yellow: return setTextAttribute( FOREGROUND_RED | FOREGROUND_GREEN );
  6425. case Colour::Grey: return setTextAttribute( 0 );
  6426. case Colour::LightGrey: return setTextAttribute( FOREGROUND_INTENSITY );
  6427. case Colour::BrightRed: return setTextAttribute( FOREGROUND_INTENSITY | FOREGROUND_RED );
  6428. case Colour::BrightGreen: return setTextAttribute( FOREGROUND_INTENSITY | FOREGROUND_GREEN );
  6429. case Colour::BrightWhite: return setTextAttribute( FOREGROUND_INTENSITY | FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_BLUE );
  6430. case Colour::BrightYellow: return setTextAttribute( FOREGROUND_INTENSITY | FOREGROUND_RED | FOREGROUND_GREEN );
  6431. case Colour::Bright: CATCH_INTERNAL_ERROR( "not a colour" );
  6432. default:
  6433. CATCH_ERROR( "Unknown colour requested" );
  6434. }
  6435. }
  6436. private:
  6437. void setTextAttribute( WORD _textAttribute ) {
  6438. SetConsoleTextAttribute( stdoutHandle, _textAttribute | originalBackgroundAttributes );
  6439. }
  6440. HANDLE stdoutHandle;
  6441. WORD originalForegroundAttributes;
  6442. WORD originalBackgroundAttributes;
  6443. };
  6444. IColourImpl* platformColourInstance() {
  6445. static Win32ColourImpl s_instance;
  6446. IConfigPtr config = getCurrentContext().getConfig();
  6447. UseColour::YesOrNo colourMode = config
  6448. ? config->useColour()
  6449. : UseColour::Auto;
  6450. if( colourMode == UseColour::Auto )
  6451. colourMode = UseColour::Yes;
  6452. return colourMode == UseColour::Yes
  6453. ? &s_instance
  6454. : NoColourImpl::instance();
  6455. }
  6456. } // end anon namespace
  6457. } // end namespace Catch
  6458. #elif defined( CATCH_CONFIG_COLOUR_ANSI ) //////////////////////////////////////
  6459. #include <unistd.h>
  6460. namespace Catch {
  6461. namespace {
  6462. // use POSIX/ ANSI console terminal codes
  6463. // Thanks to Adam Strzelecki for original contribution
  6464. // (http://github.com/nanoant)
  6465. // https://github.com/philsquared/Catch/pull/131
  6466. class PosixColourImpl : public IColourImpl {
  6467. public:
  6468. virtual void use( Colour::Code _colourCode ) override {
  6469. switch( _colourCode ) {
  6470. case Colour::None:
  6471. case Colour::White: return setColour( "[0m" );
  6472. case Colour::Red: return setColour( "[0;31m" );
  6473. case Colour::Green: return setColour( "[0;32m" );
  6474. case Colour::Blue: return setColour( "[0;34m" );
  6475. case Colour::Cyan: return setColour( "[0;36m" );
  6476. case Colour::Yellow: return setColour( "[0;33m" );
  6477. case Colour::Grey: return setColour( "[1;30m" );
  6478. case Colour::LightGrey: return setColour( "[0;37m" );
  6479. case Colour::BrightRed: return setColour( "[1;31m" );
  6480. case Colour::BrightGreen: return setColour( "[1;32m" );
  6481. case Colour::BrightWhite: return setColour( "[1;37m" );
  6482. case Colour::BrightYellow: return setColour( "[1;33m" );
  6483. case Colour::Bright: CATCH_INTERNAL_ERROR( "not a colour" );
  6484. default: CATCH_INTERNAL_ERROR( "Unknown colour requested" );
  6485. }
  6486. }
  6487. static IColourImpl* instance() {
  6488. static PosixColourImpl s_instance;
  6489. return &s_instance;
  6490. }
  6491. private:
  6492. void setColour( const char* _escapeCode ) {
  6493. getCurrentContext().getConfig()->stream()
  6494. << '\033' << _escapeCode;
  6495. }
  6496. };
  6497. bool useColourOnPlatform() {
  6498. return
  6499. #ifdef CATCH_PLATFORM_MAC
  6500. !isDebuggerActive() &&
  6501. #endif
  6502. #if !(defined(__DJGPP__) && defined(__STRICT_ANSI__))
  6503. isatty(STDOUT_FILENO)
  6504. #else
  6505. false
  6506. #endif
  6507. ;
  6508. }
  6509. IColourImpl* platformColourInstance() {
  6510. ErrnoGuard guard;
  6511. IConfigPtr config = getCurrentContext().getConfig();
  6512. UseColour::YesOrNo colourMode = config
  6513. ? config->useColour()
  6514. : UseColour::Auto;
  6515. if( colourMode == UseColour::Auto )
  6516. colourMode = useColourOnPlatform()
  6517. ? UseColour::Yes
  6518. : UseColour::No;
  6519. return colourMode == UseColour::Yes
  6520. ? PosixColourImpl::instance()
  6521. : NoColourImpl::instance();
  6522. }
  6523. } // end anon namespace
  6524. } // end namespace Catch
  6525. #else // not Windows or ANSI ///////////////////////////////////////////////
  6526. namespace Catch {
  6527. static IColourImpl* platformColourInstance() { return NoColourImpl::instance(); }
  6528. } // end namespace Catch
  6529. #endif // Windows/ ANSI/ None
  6530. namespace Catch {
  6531. Colour::Colour( Code _colourCode ) { use( _colourCode ); }
  6532. Colour::Colour( Colour&& rhs ) noexcept {
  6533. m_moved = rhs.m_moved;
  6534. rhs.m_moved = true;
  6535. }
  6536. Colour& Colour::operator=( Colour&& rhs ) noexcept {
  6537. m_moved = rhs.m_moved;
  6538. rhs.m_moved = true;
  6539. return *this;
  6540. }
  6541. Colour::~Colour(){ if( !m_moved ) use( None ); }
  6542. void Colour::use( Code _colourCode ) {
  6543. static IColourImpl* impl = platformColourInstance();
  6544. impl->use( _colourCode );
  6545. }
  6546. std::ostream& operator << ( std::ostream& os, Colour const& ) {
  6547. return os;
  6548. }
  6549. } // end namespace Catch
  6550. #if defined(__clang__)
  6551. # pragma clang diagnostic pop
  6552. #endif
  6553. // end catch_console_colour.cpp
  6554. // start catch_context.cpp
  6555. namespace Catch {
  6556. class Context : public IMutableContext, NonCopyable {
  6557. public: // IContext
  6558. virtual IResultCapture* getResultCapture() override {
  6559. return m_resultCapture;
  6560. }
  6561. virtual IRunner* getRunner() override {
  6562. return m_runner;
  6563. }
  6564. virtual IConfigPtr const& getConfig() const override {
  6565. return m_config;
  6566. }
  6567. virtual ~Context() override;
  6568. public: // IMutableContext
  6569. virtual void setResultCapture( IResultCapture* resultCapture ) override {
  6570. m_resultCapture = resultCapture;
  6571. }
  6572. virtual void setRunner( IRunner* runner ) override {
  6573. m_runner = runner;
  6574. }
  6575. virtual void setConfig( IConfigPtr const& config ) override {
  6576. m_config = config;
  6577. }
  6578. friend IMutableContext& getCurrentMutableContext();
  6579. private:
  6580. IConfigPtr m_config;
  6581. IRunner* m_runner = nullptr;
  6582. IResultCapture* m_resultCapture = nullptr;
  6583. };
  6584. IMutableContext *IMutableContext::currentContext = nullptr;
  6585. void IMutableContext::createContext()
  6586. {
  6587. currentContext = new Context();
  6588. }
  6589. void cleanUpContext() {
  6590. delete IMutableContext::currentContext;
  6591. IMutableContext::currentContext = nullptr;
  6592. }
  6593. IContext::~IContext() = default;
  6594. IMutableContext::~IMutableContext() = default;
  6595. Context::~Context() = default;
  6596. }
  6597. // end catch_context.cpp
  6598. // start catch_debug_console.cpp
  6599. // start catch_debug_console.h
  6600. #include <string>
  6601. namespace Catch {
  6602. void writeToDebugConsole( std::string const& text );
  6603. }
  6604. // end catch_debug_console.h
  6605. #ifdef CATCH_PLATFORM_WINDOWS
  6606. namespace Catch {
  6607. void writeToDebugConsole( std::string const& text ) {
  6608. ::OutputDebugStringA( text.c_str() );
  6609. }
  6610. }
  6611. #else
  6612. namespace Catch {
  6613. void writeToDebugConsole( std::string const& text ) {
  6614. // !TBD: Need a version for Mac/ XCode and other IDEs
  6615. Catch::cout() << text;
  6616. }
  6617. }
  6618. #endif // Platform
  6619. // end catch_debug_console.cpp
  6620. // start catch_debugger.cpp
  6621. #ifdef CATCH_PLATFORM_MAC
  6622. # include <assert.h>
  6623. # include <stdbool.h>
  6624. # include <sys/types.h>
  6625. # include <unistd.h>
  6626. # include <sys/sysctl.h>
  6627. # include <cstddef>
  6628. # include <ostream>
  6629. namespace Catch {
  6630. // The following function is taken directly from the following technical note:
  6631. // http://developer.apple.com/library/mac/#qa/qa2004/qa1361.html
  6632. // Returns true if the current process is being debugged (either
  6633. // running under the debugger or has a debugger attached post facto).
  6634. bool isDebuggerActive(){
  6635. int mib[4];
  6636. struct kinfo_proc info;
  6637. std::size_t size;
  6638. // Initialize the flags so that, if sysctl fails for some bizarre
  6639. // reason, we get a predictable result.
  6640. info.kp_proc.p_flag = 0;
  6641. // Initialize mib, which tells sysctl the info we want, in this case
  6642. // we're looking for information about a specific process ID.
  6643. mib[0] = CTL_KERN;
  6644. mib[1] = KERN_PROC;
  6645. mib[2] = KERN_PROC_PID;
  6646. mib[3] = getpid();
  6647. // Call sysctl.
  6648. size = sizeof(info);
  6649. if( sysctl(mib, sizeof(mib) / sizeof(*mib), &info, &size, nullptr, 0) != 0 ) {
  6650. Catch::cerr() << "\n** Call to sysctl failed - unable to determine if debugger is active **\n" << std::endl;
  6651. return false;
  6652. }
  6653. // We're being debugged if the P_TRACED flag is set.
  6654. return ( (info.kp_proc.p_flag & P_TRACED) != 0 );
  6655. }
  6656. } // namespace Catch
  6657. #elif defined(CATCH_PLATFORM_LINUX)
  6658. #include <fstream>
  6659. #include <string>
  6660. namespace Catch{
  6661. // The standard POSIX way of detecting a debugger is to attempt to
  6662. // ptrace() the process, but this needs to be done from a child and not
  6663. // this process itself to still allow attaching to this process later
  6664. // if wanted, so is rather heavy. Under Linux we have the PID of the
  6665. // "debugger" (which doesn't need to be gdb, of course, it could also
  6666. // be strace, for example) in /proc/$PID/status, so just get it from
  6667. // there instead.
  6668. bool isDebuggerActive(){
  6669. // Libstdc++ has a bug, where std::ifstream sets errno to 0
  6670. // This way our users can properly assert over errno values
  6671. ErrnoGuard guard;
  6672. std::ifstream in("/proc/self/status");
  6673. for( std::string line; std::getline(in, line); ) {
  6674. static const int PREFIX_LEN = 11;
  6675. if( line.compare(0, PREFIX_LEN, "TracerPid:\t") == 0 ) {
  6676. // We're traced if the PID is not 0 and no other PID starts
  6677. // with 0 digit, so it's enough to check for just a single
  6678. // character.
  6679. return line.length() > PREFIX_LEN && line[PREFIX_LEN] != '0';
  6680. }
  6681. }
  6682. return false;
  6683. }
  6684. } // namespace Catch
  6685. #elif defined(_MSC_VER)
  6686. extern "C" __declspec(dllimport) int __stdcall IsDebuggerPresent();
  6687. namespace Catch {
  6688. bool isDebuggerActive() {
  6689. return IsDebuggerPresent() != 0;
  6690. }
  6691. }
  6692. #elif defined(__MINGW32__)
  6693. extern "C" __declspec(dllimport) int __stdcall IsDebuggerPresent();
  6694. namespace Catch {
  6695. bool isDebuggerActive() {
  6696. return IsDebuggerPresent() != 0;
  6697. }
  6698. }
  6699. #else
  6700. namespace Catch {
  6701. bool isDebuggerActive() { return false; }
  6702. }
  6703. #endif // Platform
  6704. // end catch_debugger.cpp
  6705. // start catch_decomposer.cpp
  6706. namespace Catch {
  6707. ITransientExpression::~ITransientExpression() = default;
  6708. void formatReconstructedExpression( std::ostream &os, std::string const& lhs, StringRef op, std::string const& rhs ) {
  6709. if( lhs.size() + rhs.size() < 40 &&
  6710. lhs.find('\n') == std::string::npos &&
  6711. rhs.find('\n') == std::string::npos )
  6712. os << lhs << " " << op << " " << rhs;
  6713. else
  6714. os << lhs << "\n" << op << "\n" << rhs;
  6715. }
  6716. }
  6717. // end catch_decomposer.cpp
  6718. // start catch_enforce.cpp
  6719. namespace Catch {
  6720. #if defined(CATCH_CONFIG_DISABLE_EXCEPTIONS) && !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS_CUSTOM_HANDLER)
  6721. [[noreturn]]
  6722. void throw_exception(std::exception const& e) {
  6723. Catch::cerr() << "Catch will terminate because it needed to throw an exception.\n"
  6724. << "The message was: " << e.what() << '\n';
  6725. std::terminate();
  6726. }
  6727. #endif
  6728. } // namespace Catch;
  6729. // end catch_enforce.cpp
  6730. // start catch_errno_guard.cpp
  6731. #include <cerrno>
  6732. namespace Catch {
  6733. ErrnoGuard::ErrnoGuard():m_oldErrno(errno){}
  6734. ErrnoGuard::~ErrnoGuard() { errno = m_oldErrno; }
  6735. }
  6736. // end catch_errno_guard.cpp
  6737. // start catch_exception_translator_registry.cpp
  6738. // start catch_exception_translator_registry.h
  6739. #include <vector>
  6740. #include <string>
  6741. #include <memory>
  6742. namespace Catch {
  6743. class ExceptionTranslatorRegistry : public IExceptionTranslatorRegistry {
  6744. public:
  6745. ~ExceptionTranslatorRegistry();
  6746. virtual void registerTranslator( const IExceptionTranslator* translator );
  6747. virtual std::string translateActiveException() const override;
  6748. std::string tryTranslators() const;
  6749. private:
  6750. std::vector<std::unique_ptr<IExceptionTranslator const>> m_translators;
  6751. };
  6752. }
  6753. // end catch_exception_translator_registry.h
  6754. #ifdef __OBJC__
  6755. #import "Foundation/Foundation.h"
  6756. #endif
  6757. namespace Catch {
  6758. ExceptionTranslatorRegistry::~ExceptionTranslatorRegistry() {
  6759. }
  6760. void ExceptionTranslatorRegistry::registerTranslator( const IExceptionTranslator* translator ) {
  6761. m_translators.push_back( std::unique_ptr<const IExceptionTranslator>( translator ) );
  6762. }
  6763. #if !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
  6764. std::string ExceptionTranslatorRegistry::translateActiveException() const {
  6765. try {
  6766. #ifdef __OBJC__
  6767. // In Objective-C try objective-c exceptions first
  6768. @try {
  6769. return tryTranslators();
  6770. }
  6771. @catch (NSException *exception) {
  6772. return Catch::Detail::stringify( [exception description] );
  6773. }
  6774. #else
  6775. // Compiling a mixed mode project with MSVC means that CLR
  6776. // exceptions will be caught in (...) as well. However, these
  6777. // do not fill-in std::current_exception and thus lead to crash
  6778. // when attempting rethrow.
  6779. // /EHa switch also causes structured exceptions to be caught
  6780. // here, but they fill-in current_exception properly, so
  6781. // at worst the output should be a little weird, instead of
  6782. // causing a crash.
  6783. if (std::current_exception() == nullptr) {
  6784. return "Non C++ exception. Possibly a CLR exception.";
  6785. }
  6786. return tryTranslators();
  6787. #endif
  6788. }
  6789. catch( TestFailureException& ) {
  6790. std::rethrow_exception(std::current_exception());
  6791. }
  6792. catch( std::exception& ex ) {
  6793. return ex.what();
  6794. }
  6795. catch( std::string& msg ) {
  6796. return msg;
  6797. }
  6798. catch( const char* msg ) {
  6799. return msg;
  6800. }
  6801. catch(...) {
  6802. return "Unknown exception";
  6803. }
  6804. }
  6805. std::string ExceptionTranslatorRegistry::tryTranslators() const {
  6806. if (m_translators.empty()) {
  6807. std::rethrow_exception(std::current_exception());
  6808. } else {
  6809. return m_translators[0]->translate(m_translators.begin() + 1, m_translators.end());
  6810. }
  6811. }
  6812. #else // ^^ Exceptions are enabled // Exceptions are disabled vv
  6813. std::string ExceptionTranslatorRegistry::translateActiveException() const {
  6814. CATCH_INTERNAL_ERROR("Attempted to translate active exception under CATCH_CONFIG_DISABLE_EXCEPTIONS!");
  6815. }
  6816. std::string ExceptionTranslatorRegistry::tryTranslators() const {
  6817. CATCH_INTERNAL_ERROR("Attempted to use exception translators under CATCH_CONFIG_DISABLE_EXCEPTIONS!");
  6818. }
  6819. #endif
  6820. }
  6821. // end catch_exception_translator_registry.cpp
  6822. // start catch_fatal_condition.cpp
  6823. #if defined(__GNUC__)
  6824. # pragma GCC diagnostic push
  6825. # pragma GCC diagnostic ignored "-Wmissing-field-initializers"
  6826. #endif
  6827. #if defined( CATCH_CONFIG_WINDOWS_SEH ) || defined( CATCH_CONFIG_POSIX_SIGNALS )
  6828. namespace {
  6829. // Report the error condition
  6830. void reportFatal( char const * const message ) {
  6831. Catch::getCurrentContext().getResultCapture()->handleFatalErrorCondition( message );
  6832. }
  6833. }
  6834. #endif // signals/SEH handling
  6835. #if defined( CATCH_CONFIG_WINDOWS_SEH )
  6836. namespace Catch {
  6837. struct SignalDefs { DWORD id; const char* name; };
  6838. // There is no 1-1 mapping between signals and windows exceptions.
  6839. // Windows can easily distinguish between SO and SigSegV,
  6840. // but SigInt, SigTerm, etc are handled differently.
  6841. static SignalDefs signalDefs[] = {
  6842. { EXCEPTION_ILLEGAL_INSTRUCTION, "SIGILL - Illegal instruction signal" },
  6843. { EXCEPTION_STACK_OVERFLOW, "SIGSEGV - Stack overflow" },
  6844. { EXCEPTION_ACCESS_VIOLATION, "SIGSEGV - Segmentation violation signal" },
  6845. { EXCEPTION_INT_DIVIDE_BY_ZERO, "Divide by zero error" },
  6846. };
  6847. LONG CALLBACK FatalConditionHandler::handleVectoredException(PEXCEPTION_POINTERS ExceptionInfo) {
  6848. for (auto const& def : signalDefs) {
  6849. if (ExceptionInfo->ExceptionRecord->ExceptionCode == def.id) {
  6850. reportFatal(def.name);
  6851. }
  6852. }
  6853. // If its not an exception we care about, pass it along.
  6854. // This stops us from eating debugger breaks etc.
  6855. return EXCEPTION_CONTINUE_SEARCH;
  6856. }
  6857. FatalConditionHandler::FatalConditionHandler() {
  6858. isSet = true;
  6859. // 32k seems enough for Catch to handle stack overflow,
  6860. // but the value was found experimentally, so there is no strong guarantee
  6861. guaranteeSize = 32 * 1024;
  6862. exceptionHandlerHandle = nullptr;
  6863. // Register as first handler in current chain
  6864. exceptionHandlerHandle = AddVectoredExceptionHandler(1, handleVectoredException);
  6865. // Pass in guarantee size to be filled
  6866. SetThreadStackGuarantee(&guaranteeSize);
  6867. }
  6868. void FatalConditionHandler::reset() {
  6869. if (isSet) {
  6870. RemoveVectoredExceptionHandler(exceptionHandlerHandle);
  6871. SetThreadStackGuarantee(&guaranteeSize);
  6872. exceptionHandlerHandle = nullptr;
  6873. isSet = false;
  6874. }
  6875. }
  6876. FatalConditionHandler::~FatalConditionHandler() {
  6877. reset();
  6878. }
  6879. bool FatalConditionHandler::isSet = false;
  6880. ULONG FatalConditionHandler::guaranteeSize = 0;
  6881. PVOID FatalConditionHandler::exceptionHandlerHandle = nullptr;
  6882. } // namespace Catch
  6883. #elif defined( CATCH_CONFIG_POSIX_SIGNALS )
  6884. namespace Catch {
  6885. struct SignalDefs {
  6886. int id;
  6887. const char* name;
  6888. };
  6889. // 32kb for the alternate stack seems to be sufficient. However, this value
  6890. // is experimentally determined, so that's not guaranteed.
  6891. constexpr static std::size_t sigStackSize = 32768 >= MINSIGSTKSZ ? 32768 : MINSIGSTKSZ;
  6892. static SignalDefs signalDefs[] = {
  6893. { SIGINT, "SIGINT - Terminal interrupt signal" },
  6894. { SIGILL, "SIGILL - Illegal instruction signal" },
  6895. { SIGFPE, "SIGFPE - Floating point error signal" },
  6896. { SIGSEGV, "SIGSEGV - Segmentation violation signal" },
  6897. { SIGTERM, "SIGTERM - Termination request signal" },
  6898. { SIGABRT, "SIGABRT - Abort (abnormal termination) signal" }
  6899. };
  6900. void FatalConditionHandler::handleSignal( int sig ) {
  6901. char const * name = "<unknown signal>";
  6902. for (auto const& def : signalDefs) {
  6903. if (sig == def.id) {
  6904. name = def.name;
  6905. break;
  6906. }
  6907. }
  6908. reset();
  6909. reportFatal(name);
  6910. raise( sig );
  6911. }
  6912. FatalConditionHandler::FatalConditionHandler() {
  6913. isSet = true;
  6914. stack_t sigStack;
  6915. sigStack.ss_sp = altStackMem;
  6916. sigStack.ss_size = sigStackSize;
  6917. sigStack.ss_flags = 0;
  6918. sigaltstack(&sigStack, &oldSigStack);
  6919. struct sigaction sa = { };
  6920. sa.sa_handler = handleSignal;
  6921. sa.sa_flags = SA_ONSTACK;
  6922. for (std::size_t i = 0; i < sizeof(signalDefs)/sizeof(SignalDefs); ++i) {
  6923. sigaction(signalDefs[i].id, &sa, &oldSigActions[i]);
  6924. }
  6925. }
  6926. FatalConditionHandler::~FatalConditionHandler() {
  6927. reset();
  6928. }
  6929. void FatalConditionHandler::reset() {
  6930. if( isSet ) {
  6931. // Set signals back to previous values -- hopefully nobody overwrote them in the meantime
  6932. for( std::size_t i = 0; i < sizeof(signalDefs)/sizeof(SignalDefs); ++i ) {
  6933. sigaction(signalDefs[i].id, &oldSigActions[i], nullptr);
  6934. }
  6935. // Return the old stack
  6936. sigaltstack(&oldSigStack, nullptr);
  6937. isSet = false;
  6938. }
  6939. }
  6940. bool FatalConditionHandler::isSet = false;
  6941. struct sigaction FatalConditionHandler::oldSigActions[sizeof(signalDefs)/sizeof(SignalDefs)] = {};
  6942. stack_t FatalConditionHandler::oldSigStack = {};
  6943. char FatalConditionHandler::altStackMem[sigStackSize] = {};
  6944. } // namespace Catch
  6945. #else
  6946. namespace Catch {
  6947. void FatalConditionHandler::reset() {}
  6948. }
  6949. #endif // signals/SEH handling
  6950. #if defined(__GNUC__)
  6951. # pragma GCC diagnostic pop
  6952. #endif
  6953. // end catch_fatal_condition.cpp
  6954. // start catch_generators.cpp
  6955. // start catch_random_number_generator.h
  6956. #include <algorithm>
  6957. #include <random>
  6958. namespace Catch {
  6959. struct IConfig;
  6960. std::mt19937& rng();
  6961. void seedRng( IConfig const& config );
  6962. unsigned int rngSeed();
  6963. }
  6964. // end catch_random_number_generator.h
  6965. #include <limits>
  6966. #include <set>
  6967. namespace Catch {
  6968. IGeneratorTracker::~IGeneratorTracker() {}
  6969. const char* GeneratorException::what() const noexcept {
  6970. return m_msg;
  6971. }
  6972. namespace Generators {
  6973. GeneratorUntypedBase::~GeneratorUntypedBase() {}
  6974. auto acquireGeneratorTracker( SourceLineInfo const& lineInfo ) -> IGeneratorTracker& {
  6975. return getResultCapture().acquireGeneratorTracker( lineInfo );
  6976. }
  6977. } // namespace Generators
  6978. } // namespace Catch
  6979. // end catch_generators.cpp
  6980. // start catch_interfaces_capture.cpp
  6981. namespace Catch {
  6982. IResultCapture::~IResultCapture() = default;
  6983. }
  6984. // end catch_interfaces_capture.cpp
  6985. // start catch_interfaces_config.cpp
  6986. namespace Catch {
  6987. IConfig::~IConfig() = default;
  6988. }
  6989. // end catch_interfaces_config.cpp
  6990. // start catch_interfaces_exception.cpp
  6991. namespace Catch {
  6992. IExceptionTranslator::~IExceptionTranslator() = default;
  6993. IExceptionTranslatorRegistry::~IExceptionTranslatorRegistry() = default;
  6994. }
  6995. // end catch_interfaces_exception.cpp
  6996. // start catch_interfaces_registry_hub.cpp
  6997. namespace Catch {
  6998. IRegistryHub::~IRegistryHub() = default;
  6999. IMutableRegistryHub::~IMutableRegistryHub() = default;
  7000. }
  7001. // end catch_interfaces_registry_hub.cpp
  7002. // start catch_interfaces_reporter.cpp
  7003. // start catch_reporter_listening.h
  7004. namespace Catch {
  7005. class ListeningReporter : public IStreamingReporter {
  7006. using Reporters = std::vector<IStreamingReporterPtr>;
  7007. Reporters m_listeners;
  7008. IStreamingReporterPtr m_reporter = nullptr;
  7009. ReporterPreferences m_preferences;
  7010. public:
  7011. ListeningReporter();
  7012. void addListener( IStreamingReporterPtr&& listener );
  7013. void addReporter( IStreamingReporterPtr&& reporter );
  7014. public: // IStreamingReporter
  7015. ReporterPreferences getPreferences() const override;
  7016. void noMatchingTestCases( std::string const& spec ) override;
  7017. static std::set<Verbosity> getSupportedVerbosities();
  7018. void benchmarkStarting( BenchmarkInfo const& benchmarkInfo ) override;
  7019. void benchmarkEnded( BenchmarkStats const& benchmarkStats ) override;
  7020. void testRunStarting( TestRunInfo const& testRunInfo ) override;
  7021. void testGroupStarting( GroupInfo const& groupInfo ) override;
  7022. void testCaseStarting( TestCaseInfo const& testInfo ) override;
  7023. void sectionStarting( SectionInfo const& sectionInfo ) override;
  7024. void assertionStarting( AssertionInfo const& assertionInfo ) override;
  7025. // The return value indicates if the messages buffer should be cleared:
  7026. bool assertionEnded( AssertionStats const& assertionStats ) override;
  7027. void sectionEnded( SectionStats const& sectionStats ) override;
  7028. void testCaseEnded( TestCaseStats const& testCaseStats ) override;
  7029. void testGroupEnded( TestGroupStats const& testGroupStats ) override;
  7030. void testRunEnded( TestRunStats const& testRunStats ) override;
  7031. void skipTest( TestCaseInfo const& testInfo ) override;
  7032. bool isMulti() const override;
  7033. };
  7034. } // end namespace Catch
  7035. // end catch_reporter_listening.h
  7036. namespace Catch {
  7037. ReporterConfig::ReporterConfig( IConfigPtr const& _fullConfig )
  7038. : m_stream( &_fullConfig->stream() ), m_fullConfig( _fullConfig ) {}
  7039. ReporterConfig::ReporterConfig( IConfigPtr const& _fullConfig, std::ostream& _stream )
  7040. : m_stream( &_stream ), m_fullConfig( _fullConfig ) {}
  7041. std::ostream& ReporterConfig::stream() const { return *m_stream; }
  7042. IConfigPtr ReporterConfig::fullConfig() const { return m_fullConfig; }
  7043. TestRunInfo::TestRunInfo( std::string const& _name ) : name( _name ) {}
  7044. GroupInfo::GroupInfo( std::string const& _name,
  7045. std::size_t _groupIndex,
  7046. std::size_t _groupsCount )
  7047. : name( _name ),
  7048. groupIndex( _groupIndex ),
  7049. groupsCounts( _groupsCount )
  7050. {}
  7051. AssertionStats::AssertionStats( AssertionResult const& _assertionResult,
  7052. std::vector<MessageInfo> const& _infoMessages,
  7053. Totals const& _totals )
  7054. : assertionResult( _assertionResult ),
  7055. infoMessages( _infoMessages ),
  7056. totals( _totals )
  7057. {
  7058. assertionResult.m_resultData.lazyExpression.m_transientExpression = _assertionResult.m_resultData.lazyExpression.m_transientExpression;
  7059. if( assertionResult.hasMessage() ) {
  7060. // Copy message into messages list.
  7061. // !TBD This should have been done earlier, somewhere
  7062. MessageBuilder builder( assertionResult.getTestMacroName(), assertionResult.getSourceInfo(), assertionResult.getResultType() );
  7063. builder << assertionResult.getMessage();
  7064. builder.m_info.message = builder.m_stream.str();
  7065. infoMessages.push_back( builder.m_info );
  7066. }
  7067. }
  7068. AssertionStats::~AssertionStats() = default;
  7069. SectionStats::SectionStats( SectionInfo const& _sectionInfo,
  7070. Counts const& _assertions,
  7071. double _durationInSeconds,
  7072. bool _missingAssertions )
  7073. : sectionInfo( _sectionInfo ),
  7074. assertions( _assertions ),
  7075. durationInSeconds( _durationInSeconds ),
  7076. missingAssertions( _missingAssertions )
  7077. {}
  7078. SectionStats::~SectionStats() = default;
  7079. TestCaseStats::TestCaseStats( TestCaseInfo const& _testInfo,
  7080. Totals const& _totals,
  7081. std::string const& _stdOut,
  7082. std::string const& _stdErr,
  7083. bool _aborting )
  7084. : testInfo( _testInfo ),
  7085. totals( _totals ),
  7086. stdOut( _stdOut ),
  7087. stdErr( _stdErr ),
  7088. aborting( _aborting )
  7089. {}
  7090. TestCaseStats::~TestCaseStats() = default;
  7091. TestGroupStats::TestGroupStats( GroupInfo const& _groupInfo,
  7092. Totals const& _totals,
  7093. bool _aborting )
  7094. : groupInfo( _groupInfo ),
  7095. totals( _totals ),
  7096. aborting( _aborting )
  7097. {}
  7098. TestGroupStats::TestGroupStats( GroupInfo const& _groupInfo )
  7099. : groupInfo( _groupInfo ),
  7100. aborting( false )
  7101. {}
  7102. TestGroupStats::~TestGroupStats() = default;
  7103. TestRunStats::TestRunStats( TestRunInfo const& _runInfo,
  7104. Totals const& _totals,
  7105. bool _aborting )
  7106. : runInfo( _runInfo ),
  7107. totals( _totals ),
  7108. aborting( _aborting )
  7109. {}
  7110. TestRunStats::~TestRunStats() = default;
  7111. void IStreamingReporter::fatalErrorEncountered( StringRef ) {}
  7112. bool IStreamingReporter::isMulti() const { return false; }
  7113. IReporterFactory::~IReporterFactory() = default;
  7114. IReporterRegistry::~IReporterRegistry() = default;
  7115. } // end namespace Catch
  7116. // end catch_interfaces_reporter.cpp
  7117. // start catch_interfaces_runner.cpp
  7118. namespace Catch {
  7119. IRunner::~IRunner() = default;
  7120. }
  7121. // end catch_interfaces_runner.cpp
  7122. // start catch_interfaces_testcase.cpp
  7123. namespace Catch {
  7124. ITestInvoker::~ITestInvoker() = default;
  7125. ITestCaseRegistry::~ITestCaseRegistry() = default;
  7126. }
  7127. // end catch_interfaces_testcase.cpp
  7128. // start catch_leak_detector.cpp
  7129. #ifdef CATCH_CONFIG_WINDOWS_CRTDBG
  7130. #include <crtdbg.h>
  7131. namespace Catch {
  7132. LeakDetector::LeakDetector() {
  7133. int flag = _CrtSetDbgFlag(_CRTDBG_REPORT_FLAG);
  7134. flag |= _CRTDBG_LEAK_CHECK_DF;
  7135. flag |= _CRTDBG_ALLOC_MEM_DF;
  7136. _CrtSetDbgFlag(flag);
  7137. _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE | _CRTDBG_MODE_DEBUG);
  7138. _CrtSetReportFile(_CRT_WARN, _CRTDBG_FILE_STDERR);
  7139. // Change this to leaking allocation's number to break there
  7140. _CrtSetBreakAlloc(-1);
  7141. }
  7142. }
  7143. #else
  7144. Catch::LeakDetector::LeakDetector() {}
  7145. #endif
  7146. Catch::LeakDetector::~LeakDetector() {
  7147. Catch::cleanUp();
  7148. }
  7149. // end catch_leak_detector.cpp
  7150. // start catch_list.cpp
  7151. // start catch_list.h
  7152. #include <set>
  7153. namespace Catch {
  7154. std::size_t listTests( Config const& config );
  7155. std::size_t listTestsNamesOnly( Config const& config );
  7156. struct TagInfo {
  7157. void add( std::string const& spelling );
  7158. std::string all() const;
  7159. std::set<std::string> spellings;
  7160. std::size_t count = 0;
  7161. };
  7162. std::size_t listTags( Config const& config );
  7163. std::size_t listReporters();
  7164. Option<std::size_t> list( std::shared_ptr<Config> const& config );
  7165. } // end namespace Catch
  7166. // end catch_list.h
  7167. // start catch_text.h
  7168. namespace Catch {
  7169. using namespace clara::TextFlow;
  7170. }
  7171. // end catch_text.h
  7172. #include <limits>
  7173. #include <algorithm>
  7174. #include <iomanip>
  7175. namespace Catch {
  7176. std::size_t listTests( Config const& config ) {
  7177. TestSpec testSpec = config.testSpec();
  7178. if( config.hasTestFilters() )
  7179. Catch::cout() << "Matching test cases:\n";
  7180. else {
  7181. Catch::cout() << "All available test cases:\n";
  7182. }
  7183. auto matchedTestCases = filterTests( getAllTestCasesSorted( config ), testSpec, config );
  7184. for( auto const& testCaseInfo : matchedTestCases ) {
  7185. Colour::Code colour = testCaseInfo.isHidden()
  7186. ? Colour::SecondaryText
  7187. : Colour::None;
  7188. Colour colourGuard( colour );
  7189. Catch::cout() << Column( testCaseInfo.name ).initialIndent( 2 ).indent( 4 ) << "\n";
  7190. if( config.verbosity() >= Verbosity::High ) {
  7191. Catch::cout() << Column( Catch::Detail::stringify( testCaseInfo.lineInfo ) ).indent(4) << std::endl;
  7192. std::string description = testCaseInfo.description;
  7193. if( description.empty() )
  7194. description = "(NO DESCRIPTION)";
  7195. Catch::cout() << Column( description ).indent(4) << std::endl;
  7196. }
  7197. if( !testCaseInfo.tags.empty() )
  7198. Catch::cout() << Column( testCaseInfo.tagsAsString() ).indent( 6 ) << "\n";
  7199. }
  7200. if( !config.hasTestFilters() )
  7201. Catch::cout() << pluralise( matchedTestCases.size(), "test case" ) << '\n' << std::endl;
  7202. else
  7203. Catch::cout() << pluralise( matchedTestCases.size(), "matching test case" ) << '\n' << std::endl;
  7204. return matchedTestCases.size();
  7205. }
  7206. std::size_t listTestsNamesOnly( Config const& config ) {
  7207. TestSpec testSpec = config.testSpec();
  7208. std::size_t matchedTests = 0;
  7209. std::vector<TestCase> matchedTestCases = filterTests( getAllTestCasesSorted( config ), testSpec, config );
  7210. for( auto const& testCaseInfo : matchedTestCases ) {
  7211. matchedTests++;
  7212. if( startsWith( testCaseInfo.name, '#' ) )
  7213. Catch::cout() << '"' << testCaseInfo.name << '"';
  7214. else
  7215. Catch::cout() << testCaseInfo.name;
  7216. if ( config.verbosity() >= Verbosity::High )
  7217. Catch::cout() << "\t@" << testCaseInfo.lineInfo;
  7218. Catch::cout() << std::endl;
  7219. }
  7220. return matchedTests;
  7221. }
  7222. void TagInfo::add( std::string const& spelling ) {
  7223. ++count;
  7224. spellings.insert( spelling );
  7225. }
  7226. std::string TagInfo::all() const {
  7227. std::string out;
  7228. for( auto const& spelling : spellings )
  7229. out += "[" + spelling + "]";
  7230. return out;
  7231. }
  7232. std::size_t listTags( Config const& config ) {
  7233. TestSpec testSpec = config.testSpec();
  7234. if( config.hasTestFilters() )
  7235. Catch::cout() << "Tags for matching test cases:\n";
  7236. else {
  7237. Catch::cout() << "All available tags:\n";
  7238. }
  7239. std::map<std::string, TagInfo> tagCounts;
  7240. std::vector<TestCase> matchedTestCases = filterTests( getAllTestCasesSorted( config ), testSpec, config );
  7241. for( auto const& testCase : matchedTestCases ) {
  7242. for( auto const& tagName : testCase.getTestCaseInfo().tags ) {
  7243. std::string lcaseTagName = toLower( tagName );
  7244. auto countIt = tagCounts.find( lcaseTagName );
  7245. if( countIt == tagCounts.end() )
  7246. countIt = tagCounts.insert( std::make_pair( lcaseTagName, TagInfo() ) ).first;
  7247. countIt->second.add( tagName );
  7248. }
  7249. }
  7250. for( auto const& tagCount : tagCounts ) {
  7251. ReusableStringStream rss;
  7252. rss << " " << std::setw(2) << tagCount.second.count << " ";
  7253. auto str = rss.str();
  7254. auto wrapper = Column( tagCount.second.all() )
  7255. .initialIndent( 0 )
  7256. .indent( str.size() )
  7257. .width( CATCH_CONFIG_CONSOLE_WIDTH-10 );
  7258. Catch::cout() << str << wrapper << '\n';
  7259. }
  7260. Catch::cout() << pluralise( tagCounts.size(), "tag" ) << '\n' << std::endl;
  7261. return tagCounts.size();
  7262. }
  7263. std::size_t listReporters() {
  7264. Catch::cout() << "Available reporters:\n";
  7265. IReporterRegistry::FactoryMap const& factories = getRegistryHub().getReporterRegistry().getFactories();
  7266. std::size_t maxNameLen = 0;
  7267. for( auto const& factoryKvp : factories )
  7268. maxNameLen = (std::max)( maxNameLen, factoryKvp.first.size() );
  7269. for( auto const& factoryKvp : factories ) {
  7270. Catch::cout()
  7271. << Column( factoryKvp.first + ":" )
  7272. .indent(2)
  7273. .width( 5+maxNameLen )
  7274. + Column( factoryKvp.second->getDescription() )
  7275. .initialIndent(0)
  7276. .indent(2)
  7277. .width( CATCH_CONFIG_CONSOLE_WIDTH - maxNameLen-8 )
  7278. << "\n";
  7279. }
  7280. Catch::cout() << std::endl;
  7281. return factories.size();
  7282. }
  7283. Option<std::size_t> list( std::shared_ptr<Config> const& config ) {
  7284. Option<std::size_t> listedCount;
  7285. getCurrentMutableContext().setConfig( config );
  7286. if( config->listTests() )
  7287. listedCount = listedCount.valueOr(0) + listTests( *config );
  7288. if( config->listTestNamesOnly() )
  7289. listedCount = listedCount.valueOr(0) + listTestsNamesOnly( *config );
  7290. if( config->listTags() )
  7291. listedCount = listedCount.valueOr(0) + listTags( *config );
  7292. if( config->listReporters() )
  7293. listedCount = listedCount.valueOr(0) + listReporters();
  7294. return listedCount;
  7295. }
  7296. } // end namespace Catch
  7297. // end catch_list.cpp
  7298. // start catch_matchers.cpp
  7299. namespace Catch {
  7300. namespace Matchers {
  7301. namespace Impl {
  7302. std::string MatcherUntypedBase::toString() const {
  7303. if( m_cachedToString.empty() )
  7304. m_cachedToString = describe();
  7305. return m_cachedToString;
  7306. }
  7307. MatcherUntypedBase::~MatcherUntypedBase() = default;
  7308. } // namespace Impl
  7309. } // namespace Matchers
  7310. using namespace Matchers;
  7311. using Matchers::Impl::MatcherBase;
  7312. } // namespace Catch
  7313. // end catch_matchers.cpp
  7314. // start catch_matchers_floating.cpp
  7315. // start catch_polyfills.hpp
  7316. namespace Catch {
  7317. bool isnan(float f);
  7318. bool isnan(double d);
  7319. }
  7320. // end catch_polyfills.hpp
  7321. // start catch_to_string.hpp
  7322. #include <string>
  7323. namespace Catch {
  7324. template <typename T>
  7325. std::string to_string(T const& t) {
  7326. #if defined(CATCH_CONFIG_CPP11_TO_STRING)
  7327. return std::to_string(t);
  7328. #else
  7329. ReusableStringStream rss;
  7330. rss << t;
  7331. return rss.str();
  7332. #endif
  7333. }
  7334. } // end namespace Catch
  7335. // end catch_to_string.hpp
  7336. #include <cstdlib>
  7337. #include <cstdint>
  7338. #include <cstring>
  7339. namespace Catch {
  7340. namespace Matchers {
  7341. namespace Floating {
  7342. enum class FloatingPointKind : uint8_t {
  7343. Float,
  7344. Double
  7345. };
  7346. }
  7347. }
  7348. }
  7349. namespace {
  7350. template <typename T>
  7351. struct Converter;
  7352. template <>
  7353. struct Converter<float> {
  7354. static_assert(sizeof(float) == sizeof(int32_t), "Important ULP matcher assumption violated");
  7355. Converter(float f) {
  7356. std::memcpy(&i, &f, sizeof(f));
  7357. }
  7358. int32_t i;
  7359. };
  7360. template <>
  7361. struct Converter<double> {
  7362. static_assert(sizeof(double) == sizeof(int64_t), "Important ULP matcher assumption violated");
  7363. Converter(double d) {
  7364. std::memcpy(&i, &d, sizeof(d));
  7365. }
  7366. int64_t i;
  7367. };
  7368. template <typename T>
  7369. auto convert(T t) -> Converter<T> {
  7370. return Converter<T>(t);
  7371. }
  7372. template <typename FP>
  7373. bool almostEqualUlps(FP lhs, FP rhs, int maxUlpDiff) {
  7374. // Comparison with NaN should always be false.
  7375. // This way we can rule it out before getting into the ugly details
  7376. if (Catch::isnan(lhs) || Catch::isnan(rhs)) {
  7377. return false;
  7378. }
  7379. auto lc = convert(lhs);
  7380. auto rc = convert(rhs);
  7381. if ((lc.i < 0) != (rc.i < 0)) {
  7382. // Potentially we can have +0 and -0
  7383. return lhs == rhs;
  7384. }
  7385. auto ulpDiff = std::abs(lc.i - rc.i);
  7386. return ulpDiff <= maxUlpDiff;
  7387. }
  7388. }
  7389. namespace Catch {
  7390. namespace Matchers {
  7391. namespace Floating {
  7392. WithinAbsMatcher::WithinAbsMatcher(double target, double margin)
  7393. :m_target{ target }, m_margin{ margin } {
  7394. CATCH_ENFORCE(margin >= 0, "Invalid margin: " << margin << '.'
  7395. << " Margin has to be non-negative.");
  7396. }
  7397. // Performs equivalent check of std::fabs(lhs - rhs) <= margin
  7398. // But without the subtraction to allow for INFINITY in comparison
  7399. bool WithinAbsMatcher::match(double const& matchee) const {
  7400. return (matchee + m_margin >= m_target) && (m_target + m_margin >= matchee);
  7401. }
  7402. std::string WithinAbsMatcher::describe() const {
  7403. return "is within " + ::Catch::Detail::stringify(m_margin) + " of " + ::Catch::Detail::stringify(m_target);
  7404. }
  7405. WithinUlpsMatcher::WithinUlpsMatcher(double target, int ulps, FloatingPointKind baseType)
  7406. :m_target{ target }, m_ulps{ ulps }, m_type{ baseType } {
  7407. CATCH_ENFORCE(ulps >= 0, "Invalid ULP setting: " << ulps << '.'
  7408. << " ULPs have to be non-negative.");
  7409. }
  7410. #if defined(__clang__)
  7411. #pragma clang diagnostic push
  7412. // Clang <3.5 reports on the default branch in the switch below
  7413. #pragma clang diagnostic ignored "-Wunreachable-code"
  7414. #endif
  7415. bool WithinUlpsMatcher::match(double const& matchee) const {
  7416. switch (m_type) {
  7417. case FloatingPointKind::Float:
  7418. return almostEqualUlps<float>(static_cast<float>(matchee), static_cast<float>(m_target), m_ulps);
  7419. case FloatingPointKind::Double:
  7420. return almostEqualUlps<double>(matchee, m_target, m_ulps);
  7421. default:
  7422. CATCH_INTERNAL_ERROR( "Unknown FloatingPointKind value" );
  7423. }
  7424. }
  7425. #if defined(__clang__)
  7426. #pragma clang diagnostic pop
  7427. #endif
  7428. std::string WithinUlpsMatcher::describe() const {
  7429. return "is within " + Catch::to_string(m_ulps) + " ULPs of " + ::Catch::Detail::stringify(m_target) + ((m_type == FloatingPointKind::Float)? "f" : "");
  7430. }
  7431. }// namespace Floating
  7432. Floating::WithinUlpsMatcher WithinULP(double target, int maxUlpDiff) {
  7433. return Floating::WithinUlpsMatcher(target, maxUlpDiff, Floating::FloatingPointKind::Double);
  7434. }
  7435. Floating::WithinUlpsMatcher WithinULP(float target, int maxUlpDiff) {
  7436. return Floating::WithinUlpsMatcher(target, maxUlpDiff, Floating::FloatingPointKind::Float);
  7437. }
  7438. Floating::WithinAbsMatcher WithinAbs(double target, double margin) {
  7439. return Floating::WithinAbsMatcher(target, margin);
  7440. }
  7441. } // namespace Matchers
  7442. } // namespace Catch
  7443. // end catch_matchers_floating.cpp
  7444. // start catch_matchers_generic.cpp
  7445. std::string Catch::Matchers::Generic::Detail::finalizeDescription(const std::string& desc) {
  7446. if (desc.empty()) {
  7447. return "matches undescribed predicate";
  7448. } else {
  7449. return "matches predicate: \"" + desc + '"';
  7450. }
  7451. }
  7452. // end catch_matchers_generic.cpp
  7453. // start catch_matchers_string.cpp
  7454. #include <regex>
  7455. namespace Catch {
  7456. namespace Matchers {
  7457. namespace StdString {
  7458. CasedString::CasedString( std::string const& str, CaseSensitive::Choice caseSensitivity )
  7459. : m_caseSensitivity( caseSensitivity ),
  7460. m_str( adjustString( str ) )
  7461. {}
  7462. std::string CasedString::adjustString( std::string const& str ) const {
  7463. return m_caseSensitivity == CaseSensitive::No
  7464. ? toLower( str )
  7465. : str;
  7466. }
  7467. std::string CasedString::caseSensitivitySuffix() const {
  7468. return m_caseSensitivity == CaseSensitive::No
  7469. ? " (case insensitive)"
  7470. : std::string();
  7471. }
  7472. StringMatcherBase::StringMatcherBase( std::string const& operation, CasedString const& comparator )
  7473. : m_comparator( comparator ),
  7474. m_operation( operation ) {
  7475. }
  7476. std::string StringMatcherBase::describe() const {
  7477. std::string description;
  7478. description.reserve(5 + m_operation.size() + m_comparator.m_str.size() +
  7479. m_comparator.caseSensitivitySuffix().size());
  7480. description += m_operation;
  7481. description += ": \"";
  7482. description += m_comparator.m_str;
  7483. description += "\"";
  7484. description += m_comparator.caseSensitivitySuffix();
  7485. return description;
  7486. }
  7487. EqualsMatcher::EqualsMatcher( CasedString const& comparator ) : StringMatcherBase( "equals", comparator ) {}
  7488. bool EqualsMatcher::match( std::string const& source ) const {
  7489. return m_comparator.adjustString( source ) == m_comparator.m_str;
  7490. }
  7491. ContainsMatcher::ContainsMatcher( CasedString const& comparator ) : StringMatcherBase( "contains", comparator ) {}
  7492. bool ContainsMatcher::match( std::string const& source ) const {
  7493. return contains( m_comparator.adjustString( source ), m_comparator.m_str );
  7494. }
  7495. StartsWithMatcher::StartsWithMatcher( CasedString const& comparator ) : StringMatcherBase( "starts with", comparator ) {}
  7496. bool StartsWithMatcher::match( std::string const& source ) const {
  7497. return startsWith( m_comparator.adjustString( source ), m_comparator.m_str );
  7498. }
  7499. EndsWithMatcher::EndsWithMatcher( CasedString const& comparator ) : StringMatcherBase( "ends with", comparator ) {}
  7500. bool EndsWithMatcher::match( std::string const& source ) const {
  7501. return endsWith( m_comparator.adjustString( source ), m_comparator.m_str );
  7502. }
  7503. RegexMatcher::RegexMatcher(std::string regex, CaseSensitive::Choice caseSensitivity): m_regex(std::move(regex)), m_caseSensitivity(caseSensitivity) {}
  7504. bool RegexMatcher::match(std::string const& matchee) const {
  7505. auto flags = std::regex::ECMAScript; // ECMAScript is the default syntax option anyway
  7506. if (m_caseSensitivity == CaseSensitive::Choice::No) {
  7507. flags |= std::regex::icase;
  7508. }
  7509. auto reg = std::regex(m_regex, flags);
  7510. return std::regex_match(matchee, reg);
  7511. }
  7512. std::string RegexMatcher::describe() const {
  7513. return "matches " + ::Catch::Detail::stringify(m_regex) + ((m_caseSensitivity == CaseSensitive::Choice::Yes)? " case sensitively" : " case insensitively");
  7514. }
  7515. } // namespace StdString
  7516. StdString::EqualsMatcher Equals( std::string const& str, CaseSensitive::Choice caseSensitivity ) {
  7517. return StdString::EqualsMatcher( StdString::CasedString( str, caseSensitivity) );
  7518. }
  7519. StdString::ContainsMatcher Contains( std::string const& str, CaseSensitive::Choice caseSensitivity ) {
  7520. return StdString::ContainsMatcher( StdString::CasedString( str, caseSensitivity) );
  7521. }
  7522. StdString::EndsWithMatcher EndsWith( std::string const& str, CaseSensitive::Choice caseSensitivity ) {
  7523. return StdString::EndsWithMatcher( StdString::CasedString( str, caseSensitivity) );
  7524. }
  7525. StdString::StartsWithMatcher StartsWith( std::string const& str, CaseSensitive::Choice caseSensitivity ) {
  7526. return StdString::StartsWithMatcher( StdString::CasedString( str, caseSensitivity) );
  7527. }
  7528. StdString::RegexMatcher Matches(std::string const& regex, CaseSensitive::Choice caseSensitivity) {
  7529. return StdString::RegexMatcher(regex, caseSensitivity);
  7530. }
  7531. } // namespace Matchers
  7532. } // namespace Catch
  7533. // end catch_matchers_string.cpp
  7534. // start catch_message.cpp
  7535. // start catch_uncaught_exceptions.h
  7536. namespace Catch {
  7537. bool uncaught_exceptions();
  7538. } // end namespace Catch
  7539. // end catch_uncaught_exceptions.h
  7540. #include <cassert>
  7541. #include <stack>
  7542. namespace Catch {
  7543. MessageInfo::MessageInfo( StringRef const& _macroName,
  7544. SourceLineInfo const& _lineInfo,
  7545. ResultWas::OfType _type )
  7546. : macroName( _macroName ),
  7547. lineInfo( _lineInfo ),
  7548. type( _type ),
  7549. sequence( ++globalCount )
  7550. {}
  7551. bool MessageInfo::operator==( MessageInfo const& other ) const {
  7552. return sequence == other.sequence;
  7553. }
  7554. bool MessageInfo::operator<( MessageInfo const& other ) const {
  7555. return sequence < other.sequence;
  7556. }
  7557. // This may need protecting if threading support is added
  7558. unsigned int MessageInfo::globalCount = 0;
  7559. ////////////////////////////////////////////////////////////////////////////
  7560. Catch::MessageBuilder::MessageBuilder( StringRef const& macroName,
  7561. SourceLineInfo const& lineInfo,
  7562. ResultWas::OfType type )
  7563. :m_info(macroName, lineInfo, type) {}
  7564. ////////////////////////////////////////////////////////////////////////////
  7565. ScopedMessage::ScopedMessage( MessageBuilder const& builder )
  7566. : m_info( builder.m_info )
  7567. {
  7568. m_info.message = builder.m_stream.str();
  7569. getResultCapture().pushScopedMessage( m_info );
  7570. }
  7571. ScopedMessage::~ScopedMessage() {
  7572. if ( !uncaught_exceptions() ){
  7573. getResultCapture().popScopedMessage(m_info);
  7574. }
  7575. }
  7576. Capturer::Capturer( StringRef macroName, SourceLineInfo const& lineInfo, ResultWas::OfType resultType, StringRef names ) {
  7577. auto trimmed = [&] (size_t start, size_t end) {
  7578. while (names[start] == ',' || isspace(names[start])) {
  7579. ++start;
  7580. }
  7581. while (names[end] == ',' || isspace(names[end])) {
  7582. --end;
  7583. }
  7584. return names.substr(start, end - start + 1);
  7585. };
  7586. size_t start = 0;
  7587. std::stack<char> openings;
  7588. for (size_t pos = 0; pos < names.size(); ++pos) {
  7589. char c = names[pos];
  7590. switch (c) {
  7591. case '[':
  7592. case '{':
  7593. case '(':
  7594. // It is basically impossible to disambiguate between
  7595. // comparison and start of template args in this context
  7596. // case '<':
  7597. openings.push(c);
  7598. break;
  7599. case ']':
  7600. case '}':
  7601. case ')':
  7602. // case '>':
  7603. openings.pop();
  7604. break;
  7605. case ',':
  7606. if (start != pos && openings.size() == 0) {
  7607. m_messages.emplace_back(macroName, lineInfo, resultType);
  7608. m_messages.back().message = trimmed(start, pos);
  7609. m_messages.back().message += " := ";
  7610. start = pos;
  7611. }
  7612. }
  7613. }
  7614. assert(openings.size() == 0 && "Mismatched openings");
  7615. m_messages.emplace_back(macroName, lineInfo, resultType);
  7616. m_messages.back().message = trimmed(start, names.size() - 1);
  7617. m_messages.back().message += " := ";
  7618. }
  7619. Capturer::~Capturer() {
  7620. if ( !uncaught_exceptions() ){
  7621. assert( m_captured == m_messages.size() );
  7622. for( size_t i = 0; i < m_captured; ++i )
  7623. m_resultCapture.popScopedMessage( m_messages[i] );
  7624. }
  7625. }
  7626. void Capturer::captureValue( size_t index, std::string const& value ) {
  7627. assert( index < m_messages.size() );
  7628. m_messages[index].message += value;
  7629. m_resultCapture.pushScopedMessage( m_messages[index] );
  7630. m_captured++;
  7631. }
  7632. } // end namespace Catch
  7633. // end catch_message.cpp
  7634. // start catch_output_redirect.cpp
  7635. // start catch_output_redirect.h
  7636. #ifndef TWOBLUECUBES_CATCH_OUTPUT_REDIRECT_H
  7637. #define TWOBLUECUBES_CATCH_OUTPUT_REDIRECT_H
  7638. #include <cstdio>
  7639. #include <iosfwd>
  7640. #include <string>
  7641. namespace Catch {
  7642. class RedirectedStream {
  7643. std::ostream& m_originalStream;
  7644. std::ostream& m_redirectionStream;
  7645. std::streambuf* m_prevBuf;
  7646. public:
  7647. RedirectedStream( std::ostream& originalStream, std::ostream& redirectionStream );
  7648. ~RedirectedStream();
  7649. };
  7650. class RedirectedStdOut {
  7651. ReusableStringStream m_rss;
  7652. RedirectedStream m_cout;
  7653. public:
  7654. RedirectedStdOut();
  7655. auto str() const -> std::string;
  7656. };
  7657. // StdErr has two constituent streams in C++, std::cerr and std::clog
  7658. // This means that we need to redirect 2 streams into 1 to keep proper
  7659. // order of writes
  7660. class RedirectedStdErr {
  7661. ReusableStringStream m_rss;
  7662. RedirectedStream m_cerr;
  7663. RedirectedStream m_clog;
  7664. public:
  7665. RedirectedStdErr();
  7666. auto str() const -> std::string;
  7667. };
  7668. #if defined(CATCH_CONFIG_NEW_CAPTURE)
  7669. // Windows's implementation of std::tmpfile is terrible (it tries
  7670. // to create a file inside system folder, thus requiring elevated
  7671. // privileges for the binary), so we have to use tmpnam(_s) and
  7672. // create the file ourselves there.
  7673. class TempFile {
  7674. public:
  7675. TempFile(TempFile const&) = delete;
  7676. TempFile& operator=(TempFile const&) = delete;
  7677. TempFile(TempFile&&) = delete;
  7678. TempFile& operator=(TempFile&&) = delete;
  7679. TempFile();
  7680. ~TempFile();
  7681. std::FILE* getFile();
  7682. std::string getContents();
  7683. private:
  7684. std::FILE* m_file = nullptr;
  7685. #if defined(_MSC_VER)
  7686. char m_buffer[L_tmpnam] = { 0 };
  7687. #endif
  7688. };
  7689. class OutputRedirect {
  7690. public:
  7691. OutputRedirect(OutputRedirect const&) = delete;
  7692. OutputRedirect& operator=(OutputRedirect const&) = delete;
  7693. OutputRedirect(OutputRedirect&&) = delete;
  7694. OutputRedirect& operator=(OutputRedirect&&) = delete;
  7695. OutputRedirect(std::string& stdout_dest, std::string& stderr_dest);
  7696. ~OutputRedirect();
  7697. private:
  7698. int m_originalStdout = -1;
  7699. int m_originalStderr = -1;
  7700. TempFile m_stdoutFile;
  7701. TempFile m_stderrFile;
  7702. std::string& m_stdoutDest;
  7703. std::string& m_stderrDest;
  7704. };
  7705. #endif
  7706. } // end namespace Catch
  7707. #endif // TWOBLUECUBES_CATCH_OUTPUT_REDIRECT_H
  7708. // end catch_output_redirect.h
  7709. #include <cstdio>
  7710. #include <cstring>
  7711. #include <fstream>
  7712. #include <sstream>
  7713. #include <stdexcept>
  7714. #if defined(CATCH_CONFIG_NEW_CAPTURE)
  7715. #if defined(_MSC_VER)
  7716. #include <io.h> //_dup and _dup2
  7717. #define dup _dup
  7718. #define dup2 _dup2
  7719. #define fileno _fileno
  7720. #else
  7721. #include <unistd.h> // dup and dup2
  7722. #endif
  7723. #endif
  7724. namespace Catch {
  7725. RedirectedStream::RedirectedStream( std::ostream& originalStream, std::ostream& redirectionStream )
  7726. : m_originalStream( originalStream ),
  7727. m_redirectionStream( redirectionStream ),
  7728. m_prevBuf( m_originalStream.rdbuf() )
  7729. {
  7730. m_originalStream.rdbuf( m_redirectionStream.rdbuf() );
  7731. }
  7732. RedirectedStream::~RedirectedStream() {
  7733. m_originalStream.rdbuf( m_prevBuf );
  7734. }
  7735. RedirectedStdOut::RedirectedStdOut() : m_cout( Catch::cout(), m_rss.get() ) {}
  7736. auto RedirectedStdOut::str() const -> std::string { return m_rss.str(); }
  7737. RedirectedStdErr::RedirectedStdErr()
  7738. : m_cerr( Catch::cerr(), m_rss.get() ),
  7739. m_clog( Catch::clog(), m_rss.get() )
  7740. {}
  7741. auto RedirectedStdErr::str() const -> std::string { return m_rss.str(); }
  7742. #if defined(CATCH_CONFIG_NEW_CAPTURE)
  7743. #if defined(_MSC_VER)
  7744. TempFile::TempFile() {
  7745. if (tmpnam_s(m_buffer)) {
  7746. CATCH_RUNTIME_ERROR("Could not get a temp filename");
  7747. }
  7748. if (fopen_s(&m_file, m_buffer, "w")) {
  7749. char buffer[100];
  7750. if (strerror_s(buffer, errno)) {
  7751. CATCH_RUNTIME_ERROR("Could not translate errno to a string");
  7752. }
  7753. CATCH_RUNTIME_ERROR("Coul dnot open the temp file: '" << m_buffer << "' because: " << buffer);
  7754. }
  7755. }
  7756. #else
  7757. TempFile::TempFile() {
  7758. m_file = std::tmpfile();
  7759. if (!m_file) {
  7760. CATCH_RUNTIME_ERROR("Could not create a temp file.");
  7761. }
  7762. }
  7763. #endif
  7764. TempFile::~TempFile() {
  7765. // TBD: What to do about errors here?
  7766. std::fclose(m_file);
  7767. // We manually create the file on Windows only, on Linux
  7768. // it will be autodeleted
  7769. #if defined(_MSC_VER)
  7770. std::remove(m_buffer);
  7771. #endif
  7772. }
  7773. FILE* TempFile::getFile() {
  7774. return m_file;
  7775. }
  7776. std::string TempFile::getContents() {
  7777. std::stringstream sstr;
  7778. char buffer[100] = {};
  7779. std::rewind(m_file);
  7780. while (std::fgets(buffer, sizeof(buffer), m_file)) {
  7781. sstr << buffer;
  7782. }
  7783. return sstr.str();
  7784. }
  7785. OutputRedirect::OutputRedirect(std::string& stdout_dest, std::string& stderr_dest) :
  7786. m_originalStdout(dup(1)),
  7787. m_originalStderr(dup(2)),
  7788. m_stdoutDest(stdout_dest),
  7789. m_stderrDest(stderr_dest) {
  7790. dup2(fileno(m_stdoutFile.getFile()), 1);
  7791. dup2(fileno(m_stderrFile.getFile()), 2);
  7792. }
  7793. OutputRedirect::~OutputRedirect() {
  7794. Catch::cout() << std::flush;
  7795. fflush(stdout);
  7796. // Since we support overriding these streams, we flush cerr
  7797. // even though std::cerr is unbuffered
  7798. Catch::cerr() << std::flush;
  7799. Catch::clog() << std::flush;
  7800. fflush(stderr);
  7801. dup2(m_originalStdout, 1);
  7802. dup2(m_originalStderr, 2);
  7803. m_stdoutDest += m_stdoutFile.getContents();
  7804. m_stderrDest += m_stderrFile.getContents();
  7805. }
  7806. #endif // CATCH_CONFIG_NEW_CAPTURE
  7807. } // namespace Catch
  7808. #if defined(CATCH_CONFIG_NEW_CAPTURE)
  7809. #if defined(_MSC_VER)
  7810. #undef dup
  7811. #undef dup2
  7812. #undef fileno
  7813. #endif
  7814. #endif
  7815. // end catch_output_redirect.cpp
  7816. // start catch_polyfills.cpp
  7817. #include <cmath>
  7818. namespace Catch {
  7819. #if !defined(CATCH_CONFIG_POLYFILL_ISNAN)
  7820. bool isnan(float f) {
  7821. return std::isnan(f);
  7822. }
  7823. bool isnan(double d) {
  7824. return std::isnan(d);
  7825. }
  7826. #else
  7827. // For now we only use this for embarcadero
  7828. bool isnan(float f) {
  7829. return std::_isnan(f);
  7830. }
  7831. bool isnan(double d) {
  7832. return std::_isnan(d);
  7833. }
  7834. #endif
  7835. } // end namespace Catch
  7836. // end catch_polyfills.cpp
  7837. // start catch_random_number_generator.cpp
  7838. namespace Catch {
  7839. std::mt19937& rng() {
  7840. static std::mt19937 s_rng;
  7841. return s_rng;
  7842. }
  7843. void seedRng( IConfig const& config ) {
  7844. if( config.rngSeed() != 0 ) {
  7845. std::srand( config.rngSeed() );
  7846. rng().seed( config.rngSeed() );
  7847. }
  7848. }
  7849. unsigned int rngSeed() {
  7850. return getCurrentContext().getConfig()->rngSeed();
  7851. }
  7852. }
  7853. // end catch_random_number_generator.cpp
  7854. // start catch_registry_hub.cpp
  7855. // start catch_test_case_registry_impl.h
  7856. #include <vector>
  7857. #include <set>
  7858. #include <algorithm>
  7859. #include <ios>
  7860. namespace Catch {
  7861. class TestCase;
  7862. struct IConfig;
  7863. std::vector<TestCase> sortTests( IConfig const& config, std::vector<TestCase> const& unsortedTestCases );
  7864. bool matchTest( TestCase const& testCase, TestSpec const& testSpec, IConfig const& config );
  7865. void enforceNoDuplicateTestCases( std::vector<TestCase> const& functions );
  7866. std::vector<TestCase> filterTests( std::vector<TestCase> const& testCases, TestSpec const& testSpec, IConfig const& config );
  7867. std::vector<TestCase> const& getAllTestCasesSorted( IConfig const& config );
  7868. class TestRegistry : public ITestCaseRegistry {
  7869. public:
  7870. virtual ~TestRegistry() = default;
  7871. virtual void registerTest( TestCase const& testCase );
  7872. std::vector<TestCase> const& getAllTests() const override;
  7873. std::vector<TestCase> const& getAllTestsSorted( IConfig const& config ) const override;
  7874. private:
  7875. std::vector<TestCase> m_functions;
  7876. mutable RunTests::InWhatOrder m_currentSortOrder = RunTests::InDeclarationOrder;
  7877. mutable std::vector<TestCase> m_sortedFunctions;
  7878. std::size_t m_unnamedCount = 0;
  7879. std::ios_base::Init m_ostreamInit; // Forces cout/ cerr to be initialised
  7880. };
  7881. ///////////////////////////////////////////////////////////////////////////
  7882. class TestInvokerAsFunction : public ITestInvoker {
  7883. void(*m_testAsFunction)();
  7884. public:
  7885. TestInvokerAsFunction( void(*testAsFunction)() ) noexcept;
  7886. void invoke() const override;
  7887. };
  7888. std::string extractClassName( StringRef const& classOrQualifiedMethodName );
  7889. ///////////////////////////////////////////////////////////////////////////
  7890. } // end namespace Catch
  7891. // end catch_test_case_registry_impl.h
  7892. // start catch_reporter_registry.h
  7893. #include <map>
  7894. namespace Catch {
  7895. class ReporterRegistry : public IReporterRegistry {
  7896. public:
  7897. ~ReporterRegistry() override;
  7898. IStreamingReporterPtr create( std::string const& name, IConfigPtr const& config ) const override;
  7899. void registerReporter( std::string const& name, IReporterFactoryPtr const& factory );
  7900. void registerListener( IReporterFactoryPtr const& factory );
  7901. FactoryMap const& getFactories() const override;
  7902. Listeners const& getListeners() const override;
  7903. private:
  7904. FactoryMap m_factories;
  7905. Listeners m_listeners;
  7906. };
  7907. }
  7908. // end catch_reporter_registry.h
  7909. // start catch_tag_alias_registry.h
  7910. // start catch_tag_alias.h
  7911. #include <string>
  7912. namespace Catch {
  7913. struct TagAlias {
  7914. TagAlias(std::string const& _tag, SourceLineInfo _lineInfo);
  7915. std::string tag;
  7916. SourceLineInfo lineInfo;
  7917. };
  7918. } // end namespace Catch
  7919. // end catch_tag_alias.h
  7920. #include <map>
  7921. namespace Catch {
  7922. class TagAliasRegistry : public ITagAliasRegistry {
  7923. public:
  7924. ~TagAliasRegistry() override;
  7925. TagAlias const* find( std::string const& alias ) const override;
  7926. std::string expandAliases( std::string const& unexpandedTestSpec ) const override;
  7927. void add( std::string const& alias, std::string const& tag, SourceLineInfo const& lineInfo );
  7928. private:
  7929. std::map<std::string, TagAlias> m_registry;
  7930. };
  7931. } // end namespace Catch
  7932. // end catch_tag_alias_registry.h
  7933. // start catch_startup_exception_registry.h
  7934. #include <vector>
  7935. #include <exception>
  7936. namespace Catch {
  7937. class StartupExceptionRegistry {
  7938. public:
  7939. void add(std::exception_ptr const& exception) noexcept;
  7940. std::vector<std::exception_ptr> const& getExceptions() const noexcept;
  7941. private:
  7942. std::vector<std::exception_ptr> m_exceptions;
  7943. };
  7944. } // end namespace Catch
  7945. // end catch_startup_exception_registry.h
  7946. // start catch_singletons.hpp
  7947. namespace Catch {
  7948. struct ISingleton {
  7949. virtual ~ISingleton();
  7950. };
  7951. void addSingleton( ISingleton* singleton );
  7952. void cleanupSingletons();
  7953. template<typename SingletonImplT, typename InterfaceT = SingletonImplT, typename MutableInterfaceT = InterfaceT>
  7954. class Singleton : SingletonImplT, public ISingleton {
  7955. static auto getInternal() -> Singleton* {
  7956. static Singleton* s_instance = nullptr;
  7957. if( !s_instance ) {
  7958. s_instance = new Singleton;
  7959. addSingleton( s_instance );
  7960. }
  7961. return s_instance;
  7962. }
  7963. public:
  7964. static auto get() -> InterfaceT const& {
  7965. return *getInternal();
  7966. }
  7967. static auto getMutable() -> MutableInterfaceT& {
  7968. return *getInternal();
  7969. }
  7970. };
  7971. } // namespace Catch
  7972. // end catch_singletons.hpp
  7973. namespace Catch {
  7974. namespace {
  7975. class RegistryHub : public IRegistryHub, public IMutableRegistryHub,
  7976. private NonCopyable {
  7977. public: // IRegistryHub
  7978. RegistryHub() = default;
  7979. IReporterRegistry const& getReporterRegistry() const override {
  7980. return m_reporterRegistry;
  7981. }
  7982. ITestCaseRegistry const& getTestCaseRegistry() const override {
  7983. return m_testCaseRegistry;
  7984. }
  7985. IExceptionTranslatorRegistry const& getExceptionTranslatorRegistry() const override {
  7986. return m_exceptionTranslatorRegistry;
  7987. }
  7988. ITagAliasRegistry const& getTagAliasRegistry() const override {
  7989. return m_tagAliasRegistry;
  7990. }
  7991. StartupExceptionRegistry const& getStartupExceptionRegistry() const override {
  7992. return m_exceptionRegistry;
  7993. }
  7994. public: // IMutableRegistryHub
  7995. void registerReporter( std::string const& name, IReporterFactoryPtr const& factory ) override {
  7996. m_reporterRegistry.registerReporter( name, factory );
  7997. }
  7998. void registerListener( IReporterFactoryPtr const& factory ) override {
  7999. m_reporterRegistry.registerListener( factory );
  8000. }
  8001. void registerTest( TestCase const& testInfo ) override {
  8002. m_testCaseRegistry.registerTest( testInfo );
  8003. }
  8004. void registerTranslator( const IExceptionTranslator* translator ) override {
  8005. m_exceptionTranslatorRegistry.registerTranslator( translator );
  8006. }
  8007. void registerTagAlias( std::string const& alias, std::string const& tag, SourceLineInfo const& lineInfo ) override {
  8008. m_tagAliasRegistry.add( alias, tag, lineInfo );
  8009. }
  8010. void registerStartupException() noexcept override {
  8011. m_exceptionRegistry.add(std::current_exception());
  8012. }
  8013. private:
  8014. TestRegistry m_testCaseRegistry;
  8015. ReporterRegistry m_reporterRegistry;
  8016. ExceptionTranslatorRegistry m_exceptionTranslatorRegistry;
  8017. TagAliasRegistry m_tagAliasRegistry;
  8018. StartupExceptionRegistry m_exceptionRegistry;
  8019. };
  8020. }
  8021. using RegistryHubSingleton = Singleton<RegistryHub, IRegistryHub, IMutableRegistryHub>;
  8022. IRegistryHub const& getRegistryHub() {
  8023. return RegistryHubSingleton::get();
  8024. }
  8025. IMutableRegistryHub& getMutableRegistryHub() {
  8026. return RegistryHubSingleton::getMutable();
  8027. }
  8028. void cleanUp() {
  8029. cleanupSingletons();
  8030. cleanUpContext();
  8031. }
  8032. std::string translateActiveException() {
  8033. return getRegistryHub().getExceptionTranslatorRegistry().translateActiveException();
  8034. }
  8035. } // end namespace Catch
  8036. // end catch_registry_hub.cpp
  8037. // start catch_reporter_registry.cpp
  8038. namespace Catch {
  8039. ReporterRegistry::~ReporterRegistry() = default;
  8040. IStreamingReporterPtr ReporterRegistry::create( std::string const& name, IConfigPtr const& config ) const {
  8041. auto it = m_factories.find( name );
  8042. if( it == m_factories.end() )
  8043. return nullptr;
  8044. return it->second->create( ReporterConfig( config ) );
  8045. }
  8046. void ReporterRegistry::registerReporter( std::string const& name, IReporterFactoryPtr const& factory ) {
  8047. m_factories.emplace(name, factory);
  8048. }
  8049. void ReporterRegistry::registerListener( IReporterFactoryPtr const& factory ) {
  8050. m_listeners.push_back( factory );
  8051. }
  8052. IReporterRegistry::FactoryMap const& ReporterRegistry::getFactories() const {
  8053. return m_factories;
  8054. }
  8055. IReporterRegistry::Listeners const& ReporterRegistry::getListeners() const {
  8056. return m_listeners;
  8057. }
  8058. }
  8059. // end catch_reporter_registry.cpp
  8060. // start catch_result_type.cpp
  8061. namespace Catch {
  8062. bool isOk( ResultWas::OfType resultType ) {
  8063. return ( resultType & ResultWas::FailureBit ) == 0;
  8064. }
  8065. bool isJustInfo( int flags ) {
  8066. return flags == ResultWas::Info;
  8067. }
  8068. ResultDisposition::Flags operator | ( ResultDisposition::Flags lhs, ResultDisposition::Flags rhs ) {
  8069. return static_cast<ResultDisposition::Flags>( static_cast<int>( lhs ) | static_cast<int>( rhs ) );
  8070. }
  8071. bool shouldContinueOnFailure( int flags ) { return ( flags & ResultDisposition::ContinueOnFailure ) != 0; }
  8072. bool shouldSuppressFailure( int flags ) { return ( flags & ResultDisposition::SuppressFail ) != 0; }
  8073. } // end namespace Catch
  8074. // end catch_result_type.cpp
  8075. // start catch_run_context.cpp
  8076. #include <cassert>
  8077. #include <algorithm>
  8078. #include <sstream>
  8079. namespace Catch {
  8080. namespace Generators {
  8081. struct GeneratorTracker : TestCaseTracking::TrackerBase, IGeneratorTracker {
  8082. GeneratorBasePtr m_generator;
  8083. GeneratorTracker( TestCaseTracking::NameAndLocation const& nameAndLocation, TrackerContext& ctx, ITracker* parent )
  8084. : TrackerBase( nameAndLocation, ctx, parent )
  8085. {}
  8086. ~GeneratorTracker();
  8087. static GeneratorTracker& acquire( TrackerContext& ctx, TestCaseTracking::NameAndLocation const& nameAndLocation ) {
  8088. std::shared_ptr<GeneratorTracker> tracker;
  8089. ITracker& currentTracker = ctx.currentTracker();
  8090. if( TestCaseTracking::ITrackerPtr childTracker = currentTracker.findChild( nameAndLocation ) ) {
  8091. assert( childTracker );
  8092. assert( childTracker->isGeneratorTracker() );
  8093. tracker = std::static_pointer_cast<GeneratorTracker>( childTracker );
  8094. }
  8095. else {
  8096. tracker = std::make_shared<GeneratorTracker>( nameAndLocation, ctx, &currentTracker );
  8097. currentTracker.addChild( tracker );
  8098. }
  8099. if( !ctx.completedCycle() && !tracker->isComplete() ) {
  8100. tracker->open();
  8101. }
  8102. return *tracker;
  8103. }
  8104. // TrackerBase interface
  8105. bool isGeneratorTracker() const override { return true; }
  8106. auto hasGenerator() const -> bool override {
  8107. return !!m_generator;
  8108. }
  8109. void close() override {
  8110. TrackerBase::close();
  8111. // Generator interface only finds out if it has another item on atual move
  8112. if (m_runState == CompletedSuccessfully && m_generator->next()) {
  8113. m_children.clear();
  8114. m_runState = Executing;
  8115. }
  8116. }
  8117. // IGeneratorTracker interface
  8118. auto getGenerator() const -> GeneratorBasePtr const& override {
  8119. return m_generator;
  8120. }
  8121. void setGenerator( GeneratorBasePtr&& generator ) override {
  8122. m_generator = std::move( generator );
  8123. }
  8124. };
  8125. GeneratorTracker::~GeneratorTracker() {}
  8126. }
  8127. RunContext::RunContext(IConfigPtr const& _config, IStreamingReporterPtr&& reporter)
  8128. : m_runInfo(_config->name()),
  8129. m_context(getCurrentMutableContext()),
  8130. m_config(_config),
  8131. m_reporter(std::move(reporter)),
  8132. m_lastAssertionInfo{ StringRef(), SourceLineInfo("",0), StringRef(), ResultDisposition::Normal },
  8133. m_includeSuccessfulResults( m_config->includeSuccessfulResults() || m_reporter->getPreferences().shouldReportAllAssertions )
  8134. {
  8135. m_context.setRunner(this);
  8136. m_context.setConfig(m_config);
  8137. m_context.setResultCapture(this);
  8138. m_reporter->testRunStarting(m_runInfo);
  8139. }
  8140. RunContext::~RunContext() {
  8141. m_reporter->testRunEnded(TestRunStats(m_runInfo, m_totals, aborting()));
  8142. }
  8143. void RunContext::testGroupStarting(std::string const& testSpec, std::size_t groupIndex, std::size_t groupsCount) {
  8144. m_reporter->testGroupStarting(GroupInfo(testSpec, groupIndex, groupsCount));
  8145. }
  8146. void RunContext::testGroupEnded(std::string const& testSpec, Totals const& totals, std::size_t groupIndex, std::size_t groupsCount) {
  8147. m_reporter->testGroupEnded(TestGroupStats(GroupInfo(testSpec, groupIndex, groupsCount), totals, aborting()));
  8148. }
  8149. Totals RunContext::runTest(TestCase const& testCase) {
  8150. Totals prevTotals = m_totals;
  8151. std::string redirectedCout;
  8152. std::string redirectedCerr;
  8153. auto const& testInfo = testCase.getTestCaseInfo();
  8154. m_reporter->testCaseStarting(testInfo);
  8155. m_activeTestCase = &testCase;
  8156. ITracker& rootTracker = m_trackerContext.startRun();
  8157. assert(rootTracker.isSectionTracker());
  8158. static_cast<SectionTracker&>(rootTracker).addInitialFilters(m_config->getSectionsToRun());
  8159. do {
  8160. m_trackerContext.startCycle();
  8161. m_testCaseTracker = &SectionTracker::acquire(m_trackerContext, TestCaseTracking::NameAndLocation(testInfo.name, testInfo.lineInfo));
  8162. runCurrentTest(redirectedCout, redirectedCerr);
  8163. } while (!m_testCaseTracker->isSuccessfullyCompleted() && !aborting());
  8164. Totals deltaTotals = m_totals.delta(prevTotals);
  8165. if (testInfo.expectedToFail() && deltaTotals.testCases.passed > 0) {
  8166. deltaTotals.assertions.failed++;
  8167. deltaTotals.testCases.passed--;
  8168. deltaTotals.testCases.failed++;
  8169. }
  8170. m_totals.testCases += deltaTotals.testCases;
  8171. m_reporter->testCaseEnded(TestCaseStats(testInfo,
  8172. deltaTotals,
  8173. redirectedCout,
  8174. redirectedCerr,
  8175. aborting()));
  8176. m_activeTestCase = nullptr;
  8177. m_testCaseTracker = nullptr;
  8178. return deltaTotals;
  8179. }
  8180. IConfigPtr RunContext::config() const {
  8181. return m_config;
  8182. }
  8183. IStreamingReporter& RunContext::reporter() const {
  8184. return *m_reporter;
  8185. }
  8186. void RunContext::assertionEnded(AssertionResult const & result) {
  8187. if (result.getResultType() == ResultWas::Ok) {
  8188. m_totals.assertions.passed++;
  8189. m_lastAssertionPassed = true;
  8190. } else if (!result.isOk()) {
  8191. m_lastAssertionPassed = false;
  8192. if( m_activeTestCase->getTestCaseInfo().okToFail() )
  8193. m_totals.assertions.failedButOk++;
  8194. else
  8195. m_totals.assertions.failed++;
  8196. }
  8197. else {
  8198. m_lastAssertionPassed = true;
  8199. }
  8200. // We have no use for the return value (whether messages should be cleared), because messages were made scoped
  8201. // and should be let to clear themselves out.
  8202. static_cast<void>(m_reporter->assertionEnded(AssertionStats(result, m_messages, m_totals)));
  8203. // Reset working state
  8204. resetAssertionInfo();
  8205. m_lastResult = result;
  8206. }
  8207. void RunContext::resetAssertionInfo() {
  8208. m_lastAssertionInfo.macroName = StringRef();
  8209. m_lastAssertionInfo.capturedExpression = "{Unknown expression after the reported line}"_sr;
  8210. }
  8211. bool RunContext::sectionStarted(SectionInfo const & sectionInfo, Counts & assertions) {
  8212. ITracker& sectionTracker = SectionTracker::acquire(m_trackerContext, TestCaseTracking::NameAndLocation(sectionInfo.name, sectionInfo.lineInfo));
  8213. if (!sectionTracker.isOpen())
  8214. return false;
  8215. m_activeSections.push_back(&sectionTracker);
  8216. m_lastAssertionInfo.lineInfo = sectionInfo.lineInfo;
  8217. m_reporter->sectionStarting(sectionInfo);
  8218. assertions = m_totals.assertions;
  8219. return true;
  8220. }
  8221. auto RunContext::acquireGeneratorTracker( SourceLineInfo const& lineInfo ) -> IGeneratorTracker& {
  8222. using namespace Generators;
  8223. GeneratorTracker& tracker = GeneratorTracker::acquire( m_trackerContext, TestCaseTracking::NameAndLocation( "generator", lineInfo ) );
  8224. assert( tracker.isOpen() );
  8225. m_lastAssertionInfo.lineInfo = lineInfo;
  8226. return tracker;
  8227. }
  8228. bool RunContext::testForMissingAssertions(Counts& assertions) {
  8229. if (assertions.total() != 0)
  8230. return false;
  8231. if (!m_config->warnAboutMissingAssertions())
  8232. return false;
  8233. if (m_trackerContext.currentTracker().hasChildren())
  8234. return false;
  8235. m_totals.assertions.failed++;
  8236. assertions.failed++;
  8237. return true;
  8238. }
  8239. void RunContext::sectionEnded(SectionEndInfo const & endInfo) {
  8240. Counts assertions = m_totals.assertions - endInfo.prevAssertions;
  8241. bool missingAssertions = testForMissingAssertions(assertions);
  8242. if (!m_activeSections.empty()) {
  8243. m_activeSections.back()->close();
  8244. m_activeSections.pop_back();
  8245. }
  8246. m_reporter->sectionEnded(SectionStats(endInfo.sectionInfo, assertions, endInfo.durationInSeconds, missingAssertions));
  8247. m_messages.clear();
  8248. }
  8249. void RunContext::sectionEndedEarly(SectionEndInfo const & endInfo) {
  8250. if (m_unfinishedSections.empty())
  8251. m_activeSections.back()->fail();
  8252. else
  8253. m_activeSections.back()->close();
  8254. m_activeSections.pop_back();
  8255. m_unfinishedSections.push_back(endInfo);
  8256. }
  8257. void RunContext::benchmarkStarting( BenchmarkInfo const& info ) {
  8258. m_reporter->benchmarkStarting( info );
  8259. }
  8260. void RunContext::benchmarkEnded( BenchmarkStats const& stats ) {
  8261. m_reporter->benchmarkEnded( stats );
  8262. }
  8263. void RunContext::pushScopedMessage(MessageInfo const & message) {
  8264. m_messages.push_back(message);
  8265. }
  8266. void RunContext::popScopedMessage(MessageInfo const & message) {
  8267. m_messages.erase(std::remove(m_messages.begin(), m_messages.end(), message), m_messages.end());
  8268. }
  8269. std::string RunContext::getCurrentTestName() const {
  8270. return m_activeTestCase
  8271. ? m_activeTestCase->getTestCaseInfo().name
  8272. : std::string();
  8273. }
  8274. const AssertionResult * RunContext::getLastResult() const {
  8275. return &(*m_lastResult);
  8276. }
  8277. void RunContext::exceptionEarlyReported() {
  8278. m_shouldReportUnexpected = false;
  8279. }
  8280. void RunContext::handleFatalErrorCondition( StringRef message ) {
  8281. // First notify reporter that bad things happened
  8282. m_reporter->fatalErrorEncountered(message);
  8283. // Don't rebuild the result -- the stringification itself can cause more fatal errors
  8284. // Instead, fake a result data.
  8285. AssertionResultData tempResult( ResultWas::FatalErrorCondition, { false } );
  8286. tempResult.message = message;
  8287. AssertionResult result(m_lastAssertionInfo, tempResult);
  8288. assertionEnded(result);
  8289. handleUnfinishedSections();
  8290. // Recreate section for test case (as we will lose the one that was in scope)
  8291. auto const& testCaseInfo = m_activeTestCase->getTestCaseInfo();
  8292. SectionInfo testCaseSection(testCaseInfo.lineInfo, testCaseInfo.name);
  8293. Counts assertions;
  8294. assertions.failed = 1;
  8295. SectionStats testCaseSectionStats(testCaseSection, assertions, 0, false);
  8296. m_reporter->sectionEnded(testCaseSectionStats);
  8297. auto const& testInfo = m_activeTestCase->getTestCaseInfo();
  8298. Totals deltaTotals;
  8299. deltaTotals.testCases.failed = 1;
  8300. deltaTotals.assertions.failed = 1;
  8301. m_reporter->testCaseEnded(TestCaseStats(testInfo,
  8302. deltaTotals,
  8303. std::string(),
  8304. std::string(),
  8305. false));
  8306. m_totals.testCases.failed++;
  8307. testGroupEnded(std::string(), m_totals, 1, 1);
  8308. m_reporter->testRunEnded(TestRunStats(m_runInfo, m_totals, false));
  8309. }
  8310. bool RunContext::lastAssertionPassed() {
  8311. return m_lastAssertionPassed;
  8312. }
  8313. void RunContext::assertionPassed() {
  8314. m_lastAssertionPassed = true;
  8315. ++m_totals.assertions.passed;
  8316. resetAssertionInfo();
  8317. }
  8318. bool RunContext::aborting() const {
  8319. return m_totals.assertions.failed >= static_cast<std::size_t>(m_config->abortAfter());
  8320. }
  8321. void RunContext::runCurrentTest(std::string & redirectedCout, std::string & redirectedCerr) {
  8322. auto const& testCaseInfo = m_activeTestCase->getTestCaseInfo();
  8323. SectionInfo testCaseSection(testCaseInfo.lineInfo, testCaseInfo.name);
  8324. m_reporter->sectionStarting(testCaseSection);
  8325. Counts prevAssertions = m_totals.assertions;
  8326. double duration = 0;
  8327. m_shouldReportUnexpected = true;
  8328. m_lastAssertionInfo = { "TEST_CASE"_sr, testCaseInfo.lineInfo, StringRef(), ResultDisposition::Normal };
  8329. seedRng(*m_config);
  8330. Timer timer;
  8331. CATCH_TRY {
  8332. if (m_reporter->getPreferences().shouldRedirectStdOut) {
  8333. #if !defined(CATCH_CONFIG_EXPERIMENTAL_REDIRECT)
  8334. RedirectedStdOut redirectedStdOut;
  8335. RedirectedStdErr redirectedStdErr;
  8336. timer.start();
  8337. invokeActiveTestCase();
  8338. redirectedCout += redirectedStdOut.str();
  8339. redirectedCerr += redirectedStdErr.str();
  8340. #else
  8341. OutputRedirect r(redirectedCout, redirectedCerr);
  8342. timer.start();
  8343. invokeActiveTestCase();
  8344. #endif
  8345. } else {
  8346. timer.start();
  8347. invokeActiveTestCase();
  8348. }
  8349. duration = timer.getElapsedSeconds();
  8350. } CATCH_CATCH_ANON (TestFailureException&) {
  8351. // This just means the test was aborted due to failure
  8352. } CATCH_CATCH_ALL {
  8353. // Under CATCH_CONFIG_FAST_COMPILE, unexpected exceptions under REQUIRE assertions
  8354. // are reported without translation at the point of origin.
  8355. if( m_shouldReportUnexpected ) {
  8356. AssertionReaction dummyReaction;
  8357. handleUnexpectedInflightException( m_lastAssertionInfo, translateActiveException(), dummyReaction );
  8358. }
  8359. }
  8360. Counts assertions = m_totals.assertions - prevAssertions;
  8361. bool missingAssertions = testForMissingAssertions(assertions);
  8362. m_testCaseTracker->close();
  8363. handleUnfinishedSections();
  8364. m_messages.clear();
  8365. SectionStats testCaseSectionStats(testCaseSection, assertions, duration, missingAssertions);
  8366. m_reporter->sectionEnded(testCaseSectionStats);
  8367. }
  8368. void RunContext::invokeActiveTestCase() {
  8369. FatalConditionHandler fatalConditionHandler; // Handle signals
  8370. m_activeTestCase->invoke();
  8371. fatalConditionHandler.reset();
  8372. }
  8373. void RunContext::handleUnfinishedSections() {
  8374. // If sections ended prematurely due to an exception we stored their
  8375. // infos here so we can tear them down outside the unwind process.
  8376. for (auto it = m_unfinishedSections.rbegin(),
  8377. itEnd = m_unfinishedSections.rend();
  8378. it != itEnd;
  8379. ++it)
  8380. sectionEnded(*it);
  8381. m_unfinishedSections.clear();
  8382. }
  8383. void RunContext::handleExpr(
  8384. AssertionInfo const& info,
  8385. ITransientExpression const& expr,
  8386. AssertionReaction& reaction
  8387. ) {
  8388. m_reporter->assertionStarting( info );
  8389. bool negated = isFalseTest( info.resultDisposition );
  8390. bool result = expr.getResult() != negated;
  8391. if( result ) {
  8392. if (!m_includeSuccessfulResults) {
  8393. assertionPassed();
  8394. }
  8395. else {
  8396. reportExpr(info, ResultWas::Ok, &expr, negated);
  8397. }
  8398. }
  8399. else {
  8400. reportExpr(info, ResultWas::ExpressionFailed, &expr, negated );
  8401. populateReaction( reaction );
  8402. }
  8403. }
  8404. void RunContext::reportExpr(
  8405. AssertionInfo const &info,
  8406. ResultWas::OfType resultType,
  8407. ITransientExpression const *expr,
  8408. bool negated ) {
  8409. m_lastAssertionInfo = info;
  8410. AssertionResultData data( resultType, LazyExpression( negated ) );
  8411. AssertionResult assertionResult{ info, data };
  8412. assertionResult.m_resultData.lazyExpression.m_transientExpression = expr;
  8413. assertionEnded( assertionResult );
  8414. }
  8415. void RunContext::handleMessage(
  8416. AssertionInfo const& info,
  8417. ResultWas::OfType resultType,
  8418. StringRef const& message,
  8419. AssertionReaction& reaction
  8420. ) {
  8421. m_reporter->assertionStarting( info );
  8422. m_lastAssertionInfo = info;
  8423. AssertionResultData data( resultType, LazyExpression( false ) );
  8424. data.message = message;
  8425. AssertionResult assertionResult{ m_lastAssertionInfo, data };
  8426. assertionEnded( assertionResult );
  8427. if( !assertionResult.isOk() )
  8428. populateReaction( reaction );
  8429. }
  8430. void RunContext::handleUnexpectedExceptionNotThrown(
  8431. AssertionInfo const& info,
  8432. AssertionReaction& reaction
  8433. ) {
  8434. handleNonExpr(info, Catch::ResultWas::DidntThrowException, reaction);
  8435. }
  8436. void RunContext::handleUnexpectedInflightException(
  8437. AssertionInfo const& info,
  8438. std::string const& message,
  8439. AssertionReaction& reaction
  8440. ) {
  8441. m_lastAssertionInfo = info;
  8442. AssertionResultData data( ResultWas::ThrewException, LazyExpression( false ) );
  8443. data.message = message;
  8444. AssertionResult assertionResult{ info, data };
  8445. assertionEnded( assertionResult );
  8446. populateReaction( reaction );
  8447. }
  8448. void RunContext::populateReaction( AssertionReaction& reaction ) {
  8449. reaction.shouldDebugBreak = m_config->shouldDebugBreak();
  8450. reaction.shouldThrow = aborting() || (m_lastAssertionInfo.resultDisposition & ResultDisposition::Normal);
  8451. }
  8452. void RunContext::handleIncomplete(
  8453. AssertionInfo const& info
  8454. ) {
  8455. m_lastAssertionInfo = info;
  8456. AssertionResultData data( ResultWas::ThrewException, LazyExpression( false ) );
  8457. data.message = "Exception translation was disabled by CATCH_CONFIG_FAST_COMPILE";
  8458. AssertionResult assertionResult{ info, data };
  8459. assertionEnded( assertionResult );
  8460. }
  8461. void RunContext::handleNonExpr(
  8462. AssertionInfo const &info,
  8463. ResultWas::OfType resultType,
  8464. AssertionReaction &reaction
  8465. ) {
  8466. m_lastAssertionInfo = info;
  8467. AssertionResultData data( resultType, LazyExpression( false ) );
  8468. AssertionResult assertionResult{ info, data };
  8469. assertionEnded( assertionResult );
  8470. if( !assertionResult.isOk() )
  8471. populateReaction( reaction );
  8472. }
  8473. IResultCapture& getResultCapture() {
  8474. if (auto* capture = getCurrentContext().getResultCapture())
  8475. return *capture;
  8476. else
  8477. CATCH_INTERNAL_ERROR("No result capture instance");
  8478. }
  8479. }
  8480. // end catch_run_context.cpp
  8481. // start catch_section.cpp
  8482. namespace Catch {
  8483. Section::Section( SectionInfo const& info )
  8484. : m_info( info ),
  8485. m_sectionIncluded( getResultCapture().sectionStarted( m_info, m_assertions ) )
  8486. {
  8487. m_timer.start();
  8488. }
  8489. Section::~Section() {
  8490. if( m_sectionIncluded ) {
  8491. SectionEndInfo endInfo{ m_info, m_assertions, m_timer.getElapsedSeconds() };
  8492. if( uncaught_exceptions() )
  8493. getResultCapture().sectionEndedEarly( endInfo );
  8494. else
  8495. getResultCapture().sectionEnded( endInfo );
  8496. }
  8497. }
  8498. // This indicates whether the section should be executed or not
  8499. Section::operator bool() const {
  8500. return m_sectionIncluded;
  8501. }
  8502. } // end namespace Catch
  8503. // end catch_section.cpp
  8504. // start catch_section_info.cpp
  8505. namespace Catch {
  8506. SectionInfo::SectionInfo
  8507. ( SourceLineInfo const& _lineInfo,
  8508. std::string const& _name )
  8509. : name( _name ),
  8510. lineInfo( _lineInfo )
  8511. {}
  8512. } // end namespace Catch
  8513. // end catch_section_info.cpp
  8514. // start catch_session.cpp
  8515. // start catch_session.h
  8516. #include <memory>
  8517. namespace Catch {
  8518. class Session : NonCopyable {
  8519. public:
  8520. Session();
  8521. ~Session() override;
  8522. void showHelp() const;
  8523. void libIdentify();
  8524. int applyCommandLine( int argc, char const * const * argv );
  8525. #if defined(CATCH_CONFIG_WCHAR) && defined(WIN32) && defined(UNICODE)
  8526. int applyCommandLine( int argc, wchar_t const * const * argv );
  8527. #endif
  8528. void useConfigData( ConfigData const& configData );
  8529. template<typename CharT>
  8530. int run(int argc, CharT const * const argv[]) {
  8531. if (m_startupExceptions)
  8532. return 1;
  8533. int returnCode = applyCommandLine(argc, argv);
  8534. if (returnCode == 0)
  8535. returnCode = run();
  8536. return returnCode;
  8537. }
  8538. int run();
  8539. clara::Parser const& cli() const;
  8540. void cli( clara::Parser const& newParser );
  8541. ConfigData& configData();
  8542. Config& config();
  8543. private:
  8544. int runInternal();
  8545. clara::Parser m_cli;
  8546. ConfigData m_configData;
  8547. std::shared_ptr<Config> m_config;
  8548. bool m_startupExceptions = false;
  8549. };
  8550. } // end namespace Catch
  8551. // end catch_session.h
  8552. // start catch_version.h
  8553. #include <iosfwd>
  8554. namespace Catch {
  8555. // Versioning information
  8556. struct Version {
  8557. Version( Version const& ) = delete;
  8558. Version& operator=( Version const& ) = delete;
  8559. Version( unsigned int _majorVersion,
  8560. unsigned int _minorVersion,
  8561. unsigned int _patchNumber,
  8562. char const * const _branchName,
  8563. unsigned int _buildNumber );
  8564. unsigned int const majorVersion;
  8565. unsigned int const minorVersion;
  8566. unsigned int const patchNumber;
  8567. // buildNumber is only used if branchName is not null
  8568. char const * const branchName;
  8569. unsigned int const buildNumber;
  8570. friend std::ostream& operator << ( std::ostream& os, Version const& version );
  8571. };
  8572. Version const& libraryVersion();
  8573. }
  8574. // end catch_version.h
  8575. #include <cstdlib>
  8576. #include <iomanip>
  8577. namespace Catch {
  8578. namespace {
  8579. const int MaxExitCode = 255;
  8580. IStreamingReporterPtr createReporter(std::string const& reporterName, IConfigPtr const& config) {
  8581. auto reporter = Catch::getRegistryHub().getReporterRegistry().create(reporterName, config);
  8582. CATCH_ENFORCE(reporter, "No reporter registered with name: '" << reporterName << "'");
  8583. return reporter;
  8584. }
  8585. IStreamingReporterPtr makeReporter(std::shared_ptr<Config> const& config) {
  8586. if (Catch::getRegistryHub().getReporterRegistry().getListeners().empty()) {
  8587. return createReporter(config->getReporterName(), config);
  8588. }
  8589. // On older platforms, returning std::unique_ptr<ListeningReporter>
  8590. // when the return type is std::unique_ptr<IStreamingReporter>
  8591. // doesn't compile without a std::move call. However, this causes
  8592. // a warning on newer platforms. Thus, we have to work around
  8593. // it a bit and downcast the pointer manually.
  8594. auto ret = std::unique_ptr<IStreamingReporter>(new ListeningReporter);
  8595. auto& multi = static_cast<ListeningReporter&>(*ret);
  8596. auto const& listeners = Catch::getRegistryHub().getReporterRegistry().getListeners();
  8597. for (auto const& listener : listeners) {
  8598. multi.addListener(listener->create(Catch::ReporterConfig(config)));
  8599. }
  8600. multi.addReporter(createReporter(config->getReporterName(), config));
  8601. return ret;
  8602. }
  8603. Catch::Totals runTests(std::shared_ptr<Config> const& config) {
  8604. auto reporter = makeReporter(config);
  8605. RunContext context(config, std::move(reporter));
  8606. Totals totals;
  8607. context.testGroupStarting(config->name(), 1, 1);
  8608. TestSpec testSpec = config->testSpec();
  8609. auto const& allTestCases = getAllTestCasesSorted(*config);
  8610. for (auto const& testCase : allTestCases) {
  8611. if (!context.aborting() && matchTest(testCase, testSpec, *config))
  8612. totals += context.runTest(testCase);
  8613. else
  8614. context.reporter().skipTest(testCase);
  8615. }
  8616. if (config->warnAboutNoTests() && totals.testCases.total() == 0) {
  8617. ReusableStringStream testConfig;
  8618. bool first = true;
  8619. for (const auto& input : config->getTestsOrTags()) {
  8620. if (!first) { testConfig << ' '; }
  8621. first = false;
  8622. testConfig << input;
  8623. }
  8624. context.reporter().noMatchingTestCases(testConfig.str());
  8625. totals.error = -1;
  8626. }
  8627. context.testGroupEnded(config->name(), totals, 1, 1);
  8628. return totals;
  8629. }
  8630. void applyFilenamesAsTags(Catch::IConfig const& config) {
  8631. auto& tests = const_cast<std::vector<TestCase>&>(getAllTestCasesSorted(config));
  8632. for (auto& testCase : tests) {
  8633. auto tags = testCase.tags;
  8634. std::string filename = testCase.lineInfo.file;
  8635. auto lastSlash = filename.find_last_of("\\/");
  8636. if (lastSlash != std::string::npos) {
  8637. filename.erase(0, lastSlash);
  8638. filename[0] = '#';
  8639. }
  8640. auto lastDot = filename.find_last_of('.');
  8641. if (lastDot != std::string::npos) {
  8642. filename.erase(lastDot);
  8643. }
  8644. tags.push_back(std::move(filename));
  8645. setTags(testCase, tags);
  8646. }
  8647. }
  8648. } // anon namespace
  8649. Session::Session() {
  8650. static bool alreadyInstantiated = false;
  8651. if( alreadyInstantiated ) {
  8652. CATCH_TRY { CATCH_INTERNAL_ERROR( "Only one instance of Catch::Session can ever be used" ); }
  8653. CATCH_CATCH_ALL { getMutableRegistryHub().registerStartupException(); }
  8654. }
  8655. // There cannot be exceptions at startup in no-exception mode.
  8656. #if !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
  8657. const auto& exceptions = getRegistryHub().getStartupExceptionRegistry().getExceptions();
  8658. if ( !exceptions.empty() ) {
  8659. m_startupExceptions = true;
  8660. Colour colourGuard( Colour::Red );
  8661. Catch::cerr() << "Errors occurred during startup!" << '\n';
  8662. // iterate over all exceptions and notify user
  8663. for ( const auto& ex_ptr : exceptions ) {
  8664. try {
  8665. std::rethrow_exception(ex_ptr);
  8666. } catch ( std::exception const& ex ) {
  8667. Catch::cerr() << Column( ex.what() ).indent(2) << '\n';
  8668. }
  8669. }
  8670. }
  8671. #endif
  8672. alreadyInstantiated = true;
  8673. m_cli = makeCommandLineParser( m_configData );
  8674. }
  8675. Session::~Session() {
  8676. Catch::cleanUp();
  8677. }
  8678. void Session::showHelp() const {
  8679. Catch::cout()
  8680. << "\nCatch v" << libraryVersion() << "\n"
  8681. << m_cli << std::endl
  8682. << "For more detailed usage please see the project docs\n" << std::endl;
  8683. }
  8684. void Session::libIdentify() {
  8685. Catch::cout()
  8686. << std::left << std::setw(16) << "description: " << "A Catch test executable\n"
  8687. << std::left << std::setw(16) << "category: " << "testframework\n"
  8688. << std::left << std::setw(16) << "framework: " << "Catch Test\n"
  8689. << std::left << std::setw(16) << "version: " << libraryVersion() << std::endl;
  8690. }
  8691. int Session::applyCommandLine( int argc, char const * const * argv ) {
  8692. if( m_startupExceptions )
  8693. return 1;
  8694. auto result = m_cli.parse( clara::Args( argc, argv ) );
  8695. config();
  8696. getCurrentMutableContext().setConfig( m_config );
  8697. if( !result ) {
  8698. Catch::cerr()
  8699. << Colour( Colour::Red )
  8700. << "\nError(s) in input:\n"
  8701. << Column( result.errorMessage() ).indent( 2 )
  8702. << "\n\n";
  8703. Catch::cerr() << "Run with -? for usage\n" << std::endl;
  8704. return MaxExitCode;
  8705. }
  8706. if( m_configData.showHelp )
  8707. showHelp();
  8708. if( m_configData.libIdentify )
  8709. libIdentify();
  8710. m_config.reset();
  8711. return 0;
  8712. }
  8713. #if defined(CATCH_CONFIG_WCHAR) && defined(WIN32) && defined(UNICODE)
  8714. int Session::applyCommandLine( int argc, wchar_t const * const * argv ) {
  8715. char **utf8Argv = new char *[ argc ];
  8716. for ( int i = 0; i < argc; ++i ) {
  8717. int bufSize = WideCharToMultiByte( CP_UTF8, 0, argv[i], -1, NULL, 0, NULL, NULL );
  8718. utf8Argv[ i ] = new char[ bufSize ];
  8719. WideCharToMultiByte( CP_UTF8, 0, argv[i], -1, utf8Argv[i], bufSize, NULL, NULL );
  8720. }
  8721. int returnCode = applyCommandLine( argc, utf8Argv );
  8722. for ( int i = 0; i < argc; ++i )
  8723. delete [] utf8Argv[ i ];
  8724. delete [] utf8Argv;
  8725. return returnCode;
  8726. }
  8727. #endif
  8728. void Session::useConfigData( ConfigData const& configData ) {
  8729. m_configData = configData;
  8730. m_config.reset();
  8731. }
  8732. int Session::run() {
  8733. if( ( m_configData.waitForKeypress & WaitForKeypress::BeforeStart ) != 0 ) {
  8734. Catch::cout() << "...waiting for enter/ return before starting" << std::endl;
  8735. static_cast<void>(std::getchar());
  8736. }
  8737. int exitCode = runInternal();
  8738. if( ( m_configData.waitForKeypress & WaitForKeypress::BeforeExit ) != 0 ) {
  8739. Catch::cout() << "...waiting for enter/ return before exiting, with code: " << exitCode << std::endl;
  8740. static_cast<void>(std::getchar());
  8741. }
  8742. return exitCode;
  8743. }
  8744. clara::Parser const& Session::cli() const {
  8745. return m_cli;
  8746. }
  8747. void Session::cli( clara::Parser const& newParser ) {
  8748. m_cli = newParser;
  8749. }
  8750. ConfigData& Session::configData() {
  8751. return m_configData;
  8752. }
  8753. Config& Session::config() {
  8754. if( !m_config )
  8755. m_config = std::make_shared<Config>( m_configData );
  8756. return *m_config;
  8757. }
  8758. int Session::runInternal() {
  8759. if( m_startupExceptions )
  8760. return 1;
  8761. if (m_configData.showHelp || m_configData.libIdentify) {
  8762. return 0;
  8763. }
  8764. CATCH_TRY {
  8765. config(); // Force config to be constructed
  8766. seedRng( *m_config );
  8767. if( m_configData.filenamesAsTags )
  8768. applyFilenamesAsTags( *m_config );
  8769. // Handle list request
  8770. if( Option<std::size_t> listed = list( m_config ) )
  8771. return static_cast<int>( *listed );
  8772. auto totals = runTests( m_config );
  8773. // Note that on unices only the lower 8 bits are usually used, clamping
  8774. // the return value to 255 prevents false negative when some multiple
  8775. // of 256 tests has failed
  8776. return (std::min) (MaxExitCode, (std::max) (totals.error, static_cast<int>(totals.assertions.failed)));
  8777. }
  8778. #if !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
  8779. catch( std::exception& ex ) {
  8780. Catch::cerr() << ex.what() << std::endl;
  8781. return MaxExitCode;
  8782. }
  8783. #endif
  8784. }
  8785. } // end namespace Catch
  8786. // end catch_session.cpp
  8787. // start catch_singletons.cpp
  8788. #include <vector>
  8789. namespace Catch {
  8790. namespace {
  8791. static auto getSingletons() -> std::vector<ISingleton*>*& {
  8792. static std::vector<ISingleton*>* g_singletons = nullptr;
  8793. if( !g_singletons )
  8794. g_singletons = new std::vector<ISingleton*>();
  8795. return g_singletons;
  8796. }
  8797. }
  8798. ISingleton::~ISingleton() {}
  8799. void addSingleton(ISingleton* singleton ) {
  8800. getSingletons()->push_back( singleton );
  8801. }
  8802. void cleanupSingletons() {
  8803. auto& singletons = getSingletons();
  8804. for( auto singleton : *singletons )
  8805. delete singleton;
  8806. delete singletons;
  8807. singletons = nullptr;
  8808. }
  8809. } // namespace Catch
  8810. // end catch_singletons.cpp
  8811. // start catch_startup_exception_registry.cpp
  8812. namespace Catch {
  8813. void StartupExceptionRegistry::add( std::exception_ptr const& exception ) noexcept {
  8814. CATCH_TRY {
  8815. m_exceptions.push_back(exception);
  8816. } CATCH_CATCH_ALL {
  8817. // If we run out of memory during start-up there's really not a lot more we can do about it
  8818. std::terminate();
  8819. }
  8820. }
  8821. std::vector<std::exception_ptr> const& StartupExceptionRegistry::getExceptions() const noexcept {
  8822. return m_exceptions;
  8823. }
  8824. } // end namespace Catch
  8825. // end catch_startup_exception_registry.cpp
  8826. // start catch_stream.cpp
  8827. #include <cstdio>
  8828. #include <iostream>
  8829. #include <fstream>
  8830. #include <sstream>
  8831. #include <vector>
  8832. #include <memory>
  8833. namespace Catch {
  8834. Catch::IStream::~IStream() = default;
  8835. namespace detail { namespace {
  8836. template<typename WriterF, std::size_t bufferSize=256>
  8837. class StreamBufImpl : public std::streambuf {
  8838. char data[bufferSize];
  8839. WriterF m_writer;
  8840. public:
  8841. StreamBufImpl() {
  8842. setp( data, data + sizeof(data) );
  8843. }
  8844. ~StreamBufImpl() noexcept {
  8845. StreamBufImpl::sync();
  8846. }
  8847. private:
  8848. int overflow( int c ) override {
  8849. sync();
  8850. if( c != EOF ) {
  8851. if( pbase() == epptr() )
  8852. m_writer( std::string( 1, static_cast<char>( c ) ) );
  8853. else
  8854. sputc( static_cast<char>( c ) );
  8855. }
  8856. return 0;
  8857. }
  8858. int sync() override {
  8859. if( pbase() != pptr() ) {
  8860. m_writer( std::string( pbase(), static_cast<std::string::size_type>( pptr() - pbase() ) ) );
  8861. setp( pbase(), epptr() );
  8862. }
  8863. return 0;
  8864. }
  8865. };
  8866. ///////////////////////////////////////////////////////////////////////////
  8867. struct OutputDebugWriter {
  8868. void operator()( std::string const&str ) {
  8869. writeToDebugConsole( str );
  8870. }
  8871. };
  8872. ///////////////////////////////////////////////////////////////////////////
  8873. class FileStream : public IStream {
  8874. mutable std::ofstream m_ofs;
  8875. public:
  8876. FileStream( StringRef filename ) {
  8877. m_ofs.open( filename.c_str() );
  8878. CATCH_ENFORCE( !m_ofs.fail(), "Unable to open file: '" << filename << "'" );
  8879. }
  8880. ~FileStream() override = default;
  8881. public: // IStream
  8882. std::ostream& stream() const override {
  8883. return m_ofs;
  8884. }
  8885. };
  8886. ///////////////////////////////////////////////////////////////////////////
  8887. class CoutStream : public IStream {
  8888. mutable std::ostream m_os;
  8889. public:
  8890. // Store the streambuf from cout up-front because
  8891. // cout may get redirected when running tests
  8892. CoutStream() : m_os( Catch::cout().rdbuf() ) {}
  8893. ~CoutStream() override = default;
  8894. public: // IStream
  8895. std::ostream& stream() const override { return m_os; }
  8896. };
  8897. ///////////////////////////////////////////////////////////////////////////
  8898. class DebugOutStream : public IStream {
  8899. std::unique_ptr<StreamBufImpl<OutputDebugWriter>> m_streamBuf;
  8900. mutable std::ostream m_os;
  8901. public:
  8902. DebugOutStream()
  8903. : m_streamBuf( new StreamBufImpl<OutputDebugWriter>() ),
  8904. m_os( m_streamBuf.get() )
  8905. {}
  8906. ~DebugOutStream() override = default;
  8907. public: // IStream
  8908. std::ostream& stream() const override { return m_os; }
  8909. };
  8910. }} // namespace anon::detail
  8911. ///////////////////////////////////////////////////////////////////////////
  8912. auto makeStream( StringRef const &filename ) -> IStream const* {
  8913. if( filename.empty() )
  8914. return new detail::CoutStream();
  8915. else if( filename[0] == '%' ) {
  8916. if( filename == "%debug" )
  8917. return new detail::DebugOutStream();
  8918. else
  8919. CATCH_ERROR( "Unrecognised stream: '" << filename << "'" );
  8920. }
  8921. else
  8922. return new detail::FileStream( filename );
  8923. }
  8924. // This class encapsulates the idea of a pool of ostringstreams that can be reused.
  8925. struct StringStreams {
  8926. std::vector<std::unique_ptr<std::ostringstream>> m_streams;
  8927. std::vector<std::size_t> m_unused;
  8928. std::ostringstream m_referenceStream; // Used for copy state/ flags from
  8929. auto add() -> std::size_t {
  8930. if( m_unused.empty() ) {
  8931. m_streams.push_back( std::unique_ptr<std::ostringstream>( new std::ostringstream ) );
  8932. return m_streams.size()-1;
  8933. }
  8934. else {
  8935. auto index = m_unused.back();
  8936. m_unused.pop_back();
  8937. return index;
  8938. }
  8939. }
  8940. void release( std::size_t index ) {
  8941. m_streams[index]->copyfmt( m_referenceStream ); // Restore initial flags and other state
  8942. m_unused.push_back(index);
  8943. }
  8944. };
  8945. ReusableStringStream::ReusableStringStream()
  8946. : m_index( Singleton<StringStreams>::getMutable().add() ),
  8947. m_oss( Singleton<StringStreams>::getMutable().m_streams[m_index].get() )
  8948. {}
  8949. ReusableStringStream::~ReusableStringStream() {
  8950. static_cast<std::ostringstream*>( m_oss )->str("");
  8951. m_oss->clear();
  8952. Singleton<StringStreams>::getMutable().release( m_index );
  8953. }
  8954. auto ReusableStringStream::str() const -> std::string {
  8955. return static_cast<std::ostringstream*>( m_oss )->str();
  8956. }
  8957. ///////////////////////////////////////////////////////////////////////////
  8958. #ifndef CATCH_CONFIG_NOSTDOUT // If you #define this you must implement these functions
  8959. std::ostream& cout() { return std::cout; }
  8960. std::ostream& cerr() { return std::cerr; }
  8961. std::ostream& clog() { return std::clog; }
  8962. #endif
  8963. }
  8964. // end catch_stream.cpp
  8965. // start catch_string_manip.cpp
  8966. #include <algorithm>
  8967. #include <ostream>
  8968. #include <cstring>
  8969. #include <cctype>
  8970. namespace Catch {
  8971. namespace {
  8972. char toLowerCh(char c) {
  8973. return static_cast<char>( std::tolower( c ) );
  8974. }
  8975. }
  8976. bool startsWith( std::string const& s, std::string const& prefix ) {
  8977. return s.size() >= prefix.size() && std::equal(prefix.begin(), prefix.end(), s.begin());
  8978. }
  8979. bool startsWith( std::string const& s, char prefix ) {
  8980. return !s.empty() && s[0] == prefix;
  8981. }
  8982. bool endsWith( std::string const& s, std::string const& suffix ) {
  8983. return s.size() >= suffix.size() && std::equal(suffix.rbegin(), suffix.rend(), s.rbegin());
  8984. }
  8985. bool endsWith( std::string const& s, char suffix ) {
  8986. return !s.empty() && s[s.size()-1] == suffix;
  8987. }
  8988. bool contains( std::string const& s, std::string const& infix ) {
  8989. return s.find( infix ) != std::string::npos;
  8990. }
  8991. void toLowerInPlace( std::string& s ) {
  8992. std::transform( s.begin(), s.end(), s.begin(), toLowerCh );
  8993. }
  8994. std::string toLower( std::string const& s ) {
  8995. std::string lc = s;
  8996. toLowerInPlace( lc );
  8997. return lc;
  8998. }
  8999. std::string trim( std::string const& str ) {
  9000. static char const* whitespaceChars = "\n\r\t ";
  9001. std::string::size_type start = str.find_first_not_of( whitespaceChars );
  9002. std::string::size_type end = str.find_last_not_of( whitespaceChars );
  9003. return start != std::string::npos ? str.substr( start, 1+end-start ) : std::string();
  9004. }
  9005. bool replaceInPlace( std::string& str, std::string const& replaceThis, std::string const& withThis ) {
  9006. bool replaced = false;
  9007. std::size_t i = str.find( replaceThis );
  9008. while( i != std::string::npos ) {
  9009. replaced = true;
  9010. str = str.substr( 0, i ) + withThis + str.substr( i+replaceThis.size() );
  9011. if( i < str.size()-withThis.size() )
  9012. i = str.find( replaceThis, i+withThis.size() );
  9013. else
  9014. i = std::string::npos;
  9015. }
  9016. return replaced;
  9017. }
  9018. pluralise::pluralise( std::size_t count, std::string const& label )
  9019. : m_count( count ),
  9020. m_label( label )
  9021. {}
  9022. std::ostream& operator << ( std::ostream& os, pluralise const& pluraliser ) {
  9023. os << pluraliser.m_count << ' ' << pluraliser.m_label;
  9024. if( pluraliser.m_count != 1 )
  9025. os << 's';
  9026. return os;
  9027. }
  9028. }
  9029. // end catch_string_manip.cpp
  9030. // start catch_stringref.cpp
  9031. #if defined(__clang__)
  9032. # pragma clang diagnostic push
  9033. # pragma clang diagnostic ignored "-Wexit-time-destructors"
  9034. #endif
  9035. #include <ostream>
  9036. #include <cstring>
  9037. #include <cstdint>
  9038. namespace {
  9039. const uint32_t byte_2_lead = 0xC0;
  9040. const uint32_t byte_3_lead = 0xE0;
  9041. const uint32_t byte_4_lead = 0xF0;
  9042. }
  9043. namespace Catch {
  9044. StringRef::StringRef( char const* rawChars ) noexcept
  9045. : StringRef( rawChars, static_cast<StringRef::size_type>(std::strlen(rawChars) ) )
  9046. {}
  9047. StringRef::operator std::string() const {
  9048. return std::string( m_start, m_size );
  9049. }
  9050. void StringRef::swap( StringRef& other ) noexcept {
  9051. std::swap( m_start, other.m_start );
  9052. std::swap( m_size, other.m_size );
  9053. std::swap( m_data, other.m_data );
  9054. }
  9055. auto StringRef::c_str() const -> char const* {
  9056. if( isSubstring() )
  9057. const_cast<StringRef*>( this )->takeOwnership();
  9058. return m_start;
  9059. }
  9060. auto StringRef::currentData() const noexcept -> char const* {
  9061. return m_start;
  9062. }
  9063. auto StringRef::isOwned() const noexcept -> bool {
  9064. return m_data != nullptr;
  9065. }
  9066. auto StringRef::isSubstring() const noexcept -> bool {
  9067. return m_start[m_size] != '\0';
  9068. }
  9069. void StringRef::takeOwnership() {
  9070. if( !isOwned() ) {
  9071. m_data = new char[m_size+1];
  9072. memcpy( m_data, m_start, m_size );
  9073. m_data[m_size] = '\0';
  9074. m_start = m_data;
  9075. }
  9076. }
  9077. auto StringRef::substr( size_type start, size_type size ) const noexcept -> StringRef {
  9078. if( start < m_size )
  9079. return StringRef( m_start+start, size );
  9080. else
  9081. return StringRef();
  9082. }
  9083. auto StringRef::operator == ( StringRef const& other ) const noexcept -> bool {
  9084. return
  9085. size() == other.size() &&
  9086. (std::strncmp( m_start, other.m_start, size() ) == 0);
  9087. }
  9088. auto StringRef::operator != ( StringRef const& other ) const noexcept -> bool {
  9089. return !operator==( other );
  9090. }
  9091. auto StringRef::operator[](size_type index) const noexcept -> char {
  9092. return m_start[index];
  9093. }
  9094. auto StringRef::numberOfCharacters() const noexcept -> size_type {
  9095. size_type noChars = m_size;
  9096. // Make adjustments for uft encodings
  9097. for( size_type i=0; i < m_size; ++i ) {
  9098. char c = m_start[i];
  9099. if( ( c & byte_2_lead ) == byte_2_lead ) {
  9100. noChars--;
  9101. if (( c & byte_3_lead ) == byte_3_lead )
  9102. noChars--;
  9103. if( ( c & byte_4_lead ) == byte_4_lead )
  9104. noChars--;
  9105. }
  9106. }
  9107. return noChars;
  9108. }
  9109. auto operator + ( StringRef const& lhs, StringRef const& rhs ) -> std::string {
  9110. std::string str;
  9111. str.reserve( lhs.size() + rhs.size() );
  9112. str += lhs;
  9113. str += rhs;
  9114. return str;
  9115. }
  9116. auto operator + ( StringRef const& lhs, const char* rhs ) -> std::string {
  9117. return std::string( lhs ) + std::string( rhs );
  9118. }
  9119. auto operator + ( char const* lhs, StringRef const& rhs ) -> std::string {
  9120. return std::string( lhs ) + std::string( rhs );
  9121. }
  9122. auto operator << ( std::ostream& os, StringRef const& str ) -> std::ostream& {
  9123. return os.write(str.currentData(), str.size());
  9124. }
  9125. auto operator+=( std::string& lhs, StringRef const& rhs ) -> std::string& {
  9126. lhs.append(rhs.currentData(), rhs.size());
  9127. return lhs;
  9128. }
  9129. } // namespace Catch
  9130. #if defined(__clang__)
  9131. # pragma clang diagnostic pop
  9132. #endif
  9133. // end catch_stringref.cpp
  9134. // start catch_tag_alias.cpp
  9135. namespace Catch {
  9136. TagAlias::TagAlias(std::string const & _tag, SourceLineInfo _lineInfo): tag(_tag), lineInfo(_lineInfo) {}
  9137. }
  9138. // end catch_tag_alias.cpp
  9139. // start catch_tag_alias_autoregistrar.cpp
  9140. namespace Catch {
  9141. RegistrarForTagAliases::RegistrarForTagAliases(char const* alias, char const* tag, SourceLineInfo const& lineInfo) {
  9142. CATCH_TRY {
  9143. getMutableRegistryHub().registerTagAlias(alias, tag, lineInfo);
  9144. } CATCH_CATCH_ALL {
  9145. // Do not throw when constructing global objects, instead register the exception to be processed later
  9146. getMutableRegistryHub().registerStartupException();
  9147. }
  9148. }
  9149. }
  9150. // end catch_tag_alias_autoregistrar.cpp
  9151. // start catch_tag_alias_registry.cpp
  9152. #include <sstream>
  9153. namespace Catch {
  9154. TagAliasRegistry::~TagAliasRegistry() {}
  9155. TagAlias const* TagAliasRegistry::find( std::string const& alias ) const {
  9156. auto it = m_registry.find( alias );
  9157. if( it != m_registry.end() )
  9158. return &(it->second);
  9159. else
  9160. return nullptr;
  9161. }
  9162. std::string TagAliasRegistry::expandAliases( std::string const& unexpandedTestSpec ) const {
  9163. std::string expandedTestSpec = unexpandedTestSpec;
  9164. for( auto const& registryKvp : m_registry ) {
  9165. std::size_t pos = expandedTestSpec.find( registryKvp.first );
  9166. if( pos != std::string::npos ) {
  9167. expandedTestSpec = expandedTestSpec.substr( 0, pos ) +
  9168. registryKvp.second.tag +
  9169. expandedTestSpec.substr( pos + registryKvp.first.size() );
  9170. }
  9171. }
  9172. return expandedTestSpec;
  9173. }
  9174. void TagAliasRegistry::add( std::string const& alias, std::string const& tag, SourceLineInfo const& lineInfo ) {
  9175. CATCH_ENFORCE( startsWith(alias, "[@") && endsWith(alias, ']'),
  9176. "error: tag alias, '" << alias << "' is not of the form [@alias name].\n" << lineInfo );
  9177. CATCH_ENFORCE( m_registry.insert(std::make_pair(alias, TagAlias(tag, lineInfo))).second,
  9178. "error: tag alias, '" << alias << "' already registered.\n"
  9179. << "\tFirst seen at: " << find(alias)->lineInfo << "\n"
  9180. << "\tRedefined at: " << lineInfo );
  9181. }
  9182. ITagAliasRegistry::~ITagAliasRegistry() {}
  9183. ITagAliasRegistry const& ITagAliasRegistry::get() {
  9184. return getRegistryHub().getTagAliasRegistry();
  9185. }
  9186. } // end namespace Catch
  9187. // end catch_tag_alias_registry.cpp
  9188. // start catch_test_case_info.cpp
  9189. #include <cctype>
  9190. #include <exception>
  9191. #include <algorithm>
  9192. #include <sstream>
  9193. namespace Catch {
  9194. namespace {
  9195. TestCaseInfo::SpecialProperties parseSpecialTag( std::string const& tag ) {
  9196. if( startsWith( tag, '.' ) ||
  9197. tag == "!hide" )
  9198. return TestCaseInfo::IsHidden;
  9199. else if( tag == "!throws" )
  9200. return TestCaseInfo::Throws;
  9201. else if( tag == "!shouldfail" )
  9202. return TestCaseInfo::ShouldFail;
  9203. else if( tag == "!mayfail" )
  9204. return TestCaseInfo::MayFail;
  9205. else if( tag == "!nonportable" )
  9206. return TestCaseInfo::NonPortable;
  9207. else if( tag == "!benchmark" )
  9208. return static_cast<TestCaseInfo::SpecialProperties>( TestCaseInfo::Benchmark | TestCaseInfo::IsHidden );
  9209. else
  9210. return TestCaseInfo::None;
  9211. }
  9212. bool isReservedTag( std::string const& tag ) {
  9213. return parseSpecialTag( tag ) == TestCaseInfo::None && tag.size() > 0 && !std::isalnum( static_cast<unsigned char>(tag[0]) );
  9214. }
  9215. void enforceNotReservedTag( std::string const& tag, SourceLineInfo const& _lineInfo ) {
  9216. CATCH_ENFORCE( !isReservedTag(tag),
  9217. "Tag name: [" << tag << "] is not allowed.\n"
  9218. << "Tag names starting with non alpha-numeric characters are reserved\n"
  9219. << _lineInfo );
  9220. }
  9221. }
  9222. TestCase makeTestCase( ITestInvoker* _testCase,
  9223. std::string const& _className,
  9224. NameAndTags const& nameAndTags,
  9225. SourceLineInfo const& _lineInfo )
  9226. {
  9227. bool isHidden = false;
  9228. // Parse out tags
  9229. std::vector<std::string> tags;
  9230. std::string desc, tag;
  9231. bool inTag = false;
  9232. std::string _descOrTags = nameAndTags.tags;
  9233. for (char c : _descOrTags) {
  9234. if( !inTag ) {
  9235. if( c == '[' )
  9236. inTag = true;
  9237. else
  9238. desc += c;
  9239. }
  9240. else {
  9241. if( c == ']' ) {
  9242. TestCaseInfo::SpecialProperties prop = parseSpecialTag( tag );
  9243. if( ( prop & TestCaseInfo::IsHidden ) != 0 )
  9244. isHidden = true;
  9245. else if( prop == TestCaseInfo::None )
  9246. enforceNotReservedTag( tag, _lineInfo );
  9247. tags.push_back( tag );
  9248. tag.clear();
  9249. inTag = false;
  9250. }
  9251. else
  9252. tag += c;
  9253. }
  9254. }
  9255. if( isHidden ) {
  9256. tags.push_back( "." );
  9257. }
  9258. TestCaseInfo info( nameAndTags.name, _className, desc, tags, _lineInfo );
  9259. return TestCase( _testCase, std::move(info) );
  9260. }
  9261. void setTags( TestCaseInfo& testCaseInfo, std::vector<std::string> tags ) {
  9262. std::sort(begin(tags), end(tags));
  9263. tags.erase(std::unique(begin(tags), end(tags)), end(tags));
  9264. testCaseInfo.lcaseTags.clear();
  9265. for( auto const& tag : tags ) {
  9266. std::string lcaseTag = toLower( tag );
  9267. testCaseInfo.properties = static_cast<TestCaseInfo::SpecialProperties>( testCaseInfo.properties | parseSpecialTag( lcaseTag ) );
  9268. testCaseInfo.lcaseTags.push_back( lcaseTag );
  9269. }
  9270. testCaseInfo.tags = std::move(tags);
  9271. }
  9272. TestCaseInfo::TestCaseInfo( std::string const& _name,
  9273. std::string const& _className,
  9274. std::string const& _description,
  9275. std::vector<std::string> const& _tags,
  9276. SourceLineInfo const& _lineInfo )
  9277. : name( _name ),
  9278. className( _className ),
  9279. description( _description ),
  9280. lineInfo( _lineInfo ),
  9281. properties( None )
  9282. {
  9283. setTags( *this, _tags );
  9284. }
  9285. bool TestCaseInfo::isHidden() const {
  9286. return ( properties & IsHidden ) != 0;
  9287. }
  9288. bool TestCaseInfo::throws() const {
  9289. return ( properties & Throws ) != 0;
  9290. }
  9291. bool TestCaseInfo::okToFail() const {
  9292. return ( properties & (ShouldFail | MayFail ) ) != 0;
  9293. }
  9294. bool TestCaseInfo::expectedToFail() const {
  9295. return ( properties & (ShouldFail ) ) != 0;
  9296. }
  9297. std::string TestCaseInfo::tagsAsString() const {
  9298. std::string ret;
  9299. // '[' and ']' per tag
  9300. std::size_t full_size = 2 * tags.size();
  9301. for (const auto& tag : tags) {
  9302. full_size += tag.size();
  9303. }
  9304. ret.reserve(full_size);
  9305. for (const auto& tag : tags) {
  9306. ret.push_back('[');
  9307. ret.append(tag);
  9308. ret.push_back(']');
  9309. }
  9310. return ret;
  9311. }
  9312. TestCase::TestCase( ITestInvoker* testCase, TestCaseInfo&& info ) : TestCaseInfo( std::move(info) ), test( testCase ) {}
  9313. TestCase TestCase::withName( std::string const& _newName ) const {
  9314. TestCase other( *this );
  9315. other.name = _newName;
  9316. return other;
  9317. }
  9318. void TestCase::invoke() const {
  9319. test->invoke();
  9320. }
  9321. bool TestCase::operator == ( TestCase const& other ) const {
  9322. return test.get() == other.test.get() &&
  9323. name == other.name &&
  9324. className == other.className;
  9325. }
  9326. bool TestCase::operator < ( TestCase const& other ) const {
  9327. return name < other.name;
  9328. }
  9329. TestCaseInfo const& TestCase::getTestCaseInfo() const
  9330. {
  9331. return *this;
  9332. }
  9333. } // end namespace Catch
  9334. // end catch_test_case_info.cpp
  9335. // start catch_test_case_registry_impl.cpp
  9336. #include <sstream>
  9337. namespace Catch {
  9338. std::vector<TestCase> sortTests( IConfig const& config, std::vector<TestCase> const& unsortedTestCases ) {
  9339. std::vector<TestCase> sorted = unsortedTestCases;
  9340. switch( config.runOrder() ) {
  9341. case RunTests::InLexicographicalOrder:
  9342. std::sort( sorted.begin(), sorted.end() );
  9343. break;
  9344. case RunTests::InRandomOrder:
  9345. seedRng( config );
  9346. std::shuffle( sorted.begin(), sorted.end(), rng() );
  9347. break;
  9348. case RunTests::InDeclarationOrder:
  9349. // already in declaration order
  9350. break;
  9351. }
  9352. return sorted;
  9353. }
  9354. bool matchTest( TestCase const& testCase, TestSpec const& testSpec, IConfig const& config ) {
  9355. return testSpec.matches( testCase ) && ( config.allowThrows() || !testCase.throws() );
  9356. }
  9357. void enforceNoDuplicateTestCases( std::vector<TestCase> const& functions ) {
  9358. std::set<TestCase> seenFunctions;
  9359. for( auto const& function : functions ) {
  9360. auto prev = seenFunctions.insert( function );
  9361. CATCH_ENFORCE( prev.second,
  9362. "error: TEST_CASE( \"" << function.name << "\" ) already defined.\n"
  9363. << "\tFirst seen at " << prev.first->getTestCaseInfo().lineInfo << "\n"
  9364. << "\tRedefined at " << function.getTestCaseInfo().lineInfo );
  9365. }
  9366. }
  9367. std::vector<TestCase> filterTests( std::vector<TestCase> const& testCases, TestSpec const& testSpec, IConfig const& config ) {
  9368. std::vector<TestCase> filtered;
  9369. filtered.reserve( testCases.size() );
  9370. for( auto const& testCase : testCases )
  9371. if( matchTest( testCase, testSpec, config ) )
  9372. filtered.push_back( testCase );
  9373. return filtered;
  9374. }
  9375. std::vector<TestCase> const& getAllTestCasesSorted( IConfig const& config ) {
  9376. return getRegistryHub().getTestCaseRegistry().getAllTestsSorted( config );
  9377. }
  9378. void TestRegistry::registerTest( TestCase const& testCase ) {
  9379. std::string name = testCase.getTestCaseInfo().name;
  9380. if( name.empty() ) {
  9381. ReusableStringStream rss;
  9382. rss << "Anonymous test case " << ++m_unnamedCount;
  9383. return registerTest( testCase.withName( rss.str() ) );
  9384. }
  9385. m_functions.push_back( testCase );
  9386. }
  9387. std::vector<TestCase> const& TestRegistry::getAllTests() const {
  9388. return m_functions;
  9389. }
  9390. std::vector<TestCase> const& TestRegistry::getAllTestsSorted( IConfig const& config ) const {
  9391. if( m_sortedFunctions.empty() )
  9392. enforceNoDuplicateTestCases( m_functions );
  9393. if( m_currentSortOrder != config.runOrder() || m_sortedFunctions.empty() ) {
  9394. m_sortedFunctions = sortTests( config, m_functions );
  9395. m_currentSortOrder = config.runOrder();
  9396. }
  9397. return m_sortedFunctions;
  9398. }
  9399. ///////////////////////////////////////////////////////////////////////////
  9400. TestInvokerAsFunction::TestInvokerAsFunction( void(*testAsFunction)() ) noexcept : m_testAsFunction( testAsFunction ) {}
  9401. void TestInvokerAsFunction::invoke() const {
  9402. m_testAsFunction();
  9403. }
  9404. std::string extractClassName( StringRef const& classOrQualifiedMethodName ) {
  9405. std::string className = classOrQualifiedMethodName;
  9406. if( startsWith( className, '&' ) )
  9407. {
  9408. std::size_t lastColons = className.rfind( "::" );
  9409. std::size_t penultimateColons = className.rfind( "::", lastColons-1 );
  9410. if( penultimateColons == std::string::npos )
  9411. penultimateColons = 1;
  9412. className = className.substr( penultimateColons, lastColons-penultimateColons );
  9413. }
  9414. return className;
  9415. }
  9416. } // end namespace Catch
  9417. // end catch_test_case_registry_impl.cpp
  9418. // start catch_test_case_tracker.cpp
  9419. #include <algorithm>
  9420. #include <cassert>
  9421. #include <stdexcept>
  9422. #include <memory>
  9423. #include <sstream>
  9424. #if defined(__clang__)
  9425. # pragma clang diagnostic push
  9426. # pragma clang diagnostic ignored "-Wexit-time-destructors"
  9427. #endif
  9428. namespace Catch {
  9429. namespace TestCaseTracking {
  9430. NameAndLocation::NameAndLocation( std::string const& _name, SourceLineInfo const& _location )
  9431. : name( _name ),
  9432. location( _location )
  9433. {}
  9434. ITracker::~ITracker() = default;
  9435. TrackerContext& TrackerContext::instance() {
  9436. static TrackerContext s_instance;
  9437. return s_instance;
  9438. }
  9439. ITracker& TrackerContext::startRun() {
  9440. m_rootTracker = std::make_shared<SectionTracker>( NameAndLocation( "{root}", CATCH_INTERNAL_LINEINFO ), *this, nullptr );
  9441. m_currentTracker = nullptr;
  9442. m_runState = Executing;
  9443. return *m_rootTracker;
  9444. }
  9445. void TrackerContext::endRun() {
  9446. m_rootTracker.reset();
  9447. m_currentTracker = nullptr;
  9448. m_runState = NotStarted;
  9449. }
  9450. void TrackerContext::startCycle() {
  9451. m_currentTracker = m_rootTracker.get();
  9452. m_runState = Executing;
  9453. }
  9454. void TrackerContext::completeCycle() {
  9455. m_runState = CompletedCycle;
  9456. }
  9457. bool TrackerContext::completedCycle() const {
  9458. return m_runState == CompletedCycle;
  9459. }
  9460. ITracker& TrackerContext::currentTracker() {
  9461. return *m_currentTracker;
  9462. }
  9463. void TrackerContext::setCurrentTracker( ITracker* tracker ) {
  9464. m_currentTracker = tracker;
  9465. }
  9466. TrackerBase::TrackerBase( NameAndLocation const& nameAndLocation, TrackerContext& ctx, ITracker* parent )
  9467. : m_nameAndLocation( nameAndLocation ),
  9468. m_ctx( ctx ),
  9469. m_parent( parent )
  9470. {}
  9471. NameAndLocation const& TrackerBase::nameAndLocation() const {
  9472. return m_nameAndLocation;
  9473. }
  9474. bool TrackerBase::isComplete() const {
  9475. return m_runState == CompletedSuccessfully || m_runState == Failed;
  9476. }
  9477. bool TrackerBase::isSuccessfullyCompleted() const {
  9478. return m_runState == CompletedSuccessfully;
  9479. }
  9480. bool TrackerBase::isOpen() const {
  9481. return m_runState != NotStarted && !isComplete();
  9482. }
  9483. bool TrackerBase::hasChildren() const {
  9484. return !m_children.empty();
  9485. }
  9486. void TrackerBase::addChild( ITrackerPtr const& child ) {
  9487. m_children.push_back( child );
  9488. }
  9489. ITrackerPtr TrackerBase::findChild( NameAndLocation const& nameAndLocation ) {
  9490. auto it = std::find_if( m_children.begin(), m_children.end(),
  9491. [&nameAndLocation]( ITrackerPtr const& tracker ){
  9492. return
  9493. tracker->nameAndLocation().location == nameAndLocation.location &&
  9494. tracker->nameAndLocation().name == nameAndLocation.name;
  9495. } );
  9496. return( it != m_children.end() )
  9497. ? *it
  9498. : nullptr;
  9499. }
  9500. ITracker& TrackerBase::parent() {
  9501. assert( m_parent ); // Should always be non-null except for root
  9502. return *m_parent;
  9503. }
  9504. void TrackerBase::openChild() {
  9505. if( m_runState != ExecutingChildren ) {
  9506. m_runState = ExecutingChildren;
  9507. if( m_parent )
  9508. m_parent->openChild();
  9509. }
  9510. }
  9511. bool TrackerBase::isSectionTracker() const { return false; }
  9512. bool TrackerBase::isGeneratorTracker() const { return false; }
  9513. void TrackerBase::open() {
  9514. m_runState = Executing;
  9515. moveToThis();
  9516. if( m_parent )
  9517. m_parent->openChild();
  9518. }
  9519. void TrackerBase::close() {
  9520. // Close any still open children (e.g. generators)
  9521. while( &m_ctx.currentTracker() != this )
  9522. m_ctx.currentTracker().close();
  9523. switch( m_runState ) {
  9524. case NeedsAnotherRun:
  9525. break;
  9526. case Executing:
  9527. m_runState = CompletedSuccessfully;
  9528. break;
  9529. case ExecutingChildren:
  9530. if( m_children.empty() || m_children.back()->isComplete() )
  9531. m_runState = CompletedSuccessfully;
  9532. break;
  9533. case NotStarted:
  9534. case CompletedSuccessfully:
  9535. case Failed:
  9536. CATCH_INTERNAL_ERROR( "Illogical state: " << m_runState );
  9537. default:
  9538. CATCH_INTERNAL_ERROR( "Unknown state: " << m_runState );
  9539. }
  9540. moveToParent();
  9541. m_ctx.completeCycle();
  9542. }
  9543. void TrackerBase::fail() {
  9544. m_runState = Failed;
  9545. if( m_parent )
  9546. m_parent->markAsNeedingAnotherRun();
  9547. moveToParent();
  9548. m_ctx.completeCycle();
  9549. }
  9550. void TrackerBase::markAsNeedingAnotherRun() {
  9551. m_runState = NeedsAnotherRun;
  9552. }
  9553. void TrackerBase::moveToParent() {
  9554. assert( m_parent );
  9555. m_ctx.setCurrentTracker( m_parent );
  9556. }
  9557. void TrackerBase::moveToThis() {
  9558. m_ctx.setCurrentTracker( this );
  9559. }
  9560. SectionTracker::SectionTracker( NameAndLocation const& nameAndLocation, TrackerContext& ctx, ITracker* parent )
  9561. : TrackerBase( nameAndLocation, ctx, parent )
  9562. {
  9563. if( parent ) {
  9564. while( !parent->isSectionTracker() )
  9565. parent = &parent->parent();
  9566. SectionTracker& parentSection = static_cast<SectionTracker&>( *parent );
  9567. addNextFilters( parentSection.m_filters );
  9568. }
  9569. }
  9570. bool SectionTracker::isComplete() const {
  9571. bool complete = true;
  9572. if ((m_filters.empty() || m_filters[0] == "") ||
  9573. std::find(m_filters.begin(), m_filters.end(),
  9574. m_nameAndLocation.name) != m_filters.end())
  9575. complete = TrackerBase::isComplete();
  9576. return complete;
  9577. }
  9578. bool SectionTracker::isSectionTracker() const { return true; }
  9579. SectionTracker& SectionTracker::acquire( TrackerContext& ctx, NameAndLocation const& nameAndLocation ) {
  9580. std::shared_ptr<SectionTracker> section;
  9581. ITracker& currentTracker = ctx.currentTracker();
  9582. if( ITrackerPtr childTracker = currentTracker.findChild( nameAndLocation ) ) {
  9583. assert( childTracker );
  9584. assert( childTracker->isSectionTracker() );
  9585. section = std::static_pointer_cast<SectionTracker>( childTracker );
  9586. }
  9587. else {
  9588. section = std::make_shared<SectionTracker>( nameAndLocation, ctx, &currentTracker );
  9589. currentTracker.addChild( section );
  9590. }
  9591. if( !ctx.completedCycle() )
  9592. section->tryOpen();
  9593. return *section;
  9594. }
  9595. void SectionTracker::tryOpen() {
  9596. if( !isComplete() && (m_filters.empty() || m_filters[0].empty() || m_filters[0] == m_nameAndLocation.name ) )
  9597. open();
  9598. }
  9599. void SectionTracker::addInitialFilters( std::vector<std::string> const& filters ) {
  9600. if( !filters.empty() ) {
  9601. m_filters.push_back(""); // Root - should never be consulted
  9602. m_filters.push_back(""); // Test Case - not a section filter
  9603. m_filters.insert( m_filters.end(), filters.begin(), filters.end() );
  9604. }
  9605. }
  9606. void SectionTracker::addNextFilters( std::vector<std::string> const& filters ) {
  9607. if( filters.size() > 1 )
  9608. m_filters.insert( m_filters.end(), ++filters.begin(), filters.end() );
  9609. }
  9610. } // namespace TestCaseTracking
  9611. using TestCaseTracking::ITracker;
  9612. using TestCaseTracking::TrackerContext;
  9613. using TestCaseTracking::SectionTracker;
  9614. } // namespace Catch
  9615. #if defined(__clang__)
  9616. # pragma clang diagnostic pop
  9617. #endif
  9618. // end catch_test_case_tracker.cpp
  9619. // start catch_test_registry.cpp
  9620. namespace Catch {
  9621. auto makeTestInvoker( void(*testAsFunction)() ) noexcept -> ITestInvoker* {
  9622. return new(std::nothrow) TestInvokerAsFunction( testAsFunction );
  9623. }
  9624. NameAndTags::NameAndTags( StringRef const& name_ , StringRef const& tags_ ) noexcept : name( name_ ), tags( tags_ ) {}
  9625. AutoReg::AutoReg( ITestInvoker* invoker, SourceLineInfo const& lineInfo, StringRef const& classOrMethod, NameAndTags const& nameAndTags ) noexcept {
  9626. CATCH_TRY {
  9627. getMutableRegistryHub()
  9628. .registerTest(
  9629. makeTestCase(
  9630. invoker,
  9631. extractClassName( classOrMethod ),
  9632. nameAndTags,
  9633. lineInfo));
  9634. } CATCH_CATCH_ALL {
  9635. // Do not throw when constructing global objects, instead register the exception to be processed later
  9636. getMutableRegistryHub().registerStartupException();
  9637. }
  9638. }
  9639. AutoReg::~AutoReg() = default;
  9640. }
  9641. // end catch_test_registry.cpp
  9642. // start catch_test_spec.cpp
  9643. #include <algorithm>
  9644. #include <string>
  9645. #include <vector>
  9646. #include <memory>
  9647. namespace Catch {
  9648. TestSpec::Pattern::~Pattern() = default;
  9649. TestSpec::NamePattern::~NamePattern() = default;
  9650. TestSpec::TagPattern::~TagPattern() = default;
  9651. TestSpec::ExcludedPattern::~ExcludedPattern() = default;
  9652. TestSpec::NamePattern::NamePattern( std::string const& name )
  9653. : m_wildcardPattern( toLower( name ), CaseSensitive::No )
  9654. {}
  9655. bool TestSpec::NamePattern::matches( TestCaseInfo const& testCase ) const {
  9656. return m_wildcardPattern.matches( toLower( testCase.name ) );
  9657. }
  9658. TestSpec::TagPattern::TagPattern( std::string const& tag ) : m_tag( toLower( tag ) ) {}
  9659. bool TestSpec::TagPattern::matches( TestCaseInfo const& testCase ) const {
  9660. return std::find(begin(testCase.lcaseTags),
  9661. end(testCase.lcaseTags),
  9662. m_tag) != end(testCase.lcaseTags);
  9663. }
  9664. TestSpec::ExcludedPattern::ExcludedPattern( PatternPtr const& underlyingPattern ) : m_underlyingPattern( underlyingPattern ) {}
  9665. bool TestSpec::ExcludedPattern::matches( TestCaseInfo const& testCase ) const { return !m_underlyingPattern->matches( testCase ); }
  9666. bool TestSpec::Filter::matches( TestCaseInfo const& testCase ) const {
  9667. // All patterns in a filter must match for the filter to be a match
  9668. for( auto const& pattern : m_patterns ) {
  9669. if( !pattern->matches( testCase ) )
  9670. return false;
  9671. }
  9672. return true;
  9673. }
  9674. bool TestSpec::hasFilters() const {
  9675. return !m_filters.empty();
  9676. }
  9677. bool TestSpec::matches( TestCaseInfo const& testCase ) const {
  9678. // A TestSpec matches if any filter matches
  9679. for( auto const& filter : m_filters )
  9680. if( filter.matches( testCase ) )
  9681. return true;
  9682. return false;
  9683. }
  9684. }
  9685. // end catch_test_spec.cpp
  9686. // start catch_test_spec_parser.cpp
  9687. namespace Catch {
  9688. TestSpecParser::TestSpecParser( ITagAliasRegistry const& tagAliases ) : m_tagAliases( &tagAliases ) {}
  9689. TestSpecParser& TestSpecParser::parse( std::string const& arg ) {
  9690. m_mode = None;
  9691. m_exclusion = false;
  9692. m_start = std::string::npos;
  9693. m_arg = m_tagAliases->expandAliases( arg );
  9694. m_escapeChars.clear();
  9695. for( m_pos = 0; m_pos < m_arg.size(); ++m_pos )
  9696. visitChar( m_arg[m_pos] );
  9697. if( m_mode == Name )
  9698. addPattern<TestSpec::NamePattern>();
  9699. return *this;
  9700. }
  9701. TestSpec TestSpecParser::testSpec() {
  9702. addFilter();
  9703. return m_testSpec;
  9704. }
  9705. void TestSpecParser::visitChar( char c ) {
  9706. if( m_mode == None ) {
  9707. switch( c ) {
  9708. case ' ': return;
  9709. case '~': m_exclusion = true; return;
  9710. case '[': return startNewMode( Tag, ++m_pos );
  9711. case '"': return startNewMode( QuotedName, ++m_pos );
  9712. case '\\': return escape();
  9713. default: startNewMode( Name, m_pos ); break;
  9714. }
  9715. }
  9716. if( m_mode == Name ) {
  9717. if( c == ',' ) {
  9718. addPattern<TestSpec::NamePattern>();
  9719. addFilter();
  9720. }
  9721. else if( c == '[' ) {
  9722. if( subString() == "exclude:" )
  9723. m_exclusion = true;
  9724. else
  9725. addPattern<TestSpec::NamePattern>();
  9726. startNewMode( Tag, ++m_pos );
  9727. }
  9728. else if( c == '\\' )
  9729. escape();
  9730. }
  9731. else if( m_mode == EscapedName )
  9732. m_mode = Name;
  9733. else if( m_mode == QuotedName && c == '"' )
  9734. addPattern<TestSpec::NamePattern>();
  9735. else if( m_mode == Tag && c == ']' )
  9736. addPattern<TestSpec::TagPattern>();
  9737. }
  9738. void TestSpecParser::startNewMode( Mode mode, std::size_t start ) {
  9739. m_mode = mode;
  9740. m_start = start;
  9741. }
  9742. void TestSpecParser::escape() {
  9743. if( m_mode == None )
  9744. m_start = m_pos;
  9745. m_mode = EscapedName;
  9746. m_escapeChars.push_back( m_pos );
  9747. }
  9748. std::string TestSpecParser::subString() const { return m_arg.substr( m_start, m_pos - m_start ); }
  9749. void TestSpecParser::addFilter() {
  9750. if( !m_currentFilter.m_patterns.empty() ) {
  9751. m_testSpec.m_filters.push_back( m_currentFilter );
  9752. m_currentFilter = TestSpec::Filter();
  9753. }
  9754. }
  9755. TestSpec parseTestSpec( std::string const& arg ) {
  9756. return TestSpecParser( ITagAliasRegistry::get() ).parse( arg ).testSpec();
  9757. }
  9758. } // namespace Catch
  9759. // end catch_test_spec_parser.cpp
  9760. // start catch_timer.cpp
  9761. #include <chrono>
  9762. static const uint64_t nanosecondsInSecond = 1000000000;
  9763. namespace Catch {
  9764. auto getCurrentNanosecondsSinceEpoch() -> uint64_t {
  9765. return std::chrono::duration_cast<std::chrono::nanoseconds>( std::chrono::high_resolution_clock::now().time_since_epoch() ).count();
  9766. }
  9767. namespace {
  9768. auto estimateClockResolution() -> uint64_t {
  9769. uint64_t sum = 0;
  9770. static const uint64_t iterations = 1000000;
  9771. auto startTime = getCurrentNanosecondsSinceEpoch();
  9772. for( std::size_t i = 0; i < iterations; ++i ) {
  9773. uint64_t ticks;
  9774. uint64_t baseTicks = getCurrentNanosecondsSinceEpoch();
  9775. do {
  9776. ticks = getCurrentNanosecondsSinceEpoch();
  9777. } while( ticks == baseTicks );
  9778. auto delta = ticks - baseTicks;
  9779. sum += delta;
  9780. // If we have been calibrating for over 3 seconds -- the clock
  9781. // is terrible and we should move on.
  9782. // TBD: How to signal that the measured resolution is probably wrong?
  9783. if (ticks > startTime + 3 * nanosecondsInSecond) {
  9784. return sum / ( i + 1u );
  9785. }
  9786. }
  9787. // We're just taking the mean, here. To do better we could take the std. dev and exclude outliers
  9788. // - and potentially do more iterations if there's a high variance.
  9789. return sum/iterations;
  9790. }
  9791. }
  9792. auto getEstimatedClockResolution() -> uint64_t {
  9793. static auto s_resolution = estimateClockResolution();
  9794. return s_resolution;
  9795. }
  9796. void Timer::start() {
  9797. m_nanoseconds = getCurrentNanosecondsSinceEpoch();
  9798. }
  9799. auto Timer::getElapsedNanoseconds() const -> uint64_t {
  9800. return getCurrentNanosecondsSinceEpoch() - m_nanoseconds;
  9801. }
  9802. auto Timer::getElapsedMicroseconds() const -> uint64_t {
  9803. return getElapsedNanoseconds()/1000;
  9804. }
  9805. auto Timer::getElapsedMilliseconds() const -> unsigned int {
  9806. return static_cast<unsigned int>(getElapsedMicroseconds()/1000);
  9807. }
  9808. auto Timer::getElapsedSeconds() const -> double {
  9809. return getElapsedMicroseconds()/1000000.0;
  9810. }
  9811. } // namespace Catch
  9812. // end catch_timer.cpp
  9813. // start catch_tostring.cpp
  9814. #if defined(__clang__)
  9815. # pragma clang diagnostic push
  9816. # pragma clang diagnostic ignored "-Wexit-time-destructors"
  9817. # pragma clang diagnostic ignored "-Wglobal-constructors"
  9818. #endif
  9819. // Enable specific decls locally
  9820. #if !defined(CATCH_CONFIG_ENABLE_CHRONO_STRINGMAKER)
  9821. #define CATCH_CONFIG_ENABLE_CHRONO_STRINGMAKER
  9822. #endif
  9823. #include <cmath>
  9824. #include <iomanip>
  9825. namespace Catch {
  9826. namespace Detail {
  9827. const std::string unprintableString = "{?}";
  9828. namespace {
  9829. const int hexThreshold = 255;
  9830. struct Endianness {
  9831. enum Arch { Big, Little };
  9832. static Arch which() {
  9833. union _{
  9834. int asInt;
  9835. char asChar[sizeof (int)];
  9836. } u;
  9837. u.asInt = 1;
  9838. return ( u.asChar[sizeof(int)-1] == 1 ) ? Big : Little;
  9839. }
  9840. };
  9841. }
  9842. std::string rawMemoryToString( const void *object, std::size_t size ) {
  9843. // Reverse order for little endian architectures
  9844. int i = 0, end = static_cast<int>( size ), inc = 1;
  9845. if( Endianness::which() == Endianness::Little ) {
  9846. i = end-1;
  9847. end = inc = -1;
  9848. }
  9849. unsigned char const *bytes = static_cast<unsigned char const *>(object);
  9850. ReusableStringStream rss;
  9851. rss << "0x" << std::setfill('0') << std::hex;
  9852. for( ; i != end; i += inc )
  9853. rss << std::setw(2) << static_cast<unsigned>(bytes[i]);
  9854. return rss.str();
  9855. }
  9856. }
  9857. template<typename T>
  9858. std::string fpToString( T value, int precision ) {
  9859. if (Catch::isnan(value)) {
  9860. return "nan";
  9861. }
  9862. ReusableStringStream rss;
  9863. rss << std::setprecision( precision )
  9864. << std::fixed
  9865. << value;
  9866. std::string d = rss.str();
  9867. std::size_t i = d.find_last_not_of( '0' );
  9868. if( i != std::string::npos && i != d.size()-1 ) {
  9869. if( d[i] == '.' )
  9870. i++;
  9871. d = d.substr( 0, i+1 );
  9872. }
  9873. return d;
  9874. }
  9875. //// ======================================================= ////
  9876. //
  9877. // Out-of-line defs for full specialization of StringMaker
  9878. //
  9879. //// ======================================================= ////
  9880. std::string StringMaker<std::string>::convert(const std::string& str) {
  9881. if (!getCurrentContext().getConfig()->showInvisibles()) {
  9882. return '"' + str + '"';
  9883. }
  9884. std::string s("\"");
  9885. for (char c : str) {
  9886. switch (c) {
  9887. case '\n':
  9888. s.append("\\n");
  9889. break;
  9890. case '\t':
  9891. s.append("\\t");
  9892. break;
  9893. default:
  9894. s.push_back(c);
  9895. break;
  9896. }
  9897. }
  9898. s.append("\"");
  9899. return s;
  9900. }
  9901. #ifdef CATCH_CONFIG_CPP17_STRING_VIEW
  9902. std::string StringMaker<std::string_view>::convert(std::string_view str) {
  9903. return ::Catch::Detail::stringify(std::string{ str });
  9904. }
  9905. #endif
  9906. std::string StringMaker<char const*>::convert(char const* str) {
  9907. if (str) {
  9908. return ::Catch::Detail::stringify(std::string{ str });
  9909. } else {
  9910. return{ "{null string}" };
  9911. }
  9912. }
  9913. std::string StringMaker<char*>::convert(char* str) {
  9914. if (str) {
  9915. return ::Catch::Detail::stringify(std::string{ str });
  9916. } else {
  9917. return{ "{null string}" };
  9918. }
  9919. }
  9920. #ifdef CATCH_CONFIG_WCHAR
  9921. std::string StringMaker<std::wstring>::convert(const std::wstring& wstr) {
  9922. std::string s;
  9923. s.reserve(wstr.size());
  9924. for (auto c : wstr) {
  9925. s += (c <= 0xff) ? static_cast<char>(c) : '?';
  9926. }
  9927. return ::Catch::Detail::stringify(s);
  9928. }
  9929. # ifdef CATCH_CONFIG_CPP17_STRING_VIEW
  9930. std::string StringMaker<std::wstring_view>::convert(std::wstring_view str) {
  9931. return StringMaker<std::wstring>::convert(std::wstring(str));
  9932. }
  9933. # endif
  9934. std::string StringMaker<wchar_t const*>::convert(wchar_t const * str) {
  9935. if (str) {
  9936. return ::Catch::Detail::stringify(std::wstring{ str });
  9937. } else {
  9938. return{ "{null string}" };
  9939. }
  9940. }
  9941. std::string StringMaker<wchar_t *>::convert(wchar_t * str) {
  9942. if (str) {
  9943. return ::Catch::Detail::stringify(std::wstring{ str });
  9944. } else {
  9945. return{ "{null string}" };
  9946. }
  9947. }
  9948. #endif
  9949. std::string StringMaker<int>::convert(int value) {
  9950. return ::Catch::Detail::stringify(static_cast<long long>(value));
  9951. }
  9952. std::string StringMaker<long>::convert(long value) {
  9953. return ::Catch::Detail::stringify(static_cast<long long>(value));
  9954. }
  9955. std::string StringMaker<long long>::convert(long long value) {
  9956. ReusableStringStream rss;
  9957. rss << value;
  9958. if (value > Detail::hexThreshold) {
  9959. rss << " (0x" << std::hex << value << ')';
  9960. }
  9961. return rss.str();
  9962. }
  9963. std::string StringMaker<unsigned int>::convert(unsigned int value) {
  9964. return ::Catch::Detail::stringify(static_cast<unsigned long long>(value));
  9965. }
  9966. std::string StringMaker<unsigned long>::convert(unsigned long value) {
  9967. return ::Catch::Detail::stringify(static_cast<unsigned long long>(value));
  9968. }
  9969. std::string StringMaker<unsigned long long>::convert(unsigned long long value) {
  9970. ReusableStringStream rss;
  9971. rss << value;
  9972. if (value > Detail::hexThreshold) {
  9973. rss << " (0x" << std::hex << value << ')';
  9974. }
  9975. return rss.str();
  9976. }
  9977. std::string StringMaker<bool>::convert(bool b) {
  9978. return b ? "true" : "false";
  9979. }
  9980. std::string StringMaker<signed char>::convert(signed char value) {
  9981. if (value == '\r') {
  9982. return "'\\r'";
  9983. } else if (value == '\f') {
  9984. return "'\\f'";
  9985. } else if (value == '\n') {
  9986. return "'\\n'";
  9987. } else if (value == '\t') {
  9988. return "'\\t'";
  9989. } else if ('\0' <= value && value < ' ') {
  9990. return ::Catch::Detail::stringify(static_cast<unsigned int>(value));
  9991. } else {
  9992. char chstr[] = "' '";
  9993. chstr[1] = value;
  9994. return chstr;
  9995. }
  9996. }
  9997. std::string StringMaker<char>::convert(char c) {
  9998. return ::Catch::Detail::stringify(static_cast<signed char>(c));
  9999. }
  10000. std::string StringMaker<unsigned char>::convert(unsigned char c) {
  10001. return ::Catch::Detail::stringify(static_cast<char>(c));
  10002. }
  10003. std::string StringMaker<std::nullptr_t>::convert(std::nullptr_t) {
  10004. return "nullptr";
  10005. }
  10006. std::string StringMaker<float>::convert(float value) {
  10007. return fpToString(value, 5) + 'f';
  10008. }
  10009. std::string StringMaker<double>::convert(double value) {
  10010. return fpToString(value, 10);
  10011. }
  10012. std::string ratio_string<std::atto>::symbol() { return "a"; }
  10013. std::string ratio_string<std::femto>::symbol() { return "f"; }
  10014. std::string ratio_string<std::pico>::symbol() { return "p"; }
  10015. std::string ratio_string<std::nano>::symbol() { return "n"; }
  10016. std::string ratio_string<std::micro>::symbol() { return "u"; }
  10017. std::string ratio_string<std::milli>::symbol() { return "m"; }
  10018. } // end namespace Catch
  10019. #if defined(__clang__)
  10020. # pragma clang diagnostic pop
  10021. #endif
  10022. // end catch_tostring.cpp
  10023. // start catch_totals.cpp
  10024. namespace Catch {
  10025. Counts Counts::operator - ( Counts const& other ) const {
  10026. Counts diff;
  10027. diff.passed = passed - other.passed;
  10028. diff.failed = failed - other.failed;
  10029. diff.failedButOk = failedButOk - other.failedButOk;
  10030. return diff;
  10031. }
  10032. Counts& Counts::operator += ( Counts const& other ) {
  10033. passed += other.passed;
  10034. failed += other.failed;
  10035. failedButOk += other.failedButOk;
  10036. return *this;
  10037. }
  10038. std::size_t Counts::total() const {
  10039. return passed + failed + failedButOk;
  10040. }
  10041. bool Counts::allPassed() const {
  10042. return failed == 0 && failedButOk == 0;
  10043. }
  10044. bool Counts::allOk() const {
  10045. return failed == 0;
  10046. }
  10047. Totals Totals::operator - ( Totals const& other ) const {
  10048. Totals diff;
  10049. diff.assertions = assertions - other.assertions;
  10050. diff.testCases = testCases - other.testCases;
  10051. return diff;
  10052. }
  10053. Totals& Totals::operator += ( Totals const& other ) {
  10054. assertions += other.assertions;
  10055. testCases += other.testCases;
  10056. return *this;
  10057. }
  10058. Totals Totals::delta( Totals const& prevTotals ) const {
  10059. Totals diff = *this - prevTotals;
  10060. if( diff.assertions.failed > 0 )
  10061. ++diff.testCases.failed;
  10062. else if( diff.assertions.failedButOk > 0 )
  10063. ++diff.testCases.failedButOk;
  10064. else
  10065. ++diff.testCases.passed;
  10066. return diff;
  10067. }
  10068. }
  10069. // end catch_totals.cpp
  10070. // start catch_uncaught_exceptions.cpp
  10071. #include <exception>
  10072. namespace Catch {
  10073. bool uncaught_exceptions() {
  10074. #if defined(CATCH_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS)
  10075. return std::uncaught_exceptions() > 0;
  10076. #else
  10077. return std::uncaught_exception();
  10078. #endif
  10079. }
  10080. } // end namespace Catch
  10081. // end catch_uncaught_exceptions.cpp
  10082. // start catch_version.cpp
  10083. #include <ostream>
  10084. namespace Catch {
  10085. Version::Version
  10086. ( unsigned int _majorVersion,
  10087. unsigned int _minorVersion,
  10088. unsigned int _patchNumber,
  10089. char const * const _branchName,
  10090. unsigned int _buildNumber )
  10091. : majorVersion( _majorVersion ),
  10092. minorVersion( _minorVersion ),
  10093. patchNumber( _patchNumber ),
  10094. branchName( _branchName ),
  10095. buildNumber( _buildNumber )
  10096. {}
  10097. std::ostream& operator << ( std::ostream& os, Version const& version ) {
  10098. os << version.majorVersion << '.'
  10099. << version.minorVersion << '.'
  10100. << version.patchNumber;
  10101. // branchName is never null -> 0th char is \0 if it is empty
  10102. if (version.branchName[0]) {
  10103. os << '-' << version.branchName
  10104. << '.' << version.buildNumber;
  10105. }
  10106. return os;
  10107. }
  10108. Version const& libraryVersion() {
  10109. static Version version( 2, 6, 1, "", 0 );
  10110. return version;
  10111. }
  10112. }
  10113. // end catch_version.cpp
  10114. // start catch_wildcard_pattern.cpp
  10115. #include <sstream>
  10116. namespace Catch {
  10117. WildcardPattern::WildcardPattern( std::string const& pattern,
  10118. CaseSensitive::Choice caseSensitivity )
  10119. : m_caseSensitivity( caseSensitivity ),
  10120. m_pattern( adjustCase( pattern ) )
  10121. {
  10122. if( startsWith( m_pattern, '*' ) ) {
  10123. m_pattern = m_pattern.substr( 1 );
  10124. m_wildcard = WildcardAtStart;
  10125. }
  10126. if( endsWith( m_pattern, '*' ) ) {
  10127. m_pattern = m_pattern.substr( 0, m_pattern.size()-1 );
  10128. m_wildcard = static_cast<WildcardPosition>( m_wildcard | WildcardAtEnd );
  10129. }
  10130. }
  10131. bool WildcardPattern::matches( std::string const& str ) const {
  10132. switch( m_wildcard ) {
  10133. case NoWildcard:
  10134. return m_pattern == adjustCase( str );
  10135. case WildcardAtStart:
  10136. return endsWith( adjustCase( str ), m_pattern );
  10137. case WildcardAtEnd:
  10138. return startsWith( adjustCase( str ), m_pattern );
  10139. case WildcardAtBothEnds:
  10140. return contains( adjustCase( str ), m_pattern );
  10141. default:
  10142. CATCH_INTERNAL_ERROR( "Unknown enum" );
  10143. }
  10144. }
  10145. std::string WildcardPattern::adjustCase( std::string const& str ) const {
  10146. return m_caseSensitivity == CaseSensitive::No ? toLower( str ) : str;
  10147. }
  10148. }
  10149. // end catch_wildcard_pattern.cpp
  10150. // start catch_xmlwriter.cpp
  10151. #include <iomanip>
  10152. using uchar = unsigned char;
  10153. namespace Catch {
  10154. namespace {
  10155. size_t trailingBytes(unsigned char c) {
  10156. if ((c & 0xE0) == 0xC0) {
  10157. return 2;
  10158. }
  10159. if ((c & 0xF0) == 0xE0) {
  10160. return 3;
  10161. }
  10162. if ((c & 0xF8) == 0xF0) {
  10163. return 4;
  10164. }
  10165. CATCH_INTERNAL_ERROR("Invalid multibyte utf-8 start byte encountered");
  10166. }
  10167. uint32_t headerValue(unsigned char c) {
  10168. if ((c & 0xE0) == 0xC0) {
  10169. return c & 0x1F;
  10170. }
  10171. if ((c & 0xF0) == 0xE0) {
  10172. return c & 0x0F;
  10173. }
  10174. if ((c & 0xF8) == 0xF0) {
  10175. return c & 0x07;
  10176. }
  10177. CATCH_INTERNAL_ERROR("Invalid multibyte utf-8 start byte encountered");
  10178. }
  10179. void hexEscapeChar(std::ostream& os, unsigned char c) {
  10180. std::ios_base::fmtflags f(os.flags());
  10181. os << "\\x"
  10182. << std::uppercase << std::hex << std::setfill('0') << std::setw(2)
  10183. << static_cast<int>(c);
  10184. os.flags(f);
  10185. }
  10186. } // anonymous namespace
  10187. XmlEncode::XmlEncode( std::string const& str, ForWhat forWhat )
  10188. : m_str( str ),
  10189. m_forWhat( forWhat )
  10190. {}
  10191. void XmlEncode::encodeTo( std::ostream& os ) const {
  10192. // Apostrophe escaping not necessary if we always use " to write attributes
  10193. // (see: http://www.w3.org/TR/xml/#syntax)
  10194. for( std::size_t idx = 0; idx < m_str.size(); ++ idx ) {
  10195. uchar c = m_str[idx];
  10196. switch (c) {
  10197. case '<': os << "&lt;"; break;
  10198. case '&': os << "&amp;"; break;
  10199. case '>':
  10200. // See: http://www.w3.org/TR/xml/#syntax
  10201. if (idx > 2 && m_str[idx - 1] == ']' && m_str[idx - 2] == ']')
  10202. os << "&gt;";
  10203. else
  10204. os << c;
  10205. break;
  10206. case '\"':
  10207. if (m_forWhat == ForAttributes)
  10208. os << "&quot;";
  10209. else
  10210. os << c;
  10211. break;
  10212. default:
  10213. // Check for control characters and invalid utf-8
  10214. // Escape control characters in standard ascii
  10215. // see http://stackoverflow.com/questions/404107/why-are-control-characters-illegal-in-xml-1-0
  10216. if (c < 0x09 || (c > 0x0D && c < 0x20) || c == 0x7F) {
  10217. hexEscapeChar(os, c);
  10218. break;
  10219. }
  10220. // Plain ASCII: Write it to stream
  10221. if (c < 0x7F) {
  10222. os << c;
  10223. break;
  10224. }
  10225. // UTF-8 territory
  10226. // Check if the encoding is valid and if it is not, hex escape bytes.
  10227. // Important: We do not check the exact decoded values for validity, only the encoding format
  10228. // First check that this bytes is a valid lead byte:
  10229. // This means that it is not encoded as 1111 1XXX
  10230. // Or as 10XX XXXX
  10231. if (c < 0xC0 ||
  10232. c >= 0xF8) {
  10233. hexEscapeChar(os, c);
  10234. break;
  10235. }
  10236. auto encBytes = trailingBytes(c);
  10237. // Are there enough bytes left to avoid accessing out-of-bounds memory?
  10238. if (idx + encBytes - 1 >= m_str.size()) {
  10239. hexEscapeChar(os, c);
  10240. break;
  10241. }
  10242. // The header is valid, check data
  10243. // The next encBytes bytes must together be a valid utf-8
  10244. // This means: bitpattern 10XX XXXX and the extracted value is sane (ish)
  10245. bool valid = true;
  10246. uint32_t value = headerValue(c);
  10247. for (std::size_t n = 1; n < encBytes; ++n) {
  10248. uchar nc = m_str[idx + n];
  10249. valid &= ((nc & 0xC0) == 0x80);
  10250. value = (value << 6) | (nc & 0x3F);
  10251. }
  10252. if (
  10253. // Wrong bit pattern of following bytes
  10254. (!valid) ||
  10255. // Overlong encodings
  10256. (value < 0x80) ||
  10257. (0x80 <= value && value < 0x800 && encBytes > 2) ||
  10258. (0x800 < value && value < 0x10000 && encBytes > 3) ||
  10259. // Encoded value out of range
  10260. (value >= 0x110000)
  10261. ) {
  10262. hexEscapeChar(os, c);
  10263. break;
  10264. }
  10265. // If we got here, this is in fact a valid(ish) utf-8 sequence
  10266. for (std::size_t n = 0; n < encBytes; ++n) {
  10267. os << m_str[idx + n];
  10268. }
  10269. idx += encBytes - 1;
  10270. break;
  10271. }
  10272. }
  10273. }
  10274. std::ostream& operator << ( std::ostream& os, XmlEncode const& xmlEncode ) {
  10275. xmlEncode.encodeTo( os );
  10276. return os;
  10277. }
  10278. XmlWriter::ScopedElement::ScopedElement( XmlWriter* writer )
  10279. : m_writer( writer )
  10280. {}
  10281. XmlWriter::ScopedElement::ScopedElement( ScopedElement&& other ) noexcept
  10282. : m_writer( other.m_writer ){
  10283. other.m_writer = nullptr;
  10284. }
  10285. XmlWriter::ScopedElement& XmlWriter::ScopedElement::operator=( ScopedElement&& other ) noexcept {
  10286. if ( m_writer ) {
  10287. m_writer->endElement();
  10288. }
  10289. m_writer = other.m_writer;
  10290. other.m_writer = nullptr;
  10291. return *this;
  10292. }
  10293. XmlWriter::ScopedElement::~ScopedElement() {
  10294. if( m_writer )
  10295. m_writer->endElement();
  10296. }
  10297. XmlWriter::ScopedElement& XmlWriter::ScopedElement::writeText( std::string const& text, bool indent ) {
  10298. m_writer->writeText( text, indent );
  10299. return *this;
  10300. }
  10301. XmlWriter::XmlWriter( std::ostream& os ) : m_os( os )
  10302. {
  10303. writeDeclaration();
  10304. }
  10305. XmlWriter::~XmlWriter() {
  10306. while( !m_tags.empty() )
  10307. endElement();
  10308. }
  10309. XmlWriter& XmlWriter::startElement( std::string const& name ) {
  10310. ensureTagClosed();
  10311. newlineIfNecessary();
  10312. m_os << m_indent << '<' << name;
  10313. m_tags.push_back( name );
  10314. m_indent += " ";
  10315. m_tagIsOpen = true;
  10316. return *this;
  10317. }
  10318. XmlWriter::ScopedElement XmlWriter::scopedElement( std::string const& name ) {
  10319. ScopedElement scoped( this );
  10320. startElement( name );
  10321. return scoped;
  10322. }
  10323. XmlWriter& XmlWriter::endElement() {
  10324. newlineIfNecessary();
  10325. m_indent = m_indent.substr( 0, m_indent.size()-2 );
  10326. if( m_tagIsOpen ) {
  10327. m_os << "/>";
  10328. m_tagIsOpen = false;
  10329. }
  10330. else {
  10331. m_os << m_indent << "</" << m_tags.back() << ">";
  10332. }
  10333. m_os << std::endl;
  10334. m_tags.pop_back();
  10335. return *this;
  10336. }
  10337. XmlWriter& XmlWriter::writeAttribute( std::string const& name, std::string const& attribute ) {
  10338. if( !name.empty() && !attribute.empty() )
  10339. m_os << ' ' << name << "=\"" << XmlEncode( attribute, XmlEncode::ForAttributes ) << '"';
  10340. return *this;
  10341. }
  10342. XmlWriter& XmlWriter::writeAttribute( std::string const& name, bool attribute ) {
  10343. m_os << ' ' << name << "=\"" << ( attribute ? "true" : "false" ) << '"';
  10344. return *this;
  10345. }
  10346. XmlWriter& XmlWriter::writeText( std::string const& text, bool indent ) {
  10347. if( !text.empty() ){
  10348. bool tagWasOpen = m_tagIsOpen;
  10349. ensureTagClosed();
  10350. if( tagWasOpen && indent )
  10351. m_os << m_indent;
  10352. m_os << XmlEncode( text );
  10353. m_needsNewline = true;
  10354. }
  10355. return *this;
  10356. }
  10357. XmlWriter& XmlWriter::writeComment( std::string const& text ) {
  10358. ensureTagClosed();
  10359. m_os << m_indent << "<!--" << text << "-->";
  10360. m_needsNewline = true;
  10361. return *this;
  10362. }
  10363. void XmlWriter::writeStylesheetRef( std::string const& url ) {
  10364. m_os << "<?xml-stylesheet type=\"text/xsl\" href=\"" << url << "\"?>\n";
  10365. }
  10366. XmlWriter& XmlWriter::writeBlankLine() {
  10367. ensureTagClosed();
  10368. m_os << '\n';
  10369. return *this;
  10370. }
  10371. void XmlWriter::ensureTagClosed() {
  10372. if( m_tagIsOpen ) {
  10373. m_os << ">" << std::endl;
  10374. m_tagIsOpen = false;
  10375. }
  10376. }
  10377. void XmlWriter::writeDeclaration() {
  10378. m_os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
  10379. }
  10380. void XmlWriter::newlineIfNecessary() {
  10381. if( m_needsNewline ) {
  10382. m_os << std::endl;
  10383. m_needsNewline = false;
  10384. }
  10385. }
  10386. }
  10387. // end catch_xmlwriter.cpp
  10388. // start catch_reporter_bases.cpp
  10389. #include <cstring>
  10390. #include <cfloat>
  10391. #include <cstdio>
  10392. #include <cassert>
  10393. #include <memory>
  10394. namespace Catch {
  10395. void prepareExpandedExpression(AssertionResult& result) {
  10396. result.getExpandedExpression();
  10397. }
  10398. // Because formatting using c++ streams is stateful, drop down to C is required
  10399. // Alternatively we could use stringstream, but its performance is... not good.
  10400. std::string getFormattedDuration( double duration ) {
  10401. // Max exponent + 1 is required to represent the whole part
  10402. // + 1 for decimal point
  10403. // + 3 for the 3 decimal places
  10404. // + 1 for null terminator
  10405. const std::size_t maxDoubleSize = DBL_MAX_10_EXP + 1 + 1 + 3 + 1;
  10406. char buffer[maxDoubleSize];
  10407. // Save previous errno, to prevent sprintf from overwriting it
  10408. ErrnoGuard guard;
  10409. #ifdef _MSC_VER
  10410. sprintf_s(buffer, "%.3f", duration);
  10411. #else
  10412. sprintf(buffer, "%.3f", duration);
  10413. #endif
  10414. return std::string(buffer);
  10415. }
  10416. TestEventListenerBase::TestEventListenerBase(ReporterConfig const & _config)
  10417. :StreamingReporterBase(_config) {}
  10418. std::set<Verbosity> TestEventListenerBase::getSupportedVerbosities() {
  10419. return { Verbosity::Quiet, Verbosity::Normal, Verbosity::High };
  10420. }
  10421. void TestEventListenerBase::assertionStarting(AssertionInfo const &) {}
  10422. bool TestEventListenerBase::assertionEnded(AssertionStats const &) {
  10423. return false;
  10424. }
  10425. } // end namespace Catch
  10426. // end catch_reporter_bases.cpp
  10427. // start catch_reporter_compact.cpp
  10428. namespace {
  10429. #ifdef CATCH_PLATFORM_MAC
  10430. const char* failedString() { return "FAILED"; }
  10431. const char* passedString() { return "PASSED"; }
  10432. #else
  10433. const char* failedString() { return "failed"; }
  10434. const char* passedString() { return "passed"; }
  10435. #endif
  10436. // Colour::LightGrey
  10437. Catch::Colour::Code dimColour() { return Catch::Colour::FileName; }
  10438. std::string bothOrAll( std::size_t count ) {
  10439. return count == 1 ? std::string() :
  10440. count == 2 ? "both " : "all " ;
  10441. }
  10442. } // anon namespace
  10443. namespace Catch {
  10444. namespace {
  10445. // Colour, message variants:
  10446. // - white: No tests ran.
  10447. // - red: Failed [both/all] N test cases, failed [both/all] M assertions.
  10448. // - white: Passed [both/all] N test cases (no assertions).
  10449. // - red: Failed N tests cases, failed M assertions.
  10450. // - green: Passed [both/all] N tests cases with M assertions.
  10451. void printTotals(std::ostream& out, const Totals& totals) {
  10452. if (totals.testCases.total() == 0) {
  10453. out << "No tests ran.";
  10454. } else if (totals.testCases.failed == totals.testCases.total()) {
  10455. Colour colour(Colour::ResultError);
  10456. const std::string qualify_assertions_failed =
  10457. totals.assertions.failed == totals.assertions.total() ?
  10458. bothOrAll(totals.assertions.failed) : std::string();
  10459. out <<
  10460. "Failed " << bothOrAll(totals.testCases.failed)
  10461. << pluralise(totals.testCases.failed, "test case") << ", "
  10462. "failed " << qualify_assertions_failed <<
  10463. pluralise(totals.assertions.failed, "assertion") << '.';
  10464. } else if (totals.assertions.total() == 0) {
  10465. out <<
  10466. "Passed " << bothOrAll(totals.testCases.total())
  10467. << pluralise(totals.testCases.total(), "test case")
  10468. << " (no assertions).";
  10469. } else if (totals.assertions.failed) {
  10470. Colour colour(Colour::ResultError);
  10471. out <<
  10472. "Failed " << pluralise(totals.testCases.failed, "test case") << ", "
  10473. "failed " << pluralise(totals.assertions.failed, "assertion") << '.';
  10474. } else {
  10475. Colour colour(Colour::ResultSuccess);
  10476. out <<
  10477. "Passed " << bothOrAll(totals.testCases.passed)
  10478. << pluralise(totals.testCases.passed, "test case") <<
  10479. " with " << pluralise(totals.assertions.passed, "assertion") << '.';
  10480. }
  10481. }
  10482. // Implementation of CompactReporter formatting
  10483. class AssertionPrinter {
  10484. public:
  10485. AssertionPrinter& operator= (AssertionPrinter const&) = delete;
  10486. AssertionPrinter(AssertionPrinter const&) = delete;
  10487. AssertionPrinter(std::ostream& _stream, AssertionStats const& _stats, bool _printInfoMessages)
  10488. : stream(_stream)
  10489. , result(_stats.assertionResult)
  10490. , messages(_stats.infoMessages)
  10491. , itMessage(_stats.infoMessages.begin())
  10492. , printInfoMessages(_printInfoMessages) {}
  10493. void print() {
  10494. printSourceInfo();
  10495. itMessage = messages.begin();
  10496. switch (result.getResultType()) {
  10497. case ResultWas::Ok:
  10498. printResultType(Colour::ResultSuccess, passedString());
  10499. printOriginalExpression();
  10500. printReconstructedExpression();
  10501. if (!result.hasExpression())
  10502. printRemainingMessages(Colour::None);
  10503. else
  10504. printRemainingMessages();
  10505. break;
  10506. case ResultWas::ExpressionFailed:
  10507. if (result.isOk())
  10508. printResultType(Colour::ResultSuccess, failedString() + std::string(" - but was ok"));
  10509. else
  10510. printResultType(Colour::Error, failedString());
  10511. printOriginalExpression();
  10512. printReconstructedExpression();
  10513. printRemainingMessages();
  10514. break;
  10515. case ResultWas::ThrewException:
  10516. printResultType(Colour::Error, failedString());
  10517. printIssue("unexpected exception with message:");
  10518. printMessage();
  10519. printExpressionWas();
  10520. printRemainingMessages();
  10521. break;
  10522. case ResultWas::FatalErrorCondition:
  10523. printResultType(Colour::Error, failedString());
  10524. printIssue("fatal error condition with message:");
  10525. printMessage();
  10526. printExpressionWas();
  10527. printRemainingMessages();
  10528. break;
  10529. case ResultWas::DidntThrowException:
  10530. printResultType(Colour::Error, failedString());
  10531. printIssue("expected exception, got none");
  10532. printExpressionWas();
  10533. printRemainingMessages();
  10534. break;
  10535. case ResultWas::Info:
  10536. printResultType(Colour::None, "info");
  10537. printMessage();
  10538. printRemainingMessages();
  10539. break;
  10540. case ResultWas::Warning:
  10541. printResultType(Colour::None, "warning");
  10542. printMessage();
  10543. printRemainingMessages();
  10544. break;
  10545. case ResultWas::ExplicitFailure:
  10546. printResultType(Colour::Error, failedString());
  10547. printIssue("explicitly");
  10548. printRemainingMessages(Colour::None);
  10549. break;
  10550. // These cases are here to prevent compiler warnings
  10551. case ResultWas::Unknown:
  10552. case ResultWas::FailureBit:
  10553. case ResultWas::Exception:
  10554. printResultType(Colour::Error, "** internal error **");
  10555. break;
  10556. }
  10557. }
  10558. private:
  10559. void printSourceInfo() const {
  10560. Colour colourGuard(Colour::FileName);
  10561. stream << result.getSourceInfo() << ':';
  10562. }
  10563. void printResultType(Colour::Code colour, std::string const& passOrFail) const {
  10564. if (!passOrFail.empty()) {
  10565. {
  10566. Colour colourGuard(colour);
  10567. stream << ' ' << passOrFail;
  10568. }
  10569. stream << ':';
  10570. }
  10571. }
  10572. void printIssue(std::string const& issue) const {
  10573. stream << ' ' << issue;
  10574. }
  10575. void printExpressionWas() {
  10576. if (result.hasExpression()) {
  10577. stream << ';';
  10578. {
  10579. Colour colour(dimColour());
  10580. stream << " expression was:";
  10581. }
  10582. printOriginalExpression();
  10583. }
  10584. }
  10585. void printOriginalExpression() const {
  10586. if (result.hasExpression()) {
  10587. stream << ' ' << result.getExpression();
  10588. }
  10589. }
  10590. void printReconstructedExpression() const {
  10591. if (result.hasExpandedExpression()) {
  10592. {
  10593. Colour colour(dimColour());
  10594. stream << " for: ";
  10595. }
  10596. stream << result.getExpandedExpression();
  10597. }
  10598. }
  10599. void printMessage() {
  10600. if (itMessage != messages.end()) {
  10601. stream << " '" << itMessage->message << '\'';
  10602. ++itMessage;
  10603. }
  10604. }
  10605. void printRemainingMessages(Colour::Code colour = dimColour()) {
  10606. if (itMessage == messages.end())
  10607. return;
  10608. // using messages.end() directly yields (or auto) compilation error:
  10609. std::vector<MessageInfo>::const_iterator itEnd = messages.end();
  10610. const std::size_t N = static_cast<std::size_t>(std::distance(itMessage, itEnd));
  10611. {
  10612. Colour colourGuard(colour);
  10613. stream << " with " << pluralise(N, "message") << ':';
  10614. }
  10615. for (; itMessage != itEnd; ) {
  10616. // If this assertion is a warning ignore any INFO messages
  10617. if (printInfoMessages || itMessage->type != ResultWas::Info) {
  10618. stream << " '" << itMessage->message << '\'';
  10619. if (++itMessage != itEnd) {
  10620. Colour colourGuard(dimColour());
  10621. stream << " and";
  10622. }
  10623. }
  10624. }
  10625. }
  10626. private:
  10627. std::ostream& stream;
  10628. AssertionResult const& result;
  10629. std::vector<MessageInfo> messages;
  10630. std::vector<MessageInfo>::const_iterator itMessage;
  10631. bool printInfoMessages;
  10632. };
  10633. } // anon namespace
  10634. std::string CompactReporter::getDescription() {
  10635. return "Reports test results on a single line, suitable for IDEs";
  10636. }
  10637. ReporterPreferences CompactReporter::getPreferences() const {
  10638. return m_reporterPrefs;
  10639. }
  10640. void CompactReporter::noMatchingTestCases( std::string const& spec ) {
  10641. stream << "No test cases matched '" << spec << '\'' << std::endl;
  10642. }
  10643. void CompactReporter::assertionStarting( AssertionInfo const& ) {}
  10644. bool CompactReporter::assertionEnded( AssertionStats const& _assertionStats ) {
  10645. AssertionResult const& result = _assertionStats.assertionResult;
  10646. bool printInfoMessages = true;
  10647. // Drop out if result was successful and we're not printing those
  10648. if( !m_config->includeSuccessfulResults() && result.isOk() ) {
  10649. if( result.getResultType() != ResultWas::Warning )
  10650. return false;
  10651. printInfoMessages = false;
  10652. }
  10653. AssertionPrinter printer( stream, _assertionStats, printInfoMessages );
  10654. printer.print();
  10655. stream << std::endl;
  10656. return true;
  10657. }
  10658. void CompactReporter::sectionEnded(SectionStats const& _sectionStats) {
  10659. if (m_config->showDurations() == ShowDurations::Always) {
  10660. stream << getFormattedDuration(_sectionStats.durationInSeconds) << " s: " << _sectionStats.sectionInfo.name << std::endl;
  10661. }
  10662. }
  10663. void CompactReporter::testRunEnded( TestRunStats const& _testRunStats ) {
  10664. printTotals( stream, _testRunStats.totals );
  10665. stream << '\n' << std::endl;
  10666. StreamingReporterBase::testRunEnded( _testRunStats );
  10667. }
  10668. CompactReporter::~CompactReporter() {}
  10669. CATCH_REGISTER_REPORTER( "compact", CompactReporter )
  10670. } // end namespace Catch
  10671. // end catch_reporter_compact.cpp
  10672. // start catch_reporter_console.cpp
  10673. #include <cfloat>
  10674. #include <cstdio>
  10675. #if defined(_MSC_VER)
  10676. #pragma warning(push)
  10677. #pragma warning(disable:4061) // Not all labels are EXPLICITLY handled in switch
  10678. // Note that 4062 (not all labels are handled
  10679. // and default is missing) is enabled
  10680. #endif
  10681. namespace Catch {
  10682. namespace {
  10683. // Formatter impl for ConsoleReporter
  10684. class ConsoleAssertionPrinter {
  10685. public:
  10686. ConsoleAssertionPrinter& operator= (ConsoleAssertionPrinter const&) = delete;
  10687. ConsoleAssertionPrinter(ConsoleAssertionPrinter const&) = delete;
  10688. ConsoleAssertionPrinter(std::ostream& _stream, AssertionStats const& _stats, bool _printInfoMessages)
  10689. : stream(_stream),
  10690. stats(_stats),
  10691. result(_stats.assertionResult),
  10692. colour(Colour::None),
  10693. message(result.getMessage()),
  10694. messages(_stats.infoMessages),
  10695. printInfoMessages(_printInfoMessages) {
  10696. switch (result.getResultType()) {
  10697. case ResultWas::Ok:
  10698. colour = Colour::Success;
  10699. passOrFail = "PASSED";
  10700. //if( result.hasMessage() )
  10701. if (_stats.infoMessages.size() == 1)
  10702. messageLabel = "with message";
  10703. if (_stats.infoMessages.size() > 1)
  10704. messageLabel = "with messages";
  10705. break;
  10706. case ResultWas::ExpressionFailed:
  10707. if (result.isOk()) {
  10708. colour = Colour::Success;
  10709. passOrFail = "FAILED - but was ok";
  10710. } else {
  10711. colour = Colour::Error;
  10712. passOrFail = "FAILED";
  10713. }
  10714. if (_stats.infoMessages.size() == 1)
  10715. messageLabel = "with message";
  10716. if (_stats.infoMessages.size() > 1)
  10717. messageLabel = "with messages";
  10718. break;
  10719. case ResultWas::ThrewException:
  10720. colour = Colour::Error;
  10721. passOrFail = "FAILED";
  10722. messageLabel = "due to unexpected exception with ";
  10723. if (_stats.infoMessages.size() == 1)
  10724. messageLabel += "message";
  10725. if (_stats.infoMessages.size() > 1)
  10726. messageLabel += "messages";
  10727. break;
  10728. case ResultWas::FatalErrorCondition:
  10729. colour = Colour::Error;
  10730. passOrFail = "FAILED";
  10731. messageLabel = "due to a fatal error condition";
  10732. break;
  10733. case ResultWas::DidntThrowException:
  10734. colour = Colour::Error;
  10735. passOrFail = "FAILED";
  10736. messageLabel = "because no exception was thrown where one was expected";
  10737. break;
  10738. case ResultWas::Info:
  10739. messageLabel = "info";
  10740. break;
  10741. case ResultWas::Warning:
  10742. messageLabel = "warning";
  10743. break;
  10744. case ResultWas::ExplicitFailure:
  10745. passOrFail = "FAILED";
  10746. colour = Colour::Error;
  10747. if (_stats.infoMessages.size() == 1)
  10748. messageLabel = "explicitly with message";
  10749. if (_stats.infoMessages.size() > 1)
  10750. messageLabel = "explicitly with messages";
  10751. break;
  10752. // These cases are here to prevent compiler warnings
  10753. case ResultWas::Unknown:
  10754. case ResultWas::FailureBit:
  10755. case ResultWas::Exception:
  10756. passOrFail = "** internal error **";
  10757. colour = Colour::Error;
  10758. break;
  10759. }
  10760. }
  10761. void print() const {
  10762. printSourceInfo();
  10763. if (stats.totals.assertions.total() > 0) {
  10764. printResultType();
  10765. printOriginalExpression();
  10766. printReconstructedExpression();
  10767. } else {
  10768. stream << '\n';
  10769. }
  10770. printMessage();
  10771. }
  10772. private:
  10773. void printResultType() const {
  10774. if (!passOrFail.empty()) {
  10775. Colour colourGuard(colour);
  10776. stream << passOrFail << ":\n";
  10777. }
  10778. }
  10779. void printOriginalExpression() const {
  10780. if (result.hasExpression()) {
  10781. Colour colourGuard(Colour::OriginalExpression);
  10782. stream << " ";
  10783. stream << result.getExpressionInMacro();
  10784. stream << '\n';
  10785. }
  10786. }
  10787. void printReconstructedExpression() const {
  10788. if (result.hasExpandedExpression()) {
  10789. stream << "with expansion:\n";
  10790. Colour colourGuard(Colour::ReconstructedExpression);
  10791. stream << Column(result.getExpandedExpression()).indent(2) << '\n';
  10792. }
  10793. }
  10794. void printMessage() const {
  10795. if (!messageLabel.empty())
  10796. stream << messageLabel << ':' << '\n';
  10797. for (auto const& msg : messages) {
  10798. // If this assertion is a warning ignore any INFO messages
  10799. if (printInfoMessages || msg.type != ResultWas::Info)
  10800. stream << Column(msg.message).indent(2) << '\n';
  10801. }
  10802. }
  10803. void printSourceInfo() const {
  10804. Colour colourGuard(Colour::FileName);
  10805. stream << result.getSourceInfo() << ": ";
  10806. }
  10807. std::ostream& stream;
  10808. AssertionStats const& stats;
  10809. AssertionResult const& result;
  10810. Colour::Code colour;
  10811. std::string passOrFail;
  10812. std::string messageLabel;
  10813. std::string message;
  10814. std::vector<MessageInfo> messages;
  10815. bool printInfoMessages;
  10816. };
  10817. std::size_t makeRatio(std::size_t number, std::size_t total) {
  10818. std::size_t ratio = total > 0 ? CATCH_CONFIG_CONSOLE_WIDTH * number / total : 0;
  10819. return (ratio == 0 && number > 0) ? 1 : ratio;
  10820. }
  10821. std::size_t& findMax(std::size_t& i, std::size_t& j, std::size_t& k) {
  10822. if (i > j && i > k)
  10823. return i;
  10824. else if (j > k)
  10825. return j;
  10826. else
  10827. return k;
  10828. }
  10829. struct ColumnInfo {
  10830. enum Justification { Left, Right };
  10831. std::string name;
  10832. int width;
  10833. Justification justification;
  10834. };
  10835. struct ColumnBreak {};
  10836. struct RowBreak {};
  10837. class Duration {
  10838. enum class Unit {
  10839. Auto,
  10840. Nanoseconds,
  10841. Microseconds,
  10842. Milliseconds,
  10843. Seconds,
  10844. Minutes
  10845. };
  10846. static const uint64_t s_nanosecondsInAMicrosecond = 1000;
  10847. static const uint64_t s_nanosecondsInAMillisecond = 1000 * s_nanosecondsInAMicrosecond;
  10848. static const uint64_t s_nanosecondsInASecond = 1000 * s_nanosecondsInAMillisecond;
  10849. static const uint64_t s_nanosecondsInAMinute = 60 * s_nanosecondsInASecond;
  10850. uint64_t m_inNanoseconds;
  10851. Unit m_units;
  10852. public:
  10853. explicit Duration(uint64_t inNanoseconds, Unit units = Unit::Auto)
  10854. : m_inNanoseconds(inNanoseconds),
  10855. m_units(units) {
  10856. if (m_units == Unit::Auto) {
  10857. if (m_inNanoseconds < s_nanosecondsInAMicrosecond)
  10858. m_units = Unit::Nanoseconds;
  10859. else if (m_inNanoseconds < s_nanosecondsInAMillisecond)
  10860. m_units = Unit::Microseconds;
  10861. else if (m_inNanoseconds < s_nanosecondsInASecond)
  10862. m_units = Unit::Milliseconds;
  10863. else if (m_inNanoseconds < s_nanosecondsInAMinute)
  10864. m_units = Unit::Seconds;
  10865. else
  10866. m_units = Unit::Minutes;
  10867. }
  10868. }
  10869. auto value() const -> double {
  10870. switch (m_units) {
  10871. case Unit::Microseconds:
  10872. return m_inNanoseconds / static_cast<double>(s_nanosecondsInAMicrosecond);
  10873. case Unit::Milliseconds:
  10874. return m_inNanoseconds / static_cast<double>(s_nanosecondsInAMillisecond);
  10875. case Unit::Seconds:
  10876. return m_inNanoseconds / static_cast<double>(s_nanosecondsInASecond);
  10877. case Unit::Minutes:
  10878. return m_inNanoseconds / static_cast<double>(s_nanosecondsInAMinute);
  10879. default:
  10880. return static_cast<double>(m_inNanoseconds);
  10881. }
  10882. }
  10883. auto unitsAsString() const -> std::string {
  10884. switch (m_units) {
  10885. case Unit::Nanoseconds:
  10886. return "ns";
  10887. case Unit::Microseconds:
  10888. return "µs";
  10889. case Unit::Milliseconds:
  10890. return "ms";
  10891. case Unit::Seconds:
  10892. return "s";
  10893. case Unit::Minutes:
  10894. return "m";
  10895. default:
  10896. return "** internal error **";
  10897. }
  10898. }
  10899. friend auto operator << (std::ostream& os, Duration const& duration) -> std::ostream& {
  10900. return os << duration.value() << " " << duration.unitsAsString();
  10901. }
  10902. };
  10903. } // end anon namespace
  10904. class TablePrinter {
  10905. std::ostream& m_os;
  10906. std::vector<ColumnInfo> m_columnInfos;
  10907. std::ostringstream m_oss;
  10908. int m_currentColumn = -1;
  10909. bool m_isOpen = false;
  10910. public:
  10911. TablePrinter( std::ostream& os, std::vector<ColumnInfo> columnInfos )
  10912. : m_os( os ),
  10913. m_columnInfos( std::move( columnInfos ) ) {}
  10914. auto columnInfos() const -> std::vector<ColumnInfo> const& {
  10915. return m_columnInfos;
  10916. }
  10917. void open() {
  10918. if (!m_isOpen) {
  10919. m_isOpen = true;
  10920. *this << RowBreak();
  10921. for (auto const& info : m_columnInfos)
  10922. *this << info.name << ColumnBreak();
  10923. *this << RowBreak();
  10924. m_os << Catch::getLineOfChars<'-'>() << "\n";
  10925. }
  10926. }
  10927. void close() {
  10928. if (m_isOpen) {
  10929. *this << RowBreak();
  10930. m_os << std::endl;
  10931. m_isOpen = false;
  10932. }
  10933. }
  10934. template<typename T>
  10935. friend TablePrinter& operator << (TablePrinter& tp, T const& value) {
  10936. tp.m_oss << value;
  10937. return tp;
  10938. }
  10939. friend TablePrinter& operator << (TablePrinter& tp, ColumnBreak) {
  10940. auto colStr = tp.m_oss.str();
  10941. // This takes account of utf8 encodings
  10942. auto strSize = Catch::StringRef(colStr).numberOfCharacters();
  10943. tp.m_oss.str("");
  10944. tp.open();
  10945. if (tp.m_currentColumn == static_cast<int>(tp.m_columnInfos.size() - 1)) {
  10946. tp.m_currentColumn = -1;
  10947. tp.m_os << "\n";
  10948. }
  10949. tp.m_currentColumn++;
  10950. auto colInfo = tp.m_columnInfos[tp.m_currentColumn];
  10951. auto padding = (strSize + 2 < static_cast<std::size_t>(colInfo.width))
  10952. ? std::string(colInfo.width - (strSize + 2), ' ')
  10953. : std::string();
  10954. if (colInfo.justification == ColumnInfo::Left)
  10955. tp.m_os << colStr << padding << " ";
  10956. else
  10957. tp.m_os << padding << colStr << " ";
  10958. return tp;
  10959. }
  10960. friend TablePrinter& operator << (TablePrinter& tp, RowBreak) {
  10961. if (tp.m_currentColumn > 0) {
  10962. tp.m_os << "\n";
  10963. tp.m_currentColumn = -1;
  10964. }
  10965. return tp;
  10966. }
  10967. };
  10968. ConsoleReporter::ConsoleReporter(ReporterConfig const& config)
  10969. : StreamingReporterBase(config),
  10970. m_tablePrinter(new TablePrinter(config.stream(),
  10971. {
  10972. { "benchmark name", CATCH_CONFIG_CONSOLE_WIDTH - 32, ColumnInfo::Left },
  10973. { "iters", 8, ColumnInfo::Right },
  10974. { "elapsed ns", 14, ColumnInfo::Right },
  10975. { "average", 14, ColumnInfo::Right }
  10976. })) {}
  10977. ConsoleReporter::~ConsoleReporter() = default;
  10978. std::string ConsoleReporter::getDescription() {
  10979. return "Reports test results as plain lines of text";
  10980. }
  10981. void ConsoleReporter::noMatchingTestCases(std::string const& spec) {
  10982. stream << "No test cases matched '" << spec << '\'' << std::endl;
  10983. }
  10984. void ConsoleReporter::assertionStarting(AssertionInfo const&) {}
  10985. bool ConsoleReporter::assertionEnded(AssertionStats const& _assertionStats) {
  10986. AssertionResult const& result = _assertionStats.assertionResult;
  10987. bool includeResults = m_config->includeSuccessfulResults() || !result.isOk();
  10988. // Drop out if result was successful but we're not printing them.
  10989. if (!includeResults && result.getResultType() != ResultWas::Warning)
  10990. return false;
  10991. lazyPrint();
  10992. ConsoleAssertionPrinter printer(stream, _assertionStats, includeResults);
  10993. printer.print();
  10994. stream << std::endl;
  10995. return true;
  10996. }
  10997. void ConsoleReporter::sectionStarting(SectionInfo const& _sectionInfo) {
  10998. m_headerPrinted = false;
  10999. StreamingReporterBase::sectionStarting(_sectionInfo);
  11000. }
  11001. void ConsoleReporter::sectionEnded(SectionStats const& _sectionStats) {
  11002. m_tablePrinter->close();
  11003. if (_sectionStats.missingAssertions) {
  11004. lazyPrint();
  11005. Colour colour(Colour::ResultError);
  11006. if (m_sectionStack.size() > 1)
  11007. stream << "\nNo assertions in section";
  11008. else
  11009. stream << "\nNo assertions in test case";
  11010. stream << " '" << _sectionStats.sectionInfo.name << "'\n" << std::endl;
  11011. }
  11012. if (m_config->showDurations() == ShowDurations::Always) {
  11013. stream << getFormattedDuration(_sectionStats.durationInSeconds) << " s: " << _sectionStats.sectionInfo.name << std::endl;
  11014. }
  11015. if (m_headerPrinted) {
  11016. m_headerPrinted = false;
  11017. }
  11018. StreamingReporterBase::sectionEnded(_sectionStats);
  11019. }
  11020. void ConsoleReporter::benchmarkStarting(BenchmarkInfo const& info) {
  11021. lazyPrintWithoutClosingBenchmarkTable();
  11022. auto nameCol = Column( info.name ).width( static_cast<std::size_t>( m_tablePrinter->columnInfos()[0].width - 2 ) );
  11023. bool firstLine = true;
  11024. for (auto line : nameCol) {
  11025. if (!firstLine)
  11026. (*m_tablePrinter) << ColumnBreak() << ColumnBreak() << ColumnBreak();
  11027. else
  11028. firstLine = false;
  11029. (*m_tablePrinter) << line << ColumnBreak();
  11030. }
  11031. }
  11032. void ConsoleReporter::benchmarkEnded(BenchmarkStats const& stats) {
  11033. Duration average(stats.elapsedTimeInNanoseconds / stats.iterations);
  11034. (*m_tablePrinter)
  11035. << stats.iterations << ColumnBreak()
  11036. << stats.elapsedTimeInNanoseconds << ColumnBreak()
  11037. << average << ColumnBreak();
  11038. }
  11039. void ConsoleReporter::testCaseEnded(TestCaseStats const& _testCaseStats) {
  11040. m_tablePrinter->close();
  11041. StreamingReporterBase::testCaseEnded(_testCaseStats);
  11042. m_headerPrinted = false;
  11043. }
  11044. void ConsoleReporter::testGroupEnded(TestGroupStats const& _testGroupStats) {
  11045. if (currentGroupInfo.used) {
  11046. printSummaryDivider();
  11047. stream << "Summary for group '" << _testGroupStats.groupInfo.name << "':\n";
  11048. printTotals(_testGroupStats.totals);
  11049. stream << '\n' << std::endl;
  11050. }
  11051. StreamingReporterBase::testGroupEnded(_testGroupStats);
  11052. }
  11053. void ConsoleReporter::testRunEnded(TestRunStats const& _testRunStats) {
  11054. printTotalsDivider(_testRunStats.totals);
  11055. printTotals(_testRunStats.totals);
  11056. stream << std::endl;
  11057. StreamingReporterBase::testRunEnded(_testRunStats);
  11058. }
  11059. void ConsoleReporter::lazyPrint() {
  11060. m_tablePrinter->close();
  11061. lazyPrintWithoutClosingBenchmarkTable();
  11062. }
  11063. void ConsoleReporter::lazyPrintWithoutClosingBenchmarkTable() {
  11064. if (!currentTestRunInfo.used)
  11065. lazyPrintRunInfo();
  11066. if (!currentGroupInfo.used)
  11067. lazyPrintGroupInfo();
  11068. if (!m_headerPrinted) {
  11069. printTestCaseAndSectionHeader();
  11070. m_headerPrinted = true;
  11071. }
  11072. }
  11073. void ConsoleReporter::lazyPrintRunInfo() {
  11074. stream << '\n' << getLineOfChars<'~'>() << '\n';
  11075. Colour colour(Colour::SecondaryText);
  11076. stream << currentTestRunInfo->name
  11077. << " is a Catch v" << libraryVersion() << " host application.\n"
  11078. << "Run with -? for options\n\n";
  11079. if (m_config->rngSeed() != 0)
  11080. stream << "Randomness seeded to: " << m_config->rngSeed() << "\n\n";
  11081. currentTestRunInfo.used = true;
  11082. }
  11083. void ConsoleReporter::lazyPrintGroupInfo() {
  11084. if (!currentGroupInfo->name.empty() && currentGroupInfo->groupsCounts > 1) {
  11085. printClosedHeader("Group: " + currentGroupInfo->name);
  11086. currentGroupInfo.used = true;
  11087. }
  11088. }
  11089. void ConsoleReporter::printTestCaseAndSectionHeader() {
  11090. assert(!m_sectionStack.empty());
  11091. printOpenHeader(currentTestCaseInfo->name);
  11092. if (m_sectionStack.size() > 1) {
  11093. Colour colourGuard(Colour::Headers);
  11094. auto
  11095. it = m_sectionStack.begin() + 1, // Skip first section (test case)
  11096. itEnd = m_sectionStack.end();
  11097. for (; it != itEnd; ++it)
  11098. printHeaderString(it->name, 2);
  11099. }
  11100. SourceLineInfo lineInfo = m_sectionStack.back().lineInfo;
  11101. if (!lineInfo.empty()) {
  11102. stream << getLineOfChars<'-'>() << '\n';
  11103. Colour colourGuard(Colour::FileName);
  11104. stream << lineInfo << '\n';
  11105. }
  11106. stream << getLineOfChars<'.'>() << '\n' << std::endl;
  11107. }
  11108. void ConsoleReporter::printClosedHeader(std::string const& _name) {
  11109. printOpenHeader(_name);
  11110. stream << getLineOfChars<'.'>() << '\n';
  11111. }
  11112. void ConsoleReporter::printOpenHeader(std::string const& _name) {
  11113. stream << getLineOfChars<'-'>() << '\n';
  11114. {
  11115. Colour colourGuard(Colour::Headers);
  11116. printHeaderString(_name);
  11117. }
  11118. }
  11119. // if string has a : in first line will set indent to follow it on
  11120. // subsequent lines
  11121. void ConsoleReporter::printHeaderString(std::string const& _string, std::size_t indent) {
  11122. std::size_t i = _string.find(": ");
  11123. if (i != std::string::npos)
  11124. i += 2;
  11125. else
  11126. i = 0;
  11127. stream << Column(_string).indent(indent + i).initialIndent(indent) << '\n';
  11128. }
  11129. struct SummaryColumn {
  11130. SummaryColumn( std::string _label, Colour::Code _colour )
  11131. : label( std::move( _label ) ),
  11132. colour( _colour ) {}
  11133. SummaryColumn addRow( std::size_t count ) {
  11134. ReusableStringStream rss;
  11135. rss << count;
  11136. std::string row = rss.str();
  11137. for (auto& oldRow : rows) {
  11138. while (oldRow.size() < row.size())
  11139. oldRow = ' ' + oldRow;
  11140. while (oldRow.size() > row.size())
  11141. row = ' ' + row;
  11142. }
  11143. rows.push_back(row);
  11144. return *this;
  11145. }
  11146. std::string label;
  11147. Colour::Code colour;
  11148. std::vector<std::string> rows;
  11149. };
  11150. void ConsoleReporter::printTotals( Totals const& totals ) {
  11151. if (totals.testCases.total() == 0) {
  11152. stream << Colour(Colour::Warning) << "No tests ran\n";
  11153. } else if (totals.assertions.total() > 0 && totals.testCases.allPassed()) {
  11154. stream << Colour(Colour::ResultSuccess) << "All tests passed";
  11155. stream << " ("
  11156. << pluralise(totals.assertions.passed, "assertion") << " in "
  11157. << pluralise(totals.testCases.passed, "test case") << ')'
  11158. << '\n';
  11159. } else {
  11160. std::vector<SummaryColumn> columns;
  11161. columns.push_back(SummaryColumn("", Colour::None)
  11162. .addRow(totals.testCases.total())
  11163. .addRow(totals.assertions.total()));
  11164. columns.push_back(SummaryColumn("passed", Colour::Success)
  11165. .addRow(totals.testCases.passed)
  11166. .addRow(totals.assertions.passed));
  11167. columns.push_back(SummaryColumn("failed", Colour::ResultError)
  11168. .addRow(totals.testCases.failed)
  11169. .addRow(totals.assertions.failed));
  11170. columns.push_back(SummaryColumn("failed as expected", Colour::ResultExpectedFailure)
  11171. .addRow(totals.testCases.failedButOk)
  11172. .addRow(totals.assertions.failedButOk));
  11173. printSummaryRow("test cases", columns, 0);
  11174. printSummaryRow("assertions", columns, 1);
  11175. }
  11176. }
  11177. void ConsoleReporter::printSummaryRow(std::string const& label, std::vector<SummaryColumn> const& cols, std::size_t row) {
  11178. for (auto col : cols) {
  11179. std::string value = col.rows[row];
  11180. if (col.label.empty()) {
  11181. stream << label << ": ";
  11182. if (value != "0")
  11183. stream << value;
  11184. else
  11185. stream << Colour(Colour::Warning) << "- none -";
  11186. } else if (value != "0") {
  11187. stream << Colour(Colour::LightGrey) << " | ";
  11188. stream << Colour(col.colour)
  11189. << value << ' ' << col.label;
  11190. }
  11191. }
  11192. stream << '\n';
  11193. }
  11194. void ConsoleReporter::printTotalsDivider(Totals const& totals) {
  11195. if (totals.testCases.total() > 0) {
  11196. std::size_t failedRatio = makeRatio(totals.testCases.failed, totals.testCases.total());
  11197. std::size_t failedButOkRatio = makeRatio(totals.testCases.failedButOk, totals.testCases.total());
  11198. std::size_t passedRatio = makeRatio(totals.testCases.passed, totals.testCases.total());
  11199. while (failedRatio + failedButOkRatio + passedRatio < CATCH_CONFIG_CONSOLE_WIDTH - 1)
  11200. findMax(failedRatio, failedButOkRatio, passedRatio)++;
  11201. while (failedRatio + failedButOkRatio + passedRatio > CATCH_CONFIG_CONSOLE_WIDTH - 1)
  11202. findMax(failedRatio, failedButOkRatio, passedRatio)--;
  11203. stream << Colour(Colour::Error) << std::string(failedRatio, '=');
  11204. stream << Colour(Colour::ResultExpectedFailure) << std::string(failedButOkRatio, '=');
  11205. if (totals.testCases.allPassed())
  11206. stream << Colour(Colour::ResultSuccess) << std::string(passedRatio, '=');
  11207. else
  11208. stream << Colour(Colour::Success) << std::string(passedRatio, '=');
  11209. } else {
  11210. stream << Colour(Colour::Warning) << std::string(CATCH_CONFIG_CONSOLE_WIDTH - 1, '=');
  11211. }
  11212. stream << '\n';
  11213. }
  11214. void ConsoleReporter::printSummaryDivider() {
  11215. stream << getLineOfChars<'-'>() << '\n';
  11216. }
  11217. CATCH_REGISTER_REPORTER("console", ConsoleReporter)
  11218. } // end namespace Catch
  11219. #if defined(_MSC_VER)
  11220. #pragma warning(pop)
  11221. #endif
  11222. // end catch_reporter_console.cpp
  11223. // start catch_reporter_junit.cpp
  11224. #include <cassert>
  11225. #include <sstream>
  11226. #include <ctime>
  11227. #include <algorithm>
  11228. namespace Catch {
  11229. namespace {
  11230. std::string getCurrentTimestamp() {
  11231. // Beware, this is not reentrant because of backward compatibility issues
  11232. // Also, UTC only, again because of backward compatibility (%z is C++11)
  11233. time_t rawtime;
  11234. std::time(&rawtime);
  11235. auto const timeStampSize = sizeof("2017-01-16T17:06:45Z");
  11236. #ifdef _MSC_VER
  11237. std::tm timeInfo = {};
  11238. gmtime_s(&timeInfo, &rawtime);
  11239. #else
  11240. std::tm* timeInfo;
  11241. timeInfo = std::gmtime(&rawtime);
  11242. #endif
  11243. char timeStamp[timeStampSize];
  11244. const char * const fmt = "%Y-%m-%dT%H:%M:%SZ";
  11245. #ifdef _MSC_VER
  11246. std::strftime(timeStamp, timeStampSize, fmt, &timeInfo);
  11247. #else
  11248. std::strftime(timeStamp, timeStampSize, fmt, timeInfo);
  11249. #endif
  11250. return std::string(timeStamp);
  11251. }
  11252. std::string fileNameTag(const std::vector<std::string> &tags) {
  11253. auto it = std::find_if(begin(tags),
  11254. end(tags),
  11255. [] (std::string const& tag) {return tag.front() == '#'; });
  11256. if (it != tags.end())
  11257. return it->substr(1);
  11258. return std::string();
  11259. }
  11260. } // anonymous namespace
  11261. JunitReporter::JunitReporter( ReporterConfig const& _config )
  11262. : CumulativeReporterBase( _config ),
  11263. xml( _config.stream() )
  11264. {
  11265. m_reporterPrefs.shouldRedirectStdOut = true;
  11266. m_reporterPrefs.shouldReportAllAssertions = true;
  11267. }
  11268. JunitReporter::~JunitReporter() {}
  11269. std::string JunitReporter::getDescription() {
  11270. return "Reports test results in an XML format that looks like Ant's junitreport target";
  11271. }
  11272. void JunitReporter::noMatchingTestCases( std::string const& /*spec*/ ) {}
  11273. void JunitReporter::testRunStarting( TestRunInfo const& runInfo ) {
  11274. CumulativeReporterBase::testRunStarting( runInfo );
  11275. xml.startElement( "testsuites" );
  11276. if( m_config->rngSeed() != 0 ) {
  11277. xml.startElement( "properties" );
  11278. xml.scopedElement( "property" )
  11279. .writeAttribute( "name", "random-seed" )
  11280. .writeAttribute( "value", m_config->rngSeed() );
  11281. xml.endElement();
  11282. }
  11283. }
  11284. void JunitReporter::testGroupStarting( GroupInfo const& groupInfo ) {
  11285. suiteTimer.start();
  11286. stdOutForSuite.clear();
  11287. stdErrForSuite.clear();
  11288. unexpectedExceptions = 0;
  11289. CumulativeReporterBase::testGroupStarting( groupInfo );
  11290. }
  11291. void JunitReporter::testCaseStarting( TestCaseInfo const& testCaseInfo ) {
  11292. m_okToFail = testCaseInfo.okToFail();
  11293. }
  11294. bool JunitReporter::assertionEnded( AssertionStats const& assertionStats ) {
  11295. if( assertionStats.assertionResult.getResultType() == ResultWas::ThrewException && !m_okToFail )
  11296. unexpectedExceptions++;
  11297. return CumulativeReporterBase::assertionEnded( assertionStats );
  11298. }
  11299. void JunitReporter::testCaseEnded( TestCaseStats const& testCaseStats ) {
  11300. stdOutForSuite += testCaseStats.stdOut;
  11301. stdErrForSuite += testCaseStats.stdErr;
  11302. CumulativeReporterBase::testCaseEnded( testCaseStats );
  11303. }
  11304. void JunitReporter::testGroupEnded( TestGroupStats const& testGroupStats ) {
  11305. double suiteTime = suiteTimer.getElapsedSeconds();
  11306. CumulativeReporterBase::testGroupEnded( testGroupStats );
  11307. writeGroup( *m_testGroups.back(), suiteTime );
  11308. }
  11309. void JunitReporter::testRunEndedCumulative() {
  11310. xml.endElement();
  11311. }
  11312. void JunitReporter::writeGroup( TestGroupNode const& groupNode, double suiteTime ) {
  11313. XmlWriter::ScopedElement e = xml.scopedElement( "testsuite" );
  11314. TestGroupStats const& stats = groupNode.value;
  11315. xml.writeAttribute( "name", stats.groupInfo.name );
  11316. xml.writeAttribute( "errors", unexpectedExceptions );
  11317. xml.writeAttribute( "failures", stats.totals.assertions.failed-unexpectedExceptions );
  11318. xml.writeAttribute( "tests", stats.totals.assertions.total() );
  11319. xml.writeAttribute( "hostname", "tbd" ); // !TBD
  11320. if( m_config->showDurations() == ShowDurations::Never )
  11321. xml.writeAttribute( "time", "" );
  11322. else
  11323. xml.writeAttribute( "time", suiteTime );
  11324. xml.writeAttribute( "timestamp", getCurrentTimestamp() );
  11325. // Write test cases
  11326. for( auto const& child : groupNode.children )
  11327. writeTestCase( *child );
  11328. xml.scopedElement( "system-out" ).writeText( trim( stdOutForSuite ), false );
  11329. xml.scopedElement( "system-err" ).writeText( trim( stdErrForSuite ), false );
  11330. }
  11331. void JunitReporter::writeTestCase( TestCaseNode const& testCaseNode ) {
  11332. TestCaseStats const& stats = testCaseNode.value;
  11333. // All test cases have exactly one section - which represents the
  11334. // test case itself. That section may have 0-n nested sections
  11335. assert( testCaseNode.children.size() == 1 );
  11336. SectionNode const& rootSection = *testCaseNode.children.front();
  11337. std::string className = stats.testInfo.className;
  11338. if( className.empty() ) {
  11339. className = fileNameTag(stats.testInfo.tags);
  11340. if ( className.empty() )
  11341. className = "global";
  11342. }
  11343. if ( !m_config->name().empty() )
  11344. className = m_config->name() + "." + className;
  11345. writeSection( className, "", rootSection );
  11346. }
  11347. void JunitReporter::writeSection( std::string const& className,
  11348. std::string const& rootName,
  11349. SectionNode const& sectionNode ) {
  11350. std::string name = trim( sectionNode.stats.sectionInfo.name );
  11351. if( !rootName.empty() )
  11352. name = rootName + '/' + name;
  11353. if( !sectionNode.assertions.empty() ||
  11354. !sectionNode.stdOut.empty() ||
  11355. !sectionNode.stdErr.empty() ) {
  11356. XmlWriter::ScopedElement e = xml.scopedElement( "testcase" );
  11357. if( className.empty() ) {
  11358. xml.writeAttribute( "classname", name );
  11359. xml.writeAttribute( "name", "root" );
  11360. }
  11361. else {
  11362. xml.writeAttribute( "classname", className );
  11363. xml.writeAttribute( "name", name );
  11364. }
  11365. xml.writeAttribute( "time", ::Catch::Detail::stringify( sectionNode.stats.durationInSeconds ) );
  11366. writeAssertions( sectionNode );
  11367. if( !sectionNode.stdOut.empty() )
  11368. xml.scopedElement( "system-out" ).writeText( trim( sectionNode.stdOut ), false );
  11369. if( !sectionNode.stdErr.empty() )
  11370. xml.scopedElement( "system-err" ).writeText( trim( sectionNode.stdErr ), false );
  11371. }
  11372. for( auto const& childNode : sectionNode.childSections )
  11373. if( className.empty() )
  11374. writeSection( name, "", *childNode );
  11375. else
  11376. writeSection( className, name, *childNode );
  11377. }
  11378. void JunitReporter::writeAssertions( SectionNode const& sectionNode ) {
  11379. for( auto const& assertion : sectionNode.assertions )
  11380. writeAssertion( assertion );
  11381. }
  11382. void JunitReporter::writeAssertion( AssertionStats const& stats ) {
  11383. AssertionResult const& result = stats.assertionResult;
  11384. if( !result.isOk() ) {
  11385. std::string elementName;
  11386. switch( result.getResultType() ) {
  11387. case ResultWas::ThrewException:
  11388. case ResultWas::FatalErrorCondition:
  11389. elementName = "error";
  11390. break;
  11391. case ResultWas::ExplicitFailure:
  11392. elementName = "failure";
  11393. break;
  11394. case ResultWas::ExpressionFailed:
  11395. elementName = "failure";
  11396. break;
  11397. case ResultWas::DidntThrowException:
  11398. elementName = "failure";
  11399. break;
  11400. // We should never see these here:
  11401. case ResultWas::Info:
  11402. case ResultWas::Warning:
  11403. case ResultWas::Ok:
  11404. case ResultWas::Unknown:
  11405. case ResultWas::FailureBit:
  11406. case ResultWas::Exception:
  11407. elementName = "internalError";
  11408. break;
  11409. }
  11410. XmlWriter::ScopedElement e = xml.scopedElement( elementName );
  11411. xml.writeAttribute( "message", result.getExpandedExpression() );
  11412. xml.writeAttribute( "type", result.getTestMacroName() );
  11413. ReusableStringStream rss;
  11414. if( !result.getMessage().empty() )
  11415. rss << result.getMessage() << '\n';
  11416. for( auto const& msg : stats.infoMessages )
  11417. if( msg.type == ResultWas::Info )
  11418. rss << msg.message << '\n';
  11419. rss << "at " << result.getSourceInfo();
  11420. xml.writeText( rss.str(), false );
  11421. }
  11422. }
  11423. CATCH_REGISTER_REPORTER( "junit", JunitReporter )
  11424. } // end namespace Catch
  11425. // end catch_reporter_junit.cpp
  11426. // start catch_reporter_listening.cpp
  11427. #include <cassert>
  11428. namespace Catch {
  11429. ListeningReporter::ListeningReporter() {
  11430. // We will assume that listeners will always want all assertions
  11431. m_preferences.shouldReportAllAssertions = true;
  11432. }
  11433. void ListeningReporter::addListener( IStreamingReporterPtr&& listener ) {
  11434. m_listeners.push_back( std::move( listener ) );
  11435. }
  11436. void ListeningReporter::addReporter(IStreamingReporterPtr&& reporter) {
  11437. assert(!m_reporter && "Listening reporter can wrap only 1 real reporter");
  11438. m_reporter = std::move( reporter );
  11439. m_preferences.shouldRedirectStdOut = m_reporter->getPreferences().shouldRedirectStdOut;
  11440. }
  11441. ReporterPreferences ListeningReporter::getPreferences() const {
  11442. return m_preferences;
  11443. }
  11444. std::set<Verbosity> ListeningReporter::getSupportedVerbosities() {
  11445. return std::set<Verbosity>{ };
  11446. }
  11447. void ListeningReporter::noMatchingTestCases( std::string const& spec ) {
  11448. for ( auto const& listener : m_listeners ) {
  11449. listener->noMatchingTestCases( spec );
  11450. }
  11451. m_reporter->noMatchingTestCases( spec );
  11452. }
  11453. void ListeningReporter::benchmarkStarting( BenchmarkInfo const& benchmarkInfo ) {
  11454. for ( auto const& listener : m_listeners ) {
  11455. listener->benchmarkStarting( benchmarkInfo );
  11456. }
  11457. m_reporter->benchmarkStarting( benchmarkInfo );
  11458. }
  11459. void ListeningReporter::benchmarkEnded( BenchmarkStats const& benchmarkStats ) {
  11460. for ( auto const& listener : m_listeners ) {
  11461. listener->benchmarkEnded( benchmarkStats );
  11462. }
  11463. m_reporter->benchmarkEnded( benchmarkStats );
  11464. }
  11465. void ListeningReporter::testRunStarting( TestRunInfo const& testRunInfo ) {
  11466. for ( auto const& listener : m_listeners ) {
  11467. listener->testRunStarting( testRunInfo );
  11468. }
  11469. m_reporter->testRunStarting( testRunInfo );
  11470. }
  11471. void ListeningReporter::testGroupStarting( GroupInfo const& groupInfo ) {
  11472. for ( auto const& listener : m_listeners ) {
  11473. listener->testGroupStarting( groupInfo );
  11474. }
  11475. m_reporter->testGroupStarting( groupInfo );
  11476. }
  11477. void ListeningReporter::testCaseStarting( TestCaseInfo const& testInfo ) {
  11478. for ( auto const& listener : m_listeners ) {
  11479. listener->testCaseStarting( testInfo );
  11480. }
  11481. m_reporter->testCaseStarting( testInfo );
  11482. }
  11483. void ListeningReporter::sectionStarting( SectionInfo const& sectionInfo ) {
  11484. for ( auto const& listener : m_listeners ) {
  11485. listener->sectionStarting( sectionInfo );
  11486. }
  11487. m_reporter->sectionStarting( sectionInfo );
  11488. }
  11489. void ListeningReporter::assertionStarting( AssertionInfo const& assertionInfo ) {
  11490. for ( auto const& listener : m_listeners ) {
  11491. listener->assertionStarting( assertionInfo );
  11492. }
  11493. m_reporter->assertionStarting( assertionInfo );
  11494. }
  11495. // The return value indicates if the messages buffer should be cleared:
  11496. bool ListeningReporter::assertionEnded( AssertionStats const& assertionStats ) {
  11497. for( auto const& listener : m_listeners ) {
  11498. static_cast<void>( listener->assertionEnded( assertionStats ) );
  11499. }
  11500. return m_reporter->assertionEnded( assertionStats );
  11501. }
  11502. void ListeningReporter::sectionEnded( SectionStats const& sectionStats ) {
  11503. for ( auto const& listener : m_listeners ) {
  11504. listener->sectionEnded( sectionStats );
  11505. }
  11506. m_reporter->sectionEnded( sectionStats );
  11507. }
  11508. void ListeningReporter::testCaseEnded( TestCaseStats const& testCaseStats ) {
  11509. for ( auto const& listener : m_listeners ) {
  11510. listener->testCaseEnded( testCaseStats );
  11511. }
  11512. m_reporter->testCaseEnded( testCaseStats );
  11513. }
  11514. void ListeningReporter::testGroupEnded( TestGroupStats const& testGroupStats ) {
  11515. for ( auto const& listener : m_listeners ) {
  11516. listener->testGroupEnded( testGroupStats );
  11517. }
  11518. m_reporter->testGroupEnded( testGroupStats );
  11519. }
  11520. void ListeningReporter::testRunEnded( TestRunStats const& testRunStats ) {
  11521. for ( auto const& listener : m_listeners ) {
  11522. listener->testRunEnded( testRunStats );
  11523. }
  11524. m_reporter->testRunEnded( testRunStats );
  11525. }
  11526. void ListeningReporter::skipTest( TestCaseInfo const& testInfo ) {
  11527. for ( auto const& listener : m_listeners ) {
  11528. listener->skipTest( testInfo );
  11529. }
  11530. m_reporter->skipTest( testInfo );
  11531. }
  11532. bool ListeningReporter::isMulti() const {
  11533. return true;
  11534. }
  11535. } // end namespace Catch
  11536. // end catch_reporter_listening.cpp
  11537. // start catch_reporter_xml.cpp
  11538. #if defined(_MSC_VER)
  11539. #pragma warning(push)
  11540. #pragma warning(disable:4061) // Not all labels are EXPLICITLY handled in switch
  11541. // Note that 4062 (not all labels are handled
  11542. // and default is missing) is enabled
  11543. #endif
  11544. namespace Catch {
  11545. XmlReporter::XmlReporter( ReporterConfig const& _config )
  11546. : StreamingReporterBase( _config ),
  11547. m_xml(_config.stream())
  11548. {
  11549. m_reporterPrefs.shouldRedirectStdOut = true;
  11550. m_reporterPrefs.shouldReportAllAssertions = true;
  11551. }
  11552. XmlReporter::~XmlReporter() = default;
  11553. std::string XmlReporter::getDescription() {
  11554. return "Reports test results as an XML document";
  11555. }
  11556. std::string XmlReporter::getStylesheetRef() const {
  11557. return std::string();
  11558. }
  11559. void XmlReporter::writeSourceInfo( SourceLineInfo const& sourceInfo ) {
  11560. m_xml
  11561. .writeAttribute( "filename", sourceInfo.file )
  11562. .writeAttribute( "line", sourceInfo.line );
  11563. }
  11564. void XmlReporter::noMatchingTestCases( std::string const& s ) {
  11565. StreamingReporterBase::noMatchingTestCases( s );
  11566. }
  11567. void XmlReporter::testRunStarting( TestRunInfo const& testInfo ) {
  11568. StreamingReporterBase::testRunStarting( testInfo );
  11569. std::string stylesheetRef = getStylesheetRef();
  11570. if( !stylesheetRef.empty() )
  11571. m_xml.writeStylesheetRef( stylesheetRef );
  11572. m_xml.startElement( "Catch" );
  11573. if( !m_config->name().empty() )
  11574. m_xml.writeAttribute( "name", m_config->name() );
  11575. if( m_config->rngSeed() != 0 )
  11576. m_xml.scopedElement( "Randomness" )
  11577. .writeAttribute( "seed", m_config->rngSeed() );
  11578. }
  11579. void XmlReporter::testGroupStarting( GroupInfo const& groupInfo ) {
  11580. StreamingReporterBase::testGroupStarting( groupInfo );
  11581. m_xml.startElement( "Group" )
  11582. .writeAttribute( "name", groupInfo.name );
  11583. }
  11584. void XmlReporter::testCaseStarting( TestCaseInfo const& testInfo ) {
  11585. StreamingReporterBase::testCaseStarting(testInfo);
  11586. m_xml.startElement( "TestCase" )
  11587. .writeAttribute( "name", trim( testInfo.name ) )
  11588. .writeAttribute( "description", testInfo.description )
  11589. .writeAttribute( "tags", testInfo.tagsAsString() );
  11590. writeSourceInfo( testInfo.lineInfo );
  11591. if ( m_config->showDurations() == ShowDurations::Always )
  11592. m_testCaseTimer.start();
  11593. m_xml.ensureTagClosed();
  11594. }
  11595. void XmlReporter::sectionStarting( SectionInfo const& sectionInfo ) {
  11596. StreamingReporterBase::sectionStarting( sectionInfo );
  11597. if( m_sectionDepth++ > 0 ) {
  11598. m_xml.startElement( "Section" )
  11599. .writeAttribute( "name", trim( sectionInfo.name ) );
  11600. writeSourceInfo( sectionInfo.lineInfo );
  11601. m_xml.ensureTagClosed();
  11602. }
  11603. }
  11604. void XmlReporter::assertionStarting( AssertionInfo const& ) { }
  11605. bool XmlReporter::assertionEnded( AssertionStats const& assertionStats ) {
  11606. AssertionResult const& result = assertionStats.assertionResult;
  11607. bool includeResults = m_config->includeSuccessfulResults() || !result.isOk();
  11608. if( includeResults || result.getResultType() == ResultWas::Warning ) {
  11609. // Print any info messages in <Info> tags.
  11610. for( auto const& msg : assertionStats.infoMessages ) {
  11611. if( msg.type == ResultWas::Info && includeResults ) {
  11612. m_xml.scopedElement( "Info" )
  11613. .writeText( msg.message );
  11614. } else if ( msg.type == ResultWas::Warning ) {
  11615. m_xml.scopedElement( "Warning" )
  11616. .writeText( msg.message );
  11617. }
  11618. }
  11619. }
  11620. // Drop out if result was successful but we're not printing them.
  11621. if( !includeResults && result.getResultType() != ResultWas::Warning )
  11622. return true;
  11623. // Print the expression if there is one.
  11624. if( result.hasExpression() ) {
  11625. m_xml.startElement( "Expression" )
  11626. .writeAttribute( "success", result.succeeded() )
  11627. .writeAttribute( "type", result.getTestMacroName() );
  11628. writeSourceInfo( result.getSourceInfo() );
  11629. m_xml.scopedElement( "Original" )
  11630. .writeText( result.getExpression() );
  11631. m_xml.scopedElement( "Expanded" )
  11632. .writeText( result.getExpandedExpression() );
  11633. }
  11634. // And... Print a result applicable to each result type.
  11635. switch( result.getResultType() ) {
  11636. case ResultWas::ThrewException:
  11637. m_xml.startElement( "Exception" );
  11638. writeSourceInfo( result.getSourceInfo() );
  11639. m_xml.writeText( result.getMessage() );
  11640. m_xml.endElement();
  11641. break;
  11642. case ResultWas::FatalErrorCondition:
  11643. m_xml.startElement( "FatalErrorCondition" );
  11644. writeSourceInfo( result.getSourceInfo() );
  11645. m_xml.writeText( result.getMessage() );
  11646. m_xml.endElement();
  11647. break;
  11648. case ResultWas::Info:
  11649. m_xml.scopedElement( "Info" )
  11650. .writeText( result.getMessage() );
  11651. break;
  11652. case ResultWas::Warning:
  11653. // Warning will already have been written
  11654. break;
  11655. case ResultWas::ExplicitFailure:
  11656. m_xml.startElement( "Failure" );
  11657. writeSourceInfo( result.getSourceInfo() );
  11658. m_xml.writeText( result.getMessage() );
  11659. m_xml.endElement();
  11660. break;
  11661. default:
  11662. break;
  11663. }
  11664. if( result.hasExpression() )
  11665. m_xml.endElement();
  11666. return true;
  11667. }
  11668. void XmlReporter::sectionEnded( SectionStats const& sectionStats ) {
  11669. StreamingReporterBase::sectionEnded( sectionStats );
  11670. if( --m_sectionDepth > 0 ) {
  11671. XmlWriter::ScopedElement e = m_xml.scopedElement( "OverallResults" );
  11672. e.writeAttribute( "successes", sectionStats.assertions.passed );
  11673. e.writeAttribute( "failures", sectionStats.assertions.failed );
  11674. e.writeAttribute( "expectedFailures", sectionStats.assertions.failedButOk );
  11675. if ( m_config->showDurations() == ShowDurations::Always )
  11676. e.writeAttribute( "durationInSeconds", sectionStats.durationInSeconds );
  11677. m_xml.endElement();
  11678. }
  11679. }
  11680. void XmlReporter::testCaseEnded( TestCaseStats const& testCaseStats ) {
  11681. StreamingReporterBase::testCaseEnded( testCaseStats );
  11682. XmlWriter::ScopedElement e = m_xml.scopedElement( "OverallResult" );
  11683. e.writeAttribute( "success", testCaseStats.totals.assertions.allOk() );
  11684. if ( m_config->showDurations() == ShowDurations::Always )
  11685. e.writeAttribute( "durationInSeconds", m_testCaseTimer.getElapsedSeconds() );
  11686. if( !testCaseStats.stdOut.empty() )
  11687. m_xml.scopedElement( "StdOut" ).writeText( trim( testCaseStats.stdOut ), false );
  11688. if( !testCaseStats.stdErr.empty() )
  11689. m_xml.scopedElement( "StdErr" ).writeText( trim( testCaseStats.stdErr ), false );
  11690. m_xml.endElement();
  11691. }
  11692. void XmlReporter::testGroupEnded( TestGroupStats const& testGroupStats ) {
  11693. StreamingReporterBase::testGroupEnded( testGroupStats );
  11694. // TODO: Check testGroupStats.aborting and act accordingly.
  11695. m_xml.scopedElement( "OverallResults" )
  11696. .writeAttribute( "successes", testGroupStats.totals.assertions.passed )
  11697. .writeAttribute( "failures", testGroupStats.totals.assertions.failed )
  11698. .writeAttribute( "expectedFailures", testGroupStats.totals.assertions.failedButOk );
  11699. m_xml.endElement();
  11700. }
  11701. void XmlReporter::testRunEnded( TestRunStats const& testRunStats ) {
  11702. StreamingReporterBase::testRunEnded( testRunStats );
  11703. m_xml.scopedElement( "OverallResults" )
  11704. .writeAttribute( "successes", testRunStats.totals.assertions.passed )
  11705. .writeAttribute( "failures", testRunStats.totals.assertions.failed )
  11706. .writeAttribute( "expectedFailures", testRunStats.totals.assertions.failedButOk );
  11707. m_xml.endElement();
  11708. }
  11709. CATCH_REGISTER_REPORTER( "xml", XmlReporter )
  11710. } // end namespace Catch
  11711. #if defined(_MSC_VER)
  11712. #pragma warning(pop)
  11713. #endif
  11714. // end catch_reporter_xml.cpp
  11715. namespace Catch {
  11716. LeakDetector leakDetector;
  11717. }
  11718. #ifdef __clang__
  11719. #pragma clang diagnostic pop
  11720. #endif
  11721. // end catch_impl.hpp
  11722. #endif
  11723. #ifdef CATCH_CONFIG_MAIN
  11724. // start catch_default_main.hpp
  11725. #ifndef __OBJC__
  11726. #if defined(CATCH_CONFIG_WCHAR) && defined(WIN32) && defined(_UNICODE) && !defined(DO_NOT_USE_WMAIN)
  11727. // Standard C/C++ Win32 Unicode wmain entry point
  11728. extern "C" int wmain (int argc, wchar_t * argv[], wchar_t * []) {
  11729. #else
  11730. // Standard C/C++ main entry point
  11731. int main (int argc, char * argv[]) {
  11732. #endif
  11733. return Catch::Session().run( argc, argv );
  11734. }
  11735. #else // __OBJC__
  11736. // Objective-C entry point
  11737. int main (int argc, char * const argv[]) {
  11738. #if !CATCH_ARC_ENABLED
  11739. NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
  11740. #endif
  11741. Catch::registerTestMethods();
  11742. int result = Catch::Session().run( argc, (char**)argv );
  11743. #if !CATCH_ARC_ENABLED
  11744. [pool drain];
  11745. #endif
  11746. return result;
  11747. }
  11748. #endif // __OBJC__
  11749. // end catch_default_main.hpp
  11750. #endif
  11751. #if !defined(CATCH_CONFIG_IMPL_ONLY)
  11752. #ifdef CLARA_CONFIG_MAIN_NOT_DEFINED
  11753. # undef CLARA_CONFIG_MAIN
  11754. #endif
  11755. #if !defined(CATCH_CONFIG_DISABLE)
  11756. //////
  11757. // If this config identifier is defined then all CATCH macros are prefixed with CATCH_
  11758. #ifdef CATCH_CONFIG_PREFIX_ALL
  11759. #define CATCH_REQUIRE( ... ) INTERNAL_CATCH_TEST( "CATCH_REQUIRE", Catch::ResultDisposition::Normal, __VA_ARGS__ )
  11760. #define CATCH_REQUIRE_FALSE( ... ) INTERNAL_CATCH_TEST( "CATCH_REQUIRE_FALSE", Catch::ResultDisposition::Normal | Catch::ResultDisposition::FalseTest, __VA_ARGS__ )
  11761. #define CATCH_REQUIRE_THROWS( ... ) INTERNAL_CATCH_THROWS( "CATCH_REQUIRE_THROWS", Catch::ResultDisposition::Normal, __VA_ARGS__ )
  11762. #define CATCH_REQUIRE_THROWS_AS( expr, exceptionType ) INTERNAL_CATCH_THROWS_AS( "CATCH_REQUIRE_THROWS_AS", exceptionType, Catch::ResultDisposition::Normal, expr )
  11763. #define CATCH_REQUIRE_THROWS_WITH( expr, matcher ) INTERNAL_CATCH_THROWS_STR_MATCHES( "CATCH_REQUIRE_THROWS_WITH", Catch::ResultDisposition::Normal, matcher, expr )
  11764. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  11765. #define CATCH_REQUIRE_THROWS_MATCHES( expr, exceptionType, matcher ) INTERNAL_CATCH_THROWS_MATCHES( "CATCH_REQUIRE_THROWS_MATCHES", exceptionType, Catch::ResultDisposition::Normal, matcher, expr )
  11766. #endif// CATCH_CONFIG_DISABLE_MATCHERS
  11767. #define CATCH_REQUIRE_NOTHROW( ... ) INTERNAL_CATCH_NO_THROW( "CATCH_REQUIRE_NOTHROW", Catch::ResultDisposition::Normal, __VA_ARGS__ )
  11768. #define CATCH_CHECK( ... ) INTERNAL_CATCH_TEST( "CATCH_CHECK", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  11769. #define CATCH_CHECK_FALSE( ... ) INTERNAL_CATCH_TEST( "CATCH_CHECK_FALSE", Catch::ResultDisposition::ContinueOnFailure | Catch::ResultDisposition::FalseTest, __VA_ARGS__ )
  11770. #define CATCH_CHECKED_IF( ... ) INTERNAL_CATCH_IF( "CATCH_CHECKED_IF", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  11771. #define CATCH_CHECKED_ELSE( ... ) INTERNAL_CATCH_ELSE( "CATCH_CHECKED_ELSE", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  11772. #define CATCH_CHECK_NOFAIL( ... ) INTERNAL_CATCH_TEST( "CATCH_CHECK_NOFAIL", Catch::ResultDisposition::ContinueOnFailure | Catch::ResultDisposition::SuppressFail, __VA_ARGS__ )
  11773. #define CATCH_CHECK_THROWS( ... ) INTERNAL_CATCH_THROWS( "CATCH_CHECK_THROWS", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  11774. #define CATCH_CHECK_THROWS_AS( expr, exceptionType ) INTERNAL_CATCH_THROWS_AS( "CATCH_CHECK_THROWS_AS", exceptionType, Catch::ResultDisposition::ContinueOnFailure, expr )
  11775. #define CATCH_CHECK_THROWS_WITH( expr, matcher ) INTERNAL_CATCH_THROWS_STR_MATCHES( "CATCH_CHECK_THROWS_WITH", Catch::ResultDisposition::ContinueOnFailure, matcher, expr )
  11776. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  11777. #define CATCH_CHECK_THROWS_MATCHES( expr, exceptionType, matcher ) INTERNAL_CATCH_THROWS_MATCHES( "CATCH_CHECK_THROWS_MATCHES", exceptionType, Catch::ResultDisposition::ContinueOnFailure, matcher, expr )
  11778. #endif // CATCH_CONFIG_DISABLE_MATCHERS
  11779. #define CATCH_CHECK_NOTHROW( ... ) INTERNAL_CATCH_NO_THROW( "CATCH_CHECK_NOTHROW", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  11780. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  11781. #define CATCH_CHECK_THAT( arg, matcher ) INTERNAL_CHECK_THAT( "CATCH_CHECK_THAT", matcher, Catch::ResultDisposition::ContinueOnFailure, arg )
  11782. #define CATCH_REQUIRE_THAT( arg, matcher ) INTERNAL_CHECK_THAT( "CATCH_REQUIRE_THAT", matcher, Catch::ResultDisposition::Normal, arg )
  11783. #endif // CATCH_CONFIG_DISABLE_MATCHERS
  11784. #define CATCH_INFO( msg ) INTERNAL_CATCH_INFO( "CATCH_INFO", msg )
  11785. #define CATCH_WARN( msg ) INTERNAL_CATCH_MSG( "CATCH_WARN", Catch::ResultWas::Warning, Catch::ResultDisposition::ContinueOnFailure, msg )
  11786. #define CATCH_CAPTURE( ... ) INTERNAL_CATCH_CAPTURE( INTERNAL_CATCH_UNIQUE_NAME(capturer), "CATCH_CAPTURE",__VA_ARGS__ )
  11787. #define CATCH_TEST_CASE( ... ) INTERNAL_CATCH_TESTCASE( __VA_ARGS__ )
  11788. #define CATCH_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEST_CASE_METHOD( className, __VA_ARGS__ )
  11789. #define CATCH_METHOD_AS_TEST_CASE( method, ... ) INTERNAL_CATCH_METHOD_AS_TEST_CASE( method, __VA_ARGS__ )
  11790. #define CATCH_REGISTER_TEST_CASE( Function, ... ) INTERNAL_CATCH_REGISTER_TESTCASE( Function, __VA_ARGS__ )
  11791. #define CATCH_SECTION( ... ) INTERNAL_CATCH_SECTION( __VA_ARGS__ )
  11792. #define CATCH_DYNAMIC_SECTION( ... ) INTERNAL_CATCH_DYNAMIC_SECTION( __VA_ARGS__ )
  11793. #define CATCH_FAIL( ... ) INTERNAL_CATCH_MSG( "CATCH_FAIL", Catch::ResultWas::ExplicitFailure, Catch::ResultDisposition::Normal, __VA_ARGS__ )
  11794. #define CATCH_FAIL_CHECK( ... ) INTERNAL_CATCH_MSG( "CATCH_FAIL_CHECK", Catch::ResultWas::ExplicitFailure, Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  11795. #define CATCH_SUCCEED( ... ) INTERNAL_CATCH_MSG( "CATCH_SUCCEED", Catch::ResultWas::Ok, Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  11796. #define CATCH_ANON_TEST_CASE() INTERNAL_CATCH_TESTCASE()
  11797. #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
  11798. #define CATCH_TEMPLATE_TEST_CASE( ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE( __VA_ARGS__ )
  11799. #define CATCH_TEMPLATE_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ )
  11800. #define CATCH_TEMPLATE_PRODUCT_TEST_CASE( ... ) INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE( __VA_ARGS__ )
  11801. #define CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, __VA_ARGS__ )
  11802. #else
  11803. #define CATCH_TEMPLATE_TEST_CASE( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE( __VA_ARGS__ ) )
  11804. #define CATCH_TEMPLATE_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ ) )
  11805. #define CATCH_TEMPLATE_PRODUCT_TEST_CASE( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE( __VA_ARGS__ ) )
  11806. #define CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, __VA_ARGS__ ) )
  11807. #endif
  11808. #if !defined(CATCH_CONFIG_RUNTIME_STATIC_REQUIRE)
  11809. #define CATCH_STATIC_REQUIRE( ... ) static_assert( __VA_ARGS__ , #__VA_ARGS__ ); CATCH_SUCCEED( #__VA_ARGS__ )
  11810. #define CATCH_STATIC_REQUIRE_FALSE( ... ) static_assert( !(__VA_ARGS__), "!(" #__VA_ARGS__ ")" ); CATCH_SUCCEED( #__VA_ARGS__ )
  11811. #else
  11812. #define CATCH_STATIC_REQUIRE( ... ) CATCH_REQUIRE( __VA_ARGS__ )
  11813. #define CATCH_STATIC_REQUIRE_FALSE( ... ) CATCH_REQUIRE_FALSE( __VA_ARGS__ )
  11814. #endif
  11815. // "BDD-style" convenience wrappers
  11816. #define CATCH_SCENARIO( ... ) CATCH_TEST_CASE( "Scenario: " __VA_ARGS__ )
  11817. #define CATCH_SCENARIO_METHOD( className, ... ) INTERNAL_CATCH_TEST_CASE_METHOD( className, "Scenario: " __VA_ARGS__ )
  11818. #define CATCH_GIVEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " Given: " << desc )
  11819. #define CATCH_AND_GIVEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( "And given: " << desc )
  11820. #define CATCH_WHEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " When: " << desc )
  11821. #define CATCH_AND_WHEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " And when: " << desc )
  11822. #define CATCH_THEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " Then: " << desc )
  11823. #define CATCH_AND_THEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " And: " << desc )
  11824. // If CATCH_CONFIG_PREFIX_ALL is not defined then the CATCH_ prefix is not required
  11825. #else
  11826. #define REQUIRE( ... ) INTERNAL_CATCH_TEST( "REQUIRE", Catch::ResultDisposition::Normal, __VA_ARGS__ )
  11827. #define REQUIRE_FALSE( ... ) INTERNAL_CATCH_TEST( "REQUIRE_FALSE", Catch::ResultDisposition::Normal | Catch::ResultDisposition::FalseTest, __VA_ARGS__ )
  11828. #define REQUIRE_THROWS( ... ) INTERNAL_CATCH_THROWS( "REQUIRE_THROWS", Catch::ResultDisposition::Normal, __VA_ARGS__ )
  11829. #define REQUIRE_THROWS_AS( expr, exceptionType ) INTERNAL_CATCH_THROWS_AS( "REQUIRE_THROWS_AS", exceptionType, Catch::ResultDisposition::Normal, expr )
  11830. #define REQUIRE_THROWS_WITH( expr, matcher ) INTERNAL_CATCH_THROWS_STR_MATCHES( "REQUIRE_THROWS_WITH", Catch::ResultDisposition::Normal, matcher, expr )
  11831. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  11832. #define REQUIRE_THROWS_MATCHES( expr, exceptionType, matcher ) INTERNAL_CATCH_THROWS_MATCHES( "REQUIRE_THROWS_MATCHES", exceptionType, Catch::ResultDisposition::Normal, matcher, expr )
  11833. #endif // CATCH_CONFIG_DISABLE_MATCHERS
  11834. #define REQUIRE_NOTHROW( ... ) INTERNAL_CATCH_NO_THROW( "REQUIRE_NOTHROW", Catch::ResultDisposition::Normal, __VA_ARGS__ )
  11835. #define CHECK( ... ) INTERNAL_CATCH_TEST( "CHECK", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  11836. #define CHECK_FALSE( ... ) INTERNAL_CATCH_TEST( "CHECK_FALSE", Catch::ResultDisposition::ContinueOnFailure | Catch::ResultDisposition::FalseTest, __VA_ARGS__ )
  11837. #define CHECKED_IF( ... ) INTERNAL_CATCH_IF( "CHECKED_IF", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  11838. #define CHECKED_ELSE( ... ) INTERNAL_CATCH_ELSE( "CHECKED_ELSE", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  11839. #define CHECK_NOFAIL( ... ) INTERNAL_CATCH_TEST( "CHECK_NOFAIL", Catch::ResultDisposition::ContinueOnFailure | Catch::ResultDisposition::SuppressFail, __VA_ARGS__ )
  11840. #define CHECK_THROWS( ... ) INTERNAL_CATCH_THROWS( "CHECK_THROWS", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  11841. #define CHECK_THROWS_AS( expr, exceptionType ) INTERNAL_CATCH_THROWS_AS( "CHECK_THROWS_AS", exceptionType, Catch::ResultDisposition::ContinueOnFailure, expr )
  11842. #define CHECK_THROWS_WITH( expr, matcher ) INTERNAL_CATCH_THROWS_STR_MATCHES( "CHECK_THROWS_WITH", Catch::ResultDisposition::ContinueOnFailure, matcher, expr )
  11843. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  11844. #define CHECK_THROWS_MATCHES( expr, exceptionType, matcher ) INTERNAL_CATCH_THROWS_MATCHES( "CHECK_THROWS_MATCHES", exceptionType, Catch::ResultDisposition::ContinueOnFailure, matcher, expr )
  11845. #endif // CATCH_CONFIG_DISABLE_MATCHERS
  11846. #define CHECK_NOTHROW( ... ) INTERNAL_CATCH_NO_THROW( "CHECK_NOTHROW", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  11847. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  11848. #define CHECK_THAT( arg, matcher ) INTERNAL_CHECK_THAT( "CHECK_THAT", matcher, Catch::ResultDisposition::ContinueOnFailure, arg )
  11849. #define REQUIRE_THAT( arg, matcher ) INTERNAL_CHECK_THAT( "REQUIRE_THAT", matcher, Catch::ResultDisposition::Normal, arg )
  11850. #endif // CATCH_CONFIG_DISABLE_MATCHERS
  11851. #define INFO( msg ) INTERNAL_CATCH_INFO( "INFO", msg )
  11852. #define WARN( msg ) INTERNAL_CATCH_MSG( "WARN", Catch::ResultWas::Warning, Catch::ResultDisposition::ContinueOnFailure, msg )
  11853. #define CAPTURE( ... ) INTERNAL_CATCH_CAPTURE( INTERNAL_CATCH_UNIQUE_NAME(capturer), "CAPTURE",__VA_ARGS__ )
  11854. #define TEST_CASE( ... ) INTERNAL_CATCH_TESTCASE( __VA_ARGS__ )
  11855. #define TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEST_CASE_METHOD( className, __VA_ARGS__ )
  11856. #define METHOD_AS_TEST_CASE( method, ... ) INTERNAL_CATCH_METHOD_AS_TEST_CASE( method, __VA_ARGS__ )
  11857. #define REGISTER_TEST_CASE( Function, ... ) INTERNAL_CATCH_REGISTER_TESTCASE( Function, __VA_ARGS__ )
  11858. #define SECTION( ... ) INTERNAL_CATCH_SECTION( __VA_ARGS__ )
  11859. #define DYNAMIC_SECTION( ... ) INTERNAL_CATCH_DYNAMIC_SECTION( __VA_ARGS__ )
  11860. #define FAIL( ... ) INTERNAL_CATCH_MSG( "FAIL", Catch::ResultWas::ExplicitFailure, Catch::ResultDisposition::Normal, __VA_ARGS__ )
  11861. #define FAIL_CHECK( ... ) INTERNAL_CATCH_MSG( "FAIL_CHECK", Catch::ResultWas::ExplicitFailure, Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  11862. #define SUCCEED( ... ) INTERNAL_CATCH_MSG( "SUCCEED", Catch::ResultWas::Ok, Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  11863. #define ANON_TEST_CASE() INTERNAL_CATCH_TESTCASE()
  11864. #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
  11865. #define TEMPLATE_TEST_CASE( ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE( __VA_ARGS__ )
  11866. #define TEMPLATE_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ )
  11867. #define TEMPLATE_PRODUCT_TEST_CASE( ... ) INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE( __VA_ARGS__ )
  11868. #define TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, __VA_ARGS__ )
  11869. #else
  11870. #define TEMPLATE_TEST_CASE( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE( __VA_ARGS__ ) )
  11871. #define TEMPLATE_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ ) )
  11872. #define TEMPLATE_PRODUCT_TEST_CASE( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE( __VA_ARGS__ ) )
  11873. #define TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, __VA_ARGS__ ) )
  11874. #endif
  11875. #if !defined(CATCH_CONFIG_RUNTIME_STATIC_REQUIRE)
  11876. #define STATIC_REQUIRE( ... ) static_assert( __VA_ARGS__, #__VA_ARGS__ ); SUCCEED( #__VA_ARGS__ )
  11877. #define STATIC_REQUIRE_FALSE( ... ) static_assert( !(__VA_ARGS__), "!(" #__VA_ARGS__ ")" ); SUCCEED( "!(" #__VA_ARGS__ ")" )
  11878. #else
  11879. #define STATIC_REQUIRE( ... ) REQUIRE( __VA_ARGS__ )
  11880. #define STATIC_REQUIRE_FALSE( ... ) REQUIRE_FALSE( __VA_ARGS__ )
  11881. #endif
  11882. #endif
  11883. #define CATCH_TRANSLATE_EXCEPTION( signature ) INTERNAL_CATCH_TRANSLATE_EXCEPTION( signature )
  11884. // "BDD-style" convenience wrappers
  11885. #define SCENARIO( ... ) TEST_CASE( "Scenario: " __VA_ARGS__ )
  11886. #define SCENARIO_METHOD( className, ... ) INTERNAL_CATCH_TEST_CASE_METHOD( className, "Scenario: " __VA_ARGS__ )
  11887. #define GIVEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " Given: " << desc )
  11888. #define AND_GIVEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( "And given: " << desc )
  11889. #define WHEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " When: " << desc )
  11890. #define AND_WHEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " And when: " << desc )
  11891. #define THEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " Then: " << desc )
  11892. #define AND_THEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " And: " << desc )
  11893. using Catch::Detail::Approx;
  11894. #else // CATCH_CONFIG_DISABLE
  11895. //////
  11896. // If this config identifier is defined then all CATCH macros are prefixed with CATCH_
  11897. #ifdef CATCH_CONFIG_PREFIX_ALL
  11898. #define CATCH_REQUIRE( ... ) (void)(0)
  11899. #define CATCH_REQUIRE_FALSE( ... ) (void)(0)
  11900. #define CATCH_REQUIRE_THROWS( ... ) (void)(0)
  11901. #define CATCH_REQUIRE_THROWS_AS( expr, exceptionType ) (void)(0)
  11902. #define CATCH_REQUIRE_THROWS_WITH( expr, matcher ) (void)(0)
  11903. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  11904. #define CATCH_REQUIRE_THROWS_MATCHES( expr, exceptionType, matcher ) (void)(0)
  11905. #endif// CATCH_CONFIG_DISABLE_MATCHERS
  11906. #define CATCH_REQUIRE_NOTHROW( ... ) (void)(0)
  11907. #define CATCH_CHECK( ... ) (void)(0)
  11908. #define CATCH_CHECK_FALSE( ... ) (void)(0)
  11909. #define CATCH_CHECKED_IF( ... ) if (__VA_ARGS__)
  11910. #define CATCH_CHECKED_ELSE( ... ) if (!(__VA_ARGS__))
  11911. #define CATCH_CHECK_NOFAIL( ... ) (void)(0)
  11912. #define CATCH_CHECK_THROWS( ... ) (void)(0)
  11913. #define CATCH_CHECK_THROWS_AS( expr, exceptionType ) (void)(0)
  11914. #define CATCH_CHECK_THROWS_WITH( expr, matcher ) (void)(0)
  11915. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  11916. #define CATCH_CHECK_THROWS_MATCHES( expr, exceptionType, matcher ) (void)(0)
  11917. #endif // CATCH_CONFIG_DISABLE_MATCHERS
  11918. #define CATCH_CHECK_NOTHROW( ... ) (void)(0)
  11919. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  11920. #define CATCH_CHECK_THAT( arg, matcher ) (void)(0)
  11921. #define CATCH_REQUIRE_THAT( arg, matcher ) (void)(0)
  11922. #endif // CATCH_CONFIG_DISABLE_MATCHERS
  11923. #define CATCH_INFO( msg ) (void)(0)
  11924. #define CATCH_WARN( msg ) (void)(0)
  11925. #define CATCH_CAPTURE( msg ) (void)(0)
  11926. #define CATCH_TEST_CASE( ... ) INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ))
  11927. #define CATCH_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ))
  11928. #define CATCH_METHOD_AS_TEST_CASE( method, ... )
  11929. #define CATCH_REGISTER_TEST_CASE( Function, ... ) (void)(0)
  11930. #define CATCH_SECTION( ... )
  11931. #define CATCH_DYNAMIC_SECTION( ... )
  11932. #define CATCH_FAIL( ... ) (void)(0)
  11933. #define CATCH_FAIL_CHECK( ... ) (void)(0)
  11934. #define CATCH_SUCCEED( ... ) (void)(0)
  11935. #define CATCH_ANON_TEST_CASE() INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ))
  11936. #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
  11937. #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____ ) )
  11938. #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 )
  11939. #define CATCH_TEMPLATE_PRODUCT_TEST_CASE( ... ) CATCH_TEMPLATE_TEST_CASE( __VA_ARGS__ )
  11940. #define CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, ... ) CATCH_TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ )
  11941. #else
  11942. #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____ ) ) )
  11943. #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 ) )
  11944. #define CATCH_TEMPLATE_PRODUCT_TEST_CASE( ... ) CATCH_TEMPLATE_TEST_CASE( __VA_ARGS__ )
  11945. #define CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, ... ) CATCH_TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ )
  11946. #endif
  11947. // "BDD-style" convenience wrappers
  11948. #define CATCH_SCENARIO( ... ) INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ))
  11949. #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 )
  11950. #define CATCH_GIVEN( desc )
  11951. #define CATCH_AND_GIVEN( desc )
  11952. #define CATCH_WHEN( desc )
  11953. #define CATCH_AND_WHEN( desc )
  11954. #define CATCH_THEN( desc )
  11955. #define CATCH_AND_THEN( desc )
  11956. #define CATCH_STATIC_REQUIRE( ... ) (void)(0)
  11957. #define CATCH_STATIC_REQUIRE_FALSE( ... ) (void)(0)
  11958. // If CATCH_CONFIG_PREFIX_ALL is not defined then the CATCH_ prefix is not required
  11959. #else
  11960. #define REQUIRE( ... ) (void)(0)
  11961. #define REQUIRE_FALSE( ... ) (void)(0)
  11962. #define REQUIRE_THROWS( ... ) (void)(0)
  11963. #define REQUIRE_THROWS_AS( expr, exceptionType ) (void)(0)
  11964. #define REQUIRE_THROWS_WITH( expr, matcher ) (void)(0)
  11965. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  11966. #define REQUIRE_THROWS_MATCHES( expr, exceptionType, matcher ) (void)(0)
  11967. #endif // CATCH_CONFIG_DISABLE_MATCHERS
  11968. #define REQUIRE_NOTHROW( ... ) (void)(0)
  11969. #define CHECK( ... ) (void)(0)
  11970. #define CHECK_FALSE( ... ) (void)(0)
  11971. #define CHECKED_IF( ... ) if (__VA_ARGS__)
  11972. #define CHECKED_ELSE( ... ) if (!(__VA_ARGS__))
  11973. #define CHECK_NOFAIL( ... ) (void)(0)
  11974. #define CHECK_THROWS( ... ) (void)(0)
  11975. #define CHECK_THROWS_AS( expr, exceptionType ) (void)(0)
  11976. #define CHECK_THROWS_WITH( expr, matcher ) (void)(0)
  11977. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  11978. #define CHECK_THROWS_MATCHES( expr, exceptionType, matcher ) (void)(0)
  11979. #endif // CATCH_CONFIG_DISABLE_MATCHERS
  11980. #define CHECK_NOTHROW( ... ) (void)(0)
  11981. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  11982. #define CHECK_THAT( arg, matcher ) (void)(0)
  11983. #define REQUIRE_THAT( arg, matcher ) (void)(0)
  11984. #endif // CATCH_CONFIG_DISABLE_MATCHERS
  11985. #define INFO( msg ) (void)(0)
  11986. #define WARN( msg ) (void)(0)
  11987. #define CAPTURE( msg ) (void)(0)
  11988. #define TEST_CASE( ... ) INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ))
  11989. #define TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ))
  11990. #define METHOD_AS_TEST_CASE( method, ... )
  11991. #define REGISTER_TEST_CASE( Function, ... ) (void)(0)
  11992. #define SECTION( ... )
  11993. #define DYNAMIC_SECTION( ... )
  11994. #define FAIL( ... ) (void)(0)
  11995. #define FAIL_CHECK( ... ) (void)(0)
  11996. #define SUCCEED( ... ) (void)(0)
  11997. #define ANON_TEST_CASE() INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ))
  11998. #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
  11999. #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____ ) )
  12000. #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 )
  12001. #define TEMPLATE_PRODUCT_TEST_CASE( ... ) TEMPLATE_TEST_CASE( __VA_ARGS__ )
  12002. #define TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, ... ) TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ )
  12003. #else
  12004. #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____ ) ) )
  12005. #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 ) )
  12006. #define TEMPLATE_PRODUCT_TEST_CASE( ... ) TEMPLATE_TEST_CASE( __VA_ARGS__ )
  12007. #define TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, ... ) TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ )
  12008. #endif
  12009. #define STATIC_REQUIRE( ... ) (void)(0)
  12010. #define STATIC_REQUIRE_FALSE( ... ) (void)(0)
  12011. #endif
  12012. #define CATCH_TRANSLATE_EXCEPTION( signature ) INTERNAL_CATCH_TRANSLATE_EXCEPTION_NO_REG( INTERNAL_CATCH_UNIQUE_NAME( catch_internal_ExceptionTranslator ), signature )
  12013. // "BDD-style" convenience wrappers
  12014. #define SCENARIO( ... ) INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ) )
  12015. #define SCENARIO_METHOD( className, ... ) INTERNAL_CATCH_TESTCASE_METHOD_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ), className )
  12016. #define GIVEN( desc )
  12017. #define AND_GIVEN( desc )
  12018. #define WHEN( desc )
  12019. #define AND_WHEN( desc )
  12020. #define THEN( desc )
  12021. #define AND_THEN( desc )
  12022. using Catch::Detail::Approx;
  12023. #endif
  12024. #endif // ! CATCH_CONFIG_IMPL_ONLY
  12025. // start catch_reenable_warnings.h
  12026. #ifdef __clang__
  12027. # ifdef __ICC // icpc defines the __clang__ macro
  12028. # pragma warning(pop)
  12029. # else
  12030. # pragma clang diagnostic pop
  12031. # endif
  12032. #elif defined __GNUC__
  12033. # pragma GCC diagnostic pop
  12034. #endif
  12035. // end catch_reenable_warnings.h
  12036. // end catch.hpp
  12037. #endif // TWOBLUECUBES_SINGLE_INCLUDE_CATCH_HPP_INCLUDED