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

14688 lines
496KB

  1. /*
  2. * Catch v2.6.0
  3. * Generated: 2019-01-31 22:25:55.560884
  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 0
  17. #ifdef __clang__
  18. # pragma clang system_header
  19. #elif defined __GNUC__
  20. # pragma GCC system_header
  21. #endif
  22. // start catch_suppress_warnings.h
  23. #ifdef __clang__
  24. # ifdef __ICC // icpc defines the __clang__ macro
  25. # pragma warning(push)
  26. # pragma warning(disable: 161 1682)
  27. # else // __ICC
  28. # pragma clang diagnostic push
  29. # pragma clang diagnostic ignored "-Wpadded"
  30. # pragma clang diagnostic ignored "-Wswitch-enum"
  31. # pragma clang diagnostic ignored "-Wcovered-switch-default"
  32. # endif
  33. #elif defined __GNUC__
  34. // 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( 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( Config const& config ) {
  7284. Option<std::size_t> listedCount;
  7285. if( config.listTests() )
  7286. listedCount = listedCount.valueOr(0) + listTests( config );
  7287. if( config.listTestNamesOnly() )
  7288. listedCount = listedCount.valueOr(0) + listTestsNamesOnly( config );
  7289. if( config.listTags() )
  7290. listedCount = listedCount.valueOr(0) + listTags( config );
  7291. if( config.listReporters() )
  7292. listedCount = listedCount.valueOr(0) + listReporters();
  7293. return listedCount;
  7294. }
  7295. } // end namespace Catch
  7296. // end catch_list.cpp
  7297. // start catch_matchers.cpp
  7298. namespace Catch {
  7299. namespace Matchers {
  7300. namespace Impl {
  7301. std::string MatcherUntypedBase::toString() const {
  7302. if( m_cachedToString.empty() )
  7303. m_cachedToString = describe();
  7304. return m_cachedToString;
  7305. }
  7306. MatcherUntypedBase::~MatcherUntypedBase() = default;
  7307. } // namespace Impl
  7308. } // namespace Matchers
  7309. using namespace Matchers;
  7310. using Matchers::Impl::MatcherBase;
  7311. } // namespace Catch
  7312. // end catch_matchers.cpp
  7313. // start catch_matchers_floating.cpp
  7314. // start catch_polyfills.hpp
  7315. namespace Catch {
  7316. bool isnan(float f);
  7317. bool isnan(double d);
  7318. }
  7319. // end catch_polyfills.hpp
  7320. // start catch_to_string.hpp
  7321. #include <string>
  7322. namespace Catch {
  7323. template <typename T>
  7324. std::string to_string(T const& t) {
  7325. #if defined(CATCH_CONFIG_CPP11_TO_STRING)
  7326. return std::to_string(t);
  7327. #else
  7328. ReusableStringStream rss;
  7329. rss << t;
  7330. return rss.str();
  7331. #endif
  7332. }
  7333. } // end namespace Catch
  7334. // end catch_to_string.hpp
  7335. #include <cstdlib>
  7336. #include <cstdint>
  7337. #include <cstring>
  7338. namespace Catch {
  7339. namespace Matchers {
  7340. namespace Floating {
  7341. enum class FloatingPointKind : uint8_t {
  7342. Float,
  7343. Double
  7344. };
  7345. }
  7346. }
  7347. }
  7348. namespace {
  7349. template <typename T>
  7350. struct Converter;
  7351. template <>
  7352. struct Converter<float> {
  7353. static_assert(sizeof(float) == sizeof(int32_t), "Important ULP matcher assumption violated");
  7354. Converter(float f) {
  7355. std::memcpy(&i, &f, sizeof(f));
  7356. }
  7357. int32_t i;
  7358. };
  7359. template <>
  7360. struct Converter<double> {
  7361. static_assert(sizeof(double) == sizeof(int64_t), "Important ULP matcher assumption violated");
  7362. Converter(double d) {
  7363. std::memcpy(&i, &d, sizeof(d));
  7364. }
  7365. int64_t i;
  7366. };
  7367. template <typename T>
  7368. auto convert(T t) -> Converter<T> {
  7369. return Converter<T>(t);
  7370. }
  7371. template <typename FP>
  7372. bool almostEqualUlps(FP lhs, FP rhs, int maxUlpDiff) {
  7373. // Comparison with NaN should always be false.
  7374. // This way we can rule it out before getting into the ugly details
  7375. if (Catch::isnan(lhs) || Catch::isnan(rhs)) {
  7376. return false;
  7377. }
  7378. auto lc = convert(lhs);
  7379. auto rc = convert(rhs);
  7380. if ((lc.i < 0) != (rc.i < 0)) {
  7381. // Potentially we can have +0 and -0
  7382. return lhs == rhs;
  7383. }
  7384. auto ulpDiff = std::abs(lc.i - rc.i);
  7385. return ulpDiff <= maxUlpDiff;
  7386. }
  7387. }
  7388. namespace Catch {
  7389. namespace Matchers {
  7390. namespace Floating {
  7391. WithinAbsMatcher::WithinAbsMatcher(double target, double margin)
  7392. :m_target{ target }, m_margin{ margin } {
  7393. CATCH_ENFORCE(margin >= 0, "Invalid margin: " << margin << '.'
  7394. << " Margin has to be non-negative.");
  7395. }
  7396. // Performs equivalent check of std::fabs(lhs - rhs) <= margin
  7397. // But without the subtraction to allow for INFINITY in comparison
  7398. bool WithinAbsMatcher::match(double const& matchee) const {
  7399. return (matchee + m_margin >= m_target) && (m_target + m_margin >= matchee);
  7400. }
  7401. std::string WithinAbsMatcher::describe() const {
  7402. return "is within " + ::Catch::Detail::stringify(m_margin) + " of " + ::Catch::Detail::stringify(m_target);
  7403. }
  7404. WithinUlpsMatcher::WithinUlpsMatcher(double target, int ulps, FloatingPointKind baseType)
  7405. :m_target{ target }, m_ulps{ ulps }, m_type{ baseType } {
  7406. CATCH_ENFORCE(ulps >= 0, "Invalid ULP setting: " << ulps << '.'
  7407. << " ULPs have to be non-negative.");
  7408. }
  7409. #if defined(__clang__)
  7410. #pragma clang diagnostic push
  7411. // Clang <3.5 reports on the default branch in the switch below
  7412. #pragma clang diagnostic ignored "-Wunreachable-code"
  7413. #endif
  7414. bool WithinUlpsMatcher::match(double const& matchee) const {
  7415. switch (m_type) {
  7416. case FloatingPointKind::Float:
  7417. return almostEqualUlps<float>(static_cast<float>(matchee), static_cast<float>(m_target), m_ulps);
  7418. case FloatingPointKind::Double:
  7419. return almostEqualUlps<double>(matchee, m_target, m_ulps);
  7420. default:
  7421. CATCH_INTERNAL_ERROR( "Unknown FloatingPointKind value" );
  7422. }
  7423. }
  7424. #if defined(__clang__)
  7425. #pragma clang diagnostic pop
  7426. #endif
  7427. std::string WithinUlpsMatcher::describe() const {
  7428. return "is within " + Catch::to_string(m_ulps) + " ULPs of " + ::Catch::Detail::stringify(m_target) + ((m_type == FloatingPointKind::Float)? "f" : "");
  7429. }
  7430. }// namespace Floating
  7431. Floating::WithinUlpsMatcher WithinULP(double target, int maxUlpDiff) {
  7432. return Floating::WithinUlpsMatcher(target, maxUlpDiff, Floating::FloatingPointKind::Double);
  7433. }
  7434. Floating::WithinUlpsMatcher WithinULP(float target, int maxUlpDiff) {
  7435. return Floating::WithinUlpsMatcher(target, maxUlpDiff, Floating::FloatingPointKind::Float);
  7436. }
  7437. Floating::WithinAbsMatcher WithinAbs(double target, double margin) {
  7438. return Floating::WithinAbsMatcher(target, margin);
  7439. }
  7440. } // namespace Matchers
  7441. } // namespace Catch
  7442. // end catch_matchers_floating.cpp
  7443. // start catch_matchers_generic.cpp
  7444. std::string Catch::Matchers::Generic::Detail::finalizeDescription(const std::string& desc) {
  7445. if (desc.empty()) {
  7446. return "matches undescribed predicate";
  7447. } else {
  7448. return "matches predicate: \"" + desc + '"';
  7449. }
  7450. }
  7451. // end catch_matchers_generic.cpp
  7452. // start catch_matchers_string.cpp
  7453. #include <regex>
  7454. namespace Catch {
  7455. namespace Matchers {
  7456. namespace StdString {
  7457. CasedString::CasedString( std::string const& str, CaseSensitive::Choice caseSensitivity )
  7458. : m_caseSensitivity( caseSensitivity ),
  7459. m_str( adjustString( str ) )
  7460. {}
  7461. std::string CasedString::adjustString( std::string const& str ) const {
  7462. return m_caseSensitivity == CaseSensitive::No
  7463. ? toLower( str )
  7464. : str;
  7465. }
  7466. std::string CasedString::caseSensitivitySuffix() const {
  7467. return m_caseSensitivity == CaseSensitive::No
  7468. ? " (case insensitive)"
  7469. : std::string();
  7470. }
  7471. StringMatcherBase::StringMatcherBase( std::string const& operation, CasedString const& comparator )
  7472. : m_comparator( comparator ),
  7473. m_operation( operation ) {
  7474. }
  7475. std::string StringMatcherBase::describe() const {
  7476. std::string description;
  7477. description.reserve(5 + m_operation.size() + m_comparator.m_str.size() +
  7478. m_comparator.caseSensitivitySuffix().size());
  7479. description += m_operation;
  7480. description += ": \"";
  7481. description += m_comparator.m_str;
  7482. description += "\"";
  7483. description += m_comparator.caseSensitivitySuffix();
  7484. return description;
  7485. }
  7486. EqualsMatcher::EqualsMatcher( CasedString const& comparator ) : StringMatcherBase( "equals", comparator ) {}
  7487. bool EqualsMatcher::match( std::string const& source ) const {
  7488. return m_comparator.adjustString( source ) == m_comparator.m_str;
  7489. }
  7490. ContainsMatcher::ContainsMatcher( CasedString const& comparator ) : StringMatcherBase( "contains", comparator ) {}
  7491. bool ContainsMatcher::match( std::string const& source ) const {
  7492. return contains( m_comparator.adjustString( source ), m_comparator.m_str );
  7493. }
  7494. StartsWithMatcher::StartsWithMatcher( CasedString const& comparator ) : StringMatcherBase( "starts with", comparator ) {}
  7495. bool StartsWithMatcher::match( std::string const& source ) const {
  7496. return startsWith( m_comparator.adjustString( source ), m_comparator.m_str );
  7497. }
  7498. EndsWithMatcher::EndsWithMatcher( CasedString const& comparator ) : StringMatcherBase( "ends with", comparator ) {}
  7499. bool EndsWithMatcher::match( std::string const& source ) const {
  7500. return endsWith( m_comparator.adjustString( source ), m_comparator.m_str );
  7501. }
  7502. RegexMatcher::RegexMatcher(std::string regex, CaseSensitive::Choice caseSensitivity): m_regex(std::move(regex)), m_caseSensitivity(caseSensitivity) {}
  7503. bool RegexMatcher::match(std::string const& matchee) const {
  7504. auto flags = std::regex::ECMAScript; // ECMAScript is the default syntax option anyway
  7505. if (m_caseSensitivity == CaseSensitive::Choice::No) {
  7506. flags |= std::regex::icase;
  7507. }
  7508. auto reg = std::regex(m_regex, flags);
  7509. return std::regex_match(matchee, reg);
  7510. }
  7511. std::string RegexMatcher::describe() const {
  7512. return "matches " + ::Catch::Detail::stringify(m_regex) + ((m_caseSensitivity == CaseSensitive::Choice::Yes)? " case sensitively" : " case insensitively");
  7513. }
  7514. } // namespace StdString
  7515. StdString::EqualsMatcher Equals( std::string const& str, CaseSensitive::Choice caseSensitivity ) {
  7516. return StdString::EqualsMatcher( StdString::CasedString( str, caseSensitivity) );
  7517. }
  7518. StdString::ContainsMatcher Contains( std::string const& str, CaseSensitive::Choice caseSensitivity ) {
  7519. return StdString::ContainsMatcher( StdString::CasedString( str, caseSensitivity) );
  7520. }
  7521. StdString::EndsWithMatcher EndsWith( std::string const& str, CaseSensitive::Choice caseSensitivity ) {
  7522. return StdString::EndsWithMatcher( StdString::CasedString( str, caseSensitivity) );
  7523. }
  7524. StdString::StartsWithMatcher StartsWith( std::string const& str, CaseSensitive::Choice caseSensitivity ) {
  7525. return StdString::StartsWithMatcher( StdString::CasedString( str, caseSensitivity) );
  7526. }
  7527. StdString::RegexMatcher Matches(std::string const& regex, CaseSensitive::Choice caseSensitivity) {
  7528. return StdString::RegexMatcher(regex, caseSensitivity);
  7529. }
  7530. } // namespace Matchers
  7531. } // namespace Catch
  7532. // end catch_matchers_string.cpp
  7533. // start catch_message.cpp
  7534. // start catch_uncaught_exceptions.h
  7535. namespace Catch {
  7536. bool uncaught_exceptions();
  7537. } // end namespace Catch
  7538. // end catch_uncaught_exceptions.h
  7539. #include <cassert>
  7540. #include <stack>
  7541. namespace Catch {
  7542. MessageInfo::MessageInfo( StringRef const& _macroName,
  7543. SourceLineInfo const& _lineInfo,
  7544. ResultWas::OfType _type )
  7545. : macroName( _macroName ),
  7546. lineInfo( _lineInfo ),
  7547. type( _type ),
  7548. sequence( ++globalCount )
  7549. {}
  7550. bool MessageInfo::operator==( MessageInfo const& other ) const {
  7551. return sequence == other.sequence;
  7552. }
  7553. bool MessageInfo::operator<( MessageInfo const& other ) const {
  7554. return sequence < other.sequence;
  7555. }
  7556. // This may need protecting if threading support is added
  7557. unsigned int MessageInfo::globalCount = 0;
  7558. ////////////////////////////////////////////////////////////////////////////
  7559. Catch::MessageBuilder::MessageBuilder( StringRef const& macroName,
  7560. SourceLineInfo const& lineInfo,
  7561. ResultWas::OfType type )
  7562. :m_info(macroName, lineInfo, type) {}
  7563. ////////////////////////////////////////////////////////////////////////////
  7564. ScopedMessage::ScopedMessage( MessageBuilder const& builder )
  7565. : m_info( builder.m_info )
  7566. {
  7567. m_info.message = builder.m_stream.str();
  7568. getResultCapture().pushScopedMessage( m_info );
  7569. }
  7570. ScopedMessage::~ScopedMessage() {
  7571. if ( !uncaught_exceptions() ){
  7572. getResultCapture().popScopedMessage(m_info);
  7573. }
  7574. }
  7575. Capturer::Capturer( StringRef macroName, SourceLineInfo const& lineInfo, ResultWas::OfType resultType, StringRef names ) {
  7576. auto trimmed = [&] (size_t start, size_t end) {
  7577. while (names[start] == ',' || isspace(names[start])) {
  7578. ++start;
  7579. }
  7580. while (names[end] == ',' || isspace(names[end])) {
  7581. --end;
  7582. }
  7583. return names.substr(start, end - start + 1);
  7584. };
  7585. size_t start = 0;
  7586. std::stack<char> openings;
  7587. for (size_t pos = 0; pos < names.size(); ++pos) {
  7588. char c = names[pos];
  7589. switch (c) {
  7590. case '[':
  7591. case '{':
  7592. case '(':
  7593. // It is basically impossible to disambiguate between
  7594. // comparison and start of template args in this context
  7595. // case '<':
  7596. openings.push(c);
  7597. break;
  7598. case ']':
  7599. case '}':
  7600. case ')':
  7601. // case '>':
  7602. openings.pop();
  7603. break;
  7604. case ',':
  7605. if (start != pos && openings.size() == 0) {
  7606. m_messages.emplace_back(macroName, lineInfo, resultType);
  7607. m_messages.back().message = trimmed(start, pos);
  7608. m_messages.back().message += " := ";
  7609. start = pos;
  7610. }
  7611. }
  7612. }
  7613. assert(openings.size() == 0 && "Mismatched openings");
  7614. m_messages.emplace_back(macroName, lineInfo, resultType);
  7615. m_messages.back().message = trimmed(start, names.size() - 1);
  7616. m_messages.back().message += " := ";
  7617. }
  7618. Capturer::~Capturer() {
  7619. if ( !uncaught_exceptions() ){
  7620. assert( m_captured == m_messages.size() );
  7621. for( size_t i = 0; i < m_captured; ++i )
  7622. m_resultCapture.popScopedMessage( m_messages[i] );
  7623. }
  7624. }
  7625. void Capturer::captureValue( size_t index, std::string const& value ) {
  7626. assert( index < m_messages.size() );
  7627. m_messages[index].message += value;
  7628. m_resultCapture.pushScopedMessage( m_messages[index] );
  7629. m_captured++;
  7630. }
  7631. } // end namespace Catch
  7632. // end catch_message.cpp
  7633. // start catch_output_redirect.cpp
  7634. // start catch_output_redirect.h
  7635. #ifndef TWOBLUECUBES_CATCH_OUTPUT_REDIRECT_H
  7636. #define TWOBLUECUBES_CATCH_OUTPUT_REDIRECT_H
  7637. #include <cstdio>
  7638. #include <iosfwd>
  7639. #include <string>
  7640. namespace Catch {
  7641. class RedirectedStream {
  7642. std::ostream& m_originalStream;
  7643. std::ostream& m_redirectionStream;
  7644. std::streambuf* m_prevBuf;
  7645. public:
  7646. RedirectedStream( std::ostream& originalStream, std::ostream& redirectionStream );
  7647. ~RedirectedStream();
  7648. };
  7649. class RedirectedStdOut {
  7650. ReusableStringStream m_rss;
  7651. RedirectedStream m_cout;
  7652. public:
  7653. RedirectedStdOut();
  7654. auto str() const -> std::string;
  7655. };
  7656. // StdErr has two constituent streams in C++, std::cerr and std::clog
  7657. // This means that we need to redirect 2 streams into 1 to keep proper
  7658. // order of writes
  7659. class RedirectedStdErr {
  7660. ReusableStringStream m_rss;
  7661. RedirectedStream m_cerr;
  7662. RedirectedStream m_clog;
  7663. public:
  7664. RedirectedStdErr();
  7665. auto str() const -> std::string;
  7666. };
  7667. #if defined(CATCH_CONFIG_NEW_CAPTURE)
  7668. // Windows's implementation of std::tmpfile is terrible (it tries
  7669. // to create a file inside system folder, thus requiring elevated
  7670. // privileges for the binary), so we have to use tmpnam(_s) and
  7671. // create the file ourselves there.
  7672. class TempFile {
  7673. public:
  7674. TempFile(TempFile const&) = delete;
  7675. TempFile& operator=(TempFile const&) = delete;
  7676. TempFile(TempFile&&) = delete;
  7677. TempFile& operator=(TempFile&&) = delete;
  7678. TempFile();
  7679. ~TempFile();
  7680. std::FILE* getFile();
  7681. std::string getContents();
  7682. private:
  7683. std::FILE* m_file = nullptr;
  7684. #if defined(_MSC_VER)
  7685. char m_buffer[L_tmpnam] = { 0 };
  7686. #endif
  7687. };
  7688. class OutputRedirect {
  7689. public:
  7690. OutputRedirect(OutputRedirect const&) = delete;
  7691. OutputRedirect& operator=(OutputRedirect const&) = delete;
  7692. OutputRedirect(OutputRedirect&&) = delete;
  7693. OutputRedirect& operator=(OutputRedirect&&) = delete;
  7694. OutputRedirect(std::string& stdout_dest, std::string& stderr_dest);
  7695. ~OutputRedirect();
  7696. private:
  7697. int m_originalStdout = -1;
  7698. int m_originalStderr = -1;
  7699. TempFile m_stdoutFile;
  7700. TempFile m_stderrFile;
  7701. std::string& m_stdoutDest;
  7702. std::string& m_stderrDest;
  7703. };
  7704. #endif
  7705. } // end namespace Catch
  7706. #endif // TWOBLUECUBES_CATCH_OUTPUT_REDIRECT_H
  7707. // end catch_output_redirect.h
  7708. #include <cstdio>
  7709. #include <cstring>
  7710. #include <fstream>
  7711. #include <sstream>
  7712. #include <stdexcept>
  7713. #if defined(CATCH_CONFIG_NEW_CAPTURE)
  7714. #if defined(_MSC_VER)
  7715. #include <io.h> //_dup and _dup2
  7716. #define dup _dup
  7717. #define dup2 _dup2
  7718. #define fileno _fileno
  7719. #else
  7720. #include <unistd.h> // dup and dup2
  7721. #endif
  7722. #endif
  7723. namespace Catch {
  7724. RedirectedStream::RedirectedStream( std::ostream& originalStream, std::ostream& redirectionStream )
  7725. : m_originalStream( originalStream ),
  7726. m_redirectionStream( redirectionStream ),
  7727. m_prevBuf( m_originalStream.rdbuf() )
  7728. {
  7729. m_originalStream.rdbuf( m_redirectionStream.rdbuf() );
  7730. }
  7731. RedirectedStream::~RedirectedStream() {
  7732. m_originalStream.rdbuf( m_prevBuf );
  7733. }
  7734. RedirectedStdOut::RedirectedStdOut() : m_cout( Catch::cout(), m_rss.get() ) {}
  7735. auto RedirectedStdOut::str() const -> std::string { return m_rss.str(); }
  7736. RedirectedStdErr::RedirectedStdErr()
  7737. : m_cerr( Catch::cerr(), m_rss.get() ),
  7738. m_clog( Catch::clog(), m_rss.get() )
  7739. {}
  7740. auto RedirectedStdErr::str() const -> std::string { return m_rss.str(); }
  7741. #if defined(CATCH_CONFIG_NEW_CAPTURE)
  7742. #if defined(_MSC_VER)
  7743. TempFile::TempFile() {
  7744. if (tmpnam_s(m_buffer)) {
  7745. CATCH_RUNTIME_ERROR("Could not get a temp filename");
  7746. }
  7747. if (fopen_s(&m_file, m_buffer, "w")) {
  7748. char buffer[100];
  7749. if (strerror_s(buffer, errno)) {
  7750. CATCH_RUNTIME_ERROR("Could not translate errno to a string");
  7751. }
  7752. CATCH_RUNTIME_ERROR("Coul dnot open the temp file: '" << m_buffer << "' because: " << buffer);
  7753. }
  7754. }
  7755. #else
  7756. TempFile::TempFile() {
  7757. m_file = std::tmpfile();
  7758. if (!m_file) {
  7759. CATCH_RUNTIME_ERROR("Could not create a temp file.");
  7760. }
  7761. }
  7762. #endif
  7763. TempFile::~TempFile() {
  7764. // TBD: What to do about errors here?
  7765. std::fclose(m_file);
  7766. // We manually create the file on Windows only, on Linux
  7767. // it will be autodeleted
  7768. #if defined(_MSC_VER)
  7769. std::remove(m_buffer);
  7770. #endif
  7771. }
  7772. FILE* TempFile::getFile() {
  7773. return m_file;
  7774. }
  7775. std::string TempFile::getContents() {
  7776. std::stringstream sstr;
  7777. char buffer[100] = {};
  7778. std::rewind(m_file);
  7779. while (std::fgets(buffer, sizeof(buffer), m_file)) {
  7780. sstr << buffer;
  7781. }
  7782. return sstr.str();
  7783. }
  7784. OutputRedirect::OutputRedirect(std::string& stdout_dest, std::string& stderr_dest) :
  7785. m_originalStdout(dup(1)),
  7786. m_originalStderr(dup(2)),
  7787. m_stdoutDest(stdout_dest),
  7788. m_stderrDest(stderr_dest) {
  7789. dup2(fileno(m_stdoutFile.getFile()), 1);
  7790. dup2(fileno(m_stderrFile.getFile()), 2);
  7791. }
  7792. OutputRedirect::~OutputRedirect() {
  7793. Catch::cout() << std::flush;
  7794. fflush(stdout);
  7795. // Since we support overriding these streams, we flush cerr
  7796. // even though std::cerr is unbuffered
  7797. Catch::cerr() << std::flush;
  7798. Catch::clog() << std::flush;
  7799. fflush(stderr);
  7800. dup2(m_originalStdout, 1);
  7801. dup2(m_originalStderr, 2);
  7802. m_stdoutDest += m_stdoutFile.getContents();
  7803. m_stderrDest += m_stderrFile.getContents();
  7804. }
  7805. #endif // CATCH_CONFIG_NEW_CAPTURE
  7806. } // namespace Catch
  7807. #if defined(CATCH_CONFIG_NEW_CAPTURE)
  7808. #if defined(_MSC_VER)
  7809. #undef dup
  7810. #undef dup2
  7811. #undef fileno
  7812. #endif
  7813. #endif
  7814. // end catch_output_redirect.cpp
  7815. // start catch_polyfills.cpp
  7816. #include <cmath>
  7817. namespace Catch {
  7818. #if !defined(CATCH_CONFIG_POLYFILL_ISNAN)
  7819. bool isnan(float f) {
  7820. return std::isnan(f);
  7821. }
  7822. bool isnan(double d) {
  7823. return std::isnan(d);
  7824. }
  7825. #else
  7826. // For now we only use this for embarcadero
  7827. bool isnan(float f) {
  7828. return std::_isnan(f);
  7829. }
  7830. bool isnan(double d) {
  7831. return std::_isnan(d);
  7832. }
  7833. #endif
  7834. } // end namespace Catch
  7835. // end catch_polyfills.cpp
  7836. // start catch_random_number_generator.cpp
  7837. namespace Catch {
  7838. std::mt19937& rng() {
  7839. static std::mt19937 s_rng;
  7840. return s_rng;
  7841. }
  7842. void seedRng( IConfig const& config ) {
  7843. if( config.rngSeed() != 0 ) {
  7844. std::srand( config.rngSeed() );
  7845. rng().seed( config.rngSeed() );
  7846. }
  7847. }
  7848. unsigned int rngSeed() {
  7849. return getCurrentContext().getConfig()->rngSeed();
  7850. }
  7851. }
  7852. // end catch_random_number_generator.cpp
  7853. // start catch_registry_hub.cpp
  7854. // start catch_test_case_registry_impl.h
  7855. #include <vector>
  7856. #include <set>
  7857. #include <algorithm>
  7858. #include <ios>
  7859. namespace Catch {
  7860. class TestCase;
  7861. struct IConfig;
  7862. std::vector<TestCase> sortTests( IConfig const& config, std::vector<TestCase> const& unsortedTestCases );
  7863. bool matchTest( TestCase const& testCase, TestSpec const& testSpec, IConfig const& config );
  7864. void enforceNoDuplicateTestCases( std::vector<TestCase> const& functions );
  7865. std::vector<TestCase> filterTests( std::vector<TestCase> const& testCases, TestSpec const& testSpec, IConfig const& config );
  7866. std::vector<TestCase> const& getAllTestCasesSorted( IConfig const& config );
  7867. class TestRegistry : public ITestCaseRegistry {
  7868. public:
  7869. virtual ~TestRegistry() = default;
  7870. virtual void registerTest( TestCase const& testCase );
  7871. std::vector<TestCase> const& getAllTests() const override;
  7872. std::vector<TestCase> const& getAllTestsSorted( IConfig const& config ) const override;
  7873. private:
  7874. std::vector<TestCase> m_functions;
  7875. mutable RunTests::InWhatOrder m_currentSortOrder = RunTests::InDeclarationOrder;
  7876. mutable std::vector<TestCase> m_sortedFunctions;
  7877. std::size_t m_unnamedCount = 0;
  7878. std::ios_base::Init m_ostreamInit; // Forces cout/ cerr to be initialised
  7879. };
  7880. ///////////////////////////////////////////////////////////////////////////
  7881. class TestInvokerAsFunction : public ITestInvoker {
  7882. void(*m_testAsFunction)();
  7883. public:
  7884. TestInvokerAsFunction( void(*testAsFunction)() ) noexcept;
  7885. void invoke() const override;
  7886. };
  7887. std::string extractClassName( StringRef const& classOrQualifiedMethodName );
  7888. ///////////////////////////////////////////////////////////////////////////
  7889. } // end namespace Catch
  7890. // end catch_test_case_registry_impl.h
  7891. // start catch_reporter_registry.h
  7892. #include <map>
  7893. namespace Catch {
  7894. class ReporterRegistry : public IReporterRegistry {
  7895. public:
  7896. ~ReporterRegistry() override;
  7897. IStreamingReporterPtr create( std::string const& name, IConfigPtr const& config ) const override;
  7898. void registerReporter( std::string const& name, IReporterFactoryPtr const& factory );
  7899. void registerListener( IReporterFactoryPtr const& factory );
  7900. FactoryMap const& getFactories() const override;
  7901. Listeners const& getListeners() const override;
  7902. private:
  7903. FactoryMap m_factories;
  7904. Listeners m_listeners;
  7905. };
  7906. }
  7907. // end catch_reporter_registry.h
  7908. // start catch_tag_alias_registry.h
  7909. // start catch_tag_alias.h
  7910. #include <string>
  7911. namespace Catch {
  7912. struct TagAlias {
  7913. TagAlias(std::string const& _tag, SourceLineInfo _lineInfo);
  7914. std::string tag;
  7915. SourceLineInfo lineInfo;
  7916. };
  7917. } // end namespace Catch
  7918. // end catch_tag_alias.h
  7919. #include <map>
  7920. namespace Catch {
  7921. class TagAliasRegistry : public ITagAliasRegistry {
  7922. public:
  7923. ~TagAliasRegistry() override;
  7924. TagAlias const* find( std::string const& alias ) const override;
  7925. std::string expandAliases( std::string const& unexpandedTestSpec ) const override;
  7926. void add( std::string const& alias, std::string const& tag, SourceLineInfo const& lineInfo );
  7927. private:
  7928. std::map<std::string, TagAlias> m_registry;
  7929. };
  7930. } // end namespace Catch
  7931. // end catch_tag_alias_registry.h
  7932. // start catch_startup_exception_registry.h
  7933. #include <vector>
  7934. #include <exception>
  7935. namespace Catch {
  7936. class StartupExceptionRegistry {
  7937. public:
  7938. void add(std::exception_ptr const& exception) noexcept;
  7939. std::vector<std::exception_ptr> const& getExceptions() const noexcept;
  7940. private:
  7941. std::vector<std::exception_ptr> m_exceptions;
  7942. };
  7943. } // end namespace Catch
  7944. // end catch_startup_exception_registry.h
  7945. // start catch_singletons.hpp
  7946. namespace Catch {
  7947. struct ISingleton {
  7948. virtual ~ISingleton();
  7949. };
  7950. void addSingleton( ISingleton* singleton );
  7951. void cleanupSingletons();
  7952. template<typename SingletonImplT, typename InterfaceT = SingletonImplT, typename MutableInterfaceT = InterfaceT>
  7953. class Singleton : SingletonImplT, public ISingleton {
  7954. static auto getInternal() -> Singleton* {
  7955. static Singleton* s_instance = nullptr;
  7956. if( !s_instance ) {
  7957. s_instance = new Singleton;
  7958. addSingleton( s_instance );
  7959. }
  7960. return s_instance;
  7961. }
  7962. public:
  7963. static auto get() -> InterfaceT const& {
  7964. return *getInternal();
  7965. }
  7966. static auto getMutable() -> MutableInterfaceT& {
  7967. return *getInternal();
  7968. }
  7969. };
  7970. } // namespace Catch
  7971. // end catch_singletons.hpp
  7972. namespace Catch {
  7973. namespace {
  7974. class RegistryHub : public IRegistryHub, public IMutableRegistryHub,
  7975. private NonCopyable {
  7976. public: // IRegistryHub
  7977. RegistryHub() = default;
  7978. IReporterRegistry const& getReporterRegistry() const override {
  7979. return m_reporterRegistry;
  7980. }
  7981. ITestCaseRegistry const& getTestCaseRegistry() const override {
  7982. return m_testCaseRegistry;
  7983. }
  7984. IExceptionTranslatorRegistry const& getExceptionTranslatorRegistry() const override {
  7985. return m_exceptionTranslatorRegistry;
  7986. }
  7987. ITagAliasRegistry const& getTagAliasRegistry() const override {
  7988. return m_tagAliasRegistry;
  7989. }
  7990. StartupExceptionRegistry const& getStartupExceptionRegistry() const override {
  7991. return m_exceptionRegistry;
  7992. }
  7993. public: // IMutableRegistryHub
  7994. void registerReporter( std::string const& name, IReporterFactoryPtr const& factory ) override {
  7995. m_reporterRegistry.registerReporter( name, factory );
  7996. }
  7997. void registerListener( IReporterFactoryPtr const& factory ) override {
  7998. m_reporterRegistry.registerListener( factory );
  7999. }
  8000. void registerTest( TestCase const& testInfo ) override {
  8001. m_testCaseRegistry.registerTest( testInfo );
  8002. }
  8003. void registerTranslator( const IExceptionTranslator* translator ) override {
  8004. m_exceptionTranslatorRegistry.registerTranslator( translator );
  8005. }
  8006. void registerTagAlias( std::string const& alias, std::string const& tag, SourceLineInfo const& lineInfo ) override {
  8007. m_tagAliasRegistry.add( alias, tag, lineInfo );
  8008. }
  8009. void registerStartupException() noexcept override {
  8010. m_exceptionRegistry.add(std::current_exception());
  8011. }
  8012. private:
  8013. TestRegistry m_testCaseRegistry;
  8014. ReporterRegistry m_reporterRegistry;
  8015. ExceptionTranslatorRegistry m_exceptionTranslatorRegistry;
  8016. TagAliasRegistry m_tagAliasRegistry;
  8017. StartupExceptionRegistry m_exceptionRegistry;
  8018. };
  8019. }
  8020. using RegistryHubSingleton = Singleton<RegistryHub, IRegistryHub, IMutableRegistryHub>;
  8021. IRegistryHub const& getRegistryHub() {
  8022. return RegistryHubSingleton::get();
  8023. }
  8024. IMutableRegistryHub& getMutableRegistryHub() {
  8025. return RegistryHubSingleton::getMutable();
  8026. }
  8027. void cleanUp() {
  8028. cleanupSingletons();
  8029. cleanUpContext();
  8030. }
  8031. std::string translateActiveException() {
  8032. return getRegistryHub().getExceptionTranslatorRegistry().translateActiveException();
  8033. }
  8034. } // end namespace Catch
  8035. // end catch_registry_hub.cpp
  8036. // start catch_reporter_registry.cpp
  8037. namespace Catch {
  8038. ReporterRegistry::~ReporterRegistry() = default;
  8039. IStreamingReporterPtr ReporterRegistry::create( std::string const& name, IConfigPtr const& config ) const {
  8040. auto it = m_factories.find( name );
  8041. if( it == m_factories.end() )
  8042. return nullptr;
  8043. return it->second->create( ReporterConfig( config ) );
  8044. }
  8045. void ReporterRegistry::registerReporter( std::string const& name, IReporterFactoryPtr const& factory ) {
  8046. m_factories.emplace(name, factory);
  8047. }
  8048. void ReporterRegistry::registerListener( IReporterFactoryPtr const& factory ) {
  8049. m_listeners.push_back( factory );
  8050. }
  8051. IReporterRegistry::FactoryMap const& ReporterRegistry::getFactories() const {
  8052. return m_factories;
  8053. }
  8054. IReporterRegistry::Listeners const& ReporterRegistry::getListeners() const {
  8055. return m_listeners;
  8056. }
  8057. }
  8058. // end catch_reporter_registry.cpp
  8059. // start catch_result_type.cpp
  8060. namespace Catch {
  8061. bool isOk( ResultWas::OfType resultType ) {
  8062. return ( resultType & ResultWas::FailureBit ) == 0;
  8063. }
  8064. bool isJustInfo( int flags ) {
  8065. return flags == ResultWas::Info;
  8066. }
  8067. ResultDisposition::Flags operator | ( ResultDisposition::Flags lhs, ResultDisposition::Flags rhs ) {
  8068. return static_cast<ResultDisposition::Flags>( static_cast<int>( lhs ) | static_cast<int>( rhs ) );
  8069. }
  8070. bool shouldContinueOnFailure( int flags ) { return ( flags & ResultDisposition::ContinueOnFailure ) != 0; }
  8071. bool shouldSuppressFailure( int flags ) { return ( flags & ResultDisposition::SuppressFail ) != 0; }
  8072. } // end namespace Catch
  8073. // end catch_result_type.cpp
  8074. // start catch_run_context.cpp
  8075. #include <cassert>
  8076. #include <algorithm>
  8077. #include <sstream>
  8078. namespace Catch {
  8079. namespace Generators {
  8080. struct GeneratorTracker : TestCaseTracking::TrackerBase, IGeneratorTracker {
  8081. GeneratorBasePtr m_generator;
  8082. GeneratorTracker( TestCaseTracking::NameAndLocation const& nameAndLocation, TrackerContext& ctx, ITracker* parent )
  8083. : TrackerBase( nameAndLocation, ctx, parent )
  8084. {}
  8085. ~GeneratorTracker();
  8086. static GeneratorTracker& acquire( TrackerContext& ctx, TestCaseTracking::NameAndLocation const& nameAndLocation ) {
  8087. std::shared_ptr<GeneratorTracker> tracker;
  8088. ITracker& currentTracker = ctx.currentTracker();
  8089. if( TestCaseTracking::ITrackerPtr childTracker = currentTracker.findChild( nameAndLocation ) ) {
  8090. assert( childTracker );
  8091. assert( childTracker->isGeneratorTracker() );
  8092. tracker = std::static_pointer_cast<GeneratorTracker>( childTracker );
  8093. }
  8094. else {
  8095. tracker = std::make_shared<GeneratorTracker>( nameAndLocation, ctx, &currentTracker );
  8096. currentTracker.addChild( tracker );
  8097. }
  8098. if( !ctx.completedCycle() && !tracker->isComplete() ) {
  8099. tracker->open();
  8100. }
  8101. return *tracker;
  8102. }
  8103. // TrackerBase interface
  8104. bool isGeneratorTracker() const override { return true; }
  8105. auto hasGenerator() const -> bool override {
  8106. return !!m_generator;
  8107. }
  8108. void close() override {
  8109. TrackerBase::close();
  8110. // Generator interface only finds out if it has another item on atual move
  8111. if (m_runState == CompletedSuccessfully && m_generator->next()) {
  8112. m_children.clear();
  8113. m_runState = Executing;
  8114. }
  8115. }
  8116. // IGeneratorTracker interface
  8117. auto getGenerator() const -> GeneratorBasePtr const& override {
  8118. return m_generator;
  8119. }
  8120. void setGenerator( GeneratorBasePtr&& generator ) override {
  8121. m_generator = std::move( generator );
  8122. }
  8123. };
  8124. GeneratorTracker::~GeneratorTracker() {}
  8125. }
  8126. RunContext::RunContext(IConfigPtr const& _config, IStreamingReporterPtr&& reporter)
  8127. : m_runInfo(_config->name()),
  8128. m_context(getCurrentMutableContext()),
  8129. m_config(_config),
  8130. m_reporter(std::move(reporter)),
  8131. m_lastAssertionInfo{ StringRef(), SourceLineInfo("",0), StringRef(), ResultDisposition::Normal },
  8132. m_includeSuccessfulResults( m_config->includeSuccessfulResults() || m_reporter->getPreferences().shouldReportAllAssertions )
  8133. {
  8134. m_context.setRunner(this);
  8135. m_context.setConfig(m_config);
  8136. m_context.setResultCapture(this);
  8137. m_reporter->testRunStarting(m_runInfo);
  8138. }
  8139. RunContext::~RunContext() {
  8140. m_reporter->testRunEnded(TestRunStats(m_runInfo, m_totals, aborting()));
  8141. }
  8142. void RunContext::testGroupStarting(std::string const& testSpec, std::size_t groupIndex, std::size_t groupsCount) {
  8143. m_reporter->testGroupStarting(GroupInfo(testSpec, groupIndex, groupsCount));
  8144. }
  8145. void RunContext::testGroupEnded(std::string const& testSpec, Totals const& totals, std::size_t groupIndex, std::size_t groupsCount) {
  8146. m_reporter->testGroupEnded(TestGroupStats(GroupInfo(testSpec, groupIndex, groupsCount), totals, aborting()));
  8147. }
  8148. Totals RunContext::runTest(TestCase const& testCase) {
  8149. Totals prevTotals = m_totals;
  8150. std::string redirectedCout;
  8151. std::string redirectedCerr;
  8152. auto const& testInfo = testCase.getTestCaseInfo();
  8153. m_reporter->testCaseStarting(testInfo);
  8154. m_activeTestCase = &testCase;
  8155. ITracker& rootTracker = m_trackerContext.startRun();
  8156. assert(rootTracker.isSectionTracker());
  8157. static_cast<SectionTracker&>(rootTracker).addInitialFilters(m_config->getSectionsToRun());
  8158. do {
  8159. m_trackerContext.startCycle();
  8160. m_testCaseTracker = &SectionTracker::acquire(m_trackerContext, TestCaseTracking::NameAndLocation(testInfo.name, testInfo.lineInfo));
  8161. runCurrentTest(redirectedCout, redirectedCerr);
  8162. } while (!m_testCaseTracker->isSuccessfullyCompleted() && !aborting());
  8163. Totals deltaTotals = m_totals.delta(prevTotals);
  8164. if (testInfo.expectedToFail() && deltaTotals.testCases.passed > 0) {
  8165. deltaTotals.assertions.failed++;
  8166. deltaTotals.testCases.passed--;
  8167. deltaTotals.testCases.failed++;
  8168. }
  8169. m_totals.testCases += deltaTotals.testCases;
  8170. m_reporter->testCaseEnded(TestCaseStats(testInfo,
  8171. deltaTotals,
  8172. redirectedCout,
  8173. redirectedCerr,
  8174. aborting()));
  8175. m_activeTestCase = nullptr;
  8176. m_testCaseTracker = nullptr;
  8177. return deltaTotals;
  8178. }
  8179. IConfigPtr RunContext::config() const {
  8180. return m_config;
  8181. }
  8182. IStreamingReporter& RunContext::reporter() const {
  8183. return *m_reporter;
  8184. }
  8185. void RunContext::assertionEnded(AssertionResult const & result) {
  8186. if (result.getResultType() == ResultWas::Ok) {
  8187. m_totals.assertions.passed++;
  8188. m_lastAssertionPassed = true;
  8189. } else if (!result.isOk()) {
  8190. m_lastAssertionPassed = false;
  8191. if( m_activeTestCase->getTestCaseInfo().okToFail() )
  8192. m_totals.assertions.failedButOk++;
  8193. else
  8194. m_totals.assertions.failed++;
  8195. }
  8196. else {
  8197. m_lastAssertionPassed = true;
  8198. }
  8199. // We have no use for the return value (whether messages should be cleared), because messages were made scoped
  8200. // and should be let to clear themselves out.
  8201. static_cast<void>(m_reporter->assertionEnded(AssertionStats(result, m_messages, m_totals)));
  8202. // Reset working state
  8203. resetAssertionInfo();
  8204. m_lastResult = result;
  8205. }
  8206. void RunContext::resetAssertionInfo() {
  8207. m_lastAssertionInfo.macroName = StringRef();
  8208. m_lastAssertionInfo.capturedExpression = "{Unknown expression after the reported line}"_sr;
  8209. }
  8210. bool RunContext::sectionStarted(SectionInfo const & sectionInfo, Counts & assertions) {
  8211. ITracker& sectionTracker = SectionTracker::acquire(m_trackerContext, TestCaseTracking::NameAndLocation(sectionInfo.name, sectionInfo.lineInfo));
  8212. if (!sectionTracker.isOpen())
  8213. return false;
  8214. m_activeSections.push_back(&sectionTracker);
  8215. m_lastAssertionInfo.lineInfo = sectionInfo.lineInfo;
  8216. m_reporter->sectionStarting(sectionInfo);
  8217. assertions = m_totals.assertions;
  8218. return true;
  8219. }
  8220. auto RunContext::acquireGeneratorTracker( SourceLineInfo const& lineInfo ) -> IGeneratorTracker& {
  8221. using namespace Generators;
  8222. GeneratorTracker& tracker = GeneratorTracker::acquire( m_trackerContext, TestCaseTracking::NameAndLocation( "generator", lineInfo ) );
  8223. assert( tracker.isOpen() );
  8224. m_lastAssertionInfo.lineInfo = lineInfo;
  8225. return tracker;
  8226. }
  8227. bool RunContext::testForMissingAssertions(Counts& assertions) {
  8228. if (assertions.total() != 0)
  8229. return false;
  8230. if (!m_config->warnAboutMissingAssertions())
  8231. return false;
  8232. if (m_trackerContext.currentTracker().hasChildren())
  8233. return false;
  8234. m_totals.assertions.failed++;
  8235. assertions.failed++;
  8236. return true;
  8237. }
  8238. void RunContext::sectionEnded(SectionEndInfo const & endInfo) {
  8239. Counts assertions = m_totals.assertions - endInfo.prevAssertions;
  8240. bool missingAssertions = testForMissingAssertions(assertions);
  8241. if (!m_activeSections.empty()) {
  8242. m_activeSections.back()->close();
  8243. m_activeSections.pop_back();
  8244. }
  8245. m_reporter->sectionEnded(SectionStats(endInfo.sectionInfo, assertions, endInfo.durationInSeconds, missingAssertions));
  8246. m_messages.clear();
  8247. }
  8248. void RunContext::sectionEndedEarly(SectionEndInfo const & endInfo) {
  8249. if (m_unfinishedSections.empty())
  8250. m_activeSections.back()->fail();
  8251. else
  8252. m_activeSections.back()->close();
  8253. m_activeSections.pop_back();
  8254. m_unfinishedSections.push_back(endInfo);
  8255. }
  8256. void RunContext::benchmarkStarting( BenchmarkInfo const& info ) {
  8257. m_reporter->benchmarkStarting( info );
  8258. }
  8259. void RunContext::benchmarkEnded( BenchmarkStats const& stats ) {
  8260. m_reporter->benchmarkEnded( stats );
  8261. }
  8262. void RunContext::pushScopedMessage(MessageInfo const & message) {
  8263. m_messages.push_back(message);
  8264. }
  8265. void RunContext::popScopedMessage(MessageInfo const & message) {
  8266. m_messages.erase(std::remove(m_messages.begin(), m_messages.end(), message), m_messages.end());
  8267. }
  8268. std::string RunContext::getCurrentTestName() const {
  8269. return m_activeTestCase
  8270. ? m_activeTestCase->getTestCaseInfo().name
  8271. : std::string();
  8272. }
  8273. const AssertionResult * RunContext::getLastResult() const {
  8274. return &(*m_lastResult);
  8275. }
  8276. void RunContext::exceptionEarlyReported() {
  8277. m_shouldReportUnexpected = false;
  8278. }
  8279. void RunContext::handleFatalErrorCondition( StringRef message ) {
  8280. // First notify reporter that bad things happened
  8281. m_reporter->fatalErrorEncountered(message);
  8282. // Don't rebuild the result -- the stringification itself can cause more fatal errors
  8283. // Instead, fake a result data.
  8284. AssertionResultData tempResult( ResultWas::FatalErrorCondition, { false } );
  8285. tempResult.message = message;
  8286. AssertionResult result(m_lastAssertionInfo, tempResult);
  8287. assertionEnded(result);
  8288. handleUnfinishedSections();
  8289. // Recreate section for test case (as we will lose the one that was in scope)
  8290. auto const& testCaseInfo = m_activeTestCase->getTestCaseInfo();
  8291. SectionInfo testCaseSection(testCaseInfo.lineInfo, testCaseInfo.name);
  8292. Counts assertions;
  8293. assertions.failed = 1;
  8294. SectionStats testCaseSectionStats(testCaseSection, assertions, 0, false);
  8295. m_reporter->sectionEnded(testCaseSectionStats);
  8296. auto const& testInfo = m_activeTestCase->getTestCaseInfo();
  8297. Totals deltaTotals;
  8298. deltaTotals.testCases.failed = 1;
  8299. deltaTotals.assertions.failed = 1;
  8300. m_reporter->testCaseEnded(TestCaseStats(testInfo,
  8301. deltaTotals,
  8302. std::string(),
  8303. std::string(),
  8304. false));
  8305. m_totals.testCases.failed++;
  8306. testGroupEnded(std::string(), m_totals, 1, 1);
  8307. m_reporter->testRunEnded(TestRunStats(m_runInfo, m_totals, false));
  8308. }
  8309. bool RunContext::lastAssertionPassed() {
  8310. return m_lastAssertionPassed;
  8311. }
  8312. void RunContext::assertionPassed() {
  8313. m_lastAssertionPassed = true;
  8314. ++m_totals.assertions.passed;
  8315. resetAssertionInfo();
  8316. }
  8317. bool RunContext::aborting() const {
  8318. return m_totals.assertions.failed >= static_cast<std::size_t>(m_config->abortAfter());
  8319. }
  8320. void RunContext::runCurrentTest(std::string & redirectedCout, std::string & redirectedCerr) {
  8321. auto const& testCaseInfo = m_activeTestCase->getTestCaseInfo();
  8322. SectionInfo testCaseSection(testCaseInfo.lineInfo, testCaseInfo.name);
  8323. m_reporter->sectionStarting(testCaseSection);
  8324. Counts prevAssertions = m_totals.assertions;
  8325. double duration = 0;
  8326. m_shouldReportUnexpected = true;
  8327. m_lastAssertionInfo = { "TEST_CASE"_sr, testCaseInfo.lineInfo, StringRef(), ResultDisposition::Normal };
  8328. seedRng(*m_config);
  8329. Timer timer;
  8330. CATCH_TRY {
  8331. if (m_reporter->getPreferences().shouldRedirectStdOut) {
  8332. #if !defined(CATCH_CONFIG_EXPERIMENTAL_REDIRECT)
  8333. RedirectedStdOut redirectedStdOut;
  8334. RedirectedStdErr redirectedStdErr;
  8335. timer.start();
  8336. invokeActiveTestCase();
  8337. redirectedCout += redirectedStdOut.str();
  8338. redirectedCerr += redirectedStdErr.str();
  8339. #else
  8340. OutputRedirect r(redirectedCout, redirectedCerr);
  8341. timer.start();
  8342. invokeActiveTestCase();
  8343. #endif
  8344. } else {
  8345. timer.start();
  8346. invokeActiveTestCase();
  8347. }
  8348. duration = timer.getElapsedSeconds();
  8349. } CATCH_CATCH_ANON (TestFailureException&) {
  8350. // This just means the test was aborted due to failure
  8351. } CATCH_CATCH_ALL {
  8352. // Under CATCH_CONFIG_FAST_COMPILE, unexpected exceptions under REQUIRE assertions
  8353. // are reported without translation at the point of origin.
  8354. if( m_shouldReportUnexpected ) {
  8355. AssertionReaction dummyReaction;
  8356. handleUnexpectedInflightException( m_lastAssertionInfo, translateActiveException(), dummyReaction );
  8357. }
  8358. }
  8359. Counts assertions = m_totals.assertions - prevAssertions;
  8360. bool missingAssertions = testForMissingAssertions(assertions);
  8361. m_testCaseTracker->close();
  8362. handleUnfinishedSections();
  8363. m_messages.clear();
  8364. SectionStats testCaseSectionStats(testCaseSection, assertions, duration, missingAssertions);
  8365. m_reporter->sectionEnded(testCaseSectionStats);
  8366. }
  8367. void RunContext::invokeActiveTestCase() {
  8368. FatalConditionHandler fatalConditionHandler; // Handle signals
  8369. m_activeTestCase->invoke();
  8370. fatalConditionHandler.reset();
  8371. }
  8372. void RunContext::handleUnfinishedSections() {
  8373. // If sections ended prematurely due to an exception we stored their
  8374. // infos here so we can tear them down outside the unwind process.
  8375. for (auto it = m_unfinishedSections.rbegin(),
  8376. itEnd = m_unfinishedSections.rend();
  8377. it != itEnd;
  8378. ++it)
  8379. sectionEnded(*it);
  8380. m_unfinishedSections.clear();
  8381. }
  8382. void RunContext::handleExpr(
  8383. AssertionInfo const& info,
  8384. ITransientExpression const& expr,
  8385. AssertionReaction& reaction
  8386. ) {
  8387. m_reporter->assertionStarting( info );
  8388. bool negated = isFalseTest( info.resultDisposition );
  8389. bool result = expr.getResult() != negated;
  8390. if( result ) {
  8391. if (!m_includeSuccessfulResults) {
  8392. assertionPassed();
  8393. }
  8394. else {
  8395. reportExpr(info, ResultWas::Ok, &expr, negated);
  8396. }
  8397. }
  8398. else {
  8399. reportExpr(info, ResultWas::ExpressionFailed, &expr, negated );
  8400. populateReaction( reaction );
  8401. }
  8402. }
  8403. void RunContext::reportExpr(
  8404. AssertionInfo const &info,
  8405. ResultWas::OfType resultType,
  8406. ITransientExpression const *expr,
  8407. bool negated ) {
  8408. m_lastAssertionInfo = info;
  8409. AssertionResultData data( resultType, LazyExpression( negated ) );
  8410. AssertionResult assertionResult{ info, data };
  8411. assertionResult.m_resultData.lazyExpression.m_transientExpression = expr;
  8412. assertionEnded( assertionResult );
  8413. }
  8414. void RunContext::handleMessage(
  8415. AssertionInfo const& info,
  8416. ResultWas::OfType resultType,
  8417. StringRef const& message,
  8418. AssertionReaction& reaction
  8419. ) {
  8420. m_reporter->assertionStarting( info );
  8421. m_lastAssertionInfo = info;
  8422. AssertionResultData data( resultType, LazyExpression( false ) );
  8423. data.message = message;
  8424. AssertionResult assertionResult{ m_lastAssertionInfo, data };
  8425. assertionEnded( assertionResult );
  8426. if( !assertionResult.isOk() )
  8427. populateReaction( reaction );
  8428. }
  8429. void RunContext::handleUnexpectedExceptionNotThrown(
  8430. AssertionInfo const& info,
  8431. AssertionReaction& reaction
  8432. ) {
  8433. handleNonExpr(info, Catch::ResultWas::DidntThrowException, reaction);
  8434. }
  8435. void RunContext::handleUnexpectedInflightException(
  8436. AssertionInfo const& info,
  8437. std::string const& message,
  8438. AssertionReaction& reaction
  8439. ) {
  8440. m_lastAssertionInfo = info;
  8441. AssertionResultData data( ResultWas::ThrewException, LazyExpression( false ) );
  8442. data.message = message;
  8443. AssertionResult assertionResult{ info, data };
  8444. assertionEnded( assertionResult );
  8445. populateReaction( reaction );
  8446. }
  8447. void RunContext::populateReaction( AssertionReaction& reaction ) {
  8448. reaction.shouldDebugBreak = m_config->shouldDebugBreak();
  8449. reaction.shouldThrow = aborting() || (m_lastAssertionInfo.resultDisposition & ResultDisposition::Normal);
  8450. }
  8451. void RunContext::handleIncomplete(
  8452. AssertionInfo const& info
  8453. ) {
  8454. m_lastAssertionInfo = info;
  8455. AssertionResultData data( ResultWas::ThrewException, LazyExpression( false ) );
  8456. data.message = "Exception translation was disabled by CATCH_CONFIG_FAST_COMPILE";
  8457. AssertionResult assertionResult{ info, data };
  8458. assertionEnded( assertionResult );
  8459. }
  8460. void RunContext::handleNonExpr(
  8461. AssertionInfo const &info,
  8462. ResultWas::OfType resultType,
  8463. AssertionReaction &reaction
  8464. ) {
  8465. m_lastAssertionInfo = info;
  8466. AssertionResultData data( resultType, LazyExpression( false ) );
  8467. AssertionResult assertionResult{ info, data };
  8468. assertionEnded( assertionResult );
  8469. if( !assertionResult.isOk() )
  8470. populateReaction( reaction );
  8471. }
  8472. IResultCapture& getResultCapture() {
  8473. if (auto* capture = getCurrentContext().getResultCapture())
  8474. return *capture;
  8475. else
  8476. CATCH_INTERNAL_ERROR("No result capture instance");
  8477. }
  8478. }
  8479. // end catch_run_context.cpp
  8480. // start catch_section.cpp
  8481. namespace Catch {
  8482. Section::Section( SectionInfo const& info )
  8483. : m_info( info ),
  8484. m_sectionIncluded( getResultCapture().sectionStarted( m_info, m_assertions ) )
  8485. {
  8486. m_timer.start();
  8487. }
  8488. Section::~Section() {
  8489. if( m_sectionIncluded ) {
  8490. SectionEndInfo endInfo{ m_info, m_assertions, m_timer.getElapsedSeconds() };
  8491. if( uncaught_exceptions() )
  8492. getResultCapture().sectionEndedEarly( endInfo );
  8493. else
  8494. getResultCapture().sectionEnded( endInfo );
  8495. }
  8496. }
  8497. // This indicates whether the section should be executed or not
  8498. Section::operator bool() const {
  8499. return m_sectionIncluded;
  8500. }
  8501. } // end namespace Catch
  8502. // end catch_section.cpp
  8503. // start catch_section_info.cpp
  8504. namespace Catch {
  8505. SectionInfo::SectionInfo
  8506. ( SourceLineInfo const& _lineInfo,
  8507. std::string const& _name )
  8508. : name( _name ),
  8509. lineInfo( _lineInfo )
  8510. {}
  8511. } // end namespace Catch
  8512. // end catch_section_info.cpp
  8513. // start catch_session.cpp
  8514. // start catch_session.h
  8515. #include <memory>
  8516. namespace Catch {
  8517. class Session : NonCopyable {
  8518. public:
  8519. Session();
  8520. ~Session() override;
  8521. void showHelp() const;
  8522. void libIdentify();
  8523. int applyCommandLine( int argc, char const * const * argv );
  8524. #if defined(CATCH_CONFIG_WCHAR) && defined(WIN32) && defined(UNICODE)
  8525. int applyCommandLine( int argc, wchar_t const * const * argv );
  8526. #endif
  8527. void useConfigData( ConfigData const& configData );
  8528. template<typename CharT>
  8529. int run(int argc, CharT const * const argv[]) {
  8530. if (m_startupExceptions)
  8531. return 1;
  8532. int returnCode = applyCommandLine(argc, argv);
  8533. if (returnCode == 0)
  8534. returnCode = run();
  8535. return returnCode;
  8536. }
  8537. int run();
  8538. clara::Parser const& cli() const;
  8539. void cli( clara::Parser const& newParser );
  8540. ConfigData& configData();
  8541. Config& config();
  8542. private:
  8543. int runInternal();
  8544. clara::Parser m_cli;
  8545. ConfigData m_configData;
  8546. std::shared_ptr<Config> m_config;
  8547. bool m_startupExceptions = false;
  8548. };
  8549. } // end namespace Catch
  8550. // end catch_session.h
  8551. // start catch_version.h
  8552. #include <iosfwd>
  8553. namespace Catch {
  8554. // Versioning information
  8555. struct Version {
  8556. Version( Version const& ) = delete;
  8557. Version& operator=( Version const& ) = delete;
  8558. Version( unsigned int _majorVersion,
  8559. unsigned int _minorVersion,
  8560. unsigned int _patchNumber,
  8561. char const * const _branchName,
  8562. unsigned int _buildNumber );
  8563. unsigned int const majorVersion;
  8564. unsigned int const minorVersion;
  8565. unsigned int const patchNumber;
  8566. // buildNumber is only used if branchName is not null
  8567. char const * const branchName;
  8568. unsigned int const buildNumber;
  8569. friend std::ostream& operator << ( std::ostream& os, Version const& version );
  8570. };
  8571. Version const& libraryVersion();
  8572. }
  8573. // end catch_version.h
  8574. #include <cstdlib>
  8575. #include <iomanip>
  8576. namespace Catch {
  8577. namespace {
  8578. const int MaxExitCode = 255;
  8579. IStreamingReporterPtr createReporter(std::string const& reporterName, IConfigPtr const& config) {
  8580. auto reporter = Catch::getRegistryHub().getReporterRegistry().create(reporterName, config);
  8581. CATCH_ENFORCE(reporter, "No reporter registered with name: '" << reporterName << "'");
  8582. return reporter;
  8583. }
  8584. IStreamingReporterPtr makeReporter(std::shared_ptr<Config> const& config) {
  8585. if (Catch::getRegistryHub().getReporterRegistry().getListeners().empty()) {
  8586. return createReporter(config->getReporterName(), config);
  8587. }
  8588. // On older platforms, returning std::unique_ptr<ListeningReporter>
  8589. // when the return type is std::unique_ptr<IStreamingReporter>
  8590. // doesn't compile without a std::move call. However, this causes
  8591. // a warning on newer platforms. Thus, we have to work around
  8592. // it a bit and downcast the pointer manually.
  8593. auto ret = std::unique_ptr<IStreamingReporter>(new ListeningReporter);
  8594. auto& multi = static_cast<ListeningReporter&>(*ret);
  8595. auto const& listeners = Catch::getRegistryHub().getReporterRegistry().getListeners();
  8596. for (auto const& listener : listeners) {
  8597. multi.addListener(listener->create(Catch::ReporterConfig(config)));
  8598. }
  8599. multi.addReporter(createReporter(config->getReporterName(), config));
  8600. return ret;
  8601. }
  8602. Catch::Totals runTests(std::shared_ptr<Config> const& config) {
  8603. auto reporter = makeReporter(config);
  8604. RunContext context(config, std::move(reporter));
  8605. Totals totals;
  8606. context.testGroupStarting(config->name(), 1, 1);
  8607. TestSpec testSpec = config->testSpec();
  8608. auto const& allTestCases = getAllTestCasesSorted(*config);
  8609. for (auto const& testCase : allTestCases) {
  8610. if (!context.aborting() && matchTest(testCase, testSpec, *config))
  8611. totals += context.runTest(testCase);
  8612. else
  8613. context.reporter().skipTest(testCase);
  8614. }
  8615. if (config->warnAboutNoTests() && totals.testCases.total() == 0) {
  8616. ReusableStringStream testConfig;
  8617. bool first = true;
  8618. for (const auto& input : config->getTestsOrTags()) {
  8619. if (!first) { testConfig << ' '; }
  8620. first = false;
  8621. testConfig << input;
  8622. }
  8623. context.reporter().noMatchingTestCases(testConfig.str());
  8624. totals.error = -1;
  8625. }
  8626. context.testGroupEnded(config->name(), totals, 1, 1);
  8627. return totals;
  8628. }
  8629. void applyFilenamesAsTags(Catch::IConfig const& config) {
  8630. auto& tests = const_cast<std::vector<TestCase>&>(getAllTestCasesSorted(config));
  8631. for (auto& testCase : tests) {
  8632. auto tags = testCase.tags;
  8633. std::string filename = testCase.lineInfo.file;
  8634. auto lastSlash = filename.find_last_of("\\/");
  8635. if (lastSlash != std::string::npos) {
  8636. filename.erase(0, lastSlash);
  8637. filename[0] = '#';
  8638. }
  8639. auto lastDot = filename.find_last_of('.');
  8640. if (lastDot != std::string::npos) {
  8641. filename.erase(lastDot);
  8642. }
  8643. tags.push_back(std::move(filename));
  8644. setTags(testCase, tags);
  8645. }
  8646. }
  8647. } // anon namespace
  8648. Session::Session() {
  8649. static bool alreadyInstantiated = false;
  8650. if( alreadyInstantiated ) {
  8651. CATCH_TRY { CATCH_INTERNAL_ERROR( "Only one instance of Catch::Session can ever be used" ); }
  8652. CATCH_CATCH_ALL { getMutableRegistryHub().registerStartupException(); }
  8653. }
  8654. // There cannot be exceptions at startup in no-exception mode.
  8655. #if !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
  8656. const auto& exceptions = getRegistryHub().getStartupExceptionRegistry().getExceptions();
  8657. if ( !exceptions.empty() ) {
  8658. m_startupExceptions = true;
  8659. Colour colourGuard( Colour::Red );
  8660. Catch::cerr() << "Errors occurred during startup!" << '\n';
  8661. // iterate over all exceptions and notify user
  8662. for ( const auto& ex_ptr : exceptions ) {
  8663. try {
  8664. std::rethrow_exception(ex_ptr);
  8665. } catch ( std::exception const& ex ) {
  8666. Catch::cerr() << Column( ex.what() ).indent(2) << '\n';
  8667. }
  8668. }
  8669. }
  8670. #endif
  8671. alreadyInstantiated = true;
  8672. m_cli = makeCommandLineParser( m_configData );
  8673. }
  8674. Session::~Session() {
  8675. Catch::cleanUp();
  8676. }
  8677. void Session::showHelp() const {
  8678. Catch::cout()
  8679. << "\nCatch v" << libraryVersion() << "\n"
  8680. << m_cli << std::endl
  8681. << "For more detailed usage please see the project docs\n" << std::endl;
  8682. }
  8683. void Session::libIdentify() {
  8684. Catch::cout()
  8685. << std::left << std::setw(16) << "description: " << "A Catch test executable\n"
  8686. << std::left << std::setw(16) << "category: " << "testframework\n"
  8687. << std::left << std::setw(16) << "framework: " << "Catch Test\n"
  8688. << std::left << std::setw(16) << "version: " << libraryVersion() << std::endl;
  8689. }
  8690. int Session::applyCommandLine( int argc, char const * const * argv ) {
  8691. if( m_startupExceptions )
  8692. return 1;
  8693. auto result = m_cli.parse( clara::Args( argc, argv ) );
  8694. if( !result ) {
  8695. Catch::cerr()
  8696. << Colour( Colour::Red )
  8697. << "\nError(s) in input:\n"
  8698. << Column( result.errorMessage() ).indent( 2 )
  8699. << "\n\n";
  8700. Catch::cerr() << "Run with -? for usage\n" << std::endl;
  8701. return MaxExitCode;
  8702. }
  8703. if( m_configData.showHelp )
  8704. showHelp();
  8705. if( m_configData.libIdentify )
  8706. libIdentify();
  8707. m_config.reset();
  8708. return 0;
  8709. }
  8710. #if defined(CATCH_CONFIG_WCHAR) && defined(WIN32) && defined(UNICODE)
  8711. int Session::applyCommandLine( int argc, wchar_t const * const * argv ) {
  8712. char **utf8Argv = new char *[ argc ];
  8713. for ( int i = 0; i < argc; ++i ) {
  8714. int bufSize = WideCharToMultiByte( CP_UTF8, 0, argv[i], -1, NULL, 0, NULL, NULL );
  8715. utf8Argv[ i ] = new char[ bufSize ];
  8716. WideCharToMultiByte( CP_UTF8, 0, argv[i], -1, utf8Argv[i], bufSize, NULL, NULL );
  8717. }
  8718. int returnCode = applyCommandLine( argc, utf8Argv );
  8719. for ( int i = 0; i < argc; ++i )
  8720. delete [] utf8Argv[ i ];
  8721. delete [] utf8Argv;
  8722. return returnCode;
  8723. }
  8724. #endif
  8725. void Session::useConfigData( ConfigData const& configData ) {
  8726. m_configData = configData;
  8727. m_config.reset();
  8728. }
  8729. int Session::run() {
  8730. if( ( m_configData.waitForKeypress & WaitForKeypress::BeforeStart ) != 0 ) {
  8731. Catch::cout() << "...waiting for enter/ return before starting" << std::endl;
  8732. static_cast<void>(std::getchar());
  8733. }
  8734. int exitCode = runInternal();
  8735. if( ( m_configData.waitForKeypress & WaitForKeypress::BeforeExit ) != 0 ) {
  8736. Catch::cout() << "...waiting for enter/ return before exiting, with code: " << exitCode << std::endl;
  8737. static_cast<void>(std::getchar());
  8738. }
  8739. return exitCode;
  8740. }
  8741. clara::Parser const& Session::cli() const {
  8742. return m_cli;
  8743. }
  8744. void Session::cli( clara::Parser const& newParser ) {
  8745. m_cli = newParser;
  8746. }
  8747. ConfigData& Session::configData() {
  8748. return m_configData;
  8749. }
  8750. Config& Session::config() {
  8751. if( !m_config )
  8752. m_config = std::make_shared<Config>( m_configData );
  8753. return *m_config;
  8754. }
  8755. int Session::runInternal() {
  8756. if( m_startupExceptions )
  8757. return 1;
  8758. if (m_configData.showHelp || m_configData.libIdentify) {
  8759. return 0;
  8760. }
  8761. CATCH_TRY {
  8762. config(); // Force config to be constructed
  8763. seedRng( *m_config );
  8764. if( m_configData.filenamesAsTags )
  8765. applyFilenamesAsTags( *m_config );
  8766. // Handle list request
  8767. if( Option<std::size_t> listed = list( config() ) )
  8768. return static_cast<int>( *listed );
  8769. auto totals = runTests( m_config );
  8770. // Note that on unices only the lower 8 bits are usually used, clamping
  8771. // the return value to 255 prevents false negative when some multiple
  8772. // of 256 tests has failed
  8773. return (std::min) (MaxExitCode, (std::max) (totals.error, static_cast<int>(totals.assertions.failed)));
  8774. }
  8775. #if !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
  8776. catch( std::exception& ex ) {
  8777. Catch::cerr() << ex.what() << std::endl;
  8778. return MaxExitCode;
  8779. }
  8780. #endif
  8781. }
  8782. } // end namespace Catch
  8783. // end catch_session.cpp
  8784. // start catch_singletons.cpp
  8785. #include <vector>
  8786. namespace Catch {
  8787. namespace {
  8788. static auto getSingletons() -> std::vector<ISingleton*>*& {
  8789. static std::vector<ISingleton*>* g_singletons = nullptr;
  8790. if( !g_singletons )
  8791. g_singletons = new std::vector<ISingleton*>();
  8792. return g_singletons;
  8793. }
  8794. }
  8795. ISingleton::~ISingleton() {}
  8796. void addSingleton(ISingleton* singleton ) {
  8797. getSingletons()->push_back( singleton );
  8798. }
  8799. void cleanupSingletons() {
  8800. auto& singletons = getSingletons();
  8801. for( auto singleton : *singletons )
  8802. delete singleton;
  8803. delete singletons;
  8804. singletons = nullptr;
  8805. }
  8806. } // namespace Catch
  8807. // end catch_singletons.cpp
  8808. // start catch_startup_exception_registry.cpp
  8809. namespace Catch {
  8810. void StartupExceptionRegistry::add( std::exception_ptr const& exception ) noexcept {
  8811. CATCH_TRY {
  8812. m_exceptions.push_back(exception);
  8813. } CATCH_CATCH_ALL {
  8814. // If we run out of memory during start-up there's really not a lot more we can do about it
  8815. std::terminate();
  8816. }
  8817. }
  8818. std::vector<std::exception_ptr> const& StartupExceptionRegistry::getExceptions() const noexcept {
  8819. return m_exceptions;
  8820. }
  8821. } // end namespace Catch
  8822. // end catch_startup_exception_registry.cpp
  8823. // start catch_stream.cpp
  8824. #include <cstdio>
  8825. #include <iostream>
  8826. #include <fstream>
  8827. #include <sstream>
  8828. #include <vector>
  8829. #include <memory>
  8830. namespace Catch {
  8831. Catch::IStream::~IStream() = default;
  8832. namespace detail { namespace {
  8833. template<typename WriterF, std::size_t bufferSize=256>
  8834. class StreamBufImpl : public std::streambuf {
  8835. char data[bufferSize];
  8836. WriterF m_writer;
  8837. public:
  8838. StreamBufImpl() {
  8839. setp( data, data + sizeof(data) );
  8840. }
  8841. ~StreamBufImpl() noexcept {
  8842. StreamBufImpl::sync();
  8843. }
  8844. private:
  8845. int overflow( int c ) override {
  8846. sync();
  8847. if( c != EOF ) {
  8848. if( pbase() == epptr() )
  8849. m_writer( std::string( 1, static_cast<char>( c ) ) );
  8850. else
  8851. sputc( static_cast<char>( c ) );
  8852. }
  8853. return 0;
  8854. }
  8855. int sync() override {
  8856. if( pbase() != pptr() ) {
  8857. m_writer( std::string( pbase(), static_cast<std::string::size_type>( pptr() - pbase() ) ) );
  8858. setp( pbase(), epptr() );
  8859. }
  8860. return 0;
  8861. }
  8862. };
  8863. ///////////////////////////////////////////////////////////////////////////
  8864. struct OutputDebugWriter {
  8865. void operator()( std::string const&str ) {
  8866. writeToDebugConsole( str );
  8867. }
  8868. };
  8869. ///////////////////////////////////////////////////////////////////////////
  8870. class FileStream : public IStream {
  8871. mutable std::ofstream m_ofs;
  8872. public:
  8873. FileStream( StringRef filename ) {
  8874. m_ofs.open( filename.c_str() );
  8875. CATCH_ENFORCE( !m_ofs.fail(), "Unable to open file: '" << filename << "'" );
  8876. }
  8877. ~FileStream() override = default;
  8878. public: // IStream
  8879. std::ostream& stream() const override {
  8880. return m_ofs;
  8881. }
  8882. };
  8883. ///////////////////////////////////////////////////////////////////////////
  8884. class CoutStream : public IStream {
  8885. mutable std::ostream m_os;
  8886. public:
  8887. // Store the streambuf from cout up-front because
  8888. // cout may get redirected when running tests
  8889. CoutStream() : m_os( Catch::cout().rdbuf() ) {}
  8890. ~CoutStream() override = default;
  8891. public: // IStream
  8892. std::ostream& stream() const override { return m_os; }
  8893. };
  8894. ///////////////////////////////////////////////////////////////////////////
  8895. class DebugOutStream : public IStream {
  8896. std::unique_ptr<StreamBufImpl<OutputDebugWriter>> m_streamBuf;
  8897. mutable std::ostream m_os;
  8898. public:
  8899. DebugOutStream()
  8900. : m_streamBuf( new StreamBufImpl<OutputDebugWriter>() ),
  8901. m_os( m_streamBuf.get() )
  8902. {}
  8903. ~DebugOutStream() override = default;
  8904. public: // IStream
  8905. std::ostream& stream() const override { return m_os; }
  8906. };
  8907. }} // namespace anon::detail
  8908. ///////////////////////////////////////////////////////////////////////////
  8909. auto makeStream( StringRef const &filename ) -> IStream const* {
  8910. if( filename.empty() )
  8911. return new detail::CoutStream();
  8912. else if( filename[0] == '%' ) {
  8913. if( filename == "%debug" )
  8914. return new detail::DebugOutStream();
  8915. else
  8916. CATCH_ERROR( "Unrecognised stream: '" << filename << "'" );
  8917. }
  8918. else
  8919. return new detail::FileStream( filename );
  8920. }
  8921. // This class encapsulates the idea of a pool of ostringstreams that can be reused.
  8922. struct StringStreams {
  8923. std::vector<std::unique_ptr<std::ostringstream>> m_streams;
  8924. std::vector<std::size_t> m_unused;
  8925. std::ostringstream m_referenceStream; // Used for copy state/ flags from
  8926. auto add() -> std::size_t {
  8927. if( m_unused.empty() ) {
  8928. m_streams.push_back( std::unique_ptr<std::ostringstream>( new std::ostringstream ) );
  8929. return m_streams.size()-1;
  8930. }
  8931. else {
  8932. auto index = m_unused.back();
  8933. m_unused.pop_back();
  8934. return index;
  8935. }
  8936. }
  8937. void release( std::size_t index ) {
  8938. m_streams[index]->copyfmt( m_referenceStream ); // Restore initial flags and other state
  8939. m_unused.push_back(index);
  8940. }
  8941. };
  8942. ReusableStringStream::ReusableStringStream()
  8943. : m_index( Singleton<StringStreams>::getMutable().add() ),
  8944. m_oss( Singleton<StringStreams>::getMutable().m_streams[m_index].get() )
  8945. {}
  8946. ReusableStringStream::~ReusableStringStream() {
  8947. static_cast<std::ostringstream*>( m_oss )->str("");
  8948. m_oss->clear();
  8949. Singleton<StringStreams>::getMutable().release( m_index );
  8950. }
  8951. auto ReusableStringStream::str() const -> std::string {
  8952. return static_cast<std::ostringstream*>( m_oss )->str();
  8953. }
  8954. ///////////////////////////////////////////////////////////////////////////
  8955. #ifndef CATCH_CONFIG_NOSTDOUT // If you #define this you must implement these functions
  8956. std::ostream& cout() { return std::cout; }
  8957. std::ostream& cerr() { return std::cerr; }
  8958. std::ostream& clog() { return std::clog; }
  8959. #endif
  8960. }
  8961. // end catch_stream.cpp
  8962. // start catch_string_manip.cpp
  8963. #include <algorithm>
  8964. #include <ostream>
  8965. #include <cstring>
  8966. #include <cctype>
  8967. namespace Catch {
  8968. namespace {
  8969. char toLowerCh(char c) {
  8970. return static_cast<char>( std::tolower( c ) );
  8971. }
  8972. }
  8973. bool startsWith( std::string const& s, std::string const& prefix ) {
  8974. return s.size() >= prefix.size() && std::equal(prefix.begin(), prefix.end(), s.begin());
  8975. }
  8976. bool startsWith( std::string const& s, char prefix ) {
  8977. return !s.empty() && s[0] == prefix;
  8978. }
  8979. bool endsWith( std::string const& s, std::string const& suffix ) {
  8980. return s.size() >= suffix.size() && std::equal(suffix.rbegin(), suffix.rend(), s.rbegin());
  8981. }
  8982. bool endsWith( std::string const& s, char suffix ) {
  8983. return !s.empty() && s[s.size()-1] == suffix;
  8984. }
  8985. bool contains( std::string const& s, std::string const& infix ) {
  8986. return s.find( infix ) != std::string::npos;
  8987. }
  8988. void toLowerInPlace( std::string& s ) {
  8989. std::transform( s.begin(), s.end(), s.begin(), toLowerCh );
  8990. }
  8991. std::string toLower( std::string const& s ) {
  8992. std::string lc = s;
  8993. toLowerInPlace( lc );
  8994. return lc;
  8995. }
  8996. std::string trim( std::string const& str ) {
  8997. static char const* whitespaceChars = "\n\r\t ";
  8998. std::string::size_type start = str.find_first_not_of( whitespaceChars );
  8999. std::string::size_type end = str.find_last_not_of( whitespaceChars );
  9000. return start != std::string::npos ? str.substr( start, 1+end-start ) : std::string();
  9001. }
  9002. bool replaceInPlace( std::string& str, std::string const& replaceThis, std::string const& withThis ) {
  9003. bool replaced = false;
  9004. std::size_t i = str.find( replaceThis );
  9005. while( i != std::string::npos ) {
  9006. replaced = true;
  9007. str = str.substr( 0, i ) + withThis + str.substr( i+replaceThis.size() );
  9008. if( i < str.size()-withThis.size() )
  9009. i = str.find( replaceThis, i+withThis.size() );
  9010. else
  9011. i = std::string::npos;
  9012. }
  9013. return replaced;
  9014. }
  9015. pluralise::pluralise( std::size_t count, std::string const& label )
  9016. : m_count( count ),
  9017. m_label( label )
  9018. {}
  9019. std::ostream& operator << ( std::ostream& os, pluralise const& pluraliser ) {
  9020. os << pluraliser.m_count << ' ' << pluraliser.m_label;
  9021. if( pluraliser.m_count != 1 )
  9022. os << 's';
  9023. return os;
  9024. }
  9025. }
  9026. // end catch_string_manip.cpp
  9027. // start catch_stringref.cpp
  9028. #if defined(__clang__)
  9029. # pragma clang diagnostic push
  9030. # pragma clang diagnostic ignored "-Wexit-time-destructors"
  9031. #endif
  9032. #include <ostream>
  9033. #include <cstring>
  9034. #include <cstdint>
  9035. namespace {
  9036. const uint32_t byte_2_lead = 0xC0;
  9037. const uint32_t byte_3_lead = 0xE0;
  9038. const uint32_t byte_4_lead = 0xF0;
  9039. }
  9040. namespace Catch {
  9041. StringRef::StringRef( char const* rawChars ) noexcept
  9042. : StringRef( rawChars, static_cast<StringRef::size_type>(std::strlen(rawChars) ) )
  9043. {}
  9044. StringRef::operator std::string() const {
  9045. return std::string( m_start, m_size );
  9046. }
  9047. void StringRef::swap( StringRef& other ) noexcept {
  9048. std::swap( m_start, other.m_start );
  9049. std::swap( m_size, other.m_size );
  9050. std::swap( m_data, other.m_data );
  9051. }
  9052. auto StringRef::c_str() const -> char const* {
  9053. if( isSubstring() )
  9054. const_cast<StringRef*>( this )->takeOwnership();
  9055. return m_start;
  9056. }
  9057. auto StringRef::currentData() const noexcept -> char const* {
  9058. return m_start;
  9059. }
  9060. auto StringRef::isOwned() const noexcept -> bool {
  9061. return m_data != nullptr;
  9062. }
  9063. auto StringRef::isSubstring() const noexcept -> bool {
  9064. return m_start[m_size] != '\0';
  9065. }
  9066. void StringRef::takeOwnership() {
  9067. if( !isOwned() ) {
  9068. m_data = new char[m_size+1];
  9069. memcpy( m_data, m_start, m_size );
  9070. m_data[m_size] = '\0';
  9071. m_start = m_data;
  9072. }
  9073. }
  9074. auto StringRef::substr( size_type start, size_type size ) const noexcept -> StringRef {
  9075. if( start < m_size )
  9076. return StringRef( m_start+start, size );
  9077. else
  9078. return StringRef();
  9079. }
  9080. auto StringRef::operator == ( StringRef const& other ) const noexcept -> bool {
  9081. return
  9082. size() == other.size() &&
  9083. (std::strncmp( m_start, other.m_start, size() ) == 0);
  9084. }
  9085. auto StringRef::operator != ( StringRef const& other ) const noexcept -> bool {
  9086. return !operator==( other );
  9087. }
  9088. auto StringRef::operator[](size_type index) const noexcept -> char {
  9089. return m_start[index];
  9090. }
  9091. auto StringRef::numberOfCharacters() const noexcept -> size_type {
  9092. size_type noChars = m_size;
  9093. // Make adjustments for uft encodings
  9094. for( size_type i=0; i < m_size; ++i ) {
  9095. char c = m_start[i];
  9096. if( ( c & byte_2_lead ) == byte_2_lead ) {
  9097. noChars--;
  9098. if (( c & byte_3_lead ) == byte_3_lead )
  9099. noChars--;
  9100. if( ( c & byte_4_lead ) == byte_4_lead )
  9101. noChars--;
  9102. }
  9103. }
  9104. return noChars;
  9105. }
  9106. auto operator + ( StringRef const& lhs, StringRef const& rhs ) -> std::string {
  9107. std::string str;
  9108. str.reserve( lhs.size() + rhs.size() );
  9109. str += lhs;
  9110. str += rhs;
  9111. return str;
  9112. }
  9113. auto operator + ( StringRef const& lhs, const char* rhs ) -> std::string {
  9114. return std::string( lhs ) + std::string( rhs );
  9115. }
  9116. auto operator + ( char const* lhs, StringRef const& rhs ) -> std::string {
  9117. return std::string( lhs ) + std::string( rhs );
  9118. }
  9119. auto operator << ( std::ostream& os, StringRef const& str ) -> std::ostream& {
  9120. return os.write(str.currentData(), str.size());
  9121. }
  9122. auto operator+=( std::string& lhs, StringRef const& rhs ) -> std::string& {
  9123. lhs.append(rhs.currentData(), rhs.size());
  9124. return lhs;
  9125. }
  9126. } // namespace Catch
  9127. #if defined(__clang__)
  9128. # pragma clang diagnostic pop
  9129. #endif
  9130. // end catch_stringref.cpp
  9131. // start catch_tag_alias.cpp
  9132. namespace Catch {
  9133. TagAlias::TagAlias(std::string const & _tag, SourceLineInfo _lineInfo): tag(_tag), lineInfo(_lineInfo) {}
  9134. }
  9135. // end catch_tag_alias.cpp
  9136. // start catch_tag_alias_autoregistrar.cpp
  9137. namespace Catch {
  9138. RegistrarForTagAliases::RegistrarForTagAliases(char const* alias, char const* tag, SourceLineInfo const& lineInfo) {
  9139. CATCH_TRY {
  9140. getMutableRegistryHub().registerTagAlias(alias, tag, lineInfo);
  9141. } CATCH_CATCH_ALL {
  9142. // Do not throw when constructing global objects, instead register the exception to be processed later
  9143. getMutableRegistryHub().registerStartupException();
  9144. }
  9145. }
  9146. }
  9147. // end catch_tag_alias_autoregistrar.cpp
  9148. // start catch_tag_alias_registry.cpp
  9149. #include <sstream>
  9150. namespace Catch {
  9151. TagAliasRegistry::~TagAliasRegistry() {}
  9152. TagAlias const* TagAliasRegistry::find( std::string const& alias ) const {
  9153. auto it = m_registry.find( alias );
  9154. if( it != m_registry.end() )
  9155. return &(it->second);
  9156. else
  9157. return nullptr;
  9158. }
  9159. std::string TagAliasRegistry::expandAliases( std::string const& unexpandedTestSpec ) const {
  9160. std::string expandedTestSpec = unexpandedTestSpec;
  9161. for( auto const& registryKvp : m_registry ) {
  9162. std::size_t pos = expandedTestSpec.find( registryKvp.first );
  9163. if( pos != std::string::npos ) {
  9164. expandedTestSpec = expandedTestSpec.substr( 0, pos ) +
  9165. registryKvp.second.tag +
  9166. expandedTestSpec.substr( pos + registryKvp.first.size() );
  9167. }
  9168. }
  9169. return expandedTestSpec;
  9170. }
  9171. void TagAliasRegistry::add( std::string const& alias, std::string const& tag, SourceLineInfo const& lineInfo ) {
  9172. CATCH_ENFORCE( startsWith(alias, "[@") && endsWith(alias, ']'),
  9173. "error: tag alias, '" << alias << "' is not of the form [@alias name].\n" << lineInfo );
  9174. CATCH_ENFORCE( m_registry.insert(std::make_pair(alias, TagAlias(tag, lineInfo))).second,
  9175. "error: tag alias, '" << alias << "' already registered.\n"
  9176. << "\tFirst seen at: " << find(alias)->lineInfo << "\n"
  9177. << "\tRedefined at: " << lineInfo );
  9178. }
  9179. ITagAliasRegistry::~ITagAliasRegistry() {}
  9180. ITagAliasRegistry const& ITagAliasRegistry::get() {
  9181. return getRegistryHub().getTagAliasRegistry();
  9182. }
  9183. } // end namespace Catch
  9184. // end catch_tag_alias_registry.cpp
  9185. // start catch_test_case_info.cpp
  9186. #include <cctype>
  9187. #include <exception>
  9188. #include <algorithm>
  9189. #include <sstream>
  9190. namespace Catch {
  9191. namespace {
  9192. TestCaseInfo::SpecialProperties parseSpecialTag( std::string const& tag ) {
  9193. if( startsWith( tag, '.' ) ||
  9194. tag == "!hide" )
  9195. return TestCaseInfo::IsHidden;
  9196. else if( tag == "!throws" )
  9197. return TestCaseInfo::Throws;
  9198. else if( tag == "!shouldfail" )
  9199. return TestCaseInfo::ShouldFail;
  9200. else if( tag == "!mayfail" )
  9201. return TestCaseInfo::MayFail;
  9202. else if( tag == "!nonportable" )
  9203. return TestCaseInfo::NonPortable;
  9204. else if( tag == "!benchmark" )
  9205. return static_cast<TestCaseInfo::SpecialProperties>( TestCaseInfo::Benchmark | TestCaseInfo::IsHidden );
  9206. else
  9207. return TestCaseInfo::None;
  9208. }
  9209. bool isReservedTag( std::string const& tag ) {
  9210. return parseSpecialTag( tag ) == TestCaseInfo::None && tag.size() > 0 && !std::isalnum( static_cast<unsigned char>(tag[0]) );
  9211. }
  9212. void enforceNotReservedTag( std::string const& tag, SourceLineInfo const& _lineInfo ) {
  9213. CATCH_ENFORCE( !isReservedTag(tag),
  9214. "Tag name: [" << tag << "] is not allowed.\n"
  9215. << "Tag names starting with non alpha-numeric characters are reserved\n"
  9216. << _lineInfo );
  9217. }
  9218. }
  9219. TestCase makeTestCase( ITestInvoker* _testCase,
  9220. std::string const& _className,
  9221. NameAndTags const& nameAndTags,
  9222. SourceLineInfo const& _lineInfo )
  9223. {
  9224. bool isHidden = false;
  9225. // Parse out tags
  9226. std::vector<std::string> tags;
  9227. std::string desc, tag;
  9228. bool inTag = false;
  9229. std::string _descOrTags = nameAndTags.tags;
  9230. for (char c : _descOrTags) {
  9231. if( !inTag ) {
  9232. if( c == '[' )
  9233. inTag = true;
  9234. else
  9235. desc += c;
  9236. }
  9237. else {
  9238. if( c == ']' ) {
  9239. TestCaseInfo::SpecialProperties prop = parseSpecialTag( tag );
  9240. if( ( prop & TestCaseInfo::IsHidden ) != 0 )
  9241. isHidden = true;
  9242. else if( prop == TestCaseInfo::None )
  9243. enforceNotReservedTag( tag, _lineInfo );
  9244. tags.push_back( tag );
  9245. tag.clear();
  9246. inTag = false;
  9247. }
  9248. else
  9249. tag += c;
  9250. }
  9251. }
  9252. if( isHidden ) {
  9253. tags.push_back( "." );
  9254. }
  9255. TestCaseInfo info( nameAndTags.name, _className, desc, tags, _lineInfo );
  9256. return TestCase( _testCase, std::move(info) );
  9257. }
  9258. void setTags( TestCaseInfo& testCaseInfo, std::vector<std::string> tags ) {
  9259. std::sort(begin(tags), end(tags));
  9260. tags.erase(std::unique(begin(tags), end(tags)), end(tags));
  9261. testCaseInfo.lcaseTags.clear();
  9262. for( auto const& tag : tags ) {
  9263. std::string lcaseTag = toLower( tag );
  9264. testCaseInfo.properties = static_cast<TestCaseInfo::SpecialProperties>( testCaseInfo.properties | parseSpecialTag( lcaseTag ) );
  9265. testCaseInfo.lcaseTags.push_back( lcaseTag );
  9266. }
  9267. testCaseInfo.tags = std::move(tags);
  9268. }
  9269. TestCaseInfo::TestCaseInfo( std::string const& _name,
  9270. std::string const& _className,
  9271. std::string const& _description,
  9272. std::vector<std::string> const& _tags,
  9273. SourceLineInfo const& _lineInfo )
  9274. : name( _name ),
  9275. className( _className ),
  9276. description( _description ),
  9277. lineInfo( _lineInfo ),
  9278. properties( None )
  9279. {
  9280. setTags( *this, _tags );
  9281. }
  9282. bool TestCaseInfo::isHidden() const {
  9283. return ( properties & IsHidden ) != 0;
  9284. }
  9285. bool TestCaseInfo::throws() const {
  9286. return ( properties & Throws ) != 0;
  9287. }
  9288. bool TestCaseInfo::okToFail() const {
  9289. return ( properties & (ShouldFail | MayFail ) ) != 0;
  9290. }
  9291. bool TestCaseInfo::expectedToFail() const {
  9292. return ( properties & (ShouldFail ) ) != 0;
  9293. }
  9294. std::string TestCaseInfo::tagsAsString() const {
  9295. std::string ret;
  9296. // '[' and ']' per tag
  9297. std::size_t full_size = 2 * tags.size();
  9298. for (const auto& tag : tags) {
  9299. full_size += tag.size();
  9300. }
  9301. ret.reserve(full_size);
  9302. for (const auto& tag : tags) {
  9303. ret.push_back('[');
  9304. ret.append(tag);
  9305. ret.push_back(']');
  9306. }
  9307. return ret;
  9308. }
  9309. TestCase::TestCase( ITestInvoker* testCase, TestCaseInfo&& info ) : TestCaseInfo( std::move(info) ), test( testCase ) {}
  9310. TestCase TestCase::withName( std::string const& _newName ) const {
  9311. TestCase other( *this );
  9312. other.name = _newName;
  9313. return other;
  9314. }
  9315. void TestCase::invoke() const {
  9316. test->invoke();
  9317. }
  9318. bool TestCase::operator == ( TestCase const& other ) const {
  9319. return test.get() == other.test.get() &&
  9320. name == other.name &&
  9321. className == other.className;
  9322. }
  9323. bool TestCase::operator < ( TestCase const& other ) const {
  9324. return name < other.name;
  9325. }
  9326. TestCaseInfo const& TestCase::getTestCaseInfo() const
  9327. {
  9328. return *this;
  9329. }
  9330. } // end namespace Catch
  9331. // end catch_test_case_info.cpp
  9332. // start catch_test_case_registry_impl.cpp
  9333. #include <sstream>
  9334. namespace Catch {
  9335. std::vector<TestCase> sortTests( IConfig const& config, std::vector<TestCase> const& unsortedTestCases ) {
  9336. std::vector<TestCase> sorted = unsortedTestCases;
  9337. switch( config.runOrder() ) {
  9338. case RunTests::InLexicographicalOrder:
  9339. std::sort( sorted.begin(), sorted.end() );
  9340. break;
  9341. case RunTests::InRandomOrder:
  9342. seedRng( config );
  9343. std::shuffle( sorted.begin(), sorted.end(), rng() );
  9344. break;
  9345. case RunTests::InDeclarationOrder:
  9346. // already in declaration order
  9347. break;
  9348. }
  9349. return sorted;
  9350. }
  9351. bool matchTest( TestCase const& testCase, TestSpec const& testSpec, IConfig const& config ) {
  9352. return testSpec.matches( testCase ) && ( config.allowThrows() || !testCase.throws() );
  9353. }
  9354. void enforceNoDuplicateTestCases( std::vector<TestCase> const& functions ) {
  9355. std::set<TestCase> seenFunctions;
  9356. for( auto const& function : functions ) {
  9357. auto prev = seenFunctions.insert( function );
  9358. CATCH_ENFORCE( prev.second,
  9359. "error: TEST_CASE( \"" << function.name << "\" ) already defined.\n"
  9360. << "\tFirst seen at " << prev.first->getTestCaseInfo().lineInfo << "\n"
  9361. << "\tRedefined at " << function.getTestCaseInfo().lineInfo );
  9362. }
  9363. }
  9364. std::vector<TestCase> filterTests( std::vector<TestCase> const& testCases, TestSpec const& testSpec, IConfig const& config ) {
  9365. std::vector<TestCase> filtered;
  9366. filtered.reserve( testCases.size() );
  9367. for( auto const& testCase : testCases )
  9368. if( matchTest( testCase, testSpec, config ) )
  9369. filtered.push_back( testCase );
  9370. return filtered;
  9371. }
  9372. std::vector<TestCase> const& getAllTestCasesSorted( IConfig const& config ) {
  9373. return getRegistryHub().getTestCaseRegistry().getAllTestsSorted( config );
  9374. }
  9375. void TestRegistry::registerTest( TestCase const& testCase ) {
  9376. std::string name = testCase.getTestCaseInfo().name;
  9377. if( name.empty() ) {
  9378. ReusableStringStream rss;
  9379. rss << "Anonymous test case " << ++m_unnamedCount;
  9380. return registerTest( testCase.withName( rss.str() ) );
  9381. }
  9382. m_functions.push_back( testCase );
  9383. }
  9384. std::vector<TestCase> const& TestRegistry::getAllTests() const {
  9385. return m_functions;
  9386. }
  9387. std::vector<TestCase> const& TestRegistry::getAllTestsSorted( IConfig const& config ) const {
  9388. if( m_sortedFunctions.empty() )
  9389. enforceNoDuplicateTestCases( m_functions );
  9390. if( m_currentSortOrder != config.runOrder() || m_sortedFunctions.empty() ) {
  9391. m_sortedFunctions = sortTests( config, m_functions );
  9392. m_currentSortOrder = config.runOrder();
  9393. }
  9394. return m_sortedFunctions;
  9395. }
  9396. ///////////////////////////////////////////////////////////////////////////
  9397. TestInvokerAsFunction::TestInvokerAsFunction( void(*testAsFunction)() ) noexcept : m_testAsFunction( testAsFunction ) {}
  9398. void TestInvokerAsFunction::invoke() const {
  9399. m_testAsFunction();
  9400. }
  9401. std::string extractClassName( StringRef const& classOrQualifiedMethodName ) {
  9402. std::string className = classOrQualifiedMethodName;
  9403. if( startsWith( className, '&' ) )
  9404. {
  9405. std::size_t lastColons = className.rfind( "::" );
  9406. std::size_t penultimateColons = className.rfind( "::", lastColons-1 );
  9407. if( penultimateColons == std::string::npos )
  9408. penultimateColons = 1;
  9409. className = className.substr( penultimateColons, lastColons-penultimateColons );
  9410. }
  9411. return className;
  9412. }
  9413. } // end namespace Catch
  9414. // end catch_test_case_registry_impl.cpp
  9415. // start catch_test_case_tracker.cpp
  9416. #include <algorithm>
  9417. #include <cassert>
  9418. #include <stdexcept>
  9419. #include <memory>
  9420. #include <sstream>
  9421. #if defined(__clang__)
  9422. # pragma clang diagnostic push
  9423. # pragma clang diagnostic ignored "-Wexit-time-destructors"
  9424. #endif
  9425. namespace Catch {
  9426. namespace TestCaseTracking {
  9427. NameAndLocation::NameAndLocation( std::string const& _name, SourceLineInfo const& _location )
  9428. : name( _name ),
  9429. location( _location )
  9430. {}
  9431. ITracker::~ITracker() = default;
  9432. TrackerContext& TrackerContext::instance() {
  9433. static TrackerContext s_instance;
  9434. return s_instance;
  9435. }
  9436. ITracker& TrackerContext::startRun() {
  9437. m_rootTracker = std::make_shared<SectionTracker>( NameAndLocation( "{root}", CATCH_INTERNAL_LINEINFO ), *this, nullptr );
  9438. m_currentTracker = nullptr;
  9439. m_runState = Executing;
  9440. return *m_rootTracker;
  9441. }
  9442. void TrackerContext::endRun() {
  9443. m_rootTracker.reset();
  9444. m_currentTracker = nullptr;
  9445. m_runState = NotStarted;
  9446. }
  9447. void TrackerContext::startCycle() {
  9448. m_currentTracker = m_rootTracker.get();
  9449. m_runState = Executing;
  9450. }
  9451. void TrackerContext::completeCycle() {
  9452. m_runState = CompletedCycle;
  9453. }
  9454. bool TrackerContext::completedCycle() const {
  9455. return m_runState == CompletedCycle;
  9456. }
  9457. ITracker& TrackerContext::currentTracker() {
  9458. return *m_currentTracker;
  9459. }
  9460. void TrackerContext::setCurrentTracker( ITracker* tracker ) {
  9461. m_currentTracker = tracker;
  9462. }
  9463. TrackerBase::TrackerBase( NameAndLocation const& nameAndLocation, TrackerContext& ctx, ITracker* parent )
  9464. : m_nameAndLocation( nameAndLocation ),
  9465. m_ctx( ctx ),
  9466. m_parent( parent )
  9467. {}
  9468. NameAndLocation const& TrackerBase::nameAndLocation() const {
  9469. return m_nameAndLocation;
  9470. }
  9471. bool TrackerBase::isComplete() const {
  9472. return m_runState == CompletedSuccessfully || m_runState == Failed;
  9473. }
  9474. bool TrackerBase::isSuccessfullyCompleted() const {
  9475. return m_runState == CompletedSuccessfully;
  9476. }
  9477. bool TrackerBase::isOpen() const {
  9478. return m_runState != NotStarted && !isComplete();
  9479. }
  9480. bool TrackerBase::hasChildren() const {
  9481. return !m_children.empty();
  9482. }
  9483. void TrackerBase::addChild( ITrackerPtr const& child ) {
  9484. m_children.push_back( child );
  9485. }
  9486. ITrackerPtr TrackerBase::findChild( NameAndLocation const& nameAndLocation ) {
  9487. auto it = std::find_if( m_children.begin(), m_children.end(),
  9488. [&nameAndLocation]( ITrackerPtr const& tracker ){
  9489. return
  9490. tracker->nameAndLocation().location == nameAndLocation.location &&
  9491. tracker->nameAndLocation().name == nameAndLocation.name;
  9492. } );
  9493. return( it != m_children.end() )
  9494. ? *it
  9495. : nullptr;
  9496. }
  9497. ITracker& TrackerBase::parent() {
  9498. assert( m_parent ); // Should always be non-null except for root
  9499. return *m_parent;
  9500. }
  9501. void TrackerBase::openChild() {
  9502. if( m_runState != ExecutingChildren ) {
  9503. m_runState = ExecutingChildren;
  9504. if( m_parent )
  9505. m_parent->openChild();
  9506. }
  9507. }
  9508. bool TrackerBase::isSectionTracker() const { return false; }
  9509. bool TrackerBase::isGeneratorTracker() const { return false; }
  9510. void TrackerBase::open() {
  9511. m_runState = Executing;
  9512. moveToThis();
  9513. if( m_parent )
  9514. m_parent->openChild();
  9515. }
  9516. void TrackerBase::close() {
  9517. // Close any still open children (e.g. generators)
  9518. while( &m_ctx.currentTracker() != this )
  9519. m_ctx.currentTracker().close();
  9520. switch( m_runState ) {
  9521. case NeedsAnotherRun:
  9522. break;
  9523. case Executing:
  9524. m_runState = CompletedSuccessfully;
  9525. break;
  9526. case ExecutingChildren:
  9527. if( m_children.empty() || m_children.back()->isComplete() )
  9528. m_runState = CompletedSuccessfully;
  9529. break;
  9530. case NotStarted:
  9531. case CompletedSuccessfully:
  9532. case Failed:
  9533. CATCH_INTERNAL_ERROR( "Illogical state: " << m_runState );
  9534. default:
  9535. CATCH_INTERNAL_ERROR( "Unknown state: " << m_runState );
  9536. }
  9537. moveToParent();
  9538. m_ctx.completeCycle();
  9539. }
  9540. void TrackerBase::fail() {
  9541. m_runState = Failed;
  9542. if( m_parent )
  9543. m_parent->markAsNeedingAnotherRun();
  9544. moveToParent();
  9545. m_ctx.completeCycle();
  9546. }
  9547. void TrackerBase::markAsNeedingAnotherRun() {
  9548. m_runState = NeedsAnotherRun;
  9549. }
  9550. void TrackerBase::moveToParent() {
  9551. assert( m_parent );
  9552. m_ctx.setCurrentTracker( m_parent );
  9553. }
  9554. void TrackerBase::moveToThis() {
  9555. m_ctx.setCurrentTracker( this );
  9556. }
  9557. SectionTracker::SectionTracker( NameAndLocation const& nameAndLocation, TrackerContext& ctx, ITracker* parent )
  9558. : TrackerBase( nameAndLocation, ctx, parent )
  9559. {
  9560. if( parent ) {
  9561. while( !parent->isSectionTracker() )
  9562. parent = &parent->parent();
  9563. SectionTracker& parentSection = static_cast<SectionTracker&>( *parent );
  9564. addNextFilters( parentSection.m_filters );
  9565. }
  9566. }
  9567. bool SectionTracker::isComplete() const {
  9568. bool complete = true;
  9569. if ((m_filters.empty() || m_filters[0] == "") ||
  9570. std::find(m_filters.begin(), m_filters.end(),
  9571. m_nameAndLocation.name) != m_filters.end())
  9572. complete = TrackerBase::isComplete();
  9573. return complete;
  9574. }
  9575. bool SectionTracker::isSectionTracker() const { return true; }
  9576. SectionTracker& SectionTracker::acquire( TrackerContext& ctx, NameAndLocation const& nameAndLocation ) {
  9577. std::shared_ptr<SectionTracker> section;
  9578. ITracker& currentTracker = ctx.currentTracker();
  9579. if( ITrackerPtr childTracker = currentTracker.findChild( nameAndLocation ) ) {
  9580. assert( childTracker );
  9581. assert( childTracker->isSectionTracker() );
  9582. section = std::static_pointer_cast<SectionTracker>( childTracker );
  9583. }
  9584. else {
  9585. section = std::make_shared<SectionTracker>( nameAndLocation, ctx, &currentTracker );
  9586. currentTracker.addChild( section );
  9587. }
  9588. if( !ctx.completedCycle() )
  9589. section->tryOpen();
  9590. return *section;
  9591. }
  9592. void SectionTracker::tryOpen() {
  9593. if( !isComplete() && (m_filters.empty() || m_filters[0].empty() || m_filters[0] == m_nameAndLocation.name ) )
  9594. open();
  9595. }
  9596. void SectionTracker::addInitialFilters( std::vector<std::string> const& filters ) {
  9597. if( !filters.empty() ) {
  9598. m_filters.push_back(""); // Root - should never be consulted
  9599. m_filters.push_back(""); // Test Case - not a section filter
  9600. m_filters.insert( m_filters.end(), filters.begin(), filters.end() );
  9601. }
  9602. }
  9603. void SectionTracker::addNextFilters( std::vector<std::string> const& filters ) {
  9604. if( filters.size() > 1 )
  9605. m_filters.insert( m_filters.end(), ++filters.begin(), filters.end() );
  9606. }
  9607. } // namespace TestCaseTracking
  9608. using TestCaseTracking::ITracker;
  9609. using TestCaseTracking::TrackerContext;
  9610. using TestCaseTracking::SectionTracker;
  9611. } // namespace Catch
  9612. #if defined(__clang__)
  9613. # pragma clang diagnostic pop
  9614. #endif
  9615. // end catch_test_case_tracker.cpp
  9616. // start catch_test_registry.cpp
  9617. namespace Catch {
  9618. auto makeTestInvoker( void(*testAsFunction)() ) noexcept -> ITestInvoker* {
  9619. return new(std::nothrow) TestInvokerAsFunction( testAsFunction );
  9620. }
  9621. NameAndTags::NameAndTags( StringRef const& name_ , StringRef const& tags_ ) noexcept : name( name_ ), tags( tags_ ) {}
  9622. AutoReg::AutoReg( ITestInvoker* invoker, SourceLineInfo const& lineInfo, StringRef const& classOrMethod, NameAndTags const& nameAndTags ) noexcept {
  9623. CATCH_TRY {
  9624. getMutableRegistryHub()
  9625. .registerTest(
  9626. makeTestCase(
  9627. invoker,
  9628. extractClassName( classOrMethod ),
  9629. nameAndTags,
  9630. lineInfo));
  9631. } CATCH_CATCH_ALL {
  9632. // Do not throw when constructing global objects, instead register the exception to be processed later
  9633. getMutableRegistryHub().registerStartupException();
  9634. }
  9635. }
  9636. AutoReg::~AutoReg() = default;
  9637. }
  9638. // end catch_test_registry.cpp
  9639. // start catch_test_spec.cpp
  9640. #include <algorithm>
  9641. #include <string>
  9642. #include <vector>
  9643. #include <memory>
  9644. namespace Catch {
  9645. TestSpec::Pattern::~Pattern() = default;
  9646. TestSpec::NamePattern::~NamePattern() = default;
  9647. TestSpec::TagPattern::~TagPattern() = default;
  9648. TestSpec::ExcludedPattern::~ExcludedPattern() = default;
  9649. TestSpec::NamePattern::NamePattern( std::string const& name )
  9650. : m_wildcardPattern( toLower( name ), CaseSensitive::No )
  9651. {}
  9652. bool TestSpec::NamePattern::matches( TestCaseInfo const& testCase ) const {
  9653. return m_wildcardPattern.matches( toLower( testCase.name ) );
  9654. }
  9655. TestSpec::TagPattern::TagPattern( std::string const& tag ) : m_tag( toLower( tag ) ) {}
  9656. bool TestSpec::TagPattern::matches( TestCaseInfo const& testCase ) const {
  9657. return std::find(begin(testCase.lcaseTags),
  9658. end(testCase.lcaseTags),
  9659. m_tag) != end(testCase.lcaseTags);
  9660. }
  9661. TestSpec::ExcludedPattern::ExcludedPattern( PatternPtr const& underlyingPattern ) : m_underlyingPattern( underlyingPattern ) {}
  9662. bool TestSpec::ExcludedPattern::matches( TestCaseInfo const& testCase ) const { return !m_underlyingPattern->matches( testCase ); }
  9663. bool TestSpec::Filter::matches( TestCaseInfo const& testCase ) const {
  9664. // All patterns in a filter must match for the filter to be a match
  9665. for( auto const& pattern : m_patterns ) {
  9666. if( !pattern->matches( testCase ) )
  9667. return false;
  9668. }
  9669. return true;
  9670. }
  9671. bool TestSpec::hasFilters() const {
  9672. return !m_filters.empty();
  9673. }
  9674. bool TestSpec::matches( TestCaseInfo const& testCase ) const {
  9675. // A TestSpec matches if any filter matches
  9676. for( auto const& filter : m_filters )
  9677. if( filter.matches( testCase ) )
  9678. return true;
  9679. return false;
  9680. }
  9681. }
  9682. // end catch_test_spec.cpp
  9683. // start catch_test_spec_parser.cpp
  9684. namespace Catch {
  9685. TestSpecParser::TestSpecParser( ITagAliasRegistry const& tagAliases ) : m_tagAliases( &tagAliases ) {}
  9686. TestSpecParser& TestSpecParser::parse( std::string const& arg ) {
  9687. m_mode = None;
  9688. m_exclusion = false;
  9689. m_start = std::string::npos;
  9690. m_arg = m_tagAliases->expandAliases( arg );
  9691. m_escapeChars.clear();
  9692. for( m_pos = 0; m_pos < m_arg.size(); ++m_pos )
  9693. visitChar( m_arg[m_pos] );
  9694. if( m_mode == Name )
  9695. addPattern<TestSpec::NamePattern>();
  9696. return *this;
  9697. }
  9698. TestSpec TestSpecParser::testSpec() {
  9699. addFilter();
  9700. return m_testSpec;
  9701. }
  9702. void TestSpecParser::visitChar( char c ) {
  9703. if( m_mode == None ) {
  9704. switch( c ) {
  9705. case ' ': return;
  9706. case '~': m_exclusion = true; return;
  9707. case '[': return startNewMode( Tag, ++m_pos );
  9708. case '"': return startNewMode( QuotedName, ++m_pos );
  9709. case '\\': return escape();
  9710. default: startNewMode( Name, m_pos ); break;
  9711. }
  9712. }
  9713. if( m_mode == Name ) {
  9714. if( c == ',' ) {
  9715. addPattern<TestSpec::NamePattern>();
  9716. addFilter();
  9717. }
  9718. else if( c == '[' ) {
  9719. if( subString() == "exclude:" )
  9720. m_exclusion = true;
  9721. else
  9722. addPattern<TestSpec::NamePattern>();
  9723. startNewMode( Tag, ++m_pos );
  9724. }
  9725. else if( c == '\\' )
  9726. escape();
  9727. }
  9728. else if( m_mode == EscapedName )
  9729. m_mode = Name;
  9730. else if( m_mode == QuotedName && c == '"' )
  9731. addPattern<TestSpec::NamePattern>();
  9732. else if( m_mode == Tag && c == ']' )
  9733. addPattern<TestSpec::TagPattern>();
  9734. }
  9735. void TestSpecParser::startNewMode( Mode mode, std::size_t start ) {
  9736. m_mode = mode;
  9737. m_start = start;
  9738. }
  9739. void TestSpecParser::escape() {
  9740. if( m_mode == None )
  9741. m_start = m_pos;
  9742. m_mode = EscapedName;
  9743. m_escapeChars.push_back( m_pos );
  9744. }
  9745. std::string TestSpecParser::subString() const { return m_arg.substr( m_start, m_pos - m_start ); }
  9746. void TestSpecParser::addFilter() {
  9747. if( !m_currentFilter.m_patterns.empty() ) {
  9748. m_testSpec.m_filters.push_back( m_currentFilter );
  9749. m_currentFilter = TestSpec::Filter();
  9750. }
  9751. }
  9752. TestSpec parseTestSpec( std::string const& arg ) {
  9753. return TestSpecParser( ITagAliasRegistry::get() ).parse( arg ).testSpec();
  9754. }
  9755. } // namespace Catch
  9756. // end catch_test_spec_parser.cpp
  9757. // start catch_timer.cpp
  9758. #include <chrono>
  9759. static const uint64_t nanosecondsInSecond = 1000000000;
  9760. namespace Catch {
  9761. auto getCurrentNanosecondsSinceEpoch() -> uint64_t {
  9762. return std::chrono::duration_cast<std::chrono::nanoseconds>( std::chrono::high_resolution_clock::now().time_since_epoch() ).count();
  9763. }
  9764. namespace {
  9765. auto estimateClockResolution() -> uint64_t {
  9766. uint64_t sum = 0;
  9767. static const uint64_t iterations = 1000000;
  9768. auto startTime = getCurrentNanosecondsSinceEpoch();
  9769. for( std::size_t i = 0; i < iterations; ++i ) {
  9770. uint64_t ticks;
  9771. uint64_t baseTicks = getCurrentNanosecondsSinceEpoch();
  9772. do {
  9773. ticks = getCurrentNanosecondsSinceEpoch();
  9774. } while( ticks == baseTicks );
  9775. auto delta = ticks - baseTicks;
  9776. sum += delta;
  9777. // If we have been calibrating for over 3 seconds -- the clock
  9778. // is terrible and we should move on.
  9779. // TBD: How to signal that the measured resolution is probably wrong?
  9780. if (ticks > startTime + 3 * nanosecondsInSecond) {
  9781. return sum / ( i + 1u );
  9782. }
  9783. }
  9784. // We're just taking the mean, here. To do better we could take the std. dev and exclude outliers
  9785. // - and potentially do more iterations if there's a high variance.
  9786. return sum/iterations;
  9787. }
  9788. }
  9789. auto getEstimatedClockResolution() -> uint64_t {
  9790. static auto s_resolution = estimateClockResolution();
  9791. return s_resolution;
  9792. }
  9793. void Timer::start() {
  9794. m_nanoseconds = getCurrentNanosecondsSinceEpoch();
  9795. }
  9796. auto Timer::getElapsedNanoseconds() const -> uint64_t {
  9797. return getCurrentNanosecondsSinceEpoch() - m_nanoseconds;
  9798. }
  9799. auto Timer::getElapsedMicroseconds() const -> uint64_t {
  9800. return getElapsedNanoseconds()/1000;
  9801. }
  9802. auto Timer::getElapsedMilliseconds() const -> unsigned int {
  9803. return static_cast<unsigned int>(getElapsedMicroseconds()/1000);
  9804. }
  9805. auto Timer::getElapsedSeconds() const -> double {
  9806. return getElapsedMicroseconds()/1000000.0;
  9807. }
  9808. } // namespace Catch
  9809. // end catch_timer.cpp
  9810. // start catch_tostring.cpp
  9811. #if defined(__clang__)
  9812. # pragma clang diagnostic push
  9813. # pragma clang diagnostic ignored "-Wexit-time-destructors"
  9814. # pragma clang diagnostic ignored "-Wglobal-constructors"
  9815. #endif
  9816. // Enable specific decls locally
  9817. #if !defined(CATCH_CONFIG_ENABLE_CHRONO_STRINGMAKER)
  9818. #define CATCH_CONFIG_ENABLE_CHRONO_STRINGMAKER
  9819. #endif
  9820. #include <cmath>
  9821. #include <iomanip>
  9822. namespace Catch {
  9823. namespace Detail {
  9824. const std::string unprintableString = "{?}";
  9825. namespace {
  9826. const int hexThreshold = 255;
  9827. struct Endianness {
  9828. enum Arch { Big, Little };
  9829. static Arch which() {
  9830. union _{
  9831. int asInt;
  9832. char asChar[sizeof (int)];
  9833. } u;
  9834. u.asInt = 1;
  9835. return ( u.asChar[sizeof(int)-1] == 1 ) ? Big : Little;
  9836. }
  9837. };
  9838. }
  9839. std::string rawMemoryToString( const void *object, std::size_t size ) {
  9840. // Reverse order for little endian architectures
  9841. int i = 0, end = static_cast<int>( size ), inc = 1;
  9842. if( Endianness::which() == Endianness::Little ) {
  9843. i = end-1;
  9844. end = inc = -1;
  9845. }
  9846. unsigned char const *bytes = static_cast<unsigned char const *>(object);
  9847. ReusableStringStream rss;
  9848. rss << "0x" << std::setfill('0') << std::hex;
  9849. for( ; i != end; i += inc )
  9850. rss << std::setw(2) << static_cast<unsigned>(bytes[i]);
  9851. return rss.str();
  9852. }
  9853. }
  9854. template<typename T>
  9855. std::string fpToString( T value, int precision ) {
  9856. if (Catch::isnan(value)) {
  9857. return "nan";
  9858. }
  9859. ReusableStringStream rss;
  9860. rss << std::setprecision( precision )
  9861. << std::fixed
  9862. << value;
  9863. std::string d = rss.str();
  9864. std::size_t i = d.find_last_not_of( '0' );
  9865. if( i != std::string::npos && i != d.size()-1 ) {
  9866. if( d[i] == '.' )
  9867. i++;
  9868. d = d.substr( 0, i+1 );
  9869. }
  9870. return d;
  9871. }
  9872. //// ======================================================= ////
  9873. //
  9874. // Out-of-line defs for full specialization of StringMaker
  9875. //
  9876. //// ======================================================= ////
  9877. std::string StringMaker<std::string>::convert(const std::string& str) {
  9878. if (!getCurrentContext().getConfig()->showInvisibles()) {
  9879. return '"' + str + '"';
  9880. }
  9881. std::string s("\"");
  9882. for (char c : str) {
  9883. switch (c) {
  9884. case '\n':
  9885. s.append("\\n");
  9886. break;
  9887. case '\t':
  9888. s.append("\\t");
  9889. break;
  9890. default:
  9891. s.push_back(c);
  9892. break;
  9893. }
  9894. }
  9895. s.append("\"");
  9896. return s;
  9897. }
  9898. #ifdef CATCH_CONFIG_CPP17_STRING_VIEW
  9899. std::string StringMaker<std::string_view>::convert(std::string_view str) {
  9900. return ::Catch::Detail::stringify(std::string{ str });
  9901. }
  9902. #endif
  9903. std::string StringMaker<char const*>::convert(char const* str) {
  9904. if (str) {
  9905. return ::Catch::Detail::stringify(std::string{ str });
  9906. } else {
  9907. return{ "{null string}" };
  9908. }
  9909. }
  9910. std::string StringMaker<char*>::convert(char* str) {
  9911. if (str) {
  9912. return ::Catch::Detail::stringify(std::string{ str });
  9913. } else {
  9914. return{ "{null string}" };
  9915. }
  9916. }
  9917. #ifdef CATCH_CONFIG_WCHAR
  9918. std::string StringMaker<std::wstring>::convert(const std::wstring& wstr) {
  9919. std::string s;
  9920. s.reserve(wstr.size());
  9921. for (auto c : wstr) {
  9922. s += (c <= 0xff) ? static_cast<char>(c) : '?';
  9923. }
  9924. return ::Catch::Detail::stringify(s);
  9925. }
  9926. # ifdef CATCH_CONFIG_CPP17_STRING_VIEW
  9927. std::string StringMaker<std::wstring_view>::convert(std::wstring_view str) {
  9928. return StringMaker<std::wstring>::convert(std::wstring(str));
  9929. }
  9930. # endif
  9931. std::string StringMaker<wchar_t const*>::convert(wchar_t const * str) {
  9932. if (str) {
  9933. return ::Catch::Detail::stringify(std::wstring{ str });
  9934. } else {
  9935. return{ "{null string}" };
  9936. }
  9937. }
  9938. std::string StringMaker<wchar_t *>::convert(wchar_t * str) {
  9939. if (str) {
  9940. return ::Catch::Detail::stringify(std::wstring{ str });
  9941. } else {
  9942. return{ "{null string}" };
  9943. }
  9944. }
  9945. #endif
  9946. std::string StringMaker<int>::convert(int value) {
  9947. return ::Catch::Detail::stringify(static_cast<long long>(value));
  9948. }
  9949. std::string StringMaker<long>::convert(long value) {
  9950. return ::Catch::Detail::stringify(static_cast<long long>(value));
  9951. }
  9952. std::string StringMaker<long long>::convert(long long value) {
  9953. ReusableStringStream rss;
  9954. rss << value;
  9955. if (value > Detail::hexThreshold) {
  9956. rss << " (0x" << std::hex << value << ')';
  9957. }
  9958. return rss.str();
  9959. }
  9960. std::string StringMaker<unsigned int>::convert(unsigned int value) {
  9961. return ::Catch::Detail::stringify(static_cast<unsigned long long>(value));
  9962. }
  9963. std::string StringMaker<unsigned long>::convert(unsigned long value) {
  9964. return ::Catch::Detail::stringify(static_cast<unsigned long long>(value));
  9965. }
  9966. std::string StringMaker<unsigned long long>::convert(unsigned long long value) {
  9967. ReusableStringStream rss;
  9968. rss << value;
  9969. if (value > Detail::hexThreshold) {
  9970. rss << " (0x" << std::hex << value << ')';
  9971. }
  9972. return rss.str();
  9973. }
  9974. std::string StringMaker<bool>::convert(bool b) {
  9975. return b ? "true" : "false";
  9976. }
  9977. std::string StringMaker<signed char>::convert(signed char value) {
  9978. if (value == '\r') {
  9979. return "'\\r'";
  9980. } else if (value == '\f') {
  9981. return "'\\f'";
  9982. } else if (value == '\n') {
  9983. return "'\\n'";
  9984. } else if (value == '\t') {
  9985. return "'\\t'";
  9986. } else if ('\0' <= value && value < ' ') {
  9987. return ::Catch::Detail::stringify(static_cast<unsigned int>(value));
  9988. } else {
  9989. char chstr[] = "' '";
  9990. chstr[1] = value;
  9991. return chstr;
  9992. }
  9993. }
  9994. std::string StringMaker<char>::convert(char c) {
  9995. return ::Catch::Detail::stringify(static_cast<signed char>(c));
  9996. }
  9997. std::string StringMaker<unsigned char>::convert(unsigned char c) {
  9998. return ::Catch::Detail::stringify(static_cast<char>(c));
  9999. }
  10000. std::string StringMaker<std::nullptr_t>::convert(std::nullptr_t) {
  10001. return "nullptr";
  10002. }
  10003. std::string StringMaker<float>::convert(float value) {
  10004. return fpToString(value, 5) + 'f';
  10005. }
  10006. std::string StringMaker<double>::convert(double value) {
  10007. return fpToString(value, 10);
  10008. }
  10009. std::string ratio_string<std::atto>::symbol() { return "a"; }
  10010. std::string ratio_string<std::femto>::symbol() { return "f"; }
  10011. std::string ratio_string<std::pico>::symbol() { return "p"; }
  10012. std::string ratio_string<std::nano>::symbol() { return "n"; }
  10013. std::string ratio_string<std::micro>::symbol() { return "u"; }
  10014. std::string ratio_string<std::milli>::symbol() { return "m"; }
  10015. } // end namespace Catch
  10016. #if defined(__clang__)
  10017. # pragma clang diagnostic pop
  10018. #endif
  10019. // end catch_tostring.cpp
  10020. // start catch_totals.cpp
  10021. namespace Catch {
  10022. Counts Counts::operator - ( Counts const& other ) const {
  10023. Counts diff;
  10024. diff.passed = passed - other.passed;
  10025. diff.failed = failed - other.failed;
  10026. diff.failedButOk = failedButOk - other.failedButOk;
  10027. return diff;
  10028. }
  10029. Counts& Counts::operator += ( Counts const& other ) {
  10030. passed += other.passed;
  10031. failed += other.failed;
  10032. failedButOk += other.failedButOk;
  10033. return *this;
  10034. }
  10035. std::size_t Counts::total() const {
  10036. return passed + failed + failedButOk;
  10037. }
  10038. bool Counts::allPassed() const {
  10039. return failed == 0 && failedButOk == 0;
  10040. }
  10041. bool Counts::allOk() const {
  10042. return failed == 0;
  10043. }
  10044. Totals Totals::operator - ( Totals const& other ) const {
  10045. Totals diff;
  10046. diff.assertions = assertions - other.assertions;
  10047. diff.testCases = testCases - other.testCases;
  10048. return diff;
  10049. }
  10050. Totals& Totals::operator += ( Totals const& other ) {
  10051. assertions += other.assertions;
  10052. testCases += other.testCases;
  10053. return *this;
  10054. }
  10055. Totals Totals::delta( Totals const& prevTotals ) const {
  10056. Totals diff = *this - prevTotals;
  10057. if( diff.assertions.failed > 0 )
  10058. ++diff.testCases.failed;
  10059. else if( diff.assertions.failedButOk > 0 )
  10060. ++diff.testCases.failedButOk;
  10061. else
  10062. ++diff.testCases.passed;
  10063. return diff;
  10064. }
  10065. }
  10066. // end catch_totals.cpp
  10067. // start catch_uncaught_exceptions.cpp
  10068. #include <exception>
  10069. namespace Catch {
  10070. bool uncaught_exceptions() {
  10071. #if defined(CATCH_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS)
  10072. return std::uncaught_exceptions() > 0;
  10073. #else
  10074. return std::uncaught_exception();
  10075. #endif
  10076. }
  10077. } // end namespace Catch
  10078. // end catch_uncaught_exceptions.cpp
  10079. // start catch_version.cpp
  10080. #include <ostream>
  10081. namespace Catch {
  10082. Version::Version
  10083. ( unsigned int _majorVersion,
  10084. unsigned int _minorVersion,
  10085. unsigned int _patchNumber,
  10086. char const * const _branchName,
  10087. unsigned int _buildNumber )
  10088. : majorVersion( _majorVersion ),
  10089. minorVersion( _minorVersion ),
  10090. patchNumber( _patchNumber ),
  10091. branchName( _branchName ),
  10092. buildNumber( _buildNumber )
  10093. {}
  10094. std::ostream& operator << ( std::ostream& os, Version const& version ) {
  10095. os << version.majorVersion << '.'
  10096. << version.minorVersion << '.'
  10097. << version.patchNumber;
  10098. // branchName is never null -> 0th char is \0 if it is empty
  10099. if (version.branchName[0]) {
  10100. os << '-' << version.branchName
  10101. << '.' << version.buildNumber;
  10102. }
  10103. return os;
  10104. }
  10105. Version const& libraryVersion() {
  10106. static Version version( 2, 6, 0, "", 0 );
  10107. return version;
  10108. }
  10109. }
  10110. // end catch_version.cpp
  10111. // start catch_wildcard_pattern.cpp
  10112. #include <sstream>
  10113. namespace Catch {
  10114. WildcardPattern::WildcardPattern( std::string const& pattern,
  10115. CaseSensitive::Choice caseSensitivity )
  10116. : m_caseSensitivity( caseSensitivity ),
  10117. m_pattern( adjustCase( pattern ) )
  10118. {
  10119. if( startsWith( m_pattern, '*' ) ) {
  10120. m_pattern = m_pattern.substr( 1 );
  10121. m_wildcard = WildcardAtStart;
  10122. }
  10123. if( endsWith( m_pattern, '*' ) ) {
  10124. m_pattern = m_pattern.substr( 0, m_pattern.size()-1 );
  10125. m_wildcard = static_cast<WildcardPosition>( m_wildcard | WildcardAtEnd );
  10126. }
  10127. }
  10128. bool WildcardPattern::matches( std::string const& str ) const {
  10129. switch( m_wildcard ) {
  10130. case NoWildcard:
  10131. return m_pattern == adjustCase( str );
  10132. case WildcardAtStart:
  10133. return endsWith( adjustCase( str ), m_pattern );
  10134. case WildcardAtEnd:
  10135. return startsWith( adjustCase( str ), m_pattern );
  10136. case WildcardAtBothEnds:
  10137. return contains( adjustCase( str ), m_pattern );
  10138. default:
  10139. CATCH_INTERNAL_ERROR( "Unknown enum" );
  10140. }
  10141. }
  10142. std::string WildcardPattern::adjustCase( std::string const& str ) const {
  10143. return m_caseSensitivity == CaseSensitive::No ? toLower( str ) : str;
  10144. }
  10145. }
  10146. // end catch_wildcard_pattern.cpp
  10147. // start catch_xmlwriter.cpp
  10148. #include <iomanip>
  10149. using uchar = unsigned char;
  10150. namespace Catch {
  10151. namespace {
  10152. size_t trailingBytes(unsigned char c) {
  10153. if ((c & 0xE0) == 0xC0) {
  10154. return 2;
  10155. }
  10156. if ((c & 0xF0) == 0xE0) {
  10157. return 3;
  10158. }
  10159. if ((c & 0xF8) == 0xF0) {
  10160. return 4;
  10161. }
  10162. CATCH_INTERNAL_ERROR("Invalid multibyte utf-8 start byte encountered");
  10163. }
  10164. uint32_t headerValue(unsigned char c) {
  10165. if ((c & 0xE0) == 0xC0) {
  10166. return c & 0x1F;
  10167. }
  10168. if ((c & 0xF0) == 0xE0) {
  10169. return c & 0x0F;
  10170. }
  10171. if ((c & 0xF8) == 0xF0) {
  10172. return c & 0x07;
  10173. }
  10174. CATCH_INTERNAL_ERROR("Invalid multibyte utf-8 start byte encountered");
  10175. }
  10176. void hexEscapeChar(std::ostream& os, unsigned char c) {
  10177. std::ios_base::fmtflags f(os.flags());
  10178. os << "\\x"
  10179. << std::uppercase << std::hex << std::setfill('0') << std::setw(2)
  10180. << static_cast<int>(c);
  10181. os.flags(f);
  10182. }
  10183. } // anonymous namespace
  10184. XmlEncode::XmlEncode( std::string const& str, ForWhat forWhat )
  10185. : m_str( str ),
  10186. m_forWhat( forWhat )
  10187. {}
  10188. void XmlEncode::encodeTo( std::ostream& os ) const {
  10189. // Apostrophe escaping not necessary if we always use " to write attributes
  10190. // (see: http://www.w3.org/TR/xml/#syntax)
  10191. for( std::size_t idx = 0; idx < m_str.size(); ++ idx ) {
  10192. uchar c = m_str[idx];
  10193. switch (c) {
  10194. case '<': os << "&lt;"; break;
  10195. case '&': os << "&amp;"; break;
  10196. case '>':
  10197. // See: http://www.w3.org/TR/xml/#syntax
  10198. if (idx > 2 && m_str[idx - 1] == ']' && m_str[idx - 2] == ']')
  10199. os << "&gt;";
  10200. else
  10201. os << c;
  10202. break;
  10203. case '\"':
  10204. if (m_forWhat == ForAttributes)
  10205. os << "&quot;";
  10206. else
  10207. os << c;
  10208. break;
  10209. default:
  10210. // Check for control characters and invalid utf-8
  10211. // Escape control characters in standard ascii
  10212. // see http://stackoverflow.com/questions/404107/why-are-control-characters-illegal-in-xml-1-0
  10213. if (c < 0x09 || (c > 0x0D && c < 0x20) || c == 0x7F) {
  10214. hexEscapeChar(os, c);
  10215. break;
  10216. }
  10217. // Plain ASCII: Write it to stream
  10218. if (c < 0x7F) {
  10219. os << c;
  10220. break;
  10221. }
  10222. // UTF-8 territory
  10223. // Check if the encoding is valid and if it is not, hex escape bytes.
  10224. // Important: We do not check the exact decoded values for validity, only the encoding format
  10225. // First check that this bytes is a valid lead byte:
  10226. // This means that it is not encoded as 1111 1XXX
  10227. // Or as 10XX XXXX
  10228. if (c < 0xC0 ||
  10229. c >= 0xF8) {
  10230. hexEscapeChar(os, c);
  10231. break;
  10232. }
  10233. auto encBytes = trailingBytes(c);
  10234. // Are there enough bytes left to avoid accessing out-of-bounds memory?
  10235. if (idx + encBytes - 1 >= m_str.size()) {
  10236. hexEscapeChar(os, c);
  10237. break;
  10238. }
  10239. // The header is valid, check data
  10240. // The next encBytes bytes must together be a valid utf-8
  10241. // This means: bitpattern 10XX XXXX and the extracted value is sane (ish)
  10242. bool valid = true;
  10243. uint32_t value = headerValue(c);
  10244. for (std::size_t n = 1; n < encBytes; ++n) {
  10245. uchar nc = m_str[idx + n];
  10246. valid &= ((nc & 0xC0) == 0x80);
  10247. value = (value << 6) | (nc & 0x3F);
  10248. }
  10249. if (
  10250. // Wrong bit pattern of following bytes
  10251. (!valid) ||
  10252. // Overlong encodings
  10253. (value < 0x80) ||
  10254. (0x80 <= value && value < 0x800 && encBytes > 2) ||
  10255. (0x800 < value && value < 0x10000 && encBytes > 3) ||
  10256. // Encoded value out of range
  10257. (value >= 0x110000)
  10258. ) {
  10259. hexEscapeChar(os, c);
  10260. break;
  10261. }
  10262. // If we got here, this is in fact a valid(ish) utf-8 sequence
  10263. for (std::size_t n = 0; n < encBytes; ++n) {
  10264. os << m_str[idx + n];
  10265. }
  10266. idx += encBytes - 1;
  10267. break;
  10268. }
  10269. }
  10270. }
  10271. std::ostream& operator << ( std::ostream& os, XmlEncode const& xmlEncode ) {
  10272. xmlEncode.encodeTo( os );
  10273. return os;
  10274. }
  10275. XmlWriter::ScopedElement::ScopedElement( XmlWriter* writer )
  10276. : m_writer( writer )
  10277. {}
  10278. XmlWriter::ScopedElement::ScopedElement( ScopedElement&& other ) noexcept
  10279. : m_writer( other.m_writer ){
  10280. other.m_writer = nullptr;
  10281. }
  10282. XmlWriter::ScopedElement& XmlWriter::ScopedElement::operator=( ScopedElement&& other ) noexcept {
  10283. if ( m_writer ) {
  10284. m_writer->endElement();
  10285. }
  10286. m_writer = other.m_writer;
  10287. other.m_writer = nullptr;
  10288. return *this;
  10289. }
  10290. XmlWriter::ScopedElement::~ScopedElement() {
  10291. if( m_writer )
  10292. m_writer->endElement();
  10293. }
  10294. XmlWriter::ScopedElement& XmlWriter::ScopedElement::writeText( std::string const& text, bool indent ) {
  10295. m_writer->writeText( text, indent );
  10296. return *this;
  10297. }
  10298. XmlWriter::XmlWriter( std::ostream& os ) : m_os( os )
  10299. {
  10300. writeDeclaration();
  10301. }
  10302. XmlWriter::~XmlWriter() {
  10303. while( !m_tags.empty() )
  10304. endElement();
  10305. }
  10306. XmlWriter& XmlWriter::startElement( std::string const& name ) {
  10307. ensureTagClosed();
  10308. newlineIfNecessary();
  10309. m_os << m_indent << '<' << name;
  10310. m_tags.push_back( name );
  10311. m_indent += " ";
  10312. m_tagIsOpen = true;
  10313. return *this;
  10314. }
  10315. XmlWriter::ScopedElement XmlWriter::scopedElement( std::string const& name ) {
  10316. ScopedElement scoped( this );
  10317. startElement( name );
  10318. return scoped;
  10319. }
  10320. XmlWriter& XmlWriter::endElement() {
  10321. newlineIfNecessary();
  10322. m_indent = m_indent.substr( 0, m_indent.size()-2 );
  10323. if( m_tagIsOpen ) {
  10324. m_os << "/>";
  10325. m_tagIsOpen = false;
  10326. }
  10327. else {
  10328. m_os << m_indent << "</" << m_tags.back() << ">";
  10329. }
  10330. m_os << std::endl;
  10331. m_tags.pop_back();
  10332. return *this;
  10333. }
  10334. XmlWriter& XmlWriter::writeAttribute( std::string const& name, std::string const& attribute ) {
  10335. if( !name.empty() && !attribute.empty() )
  10336. m_os << ' ' << name << "=\"" << XmlEncode( attribute, XmlEncode::ForAttributes ) << '"';
  10337. return *this;
  10338. }
  10339. XmlWriter& XmlWriter::writeAttribute( std::string const& name, bool attribute ) {
  10340. m_os << ' ' << name << "=\"" << ( attribute ? "true" : "false" ) << '"';
  10341. return *this;
  10342. }
  10343. XmlWriter& XmlWriter::writeText( std::string const& text, bool indent ) {
  10344. if( !text.empty() ){
  10345. bool tagWasOpen = m_tagIsOpen;
  10346. ensureTagClosed();
  10347. if( tagWasOpen && indent )
  10348. m_os << m_indent;
  10349. m_os << XmlEncode( text );
  10350. m_needsNewline = true;
  10351. }
  10352. return *this;
  10353. }
  10354. XmlWriter& XmlWriter::writeComment( std::string const& text ) {
  10355. ensureTagClosed();
  10356. m_os << m_indent << "<!--" << text << "-->";
  10357. m_needsNewline = true;
  10358. return *this;
  10359. }
  10360. void XmlWriter::writeStylesheetRef( std::string const& url ) {
  10361. m_os << "<?xml-stylesheet type=\"text/xsl\" href=\"" << url << "\"?>\n";
  10362. }
  10363. XmlWriter& XmlWriter::writeBlankLine() {
  10364. ensureTagClosed();
  10365. m_os << '\n';
  10366. return *this;
  10367. }
  10368. void XmlWriter::ensureTagClosed() {
  10369. if( m_tagIsOpen ) {
  10370. m_os << ">" << std::endl;
  10371. m_tagIsOpen = false;
  10372. }
  10373. }
  10374. void XmlWriter::writeDeclaration() {
  10375. m_os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
  10376. }
  10377. void XmlWriter::newlineIfNecessary() {
  10378. if( m_needsNewline ) {
  10379. m_os << std::endl;
  10380. m_needsNewline = false;
  10381. }
  10382. }
  10383. }
  10384. // end catch_xmlwriter.cpp
  10385. // start catch_reporter_bases.cpp
  10386. #include <cstring>
  10387. #include <cfloat>
  10388. #include <cstdio>
  10389. #include <cassert>
  10390. #include <memory>
  10391. namespace Catch {
  10392. void prepareExpandedExpression(AssertionResult& result) {
  10393. result.getExpandedExpression();
  10394. }
  10395. // Because formatting using c++ streams is stateful, drop down to C is required
  10396. // Alternatively we could use stringstream, but its performance is... not good.
  10397. std::string getFormattedDuration( double duration ) {
  10398. // Max exponent + 1 is required to represent the whole part
  10399. // + 1 for decimal point
  10400. // + 3 for the 3 decimal places
  10401. // + 1 for null terminator
  10402. const std::size_t maxDoubleSize = DBL_MAX_10_EXP + 1 + 1 + 3 + 1;
  10403. char buffer[maxDoubleSize];
  10404. // Save previous errno, to prevent sprintf from overwriting it
  10405. ErrnoGuard guard;
  10406. #ifdef _MSC_VER
  10407. sprintf_s(buffer, "%.3f", duration);
  10408. #else
  10409. sprintf(buffer, "%.3f", duration);
  10410. #endif
  10411. return std::string(buffer);
  10412. }
  10413. TestEventListenerBase::TestEventListenerBase(ReporterConfig const & _config)
  10414. :StreamingReporterBase(_config) {}
  10415. std::set<Verbosity> TestEventListenerBase::getSupportedVerbosities() {
  10416. return { Verbosity::Quiet, Verbosity::Normal, Verbosity::High };
  10417. }
  10418. void TestEventListenerBase::assertionStarting(AssertionInfo const &) {}
  10419. bool TestEventListenerBase::assertionEnded(AssertionStats const &) {
  10420. return false;
  10421. }
  10422. } // end namespace Catch
  10423. // end catch_reporter_bases.cpp
  10424. // start catch_reporter_compact.cpp
  10425. namespace {
  10426. #ifdef CATCH_PLATFORM_MAC
  10427. const char* failedString() { return "FAILED"; }
  10428. const char* passedString() { return "PASSED"; }
  10429. #else
  10430. const char* failedString() { return "failed"; }
  10431. const char* passedString() { return "passed"; }
  10432. #endif
  10433. // Colour::LightGrey
  10434. Catch::Colour::Code dimColour() { return Catch::Colour::FileName; }
  10435. std::string bothOrAll( std::size_t count ) {
  10436. return count == 1 ? std::string() :
  10437. count == 2 ? "both " : "all " ;
  10438. }
  10439. } // anon namespace
  10440. namespace Catch {
  10441. namespace {
  10442. // Colour, message variants:
  10443. // - white: No tests ran.
  10444. // - red: Failed [both/all] N test cases, failed [both/all] M assertions.
  10445. // - white: Passed [both/all] N test cases (no assertions).
  10446. // - red: Failed N tests cases, failed M assertions.
  10447. // - green: Passed [both/all] N tests cases with M assertions.
  10448. void printTotals(std::ostream& out, const Totals& totals) {
  10449. if (totals.testCases.total() == 0) {
  10450. out << "No tests ran.";
  10451. } else if (totals.testCases.failed == totals.testCases.total()) {
  10452. Colour colour(Colour::ResultError);
  10453. const std::string qualify_assertions_failed =
  10454. totals.assertions.failed == totals.assertions.total() ?
  10455. bothOrAll(totals.assertions.failed) : std::string();
  10456. out <<
  10457. "Failed " << bothOrAll(totals.testCases.failed)
  10458. << pluralise(totals.testCases.failed, "test case") << ", "
  10459. "failed " << qualify_assertions_failed <<
  10460. pluralise(totals.assertions.failed, "assertion") << '.';
  10461. } else if (totals.assertions.total() == 0) {
  10462. out <<
  10463. "Passed " << bothOrAll(totals.testCases.total())
  10464. << pluralise(totals.testCases.total(), "test case")
  10465. << " (no assertions).";
  10466. } else if (totals.assertions.failed) {
  10467. Colour colour(Colour::ResultError);
  10468. out <<
  10469. "Failed " << pluralise(totals.testCases.failed, "test case") << ", "
  10470. "failed " << pluralise(totals.assertions.failed, "assertion") << '.';
  10471. } else {
  10472. Colour colour(Colour::ResultSuccess);
  10473. out <<
  10474. "Passed " << bothOrAll(totals.testCases.passed)
  10475. << pluralise(totals.testCases.passed, "test case") <<
  10476. " with " << pluralise(totals.assertions.passed, "assertion") << '.';
  10477. }
  10478. }
  10479. // Implementation of CompactReporter formatting
  10480. class AssertionPrinter {
  10481. public:
  10482. AssertionPrinter& operator= (AssertionPrinter const&) = delete;
  10483. AssertionPrinter(AssertionPrinter const&) = delete;
  10484. AssertionPrinter(std::ostream& _stream, AssertionStats const& _stats, bool _printInfoMessages)
  10485. : stream(_stream)
  10486. , result(_stats.assertionResult)
  10487. , messages(_stats.infoMessages)
  10488. , itMessage(_stats.infoMessages.begin())
  10489. , printInfoMessages(_printInfoMessages) {}
  10490. void print() {
  10491. printSourceInfo();
  10492. itMessage = messages.begin();
  10493. switch (result.getResultType()) {
  10494. case ResultWas::Ok:
  10495. printResultType(Colour::ResultSuccess, passedString());
  10496. printOriginalExpression();
  10497. printReconstructedExpression();
  10498. if (!result.hasExpression())
  10499. printRemainingMessages(Colour::None);
  10500. else
  10501. printRemainingMessages();
  10502. break;
  10503. case ResultWas::ExpressionFailed:
  10504. if (result.isOk())
  10505. printResultType(Colour::ResultSuccess, failedString() + std::string(" - but was ok"));
  10506. else
  10507. printResultType(Colour::Error, failedString());
  10508. printOriginalExpression();
  10509. printReconstructedExpression();
  10510. printRemainingMessages();
  10511. break;
  10512. case ResultWas::ThrewException:
  10513. printResultType(Colour::Error, failedString());
  10514. printIssue("unexpected exception with message:");
  10515. printMessage();
  10516. printExpressionWas();
  10517. printRemainingMessages();
  10518. break;
  10519. case ResultWas::FatalErrorCondition:
  10520. printResultType(Colour::Error, failedString());
  10521. printIssue("fatal error condition with message:");
  10522. printMessage();
  10523. printExpressionWas();
  10524. printRemainingMessages();
  10525. break;
  10526. case ResultWas::DidntThrowException:
  10527. printResultType(Colour::Error, failedString());
  10528. printIssue("expected exception, got none");
  10529. printExpressionWas();
  10530. printRemainingMessages();
  10531. break;
  10532. case ResultWas::Info:
  10533. printResultType(Colour::None, "info");
  10534. printMessage();
  10535. printRemainingMessages();
  10536. break;
  10537. case ResultWas::Warning:
  10538. printResultType(Colour::None, "warning");
  10539. printMessage();
  10540. printRemainingMessages();
  10541. break;
  10542. case ResultWas::ExplicitFailure:
  10543. printResultType(Colour::Error, failedString());
  10544. printIssue("explicitly");
  10545. printRemainingMessages(Colour::None);
  10546. break;
  10547. // These cases are here to prevent compiler warnings
  10548. case ResultWas::Unknown:
  10549. case ResultWas::FailureBit:
  10550. case ResultWas::Exception:
  10551. printResultType(Colour::Error, "** internal error **");
  10552. break;
  10553. }
  10554. }
  10555. private:
  10556. void printSourceInfo() const {
  10557. Colour colourGuard(Colour::FileName);
  10558. stream << result.getSourceInfo() << ':';
  10559. }
  10560. void printResultType(Colour::Code colour, std::string const& passOrFail) const {
  10561. if (!passOrFail.empty()) {
  10562. {
  10563. Colour colourGuard(colour);
  10564. stream << ' ' << passOrFail;
  10565. }
  10566. stream << ':';
  10567. }
  10568. }
  10569. void printIssue(std::string const& issue) const {
  10570. stream << ' ' << issue;
  10571. }
  10572. void printExpressionWas() {
  10573. if (result.hasExpression()) {
  10574. stream << ';';
  10575. {
  10576. Colour colour(dimColour());
  10577. stream << " expression was:";
  10578. }
  10579. printOriginalExpression();
  10580. }
  10581. }
  10582. void printOriginalExpression() const {
  10583. if (result.hasExpression()) {
  10584. stream << ' ' << result.getExpression();
  10585. }
  10586. }
  10587. void printReconstructedExpression() const {
  10588. if (result.hasExpandedExpression()) {
  10589. {
  10590. Colour colour(dimColour());
  10591. stream << " for: ";
  10592. }
  10593. stream << result.getExpandedExpression();
  10594. }
  10595. }
  10596. void printMessage() {
  10597. if (itMessage != messages.end()) {
  10598. stream << " '" << itMessage->message << '\'';
  10599. ++itMessage;
  10600. }
  10601. }
  10602. void printRemainingMessages(Colour::Code colour = dimColour()) {
  10603. if (itMessage == messages.end())
  10604. return;
  10605. // using messages.end() directly yields (or auto) compilation error:
  10606. std::vector<MessageInfo>::const_iterator itEnd = messages.end();
  10607. const std::size_t N = static_cast<std::size_t>(std::distance(itMessage, itEnd));
  10608. {
  10609. Colour colourGuard(colour);
  10610. stream << " with " << pluralise(N, "message") << ':';
  10611. }
  10612. for (; itMessage != itEnd; ) {
  10613. // If this assertion is a warning ignore any INFO messages
  10614. if (printInfoMessages || itMessage->type != ResultWas::Info) {
  10615. stream << " '" << itMessage->message << '\'';
  10616. if (++itMessage != itEnd) {
  10617. Colour colourGuard(dimColour());
  10618. stream << " and";
  10619. }
  10620. }
  10621. }
  10622. }
  10623. private:
  10624. std::ostream& stream;
  10625. AssertionResult const& result;
  10626. std::vector<MessageInfo> messages;
  10627. std::vector<MessageInfo>::const_iterator itMessage;
  10628. bool printInfoMessages;
  10629. };
  10630. } // anon namespace
  10631. std::string CompactReporter::getDescription() {
  10632. return "Reports test results on a single line, suitable for IDEs";
  10633. }
  10634. ReporterPreferences CompactReporter::getPreferences() const {
  10635. return m_reporterPrefs;
  10636. }
  10637. void CompactReporter::noMatchingTestCases( std::string const& spec ) {
  10638. stream << "No test cases matched '" << spec << '\'' << std::endl;
  10639. }
  10640. void CompactReporter::assertionStarting( AssertionInfo const& ) {}
  10641. bool CompactReporter::assertionEnded( AssertionStats const& _assertionStats ) {
  10642. AssertionResult const& result = _assertionStats.assertionResult;
  10643. bool printInfoMessages = true;
  10644. // Drop out if result was successful and we're not printing those
  10645. if( !m_config->includeSuccessfulResults() && result.isOk() ) {
  10646. if( result.getResultType() != ResultWas::Warning )
  10647. return false;
  10648. printInfoMessages = false;
  10649. }
  10650. AssertionPrinter printer( stream, _assertionStats, printInfoMessages );
  10651. printer.print();
  10652. stream << std::endl;
  10653. return true;
  10654. }
  10655. void CompactReporter::sectionEnded(SectionStats const& _sectionStats) {
  10656. if (m_config->showDurations() == ShowDurations::Always) {
  10657. stream << getFormattedDuration(_sectionStats.durationInSeconds) << " s: " << _sectionStats.sectionInfo.name << std::endl;
  10658. }
  10659. }
  10660. void CompactReporter::testRunEnded( TestRunStats const& _testRunStats ) {
  10661. printTotals( stream, _testRunStats.totals );
  10662. stream << '\n' << std::endl;
  10663. StreamingReporterBase::testRunEnded( _testRunStats );
  10664. }
  10665. CompactReporter::~CompactReporter() {}
  10666. CATCH_REGISTER_REPORTER( "compact", CompactReporter )
  10667. } // end namespace Catch
  10668. // end catch_reporter_compact.cpp
  10669. // start catch_reporter_console.cpp
  10670. #include <cfloat>
  10671. #include <cstdio>
  10672. #if defined(_MSC_VER)
  10673. #pragma warning(push)
  10674. #pragma warning(disable:4061) // Not all labels are EXPLICITLY handled in switch
  10675. // Note that 4062 (not all labels are handled
  10676. // and default is missing) is enabled
  10677. #endif
  10678. namespace Catch {
  10679. namespace {
  10680. // Formatter impl for ConsoleReporter
  10681. class ConsoleAssertionPrinter {
  10682. public:
  10683. ConsoleAssertionPrinter& operator= (ConsoleAssertionPrinter const&) = delete;
  10684. ConsoleAssertionPrinter(ConsoleAssertionPrinter const&) = delete;
  10685. ConsoleAssertionPrinter(std::ostream& _stream, AssertionStats const& _stats, bool _printInfoMessages)
  10686. : stream(_stream),
  10687. stats(_stats),
  10688. result(_stats.assertionResult),
  10689. colour(Colour::None),
  10690. message(result.getMessage()),
  10691. messages(_stats.infoMessages),
  10692. printInfoMessages(_printInfoMessages) {
  10693. switch (result.getResultType()) {
  10694. case ResultWas::Ok:
  10695. colour = Colour::Success;
  10696. passOrFail = "PASSED";
  10697. //if( result.hasMessage() )
  10698. if (_stats.infoMessages.size() == 1)
  10699. messageLabel = "with message";
  10700. if (_stats.infoMessages.size() > 1)
  10701. messageLabel = "with messages";
  10702. break;
  10703. case ResultWas::ExpressionFailed:
  10704. if (result.isOk()) {
  10705. colour = Colour::Success;
  10706. passOrFail = "FAILED - but was ok";
  10707. } else {
  10708. colour = Colour::Error;
  10709. passOrFail = "FAILED";
  10710. }
  10711. if (_stats.infoMessages.size() == 1)
  10712. messageLabel = "with message";
  10713. if (_stats.infoMessages.size() > 1)
  10714. messageLabel = "with messages";
  10715. break;
  10716. case ResultWas::ThrewException:
  10717. colour = Colour::Error;
  10718. passOrFail = "FAILED";
  10719. messageLabel = "due to unexpected exception with ";
  10720. if (_stats.infoMessages.size() == 1)
  10721. messageLabel += "message";
  10722. if (_stats.infoMessages.size() > 1)
  10723. messageLabel += "messages";
  10724. break;
  10725. case ResultWas::FatalErrorCondition:
  10726. colour = Colour::Error;
  10727. passOrFail = "FAILED";
  10728. messageLabel = "due to a fatal error condition";
  10729. break;
  10730. case ResultWas::DidntThrowException:
  10731. colour = Colour::Error;
  10732. passOrFail = "FAILED";
  10733. messageLabel = "because no exception was thrown where one was expected";
  10734. break;
  10735. case ResultWas::Info:
  10736. messageLabel = "info";
  10737. break;
  10738. case ResultWas::Warning:
  10739. messageLabel = "warning";
  10740. break;
  10741. case ResultWas::ExplicitFailure:
  10742. passOrFail = "FAILED";
  10743. colour = Colour::Error;
  10744. if (_stats.infoMessages.size() == 1)
  10745. messageLabel = "explicitly with message";
  10746. if (_stats.infoMessages.size() > 1)
  10747. messageLabel = "explicitly with messages";
  10748. break;
  10749. // These cases are here to prevent compiler warnings
  10750. case ResultWas::Unknown:
  10751. case ResultWas::FailureBit:
  10752. case ResultWas::Exception:
  10753. passOrFail = "** internal error **";
  10754. colour = Colour::Error;
  10755. break;
  10756. }
  10757. }
  10758. void print() const {
  10759. printSourceInfo();
  10760. if (stats.totals.assertions.total() > 0) {
  10761. printResultType();
  10762. printOriginalExpression();
  10763. printReconstructedExpression();
  10764. } else {
  10765. stream << '\n';
  10766. }
  10767. printMessage();
  10768. }
  10769. private:
  10770. void printResultType() const {
  10771. if (!passOrFail.empty()) {
  10772. Colour colourGuard(colour);
  10773. stream << passOrFail << ":\n";
  10774. }
  10775. }
  10776. void printOriginalExpression() const {
  10777. if (result.hasExpression()) {
  10778. Colour colourGuard(Colour::OriginalExpression);
  10779. stream << " ";
  10780. stream << result.getExpressionInMacro();
  10781. stream << '\n';
  10782. }
  10783. }
  10784. void printReconstructedExpression() const {
  10785. if (result.hasExpandedExpression()) {
  10786. stream << "with expansion:\n";
  10787. Colour colourGuard(Colour::ReconstructedExpression);
  10788. stream << Column(result.getExpandedExpression()).indent(2) << '\n';
  10789. }
  10790. }
  10791. void printMessage() const {
  10792. if (!messageLabel.empty())
  10793. stream << messageLabel << ':' << '\n';
  10794. for (auto const& msg : messages) {
  10795. // If this assertion is a warning ignore any INFO messages
  10796. if (printInfoMessages || msg.type != ResultWas::Info)
  10797. stream << Column(msg.message).indent(2) << '\n';
  10798. }
  10799. }
  10800. void printSourceInfo() const {
  10801. Colour colourGuard(Colour::FileName);
  10802. stream << result.getSourceInfo() << ": ";
  10803. }
  10804. std::ostream& stream;
  10805. AssertionStats const& stats;
  10806. AssertionResult const& result;
  10807. Colour::Code colour;
  10808. std::string passOrFail;
  10809. std::string messageLabel;
  10810. std::string message;
  10811. std::vector<MessageInfo> messages;
  10812. bool printInfoMessages;
  10813. };
  10814. std::size_t makeRatio(std::size_t number, std::size_t total) {
  10815. std::size_t ratio = total > 0 ? CATCH_CONFIG_CONSOLE_WIDTH * number / total : 0;
  10816. return (ratio == 0 && number > 0) ? 1 : ratio;
  10817. }
  10818. std::size_t& findMax(std::size_t& i, std::size_t& j, std::size_t& k) {
  10819. if (i > j && i > k)
  10820. return i;
  10821. else if (j > k)
  10822. return j;
  10823. else
  10824. return k;
  10825. }
  10826. struct ColumnInfo {
  10827. enum Justification { Left, Right };
  10828. std::string name;
  10829. int width;
  10830. Justification justification;
  10831. };
  10832. struct ColumnBreak {};
  10833. struct RowBreak {};
  10834. class Duration {
  10835. enum class Unit {
  10836. Auto,
  10837. Nanoseconds,
  10838. Microseconds,
  10839. Milliseconds,
  10840. Seconds,
  10841. Minutes
  10842. };
  10843. static const uint64_t s_nanosecondsInAMicrosecond = 1000;
  10844. static const uint64_t s_nanosecondsInAMillisecond = 1000 * s_nanosecondsInAMicrosecond;
  10845. static const uint64_t s_nanosecondsInASecond = 1000 * s_nanosecondsInAMillisecond;
  10846. static const uint64_t s_nanosecondsInAMinute = 60 * s_nanosecondsInASecond;
  10847. uint64_t m_inNanoseconds;
  10848. Unit m_units;
  10849. public:
  10850. explicit Duration(uint64_t inNanoseconds, Unit units = Unit::Auto)
  10851. : m_inNanoseconds(inNanoseconds),
  10852. m_units(units) {
  10853. if (m_units == Unit::Auto) {
  10854. if (m_inNanoseconds < s_nanosecondsInAMicrosecond)
  10855. m_units = Unit::Nanoseconds;
  10856. else if (m_inNanoseconds < s_nanosecondsInAMillisecond)
  10857. m_units = Unit::Microseconds;
  10858. else if (m_inNanoseconds < s_nanosecondsInASecond)
  10859. m_units = Unit::Milliseconds;
  10860. else if (m_inNanoseconds < s_nanosecondsInAMinute)
  10861. m_units = Unit::Seconds;
  10862. else
  10863. m_units = Unit::Minutes;
  10864. }
  10865. }
  10866. auto value() const -> double {
  10867. switch (m_units) {
  10868. case Unit::Microseconds:
  10869. return m_inNanoseconds / static_cast<double>(s_nanosecondsInAMicrosecond);
  10870. case Unit::Milliseconds:
  10871. return m_inNanoseconds / static_cast<double>(s_nanosecondsInAMillisecond);
  10872. case Unit::Seconds:
  10873. return m_inNanoseconds / static_cast<double>(s_nanosecondsInASecond);
  10874. case Unit::Minutes:
  10875. return m_inNanoseconds / static_cast<double>(s_nanosecondsInAMinute);
  10876. default:
  10877. return static_cast<double>(m_inNanoseconds);
  10878. }
  10879. }
  10880. auto unitsAsString() const -> std::string {
  10881. switch (m_units) {
  10882. case Unit::Nanoseconds:
  10883. return "ns";
  10884. case Unit::Microseconds:
  10885. return "µs";
  10886. case Unit::Milliseconds:
  10887. return "ms";
  10888. case Unit::Seconds:
  10889. return "s";
  10890. case Unit::Minutes:
  10891. return "m";
  10892. default:
  10893. return "** internal error **";
  10894. }
  10895. }
  10896. friend auto operator << (std::ostream& os, Duration const& duration) -> std::ostream& {
  10897. return os << duration.value() << " " << duration.unitsAsString();
  10898. }
  10899. };
  10900. } // end anon namespace
  10901. class TablePrinter {
  10902. std::ostream& m_os;
  10903. std::vector<ColumnInfo> m_columnInfos;
  10904. std::ostringstream m_oss;
  10905. int m_currentColumn = -1;
  10906. bool m_isOpen = false;
  10907. public:
  10908. TablePrinter( std::ostream& os, std::vector<ColumnInfo> columnInfos )
  10909. : m_os( os ),
  10910. m_columnInfos( std::move( columnInfos ) ) {}
  10911. auto columnInfos() const -> std::vector<ColumnInfo> const& {
  10912. return m_columnInfos;
  10913. }
  10914. void open() {
  10915. if (!m_isOpen) {
  10916. m_isOpen = true;
  10917. *this << RowBreak();
  10918. for (auto const& info : m_columnInfos)
  10919. *this << info.name << ColumnBreak();
  10920. *this << RowBreak();
  10921. m_os << Catch::getLineOfChars<'-'>() << "\n";
  10922. }
  10923. }
  10924. void close() {
  10925. if (m_isOpen) {
  10926. *this << RowBreak();
  10927. m_os << std::endl;
  10928. m_isOpen = false;
  10929. }
  10930. }
  10931. template<typename T>
  10932. friend TablePrinter& operator << (TablePrinter& tp, T const& value) {
  10933. tp.m_oss << value;
  10934. return tp;
  10935. }
  10936. friend TablePrinter& operator << (TablePrinter& tp, ColumnBreak) {
  10937. auto colStr = tp.m_oss.str();
  10938. // This takes account of utf8 encodings
  10939. auto strSize = Catch::StringRef(colStr).numberOfCharacters();
  10940. tp.m_oss.str("");
  10941. tp.open();
  10942. if (tp.m_currentColumn == static_cast<int>(tp.m_columnInfos.size() - 1)) {
  10943. tp.m_currentColumn = -1;
  10944. tp.m_os << "\n";
  10945. }
  10946. tp.m_currentColumn++;
  10947. auto colInfo = tp.m_columnInfos[tp.m_currentColumn];
  10948. auto padding = (strSize + 2 < static_cast<std::size_t>(colInfo.width))
  10949. ? std::string(colInfo.width - (strSize + 2), ' ')
  10950. : std::string();
  10951. if (colInfo.justification == ColumnInfo::Left)
  10952. tp.m_os << colStr << padding << " ";
  10953. else
  10954. tp.m_os << padding << colStr << " ";
  10955. return tp;
  10956. }
  10957. friend TablePrinter& operator << (TablePrinter& tp, RowBreak) {
  10958. if (tp.m_currentColumn > 0) {
  10959. tp.m_os << "\n";
  10960. tp.m_currentColumn = -1;
  10961. }
  10962. return tp;
  10963. }
  10964. };
  10965. ConsoleReporter::ConsoleReporter(ReporterConfig const& config)
  10966. : StreamingReporterBase(config),
  10967. m_tablePrinter(new TablePrinter(config.stream(),
  10968. {
  10969. { "benchmark name", CATCH_CONFIG_CONSOLE_WIDTH - 32, ColumnInfo::Left },
  10970. { "iters", 8, ColumnInfo::Right },
  10971. { "elapsed ns", 14, ColumnInfo::Right },
  10972. { "average", 14, ColumnInfo::Right }
  10973. })) {}
  10974. ConsoleReporter::~ConsoleReporter() = default;
  10975. std::string ConsoleReporter::getDescription() {
  10976. return "Reports test results as plain lines of text";
  10977. }
  10978. void ConsoleReporter::noMatchingTestCases(std::string const& spec) {
  10979. stream << "No test cases matched '" << spec << '\'' << std::endl;
  10980. }
  10981. void ConsoleReporter::assertionStarting(AssertionInfo const&) {}
  10982. bool ConsoleReporter::assertionEnded(AssertionStats const& _assertionStats) {
  10983. AssertionResult const& result = _assertionStats.assertionResult;
  10984. bool includeResults = m_config->includeSuccessfulResults() || !result.isOk();
  10985. // Drop out if result was successful but we're not printing them.
  10986. if (!includeResults && result.getResultType() != ResultWas::Warning)
  10987. return false;
  10988. lazyPrint();
  10989. ConsoleAssertionPrinter printer(stream, _assertionStats, includeResults);
  10990. printer.print();
  10991. stream << std::endl;
  10992. return true;
  10993. }
  10994. void ConsoleReporter::sectionStarting(SectionInfo const& _sectionInfo) {
  10995. m_headerPrinted = false;
  10996. StreamingReporterBase::sectionStarting(_sectionInfo);
  10997. }
  10998. void ConsoleReporter::sectionEnded(SectionStats const& _sectionStats) {
  10999. m_tablePrinter->close();
  11000. if (_sectionStats.missingAssertions) {
  11001. lazyPrint();
  11002. Colour colour(Colour::ResultError);
  11003. if (m_sectionStack.size() > 1)
  11004. stream << "\nNo assertions in section";
  11005. else
  11006. stream << "\nNo assertions in test case";
  11007. stream << " '" << _sectionStats.sectionInfo.name << "'\n" << std::endl;
  11008. }
  11009. if (m_config->showDurations() == ShowDurations::Always) {
  11010. stream << getFormattedDuration(_sectionStats.durationInSeconds) << " s: " << _sectionStats.sectionInfo.name << std::endl;
  11011. }
  11012. if (m_headerPrinted) {
  11013. m_headerPrinted = false;
  11014. }
  11015. StreamingReporterBase::sectionEnded(_sectionStats);
  11016. }
  11017. void ConsoleReporter::benchmarkStarting(BenchmarkInfo const& info) {
  11018. lazyPrintWithoutClosingBenchmarkTable();
  11019. auto nameCol = Column( info.name ).width( static_cast<std::size_t>( m_tablePrinter->columnInfos()[0].width - 2 ) );
  11020. bool firstLine = true;
  11021. for (auto line : nameCol) {
  11022. if (!firstLine)
  11023. (*m_tablePrinter) << ColumnBreak() << ColumnBreak() << ColumnBreak();
  11024. else
  11025. firstLine = false;
  11026. (*m_tablePrinter) << line << ColumnBreak();
  11027. }
  11028. }
  11029. void ConsoleReporter::benchmarkEnded(BenchmarkStats const& stats) {
  11030. Duration average(stats.elapsedTimeInNanoseconds / stats.iterations);
  11031. (*m_tablePrinter)
  11032. << stats.iterations << ColumnBreak()
  11033. << stats.elapsedTimeInNanoseconds << ColumnBreak()
  11034. << average << ColumnBreak();
  11035. }
  11036. void ConsoleReporter::testCaseEnded(TestCaseStats const& _testCaseStats) {
  11037. m_tablePrinter->close();
  11038. StreamingReporterBase::testCaseEnded(_testCaseStats);
  11039. m_headerPrinted = false;
  11040. }
  11041. void ConsoleReporter::testGroupEnded(TestGroupStats const& _testGroupStats) {
  11042. if (currentGroupInfo.used) {
  11043. printSummaryDivider();
  11044. stream << "Summary for group '" << _testGroupStats.groupInfo.name << "':\n";
  11045. printTotals(_testGroupStats.totals);
  11046. stream << '\n' << std::endl;
  11047. }
  11048. StreamingReporterBase::testGroupEnded(_testGroupStats);
  11049. }
  11050. void ConsoleReporter::testRunEnded(TestRunStats const& _testRunStats) {
  11051. printTotalsDivider(_testRunStats.totals);
  11052. printTotals(_testRunStats.totals);
  11053. stream << std::endl;
  11054. StreamingReporterBase::testRunEnded(_testRunStats);
  11055. }
  11056. void ConsoleReporter::lazyPrint() {
  11057. m_tablePrinter->close();
  11058. lazyPrintWithoutClosingBenchmarkTable();
  11059. }
  11060. void ConsoleReporter::lazyPrintWithoutClosingBenchmarkTable() {
  11061. if (!currentTestRunInfo.used)
  11062. lazyPrintRunInfo();
  11063. if (!currentGroupInfo.used)
  11064. lazyPrintGroupInfo();
  11065. if (!m_headerPrinted) {
  11066. printTestCaseAndSectionHeader();
  11067. m_headerPrinted = true;
  11068. }
  11069. }
  11070. void ConsoleReporter::lazyPrintRunInfo() {
  11071. stream << '\n' << getLineOfChars<'~'>() << '\n';
  11072. Colour colour(Colour::SecondaryText);
  11073. stream << currentTestRunInfo->name
  11074. << " is a Catch v" << libraryVersion() << " host application.\n"
  11075. << "Run with -? for options\n\n";
  11076. if (m_config->rngSeed() != 0)
  11077. stream << "Randomness seeded to: " << m_config->rngSeed() << "\n\n";
  11078. currentTestRunInfo.used = true;
  11079. }
  11080. void ConsoleReporter::lazyPrintGroupInfo() {
  11081. if (!currentGroupInfo->name.empty() && currentGroupInfo->groupsCounts > 1) {
  11082. printClosedHeader("Group: " + currentGroupInfo->name);
  11083. currentGroupInfo.used = true;
  11084. }
  11085. }
  11086. void ConsoleReporter::printTestCaseAndSectionHeader() {
  11087. assert(!m_sectionStack.empty());
  11088. printOpenHeader(currentTestCaseInfo->name);
  11089. if (m_sectionStack.size() > 1) {
  11090. Colour colourGuard(Colour::Headers);
  11091. auto
  11092. it = m_sectionStack.begin() + 1, // Skip first section (test case)
  11093. itEnd = m_sectionStack.end();
  11094. for (; it != itEnd; ++it)
  11095. printHeaderString(it->name, 2);
  11096. }
  11097. SourceLineInfo lineInfo = m_sectionStack.back().lineInfo;
  11098. if (!lineInfo.empty()) {
  11099. stream << getLineOfChars<'-'>() << '\n';
  11100. Colour colourGuard(Colour::FileName);
  11101. stream << lineInfo << '\n';
  11102. }
  11103. stream << getLineOfChars<'.'>() << '\n' << std::endl;
  11104. }
  11105. void ConsoleReporter::printClosedHeader(std::string const& _name) {
  11106. printOpenHeader(_name);
  11107. stream << getLineOfChars<'.'>() << '\n';
  11108. }
  11109. void ConsoleReporter::printOpenHeader(std::string const& _name) {
  11110. stream << getLineOfChars<'-'>() << '\n';
  11111. {
  11112. Colour colourGuard(Colour::Headers);
  11113. printHeaderString(_name);
  11114. }
  11115. }
  11116. // if string has a : in first line will set indent to follow it on
  11117. // subsequent lines
  11118. void ConsoleReporter::printHeaderString(std::string const& _string, std::size_t indent) {
  11119. std::size_t i = _string.find(": ");
  11120. if (i != std::string::npos)
  11121. i += 2;
  11122. else
  11123. i = 0;
  11124. stream << Column(_string).indent(indent + i).initialIndent(indent) << '\n';
  11125. }
  11126. struct SummaryColumn {
  11127. SummaryColumn( std::string _label, Colour::Code _colour )
  11128. : label( std::move( _label ) ),
  11129. colour( _colour ) {}
  11130. SummaryColumn addRow( std::size_t count ) {
  11131. ReusableStringStream rss;
  11132. rss << count;
  11133. std::string row = rss.str();
  11134. for (auto& oldRow : rows) {
  11135. while (oldRow.size() < row.size())
  11136. oldRow = ' ' + oldRow;
  11137. while (oldRow.size() > row.size())
  11138. row = ' ' + row;
  11139. }
  11140. rows.push_back(row);
  11141. return *this;
  11142. }
  11143. std::string label;
  11144. Colour::Code colour;
  11145. std::vector<std::string> rows;
  11146. };
  11147. void ConsoleReporter::printTotals( Totals const& totals ) {
  11148. if (totals.testCases.total() == 0) {
  11149. stream << Colour(Colour::Warning) << "No tests ran\n";
  11150. } else if (totals.assertions.total() > 0 && totals.testCases.allPassed()) {
  11151. stream << Colour(Colour::ResultSuccess) << "All tests passed";
  11152. stream << " ("
  11153. << pluralise(totals.assertions.passed, "assertion") << " in "
  11154. << pluralise(totals.testCases.passed, "test case") << ')'
  11155. << '\n';
  11156. } else {
  11157. std::vector<SummaryColumn> columns;
  11158. columns.push_back(SummaryColumn("", Colour::None)
  11159. .addRow(totals.testCases.total())
  11160. .addRow(totals.assertions.total()));
  11161. columns.push_back(SummaryColumn("passed", Colour::Success)
  11162. .addRow(totals.testCases.passed)
  11163. .addRow(totals.assertions.passed));
  11164. columns.push_back(SummaryColumn("failed", Colour::ResultError)
  11165. .addRow(totals.testCases.failed)
  11166. .addRow(totals.assertions.failed));
  11167. columns.push_back(SummaryColumn("failed as expected", Colour::ResultExpectedFailure)
  11168. .addRow(totals.testCases.failedButOk)
  11169. .addRow(totals.assertions.failedButOk));
  11170. printSummaryRow("test cases", columns, 0);
  11171. printSummaryRow("assertions", columns, 1);
  11172. }
  11173. }
  11174. void ConsoleReporter::printSummaryRow(std::string const& label, std::vector<SummaryColumn> const& cols, std::size_t row) {
  11175. for (auto col : cols) {
  11176. std::string value = col.rows[row];
  11177. if (col.label.empty()) {
  11178. stream << label << ": ";
  11179. if (value != "0")
  11180. stream << value;
  11181. else
  11182. stream << Colour(Colour::Warning) << "- none -";
  11183. } else if (value != "0") {
  11184. stream << Colour(Colour::LightGrey) << " | ";
  11185. stream << Colour(col.colour)
  11186. << value << ' ' << col.label;
  11187. }
  11188. }
  11189. stream << '\n';
  11190. }
  11191. void ConsoleReporter::printTotalsDivider(Totals const& totals) {
  11192. if (totals.testCases.total() > 0) {
  11193. std::size_t failedRatio = makeRatio(totals.testCases.failed, totals.testCases.total());
  11194. std::size_t failedButOkRatio = makeRatio(totals.testCases.failedButOk, totals.testCases.total());
  11195. std::size_t passedRatio = makeRatio(totals.testCases.passed, totals.testCases.total());
  11196. while (failedRatio + failedButOkRatio + passedRatio < CATCH_CONFIG_CONSOLE_WIDTH - 1)
  11197. findMax(failedRatio, failedButOkRatio, passedRatio)++;
  11198. while (failedRatio + failedButOkRatio + passedRatio > CATCH_CONFIG_CONSOLE_WIDTH - 1)
  11199. findMax(failedRatio, failedButOkRatio, passedRatio)--;
  11200. stream << Colour(Colour::Error) << std::string(failedRatio, '=');
  11201. stream << Colour(Colour::ResultExpectedFailure) << std::string(failedButOkRatio, '=');
  11202. if (totals.testCases.allPassed())
  11203. stream << Colour(Colour::ResultSuccess) << std::string(passedRatio, '=');
  11204. else
  11205. stream << Colour(Colour::Success) << std::string(passedRatio, '=');
  11206. } else {
  11207. stream << Colour(Colour::Warning) << std::string(CATCH_CONFIG_CONSOLE_WIDTH - 1, '=');
  11208. }
  11209. stream << '\n';
  11210. }
  11211. void ConsoleReporter::printSummaryDivider() {
  11212. stream << getLineOfChars<'-'>() << '\n';
  11213. }
  11214. CATCH_REGISTER_REPORTER("console", ConsoleReporter)
  11215. } // end namespace Catch
  11216. #if defined(_MSC_VER)
  11217. #pragma warning(pop)
  11218. #endif
  11219. // end catch_reporter_console.cpp
  11220. // start catch_reporter_junit.cpp
  11221. #include <cassert>
  11222. #include <sstream>
  11223. #include <ctime>
  11224. #include <algorithm>
  11225. namespace Catch {
  11226. namespace {
  11227. std::string getCurrentTimestamp() {
  11228. // Beware, this is not reentrant because of backward compatibility issues
  11229. // Also, UTC only, again because of backward compatibility (%z is C++11)
  11230. time_t rawtime;
  11231. std::time(&rawtime);
  11232. auto const timeStampSize = sizeof("2017-01-16T17:06:45Z");
  11233. #ifdef _MSC_VER
  11234. std::tm timeInfo = {};
  11235. gmtime_s(&timeInfo, &rawtime);
  11236. #else
  11237. std::tm* timeInfo;
  11238. timeInfo = std::gmtime(&rawtime);
  11239. #endif
  11240. char timeStamp[timeStampSize];
  11241. const char * const fmt = "%Y-%m-%dT%H:%M:%SZ";
  11242. #ifdef _MSC_VER
  11243. std::strftime(timeStamp, timeStampSize, fmt, &timeInfo);
  11244. #else
  11245. std::strftime(timeStamp, timeStampSize, fmt, timeInfo);
  11246. #endif
  11247. return std::string(timeStamp);
  11248. }
  11249. std::string fileNameTag(const std::vector<std::string> &tags) {
  11250. auto it = std::find_if(begin(tags),
  11251. end(tags),
  11252. [] (std::string const& tag) {return tag.front() == '#'; });
  11253. if (it != tags.end())
  11254. return it->substr(1);
  11255. return std::string();
  11256. }
  11257. } // anonymous namespace
  11258. JunitReporter::JunitReporter( ReporterConfig const& _config )
  11259. : CumulativeReporterBase( _config ),
  11260. xml( _config.stream() )
  11261. {
  11262. m_reporterPrefs.shouldRedirectStdOut = true;
  11263. m_reporterPrefs.shouldReportAllAssertions = true;
  11264. }
  11265. JunitReporter::~JunitReporter() {}
  11266. std::string JunitReporter::getDescription() {
  11267. return "Reports test results in an XML format that looks like Ant's junitreport target";
  11268. }
  11269. void JunitReporter::noMatchingTestCases( std::string const& /*spec*/ ) {}
  11270. void JunitReporter::testRunStarting( TestRunInfo const& runInfo ) {
  11271. CumulativeReporterBase::testRunStarting( runInfo );
  11272. xml.startElement( "testsuites" );
  11273. }
  11274. void JunitReporter::testGroupStarting( GroupInfo const& groupInfo ) {
  11275. suiteTimer.start();
  11276. stdOutForSuite.clear();
  11277. stdErrForSuite.clear();
  11278. unexpectedExceptions = 0;
  11279. CumulativeReporterBase::testGroupStarting( groupInfo );
  11280. }
  11281. void JunitReporter::testCaseStarting( TestCaseInfo const& testCaseInfo ) {
  11282. m_okToFail = testCaseInfo.okToFail();
  11283. }
  11284. bool JunitReporter::assertionEnded( AssertionStats const& assertionStats ) {
  11285. if( assertionStats.assertionResult.getResultType() == ResultWas::ThrewException && !m_okToFail )
  11286. unexpectedExceptions++;
  11287. return CumulativeReporterBase::assertionEnded( assertionStats );
  11288. }
  11289. void JunitReporter::testCaseEnded( TestCaseStats const& testCaseStats ) {
  11290. stdOutForSuite += testCaseStats.stdOut;
  11291. stdErrForSuite += testCaseStats.stdErr;
  11292. CumulativeReporterBase::testCaseEnded( testCaseStats );
  11293. }
  11294. void JunitReporter::testGroupEnded( TestGroupStats const& testGroupStats ) {
  11295. double suiteTime = suiteTimer.getElapsedSeconds();
  11296. CumulativeReporterBase::testGroupEnded( testGroupStats );
  11297. writeGroup( *m_testGroups.back(), suiteTime );
  11298. }
  11299. void JunitReporter::testRunEndedCumulative() {
  11300. xml.endElement();
  11301. }
  11302. void JunitReporter::writeGroup( TestGroupNode const& groupNode, double suiteTime ) {
  11303. XmlWriter::ScopedElement e = xml.scopedElement( "testsuite" );
  11304. TestGroupStats const& stats = groupNode.value;
  11305. xml.writeAttribute( "name", stats.groupInfo.name );
  11306. xml.writeAttribute( "errors", unexpectedExceptions );
  11307. xml.writeAttribute( "failures", stats.totals.assertions.failed-unexpectedExceptions );
  11308. xml.writeAttribute( "tests", stats.totals.assertions.total() );
  11309. xml.writeAttribute( "hostname", "tbd" ); // !TBD
  11310. if( m_config->showDurations() == ShowDurations::Never )
  11311. xml.writeAttribute( "time", "" );
  11312. else
  11313. xml.writeAttribute( "time", suiteTime );
  11314. xml.writeAttribute( "timestamp", getCurrentTimestamp() );
  11315. // Write test cases
  11316. for( auto const& child : groupNode.children )
  11317. writeTestCase( *child );
  11318. xml.scopedElement( "system-out" ).writeText( trim( stdOutForSuite ), false );
  11319. xml.scopedElement( "system-err" ).writeText( trim( stdErrForSuite ), false );
  11320. }
  11321. void JunitReporter::writeTestCase( TestCaseNode const& testCaseNode ) {
  11322. TestCaseStats const& stats = testCaseNode.value;
  11323. // All test cases have exactly one section - which represents the
  11324. // test case itself. That section may have 0-n nested sections
  11325. assert( testCaseNode.children.size() == 1 );
  11326. SectionNode const& rootSection = *testCaseNode.children.front();
  11327. std::string className = stats.testInfo.className;
  11328. if( className.empty() ) {
  11329. className = fileNameTag(stats.testInfo.tags);
  11330. if ( className.empty() )
  11331. className = "global";
  11332. }
  11333. if ( !m_config->name().empty() )
  11334. className = m_config->name() + "." + className;
  11335. writeSection( className, "", rootSection );
  11336. }
  11337. void JunitReporter::writeSection( std::string const& className,
  11338. std::string const& rootName,
  11339. SectionNode const& sectionNode ) {
  11340. std::string name = trim( sectionNode.stats.sectionInfo.name );
  11341. if( !rootName.empty() )
  11342. name = rootName + '/' + name;
  11343. if( !sectionNode.assertions.empty() ||
  11344. !sectionNode.stdOut.empty() ||
  11345. !sectionNode.stdErr.empty() ) {
  11346. XmlWriter::ScopedElement e = xml.scopedElement( "testcase" );
  11347. if( className.empty() ) {
  11348. xml.writeAttribute( "classname", name );
  11349. xml.writeAttribute( "name", "root" );
  11350. }
  11351. else {
  11352. xml.writeAttribute( "classname", className );
  11353. xml.writeAttribute( "name", name );
  11354. }
  11355. xml.writeAttribute( "time", ::Catch::Detail::stringify( sectionNode.stats.durationInSeconds ) );
  11356. writeAssertions( sectionNode );
  11357. if( !sectionNode.stdOut.empty() )
  11358. xml.scopedElement( "system-out" ).writeText( trim( sectionNode.stdOut ), false );
  11359. if( !sectionNode.stdErr.empty() )
  11360. xml.scopedElement( "system-err" ).writeText( trim( sectionNode.stdErr ), false );
  11361. }
  11362. for( auto const& childNode : sectionNode.childSections )
  11363. if( className.empty() )
  11364. writeSection( name, "", *childNode );
  11365. else
  11366. writeSection( className, name, *childNode );
  11367. }
  11368. void JunitReporter::writeAssertions( SectionNode const& sectionNode ) {
  11369. for( auto const& assertion : sectionNode.assertions )
  11370. writeAssertion( assertion );
  11371. }
  11372. void JunitReporter::writeAssertion( AssertionStats const& stats ) {
  11373. AssertionResult const& result = stats.assertionResult;
  11374. if( !result.isOk() ) {
  11375. std::string elementName;
  11376. switch( result.getResultType() ) {
  11377. case ResultWas::ThrewException:
  11378. case ResultWas::FatalErrorCondition:
  11379. elementName = "error";
  11380. break;
  11381. case ResultWas::ExplicitFailure:
  11382. elementName = "failure";
  11383. break;
  11384. case ResultWas::ExpressionFailed:
  11385. elementName = "failure";
  11386. break;
  11387. case ResultWas::DidntThrowException:
  11388. elementName = "failure";
  11389. break;
  11390. // We should never see these here:
  11391. case ResultWas::Info:
  11392. case ResultWas::Warning:
  11393. case ResultWas::Ok:
  11394. case ResultWas::Unknown:
  11395. case ResultWas::FailureBit:
  11396. case ResultWas::Exception:
  11397. elementName = "internalError";
  11398. break;
  11399. }
  11400. XmlWriter::ScopedElement e = xml.scopedElement( elementName );
  11401. xml.writeAttribute( "message", result.getExpandedExpression() );
  11402. xml.writeAttribute( "type", result.getTestMacroName() );
  11403. ReusableStringStream rss;
  11404. if( !result.getMessage().empty() )
  11405. rss << result.getMessage() << '\n';
  11406. for( auto const& msg : stats.infoMessages )
  11407. if( msg.type == ResultWas::Info )
  11408. rss << msg.message << '\n';
  11409. rss << "at " << result.getSourceInfo();
  11410. xml.writeText( rss.str(), false );
  11411. }
  11412. }
  11413. CATCH_REGISTER_REPORTER( "junit", JunitReporter )
  11414. } // end namespace Catch
  11415. // end catch_reporter_junit.cpp
  11416. // start catch_reporter_listening.cpp
  11417. #include <cassert>
  11418. namespace Catch {
  11419. ListeningReporter::ListeningReporter() {
  11420. // We will assume that listeners will always want all assertions
  11421. m_preferences.shouldReportAllAssertions = true;
  11422. }
  11423. void ListeningReporter::addListener( IStreamingReporterPtr&& listener ) {
  11424. m_listeners.push_back( std::move( listener ) );
  11425. }
  11426. void ListeningReporter::addReporter(IStreamingReporterPtr&& reporter) {
  11427. assert(!m_reporter && "Listening reporter can wrap only 1 real reporter");
  11428. m_reporter = std::move( reporter );
  11429. m_preferences.shouldRedirectStdOut = m_reporter->getPreferences().shouldRedirectStdOut;
  11430. }
  11431. ReporterPreferences ListeningReporter::getPreferences() const {
  11432. return m_preferences;
  11433. }
  11434. std::set<Verbosity> ListeningReporter::getSupportedVerbosities() {
  11435. return std::set<Verbosity>{ };
  11436. }
  11437. void ListeningReporter::noMatchingTestCases( std::string const& spec ) {
  11438. for ( auto const& listener : m_listeners ) {
  11439. listener->noMatchingTestCases( spec );
  11440. }
  11441. m_reporter->noMatchingTestCases( spec );
  11442. }
  11443. void ListeningReporter::benchmarkStarting( BenchmarkInfo const& benchmarkInfo ) {
  11444. for ( auto const& listener : m_listeners ) {
  11445. listener->benchmarkStarting( benchmarkInfo );
  11446. }
  11447. m_reporter->benchmarkStarting( benchmarkInfo );
  11448. }
  11449. void ListeningReporter::benchmarkEnded( BenchmarkStats const& benchmarkStats ) {
  11450. for ( auto const& listener : m_listeners ) {
  11451. listener->benchmarkEnded( benchmarkStats );
  11452. }
  11453. m_reporter->benchmarkEnded( benchmarkStats );
  11454. }
  11455. void ListeningReporter::testRunStarting( TestRunInfo const& testRunInfo ) {
  11456. for ( auto const& listener : m_listeners ) {
  11457. listener->testRunStarting( testRunInfo );
  11458. }
  11459. m_reporter->testRunStarting( testRunInfo );
  11460. }
  11461. void ListeningReporter::testGroupStarting( GroupInfo const& groupInfo ) {
  11462. for ( auto const& listener : m_listeners ) {
  11463. listener->testGroupStarting( groupInfo );
  11464. }
  11465. m_reporter->testGroupStarting( groupInfo );
  11466. }
  11467. void ListeningReporter::testCaseStarting( TestCaseInfo const& testInfo ) {
  11468. for ( auto const& listener : m_listeners ) {
  11469. listener->testCaseStarting( testInfo );
  11470. }
  11471. m_reporter->testCaseStarting( testInfo );
  11472. }
  11473. void ListeningReporter::sectionStarting( SectionInfo const& sectionInfo ) {
  11474. for ( auto const& listener : m_listeners ) {
  11475. listener->sectionStarting( sectionInfo );
  11476. }
  11477. m_reporter->sectionStarting( sectionInfo );
  11478. }
  11479. void ListeningReporter::assertionStarting( AssertionInfo const& assertionInfo ) {
  11480. for ( auto const& listener : m_listeners ) {
  11481. listener->assertionStarting( assertionInfo );
  11482. }
  11483. m_reporter->assertionStarting( assertionInfo );
  11484. }
  11485. // The return value indicates if the messages buffer should be cleared:
  11486. bool ListeningReporter::assertionEnded( AssertionStats const& assertionStats ) {
  11487. for( auto const& listener : m_listeners ) {
  11488. static_cast<void>( listener->assertionEnded( assertionStats ) );
  11489. }
  11490. return m_reporter->assertionEnded( assertionStats );
  11491. }
  11492. void ListeningReporter::sectionEnded( SectionStats const& sectionStats ) {
  11493. for ( auto const& listener : m_listeners ) {
  11494. listener->sectionEnded( sectionStats );
  11495. }
  11496. m_reporter->sectionEnded( sectionStats );
  11497. }
  11498. void ListeningReporter::testCaseEnded( TestCaseStats const& testCaseStats ) {
  11499. for ( auto const& listener : m_listeners ) {
  11500. listener->testCaseEnded( testCaseStats );
  11501. }
  11502. m_reporter->testCaseEnded( testCaseStats );
  11503. }
  11504. void ListeningReporter::testGroupEnded( TestGroupStats const& testGroupStats ) {
  11505. for ( auto const& listener : m_listeners ) {
  11506. listener->testGroupEnded( testGroupStats );
  11507. }
  11508. m_reporter->testGroupEnded( testGroupStats );
  11509. }
  11510. void ListeningReporter::testRunEnded( TestRunStats const& testRunStats ) {
  11511. for ( auto const& listener : m_listeners ) {
  11512. listener->testRunEnded( testRunStats );
  11513. }
  11514. m_reporter->testRunEnded( testRunStats );
  11515. }
  11516. void ListeningReporter::skipTest( TestCaseInfo const& testInfo ) {
  11517. for ( auto const& listener : m_listeners ) {
  11518. listener->skipTest( testInfo );
  11519. }
  11520. m_reporter->skipTest( testInfo );
  11521. }
  11522. bool ListeningReporter::isMulti() const {
  11523. return true;
  11524. }
  11525. } // end namespace Catch
  11526. // end catch_reporter_listening.cpp
  11527. // start catch_reporter_xml.cpp
  11528. #if defined(_MSC_VER)
  11529. #pragma warning(push)
  11530. #pragma warning(disable:4061) // Not all labels are EXPLICITLY handled in switch
  11531. // Note that 4062 (not all labels are handled
  11532. // and default is missing) is enabled
  11533. #endif
  11534. namespace Catch {
  11535. XmlReporter::XmlReporter( ReporterConfig const& _config )
  11536. : StreamingReporterBase( _config ),
  11537. m_xml(_config.stream())
  11538. {
  11539. m_reporterPrefs.shouldRedirectStdOut = true;
  11540. m_reporterPrefs.shouldReportAllAssertions = true;
  11541. }
  11542. XmlReporter::~XmlReporter() = default;
  11543. std::string XmlReporter::getDescription() {
  11544. return "Reports test results as an XML document";
  11545. }
  11546. std::string XmlReporter::getStylesheetRef() const {
  11547. return std::string();
  11548. }
  11549. void XmlReporter::writeSourceInfo( SourceLineInfo const& sourceInfo ) {
  11550. m_xml
  11551. .writeAttribute( "filename", sourceInfo.file )
  11552. .writeAttribute( "line", sourceInfo.line );
  11553. }
  11554. void XmlReporter::noMatchingTestCases( std::string const& s ) {
  11555. StreamingReporterBase::noMatchingTestCases( s );
  11556. }
  11557. void XmlReporter::testRunStarting( TestRunInfo const& testInfo ) {
  11558. StreamingReporterBase::testRunStarting( testInfo );
  11559. std::string stylesheetRef = getStylesheetRef();
  11560. if( !stylesheetRef.empty() )
  11561. m_xml.writeStylesheetRef( stylesheetRef );
  11562. m_xml.startElement( "Catch" );
  11563. if( !m_config->name().empty() )
  11564. m_xml.writeAttribute( "name", m_config->name() );
  11565. if( m_config->rngSeed() != 0 )
  11566. m_xml.scopedElement( "Randomness" )
  11567. .writeAttribute( "seed", m_config->rngSeed() );
  11568. }
  11569. void XmlReporter::testGroupStarting( GroupInfo const& groupInfo ) {
  11570. StreamingReporterBase::testGroupStarting( groupInfo );
  11571. m_xml.startElement( "Group" )
  11572. .writeAttribute( "name", groupInfo.name );
  11573. }
  11574. void XmlReporter::testCaseStarting( TestCaseInfo const& testInfo ) {
  11575. StreamingReporterBase::testCaseStarting(testInfo);
  11576. m_xml.startElement( "TestCase" )
  11577. .writeAttribute( "name", trim( testInfo.name ) )
  11578. .writeAttribute( "description", testInfo.description )
  11579. .writeAttribute( "tags", testInfo.tagsAsString() );
  11580. writeSourceInfo( testInfo.lineInfo );
  11581. if ( m_config->showDurations() == ShowDurations::Always )
  11582. m_testCaseTimer.start();
  11583. m_xml.ensureTagClosed();
  11584. }
  11585. void XmlReporter::sectionStarting( SectionInfo const& sectionInfo ) {
  11586. StreamingReporterBase::sectionStarting( sectionInfo );
  11587. if( m_sectionDepth++ > 0 ) {
  11588. m_xml.startElement( "Section" )
  11589. .writeAttribute( "name", trim( sectionInfo.name ) );
  11590. writeSourceInfo( sectionInfo.lineInfo );
  11591. m_xml.ensureTagClosed();
  11592. }
  11593. }
  11594. void XmlReporter::assertionStarting( AssertionInfo const& ) { }
  11595. bool XmlReporter::assertionEnded( AssertionStats const& assertionStats ) {
  11596. AssertionResult const& result = assertionStats.assertionResult;
  11597. bool includeResults = m_config->includeSuccessfulResults() || !result.isOk();
  11598. if( includeResults || result.getResultType() == ResultWas::Warning ) {
  11599. // Print any info messages in <Info> tags.
  11600. for( auto const& msg : assertionStats.infoMessages ) {
  11601. if( msg.type == ResultWas::Info && includeResults ) {
  11602. m_xml.scopedElement( "Info" )
  11603. .writeText( msg.message );
  11604. } else if ( msg.type == ResultWas::Warning ) {
  11605. m_xml.scopedElement( "Warning" )
  11606. .writeText( msg.message );
  11607. }
  11608. }
  11609. }
  11610. // Drop out if result was successful but we're not printing them.
  11611. if( !includeResults && result.getResultType() != ResultWas::Warning )
  11612. return true;
  11613. // Print the expression if there is one.
  11614. if( result.hasExpression() ) {
  11615. m_xml.startElement( "Expression" )
  11616. .writeAttribute( "success", result.succeeded() )
  11617. .writeAttribute( "type", result.getTestMacroName() );
  11618. writeSourceInfo( result.getSourceInfo() );
  11619. m_xml.scopedElement( "Original" )
  11620. .writeText( result.getExpression() );
  11621. m_xml.scopedElement( "Expanded" )
  11622. .writeText( result.getExpandedExpression() );
  11623. }
  11624. // And... Print a result applicable to each result type.
  11625. switch( result.getResultType() ) {
  11626. case ResultWas::ThrewException:
  11627. m_xml.startElement( "Exception" );
  11628. writeSourceInfo( result.getSourceInfo() );
  11629. m_xml.writeText( result.getMessage() );
  11630. m_xml.endElement();
  11631. break;
  11632. case ResultWas::FatalErrorCondition:
  11633. m_xml.startElement( "FatalErrorCondition" );
  11634. writeSourceInfo( result.getSourceInfo() );
  11635. m_xml.writeText( result.getMessage() );
  11636. m_xml.endElement();
  11637. break;
  11638. case ResultWas::Info:
  11639. m_xml.scopedElement( "Info" )
  11640. .writeText( result.getMessage() );
  11641. break;
  11642. case ResultWas::Warning:
  11643. // Warning will already have been written
  11644. break;
  11645. case ResultWas::ExplicitFailure:
  11646. m_xml.startElement( "Failure" );
  11647. writeSourceInfo( result.getSourceInfo() );
  11648. m_xml.writeText( result.getMessage() );
  11649. m_xml.endElement();
  11650. break;
  11651. default:
  11652. break;
  11653. }
  11654. if( result.hasExpression() )
  11655. m_xml.endElement();
  11656. return true;
  11657. }
  11658. void XmlReporter::sectionEnded( SectionStats const& sectionStats ) {
  11659. StreamingReporterBase::sectionEnded( sectionStats );
  11660. if( --m_sectionDepth > 0 ) {
  11661. XmlWriter::ScopedElement e = m_xml.scopedElement( "OverallResults" );
  11662. e.writeAttribute( "successes", sectionStats.assertions.passed );
  11663. e.writeAttribute( "failures", sectionStats.assertions.failed );
  11664. e.writeAttribute( "expectedFailures", sectionStats.assertions.failedButOk );
  11665. if ( m_config->showDurations() == ShowDurations::Always )
  11666. e.writeAttribute( "durationInSeconds", sectionStats.durationInSeconds );
  11667. m_xml.endElement();
  11668. }
  11669. }
  11670. void XmlReporter::testCaseEnded( TestCaseStats const& testCaseStats ) {
  11671. StreamingReporterBase::testCaseEnded( testCaseStats );
  11672. XmlWriter::ScopedElement e = m_xml.scopedElement( "OverallResult" );
  11673. e.writeAttribute( "success", testCaseStats.totals.assertions.allOk() );
  11674. if ( m_config->showDurations() == ShowDurations::Always )
  11675. e.writeAttribute( "durationInSeconds", m_testCaseTimer.getElapsedSeconds() );
  11676. if( !testCaseStats.stdOut.empty() )
  11677. m_xml.scopedElement( "StdOut" ).writeText( trim( testCaseStats.stdOut ), false );
  11678. if( !testCaseStats.stdErr.empty() )
  11679. m_xml.scopedElement( "StdErr" ).writeText( trim( testCaseStats.stdErr ), false );
  11680. m_xml.endElement();
  11681. }
  11682. void XmlReporter::testGroupEnded( TestGroupStats const& testGroupStats ) {
  11683. StreamingReporterBase::testGroupEnded( testGroupStats );
  11684. // TODO: Check testGroupStats.aborting and act accordingly.
  11685. m_xml.scopedElement( "OverallResults" )
  11686. .writeAttribute( "successes", testGroupStats.totals.assertions.passed )
  11687. .writeAttribute( "failures", testGroupStats.totals.assertions.failed )
  11688. .writeAttribute( "expectedFailures", testGroupStats.totals.assertions.failedButOk );
  11689. m_xml.endElement();
  11690. }
  11691. void XmlReporter::testRunEnded( TestRunStats const& testRunStats ) {
  11692. StreamingReporterBase::testRunEnded( testRunStats );
  11693. m_xml.scopedElement( "OverallResults" )
  11694. .writeAttribute( "successes", testRunStats.totals.assertions.passed )
  11695. .writeAttribute( "failures", testRunStats.totals.assertions.failed )
  11696. .writeAttribute( "expectedFailures", testRunStats.totals.assertions.failedButOk );
  11697. m_xml.endElement();
  11698. }
  11699. CATCH_REGISTER_REPORTER( "xml", XmlReporter )
  11700. } // end namespace Catch
  11701. #if defined(_MSC_VER)
  11702. #pragma warning(pop)
  11703. #endif
  11704. // end catch_reporter_xml.cpp
  11705. namespace Catch {
  11706. LeakDetector leakDetector;
  11707. }
  11708. #ifdef __clang__
  11709. #pragma clang diagnostic pop
  11710. #endif
  11711. // end catch_impl.hpp
  11712. #endif
  11713. #ifdef CATCH_CONFIG_MAIN
  11714. // start catch_default_main.hpp
  11715. #ifndef __OBJC__
  11716. #if defined(CATCH_CONFIG_WCHAR) && defined(WIN32) && defined(_UNICODE) && !defined(DO_NOT_USE_WMAIN)
  11717. // Standard C/C++ Win32 Unicode wmain entry point
  11718. extern "C" int wmain (int argc, wchar_t * argv[], wchar_t * []) {
  11719. #else
  11720. // Standard C/C++ main entry point
  11721. int main (int argc, char * argv[]) {
  11722. #endif
  11723. return Catch::Session().run( argc, argv );
  11724. }
  11725. #else // __OBJC__
  11726. // Objective-C entry point
  11727. int main (int argc, char * const argv[]) {
  11728. #if !CATCH_ARC_ENABLED
  11729. NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
  11730. #endif
  11731. Catch::registerTestMethods();
  11732. int result = Catch::Session().run( argc, (char**)argv );
  11733. #if !CATCH_ARC_ENABLED
  11734. [pool drain];
  11735. #endif
  11736. return result;
  11737. }
  11738. #endif // __OBJC__
  11739. // end catch_default_main.hpp
  11740. #endif
  11741. #if !defined(CATCH_CONFIG_IMPL_ONLY)
  11742. #ifdef CLARA_CONFIG_MAIN_NOT_DEFINED
  11743. # undef CLARA_CONFIG_MAIN
  11744. #endif
  11745. #if !defined(CATCH_CONFIG_DISABLE)
  11746. //////
  11747. // If this config identifier is defined then all CATCH macros are prefixed with CATCH_
  11748. #ifdef CATCH_CONFIG_PREFIX_ALL
  11749. #define CATCH_REQUIRE( ... ) INTERNAL_CATCH_TEST( "CATCH_REQUIRE", Catch::ResultDisposition::Normal, __VA_ARGS__ )
  11750. #define CATCH_REQUIRE_FALSE( ... ) INTERNAL_CATCH_TEST( "CATCH_REQUIRE_FALSE", Catch::ResultDisposition::Normal | Catch::ResultDisposition::FalseTest, __VA_ARGS__ )
  11751. #define CATCH_REQUIRE_THROWS( ... ) INTERNAL_CATCH_THROWS( "CATCH_REQUIRE_THROWS", Catch::ResultDisposition::Normal, "", __VA_ARGS__ )
  11752. #define CATCH_REQUIRE_THROWS_AS( expr, exceptionType ) INTERNAL_CATCH_THROWS_AS( "CATCH_REQUIRE_THROWS_AS", exceptionType, Catch::ResultDisposition::Normal, expr )
  11753. #define CATCH_REQUIRE_THROWS_WITH( expr, matcher ) INTERNAL_CATCH_THROWS_STR_MATCHES( "CATCH_REQUIRE_THROWS_WITH", Catch::ResultDisposition::Normal, matcher, expr )
  11754. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  11755. #define CATCH_REQUIRE_THROWS_MATCHES( expr, exceptionType, matcher ) INTERNAL_CATCH_THROWS_MATCHES( "CATCH_REQUIRE_THROWS_MATCHES", exceptionType, Catch::ResultDisposition::Normal, matcher, expr )
  11756. #endif// CATCH_CONFIG_DISABLE_MATCHERS
  11757. #define CATCH_REQUIRE_NOTHROW( ... ) INTERNAL_CATCH_NO_THROW( "CATCH_REQUIRE_NOTHROW", Catch::ResultDisposition::Normal, __VA_ARGS__ )
  11758. #define CATCH_CHECK( ... ) INTERNAL_CATCH_TEST( "CATCH_CHECK", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  11759. #define CATCH_CHECK_FALSE( ... ) INTERNAL_CATCH_TEST( "CATCH_CHECK_FALSE", Catch::ResultDisposition::ContinueOnFailure | Catch::ResultDisposition::FalseTest, __VA_ARGS__ )
  11760. #define CATCH_CHECKED_IF( ... ) INTERNAL_CATCH_IF( "CATCH_CHECKED_IF", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  11761. #define CATCH_CHECKED_ELSE( ... ) INTERNAL_CATCH_ELSE( "CATCH_CHECKED_ELSE", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  11762. #define CATCH_CHECK_NOFAIL( ... ) INTERNAL_CATCH_TEST( "CATCH_CHECK_NOFAIL", Catch::ResultDisposition::ContinueOnFailure | Catch::ResultDisposition::SuppressFail, __VA_ARGS__ )
  11763. #define CATCH_CHECK_THROWS( ... ) INTERNAL_CATCH_THROWS( "CATCH_CHECK_THROWS", Catch::ResultDisposition::ContinueOnFailure, "", __VA_ARGS__ )
  11764. #define CATCH_CHECK_THROWS_AS( expr, exceptionType ) INTERNAL_CATCH_THROWS_AS( "CATCH_CHECK_THROWS_AS", exceptionType, Catch::ResultDisposition::ContinueOnFailure, expr )
  11765. #define CATCH_CHECK_THROWS_WITH( expr, matcher ) INTERNAL_CATCH_THROWS_STR_MATCHES( "CATCH_CHECK_THROWS_WITH", Catch::ResultDisposition::ContinueOnFailure, matcher, expr )
  11766. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  11767. #define CATCH_CHECK_THROWS_MATCHES( expr, exceptionType, matcher ) INTERNAL_CATCH_THROWS_MATCHES( "CATCH_CHECK_THROWS_MATCHES", exceptionType, Catch::ResultDisposition::ContinueOnFailure, matcher, expr )
  11768. #endif // CATCH_CONFIG_DISABLE_MATCHERS
  11769. #define CATCH_CHECK_NOTHROW( ... ) INTERNAL_CATCH_NO_THROW( "CATCH_CHECK_NOTHROW", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  11770. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  11771. #define CATCH_CHECK_THAT( arg, matcher ) INTERNAL_CHECK_THAT( "CATCH_CHECK_THAT", matcher, Catch::ResultDisposition::ContinueOnFailure, arg )
  11772. #define CATCH_REQUIRE_THAT( arg, matcher ) INTERNAL_CHECK_THAT( "CATCH_REQUIRE_THAT", matcher, Catch::ResultDisposition::Normal, arg )
  11773. #endif // CATCH_CONFIG_DISABLE_MATCHERS
  11774. #define CATCH_INFO( msg ) INTERNAL_CATCH_INFO( "CATCH_INFO", msg )
  11775. #define CATCH_WARN( msg ) INTERNAL_CATCH_MSG( "CATCH_WARN", Catch::ResultWas::Warning, Catch::ResultDisposition::ContinueOnFailure, msg )
  11776. #define CATCH_CAPTURE( ... ) INTERNAL_CATCH_CAPTURE( INTERNAL_CATCH_UNIQUE_NAME(capturer), "CATCH_CAPTURE",__VA_ARGS__ )
  11777. #define CATCH_TEST_CASE( ... ) INTERNAL_CATCH_TESTCASE( __VA_ARGS__ )
  11778. #define CATCH_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEST_CASE_METHOD( className, __VA_ARGS__ )
  11779. #define CATCH_METHOD_AS_TEST_CASE( method, ... ) INTERNAL_CATCH_METHOD_AS_TEST_CASE( method, __VA_ARGS__ )
  11780. #define CATCH_REGISTER_TEST_CASE( Function, ... ) INTERNAL_CATCH_REGISTER_TESTCASE( Function, __VA_ARGS__ )
  11781. #define CATCH_SECTION( ... ) INTERNAL_CATCH_SECTION( __VA_ARGS__ )
  11782. #define CATCH_DYNAMIC_SECTION( ... ) INTERNAL_CATCH_DYNAMIC_SECTION( __VA_ARGS__ )
  11783. #define CATCH_FAIL( ... ) INTERNAL_CATCH_MSG( "CATCH_FAIL", Catch::ResultWas::ExplicitFailure, Catch::ResultDisposition::Normal, __VA_ARGS__ )
  11784. #define CATCH_FAIL_CHECK( ... ) INTERNAL_CATCH_MSG( "CATCH_FAIL_CHECK", Catch::ResultWas::ExplicitFailure, Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  11785. #define CATCH_SUCCEED( ... ) INTERNAL_CATCH_MSG( "CATCH_SUCCEED", Catch::ResultWas::Ok, Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  11786. #define CATCH_ANON_TEST_CASE() INTERNAL_CATCH_TESTCASE()
  11787. #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
  11788. #define CATCH_TEMPLATE_TEST_CASE( ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE( __VA_ARGS__ )
  11789. #define CATCH_TEMPLATE_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ )
  11790. #define CATCH_TEMPLATE_PRODUCT_TEST_CASE( ... ) INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE( __VA_ARGS__ )
  11791. #define CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, __VA_ARGS__ )
  11792. #else
  11793. #define CATCH_TEMPLATE_TEST_CASE( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE( __VA_ARGS__ ) )
  11794. #define CATCH_TEMPLATE_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ ) )
  11795. #define CATCH_TEMPLATE_PRODUCT_TEST_CASE( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE( __VA_ARGS__ ) )
  11796. #define CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, __VA_ARGS__ ) )
  11797. #endif
  11798. #if !defined(CATCH_CONFIG_RUNTIME_STATIC_REQUIRE)
  11799. #define CATCH_STATIC_REQUIRE( ... ) static_assert( __VA_ARGS__ , #__VA_ARGS__ ); CATCH_SUCCEED( #__VA_ARGS__ )
  11800. #define CATCH_STATIC_REQUIRE_FALSE( ... ) static_assert( !(__VA_ARGS__), "!(" #__VA_ARGS__ ")" ); CATCH_SUCCEED( #__VA_ARGS__ )
  11801. #else
  11802. #define CATCH_STATIC_REQUIRE( ... ) CATCH_REQUIRE( __VA_ARGS__ )
  11803. #define CATCH_STATIC_REQUIRE_FALSE( ... ) CATCH_REQUIRE_FALSE( __VA_ARGS__ )
  11804. #endif
  11805. // "BDD-style" convenience wrappers
  11806. #define CATCH_SCENARIO( ... ) CATCH_TEST_CASE( "Scenario: " __VA_ARGS__ )
  11807. #define CATCH_SCENARIO_METHOD( className, ... ) INTERNAL_CATCH_TEST_CASE_METHOD( className, "Scenario: " __VA_ARGS__ )
  11808. #define CATCH_GIVEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " Given: " << desc )
  11809. #define CATCH_AND_GIVEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( "And given: " << desc )
  11810. #define CATCH_WHEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " When: " << desc )
  11811. #define CATCH_AND_WHEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " And when: " << desc )
  11812. #define CATCH_THEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " Then: " << desc )
  11813. #define CATCH_AND_THEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " And: " << desc )
  11814. // If CATCH_CONFIG_PREFIX_ALL is not defined then the CATCH_ prefix is not required
  11815. #else
  11816. #define REQUIRE( ... ) INTERNAL_CATCH_TEST( "REQUIRE", Catch::ResultDisposition::Normal, __VA_ARGS__ )
  11817. #define REQUIRE_FALSE( ... ) INTERNAL_CATCH_TEST( "REQUIRE_FALSE", Catch::ResultDisposition::Normal | Catch::ResultDisposition::FalseTest, __VA_ARGS__ )
  11818. #define REQUIRE_THROWS( ... ) INTERNAL_CATCH_THROWS( "REQUIRE_THROWS", Catch::ResultDisposition::Normal, __VA_ARGS__ )
  11819. #define REQUIRE_THROWS_AS( expr, exceptionType ) INTERNAL_CATCH_THROWS_AS( "REQUIRE_THROWS_AS", exceptionType, Catch::ResultDisposition::Normal, expr )
  11820. #define REQUIRE_THROWS_WITH( expr, matcher ) INTERNAL_CATCH_THROWS_STR_MATCHES( "REQUIRE_THROWS_WITH", Catch::ResultDisposition::Normal, matcher, expr )
  11821. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  11822. #define REQUIRE_THROWS_MATCHES( expr, exceptionType, matcher ) INTERNAL_CATCH_THROWS_MATCHES( "REQUIRE_THROWS_MATCHES", exceptionType, Catch::ResultDisposition::Normal, matcher, expr )
  11823. #endif // CATCH_CONFIG_DISABLE_MATCHERS
  11824. #define REQUIRE_NOTHROW( ... ) INTERNAL_CATCH_NO_THROW( "REQUIRE_NOTHROW", Catch::ResultDisposition::Normal, __VA_ARGS__ )
  11825. #define CHECK( ... ) INTERNAL_CATCH_TEST( "CHECK", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  11826. #define CHECK_FALSE( ... ) INTERNAL_CATCH_TEST( "CHECK_FALSE", Catch::ResultDisposition::ContinueOnFailure | Catch::ResultDisposition::FalseTest, __VA_ARGS__ )
  11827. #define CHECKED_IF( ... ) INTERNAL_CATCH_IF( "CHECKED_IF", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  11828. #define CHECKED_ELSE( ... ) INTERNAL_CATCH_ELSE( "CHECKED_ELSE", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  11829. #define CHECK_NOFAIL( ... ) INTERNAL_CATCH_TEST( "CHECK_NOFAIL", Catch::ResultDisposition::ContinueOnFailure | Catch::ResultDisposition::SuppressFail, __VA_ARGS__ )
  11830. #define CHECK_THROWS( ... ) INTERNAL_CATCH_THROWS( "CHECK_THROWS", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  11831. #define CHECK_THROWS_AS( expr, exceptionType ) INTERNAL_CATCH_THROWS_AS( "CHECK_THROWS_AS", exceptionType, Catch::ResultDisposition::ContinueOnFailure, expr )
  11832. #define CHECK_THROWS_WITH( expr, matcher ) INTERNAL_CATCH_THROWS_STR_MATCHES( "CHECK_THROWS_WITH", Catch::ResultDisposition::ContinueOnFailure, matcher, expr )
  11833. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  11834. #define CHECK_THROWS_MATCHES( expr, exceptionType, matcher ) INTERNAL_CATCH_THROWS_MATCHES( "CHECK_THROWS_MATCHES", exceptionType, Catch::ResultDisposition::ContinueOnFailure, matcher, expr )
  11835. #endif // CATCH_CONFIG_DISABLE_MATCHERS
  11836. #define CHECK_NOTHROW( ... ) INTERNAL_CATCH_NO_THROW( "CHECK_NOTHROW", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  11837. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  11838. #define CHECK_THAT( arg, matcher ) INTERNAL_CHECK_THAT( "CHECK_THAT", matcher, Catch::ResultDisposition::ContinueOnFailure, arg )
  11839. #define REQUIRE_THAT( arg, matcher ) INTERNAL_CHECK_THAT( "REQUIRE_THAT", matcher, Catch::ResultDisposition::Normal, arg )
  11840. #endif // CATCH_CONFIG_DISABLE_MATCHERS
  11841. #define INFO( msg ) INTERNAL_CATCH_INFO( "INFO", msg )
  11842. #define WARN( msg ) INTERNAL_CATCH_MSG( "WARN", Catch::ResultWas::Warning, Catch::ResultDisposition::ContinueOnFailure, msg )
  11843. #define CAPTURE( ... ) INTERNAL_CATCH_CAPTURE( INTERNAL_CATCH_UNIQUE_NAME(capturer), "CAPTURE",__VA_ARGS__ )
  11844. #define TEST_CASE( ... ) INTERNAL_CATCH_TESTCASE( __VA_ARGS__ )
  11845. #define TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEST_CASE_METHOD( className, __VA_ARGS__ )
  11846. #define METHOD_AS_TEST_CASE( method, ... ) INTERNAL_CATCH_METHOD_AS_TEST_CASE( method, __VA_ARGS__ )
  11847. #define REGISTER_TEST_CASE( Function, ... ) INTERNAL_CATCH_REGISTER_TESTCASE( Function, __VA_ARGS__ )
  11848. #define SECTION( ... ) INTERNAL_CATCH_SECTION( __VA_ARGS__ )
  11849. #define DYNAMIC_SECTION( ... ) INTERNAL_CATCH_DYNAMIC_SECTION( __VA_ARGS__ )
  11850. #define FAIL( ... ) INTERNAL_CATCH_MSG( "FAIL", Catch::ResultWas::ExplicitFailure, Catch::ResultDisposition::Normal, __VA_ARGS__ )
  11851. #define FAIL_CHECK( ... ) INTERNAL_CATCH_MSG( "FAIL_CHECK", Catch::ResultWas::ExplicitFailure, Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  11852. #define SUCCEED( ... ) INTERNAL_CATCH_MSG( "SUCCEED", Catch::ResultWas::Ok, Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  11853. #define ANON_TEST_CASE() INTERNAL_CATCH_TESTCASE()
  11854. #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
  11855. #define TEMPLATE_TEST_CASE( ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE( __VA_ARGS__ )
  11856. #define TEMPLATE_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ )
  11857. #define TEMPLATE_PRODUCT_TEST_CASE( ... ) INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE( __VA_ARGS__ )
  11858. #define TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, __VA_ARGS__ )
  11859. #else
  11860. #define TEMPLATE_TEST_CASE( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE( __VA_ARGS__ ) )
  11861. #define TEMPLATE_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ ) )
  11862. #define TEMPLATE_PRODUCT_TEST_CASE( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE( __VA_ARGS__ ) )
  11863. #define TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, __VA_ARGS__ ) )
  11864. #endif
  11865. #if !defined(CATCH_CONFIG_RUNTIME_STATIC_REQUIRE)
  11866. #define STATIC_REQUIRE( ... ) static_assert( __VA_ARGS__, #__VA_ARGS__ ); SUCCEED( #__VA_ARGS__ )
  11867. #define STATIC_REQUIRE_FALSE( ... ) static_assert( !(__VA_ARGS__), "!(" #__VA_ARGS__ ")" ); SUCCEED( "!(" #__VA_ARGS__ ")" )
  11868. #else
  11869. #define STATIC_REQUIRE( ... ) REQUIRE( __VA_ARGS__ )
  11870. #define STATIC_REQUIRE_FALSE( ... ) REQUIRE_FALSE( __VA_ARGS__ )
  11871. #endif
  11872. #endif
  11873. #define CATCH_TRANSLATE_EXCEPTION( signature ) INTERNAL_CATCH_TRANSLATE_EXCEPTION( signature )
  11874. // "BDD-style" convenience wrappers
  11875. #define SCENARIO( ... ) TEST_CASE( "Scenario: " __VA_ARGS__ )
  11876. #define SCENARIO_METHOD( className, ... ) INTERNAL_CATCH_TEST_CASE_METHOD( className, "Scenario: " __VA_ARGS__ )
  11877. #define GIVEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " Given: " << desc )
  11878. #define AND_GIVEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( "And given: " << desc )
  11879. #define WHEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " When: " << desc )
  11880. #define AND_WHEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " And when: " << desc )
  11881. #define THEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " Then: " << desc )
  11882. #define AND_THEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " And: " << desc )
  11883. using Catch::Detail::Approx;
  11884. #else // CATCH_CONFIG_DISABLE
  11885. //////
  11886. // If this config identifier is defined then all CATCH macros are prefixed with CATCH_
  11887. #ifdef CATCH_CONFIG_PREFIX_ALL
  11888. #define CATCH_REQUIRE( ... ) (void)(0)
  11889. #define CATCH_REQUIRE_FALSE( ... ) (void)(0)
  11890. #define CATCH_REQUIRE_THROWS( ... ) (void)(0)
  11891. #define CATCH_REQUIRE_THROWS_AS( expr, exceptionType ) (void)(0)
  11892. #define CATCH_REQUIRE_THROWS_WITH( expr, matcher ) (void)(0)
  11893. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  11894. #define CATCH_REQUIRE_THROWS_MATCHES( expr, exceptionType, matcher ) (void)(0)
  11895. #endif// CATCH_CONFIG_DISABLE_MATCHERS
  11896. #define CATCH_REQUIRE_NOTHROW( ... ) (void)(0)
  11897. #define CATCH_CHECK( ... ) (void)(0)
  11898. #define CATCH_CHECK_FALSE( ... ) (void)(0)
  11899. #define CATCH_CHECKED_IF( ... ) if (__VA_ARGS__)
  11900. #define CATCH_CHECKED_ELSE( ... ) if (!(__VA_ARGS__))
  11901. #define CATCH_CHECK_NOFAIL( ... ) (void)(0)
  11902. #define CATCH_CHECK_THROWS( ... ) (void)(0)
  11903. #define CATCH_CHECK_THROWS_AS( expr, exceptionType ) (void)(0)
  11904. #define CATCH_CHECK_THROWS_WITH( expr, matcher ) (void)(0)
  11905. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  11906. #define CATCH_CHECK_THROWS_MATCHES( expr, exceptionType, matcher ) (void)(0)
  11907. #endif // CATCH_CONFIG_DISABLE_MATCHERS
  11908. #define CATCH_CHECK_NOTHROW( ... ) (void)(0)
  11909. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  11910. #define CATCH_CHECK_THAT( arg, matcher ) (void)(0)
  11911. #define CATCH_REQUIRE_THAT( arg, matcher ) (void)(0)
  11912. #endif // CATCH_CONFIG_DISABLE_MATCHERS
  11913. #define CATCH_INFO( msg ) (void)(0)
  11914. #define CATCH_WARN( msg ) (void)(0)
  11915. #define CATCH_CAPTURE( msg ) (void)(0)
  11916. #define CATCH_TEST_CASE( ... ) INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ))
  11917. #define CATCH_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ))
  11918. #define CATCH_METHOD_AS_TEST_CASE( method, ... )
  11919. #define CATCH_REGISTER_TEST_CASE( Function, ... ) (void)(0)
  11920. #define CATCH_SECTION( ... )
  11921. #define CATCH_DYNAMIC_SECTION( ... )
  11922. #define CATCH_FAIL( ... ) (void)(0)
  11923. #define CATCH_FAIL_CHECK( ... ) (void)(0)
  11924. #define CATCH_SUCCEED( ... ) (void)(0)
  11925. #define CATCH_ANON_TEST_CASE() INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ))
  11926. #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
  11927. #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____ ) )
  11928. #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 )
  11929. #define CATCH_TEMPLATE_PRODUCT_TEST_CASE( ... ) CATCH_TEMPLATE_TEST_CASE( __VA_ARGS__ )
  11930. #define CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, ... ) CATCH_TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ )
  11931. #else
  11932. #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____ ) ) )
  11933. #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 ) )
  11934. #define CATCH_TEMPLATE_PRODUCT_TEST_CASE( ... ) CATCH_TEMPLATE_TEST_CASE( __VA_ARGS__ )
  11935. #define CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, ... ) CATCH_TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ )
  11936. #endif
  11937. // "BDD-style" convenience wrappers
  11938. #define CATCH_SCENARIO( ... ) INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ))
  11939. #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 )
  11940. #define CATCH_GIVEN( desc )
  11941. #define CATCH_AND_GIVEN( desc )
  11942. #define CATCH_WHEN( desc )
  11943. #define CATCH_AND_WHEN( desc )
  11944. #define CATCH_THEN( desc )
  11945. #define CATCH_AND_THEN( desc )
  11946. #define CATCH_STATIC_REQUIRE( ... ) (void)(0)
  11947. #define CATCH_STATIC_REQUIRE_FALSE( ... ) (void)(0)
  11948. // If CATCH_CONFIG_PREFIX_ALL is not defined then the CATCH_ prefix is not required
  11949. #else
  11950. #define REQUIRE( ... ) (void)(0)
  11951. #define REQUIRE_FALSE( ... ) (void)(0)
  11952. #define REQUIRE_THROWS( ... ) (void)(0)
  11953. #define REQUIRE_THROWS_AS( expr, exceptionType ) (void)(0)
  11954. #define REQUIRE_THROWS_WITH( expr, matcher ) (void)(0)
  11955. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  11956. #define REQUIRE_THROWS_MATCHES( expr, exceptionType, matcher ) (void)(0)
  11957. #endif // CATCH_CONFIG_DISABLE_MATCHERS
  11958. #define REQUIRE_NOTHROW( ... ) (void)(0)
  11959. #define CHECK( ... ) (void)(0)
  11960. #define CHECK_FALSE( ... ) (void)(0)
  11961. #define CHECKED_IF( ... ) if (__VA_ARGS__)
  11962. #define CHECKED_ELSE( ... ) if (!(__VA_ARGS__))
  11963. #define CHECK_NOFAIL( ... ) (void)(0)
  11964. #define CHECK_THROWS( ... ) (void)(0)
  11965. #define CHECK_THROWS_AS( expr, exceptionType ) (void)(0)
  11966. #define CHECK_THROWS_WITH( expr, matcher ) (void)(0)
  11967. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  11968. #define CHECK_THROWS_MATCHES( expr, exceptionType, matcher ) (void)(0)
  11969. #endif // CATCH_CONFIG_DISABLE_MATCHERS
  11970. #define CHECK_NOTHROW( ... ) (void)(0)
  11971. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  11972. #define CHECK_THAT( arg, matcher ) (void)(0)
  11973. #define REQUIRE_THAT( arg, matcher ) (void)(0)
  11974. #endif // CATCH_CONFIG_DISABLE_MATCHERS
  11975. #define INFO( msg ) (void)(0)
  11976. #define WARN( msg ) (void)(0)
  11977. #define CAPTURE( msg ) (void)(0)
  11978. #define TEST_CASE( ... ) INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ))
  11979. #define TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ))
  11980. #define METHOD_AS_TEST_CASE( method, ... )
  11981. #define REGISTER_TEST_CASE( Function, ... ) (void)(0)
  11982. #define SECTION( ... )
  11983. #define DYNAMIC_SECTION( ... )
  11984. #define FAIL( ... ) (void)(0)
  11985. #define FAIL_CHECK( ... ) (void)(0)
  11986. #define SUCCEED( ... ) (void)(0)
  11987. #define ANON_TEST_CASE() INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ))
  11988. #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
  11989. #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____ ) )
  11990. #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 )
  11991. #define TEMPLATE_PRODUCT_TEST_CASE( ... ) TEMPLATE_TEST_CASE( __VA_ARGS__ )
  11992. #define TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, ... ) TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ )
  11993. #else
  11994. #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____ ) ) )
  11995. #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 ) )
  11996. #define TEMPLATE_PRODUCT_TEST_CASE( ... ) TEMPLATE_TEST_CASE( __VA_ARGS__ )
  11997. #define TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, ... ) TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ )
  11998. #endif
  11999. #define STATIC_REQUIRE( ... ) (void)(0)
  12000. #define STATIC_REQUIRE_FALSE( ... ) (void)(0)
  12001. #endif
  12002. #define CATCH_TRANSLATE_EXCEPTION( signature ) INTERNAL_CATCH_TRANSLATE_EXCEPTION_NO_REG( INTERNAL_CATCH_UNIQUE_NAME( catch_internal_ExceptionTranslator ), signature )
  12003. // "BDD-style" convenience wrappers
  12004. #define SCENARIO( ... ) INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ) )
  12005. #define SCENARIO_METHOD( className, ... ) INTERNAL_CATCH_TESTCASE_METHOD_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ), className )
  12006. #define GIVEN( desc )
  12007. #define AND_GIVEN( desc )
  12008. #define WHEN( desc )
  12009. #define AND_WHEN( desc )
  12010. #define THEN( desc )
  12011. #define AND_THEN( desc )
  12012. using Catch::Detail::Approx;
  12013. #endif
  12014. #endif // ! CATCH_CONFIG_IMPL_ONLY
  12015. // start catch_reenable_warnings.h
  12016. #ifdef __clang__
  12017. # ifdef __ICC // icpc defines the __clang__ macro
  12018. # pragma warning(pop)
  12019. # else
  12020. # pragma clang diagnostic pop
  12021. # endif
  12022. #elif defined __GNUC__
  12023. # pragma GCC diagnostic pop
  12024. #endif
  12025. // end catch_reenable_warnings.h
  12026. // end catch.hpp
  12027. #endif // TWOBLUECUBES_SINGLE_INCLUDE_CATCH_HPP_INCLUDED