You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

14021 lines
466KB

  1. /*
  2. * Catch v2.4.1
  3. * Generated: 2018-09-28 15:50:15.645795
  4. * ----------------------------------------------------------
  5. * This file has been merged from multiple headers. Please don't edit it directly
  6. * Copyright (c) 2018 Two Blue Cubes Ltd. All rights reserved.
  7. *
  8. * Distributed under the Boost Software License, Version 1.0. (See accompanying
  9. * file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
  10. */
  11. #ifndef TWOBLUECUBES_SINGLE_INCLUDE_CATCH_HPP_INCLUDED
  12. #define TWOBLUECUBES_SINGLE_INCLUDE_CATCH_HPP_INCLUDED
  13. // start catch.hpp
  14. #define CATCH_VERSION_MAJOR 2
  15. #define CATCH_VERSION_MINOR 4
  16. #define CATCH_VERSION_PATCH 1
  17. #ifdef __clang__
  18. # pragma clang system_header
  19. #elif defined __GNUC__
  20. # pragma GCC system_header
  21. #endif
  22. // start catch_suppress_warnings.h
  23. #ifdef __clang__
  24. # ifdef __ICC // icpc defines the __clang__ macro
  25. # pragma warning(push)
  26. # pragma warning(disable: 161 1682)
  27. # else // __ICC
  28. # pragma clang diagnostic push
  29. # pragma clang diagnostic ignored "-Wpadded"
  30. # pragma clang diagnostic ignored "-Wswitch-enum"
  31. # pragma clang diagnostic ignored "-Wcovered-switch-default"
  32. # endif
  33. #elif defined __GNUC__
  34. // GCC likes to warn on REQUIREs, and we cannot suppress them
  35. // locally because g++'s support for _Pragma is lacking in older,
  36. // still supported, versions
  37. # pragma GCC diagnostic ignored "-Wparentheses"
  38. # pragma GCC diagnostic push
  39. # pragma GCC diagnostic ignored "-Wunused-variable"
  40. # pragma GCC diagnostic ignored "-Wpadded"
  41. #endif
  42. // end catch_suppress_warnings.h
  43. #if defined(CATCH_CONFIG_MAIN) || defined(CATCH_CONFIG_RUNNER)
  44. # define CATCH_IMPL
  45. # define CATCH_CONFIG_ALL_PARTS
  46. #endif
  47. // In the impl file, we want to have access to all parts of the headers
  48. // Can also be used to sanely support PCHs
  49. #if defined(CATCH_CONFIG_ALL_PARTS)
  50. # define CATCH_CONFIG_EXTERNAL_INTERFACES
  51. # if defined(CATCH_CONFIG_DISABLE_MATCHERS)
  52. # undef CATCH_CONFIG_DISABLE_MATCHERS
  53. # endif
  54. # if !defined(CATCH_CONFIG_ENABLE_CHRONO_STRINGMAKER)
  55. # define CATCH_CONFIG_ENABLE_CHRONO_STRINGMAKER
  56. # endif
  57. #endif
  58. #if !defined(CATCH_CONFIG_IMPL_ONLY)
  59. // start catch_platform.h
  60. #ifdef __APPLE__
  61. # include <TargetConditionals.h>
  62. # if TARGET_OS_OSX == 1
  63. # define CATCH_PLATFORM_MAC
  64. # elif TARGET_OS_IPHONE == 1
  65. # define CATCH_PLATFORM_IPHONE
  66. # endif
  67. #elif defined(linux) || defined(__linux) || defined(__linux__)
  68. # define CATCH_PLATFORM_LINUX
  69. #elif defined(WIN32) || defined(__WIN32__) || defined(_WIN32) || defined(_MSC_VER) || defined(__MINGW32__)
  70. # define CATCH_PLATFORM_WINDOWS
  71. #endif
  72. // end catch_platform.h
  73. #ifdef CATCH_IMPL
  74. # ifndef CLARA_CONFIG_MAIN
  75. # define CLARA_CONFIG_MAIN_NOT_DEFINED
  76. # define CLARA_CONFIG_MAIN
  77. # endif
  78. #endif
  79. // start catch_user_interfaces.h
  80. namespace Catch {
  81. unsigned int rngSeed();
  82. }
  83. // end catch_user_interfaces.h
  84. // start catch_tag_alias_autoregistrar.h
  85. // start catch_common.h
  86. // start catch_compiler_capabilities.h
  87. // Detect a number of compiler features - by compiler
  88. // The following features are defined:
  89. //
  90. // CATCH_CONFIG_COUNTER : is the __COUNTER__ macro supported?
  91. // CATCH_CONFIG_WINDOWS_SEH : is Windows SEH supported?
  92. // CATCH_CONFIG_POSIX_SIGNALS : are POSIX signals supported?
  93. // CATCH_CONFIG_DISABLE_EXCEPTIONS : Are exceptions enabled?
  94. // ****************
  95. // Note to maintainers: if new toggles are added please document them
  96. // in configuration.md, too
  97. // ****************
  98. // In general each macro has a _NO_<feature name> form
  99. // (e.g. CATCH_CONFIG_NO_POSIX_SIGNALS) which disables the feature.
  100. // Many features, at point of detection, define an _INTERNAL_ macro, so they
  101. // can be combined, en-mass, with the _NO_ forms later.
  102. #ifdef __cplusplus
  103. # if (__cplusplus >= 201402L) || (defined(_MSVC_LANG) && _MSVC_LANG >= 201402L)
  104. # define CATCH_CPP14_OR_GREATER
  105. # endif
  106. # if (__cplusplus >= 201703L) || (defined(_MSVC_LANG) && _MSVC_LANG >= 201703L)
  107. # define CATCH_CPP17_OR_GREATER
  108. # endif
  109. #endif
  110. #if defined(CATCH_CPP17_OR_GREATER)
  111. # define CATCH_INTERNAL_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS
  112. #endif
  113. #ifdef __clang__
  114. # define CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
  115. _Pragma( "clang diagnostic push" ) \
  116. _Pragma( "clang diagnostic ignored \"-Wexit-time-destructors\"" ) \
  117. _Pragma( "clang diagnostic ignored \"-Wglobal-constructors\"")
  118. # define CATCH_INTERNAL_UNSUPPRESS_GLOBALS_WARNINGS \
  119. _Pragma( "clang diagnostic pop" )
  120. # define CATCH_INTERNAL_SUPPRESS_PARENTHESES_WARNINGS \
  121. _Pragma( "clang diagnostic push" ) \
  122. _Pragma( "clang diagnostic ignored \"-Wparentheses\"" )
  123. # define CATCH_INTERNAL_UNSUPPRESS_PARENTHESES_WARNINGS \
  124. _Pragma( "clang diagnostic pop" )
  125. # define CATCH_INTERNAL_SUPPRESS_UNUSED_WARNINGS \
  126. _Pragma( "clang diagnostic push" ) \
  127. _Pragma( "clang diagnostic ignored \"-Wunused-variable\"" )
  128. # define CATCH_INTERNAL_UNSUPPRESS_UNUSED_WARNINGS \
  129. _Pragma( "clang diagnostic pop" )
  130. #endif // __clang__
  131. ////////////////////////////////////////////////////////////////////////////////
  132. // Assume that non-Windows platforms support posix signals by default
  133. #if !defined(CATCH_PLATFORM_WINDOWS)
  134. #define CATCH_INTERNAL_CONFIG_POSIX_SIGNALS
  135. #endif
  136. ////////////////////////////////////////////////////////////////////////////////
  137. // We know some environments not to support full POSIX signals
  138. #if defined(__CYGWIN__) || defined(__QNX__) || defined(__EMSCRIPTEN__) || defined(__DJGPP__)
  139. #define CATCH_INTERNAL_CONFIG_NO_POSIX_SIGNALS
  140. #endif
  141. #ifdef __OS400__
  142. # define CATCH_INTERNAL_CONFIG_NO_POSIX_SIGNALS
  143. # define CATCH_CONFIG_COLOUR_NONE
  144. #endif
  145. ////////////////////////////////////////////////////////////////////////////////
  146. // Android somehow still does not support std::to_string
  147. #if defined(__ANDROID__)
  148. # define CATCH_INTERNAL_CONFIG_NO_CPP11_TO_STRING
  149. #endif
  150. ////////////////////////////////////////////////////////////////////////////////
  151. // Not all Windows environments support SEH properly
  152. #if defined(__MINGW32__)
  153. # define CATCH_INTERNAL_CONFIG_NO_WINDOWS_SEH
  154. #endif
  155. ////////////////////////////////////////////////////////////////////////////////
  156. // PS4
  157. #if defined(__ORBIS__)
  158. # define CATCH_INTERNAL_CONFIG_NO_NEW_CAPTURE
  159. #endif
  160. ////////////////////////////////////////////////////////////////////////////////
  161. // Cygwin
  162. #ifdef __CYGWIN__
  163. // Required for some versions of Cygwin to declare gettimeofday
  164. // see: http://stackoverflow.com/questions/36901803/gettimeofday-not-declared-in-this-scope-cygwin
  165. # define _BSD_SOURCE
  166. // some versions of cygwin (most) do not support std::to_string. Use the libstd check.
  167. // https://gcc.gnu.org/onlinedocs/gcc-4.8.2/libstdc++/api/a01053_source.html line 2812-2813
  168. # if !((__cplusplus >= 201103L) && defined(_GLIBCXX_USE_C99) \
  169. && !defined(_GLIBCXX_HAVE_BROKEN_VSWPRINTF))
  170. # define CATCH_INTERNAL_CONFIG_NO_CPP11_TO_STRING
  171. # endif
  172. #endif // __CYGWIN__
  173. ////////////////////////////////////////////////////////////////////////////////
  174. // Visual C++
  175. #ifdef _MSC_VER
  176. # if _MSC_VER >= 1900 // Visual Studio 2015 or newer
  177. # define CATCH_INTERNAL_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS
  178. # endif
  179. // Universal Windows platform does not support SEH
  180. // Or console colours (or console at all...)
  181. # if defined(WINAPI_FAMILY) && (WINAPI_FAMILY == WINAPI_FAMILY_APP)
  182. # define CATCH_CONFIG_COLOUR_NONE
  183. # else
  184. # define CATCH_INTERNAL_CONFIG_WINDOWS_SEH
  185. # endif
  186. #endif // _MSC_VER
  187. ////////////////////////////////////////////////////////////////////////////////
  188. // Check if we are compiled with -fno-exceptions or equivalent
  189. #if defined(__EXCEPTIONS) || defined(__cpp_exceptions) || defined(_CPPUNWIND)
  190. # define CATCH_INTERNAL_CONFIG_EXCEPTIONS_ENABLED
  191. #endif
  192. ////////////////////////////////////////////////////////////////////////////////
  193. // DJGPP
  194. #ifdef __DJGPP__
  195. # define CATCH_INTERNAL_CONFIG_NO_WCHAR
  196. #endif // __DJGPP__
  197. ////////////////////////////////////////////////////////////////////////////////
  198. // Use of __COUNTER__ is suppressed during code analysis in
  199. // CLion/AppCode 2017.2.x and former, because __COUNTER__ is not properly
  200. // handled by it.
  201. // Otherwise all supported compilers support COUNTER macro,
  202. // but user still might want to turn it off
  203. #if ( !defined(__JETBRAINS_IDE__) || __JETBRAINS_IDE__ >= 20170300L )
  204. #define CATCH_INTERNAL_CONFIG_COUNTER
  205. #endif
  206. ////////////////////////////////////////////////////////////////////////////////
  207. // Check if string_view is available and usable
  208. // The check is split apart to work around v140 (VS2015) preprocessor issue...
  209. #if defined(__has_include)
  210. #if __has_include(<string_view>) && defined(CATCH_CPP17_OR_GREATER)
  211. # define CATCH_INTERNAL_CONFIG_CPP17_STRING_VIEW
  212. #endif
  213. #endif
  214. ////////////////////////////////////////////////////////////////////////////////
  215. // Check if variant is available and usable
  216. #if defined(__has_include)
  217. # if __has_include(<variant>) && defined(CATCH_CPP17_OR_GREATER)
  218. # if defined(__clang__) && (__clang_major__ < 8)
  219. // work around clang bug with libstdc++ https://bugs.llvm.org/show_bug.cgi?id=31852
  220. // fix should be in clang 8, workaround in libstdc++ 8.2
  221. # include <ciso646>
  222. # if defined(__GLIBCXX__) && defined(_GLIBCXX_RELEASE) && (_GLIBCXX_RELEASE < 9)
  223. # define CATCH_CONFIG_NO_CPP17_VARIANT
  224. # else
  225. # define CATCH_INTERNAL_CONFIG_CPP17_VARIANT
  226. # endif // defined(__GLIBCXX__) && defined(_GLIBCXX_RELEASE) && (_GLIBCXX_RELEASE < 9)
  227. # endif // defined(__clang__) && (__clang_major__ < 8)
  228. # endif // __has_include(<variant>) && defined(CATCH_CPP17_OR_GREATER)
  229. #endif // __has_include
  230. #if defined(CATCH_INTERNAL_CONFIG_COUNTER) && !defined(CATCH_CONFIG_NO_COUNTER) && !defined(CATCH_CONFIG_COUNTER)
  231. # define CATCH_CONFIG_COUNTER
  232. #endif
  233. #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)
  234. # define CATCH_CONFIG_WINDOWS_SEH
  235. #endif
  236. // This is set by default, because we assume that unix compilers are posix-signal-compatible by default.
  237. #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)
  238. # define CATCH_CONFIG_POSIX_SIGNALS
  239. #endif
  240. // This is set by default, because we assume that compilers with no wchar_t support are just rare exceptions.
  241. #if !defined(CATCH_INTERNAL_CONFIG_NO_WCHAR) && !defined(CATCH_CONFIG_NO_WCHAR) && !defined(CATCH_CONFIG_WCHAR)
  242. # define CATCH_CONFIG_WCHAR
  243. #endif
  244. #if !defined(CATCH_INTERNAL_CONFIG_NO_CPP11_TO_STRING) && !defined(CATCH_CONFIG_NO_CPP11_TO_STRING) && !defined(CATCH_CONFIG_CPP11_TO_STRING)
  245. # define CATCH_CONFIG_CPP11_TO_STRING
  246. #endif
  247. #if defined(CATCH_INTERNAL_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS) && !defined(CATCH_CONFIG_NO_CPP17_UNCAUGHT_EXCEPTIONS) && !defined(CATCH_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS)
  248. # define CATCH_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS
  249. #endif
  250. #if defined(CATCH_INTERNAL_CONFIG_CPP17_STRING_VIEW) && !defined(CATCH_CONFIG_NO_CPP17_STRING_VIEW) && !defined(CATCH_CONFIG_CPP17_STRING_VIEW)
  251. # define CATCH_CONFIG_CPP17_STRING_VIEW
  252. #endif
  253. #if defined(CATCH_INTERNAL_CONFIG_CPP17_VARIANT) && !defined(CATCH_CONFIG_NO_CPP17_VARIANT) && !defined(CATCH_CONFIG_CPP17_VARIANT)
  254. # define CATCH_CONFIG_CPP17_VARIANT
  255. #endif
  256. #if defined(CATCH_CONFIG_EXPERIMENTAL_REDIRECT)
  257. # define CATCH_INTERNAL_CONFIG_NEW_CAPTURE
  258. #endif
  259. #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)
  260. # define CATCH_CONFIG_NEW_CAPTURE
  261. #endif
  262. #if !defined(CATCH_INTERNAL_CONFIG_EXCEPTIONS_ENABLED) && !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
  263. # define CATCH_CONFIG_DISABLE_EXCEPTIONS
  264. #endif
  265. #if !defined(CATCH_INTERNAL_SUPPRESS_PARENTHESES_WARNINGS)
  266. # define CATCH_INTERNAL_SUPPRESS_PARENTHESES_WARNINGS
  267. # define CATCH_INTERNAL_UNSUPPRESS_PARENTHESES_WARNINGS
  268. #endif
  269. #if !defined(CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS)
  270. # define CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS
  271. # define CATCH_INTERNAL_UNSUPPRESS_GLOBALS_WARNINGS
  272. #endif
  273. #if !defined(CATCH_INTERNAL_SUPPRESS_UNUSED_WARNINGS)
  274. # define CATCH_INTERNAL_SUPPRESS_UNUSED_WARNINGS
  275. # define CATCH_INTERNAL_UNSUPPRESS_UNUSED_WARNINGS
  276. #endif
  277. #if defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
  278. #define CATCH_TRY if ((true))
  279. #define CATCH_CATCH_ALL if ((false))
  280. #define CATCH_CATCH_ANON(type) if ((false))
  281. #else
  282. #define CATCH_TRY try
  283. #define CATCH_CATCH_ALL catch (...)
  284. #define CATCH_CATCH_ANON(type) catch (type)
  285. #endif
  286. // end catch_compiler_capabilities.h
  287. #define INTERNAL_CATCH_UNIQUE_NAME_LINE2( name, line ) name##line
  288. #define INTERNAL_CATCH_UNIQUE_NAME_LINE( name, line ) INTERNAL_CATCH_UNIQUE_NAME_LINE2( name, line )
  289. #ifdef CATCH_CONFIG_COUNTER
  290. # define INTERNAL_CATCH_UNIQUE_NAME( name ) INTERNAL_CATCH_UNIQUE_NAME_LINE( name, __COUNTER__ )
  291. #else
  292. # define INTERNAL_CATCH_UNIQUE_NAME( name ) INTERNAL_CATCH_UNIQUE_NAME_LINE( name, __LINE__ )
  293. #endif
  294. #include <iosfwd>
  295. #include <string>
  296. #include <cstdint>
  297. namespace Catch {
  298. struct CaseSensitive { enum Choice {
  299. Yes,
  300. No
  301. }; };
  302. class NonCopyable {
  303. NonCopyable( NonCopyable const& ) = delete;
  304. NonCopyable( NonCopyable && ) = delete;
  305. NonCopyable& operator = ( NonCopyable const& ) = delete;
  306. NonCopyable& operator = ( NonCopyable && ) = delete;
  307. protected:
  308. NonCopyable();
  309. virtual ~NonCopyable();
  310. };
  311. struct SourceLineInfo {
  312. SourceLineInfo() = delete;
  313. SourceLineInfo( char const* _file, std::size_t _line ) noexcept
  314. : file( _file ),
  315. line( _line )
  316. {}
  317. SourceLineInfo( SourceLineInfo const& other ) = default;
  318. SourceLineInfo( SourceLineInfo && ) = default;
  319. SourceLineInfo& operator = ( SourceLineInfo const& ) = default;
  320. SourceLineInfo& operator = ( SourceLineInfo && ) = default;
  321. bool empty() const noexcept;
  322. bool operator == ( SourceLineInfo const& other ) const noexcept;
  323. bool operator < ( SourceLineInfo const& other ) const noexcept;
  324. char const* file;
  325. std::size_t line;
  326. };
  327. std::ostream& operator << ( std::ostream& os, SourceLineInfo const& info );
  328. // Use this in variadic streaming macros to allow
  329. // >> +StreamEndStop
  330. // as well as
  331. // >> stuff +StreamEndStop
  332. struct StreamEndStop {
  333. std::string operator+() const;
  334. };
  335. template<typename T>
  336. T const& operator + ( T const& value, StreamEndStop ) {
  337. return value;
  338. }
  339. }
  340. #define CATCH_INTERNAL_LINEINFO \
  341. ::Catch::SourceLineInfo( __FILE__, static_cast<std::size_t>( __LINE__ ) )
  342. // end catch_common.h
  343. namespace Catch {
  344. struct RegistrarForTagAliases {
  345. RegistrarForTagAliases( char const* alias, char const* tag, SourceLineInfo const& lineInfo );
  346. };
  347. } // end namespace Catch
  348. #define CATCH_REGISTER_TAG_ALIAS( alias, spec ) \
  349. CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
  350. namespace{ Catch::RegistrarForTagAliases INTERNAL_CATCH_UNIQUE_NAME( AutoRegisterTagAlias )( alias, spec, CATCH_INTERNAL_LINEINFO ); } \
  351. CATCH_INTERNAL_UNSUPPRESS_GLOBALS_WARNINGS
  352. // end catch_tag_alias_autoregistrar.h
  353. // start catch_test_registry.h
  354. // start catch_interfaces_testcase.h
  355. #include <vector>
  356. #include <memory>
  357. namespace Catch {
  358. class TestSpec;
  359. struct ITestInvoker {
  360. virtual void invoke () const = 0;
  361. virtual ~ITestInvoker();
  362. };
  363. using ITestCasePtr = std::shared_ptr<ITestInvoker>;
  364. class TestCase;
  365. struct IConfig;
  366. struct ITestCaseRegistry {
  367. virtual ~ITestCaseRegistry();
  368. virtual std::vector<TestCase> const& getAllTests() const = 0;
  369. virtual std::vector<TestCase> const& getAllTestsSorted( IConfig const& config ) const = 0;
  370. };
  371. bool matchTest( TestCase const& testCase, TestSpec const& testSpec, IConfig const& config );
  372. std::vector<TestCase> filterTests( std::vector<TestCase> const& testCases, TestSpec const& testSpec, IConfig const& config );
  373. std::vector<TestCase> const& getAllTestCasesSorted( IConfig const& config );
  374. }
  375. // end catch_interfaces_testcase.h
  376. // start catch_stringref.h
  377. #include <cstddef>
  378. #include <string>
  379. #include <iosfwd>
  380. namespace Catch {
  381. class StringData;
  382. /// A non-owning string class (similar to the forthcoming std::string_view)
  383. /// Note that, because a StringRef may be a substring of another string,
  384. /// it may not be null terminated. c_str() must return a null terminated
  385. /// string, however, and so the StringRef will internally take ownership
  386. /// (taking a copy), if necessary. In theory this ownership is not externally
  387. /// visible - but it does mean (substring) StringRefs should not be shared between
  388. /// threads.
  389. class StringRef {
  390. public:
  391. using size_type = std::size_t;
  392. private:
  393. friend struct StringRefTestAccess;
  394. char const* m_start;
  395. size_type m_size;
  396. char* m_data = nullptr;
  397. void takeOwnership();
  398. static constexpr char const* const s_empty = "";
  399. public: // construction/ assignment
  400. StringRef() noexcept
  401. : StringRef( s_empty, 0 )
  402. {}
  403. StringRef( StringRef const& other ) noexcept
  404. : m_start( other.m_start ),
  405. m_size( other.m_size )
  406. {}
  407. StringRef( StringRef&& other ) noexcept
  408. : m_start( other.m_start ),
  409. m_size( other.m_size ),
  410. m_data( other.m_data )
  411. {
  412. other.m_data = nullptr;
  413. }
  414. StringRef( char const* rawChars ) noexcept;
  415. StringRef( char const* rawChars, size_type size ) noexcept
  416. : m_start( rawChars ),
  417. m_size( size )
  418. {}
  419. StringRef( std::string const& stdString ) noexcept
  420. : m_start( stdString.c_str() ),
  421. m_size( stdString.size() )
  422. {}
  423. ~StringRef() noexcept {
  424. delete[] m_data;
  425. }
  426. auto operator = ( StringRef const &other ) noexcept -> StringRef& {
  427. delete[] m_data;
  428. m_data = nullptr;
  429. m_start = other.m_start;
  430. m_size = other.m_size;
  431. return *this;
  432. }
  433. operator std::string() const;
  434. void swap( StringRef& other ) noexcept;
  435. public: // operators
  436. auto operator == ( StringRef const& other ) const noexcept -> bool;
  437. auto operator != ( StringRef const& other ) const noexcept -> bool;
  438. auto operator[] ( size_type index ) const noexcept -> char;
  439. public: // named queries
  440. auto empty() const noexcept -> bool {
  441. return m_size == 0;
  442. }
  443. auto size() const noexcept -> size_type {
  444. return m_size;
  445. }
  446. auto numberOfCharacters() const noexcept -> size_type;
  447. auto c_str() const -> char const*;
  448. public: // substrings and searches
  449. auto substr( size_type start, size_type size ) const noexcept -> StringRef;
  450. // Returns the current start pointer.
  451. // Note that the pointer can change when if the StringRef is a substring
  452. auto currentData() const noexcept -> char const*;
  453. private: // ownership queries - may not be consistent between calls
  454. auto isOwned() const noexcept -> bool;
  455. auto isSubstring() const noexcept -> bool;
  456. };
  457. auto operator + ( StringRef const& lhs, StringRef const& rhs ) -> std::string;
  458. auto operator + ( StringRef const& lhs, char const* rhs ) -> std::string;
  459. auto operator + ( char const* lhs, StringRef const& rhs ) -> std::string;
  460. auto operator += ( std::string& lhs, StringRef const& sr ) -> std::string&;
  461. auto operator << ( std::ostream& os, StringRef const& sr ) -> std::ostream&;
  462. inline auto operator "" _sr( char const* rawChars, std::size_t size ) noexcept -> StringRef {
  463. return StringRef( rawChars, size );
  464. }
  465. } // namespace Catch
  466. inline auto operator "" _catch_sr( char const* rawChars, std::size_t size ) noexcept -> Catch::StringRef {
  467. return Catch::StringRef( rawChars, size );
  468. }
  469. // end catch_stringref.h
  470. namespace Catch {
  471. template<typename C>
  472. class TestInvokerAsMethod : public ITestInvoker {
  473. void (C::*m_testAsMethod)();
  474. public:
  475. TestInvokerAsMethod( void (C::*testAsMethod)() ) noexcept : m_testAsMethod( testAsMethod ) {}
  476. void invoke() const override {
  477. C obj;
  478. (obj.*m_testAsMethod)();
  479. }
  480. };
  481. auto makeTestInvoker( void(*testAsFunction)() ) noexcept -> ITestInvoker*;
  482. template<typename C>
  483. auto makeTestInvoker( void (C::*testAsMethod)() ) noexcept -> ITestInvoker* {
  484. return new(std::nothrow) TestInvokerAsMethod<C>( testAsMethod );
  485. }
  486. struct NameAndTags {
  487. NameAndTags( StringRef const& name_ = StringRef(), StringRef const& tags_ = StringRef() ) noexcept;
  488. StringRef name;
  489. StringRef tags;
  490. };
  491. struct AutoReg : NonCopyable {
  492. AutoReg( ITestInvoker* invoker, SourceLineInfo const& lineInfo, StringRef const& classOrMethod, NameAndTags const& nameAndTags ) noexcept;
  493. ~AutoReg();
  494. };
  495. } // end namespace Catch
  496. #define INTERNAL_CATCH_EXPAND1(param) INTERNAL_CATCH_EXPAND2(param)
  497. #define INTERNAL_CATCH_EXPAND2(...) INTERNAL_CATCH_NO## __VA_ARGS__
  498. #define INTERNAL_CATCH_DEF(...) INTERNAL_CATCH_DEF __VA_ARGS__
  499. #define INTERNAL_CATCH_NOINTERNAL_CATCH_DEF
  500. #if defined(CATCH_CONFIG_DISABLE)
  501. #define INTERNAL_CATCH_TESTCASE_NO_REGISTRATION( TestName, ... ) \
  502. static void TestName()
  503. #define INTERNAL_CATCH_TESTCASE_METHOD_NO_REGISTRATION( TestName, ClassName, ... ) \
  504. namespace{ \
  505. struct TestName : INTERNAL_CATCH_EXPAND1(INTERNAL_CATCH_DEF ClassName) { \
  506. void test(); \
  507. }; \
  508. } \
  509. void TestName::test()
  510. #endif
  511. ///////////////////////////////////////////////////////////////////////////////
  512. #define INTERNAL_CATCH_TESTCASE2( TestName, ... ) \
  513. static void TestName(); \
  514. CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
  515. namespace{ Catch::AutoReg INTERNAL_CATCH_UNIQUE_NAME( autoRegistrar )( Catch::makeTestInvoker( &TestName ), CATCH_INTERNAL_LINEINFO, Catch::StringRef(), Catch::NameAndTags{ __VA_ARGS__ } ); } /* NOLINT */ \
  516. CATCH_INTERNAL_UNSUPPRESS_GLOBALS_WARNINGS \
  517. static void TestName()
  518. #define INTERNAL_CATCH_TESTCASE( ... ) \
  519. INTERNAL_CATCH_TESTCASE2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ), __VA_ARGS__ )
  520. ///////////////////////////////////////////////////////////////////////////////
  521. #define INTERNAL_CATCH_METHOD_AS_TEST_CASE( QualifiedMethod, ... ) \
  522. CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
  523. namespace{ Catch::AutoReg INTERNAL_CATCH_UNIQUE_NAME( autoRegistrar )( Catch::makeTestInvoker( &QualifiedMethod ), CATCH_INTERNAL_LINEINFO, "&" #QualifiedMethod, Catch::NameAndTags{ __VA_ARGS__ } ); } /* NOLINT */ \
  524. CATCH_INTERNAL_UNSUPPRESS_GLOBALS_WARNINGS
  525. ///////////////////////////////////////////////////////////////////////////////
  526. #define INTERNAL_CATCH_TEST_CASE_METHOD2( TestName, ClassName, ... )\
  527. CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
  528. namespace{ \
  529. struct TestName : INTERNAL_CATCH_EXPAND1(INTERNAL_CATCH_DEF ClassName) { \
  530. void test(); \
  531. }; \
  532. Catch::AutoReg INTERNAL_CATCH_UNIQUE_NAME( autoRegistrar ) ( Catch::makeTestInvoker( &TestName::test ), CATCH_INTERNAL_LINEINFO, #ClassName, Catch::NameAndTags{ __VA_ARGS__ } ); /* NOLINT */ \
  533. } \
  534. CATCH_INTERNAL_UNSUPPRESS_GLOBALS_WARNINGS \
  535. void TestName::test()
  536. #define INTERNAL_CATCH_TEST_CASE_METHOD( ClassName, ... ) \
  537. INTERNAL_CATCH_TEST_CASE_METHOD2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ), ClassName, __VA_ARGS__ )
  538. ///////////////////////////////////////////////////////////////////////////////
  539. #define INTERNAL_CATCH_REGISTER_TESTCASE( Function, ... ) \
  540. CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
  541. Catch::AutoReg INTERNAL_CATCH_UNIQUE_NAME( autoRegistrar )( Catch::makeTestInvoker( Function ), CATCH_INTERNAL_LINEINFO, Catch::StringRef(), Catch::NameAndTags{ __VA_ARGS__ } ); /* NOLINT */ \
  542. CATCH_INTERNAL_UNSUPPRESS_GLOBALS_WARNINGS
  543. // end catch_test_registry.h
  544. // start catch_capture.hpp
  545. // start catch_assertionhandler.h
  546. // start catch_assertioninfo.h
  547. // start catch_result_type.h
  548. namespace Catch {
  549. // ResultWas::OfType enum
  550. struct ResultWas { enum OfType {
  551. Unknown = -1,
  552. Ok = 0,
  553. Info = 1,
  554. Warning = 2,
  555. FailureBit = 0x10,
  556. ExpressionFailed = FailureBit | 1,
  557. ExplicitFailure = FailureBit | 2,
  558. Exception = 0x100 | FailureBit,
  559. ThrewException = Exception | 1,
  560. DidntThrowException = Exception | 2,
  561. FatalErrorCondition = 0x200 | FailureBit
  562. }; };
  563. bool isOk( ResultWas::OfType resultType );
  564. bool isJustInfo( int flags );
  565. // ResultDisposition::Flags enum
  566. struct ResultDisposition { enum Flags {
  567. Normal = 0x01,
  568. ContinueOnFailure = 0x02, // Failures fail test, but execution continues
  569. FalseTest = 0x04, // Prefix expression with !
  570. SuppressFail = 0x08 // Failures are reported but do not fail the test
  571. }; };
  572. ResultDisposition::Flags operator | ( ResultDisposition::Flags lhs, ResultDisposition::Flags rhs );
  573. bool shouldContinueOnFailure( int flags );
  574. inline bool isFalseTest( int flags ) { return ( flags & ResultDisposition::FalseTest ) != 0; }
  575. bool shouldSuppressFailure( int flags );
  576. } // end namespace Catch
  577. // end catch_result_type.h
  578. namespace Catch {
  579. struct AssertionInfo
  580. {
  581. StringRef macroName;
  582. SourceLineInfo lineInfo;
  583. StringRef capturedExpression;
  584. ResultDisposition::Flags resultDisposition;
  585. // We want to delete this constructor but a compiler bug in 4.8 means
  586. // the struct is then treated as non-aggregate
  587. //AssertionInfo() = delete;
  588. };
  589. } // end namespace Catch
  590. // end catch_assertioninfo.h
  591. // start catch_decomposer.h
  592. // start catch_tostring.h
  593. #include <vector>
  594. #include <cstddef>
  595. #include <type_traits>
  596. #include <string>
  597. // start catch_stream.h
  598. #include <iosfwd>
  599. #include <cstddef>
  600. #include <ostream>
  601. namespace Catch {
  602. std::ostream& cout();
  603. std::ostream& cerr();
  604. std::ostream& clog();
  605. class StringRef;
  606. struct IStream {
  607. virtual ~IStream();
  608. virtual std::ostream& stream() const = 0;
  609. };
  610. auto makeStream( StringRef const &filename ) -> IStream const*;
  611. class ReusableStringStream {
  612. std::size_t m_index;
  613. std::ostream* m_oss;
  614. public:
  615. ReusableStringStream();
  616. ~ReusableStringStream();
  617. auto str() const -> std::string;
  618. template<typename T>
  619. auto operator << ( T const& value ) -> ReusableStringStream& {
  620. *m_oss << value;
  621. return *this;
  622. }
  623. auto get() -> std::ostream& { return *m_oss; }
  624. };
  625. }
  626. // end catch_stream.h
  627. #ifdef CATCH_CONFIG_CPP17_STRING_VIEW
  628. #include <string_view>
  629. #endif
  630. #ifdef __OBJC__
  631. // start catch_objc_arc.hpp
  632. #import <Foundation/Foundation.h>
  633. #ifdef __has_feature
  634. #define CATCH_ARC_ENABLED __has_feature(objc_arc)
  635. #else
  636. #define CATCH_ARC_ENABLED 0
  637. #endif
  638. void arcSafeRelease( NSObject* obj );
  639. id performOptionalSelector( id obj, SEL sel );
  640. #if !CATCH_ARC_ENABLED
  641. inline void arcSafeRelease( NSObject* obj ) {
  642. [obj release];
  643. }
  644. inline id performOptionalSelector( id obj, SEL sel ) {
  645. if( [obj respondsToSelector: sel] )
  646. return [obj performSelector: sel];
  647. return nil;
  648. }
  649. #define CATCH_UNSAFE_UNRETAINED
  650. #define CATCH_ARC_STRONG
  651. #else
  652. inline void arcSafeRelease( NSObject* ){}
  653. inline id performOptionalSelector( id obj, SEL sel ) {
  654. #ifdef __clang__
  655. #pragma clang diagnostic push
  656. #pragma clang diagnostic ignored "-Warc-performSelector-leaks"
  657. #endif
  658. if( [obj respondsToSelector: sel] )
  659. return [obj performSelector: sel];
  660. #ifdef __clang__
  661. #pragma clang diagnostic pop
  662. #endif
  663. return nil;
  664. }
  665. #define CATCH_UNSAFE_UNRETAINED __unsafe_unretained
  666. #define CATCH_ARC_STRONG __strong
  667. #endif
  668. // end catch_objc_arc.hpp
  669. #endif
  670. #ifdef _MSC_VER
  671. #pragma warning(push)
  672. #pragma warning(disable:4180) // We attempt to stream a function (address) by const&, which MSVC complains about but is harmless
  673. #endif
  674. // We need a dummy global operator<< so we can bring it into Catch namespace later
  675. struct Catch_global_namespace_dummy {};
  676. std::ostream& operator<<(std::ostream&, Catch_global_namespace_dummy);
  677. namespace Catch {
  678. // Bring in operator<< from global namespace into Catch namespace
  679. using ::operator<<;
  680. namespace Detail {
  681. extern const std::string unprintableString;
  682. std::string rawMemoryToString( const void *object, std::size_t size );
  683. template<typename T>
  684. std::string rawMemoryToString( const T& object ) {
  685. return rawMemoryToString( &object, sizeof(object) );
  686. }
  687. template<typename T>
  688. class IsStreamInsertable {
  689. template<typename SS, typename TT>
  690. static auto test(int)
  691. -> decltype(std::declval<SS&>() << std::declval<TT>(), std::true_type());
  692. template<typename, typename>
  693. static auto test(...)->std::false_type;
  694. public:
  695. static const bool value = decltype(test<std::ostream, const T&>(0))::value;
  696. };
  697. template<typename E>
  698. std::string convertUnknownEnumToString( E e );
  699. template<typename T>
  700. typename std::enable_if<
  701. !std::is_enum<T>::value && !std::is_base_of<std::exception, T>::value,
  702. std::string>::type convertUnstreamable( T const& ) {
  703. return Detail::unprintableString;
  704. }
  705. template<typename T>
  706. typename std::enable_if<
  707. !std::is_enum<T>::value && std::is_base_of<std::exception, T>::value,
  708. std::string>::type convertUnstreamable(T const& ex) {
  709. return ex.what();
  710. }
  711. template<typename T>
  712. typename std::enable_if<
  713. std::is_enum<T>::value
  714. , std::string>::type convertUnstreamable( T const& value ) {
  715. return convertUnknownEnumToString( value );
  716. }
  717. #if defined(_MANAGED)
  718. //! Convert a CLR string to a utf8 std::string
  719. template<typename T>
  720. std::string clrReferenceToString( T^ ref ) {
  721. if (ref == nullptr)
  722. return std::string("null");
  723. auto bytes = System::Text::Encoding::UTF8->GetBytes(ref->ToString());
  724. cli::pin_ptr<System::Byte> p = &bytes[0];
  725. return std::string(reinterpret_cast<char const *>(p), bytes->Length);
  726. }
  727. #endif
  728. } // namespace Detail
  729. // If we decide for C++14, change these to enable_if_ts
  730. template <typename T, typename = void>
  731. struct StringMaker {
  732. template <typename Fake = T>
  733. static
  734. typename std::enable_if<::Catch::Detail::IsStreamInsertable<Fake>::value, std::string>::type
  735. convert(const Fake& value) {
  736. ReusableStringStream rss;
  737. // NB: call using the function-like syntax to avoid ambiguity with
  738. // user-defined templated operator<< under clang.
  739. rss.operator<<(value);
  740. return rss.str();
  741. }
  742. template <typename Fake = T>
  743. static
  744. typename std::enable_if<!::Catch::Detail::IsStreamInsertable<Fake>::value, std::string>::type
  745. convert( const Fake& value ) {
  746. #if !defined(CATCH_CONFIG_FALLBACK_STRINGIFIER)
  747. return Detail::convertUnstreamable(value);
  748. #else
  749. return CATCH_CONFIG_FALLBACK_STRINGIFIER(value);
  750. #endif
  751. }
  752. };
  753. namespace Detail {
  754. // This function dispatches all stringification requests inside of Catch.
  755. // Should be preferably called fully qualified, like ::Catch::Detail::stringify
  756. template <typename T>
  757. std::string stringify(const T& e) {
  758. return ::Catch::StringMaker<typename std::remove_cv<typename std::remove_reference<T>::type>::type>::convert(e);
  759. }
  760. template<typename E>
  761. std::string convertUnknownEnumToString( E e ) {
  762. return ::Catch::Detail::stringify(static_cast<typename std::underlying_type<E>::type>(e));
  763. }
  764. #if defined(_MANAGED)
  765. template <typename T>
  766. std::string stringify( T^ e ) {
  767. return ::Catch::StringMaker<T^>::convert(e);
  768. }
  769. #endif
  770. } // namespace Detail
  771. // Some predefined specializations
  772. template<>
  773. struct StringMaker<std::string> {
  774. static std::string convert(const std::string& str);
  775. };
  776. #ifdef CATCH_CONFIG_CPP17_STRING_VIEW
  777. template<>
  778. struct StringMaker<std::string_view> {
  779. static std::string convert(std::string_view str);
  780. };
  781. #endif
  782. template<>
  783. struct StringMaker<char const *> {
  784. static std::string convert(char const * str);
  785. };
  786. template<>
  787. struct StringMaker<char *> {
  788. static std::string convert(char * str);
  789. };
  790. #ifdef CATCH_CONFIG_WCHAR
  791. template<>
  792. struct StringMaker<std::wstring> {
  793. static std::string convert(const std::wstring& wstr);
  794. };
  795. # ifdef CATCH_CONFIG_CPP17_STRING_VIEW
  796. template<>
  797. struct StringMaker<std::wstring_view> {
  798. static std::string convert(std::wstring_view str);
  799. };
  800. # endif
  801. template<>
  802. struct StringMaker<wchar_t const *> {
  803. static std::string convert(wchar_t const * str);
  804. };
  805. template<>
  806. struct StringMaker<wchar_t *> {
  807. static std::string convert(wchar_t * str);
  808. };
  809. #endif
  810. // TBD: Should we use `strnlen` to ensure that we don't go out of the buffer,
  811. // while keeping string semantics?
  812. template<int SZ>
  813. struct StringMaker<char[SZ]> {
  814. static std::string convert(char const* str) {
  815. return ::Catch::Detail::stringify(std::string{ str });
  816. }
  817. };
  818. template<int SZ>
  819. struct StringMaker<signed char[SZ]> {
  820. static std::string convert(signed char const* str) {
  821. return ::Catch::Detail::stringify(std::string{ reinterpret_cast<char const *>(str) });
  822. }
  823. };
  824. template<int SZ>
  825. struct StringMaker<unsigned char[SZ]> {
  826. static std::string convert(unsigned char const* str) {
  827. return ::Catch::Detail::stringify(std::string{ reinterpret_cast<char const *>(str) });
  828. }
  829. };
  830. template<>
  831. struct StringMaker<int> {
  832. static std::string convert(int value);
  833. };
  834. template<>
  835. struct StringMaker<long> {
  836. static std::string convert(long value);
  837. };
  838. template<>
  839. struct StringMaker<long long> {
  840. static std::string convert(long long value);
  841. };
  842. template<>
  843. struct StringMaker<unsigned int> {
  844. static std::string convert(unsigned int value);
  845. };
  846. template<>
  847. struct StringMaker<unsigned long> {
  848. static std::string convert(unsigned long value);
  849. };
  850. template<>
  851. struct StringMaker<unsigned long long> {
  852. static std::string convert(unsigned long long value);
  853. };
  854. template<>
  855. struct StringMaker<bool> {
  856. static std::string convert(bool b);
  857. };
  858. template<>
  859. struct StringMaker<char> {
  860. static std::string convert(char c);
  861. };
  862. template<>
  863. struct StringMaker<signed char> {
  864. static std::string convert(signed char c);
  865. };
  866. template<>
  867. struct StringMaker<unsigned char> {
  868. static std::string convert(unsigned char c);
  869. };
  870. template<>
  871. struct StringMaker<std::nullptr_t> {
  872. static std::string convert(std::nullptr_t);
  873. };
  874. template<>
  875. struct StringMaker<float> {
  876. static std::string convert(float value);
  877. };
  878. template<>
  879. struct StringMaker<double> {
  880. static std::string convert(double value);
  881. };
  882. template <typename T>
  883. struct StringMaker<T*> {
  884. template <typename U>
  885. static std::string convert(U* p) {
  886. if (p) {
  887. return ::Catch::Detail::rawMemoryToString(p);
  888. } else {
  889. return "nullptr";
  890. }
  891. }
  892. };
  893. template <typename R, typename C>
  894. struct StringMaker<R C::*> {
  895. static std::string convert(R C::* p) {
  896. if (p) {
  897. return ::Catch::Detail::rawMemoryToString(p);
  898. } else {
  899. return "nullptr";
  900. }
  901. }
  902. };
  903. #if defined(_MANAGED)
  904. template <typename T>
  905. struct StringMaker<T^> {
  906. static std::string convert( T^ ref ) {
  907. return ::Catch::Detail::clrReferenceToString(ref);
  908. }
  909. };
  910. #endif
  911. namespace Detail {
  912. template<typename InputIterator>
  913. std::string rangeToString(InputIterator first, InputIterator last) {
  914. ReusableStringStream rss;
  915. rss << "{ ";
  916. if (first != last) {
  917. rss << ::Catch::Detail::stringify(*first);
  918. for (++first; first != last; ++first)
  919. rss << ", " << ::Catch::Detail::stringify(*first);
  920. }
  921. rss << " }";
  922. return rss.str();
  923. }
  924. }
  925. #ifdef __OBJC__
  926. template<>
  927. struct StringMaker<NSString*> {
  928. static std::string convert(NSString * nsstring) {
  929. if (!nsstring)
  930. return "nil";
  931. return std::string("@") + [nsstring UTF8String];
  932. }
  933. };
  934. template<>
  935. struct StringMaker<NSObject*> {
  936. static std::string convert(NSObject* nsObject) {
  937. return ::Catch::Detail::stringify([nsObject description]);
  938. }
  939. };
  940. namespace Detail {
  941. inline std::string stringify( NSString* nsstring ) {
  942. return StringMaker<NSString*>::convert( nsstring );
  943. }
  944. } // namespace Detail
  945. #endif // __OBJC__
  946. } // namespace Catch
  947. //////////////////////////////////////////////////////
  948. // Separate std-lib types stringification, so it can be selectively enabled
  949. // This means that we do not bring in
  950. #if defined(CATCH_CONFIG_ENABLE_ALL_STRINGMAKERS)
  951. # define CATCH_CONFIG_ENABLE_PAIR_STRINGMAKER
  952. # define CATCH_CONFIG_ENABLE_TUPLE_STRINGMAKER
  953. # define CATCH_CONFIG_ENABLE_VARIANT_STRINGMAKER
  954. # define CATCH_CONFIG_ENABLE_CHRONO_STRINGMAKER
  955. #endif
  956. // Separate std::pair specialization
  957. #if defined(CATCH_CONFIG_ENABLE_PAIR_STRINGMAKER)
  958. #include <utility>
  959. namespace Catch {
  960. template<typename T1, typename T2>
  961. struct StringMaker<std::pair<T1, T2> > {
  962. static std::string convert(const std::pair<T1, T2>& pair) {
  963. ReusableStringStream rss;
  964. rss << "{ "
  965. << ::Catch::Detail::stringify(pair.first)
  966. << ", "
  967. << ::Catch::Detail::stringify(pair.second)
  968. << " }";
  969. return rss.str();
  970. }
  971. };
  972. }
  973. #endif // CATCH_CONFIG_ENABLE_PAIR_STRINGMAKER
  974. // Separate std::tuple specialization
  975. #if defined(CATCH_CONFIG_ENABLE_TUPLE_STRINGMAKER)
  976. #include <tuple>
  977. namespace Catch {
  978. namespace Detail {
  979. template<
  980. typename Tuple,
  981. std::size_t N = 0,
  982. bool = (N < std::tuple_size<Tuple>::value)
  983. >
  984. struct TupleElementPrinter {
  985. static void print(const Tuple& tuple, std::ostream& os) {
  986. os << (N ? ", " : " ")
  987. << ::Catch::Detail::stringify(std::get<N>(tuple));
  988. TupleElementPrinter<Tuple, N + 1>::print(tuple, os);
  989. }
  990. };
  991. template<
  992. typename Tuple,
  993. std::size_t N
  994. >
  995. struct TupleElementPrinter<Tuple, N, false> {
  996. static void print(const Tuple&, std::ostream&) {}
  997. };
  998. }
  999. template<typename ...Types>
  1000. struct StringMaker<std::tuple<Types...>> {
  1001. static std::string convert(const std::tuple<Types...>& tuple) {
  1002. ReusableStringStream rss;
  1003. rss << '{';
  1004. Detail::TupleElementPrinter<std::tuple<Types...>>::print(tuple, rss.get());
  1005. rss << " }";
  1006. return rss.str();
  1007. }
  1008. };
  1009. }
  1010. #endif // CATCH_CONFIG_ENABLE_TUPLE_STRINGMAKER
  1011. #if defined(CATCH_CONFIG_ENABLE_VARIANT_STRINGMAKER) && defined(CATCH_CONFIG_CPP17_VARIANT)
  1012. #include <variant>
  1013. namespace Catch {
  1014. template<>
  1015. struct StringMaker<std::monostate> {
  1016. static std::string convert(const std::monostate&) {
  1017. return "{ }";
  1018. }
  1019. };
  1020. template<typename... Elements>
  1021. struct StringMaker<std::variant<Elements...>> {
  1022. static std::string convert(const std::variant<Elements...>& variant) {
  1023. if (variant.valueless_by_exception()) {
  1024. return "{valueless variant}";
  1025. } else {
  1026. return std::visit(
  1027. [](const auto& value) {
  1028. return ::Catch::Detail::stringify(value);
  1029. },
  1030. variant
  1031. );
  1032. }
  1033. }
  1034. };
  1035. }
  1036. #endif // CATCH_CONFIG_ENABLE_VARIANT_STRINGMAKER
  1037. namespace Catch {
  1038. struct not_this_one {}; // Tag type for detecting which begin/ end are being selected
  1039. // Import begin/ end from std here so they are considered alongside the fallback (...) overloads in this namespace
  1040. using std::begin;
  1041. using std::end;
  1042. not_this_one begin( ... );
  1043. not_this_one end( ... );
  1044. template <typename T>
  1045. struct is_range {
  1046. static const bool value =
  1047. !std::is_same<decltype(begin(std::declval<T>())), not_this_one>::value &&
  1048. !std::is_same<decltype(end(std::declval<T>())), not_this_one>::value;
  1049. };
  1050. #if defined(_MANAGED) // Managed types are never ranges
  1051. template <typename T>
  1052. struct is_range<T^> {
  1053. static const bool value = false;
  1054. };
  1055. #endif
  1056. template<typename Range>
  1057. std::string rangeToString( Range const& range ) {
  1058. return ::Catch::Detail::rangeToString( begin( range ), end( range ) );
  1059. }
  1060. // Handle vector<bool> specially
  1061. template<typename Allocator>
  1062. std::string rangeToString( std::vector<bool, Allocator> const& v ) {
  1063. ReusableStringStream rss;
  1064. rss << "{ ";
  1065. bool first = true;
  1066. for( bool b : v ) {
  1067. if( first )
  1068. first = false;
  1069. else
  1070. rss << ", ";
  1071. rss << ::Catch::Detail::stringify( b );
  1072. }
  1073. rss << " }";
  1074. return rss.str();
  1075. }
  1076. template<typename R>
  1077. struct StringMaker<R, typename std::enable_if<is_range<R>::value && !::Catch::Detail::IsStreamInsertable<R>::value>::type> {
  1078. static std::string convert( R const& range ) {
  1079. return rangeToString( range );
  1080. }
  1081. };
  1082. template <typename T, int SZ>
  1083. struct StringMaker<T[SZ]> {
  1084. static std::string convert(T const(&arr)[SZ]) {
  1085. return rangeToString(arr);
  1086. }
  1087. };
  1088. } // namespace Catch
  1089. // Separate std::chrono::duration specialization
  1090. #if defined(CATCH_CONFIG_ENABLE_CHRONO_STRINGMAKER)
  1091. #include <ctime>
  1092. #include <ratio>
  1093. #include <chrono>
  1094. namespace Catch {
  1095. template <class Ratio>
  1096. struct ratio_string {
  1097. static std::string symbol();
  1098. };
  1099. template <class Ratio>
  1100. std::string ratio_string<Ratio>::symbol() {
  1101. Catch::ReusableStringStream rss;
  1102. rss << '[' << Ratio::num << '/'
  1103. << Ratio::den << ']';
  1104. return rss.str();
  1105. }
  1106. template <>
  1107. struct ratio_string<std::atto> {
  1108. static std::string symbol();
  1109. };
  1110. template <>
  1111. struct ratio_string<std::femto> {
  1112. static std::string symbol();
  1113. };
  1114. template <>
  1115. struct ratio_string<std::pico> {
  1116. static std::string symbol();
  1117. };
  1118. template <>
  1119. struct ratio_string<std::nano> {
  1120. static std::string symbol();
  1121. };
  1122. template <>
  1123. struct ratio_string<std::micro> {
  1124. static std::string symbol();
  1125. };
  1126. template <>
  1127. struct ratio_string<std::milli> {
  1128. static std::string symbol();
  1129. };
  1130. ////////////
  1131. // std::chrono::duration specializations
  1132. template<typename Value, typename Ratio>
  1133. struct StringMaker<std::chrono::duration<Value, Ratio>> {
  1134. static std::string convert(std::chrono::duration<Value, Ratio> const& duration) {
  1135. ReusableStringStream rss;
  1136. rss << duration.count() << ' ' << ratio_string<Ratio>::symbol() << 's';
  1137. return rss.str();
  1138. }
  1139. };
  1140. template<typename Value>
  1141. struct StringMaker<std::chrono::duration<Value, std::ratio<1>>> {
  1142. static std::string convert(std::chrono::duration<Value, std::ratio<1>> const& duration) {
  1143. ReusableStringStream rss;
  1144. rss << duration.count() << " s";
  1145. return rss.str();
  1146. }
  1147. };
  1148. template<typename Value>
  1149. struct StringMaker<std::chrono::duration<Value, std::ratio<60>>> {
  1150. static std::string convert(std::chrono::duration<Value, std::ratio<60>> const& duration) {
  1151. ReusableStringStream rss;
  1152. rss << duration.count() << " m";
  1153. return rss.str();
  1154. }
  1155. };
  1156. template<typename Value>
  1157. struct StringMaker<std::chrono::duration<Value, std::ratio<3600>>> {
  1158. static std::string convert(std::chrono::duration<Value, std::ratio<3600>> const& duration) {
  1159. ReusableStringStream rss;
  1160. rss << duration.count() << " h";
  1161. return rss.str();
  1162. }
  1163. };
  1164. ////////////
  1165. // std::chrono::time_point specialization
  1166. // Generic time_point cannot be specialized, only std::chrono::time_point<system_clock>
  1167. template<typename Clock, typename Duration>
  1168. struct StringMaker<std::chrono::time_point<Clock, Duration>> {
  1169. static std::string convert(std::chrono::time_point<Clock, Duration> const& time_point) {
  1170. return ::Catch::Detail::stringify(time_point.time_since_epoch()) + " since epoch";
  1171. }
  1172. };
  1173. // std::chrono::time_point<system_clock> specialization
  1174. template<typename Duration>
  1175. struct StringMaker<std::chrono::time_point<std::chrono::system_clock, Duration>> {
  1176. static std::string convert(std::chrono::time_point<std::chrono::system_clock, Duration> const& time_point) {
  1177. auto converted = std::chrono::system_clock::to_time_t(time_point);
  1178. #ifdef _MSC_VER
  1179. std::tm timeInfo = {};
  1180. gmtime_s(&timeInfo, &converted);
  1181. #else
  1182. std::tm* timeInfo = std::gmtime(&converted);
  1183. #endif
  1184. auto const timeStampSize = sizeof("2017-01-16T17:06:45Z");
  1185. char timeStamp[timeStampSize];
  1186. const char * const fmt = "%Y-%m-%dT%H:%M:%SZ";
  1187. #ifdef _MSC_VER
  1188. std::strftime(timeStamp, timeStampSize, fmt, &timeInfo);
  1189. #else
  1190. std::strftime(timeStamp, timeStampSize, fmt, timeInfo);
  1191. #endif
  1192. return std::string(timeStamp);
  1193. }
  1194. };
  1195. }
  1196. #endif // CATCH_CONFIG_ENABLE_CHRONO_STRINGMAKER
  1197. #ifdef _MSC_VER
  1198. #pragma warning(pop)
  1199. #endif
  1200. // end catch_tostring.h
  1201. #include <iosfwd>
  1202. #ifdef _MSC_VER
  1203. #pragma warning(push)
  1204. #pragma warning(disable:4389) // '==' : signed/unsigned mismatch
  1205. #pragma warning(disable:4018) // more "signed/unsigned mismatch"
  1206. #pragma warning(disable:4312) // Converting int to T* using reinterpret_cast (issue on x64 platform)
  1207. #pragma warning(disable:4180) // qualifier applied to function type has no meaning
  1208. #endif
  1209. namespace Catch {
  1210. struct ITransientExpression {
  1211. auto isBinaryExpression() const -> bool { return m_isBinaryExpression; }
  1212. auto getResult() const -> bool { return m_result; }
  1213. virtual void streamReconstructedExpression( std::ostream &os ) const = 0;
  1214. ITransientExpression( bool isBinaryExpression, bool result )
  1215. : m_isBinaryExpression( isBinaryExpression ),
  1216. m_result( result )
  1217. {}
  1218. // We don't actually need a virtual destructor, but many static analysers
  1219. // complain if it's not here :-(
  1220. virtual ~ITransientExpression();
  1221. bool m_isBinaryExpression;
  1222. bool m_result;
  1223. };
  1224. void formatReconstructedExpression( std::ostream &os, std::string const& lhs, StringRef op, std::string const& rhs );
  1225. template<typename LhsT, typename RhsT>
  1226. class BinaryExpr : public ITransientExpression {
  1227. LhsT m_lhs;
  1228. StringRef m_op;
  1229. RhsT m_rhs;
  1230. void streamReconstructedExpression( std::ostream &os ) const override {
  1231. formatReconstructedExpression
  1232. ( os, Catch::Detail::stringify( m_lhs ), m_op, Catch::Detail::stringify( m_rhs ) );
  1233. }
  1234. public:
  1235. BinaryExpr( bool comparisonResult, LhsT lhs, StringRef op, RhsT rhs )
  1236. : ITransientExpression{ true, comparisonResult },
  1237. m_lhs( lhs ),
  1238. m_op( op ),
  1239. m_rhs( rhs )
  1240. {}
  1241. };
  1242. template<typename LhsT>
  1243. class UnaryExpr : public ITransientExpression {
  1244. LhsT m_lhs;
  1245. void streamReconstructedExpression( std::ostream &os ) const override {
  1246. os << Catch::Detail::stringify( m_lhs );
  1247. }
  1248. public:
  1249. explicit UnaryExpr( LhsT lhs )
  1250. : ITransientExpression{ false, lhs ? true : false },
  1251. m_lhs( lhs )
  1252. {}
  1253. };
  1254. // Specialised comparison functions to handle equality comparisons between ints and pointers (NULL deduces as an int)
  1255. template<typename LhsT, typename RhsT>
  1256. auto compareEqual( LhsT const& lhs, RhsT const& rhs ) -> bool { return static_cast<bool>(lhs == rhs); }
  1257. template<typename T>
  1258. auto compareEqual( T* const& lhs, int rhs ) -> bool { return lhs == reinterpret_cast<void const*>( rhs ); }
  1259. template<typename T>
  1260. auto compareEqual( T* const& lhs, long rhs ) -> bool { return lhs == reinterpret_cast<void const*>( rhs ); }
  1261. template<typename T>
  1262. auto compareEqual( int lhs, T* const& rhs ) -> bool { return reinterpret_cast<void const*>( lhs ) == rhs; }
  1263. template<typename T>
  1264. auto compareEqual( long lhs, T* const& rhs ) -> bool { return reinterpret_cast<void const*>( lhs ) == rhs; }
  1265. template<typename LhsT, typename RhsT>
  1266. auto compareNotEqual( LhsT const& lhs, RhsT&& rhs ) -> bool { return static_cast<bool>(lhs != rhs); }
  1267. template<typename T>
  1268. auto compareNotEqual( T* const& lhs, int rhs ) -> bool { return lhs != reinterpret_cast<void const*>( rhs ); }
  1269. template<typename T>
  1270. auto compareNotEqual( T* const& lhs, long rhs ) -> bool { return lhs != reinterpret_cast<void const*>( rhs ); }
  1271. template<typename T>
  1272. auto compareNotEqual( int lhs, T* const& rhs ) -> bool { return reinterpret_cast<void const*>( lhs ) != rhs; }
  1273. template<typename T>
  1274. auto compareNotEqual( long lhs, T* const& rhs ) -> bool { return reinterpret_cast<void const*>( lhs ) != rhs; }
  1275. template<typename LhsT>
  1276. class ExprLhs {
  1277. LhsT m_lhs;
  1278. public:
  1279. explicit ExprLhs( LhsT lhs ) : m_lhs( lhs ) {}
  1280. template<typename RhsT>
  1281. auto operator == ( RhsT const& rhs ) -> BinaryExpr<LhsT, RhsT const&> const {
  1282. return { compareEqual( m_lhs, rhs ), m_lhs, "==", rhs };
  1283. }
  1284. auto operator == ( bool rhs ) -> BinaryExpr<LhsT, bool> const {
  1285. return { m_lhs == rhs, m_lhs, "==", rhs };
  1286. }
  1287. template<typename RhsT>
  1288. auto operator != ( RhsT const& rhs ) -> BinaryExpr<LhsT, RhsT const&> const {
  1289. return { compareNotEqual( m_lhs, rhs ), m_lhs, "!=", rhs };
  1290. }
  1291. auto operator != ( bool rhs ) -> BinaryExpr<LhsT, bool> const {
  1292. return { m_lhs != rhs, m_lhs, "!=", rhs };
  1293. }
  1294. template<typename RhsT>
  1295. auto operator > ( RhsT const& rhs ) -> BinaryExpr<LhsT, RhsT const&> const {
  1296. return { static_cast<bool>(m_lhs > rhs), m_lhs, ">", rhs };
  1297. }
  1298. template<typename RhsT>
  1299. auto operator < ( RhsT const& rhs ) -> BinaryExpr<LhsT, RhsT const&> const {
  1300. return { static_cast<bool>(m_lhs < rhs), m_lhs, "<", rhs };
  1301. }
  1302. template<typename RhsT>
  1303. auto operator >= ( RhsT const& rhs ) -> BinaryExpr<LhsT, RhsT const&> const {
  1304. return { static_cast<bool>(m_lhs >= rhs), m_lhs, ">=", rhs };
  1305. }
  1306. template<typename RhsT>
  1307. auto operator <= ( RhsT const& rhs ) -> BinaryExpr<LhsT, RhsT const&> const {
  1308. return { static_cast<bool>(m_lhs <= rhs), m_lhs, "<=", rhs };
  1309. }
  1310. auto makeUnaryExpr() const -> UnaryExpr<LhsT> {
  1311. return UnaryExpr<LhsT>{ m_lhs };
  1312. }
  1313. };
  1314. void handleExpression( ITransientExpression const& expr );
  1315. template<typename T>
  1316. void handleExpression( ExprLhs<T> const& expr ) {
  1317. handleExpression( expr.makeUnaryExpr() );
  1318. }
  1319. struct Decomposer {
  1320. template<typename T>
  1321. auto operator <= ( T const& lhs ) -> ExprLhs<T const&> {
  1322. return ExprLhs<T const&>{ lhs };
  1323. }
  1324. auto operator <=( bool value ) -> ExprLhs<bool> {
  1325. return ExprLhs<bool>{ value };
  1326. }
  1327. };
  1328. } // end namespace Catch
  1329. #ifdef _MSC_VER
  1330. #pragma warning(pop)
  1331. #endif
  1332. // end catch_decomposer.h
  1333. // start catch_interfaces_capture.h
  1334. #include <string>
  1335. namespace Catch {
  1336. class AssertionResult;
  1337. struct AssertionInfo;
  1338. struct SectionInfo;
  1339. struct SectionEndInfo;
  1340. struct MessageInfo;
  1341. struct Counts;
  1342. struct BenchmarkInfo;
  1343. struct BenchmarkStats;
  1344. struct AssertionReaction;
  1345. struct SourceLineInfo;
  1346. struct ITransientExpression;
  1347. struct IGeneratorTracker;
  1348. struct IResultCapture {
  1349. virtual ~IResultCapture();
  1350. virtual bool sectionStarted( SectionInfo const& sectionInfo,
  1351. Counts& assertions ) = 0;
  1352. virtual void sectionEnded( SectionEndInfo const& endInfo ) = 0;
  1353. virtual void sectionEndedEarly( SectionEndInfo const& endInfo ) = 0;
  1354. virtual auto acquireGeneratorTracker( SourceLineInfo const& lineInfo ) -> IGeneratorTracker& = 0;
  1355. virtual void benchmarkStarting( BenchmarkInfo const& info ) = 0;
  1356. virtual void benchmarkEnded( BenchmarkStats const& stats ) = 0;
  1357. virtual void pushScopedMessage( MessageInfo const& message ) = 0;
  1358. virtual void popScopedMessage( MessageInfo const& message ) = 0;
  1359. virtual void handleFatalErrorCondition( StringRef message ) = 0;
  1360. virtual void handleExpr
  1361. ( AssertionInfo const& info,
  1362. ITransientExpression const& expr,
  1363. AssertionReaction& reaction ) = 0;
  1364. virtual void handleMessage
  1365. ( AssertionInfo const& info,
  1366. ResultWas::OfType resultType,
  1367. StringRef const& message,
  1368. AssertionReaction& reaction ) = 0;
  1369. virtual void handleUnexpectedExceptionNotThrown
  1370. ( AssertionInfo const& info,
  1371. AssertionReaction& reaction ) = 0;
  1372. virtual void handleUnexpectedInflightException
  1373. ( AssertionInfo const& info,
  1374. std::string const& message,
  1375. AssertionReaction& reaction ) = 0;
  1376. virtual void handleIncomplete
  1377. ( AssertionInfo const& info ) = 0;
  1378. virtual void handleNonExpr
  1379. ( AssertionInfo const &info,
  1380. ResultWas::OfType resultType,
  1381. AssertionReaction &reaction ) = 0;
  1382. virtual bool lastAssertionPassed() = 0;
  1383. virtual void assertionPassed() = 0;
  1384. // Deprecated, do not use:
  1385. virtual std::string getCurrentTestName() const = 0;
  1386. virtual const AssertionResult* getLastResult() const = 0;
  1387. virtual void exceptionEarlyReported() = 0;
  1388. };
  1389. IResultCapture& getResultCapture();
  1390. }
  1391. // end catch_interfaces_capture.h
  1392. namespace Catch {
  1393. struct TestFailureException{};
  1394. struct AssertionResultData;
  1395. struct IResultCapture;
  1396. class RunContext;
  1397. class LazyExpression {
  1398. friend class AssertionHandler;
  1399. friend struct AssertionStats;
  1400. friend class RunContext;
  1401. ITransientExpression const* m_transientExpression = nullptr;
  1402. bool m_isNegated;
  1403. public:
  1404. LazyExpression( bool isNegated );
  1405. LazyExpression( LazyExpression const& other );
  1406. LazyExpression& operator = ( LazyExpression const& ) = delete;
  1407. explicit operator bool() const;
  1408. friend auto operator << ( std::ostream& os, LazyExpression const& lazyExpr ) -> std::ostream&;
  1409. };
  1410. struct AssertionReaction {
  1411. bool shouldDebugBreak = false;
  1412. bool shouldThrow = false;
  1413. };
  1414. class AssertionHandler {
  1415. AssertionInfo m_assertionInfo;
  1416. AssertionReaction m_reaction;
  1417. bool m_completed = false;
  1418. IResultCapture& m_resultCapture;
  1419. public:
  1420. AssertionHandler
  1421. ( StringRef const& macroName,
  1422. SourceLineInfo const& lineInfo,
  1423. StringRef capturedExpression,
  1424. ResultDisposition::Flags resultDisposition );
  1425. ~AssertionHandler() {
  1426. if ( !m_completed ) {
  1427. m_resultCapture.handleIncomplete( m_assertionInfo );
  1428. }
  1429. }
  1430. template<typename T>
  1431. void handleExpr( ExprLhs<T> const& expr ) {
  1432. handleExpr( expr.makeUnaryExpr() );
  1433. }
  1434. void handleExpr( ITransientExpression const& expr );
  1435. void handleMessage(ResultWas::OfType resultType, StringRef const& message);
  1436. void handleExceptionThrownAsExpected();
  1437. void handleUnexpectedExceptionNotThrown();
  1438. void handleExceptionNotThrownAsExpected();
  1439. void handleThrowingCallSkipped();
  1440. void handleUnexpectedInflightException();
  1441. void complete();
  1442. void setCompleted();
  1443. // query
  1444. auto allowThrows() const -> bool;
  1445. };
  1446. void handleExceptionMatchExpr( AssertionHandler& handler, std::string const& str, StringRef const& matcherString );
  1447. } // namespace Catch
  1448. // end catch_assertionhandler.h
  1449. // start catch_message.h
  1450. #include <string>
  1451. #include <vector>
  1452. namespace Catch {
  1453. struct MessageInfo {
  1454. MessageInfo( StringRef const& _macroName,
  1455. SourceLineInfo const& _lineInfo,
  1456. ResultWas::OfType _type );
  1457. StringRef macroName;
  1458. std::string message;
  1459. SourceLineInfo lineInfo;
  1460. ResultWas::OfType type;
  1461. unsigned int sequence;
  1462. bool operator == ( MessageInfo const& other ) const;
  1463. bool operator < ( MessageInfo const& other ) const;
  1464. private:
  1465. static unsigned int globalCount;
  1466. };
  1467. struct MessageStream {
  1468. template<typename T>
  1469. MessageStream& operator << ( T const& value ) {
  1470. m_stream << value;
  1471. return *this;
  1472. }
  1473. ReusableStringStream m_stream;
  1474. };
  1475. struct MessageBuilder : MessageStream {
  1476. MessageBuilder( StringRef const& macroName,
  1477. SourceLineInfo const& lineInfo,
  1478. ResultWas::OfType type );
  1479. template<typename T>
  1480. MessageBuilder& operator << ( T const& value ) {
  1481. m_stream << value;
  1482. return *this;
  1483. }
  1484. MessageInfo m_info;
  1485. };
  1486. class ScopedMessage {
  1487. public:
  1488. explicit ScopedMessage( MessageBuilder const& builder );
  1489. ~ScopedMessage();
  1490. MessageInfo m_info;
  1491. };
  1492. class Capturer {
  1493. std::vector<MessageInfo> m_messages;
  1494. IResultCapture& m_resultCapture = getResultCapture();
  1495. size_t m_captured = 0;
  1496. public:
  1497. Capturer( StringRef macroName, SourceLineInfo const& lineInfo, ResultWas::OfType resultType, StringRef names );
  1498. ~Capturer();
  1499. void captureValue( size_t index, StringRef value );
  1500. template<typename T>
  1501. void captureValues( size_t index, T&& value ) {
  1502. captureValue( index, Catch::Detail::stringify( value ) );
  1503. }
  1504. template<typename T, typename... Ts>
  1505. void captureValues( size_t index, T&& value, Ts&&... values ) {
  1506. captureValues( index, value );
  1507. captureValues( index+1, values... );
  1508. }
  1509. };
  1510. } // end namespace Catch
  1511. // end catch_message.h
  1512. #if !defined(CATCH_CONFIG_DISABLE)
  1513. #if !defined(CATCH_CONFIG_DISABLE_STRINGIFICATION)
  1514. #define CATCH_INTERNAL_STRINGIFY(...) #__VA_ARGS__
  1515. #else
  1516. #define CATCH_INTERNAL_STRINGIFY(...) "Disabled by CATCH_CONFIG_DISABLE_STRINGIFICATION"
  1517. #endif
  1518. #if defined(CATCH_CONFIG_FAST_COMPILE) || defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
  1519. ///////////////////////////////////////////////////////////////////////////////
  1520. // Another way to speed-up compilation is to omit local try-catch for REQUIRE*
  1521. // macros.
  1522. #define INTERNAL_CATCH_TRY
  1523. #define INTERNAL_CATCH_CATCH( capturer )
  1524. #else // CATCH_CONFIG_FAST_COMPILE
  1525. #define INTERNAL_CATCH_TRY try
  1526. #define INTERNAL_CATCH_CATCH( handler ) catch(...) { handler.handleUnexpectedInflightException(); }
  1527. #endif
  1528. #define INTERNAL_CATCH_REACT( handler ) handler.complete();
  1529. ///////////////////////////////////////////////////////////////////////////////
  1530. #define INTERNAL_CATCH_TEST( macroName, resultDisposition, ... ) \
  1531. do { \
  1532. Catch::AssertionHandler catchAssertionHandler( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(__VA_ARGS__), resultDisposition ); \
  1533. INTERNAL_CATCH_TRY { \
  1534. CATCH_INTERNAL_SUPPRESS_PARENTHESES_WARNINGS \
  1535. catchAssertionHandler.handleExpr( Catch::Decomposer() <= __VA_ARGS__ ); \
  1536. CATCH_INTERNAL_UNSUPPRESS_PARENTHESES_WARNINGS \
  1537. } INTERNAL_CATCH_CATCH( catchAssertionHandler ) \
  1538. INTERNAL_CATCH_REACT( catchAssertionHandler ) \
  1539. } 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
  1540. // The double negation silences MSVC's C4800 warning, the static_cast forces short-circuit evaluation if the type has overloaded &&.
  1541. ///////////////////////////////////////////////////////////////////////////////
  1542. #define INTERNAL_CATCH_IF( macroName, resultDisposition, ... ) \
  1543. INTERNAL_CATCH_TEST( macroName, resultDisposition, __VA_ARGS__ ); \
  1544. if( Catch::getResultCapture().lastAssertionPassed() )
  1545. ///////////////////////////////////////////////////////////////////////////////
  1546. #define INTERNAL_CATCH_ELSE( macroName, resultDisposition, ... ) \
  1547. INTERNAL_CATCH_TEST( macroName, resultDisposition, __VA_ARGS__ ); \
  1548. if( !Catch::getResultCapture().lastAssertionPassed() )
  1549. ///////////////////////////////////////////////////////////////////////////////
  1550. #define INTERNAL_CATCH_NO_THROW( macroName, resultDisposition, ... ) \
  1551. do { \
  1552. Catch::AssertionHandler catchAssertionHandler( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(__VA_ARGS__), resultDisposition ); \
  1553. try { \
  1554. static_cast<void>(__VA_ARGS__); \
  1555. catchAssertionHandler.handleExceptionNotThrownAsExpected(); \
  1556. } \
  1557. catch( ... ) { \
  1558. catchAssertionHandler.handleUnexpectedInflightException(); \
  1559. } \
  1560. INTERNAL_CATCH_REACT( catchAssertionHandler ) \
  1561. } while( false )
  1562. ///////////////////////////////////////////////////////////////////////////////
  1563. #define INTERNAL_CATCH_THROWS( macroName, resultDisposition, ... ) \
  1564. do { \
  1565. Catch::AssertionHandler catchAssertionHandler( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(__VA_ARGS__), resultDisposition); \
  1566. if( catchAssertionHandler.allowThrows() ) \
  1567. try { \
  1568. static_cast<void>(__VA_ARGS__); \
  1569. catchAssertionHandler.handleUnexpectedExceptionNotThrown(); \
  1570. } \
  1571. catch( ... ) { \
  1572. catchAssertionHandler.handleExceptionThrownAsExpected(); \
  1573. } \
  1574. else \
  1575. catchAssertionHandler.handleThrowingCallSkipped(); \
  1576. INTERNAL_CATCH_REACT( catchAssertionHandler ) \
  1577. } while( false )
  1578. ///////////////////////////////////////////////////////////////////////////////
  1579. #define INTERNAL_CATCH_THROWS_AS( macroName, exceptionType, resultDisposition, expr ) \
  1580. do { \
  1581. Catch::AssertionHandler catchAssertionHandler( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(expr) ", " CATCH_INTERNAL_STRINGIFY(exceptionType), resultDisposition ); \
  1582. if( catchAssertionHandler.allowThrows() ) \
  1583. try { \
  1584. static_cast<void>(expr); \
  1585. catchAssertionHandler.handleUnexpectedExceptionNotThrown(); \
  1586. } \
  1587. catch( exceptionType const& ) { \
  1588. catchAssertionHandler.handleExceptionThrownAsExpected(); \
  1589. } \
  1590. catch( ... ) { \
  1591. catchAssertionHandler.handleUnexpectedInflightException(); \
  1592. } \
  1593. else \
  1594. catchAssertionHandler.handleThrowingCallSkipped(); \
  1595. INTERNAL_CATCH_REACT( catchAssertionHandler ) \
  1596. } while( false )
  1597. ///////////////////////////////////////////////////////////////////////////////
  1598. #define INTERNAL_CATCH_MSG( macroName, messageType, resultDisposition, ... ) \
  1599. do { \
  1600. Catch::AssertionHandler catchAssertionHandler( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, Catch::StringRef(), resultDisposition ); \
  1601. catchAssertionHandler.handleMessage( messageType, ( Catch::MessageStream() << __VA_ARGS__ + ::Catch::StreamEndStop() ).m_stream.str() ); \
  1602. INTERNAL_CATCH_REACT( catchAssertionHandler ) \
  1603. } while( false )
  1604. ///////////////////////////////////////////////////////////////////////////////
  1605. #define INTERNAL_CATCH_CAPTURE( varName, macroName, ... ) \
  1606. auto varName = Catch::Capturer( macroName, CATCH_INTERNAL_LINEINFO, Catch::ResultWas::Info, #__VA_ARGS__ ); \
  1607. varName.captureValues( 0, __VA_ARGS__ )
  1608. ///////////////////////////////////////////////////////////////////////////////
  1609. #define INTERNAL_CATCH_INFO( macroName, log ) \
  1610. Catch::ScopedMessage INTERNAL_CATCH_UNIQUE_NAME( scopedMessage )( Catch::MessageBuilder( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, Catch::ResultWas::Info ) << log );
  1611. ///////////////////////////////////////////////////////////////////////////////
  1612. // Although this is matcher-based, it can be used with just a string
  1613. #define INTERNAL_CATCH_THROWS_STR_MATCHES( macroName, resultDisposition, matcher, ... ) \
  1614. do { \
  1615. Catch::AssertionHandler catchAssertionHandler( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(__VA_ARGS__) ", " CATCH_INTERNAL_STRINGIFY(matcher), resultDisposition ); \
  1616. if( catchAssertionHandler.allowThrows() ) \
  1617. try { \
  1618. static_cast<void>(__VA_ARGS__); \
  1619. catchAssertionHandler.handleUnexpectedExceptionNotThrown(); \
  1620. } \
  1621. catch( ... ) { \
  1622. Catch::handleExceptionMatchExpr( catchAssertionHandler, matcher, #matcher##_catch_sr ); \
  1623. } \
  1624. else \
  1625. catchAssertionHandler.handleThrowingCallSkipped(); \
  1626. INTERNAL_CATCH_REACT( catchAssertionHandler ) \
  1627. } while( false )
  1628. #endif // CATCH_CONFIG_DISABLE
  1629. // end catch_capture.hpp
  1630. // start catch_section.h
  1631. // start catch_section_info.h
  1632. // start catch_totals.h
  1633. #include <cstddef>
  1634. namespace Catch {
  1635. struct Counts {
  1636. Counts operator - ( Counts const& other ) const;
  1637. Counts& operator += ( Counts const& other );
  1638. std::size_t total() const;
  1639. bool allPassed() const;
  1640. bool allOk() const;
  1641. std::size_t passed = 0;
  1642. std::size_t failed = 0;
  1643. std::size_t failedButOk = 0;
  1644. };
  1645. struct Totals {
  1646. Totals operator - ( Totals const& other ) const;
  1647. Totals& operator += ( Totals const& other );
  1648. Totals delta( Totals const& prevTotals ) const;
  1649. int error = 0;
  1650. Counts assertions;
  1651. Counts testCases;
  1652. };
  1653. }
  1654. // end catch_totals.h
  1655. #include <string>
  1656. namespace Catch {
  1657. struct SectionInfo {
  1658. SectionInfo
  1659. ( SourceLineInfo const& _lineInfo,
  1660. std::string const& _name );
  1661. // Deprecated
  1662. SectionInfo
  1663. ( SourceLineInfo const& _lineInfo,
  1664. std::string const& _name,
  1665. std::string const& ) : SectionInfo( _lineInfo, _name ) {}
  1666. std::string name;
  1667. std::string description; // !Deprecated: this will always be empty
  1668. SourceLineInfo lineInfo;
  1669. };
  1670. struct SectionEndInfo {
  1671. SectionInfo sectionInfo;
  1672. Counts prevAssertions;
  1673. double durationInSeconds;
  1674. };
  1675. } // end namespace Catch
  1676. // end catch_section_info.h
  1677. // start catch_timer.h
  1678. #include <cstdint>
  1679. namespace Catch {
  1680. auto getCurrentNanosecondsSinceEpoch() -> uint64_t;
  1681. auto getEstimatedClockResolution() -> uint64_t;
  1682. class Timer {
  1683. uint64_t m_nanoseconds = 0;
  1684. public:
  1685. void start();
  1686. auto getElapsedNanoseconds() const -> uint64_t;
  1687. auto getElapsedMicroseconds() const -> uint64_t;
  1688. auto getElapsedMilliseconds() const -> unsigned int;
  1689. auto getElapsedSeconds() const -> double;
  1690. };
  1691. } // namespace Catch
  1692. // end catch_timer.h
  1693. #include <string>
  1694. namespace Catch {
  1695. class Section : NonCopyable {
  1696. public:
  1697. Section( SectionInfo const& info );
  1698. ~Section();
  1699. // This indicates whether the section should be executed or not
  1700. explicit operator bool() const;
  1701. private:
  1702. SectionInfo m_info;
  1703. std::string m_name;
  1704. Counts m_assertions;
  1705. bool m_sectionIncluded;
  1706. Timer m_timer;
  1707. };
  1708. } // end namespace Catch
  1709. #define INTERNAL_CATCH_SECTION( ... ) \
  1710. CATCH_INTERNAL_SUPPRESS_UNUSED_WARNINGS \
  1711. if( Catch::Section const& INTERNAL_CATCH_UNIQUE_NAME( catch_internal_Section ) = Catch::SectionInfo( CATCH_INTERNAL_LINEINFO, __VA_ARGS__ ) ) \
  1712. CATCH_INTERNAL_UNSUPPRESS_UNUSED_WARNINGS
  1713. #define INTERNAL_CATCH_DYNAMIC_SECTION( ... ) \
  1714. CATCH_INTERNAL_SUPPRESS_UNUSED_WARNINGS \
  1715. if( Catch::Section const& INTERNAL_CATCH_UNIQUE_NAME( catch_internal_Section ) = Catch::SectionInfo( CATCH_INTERNAL_LINEINFO, (Catch::ReusableStringStream() << __VA_ARGS__).str() ) ) \
  1716. CATCH_INTERNAL_UNSUPPRESS_UNUSED_WARNINGS
  1717. // end catch_section.h
  1718. // start catch_benchmark.h
  1719. #include <cstdint>
  1720. #include <string>
  1721. namespace Catch {
  1722. class BenchmarkLooper {
  1723. std::string m_name;
  1724. std::size_t m_count = 0;
  1725. std::size_t m_iterationsToRun = 1;
  1726. uint64_t m_resolution;
  1727. Timer m_timer;
  1728. static auto getResolution() -> uint64_t;
  1729. public:
  1730. // Keep most of this inline as it's on the code path that is being timed
  1731. BenchmarkLooper( StringRef name )
  1732. : m_name( name ),
  1733. m_resolution( getResolution() )
  1734. {
  1735. reportStart();
  1736. m_timer.start();
  1737. }
  1738. explicit operator bool() {
  1739. if( m_count < m_iterationsToRun )
  1740. return true;
  1741. return needsMoreIterations();
  1742. }
  1743. void increment() {
  1744. ++m_count;
  1745. }
  1746. void reportStart();
  1747. auto needsMoreIterations() -> bool;
  1748. };
  1749. } // end namespace Catch
  1750. #define BENCHMARK( name ) \
  1751. for( Catch::BenchmarkLooper looper( name ); looper; looper.increment() )
  1752. // end catch_benchmark.h
  1753. // start catch_interfaces_exception.h
  1754. // start catch_interfaces_registry_hub.h
  1755. #include <string>
  1756. #include <memory>
  1757. namespace Catch {
  1758. class TestCase;
  1759. struct ITestCaseRegistry;
  1760. struct IExceptionTranslatorRegistry;
  1761. struct IExceptionTranslator;
  1762. struct IReporterRegistry;
  1763. struct IReporterFactory;
  1764. struct ITagAliasRegistry;
  1765. class StartupExceptionRegistry;
  1766. using IReporterFactoryPtr = std::shared_ptr<IReporterFactory>;
  1767. struct IRegistryHub {
  1768. virtual ~IRegistryHub();
  1769. virtual IReporterRegistry const& getReporterRegistry() const = 0;
  1770. virtual ITestCaseRegistry const& getTestCaseRegistry() const = 0;
  1771. virtual ITagAliasRegistry const& getTagAliasRegistry() const = 0;
  1772. virtual IExceptionTranslatorRegistry const& getExceptionTranslatorRegistry() const = 0;
  1773. virtual StartupExceptionRegistry const& getStartupExceptionRegistry() const = 0;
  1774. };
  1775. struct IMutableRegistryHub {
  1776. virtual ~IMutableRegistryHub();
  1777. virtual void registerReporter( std::string const& name, IReporterFactoryPtr const& factory ) = 0;
  1778. virtual void registerListener( IReporterFactoryPtr const& factory ) = 0;
  1779. virtual void registerTest( TestCase const& testInfo ) = 0;
  1780. virtual void registerTranslator( const IExceptionTranslator* translator ) = 0;
  1781. virtual void registerTagAlias( std::string const& alias, std::string const& tag, SourceLineInfo const& lineInfo ) = 0;
  1782. virtual void registerStartupException() noexcept = 0;
  1783. };
  1784. IRegistryHub const& getRegistryHub();
  1785. IMutableRegistryHub& getMutableRegistryHub();
  1786. void cleanUp();
  1787. std::string translateActiveException();
  1788. }
  1789. // end catch_interfaces_registry_hub.h
  1790. #if defined(CATCH_CONFIG_DISABLE)
  1791. #define INTERNAL_CATCH_TRANSLATE_EXCEPTION_NO_REG( translatorName, signature) \
  1792. static std::string translatorName( signature )
  1793. #endif
  1794. #include <exception>
  1795. #include <string>
  1796. #include <vector>
  1797. namespace Catch {
  1798. using exceptionTranslateFunction = std::string(*)();
  1799. struct IExceptionTranslator;
  1800. using ExceptionTranslators = std::vector<std::unique_ptr<IExceptionTranslator const>>;
  1801. struct IExceptionTranslator {
  1802. virtual ~IExceptionTranslator();
  1803. virtual std::string translate( ExceptionTranslators::const_iterator it, ExceptionTranslators::const_iterator itEnd ) const = 0;
  1804. };
  1805. struct IExceptionTranslatorRegistry {
  1806. virtual ~IExceptionTranslatorRegistry();
  1807. virtual std::string translateActiveException() const = 0;
  1808. };
  1809. class ExceptionTranslatorRegistrar {
  1810. template<typename T>
  1811. class ExceptionTranslator : public IExceptionTranslator {
  1812. public:
  1813. ExceptionTranslator( std::string(*translateFunction)( T& ) )
  1814. : m_translateFunction( translateFunction )
  1815. {}
  1816. std::string translate( ExceptionTranslators::const_iterator it, ExceptionTranslators::const_iterator itEnd ) const override {
  1817. try {
  1818. if( it == itEnd )
  1819. std::rethrow_exception(std::current_exception());
  1820. else
  1821. return (*it)->translate( it+1, itEnd );
  1822. }
  1823. catch( T& ex ) {
  1824. return m_translateFunction( ex );
  1825. }
  1826. }
  1827. protected:
  1828. std::string(*m_translateFunction)( T& );
  1829. };
  1830. public:
  1831. template<typename T>
  1832. ExceptionTranslatorRegistrar( std::string(*translateFunction)( T& ) ) {
  1833. getMutableRegistryHub().registerTranslator
  1834. ( new ExceptionTranslator<T>( translateFunction ) );
  1835. }
  1836. };
  1837. }
  1838. ///////////////////////////////////////////////////////////////////////////////
  1839. #define INTERNAL_CATCH_TRANSLATE_EXCEPTION2( translatorName, signature ) \
  1840. static std::string translatorName( signature ); \
  1841. CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
  1842. namespace{ Catch::ExceptionTranslatorRegistrar INTERNAL_CATCH_UNIQUE_NAME( catch_internal_ExceptionRegistrar )( &translatorName ); } \
  1843. CATCH_INTERNAL_UNSUPPRESS_GLOBALS_WARNINGS \
  1844. static std::string translatorName( signature )
  1845. #define INTERNAL_CATCH_TRANSLATE_EXCEPTION( signature ) INTERNAL_CATCH_TRANSLATE_EXCEPTION2( INTERNAL_CATCH_UNIQUE_NAME( catch_internal_ExceptionTranslator ), signature )
  1846. // end catch_interfaces_exception.h
  1847. // start catch_approx.h
  1848. #include <type_traits>
  1849. namespace Catch {
  1850. namespace Detail {
  1851. class Approx {
  1852. private:
  1853. bool equalityComparisonImpl(double other) const;
  1854. // Validates the new margin (margin >= 0)
  1855. // out-of-line to avoid including stdexcept in the header
  1856. void setMargin(double margin);
  1857. // Validates the new epsilon (0 < epsilon < 1)
  1858. // out-of-line to avoid including stdexcept in the header
  1859. void setEpsilon(double epsilon);
  1860. public:
  1861. explicit Approx ( double value );
  1862. static Approx custom();
  1863. Approx operator-() const;
  1864. template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
  1865. Approx operator()( T const& value ) {
  1866. Approx approx( static_cast<double>(value) );
  1867. approx.m_epsilon = m_epsilon;
  1868. approx.m_margin = m_margin;
  1869. approx.m_scale = m_scale;
  1870. return approx;
  1871. }
  1872. template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
  1873. explicit Approx( T const& value ): Approx(static_cast<double>(value))
  1874. {}
  1875. template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
  1876. friend bool operator == ( const T& lhs, Approx const& rhs ) {
  1877. auto lhs_v = static_cast<double>(lhs);
  1878. return rhs.equalityComparisonImpl(lhs_v);
  1879. }
  1880. template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
  1881. friend bool operator == ( Approx const& lhs, const T& rhs ) {
  1882. return operator==( rhs, lhs );
  1883. }
  1884. template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
  1885. friend bool operator != ( T const& lhs, Approx const& rhs ) {
  1886. return !operator==( lhs, rhs );
  1887. }
  1888. template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
  1889. friend bool operator != ( Approx const& lhs, T const& rhs ) {
  1890. return !operator==( rhs, lhs );
  1891. }
  1892. template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
  1893. friend bool operator <= ( T const& lhs, Approx const& rhs ) {
  1894. return static_cast<double>(lhs) < rhs.m_value || lhs == rhs;
  1895. }
  1896. template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
  1897. friend bool operator <= ( Approx const& lhs, T const& rhs ) {
  1898. return lhs.m_value < static_cast<double>(rhs) || lhs == rhs;
  1899. }
  1900. template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
  1901. friend bool operator >= ( T const& lhs, Approx const& rhs ) {
  1902. return static_cast<double>(lhs) > rhs.m_value || lhs == rhs;
  1903. }
  1904. template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
  1905. friend bool operator >= ( Approx const& lhs, T const& rhs ) {
  1906. return lhs.m_value > static_cast<double>(rhs) || lhs == rhs;
  1907. }
  1908. template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
  1909. Approx& epsilon( T const& newEpsilon ) {
  1910. double epsilonAsDouble = static_cast<double>(newEpsilon);
  1911. setEpsilon(epsilonAsDouble);
  1912. return *this;
  1913. }
  1914. template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
  1915. Approx& margin( T const& newMargin ) {
  1916. double marginAsDouble = static_cast<double>(newMargin);
  1917. setMargin(marginAsDouble);
  1918. return *this;
  1919. }
  1920. template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
  1921. Approx& scale( T const& newScale ) {
  1922. m_scale = static_cast<double>(newScale);
  1923. return *this;
  1924. }
  1925. std::string toString() const;
  1926. private:
  1927. double m_epsilon;
  1928. double m_margin;
  1929. double m_scale;
  1930. double m_value;
  1931. };
  1932. } // end namespace Detail
  1933. namespace literals {
  1934. Detail::Approx operator "" _a(long double val);
  1935. Detail::Approx operator "" _a(unsigned long long val);
  1936. } // end namespace literals
  1937. template<>
  1938. struct StringMaker<Catch::Detail::Approx> {
  1939. static std::string convert(Catch::Detail::Approx const& value);
  1940. };
  1941. } // end namespace Catch
  1942. // end catch_approx.h
  1943. // start catch_string_manip.h
  1944. #include <string>
  1945. #include <iosfwd>
  1946. namespace Catch {
  1947. bool startsWith( std::string const& s, std::string const& prefix );
  1948. bool startsWith( std::string const& s, char prefix );
  1949. bool endsWith( std::string const& s, std::string const& suffix );
  1950. bool endsWith( std::string const& s, char suffix );
  1951. bool contains( std::string const& s, std::string const& infix );
  1952. void toLowerInPlace( std::string& s );
  1953. std::string toLower( std::string const& s );
  1954. std::string trim( std::string const& str );
  1955. bool replaceInPlace( std::string& str, std::string const& replaceThis, std::string const& withThis );
  1956. struct pluralise {
  1957. pluralise( std::size_t count, std::string const& label );
  1958. friend std::ostream& operator << ( std::ostream& os, pluralise const& pluraliser );
  1959. std::size_t m_count;
  1960. std::string m_label;
  1961. };
  1962. }
  1963. // end catch_string_manip.h
  1964. #ifndef CATCH_CONFIG_DISABLE_MATCHERS
  1965. // start catch_capture_matchers.h
  1966. // start catch_matchers.h
  1967. #include <string>
  1968. #include <vector>
  1969. namespace Catch {
  1970. namespace Matchers {
  1971. namespace Impl {
  1972. template<typename ArgT> struct MatchAllOf;
  1973. template<typename ArgT> struct MatchAnyOf;
  1974. template<typename ArgT> struct MatchNotOf;
  1975. class MatcherUntypedBase {
  1976. public:
  1977. MatcherUntypedBase() = default;
  1978. MatcherUntypedBase ( MatcherUntypedBase const& ) = default;
  1979. MatcherUntypedBase& operator = ( MatcherUntypedBase const& ) = delete;
  1980. std::string toString() const;
  1981. protected:
  1982. virtual ~MatcherUntypedBase();
  1983. virtual std::string describe() const = 0;
  1984. mutable std::string m_cachedToString;
  1985. };
  1986. #ifdef __clang__
  1987. # pragma clang diagnostic push
  1988. # pragma clang diagnostic ignored "-Wnon-virtual-dtor"
  1989. #endif
  1990. template<typename ObjectT>
  1991. struct MatcherMethod {
  1992. virtual bool match( ObjectT const& arg ) const = 0;
  1993. };
  1994. template<typename PtrT>
  1995. struct MatcherMethod<PtrT*> {
  1996. virtual bool match( PtrT* arg ) const = 0;
  1997. };
  1998. #ifdef __clang__
  1999. # pragma clang diagnostic pop
  2000. #endif
  2001. template<typename T>
  2002. struct MatcherBase : MatcherUntypedBase, MatcherMethod<T> {
  2003. MatchAllOf<T> operator && ( MatcherBase const& other ) const;
  2004. MatchAnyOf<T> operator || ( MatcherBase const& other ) const;
  2005. MatchNotOf<T> operator ! () const;
  2006. };
  2007. template<typename ArgT>
  2008. struct MatchAllOf : MatcherBase<ArgT> {
  2009. bool match( ArgT const& arg ) const override {
  2010. for( auto matcher : m_matchers ) {
  2011. if (!matcher->match(arg))
  2012. return false;
  2013. }
  2014. return true;
  2015. }
  2016. std::string describe() const override {
  2017. std::string description;
  2018. description.reserve( 4 + m_matchers.size()*32 );
  2019. description += "( ";
  2020. bool first = true;
  2021. for( auto matcher : m_matchers ) {
  2022. if( first )
  2023. first = false;
  2024. else
  2025. description += " and ";
  2026. description += matcher->toString();
  2027. }
  2028. description += " )";
  2029. return description;
  2030. }
  2031. MatchAllOf<ArgT>& operator && ( MatcherBase<ArgT> const& other ) {
  2032. m_matchers.push_back( &other );
  2033. return *this;
  2034. }
  2035. std::vector<MatcherBase<ArgT> const*> m_matchers;
  2036. };
  2037. template<typename ArgT>
  2038. struct MatchAnyOf : MatcherBase<ArgT> {
  2039. bool match( ArgT const& arg ) const override {
  2040. for( auto matcher : m_matchers ) {
  2041. if (matcher->match(arg))
  2042. return true;
  2043. }
  2044. return false;
  2045. }
  2046. std::string describe() const override {
  2047. std::string description;
  2048. description.reserve( 4 + m_matchers.size()*32 );
  2049. description += "( ";
  2050. bool first = true;
  2051. for( auto matcher : m_matchers ) {
  2052. if( first )
  2053. first = false;
  2054. else
  2055. description += " or ";
  2056. description += matcher->toString();
  2057. }
  2058. description += " )";
  2059. return description;
  2060. }
  2061. MatchAnyOf<ArgT>& operator || ( MatcherBase<ArgT> const& other ) {
  2062. m_matchers.push_back( &other );
  2063. return *this;
  2064. }
  2065. std::vector<MatcherBase<ArgT> const*> m_matchers;
  2066. };
  2067. template<typename ArgT>
  2068. struct MatchNotOf : MatcherBase<ArgT> {
  2069. MatchNotOf( MatcherBase<ArgT> const& underlyingMatcher ) : m_underlyingMatcher( underlyingMatcher ) {}
  2070. bool match( ArgT const& arg ) const override {
  2071. return !m_underlyingMatcher.match( arg );
  2072. }
  2073. std::string describe() const override {
  2074. return "not " + m_underlyingMatcher.toString();
  2075. }
  2076. MatcherBase<ArgT> const& m_underlyingMatcher;
  2077. };
  2078. template<typename T>
  2079. MatchAllOf<T> MatcherBase<T>::operator && ( MatcherBase const& other ) const {
  2080. return MatchAllOf<T>() && *this && other;
  2081. }
  2082. template<typename T>
  2083. MatchAnyOf<T> MatcherBase<T>::operator || ( MatcherBase const& other ) const {
  2084. return MatchAnyOf<T>() || *this || other;
  2085. }
  2086. template<typename T>
  2087. MatchNotOf<T> MatcherBase<T>::operator ! () const {
  2088. return MatchNotOf<T>( *this );
  2089. }
  2090. } // namespace Impl
  2091. } // namespace Matchers
  2092. using namespace Matchers;
  2093. using Matchers::Impl::MatcherBase;
  2094. } // namespace Catch
  2095. // end catch_matchers.h
  2096. // start catch_matchers_floating.h
  2097. #include <type_traits>
  2098. #include <cmath>
  2099. namespace Catch {
  2100. namespace Matchers {
  2101. namespace Floating {
  2102. enum class FloatingPointKind : uint8_t;
  2103. struct WithinAbsMatcher : MatcherBase<double> {
  2104. WithinAbsMatcher(double target, double margin);
  2105. bool match(double const& matchee) const override;
  2106. std::string describe() const override;
  2107. private:
  2108. double m_target;
  2109. double m_margin;
  2110. };
  2111. struct WithinUlpsMatcher : MatcherBase<double> {
  2112. WithinUlpsMatcher(double target, int ulps, FloatingPointKind baseType);
  2113. bool match(double const& matchee) const override;
  2114. std::string describe() const override;
  2115. private:
  2116. double m_target;
  2117. int m_ulps;
  2118. FloatingPointKind m_type;
  2119. };
  2120. } // namespace Floating
  2121. // The following functions create the actual matcher objects.
  2122. // This allows the types to be inferred
  2123. Floating::WithinUlpsMatcher WithinULP(double target, int maxUlpDiff);
  2124. Floating::WithinUlpsMatcher WithinULP(float target, int maxUlpDiff);
  2125. Floating::WithinAbsMatcher WithinAbs(double target, double margin);
  2126. } // namespace Matchers
  2127. } // namespace Catch
  2128. // end catch_matchers_floating.h
  2129. // start catch_matchers_generic.hpp
  2130. #include <functional>
  2131. #include <string>
  2132. namespace Catch {
  2133. namespace Matchers {
  2134. namespace Generic {
  2135. namespace Detail {
  2136. std::string finalizeDescription(const std::string& desc);
  2137. }
  2138. template <typename T>
  2139. class PredicateMatcher : public MatcherBase<T> {
  2140. std::function<bool(T const&)> m_predicate;
  2141. std::string m_description;
  2142. public:
  2143. PredicateMatcher(std::function<bool(T const&)> const& elem, std::string const& descr)
  2144. :m_predicate(std::move(elem)),
  2145. m_description(Detail::finalizeDescription(descr))
  2146. {}
  2147. bool match( T const& item ) const override {
  2148. return m_predicate(item);
  2149. }
  2150. std::string describe() const override {
  2151. return m_description;
  2152. }
  2153. };
  2154. } // namespace Generic
  2155. // The following functions create the actual matcher objects.
  2156. // The user has to explicitly specify type to the function, because
  2157. // infering std::function<bool(T const&)> is hard (but possible) and
  2158. // requires a lot of TMP.
  2159. template<typename T>
  2160. Generic::PredicateMatcher<T> Predicate(std::function<bool(T const&)> const& predicate, std::string const& description = "") {
  2161. return Generic::PredicateMatcher<T>(predicate, description);
  2162. }
  2163. } // namespace Matchers
  2164. } // namespace Catch
  2165. // end catch_matchers_generic.hpp
  2166. // start catch_matchers_string.h
  2167. #include <string>
  2168. namespace Catch {
  2169. namespace Matchers {
  2170. namespace StdString {
  2171. struct CasedString
  2172. {
  2173. CasedString( std::string const& str, CaseSensitive::Choice caseSensitivity );
  2174. std::string adjustString( std::string const& str ) const;
  2175. std::string caseSensitivitySuffix() const;
  2176. CaseSensitive::Choice m_caseSensitivity;
  2177. std::string m_str;
  2178. };
  2179. struct StringMatcherBase : MatcherBase<std::string> {
  2180. StringMatcherBase( std::string const& operation, CasedString const& comparator );
  2181. std::string describe() const override;
  2182. CasedString m_comparator;
  2183. std::string m_operation;
  2184. };
  2185. struct EqualsMatcher : StringMatcherBase {
  2186. EqualsMatcher( CasedString const& comparator );
  2187. bool match( std::string const& source ) const override;
  2188. };
  2189. struct ContainsMatcher : StringMatcherBase {
  2190. ContainsMatcher( CasedString const& comparator );
  2191. bool match( std::string const& source ) const override;
  2192. };
  2193. struct StartsWithMatcher : StringMatcherBase {
  2194. StartsWithMatcher( CasedString const& comparator );
  2195. bool match( std::string const& source ) const override;
  2196. };
  2197. struct EndsWithMatcher : StringMatcherBase {
  2198. EndsWithMatcher( CasedString const& comparator );
  2199. bool match( std::string const& source ) const override;
  2200. };
  2201. struct RegexMatcher : MatcherBase<std::string> {
  2202. RegexMatcher( std::string regex, CaseSensitive::Choice caseSensitivity );
  2203. bool match( std::string const& matchee ) const override;
  2204. std::string describe() const override;
  2205. private:
  2206. std::string m_regex;
  2207. CaseSensitive::Choice m_caseSensitivity;
  2208. };
  2209. } // namespace StdString
  2210. // The following functions create the actual matcher objects.
  2211. // This allows the types to be inferred
  2212. StdString::EqualsMatcher Equals( std::string const& str, CaseSensitive::Choice caseSensitivity = CaseSensitive::Yes );
  2213. StdString::ContainsMatcher Contains( std::string const& str, CaseSensitive::Choice caseSensitivity = CaseSensitive::Yes );
  2214. StdString::EndsWithMatcher EndsWith( std::string const& str, CaseSensitive::Choice caseSensitivity = CaseSensitive::Yes );
  2215. StdString::StartsWithMatcher StartsWith( std::string const& str, CaseSensitive::Choice caseSensitivity = CaseSensitive::Yes );
  2216. StdString::RegexMatcher Matches( std::string const& regex, CaseSensitive::Choice caseSensitivity = CaseSensitive::Yes );
  2217. } // namespace Matchers
  2218. } // namespace Catch
  2219. // end catch_matchers_string.h
  2220. // start catch_matchers_vector.h
  2221. #include <algorithm>
  2222. namespace Catch {
  2223. namespace Matchers {
  2224. namespace Vector {
  2225. namespace Detail {
  2226. template <typename InputIterator, typename T>
  2227. size_t count(InputIterator first, InputIterator last, T const& item) {
  2228. size_t cnt = 0;
  2229. for (; first != last; ++first) {
  2230. if (*first == item) {
  2231. ++cnt;
  2232. }
  2233. }
  2234. return cnt;
  2235. }
  2236. template <typename InputIterator, typename T>
  2237. bool contains(InputIterator first, InputIterator last, T const& item) {
  2238. for (; first != last; ++first) {
  2239. if (*first == item) {
  2240. return true;
  2241. }
  2242. }
  2243. return false;
  2244. }
  2245. }
  2246. template<typename T>
  2247. struct ContainsElementMatcher : MatcherBase<std::vector<T>> {
  2248. ContainsElementMatcher(T const &comparator) : m_comparator( comparator) {}
  2249. bool match(std::vector<T> const &v) const override {
  2250. for (auto const& el : v) {
  2251. if (el == m_comparator) {
  2252. return true;
  2253. }
  2254. }
  2255. return false;
  2256. }
  2257. std::string describe() const override {
  2258. return "Contains: " + ::Catch::Detail::stringify( m_comparator );
  2259. }
  2260. T const& m_comparator;
  2261. };
  2262. template<typename T>
  2263. struct ContainsMatcher : MatcherBase<std::vector<T>> {
  2264. ContainsMatcher(std::vector<T> const &comparator) : m_comparator( comparator ) {}
  2265. bool match(std::vector<T> const &v) const override {
  2266. // !TBD: see note in EqualsMatcher
  2267. if (m_comparator.size() > v.size())
  2268. return false;
  2269. for (auto const& comparator : m_comparator) {
  2270. auto present = false;
  2271. for (const auto& el : v) {
  2272. if (el == comparator) {
  2273. present = true;
  2274. break;
  2275. }
  2276. }
  2277. if (!present) {
  2278. return false;
  2279. }
  2280. }
  2281. return true;
  2282. }
  2283. std::string describe() const override {
  2284. return "Contains: " + ::Catch::Detail::stringify( m_comparator );
  2285. }
  2286. std::vector<T> const& m_comparator;
  2287. };
  2288. template<typename T>
  2289. struct EqualsMatcher : MatcherBase<std::vector<T>> {
  2290. EqualsMatcher(std::vector<T> const &comparator) : m_comparator( comparator ) {}
  2291. bool match(std::vector<T> const &v) const override {
  2292. // !TBD: This currently works if all elements can be compared using !=
  2293. // - a more general approach would be via a compare template that defaults
  2294. // to using !=. but could be specialised for, e.g. std::vector<T> etc
  2295. // - then just call that directly
  2296. if (m_comparator.size() != v.size())
  2297. return false;
  2298. for (std::size_t i = 0; i < v.size(); ++i)
  2299. if (m_comparator[i] != v[i])
  2300. return false;
  2301. return true;
  2302. }
  2303. std::string describe() const override {
  2304. return "Equals: " + ::Catch::Detail::stringify( m_comparator );
  2305. }
  2306. std::vector<T> const& m_comparator;
  2307. };
  2308. template<typename T>
  2309. struct UnorderedEqualsMatcher : MatcherBase<std::vector<T>> {
  2310. UnorderedEqualsMatcher(std::vector<T> const& target) : m_target(target) {}
  2311. bool match(std::vector<T> const& vec) const override {
  2312. // Note: This is a reimplementation of std::is_permutation,
  2313. // because I don't want to include <algorithm> inside the common path
  2314. if (m_target.size() != vec.size()) {
  2315. return false;
  2316. }
  2317. auto lfirst = m_target.begin(), llast = m_target.end();
  2318. auto rfirst = vec.begin(), rlast = vec.end();
  2319. // Cut common prefix to optimize checking of permuted parts
  2320. while (lfirst != llast && *lfirst == *rfirst) {
  2321. ++lfirst; ++rfirst;
  2322. }
  2323. if (lfirst == llast) {
  2324. return true;
  2325. }
  2326. for (auto mid = lfirst; mid != llast; ++mid) {
  2327. // Skip already counted items
  2328. if (Detail::contains(lfirst, mid, *mid)) {
  2329. continue;
  2330. }
  2331. size_t num_vec = Detail::count(rfirst, rlast, *mid);
  2332. if (num_vec == 0 || Detail::count(lfirst, llast, *mid) != num_vec) {
  2333. return false;
  2334. }
  2335. }
  2336. return true;
  2337. }
  2338. std::string describe() const override {
  2339. return "UnorderedEquals: " + ::Catch::Detail::stringify(m_target);
  2340. }
  2341. private:
  2342. std::vector<T> const& m_target;
  2343. };
  2344. } // namespace Vector
  2345. // The following functions create the actual matcher objects.
  2346. // This allows the types to be inferred
  2347. template<typename T>
  2348. Vector::ContainsMatcher<T> Contains( std::vector<T> const& comparator ) {
  2349. return Vector::ContainsMatcher<T>( comparator );
  2350. }
  2351. template<typename T>
  2352. Vector::ContainsElementMatcher<T> VectorContains( T const& comparator ) {
  2353. return Vector::ContainsElementMatcher<T>( comparator );
  2354. }
  2355. template<typename T>
  2356. Vector::EqualsMatcher<T> Equals( std::vector<T> const& comparator ) {
  2357. return Vector::EqualsMatcher<T>( comparator );
  2358. }
  2359. template<typename T>
  2360. Vector::UnorderedEqualsMatcher<T> UnorderedEquals(std::vector<T> const& target) {
  2361. return Vector::UnorderedEqualsMatcher<T>(target);
  2362. }
  2363. } // namespace Matchers
  2364. } // namespace Catch
  2365. // end catch_matchers_vector.h
  2366. namespace Catch {
  2367. template<typename ArgT, typename MatcherT>
  2368. class MatchExpr : public ITransientExpression {
  2369. ArgT const& m_arg;
  2370. MatcherT m_matcher;
  2371. StringRef m_matcherString;
  2372. public:
  2373. MatchExpr( ArgT const& arg, MatcherT const& matcher, StringRef const& matcherString )
  2374. : ITransientExpression{ true, matcher.match( arg ) },
  2375. m_arg( arg ),
  2376. m_matcher( matcher ),
  2377. m_matcherString( matcherString )
  2378. {}
  2379. void streamReconstructedExpression( std::ostream &os ) const override {
  2380. auto matcherAsString = m_matcher.toString();
  2381. os << Catch::Detail::stringify( m_arg ) << ' ';
  2382. if( matcherAsString == Detail::unprintableString )
  2383. os << m_matcherString;
  2384. else
  2385. os << matcherAsString;
  2386. }
  2387. };
  2388. using StringMatcher = Matchers::Impl::MatcherBase<std::string>;
  2389. void handleExceptionMatchExpr( AssertionHandler& handler, StringMatcher const& matcher, StringRef const& matcherString );
  2390. template<typename ArgT, typename MatcherT>
  2391. auto makeMatchExpr( ArgT const& arg, MatcherT const& matcher, StringRef const& matcherString ) -> MatchExpr<ArgT, MatcherT> {
  2392. return MatchExpr<ArgT, MatcherT>( arg, matcher, matcherString );
  2393. }
  2394. } // namespace Catch
  2395. ///////////////////////////////////////////////////////////////////////////////
  2396. #define INTERNAL_CHECK_THAT( macroName, matcher, resultDisposition, arg ) \
  2397. do { \
  2398. Catch::AssertionHandler catchAssertionHandler( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(arg) ", " CATCH_INTERNAL_STRINGIFY(matcher), resultDisposition ); \
  2399. INTERNAL_CATCH_TRY { \
  2400. catchAssertionHandler.handleExpr( Catch::makeMatchExpr( arg, matcher, #matcher##_catch_sr ) ); \
  2401. } INTERNAL_CATCH_CATCH( catchAssertionHandler ) \
  2402. INTERNAL_CATCH_REACT( catchAssertionHandler ) \
  2403. } while( false )
  2404. ///////////////////////////////////////////////////////////////////////////////
  2405. #define INTERNAL_CATCH_THROWS_MATCHES( macroName, exceptionType, resultDisposition, matcher, ... ) \
  2406. do { \
  2407. Catch::AssertionHandler catchAssertionHandler( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(__VA_ARGS__) ", " CATCH_INTERNAL_STRINGIFY(exceptionType) ", " CATCH_INTERNAL_STRINGIFY(matcher), resultDisposition ); \
  2408. if( catchAssertionHandler.allowThrows() ) \
  2409. try { \
  2410. static_cast<void>(__VA_ARGS__ ); \
  2411. catchAssertionHandler.handleUnexpectedExceptionNotThrown(); \
  2412. } \
  2413. catch( exceptionType const& ex ) { \
  2414. catchAssertionHandler.handleExpr( Catch::makeMatchExpr( ex, matcher, #matcher##_catch_sr ) ); \
  2415. } \
  2416. catch( ... ) { \
  2417. catchAssertionHandler.handleUnexpectedInflightException(); \
  2418. } \
  2419. else \
  2420. catchAssertionHandler.handleThrowingCallSkipped(); \
  2421. INTERNAL_CATCH_REACT( catchAssertionHandler ) \
  2422. } while( false )
  2423. // end catch_capture_matchers.h
  2424. #endif
  2425. // start catch_generators.hpp
  2426. // start catch_interfaces_generatortracker.h
  2427. #include <memory>
  2428. namespace Catch {
  2429. namespace Generators {
  2430. class GeneratorBase {
  2431. protected:
  2432. size_t m_size = 0;
  2433. public:
  2434. GeneratorBase( size_t size ) : m_size( size ) {}
  2435. virtual ~GeneratorBase();
  2436. auto size() const -> size_t { return m_size; }
  2437. };
  2438. using GeneratorBasePtr = std::unique_ptr<GeneratorBase>;
  2439. } // namespace Generators
  2440. struct IGeneratorTracker {
  2441. virtual ~IGeneratorTracker();
  2442. virtual auto hasGenerator() const -> bool = 0;
  2443. virtual auto getGenerator() const -> Generators::GeneratorBasePtr const& = 0;
  2444. virtual void setGenerator( Generators::GeneratorBasePtr&& generator ) = 0;
  2445. virtual auto getIndex() const -> std::size_t = 0;
  2446. };
  2447. } // namespace Catch
  2448. // end catch_interfaces_generatortracker.h
  2449. // start catch_enforce.h
  2450. #include <stdexcept>
  2451. namespace Catch {
  2452. #if !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
  2453. template <typename Ex>
  2454. [[noreturn]]
  2455. void throw_exception(Ex const& e) {
  2456. throw e;
  2457. }
  2458. #else // ^^ Exceptions are enabled // Exceptions are disabled vv
  2459. [[noreturn]]
  2460. void throw_exception(std::exception const& e);
  2461. #endif
  2462. } // namespace Catch;
  2463. #define CATCH_PREPARE_EXCEPTION( type, msg ) \
  2464. type( ( Catch::ReusableStringStream() << msg ).str() )
  2465. #define CATCH_INTERNAL_ERROR( msg ) \
  2466. Catch::throw_exception(CATCH_PREPARE_EXCEPTION( std::logic_error, CATCH_INTERNAL_LINEINFO << ": Internal Catch error: " << msg))
  2467. #define CATCH_ERROR( msg ) \
  2468. Catch::throw_exception(CATCH_PREPARE_EXCEPTION( std::domain_error, msg ))
  2469. #define CATCH_RUNTIME_ERROR( msg ) \
  2470. Catch::throw_exception(CATCH_PREPARE_EXCEPTION( std::runtime_error, msg ))
  2471. #define CATCH_ENFORCE( condition, msg ) \
  2472. do{ if( !(condition) ) CATCH_ERROR( msg ); } while(false)
  2473. // end catch_enforce.h
  2474. #include <memory>
  2475. #include <vector>
  2476. #include <cassert>
  2477. #include <utility>
  2478. namespace Catch {
  2479. namespace Generators {
  2480. // !TBD move this into its own location?
  2481. namespace pf{
  2482. template<typename T, typename... Args>
  2483. std::unique_ptr<T> make_unique( Args&&... args ) {
  2484. return std::unique_ptr<T>(new T(std::forward<Args>(args)...));
  2485. }
  2486. }
  2487. template<typename T>
  2488. struct IGenerator {
  2489. virtual ~IGenerator() {}
  2490. virtual auto get( size_t index ) const -> T = 0;
  2491. };
  2492. template<typename T>
  2493. class SingleValueGenerator : public IGenerator<T> {
  2494. T m_value;
  2495. public:
  2496. SingleValueGenerator( T const& value ) : m_value( value ) {}
  2497. auto get( size_t ) const -> T override {
  2498. return m_value;
  2499. }
  2500. };
  2501. template<typename T>
  2502. class FixedValuesGenerator : public IGenerator<T> {
  2503. std::vector<T> m_values;
  2504. public:
  2505. FixedValuesGenerator( std::initializer_list<T> values ) : m_values( values ) {}
  2506. auto get( size_t index ) const -> T override {
  2507. return m_values[index];
  2508. }
  2509. };
  2510. template<typename T>
  2511. class RangeGenerator : public IGenerator<T> {
  2512. T const m_first;
  2513. T const m_last;
  2514. public:
  2515. RangeGenerator( T const& first, T const& last ) : m_first( first ), m_last( last ) {
  2516. assert( m_last > m_first );
  2517. }
  2518. auto get( size_t index ) const -> T override {
  2519. // ToDo:: introduce a safe cast to catch potential overflows
  2520. return static_cast<T>(m_first+index);
  2521. }
  2522. };
  2523. template<typename T>
  2524. struct NullGenerator : IGenerator<T> {
  2525. auto get( size_t ) const -> T override {
  2526. CATCH_INTERNAL_ERROR("A Null Generator is always empty");
  2527. }
  2528. };
  2529. template<typename T>
  2530. class Generator {
  2531. std::unique_ptr<IGenerator<T>> m_generator;
  2532. size_t m_size;
  2533. public:
  2534. Generator( size_t size, std::unique_ptr<IGenerator<T>> generator )
  2535. : m_generator( std::move( generator ) ),
  2536. m_size( size )
  2537. {}
  2538. auto size() const -> size_t { return m_size; }
  2539. auto operator[]( size_t index ) const -> T {
  2540. assert( index < m_size );
  2541. return m_generator->get( index );
  2542. }
  2543. };
  2544. std::vector<size_t> randomiseIndices( size_t selectionSize, size_t sourceSize );
  2545. template<typename T>
  2546. class GeneratorRandomiser : public IGenerator<T> {
  2547. Generator<T> m_baseGenerator;
  2548. std::vector<size_t> m_indices;
  2549. public:
  2550. GeneratorRandomiser( Generator<T>&& baseGenerator, size_t numberOfItems )
  2551. : m_baseGenerator( std::move( baseGenerator ) ),
  2552. m_indices( randomiseIndices( numberOfItems, m_baseGenerator.size() ) )
  2553. {}
  2554. auto get( size_t index ) const -> T override {
  2555. return m_baseGenerator[m_indices[index]];
  2556. }
  2557. };
  2558. template<typename T>
  2559. struct RequiresASpecialisationFor;
  2560. template<typename T>
  2561. auto all() -> Generator<T> { return RequiresASpecialisationFor<T>(); }
  2562. template<>
  2563. auto all<int>() -> Generator<int>;
  2564. template<typename T>
  2565. auto range( T const& first, T const& last ) -> Generator<T> {
  2566. return Generator<T>( (last-first), pf::make_unique<RangeGenerator<T>>( first, last ) );
  2567. }
  2568. template<typename T>
  2569. auto random( T const& first, T const& last ) -> Generator<T> {
  2570. auto gen = range( first, last );
  2571. auto size = gen.size();
  2572. return Generator<T>( size, pf::make_unique<GeneratorRandomiser<T>>( std::move( gen ), size ) );
  2573. }
  2574. template<typename T>
  2575. auto random( size_t size ) -> Generator<T> {
  2576. return Generator<T>( size, pf::make_unique<GeneratorRandomiser<T>>( all<T>(), size ) );
  2577. }
  2578. template<typename T>
  2579. auto values( std::initializer_list<T> values ) -> Generator<T> {
  2580. return Generator<T>( values.size(), pf::make_unique<FixedValuesGenerator<T>>( values ) );
  2581. }
  2582. template<typename T>
  2583. auto value( T const& val ) -> Generator<T> {
  2584. return Generator<T>( 1, pf::make_unique<SingleValueGenerator<T>>( val ) );
  2585. }
  2586. template<typename T>
  2587. auto as() -> Generator<T> {
  2588. return Generator<T>( 0, pf::make_unique<NullGenerator<T>>() );
  2589. }
  2590. template<typename... Ts>
  2591. auto table( std::initializer_list<std::tuple<Ts...>>&& tuples ) -> Generator<std::tuple<Ts...>> {
  2592. return values<std::tuple<Ts...>>( std::forward<std::initializer_list<std::tuple<Ts...>>>( tuples ) );
  2593. }
  2594. template<typename T>
  2595. struct Generators : GeneratorBase {
  2596. std::vector<Generator<T>> m_generators;
  2597. using type = T;
  2598. Generators() : GeneratorBase( 0 ) {}
  2599. void populate( T&& val ) {
  2600. m_size += 1;
  2601. m_generators.emplace_back( value( std::move( val ) ) );
  2602. }
  2603. template<typename U>
  2604. void populate( U&& val ) {
  2605. populate( T( std::move( val ) ) );
  2606. }
  2607. void populate( Generator<T>&& generator ) {
  2608. m_size += generator.size();
  2609. m_generators.emplace_back( std::move( generator ) );
  2610. }
  2611. template<typename U, typename... Gs>
  2612. void populate( U&& valueOrGenerator, Gs... moreGenerators ) {
  2613. populate( std::forward<U>( valueOrGenerator ) );
  2614. populate( std::forward<Gs>( moreGenerators )... );
  2615. }
  2616. auto operator[]( size_t index ) const -> T {
  2617. size_t sizes = 0;
  2618. for( auto const& gen : m_generators ) {
  2619. auto localIndex = index-sizes;
  2620. sizes += gen.size();
  2621. if( index < sizes )
  2622. return gen[localIndex];
  2623. }
  2624. CATCH_INTERNAL_ERROR("Index '" << index << "' is out of range (" << sizes << ')');
  2625. }
  2626. };
  2627. template<typename T, typename... Gs>
  2628. auto makeGenerators( Generator<T>&& generator, Gs... moreGenerators ) -> Generators<T> {
  2629. Generators<T> generators;
  2630. generators.m_generators.reserve( 1+sizeof...(Gs) );
  2631. generators.populate( std::move( generator ), std::forward<Gs>( moreGenerators )... );
  2632. return generators;
  2633. }
  2634. template<typename T>
  2635. auto makeGenerators( Generator<T>&& generator ) -> Generators<T> {
  2636. Generators<T> generators;
  2637. generators.populate( std::move( generator ) );
  2638. return generators;
  2639. }
  2640. template<typename T, typename... Gs>
  2641. auto makeGenerators( T&& val, Gs... moreGenerators ) -> Generators<T> {
  2642. return makeGenerators( value( std::forward<T>( val ) ), std::forward<Gs>( moreGenerators )... );
  2643. }
  2644. template<typename T, typename U, typename... Gs>
  2645. auto makeGenerators( U&& val, Gs... moreGenerators ) -> Generators<T> {
  2646. return makeGenerators( value( T( std::forward<U>( val ) ) ), std::forward<Gs>( moreGenerators )... );
  2647. }
  2648. auto acquireGeneratorTracker( SourceLineInfo const& lineInfo ) -> IGeneratorTracker&;
  2649. template<typename L>
  2650. // Note: The type after -> is weird, because VS2015 cannot parse
  2651. // the expression used in the typedef inside, when it is in
  2652. // return type. Yeah, ¯\_(ツ)_/¯
  2653. auto generate( SourceLineInfo const& lineInfo, L const& generatorExpression ) -> decltype(std::declval<decltype(generatorExpression())>()[0]) {
  2654. using UnderlyingType = typename decltype(generatorExpression())::type;
  2655. IGeneratorTracker& tracker = acquireGeneratorTracker( lineInfo );
  2656. if( !tracker.hasGenerator() )
  2657. tracker.setGenerator( pf::make_unique<Generators<UnderlyingType>>( generatorExpression() ) );
  2658. auto const& generator = static_cast<Generators<UnderlyingType> const&>( *tracker.getGenerator() );
  2659. return generator[tracker.getIndex()];
  2660. }
  2661. } // namespace Generators
  2662. } // namespace Catch
  2663. #define GENERATE( ... ) \
  2664. Catch::Generators::generate( CATCH_INTERNAL_LINEINFO, []{ using namespace Catch::Generators; return makeGenerators( __VA_ARGS__ ); } )
  2665. // end catch_generators.hpp
  2666. // These files are included here so the single_include script doesn't put them
  2667. // in the conditionally compiled sections
  2668. // start catch_test_case_info.h
  2669. #include <string>
  2670. #include <vector>
  2671. #include <memory>
  2672. #ifdef __clang__
  2673. #pragma clang diagnostic push
  2674. #pragma clang diagnostic ignored "-Wpadded"
  2675. #endif
  2676. namespace Catch {
  2677. struct ITestInvoker;
  2678. struct TestCaseInfo {
  2679. enum SpecialProperties{
  2680. None = 0,
  2681. IsHidden = 1 << 1,
  2682. ShouldFail = 1 << 2,
  2683. MayFail = 1 << 3,
  2684. Throws = 1 << 4,
  2685. NonPortable = 1 << 5,
  2686. Benchmark = 1 << 6
  2687. };
  2688. TestCaseInfo( std::string const& _name,
  2689. std::string const& _className,
  2690. std::string const& _description,
  2691. std::vector<std::string> const& _tags,
  2692. SourceLineInfo const& _lineInfo );
  2693. friend void setTags( TestCaseInfo& testCaseInfo, std::vector<std::string> tags );
  2694. bool isHidden() const;
  2695. bool throws() const;
  2696. bool okToFail() const;
  2697. bool expectedToFail() const;
  2698. std::string tagsAsString() const;
  2699. std::string name;
  2700. std::string className;
  2701. std::string description;
  2702. std::vector<std::string> tags;
  2703. std::vector<std::string> lcaseTags;
  2704. SourceLineInfo lineInfo;
  2705. SpecialProperties properties;
  2706. };
  2707. class TestCase : public TestCaseInfo {
  2708. public:
  2709. TestCase( ITestInvoker* testCase, TestCaseInfo&& info );
  2710. TestCase withName( std::string const& _newName ) const;
  2711. void invoke() const;
  2712. TestCaseInfo const& getTestCaseInfo() const;
  2713. bool operator == ( TestCase const& other ) const;
  2714. bool operator < ( TestCase const& other ) const;
  2715. private:
  2716. std::shared_ptr<ITestInvoker> test;
  2717. };
  2718. TestCase makeTestCase( ITestInvoker* testCase,
  2719. std::string const& className,
  2720. NameAndTags const& nameAndTags,
  2721. SourceLineInfo const& lineInfo );
  2722. }
  2723. #ifdef __clang__
  2724. #pragma clang diagnostic pop
  2725. #endif
  2726. // end catch_test_case_info.h
  2727. // start catch_interfaces_runner.h
  2728. namespace Catch {
  2729. struct IRunner {
  2730. virtual ~IRunner();
  2731. virtual bool aborting() const = 0;
  2732. };
  2733. }
  2734. // end catch_interfaces_runner.h
  2735. #ifdef __OBJC__
  2736. // start catch_objc.hpp
  2737. #import <objc/runtime.h>
  2738. #include <string>
  2739. // NB. Any general catch headers included here must be included
  2740. // in catch.hpp first to make sure they are included by the single
  2741. // header for non obj-usage
  2742. ///////////////////////////////////////////////////////////////////////////////
  2743. // This protocol is really only here for (self) documenting purposes, since
  2744. // all its methods are optional.
  2745. @protocol OcFixture
  2746. @optional
  2747. -(void) setUp;
  2748. -(void) tearDown;
  2749. @end
  2750. namespace Catch {
  2751. class OcMethod : public ITestInvoker {
  2752. public:
  2753. OcMethod( Class cls, SEL sel ) : m_cls( cls ), m_sel( sel ) {}
  2754. virtual void invoke() const {
  2755. id obj = [[m_cls alloc] init];
  2756. performOptionalSelector( obj, @selector(setUp) );
  2757. performOptionalSelector( obj, m_sel );
  2758. performOptionalSelector( obj, @selector(tearDown) );
  2759. arcSafeRelease( obj );
  2760. }
  2761. private:
  2762. virtual ~OcMethod() {}
  2763. Class m_cls;
  2764. SEL m_sel;
  2765. };
  2766. namespace Detail{
  2767. inline std::string getAnnotation( Class cls,
  2768. std::string const& annotationName,
  2769. std::string const& testCaseName ) {
  2770. NSString* selStr = [[NSString alloc] initWithFormat:@"Catch_%s_%s", annotationName.c_str(), testCaseName.c_str()];
  2771. SEL sel = NSSelectorFromString( selStr );
  2772. arcSafeRelease( selStr );
  2773. id value = performOptionalSelector( cls, sel );
  2774. if( value )
  2775. return [(NSString*)value UTF8String];
  2776. return "";
  2777. }
  2778. }
  2779. inline std::size_t registerTestMethods() {
  2780. std::size_t noTestMethods = 0;
  2781. int noClasses = objc_getClassList( nullptr, 0 );
  2782. Class* classes = (CATCH_UNSAFE_UNRETAINED Class *)malloc( sizeof(Class) * noClasses);
  2783. objc_getClassList( classes, noClasses );
  2784. for( int c = 0; c < noClasses; c++ ) {
  2785. Class cls = classes[c];
  2786. {
  2787. u_int count;
  2788. Method* methods = class_copyMethodList( cls, &count );
  2789. for( u_int m = 0; m < count ; m++ ) {
  2790. SEL selector = method_getName(methods[m]);
  2791. std::string methodName = sel_getName(selector);
  2792. if( startsWith( methodName, "Catch_TestCase_" ) ) {
  2793. std::string testCaseName = methodName.substr( 15 );
  2794. std::string name = Detail::getAnnotation( cls, "Name", testCaseName );
  2795. std::string desc = Detail::getAnnotation( cls, "Description", testCaseName );
  2796. const char* className = class_getName( cls );
  2797. getMutableRegistryHub().registerTest( makeTestCase( new OcMethod( cls, selector ), className, NameAndTags( name.c_str(), desc.c_str() ), SourceLineInfo("",0) ) );
  2798. noTestMethods++;
  2799. }
  2800. }
  2801. free(methods);
  2802. }
  2803. }
  2804. return noTestMethods;
  2805. }
  2806. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  2807. namespace Matchers {
  2808. namespace Impl {
  2809. namespace NSStringMatchers {
  2810. struct StringHolder : MatcherBase<NSString*>{
  2811. StringHolder( NSString* substr ) : m_substr( [substr copy] ){}
  2812. StringHolder( StringHolder const& other ) : m_substr( [other.m_substr copy] ){}
  2813. StringHolder() {
  2814. arcSafeRelease( m_substr );
  2815. }
  2816. bool match( NSString* arg ) const override {
  2817. return false;
  2818. }
  2819. NSString* CATCH_ARC_STRONG m_substr;
  2820. };
  2821. struct Equals : StringHolder {
  2822. Equals( NSString* substr ) : StringHolder( substr ){}
  2823. bool match( NSString* str ) const override {
  2824. return (str != nil || m_substr == nil ) &&
  2825. [str isEqualToString:m_substr];
  2826. }
  2827. std::string describe() const override {
  2828. return "equals string: " + Catch::Detail::stringify( m_substr );
  2829. }
  2830. };
  2831. struct Contains : StringHolder {
  2832. Contains( NSString* substr ) : StringHolder( substr ){}
  2833. bool match( NSString* str ) const {
  2834. return (str != nil || m_substr == nil ) &&
  2835. [str rangeOfString:m_substr].location != NSNotFound;
  2836. }
  2837. std::string describe() const override {
  2838. return "contains string: " + Catch::Detail::stringify( m_substr );
  2839. }
  2840. };
  2841. struct StartsWith : StringHolder {
  2842. StartsWith( NSString* substr ) : StringHolder( substr ){}
  2843. bool match( NSString* str ) const override {
  2844. return (str != nil || m_substr == nil ) &&
  2845. [str rangeOfString:m_substr].location == 0;
  2846. }
  2847. std::string describe() const override {
  2848. return "starts with: " + Catch::Detail::stringify( m_substr );
  2849. }
  2850. };
  2851. struct EndsWith : StringHolder {
  2852. EndsWith( NSString* substr ) : StringHolder( substr ){}
  2853. bool match( NSString* str ) const override {
  2854. return (str != nil || m_substr == nil ) &&
  2855. [str rangeOfString:m_substr].location == [str length] - [m_substr length];
  2856. }
  2857. std::string describe() const override {
  2858. return "ends with: " + Catch::Detail::stringify( m_substr );
  2859. }
  2860. };
  2861. } // namespace NSStringMatchers
  2862. } // namespace Impl
  2863. inline Impl::NSStringMatchers::Equals
  2864. Equals( NSString* substr ){ return Impl::NSStringMatchers::Equals( substr ); }
  2865. inline Impl::NSStringMatchers::Contains
  2866. Contains( NSString* substr ){ return Impl::NSStringMatchers::Contains( substr ); }
  2867. inline Impl::NSStringMatchers::StartsWith
  2868. StartsWith( NSString* substr ){ return Impl::NSStringMatchers::StartsWith( substr ); }
  2869. inline Impl::NSStringMatchers::EndsWith
  2870. EndsWith( NSString* substr ){ return Impl::NSStringMatchers::EndsWith( substr ); }
  2871. } // namespace Matchers
  2872. using namespace Matchers;
  2873. #endif // CATCH_CONFIG_DISABLE_MATCHERS
  2874. } // namespace Catch
  2875. ///////////////////////////////////////////////////////////////////////////////
  2876. #define OC_MAKE_UNIQUE_NAME( root, uniqueSuffix ) root##uniqueSuffix
  2877. #define OC_TEST_CASE2( name, desc, uniqueSuffix ) \
  2878. +(NSString*) OC_MAKE_UNIQUE_NAME( Catch_Name_test_, uniqueSuffix ) \
  2879. { \
  2880. return @ name; \
  2881. } \
  2882. +(NSString*) OC_MAKE_UNIQUE_NAME( Catch_Description_test_, uniqueSuffix ) \
  2883. { \
  2884. return @ desc; \
  2885. } \
  2886. -(void) OC_MAKE_UNIQUE_NAME( Catch_TestCase_test_, uniqueSuffix )
  2887. #define OC_TEST_CASE( name, desc ) OC_TEST_CASE2( name, desc, __LINE__ )
  2888. // end catch_objc.hpp
  2889. #endif
  2890. #ifdef CATCH_CONFIG_EXTERNAL_INTERFACES
  2891. // start catch_external_interfaces.h
  2892. // start catch_reporter_bases.hpp
  2893. // start catch_interfaces_reporter.h
  2894. // start catch_config.hpp
  2895. // start catch_test_spec_parser.h
  2896. #ifdef __clang__
  2897. #pragma clang diagnostic push
  2898. #pragma clang diagnostic ignored "-Wpadded"
  2899. #endif
  2900. // start catch_test_spec.h
  2901. #ifdef __clang__
  2902. #pragma clang diagnostic push
  2903. #pragma clang diagnostic ignored "-Wpadded"
  2904. #endif
  2905. // start catch_wildcard_pattern.h
  2906. namespace Catch
  2907. {
  2908. class WildcardPattern {
  2909. enum WildcardPosition {
  2910. NoWildcard = 0,
  2911. WildcardAtStart = 1,
  2912. WildcardAtEnd = 2,
  2913. WildcardAtBothEnds = WildcardAtStart | WildcardAtEnd
  2914. };
  2915. public:
  2916. WildcardPattern( std::string const& pattern, CaseSensitive::Choice caseSensitivity );
  2917. virtual ~WildcardPattern() = default;
  2918. virtual bool matches( std::string const& str ) const;
  2919. private:
  2920. std::string adjustCase( std::string const& str ) const;
  2921. CaseSensitive::Choice m_caseSensitivity;
  2922. WildcardPosition m_wildcard = NoWildcard;
  2923. std::string m_pattern;
  2924. };
  2925. }
  2926. // end catch_wildcard_pattern.h
  2927. #include <string>
  2928. #include <vector>
  2929. #include <memory>
  2930. namespace Catch {
  2931. class TestSpec {
  2932. struct Pattern {
  2933. virtual ~Pattern();
  2934. virtual bool matches( TestCaseInfo const& testCase ) const = 0;
  2935. };
  2936. using PatternPtr = std::shared_ptr<Pattern>;
  2937. class NamePattern : public Pattern {
  2938. public:
  2939. NamePattern( std::string const& name );
  2940. virtual ~NamePattern();
  2941. virtual bool matches( TestCaseInfo const& testCase ) const override;
  2942. private:
  2943. WildcardPattern m_wildcardPattern;
  2944. };
  2945. class TagPattern : public Pattern {
  2946. public:
  2947. TagPattern( std::string const& tag );
  2948. virtual ~TagPattern();
  2949. virtual bool matches( TestCaseInfo const& testCase ) const override;
  2950. private:
  2951. std::string m_tag;
  2952. };
  2953. class ExcludedPattern : public Pattern {
  2954. public:
  2955. ExcludedPattern( PatternPtr const& underlyingPattern );
  2956. virtual ~ExcludedPattern();
  2957. virtual bool matches( TestCaseInfo const& testCase ) const override;
  2958. private:
  2959. PatternPtr m_underlyingPattern;
  2960. };
  2961. struct Filter {
  2962. std::vector<PatternPtr> m_patterns;
  2963. bool matches( TestCaseInfo const& testCase ) const;
  2964. };
  2965. public:
  2966. bool hasFilters() const;
  2967. bool matches( TestCaseInfo const& testCase ) const;
  2968. private:
  2969. std::vector<Filter> m_filters;
  2970. friend class TestSpecParser;
  2971. };
  2972. }
  2973. #ifdef __clang__
  2974. #pragma clang diagnostic pop
  2975. #endif
  2976. // end catch_test_spec.h
  2977. // start catch_interfaces_tag_alias_registry.h
  2978. #include <string>
  2979. namespace Catch {
  2980. struct TagAlias;
  2981. struct ITagAliasRegistry {
  2982. virtual ~ITagAliasRegistry();
  2983. // Nullptr if not present
  2984. virtual TagAlias const* find( std::string const& alias ) const = 0;
  2985. virtual std::string expandAliases( std::string const& unexpandedTestSpec ) const = 0;
  2986. static ITagAliasRegistry const& get();
  2987. };
  2988. } // end namespace Catch
  2989. // end catch_interfaces_tag_alias_registry.h
  2990. namespace Catch {
  2991. class TestSpecParser {
  2992. enum Mode{ None, Name, QuotedName, Tag, EscapedName };
  2993. Mode m_mode = None;
  2994. bool m_exclusion = false;
  2995. std::size_t m_start = std::string::npos, m_pos = 0;
  2996. std::string m_arg;
  2997. std::vector<std::size_t> m_escapeChars;
  2998. TestSpec::Filter m_currentFilter;
  2999. TestSpec m_testSpec;
  3000. ITagAliasRegistry const* m_tagAliases = nullptr;
  3001. public:
  3002. TestSpecParser( ITagAliasRegistry const& tagAliases );
  3003. TestSpecParser& parse( std::string const& arg );
  3004. TestSpec testSpec();
  3005. private:
  3006. void visitChar( char c );
  3007. void startNewMode( Mode mode, std::size_t start );
  3008. void escape();
  3009. std::string subString() const;
  3010. template<typename T>
  3011. void addPattern() {
  3012. std::string token = subString();
  3013. for( std::size_t i = 0; i < m_escapeChars.size(); ++i )
  3014. token = token.substr( 0, m_escapeChars[i]-m_start-i ) + token.substr( m_escapeChars[i]-m_start-i+1 );
  3015. m_escapeChars.clear();
  3016. if( startsWith( token, "exclude:" ) ) {
  3017. m_exclusion = true;
  3018. token = token.substr( 8 );
  3019. }
  3020. if( !token.empty() ) {
  3021. TestSpec::PatternPtr pattern = std::make_shared<T>( token );
  3022. if( m_exclusion )
  3023. pattern = std::make_shared<TestSpec::ExcludedPattern>( pattern );
  3024. m_currentFilter.m_patterns.push_back( pattern );
  3025. }
  3026. m_exclusion = false;
  3027. m_mode = None;
  3028. }
  3029. void addFilter();
  3030. };
  3031. TestSpec parseTestSpec( std::string const& arg );
  3032. } // namespace Catch
  3033. #ifdef __clang__
  3034. #pragma clang diagnostic pop
  3035. #endif
  3036. // end catch_test_spec_parser.h
  3037. // start catch_interfaces_config.h
  3038. #include <iosfwd>
  3039. #include <string>
  3040. #include <vector>
  3041. #include <memory>
  3042. namespace Catch {
  3043. enum class Verbosity {
  3044. Quiet = 0,
  3045. Normal,
  3046. High
  3047. };
  3048. struct WarnAbout { enum What {
  3049. Nothing = 0x00,
  3050. NoAssertions = 0x01,
  3051. NoTests = 0x02
  3052. }; };
  3053. struct ShowDurations { enum OrNot {
  3054. DefaultForReporter,
  3055. Always,
  3056. Never
  3057. }; };
  3058. struct RunTests { enum InWhatOrder {
  3059. InDeclarationOrder,
  3060. InLexicographicalOrder,
  3061. InRandomOrder
  3062. }; };
  3063. struct UseColour { enum YesOrNo {
  3064. Auto,
  3065. Yes,
  3066. No
  3067. }; };
  3068. struct WaitForKeypress { enum When {
  3069. Never,
  3070. BeforeStart = 1,
  3071. BeforeExit = 2,
  3072. BeforeStartAndExit = BeforeStart | BeforeExit
  3073. }; };
  3074. class TestSpec;
  3075. struct IConfig : NonCopyable {
  3076. virtual ~IConfig();
  3077. virtual bool allowThrows() const = 0;
  3078. virtual std::ostream& stream() const = 0;
  3079. virtual std::string name() const = 0;
  3080. virtual bool includeSuccessfulResults() const = 0;
  3081. virtual bool shouldDebugBreak() const = 0;
  3082. virtual bool warnAboutMissingAssertions() const = 0;
  3083. virtual bool warnAboutNoTests() const = 0;
  3084. virtual int abortAfter() const = 0;
  3085. virtual bool showInvisibles() const = 0;
  3086. virtual ShowDurations::OrNot showDurations() const = 0;
  3087. virtual TestSpec const& testSpec() const = 0;
  3088. virtual bool hasTestFilters() const = 0;
  3089. virtual RunTests::InWhatOrder runOrder() const = 0;
  3090. virtual unsigned int rngSeed() const = 0;
  3091. virtual int benchmarkResolutionMultiple() const = 0;
  3092. virtual UseColour::YesOrNo useColour() const = 0;
  3093. virtual std::vector<std::string> const& getSectionsToRun() const = 0;
  3094. virtual Verbosity verbosity() const = 0;
  3095. };
  3096. using IConfigPtr = std::shared_ptr<IConfig const>;
  3097. }
  3098. // end catch_interfaces_config.h
  3099. // Libstdc++ doesn't like incomplete classes for unique_ptr
  3100. #include <memory>
  3101. #include <vector>
  3102. #include <string>
  3103. #ifndef CATCH_CONFIG_CONSOLE_WIDTH
  3104. #define CATCH_CONFIG_CONSOLE_WIDTH 80
  3105. #endif
  3106. namespace Catch {
  3107. struct IStream;
  3108. struct ConfigData {
  3109. bool listTests = false;
  3110. bool listTags = false;
  3111. bool listReporters = false;
  3112. bool listTestNamesOnly = false;
  3113. bool showSuccessfulTests = false;
  3114. bool shouldDebugBreak = false;
  3115. bool noThrow = false;
  3116. bool showHelp = false;
  3117. bool showInvisibles = false;
  3118. bool filenamesAsTags = false;
  3119. bool libIdentify = false;
  3120. int abortAfter = -1;
  3121. unsigned int rngSeed = 0;
  3122. int benchmarkResolutionMultiple = 100;
  3123. Verbosity verbosity = Verbosity::Normal;
  3124. WarnAbout::What warnings = WarnAbout::Nothing;
  3125. ShowDurations::OrNot showDurations = ShowDurations::DefaultForReporter;
  3126. RunTests::InWhatOrder runOrder = RunTests::InDeclarationOrder;
  3127. UseColour::YesOrNo useColour = UseColour::Auto;
  3128. WaitForKeypress::When waitForKeypress = WaitForKeypress::Never;
  3129. std::string outputFilename;
  3130. std::string name;
  3131. std::string processName;
  3132. #ifndef CATCH_CONFIG_DEFAULT_REPORTER
  3133. #define CATCH_CONFIG_DEFAULT_REPORTER "console"
  3134. #endif
  3135. std::string reporterName = CATCH_CONFIG_DEFAULT_REPORTER;
  3136. #undef CATCH_CONFIG_DEFAULT_REPORTER
  3137. std::vector<std::string> testsOrTags;
  3138. std::vector<std::string> sectionsToRun;
  3139. };
  3140. class Config : public IConfig {
  3141. public:
  3142. Config() = default;
  3143. Config( ConfigData const& data );
  3144. virtual ~Config() = default;
  3145. std::string const& getFilename() const;
  3146. bool listTests() const;
  3147. bool listTestNamesOnly() const;
  3148. bool listTags() const;
  3149. bool listReporters() const;
  3150. std::string getProcessName() const;
  3151. std::string const& getReporterName() const;
  3152. std::vector<std::string> const& getTestsOrTags() const;
  3153. std::vector<std::string> const& getSectionsToRun() const override;
  3154. virtual TestSpec const& testSpec() const override;
  3155. bool hasTestFilters() const override;
  3156. bool showHelp() const;
  3157. // IConfig interface
  3158. bool allowThrows() const override;
  3159. std::ostream& stream() const override;
  3160. std::string name() const override;
  3161. bool includeSuccessfulResults() const override;
  3162. bool warnAboutMissingAssertions() const override;
  3163. bool warnAboutNoTests() const override;
  3164. ShowDurations::OrNot showDurations() const override;
  3165. RunTests::InWhatOrder runOrder() const override;
  3166. unsigned int rngSeed() const override;
  3167. int benchmarkResolutionMultiple() const override;
  3168. UseColour::YesOrNo useColour() const override;
  3169. bool shouldDebugBreak() const override;
  3170. int abortAfter() const override;
  3171. bool showInvisibles() const override;
  3172. Verbosity verbosity() const override;
  3173. private:
  3174. IStream const* openStream();
  3175. ConfigData m_data;
  3176. std::unique_ptr<IStream const> m_stream;
  3177. TestSpec m_testSpec;
  3178. bool m_hasTestFilters = false;
  3179. };
  3180. } // end namespace Catch
  3181. // end catch_config.hpp
  3182. // start catch_assertionresult.h
  3183. #include <string>
  3184. namespace Catch {
  3185. struct AssertionResultData
  3186. {
  3187. AssertionResultData() = delete;
  3188. AssertionResultData( ResultWas::OfType _resultType, LazyExpression const& _lazyExpression );
  3189. std::string message;
  3190. mutable std::string reconstructedExpression;
  3191. LazyExpression lazyExpression;
  3192. ResultWas::OfType resultType;
  3193. std::string reconstructExpression() const;
  3194. };
  3195. class AssertionResult {
  3196. public:
  3197. AssertionResult() = delete;
  3198. AssertionResult( AssertionInfo const& info, AssertionResultData const& data );
  3199. bool isOk() const;
  3200. bool succeeded() const;
  3201. ResultWas::OfType getResultType() const;
  3202. bool hasExpression() const;
  3203. bool hasMessage() const;
  3204. std::string getExpression() const;
  3205. std::string getExpressionInMacro() const;
  3206. bool hasExpandedExpression() const;
  3207. std::string getExpandedExpression() const;
  3208. std::string getMessage() const;
  3209. SourceLineInfo getSourceInfo() const;
  3210. StringRef getTestMacroName() const;
  3211. //protected:
  3212. AssertionInfo m_info;
  3213. AssertionResultData m_resultData;
  3214. };
  3215. } // end namespace Catch
  3216. // end catch_assertionresult.h
  3217. // start catch_option.hpp
  3218. namespace Catch {
  3219. // An optional type
  3220. template<typename T>
  3221. class Option {
  3222. public:
  3223. Option() : nullableValue( nullptr ) {}
  3224. Option( T const& _value )
  3225. : nullableValue( new( storage ) T( _value ) )
  3226. {}
  3227. Option( Option const& _other )
  3228. : nullableValue( _other ? new( storage ) T( *_other ) : nullptr )
  3229. {}
  3230. ~Option() {
  3231. reset();
  3232. }
  3233. Option& operator= ( Option const& _other ) {
  3234. if( &_other != this ) {
  3235. reset();
  3236. if( _other )
  3237. nullableValue = new( storage ) T( *_other );
  3238. }
  3239. return *this;
  3240. }
  3241. Option& operator = ( T const& _value ) {
  3242. reset();
  3243. nullableValue = new( storage ) T( _value );
  3244. return *this;
  3245. }
  3246. void reset() {
  3247. if( nullableValue )
  3248. nullableValue->~T();
  3249. nullableValue = nullptr;
  3250. }
  3251. T& operator*() { return *nullableValue; }
  3252. T const& operator*() const { return *nullableValue; }
  3253. T* operator->() { return nullableValue; }
  3254. const T* operator->() const { return nullableValue; }
  3255. T valueOr( T const& defaultValue ) const {
  3256. return nullableValue ? *nullableValue : defaultValue;
  3257. }
  3258. bool some() const { return nullableValue != nullptr; }
  3259. bool none() const { return nullableValue == nullptr; }
  3260. bool operator !() const { return nullableValue == nullptr; }
  3261. explicit operator bool() const {
  3262. return some();
  3263. }
  3264. private:
  3265. T *nullableValue;
  3266. alignas(alignof(T)) char storage[sizeof(T)];
  3267. };
  3268. } // end namespace Catch
  3269. // end catch_option.hpp
  3270. #include <string>
  3271. #include <iosfwd>
  3272. #include <map>
  3273. #include <set>
  3274. #include <memory>
  3275. namespace Catch {
  3276. struct ReporterConfig {
  3277. explicit ReporterConfig( IConfigPtr const& _fullConfig );
  3278. ReporterConfig( IConfigPtr const& _fullConfig, std::ostream& _stream );
  3279. std::ostream& stream() const;
  3280. IConfigPtr fullConfig() const;
  3281. private:
  3282. std::ostream* m_stream;
  3283. IConfigPtr m_fullConfig;
  3284. };
  3285. struct ReporterPreferences {
  3286. bool shouldRedirectStdOut = false;
  3287. bool shouldReportAllAssertions = false;
  3288. };
  3289. template<typename T>
  3290. struct LazyStat : Option<T> {
  3291. LazyStat& operator=( T const& _value ) {
  3292. Option<T>::operator=( _value );
  3293. used = false;
  3294. return *this;
  3295. }
  3296. void reset() {
  3297. Option<T>::reset();
  3298. used = false;
  3299. }
  3300. bool used = false;
  3301. };
  3302. struct TestRunInfo {
  3303. TestRunInfo( std::string const& _name );
  3304. std::string name;
  3305. };
  3306. struct GroupInfo {
  3307. GroupInfo( std::string const& _name,
  3308. std::size_t _groupIndex,
  3309. std::size_t _groupsCount );
  3310. std::string name;
  3311. std::size_t groupIndex;
  3312. std::size_t groupsCounts;
  3313. };
  3314. struct AssertionStats {
  3315. AssertionStats( AssertionResult const& _assertionResult,
  3316. std::vector<MessageInfo> const& _infoMessages,
  3317. Totals const& _totals );
  3318. AssertionStats( AssertionStats const& ) = default;
  3319. AssertionStats( AssertionStats && ) = default;
  3320. AssertionStats& operator = ( AssertionStats const& ) = default;
  3321. AssertionStats& operator = ( AssertionStats && ) = default;
  3322. virtual ~AssertionStats();
  3323. AssertionResult assertionResult;
  3324. std::vector<MessageInfo> infoMessages;
  3325. Totals totals;
  3326. };
  3327. struct SectionStats {
  3328. SectionStats( SectionInfo const& _sectionInfo,
  3329. Counts const& _assertions,
  3330. double _durationInSeconds,
  3331. bool _missingAssertions );
  3332. SectionStats( SectionStats const& ) = default;
  3333. SectionStats( SectionStats && ) = default;
  3334. SectionStats& operator = ( SectionStats const& ) = default;
  3335. SectionStats& operator = ( SectionStats && ) = default;
  3336. virtual ~SectionStats();
  3337. SectionInfo sectionInfo;
  3338. Counts assertions;
  3339. double durationInSeconds;
  3340. bool missingAssertions;
  3341. };
  3342. struct TestCaseStats {
  3343. TestCaseStats( TestCaseInfo const& _testInfo,
  3344. Totals const& _totals,
  3345. std::string const& _stdOut,
  3346. std::string const& _stdErr,
  3347. bool _aborting );
  3348. TestCaseStats( TestCaseStats const& ) = default;
  3349. TestCaseStats( TestCaseStats && ) = default;
  3350. TestCaseStats& operator = ( TestCaseStats const& ) = default;
  3351. TestCaseStats& operator = ( TestCaseStats && ) = default;
  3352. virtual ~TestCaseStats();
  3353. TestCaseInfo testInfo;
  3354. Totals totals;
  3355. std::string stdOut;
  3356. std::string stdErr;
  3357. bool aborting;
  3358. };
  3359. struct TestGroupStats {
  3360. TestGroupStats( GroupInfo const& _groupInfo,
  3361. Totals const& _totals,
  3362. bool _aborting );
  3363. TestGroupStats( GroupInfo const& _groupInfo );
  3364. TestGroupStats( TestGroupStats const& ) = default;
  3365. TestGroupStats( TestGroupStats && ) = default;
  3366. TestGroupStats& operator = ( TestGroupStats const& ) = default;
  3367. TestGroupStats& operator = ( TestGroupStats && ) = default;
  3368. virtual ~TestGroupStats();
  3369. GroupInfo groupInfo;
  3370. Totals totals;
  3371. bool aborting;
  3372. };
  3373. struct TestRunStats {
  3374. TestRunStats( TestRunInfo const& _runInfo,
  3375. Totals const& _totals,
  3376. bool _aborting );
  3377. TestRunStats( TestRunStats const& ) = default;
  3378. TestRunStats( TestRunStats && ) = default;
  3379. TestRunStats& operator = ( TestRunStats const& ) = default;
  3380. TestRunStats& operator = ( TestRunStats && ) = default;
  3381. virtual ~TestRunStats();
  3382. TestRunInfo runInfo;
  3383. Totals totals;
  3384. bool aborting;
  3385. };
  3386. struct BenchmarkInfo {
  3387. std::string name;
  3388. };
  3389. struct BenchmarkStats {
  3390. BenchmarkInfo info;
  3391. std::size_t iterations;
  3392. uint64_t elapsedTimeInNanoseconds;
  3393. };
  3394. struct IStreamingReporter {
  3395. virtual ~IStreamingReporter() = default;
  3396. // Implementing class must also provide the following static methods:
  3397. // static std::string getDescription();
  3398. // static std::set<Verbosity> getSupportedVerbosities()
  3399. virtual ReporterPreferences getPreferences() const = 0;
  3400. virtual void noMatchingTestCases( std::string const& spec ) = 0;
  3401. virtual void testRunStarting( TestRunInfo const& testRunInfo ) = 0;
  3402. virtual void testGroupStarting( GroupInfo const& groupInfo ) = 0;
  3403. virtual void testCaseStarting( TestCaseInfo const& testInfo ) = 0;
  3404. virtual void sectionStarting( SectionInfo const& sectionInfo ) = 0;
  3405. // *** experimental ***
  3406. virtual void benchmarkStarting( BenchmarkInfo const& ) {}
  3407. virtual void assertionStarting( AssertionInfo const& assertionInfo ) = 0;
  3408. // The return value indicates if the messages buffer should be cleared:
  3409. virtual bool assertionEnded( AssertionStats const& assertionStats ) = 0;
  3410. // *** experimental ***
  3411. virtual void benchmarkEnded( BenchmarkStats const& ) {}
  3412. virtual void sectionEnded( SectionStats const& sectionStats ) = 0;
  3413. virtual void testCaseEnded( TestCaseStats const& testCaseStats ) = 0;
  3414. virtual void testGroupEnded( TestGroupStats const& testGroupStats ) = 0;
  3415. virtual void testRunEnded( TestRunStats const& testRunStats ) = 0;
  3416. virtual void skipTest( TestCaseInfo const& testInfo ) = 0;
  3417. // Default empty implementation provided
  3418. virtual void fatalErrorEncountered( StringRef name );
  3419. virtual bool isMulti() const;
  3420. };
  3421. using IStreamingReporterPtr = std::unique_ptr<IStreamingReporter>;
  3422. struct IReporterFactory {
  3423. virtual ~IReporterFactory();
  3424. virtual IStreamingReporterPtr create( ReporterConfig const& config ) const = 0;
  3425. virtual std::string getDescription() const = 0;
  3426. };
  3427. using IReporterFactoryPtr = std::shared_ptr<IReporterFactory>;
  3428. struct IReporterRegistry {
  3429. using FactoryMap = std::map<std::string, IReporterFactoryPtr>;
  3430. using Listeners = std::vector<IReporterFactoryPtr>;
  3431. virtual ~IReporterRegistry();
  3432. virtual IStreamingReporterPtr create( std::string const& name, IConfigPtr const& config ) const = 0;
  3433. virtual FactoryMap const& getFactories() const = 0;
  3434. virtual Listeners const& getListeners() const = 0;
  3435. };
  3436. } // end namespace Catch
  3437. // end catch_interfaces_reporter.h
  3438. #include <algorithm>
  3439. #include <cstring>
  3440. #include <cfloat>
  3441. #include <cstdio>
  3442. #include <cassert>
  3443. #include <memory>
  3444. #include <ostream>
  3445. namespace Catch {
  3446. void prepareExpandedExpression(AssertionResult& result);
  3447. // Returns double formatted as %.3f (format expected on output)
  3448. std::string getFormattedDuration( double duration );
  3449. template<typename DerivedT>
  3450. struct StreamingReporterBase : IStreamingReporter {
  3451. StreamingReporterBase( ReporterConfig const& _config )
  3452. : m_config( _config.fullConfig() ),
  3453. stream( _config.stream() )
  3454. {
  3455. m_reporterPrefs.shouldRedirectStdOut = false;
  3456. if( !DerivedT::getSupportedVerbosities().count( m_config->verbosity() ) )
  3457. CATCH_ERROR( "Verbosity level not supported by this reporter" );
  3458. }
  3459. ReporterPreferences getPreferences() const override {
  3460. return m_reporterPrefs;
  3461. }
  3462. static std::set<Verbosity> getSupportedVerbosities() {
  3463. return { Verbosity::Normal };
  3464. }
  3465. ~StreamingReporterBase() override = default;
  3466. void noMatchingTestCases(std::string const&) override {}
  3467. void testRunStarting(TestRunInfo const& _testRunInfo) override {
  3468. currentTestRunInfo = _testRunInfo;
  3469. }
  3470. void testGroupStarting(GroupInfo const& _groupInfo) override {
  3471. currentGroupInfo = _groupInfo;
  3472. }
  3473. void testCaseStarting(TestCaseInfo const& _testInfo) override {
  3474. currentTestCaseInfo = _testInfo;
  3475. }
  3476. void sectionStarting(SectionInfo const& _sectionInfo) override {
  3477. m_sectionStack.push_back(_sectionInfo);
  3478. }
  3479. void sectionEnded(SectionStats const& /* _sectionStats */) override {
  3480. m_sectionStack.pop_back();
  3481. }
  3482. void testCaseEnded(TestCaseStats const& /* _testCaseStats */) override {
  3483. currentTestCaseInfo.reset();
  3484. }
  3485. void testGroupEnded(TestGroupStats const& /* _testGroupStats */) override {
  3486. currentGroupInfo.reset();
  3487. }
  3488. void testRunEnded(TestRunStats const& /* _testRunStats */) override {
  3489. currentTestCaseInfo.reset();
  3490. currentGroupInfo.reset();
  3491. currentTestRunInfo.reset();
  3492. }
  3493. void skipTest(TestCaseInfo const&) override {
  3494. // Don't do anything with this by default.
  3495. // It can optionally be overridden in the derived class.
  3496. }
  3497. IConfigPtr m_config;
  3498. std::ostream& stream;
  3499. LazyStat<TestRunInfo> currentTestRunInfo;
  3500. LazyStat<GroupInfo> currentGroupInfo;
  3501. LazyStat<TestCaseInfo> currentTestCaseInfo;
  3502. std::vector<SectionInfo> m_sectionStack;
  3503. ReporterPreferences m_reporterPrefs;
  3504. };
  3505. template<typename DerivedT>
  3506. struct CumulativeReporterBase : IStreamingReporter {
  3507. template<typename T, typename ChildNodeT>
  3508. struct Node {
  3509. explicit Node( T const& _value ) : value( _value ) {}
  3510. virtual ~Node() {}
  3511. using ChildNodes = std::vector<std::shared_ptr<ChildNodeT>>;
  3512. T value;
  3513. ChildNodes children;
  3514. };
  3515. struct SectionNode {
  3516. explicit SectionNode(SectionStats const& _stats) : stats(_stats) {}
  3517. virtual ~SectionNode() = default;
  3518. bool operator == (SectionNode const& other) const {
  3519. return stats.sectionInfo.lineInfo == other.stats.sectionInfo.lineInfo;
  3520. }
  3521. bool operator == (std::shared_ptr<SectionNode> const& other) const {
  3522. return operator==(*other);
  3523. }
  3524. SectionStats stats;
  3525. using ChildSections = std::vector<std::shared_ptr<SectionNode>>;
  3526. using Assertions = std::vector<AssertionStats>;
  3527. ChildSections childSections;
  3528. Assertions assertions;
  3529. std::string stdOut;
  3530. std::string stdErr;
  3531. };
  3532. struct BySectionInfo {
  3533. BySectionInfo( SectionInfo const& other ) : m_other( other ) {}
  3534. BySectionInfo( BySectionInfo const& other ) : m_other( other.m_other ) {}
  3535. bool operator() (std::shared_ptr<SectionNode> const& node) const {
  3536. return ((node->stats.sectionInfo.name == m_other.name) &&
  3537. (node->stats.sectionInfo.lineInfo == m_other.lineInfo));
  3538. }
  3539. void operator=(BySectionInfo const&) = delete;
  3540. private:
  3541. SectionInfo const& m_other;
  3542. };
  3543. using TestCaseNode = Node<TestCaseStats, SectionNode>;
  3544. using TestGroupNode = Node<TestGroupStats, TestCaseNode>;
  3545. using TestRunNode = Node<TestRunStats, TestGroupNode>;
  3546. CumulativeReporterBase( ReporterConfig const& _config )
  3547. : m_config( _config.fullConfig() ),
  3548. stream( _config.stream() )
  3549. {
  3550. m_reporterPrefs.shouldRedirectStdOut = false;
  3551. if( !DerivedT::getSupportedVerbosities().count( m_config->verbosity() ) )
  3552. CATCH_ERROR( "Verbosity level not supported by this reporter" );
  3553. }
  3554. ~CumulativeReporterBase() override = default;
  3555. ReporterPreferences getPreferences() const override {
  3556. return m_reporterPrefs;
  3557. }
  3558. static std::set<Verbosity> getSupportedVerbosities() {
  3559. return { Verbosity::Normal };
  3560. }
  3561. void testRunStarting( TestRunInfo const& ) override {}
  3562. void testGroupStarting( GroupInfo const& ) override {}
  3563. void testCaseStarting( TestCaseInfo const& ) override {}
  3564. void sectionStarting( SectionInfo const& sectionInfo ) override {
  3565. SectionStats incompleteStats( sectionInfo, Counts(), 0, false );
  3566. std::shared_ptr<SectionNode> node;
  3567. if( m_sectionStack.empty() ) {
  3568. if( !m_rootSection )
  3569. m_rootSection = std::make_shared<SectionNode>( incompleteStats );
  3570. node = m_rootSection;
  3571. }
  3572. else {
  3573. SectionNode& parentNode = *m_sectionStack.back();
  3574. auto it =
  3575. std::find_if( parentNode.childSections.begin(),
  3576. parentNode.childSections.end(),
  3577. BySectionInfo( sectionInfo ) );
  3578. if( it == parentNode.childSections.end() ) {
  3579. node = std::make_shared<SectionNode>( incompleteStats );
  3580. parentNode.childSections.push_back( node );
  3581. }
  3582. else
  3583. node = *it;
  3584. }
  3585. m_sectionStack.push_back( node );
  3586. m_deepestSection = std::move(node);
  3587. }
  3588. void assertionStarting(AssertionInfo const&) override {}
  3589. bool assertionEnded(AssertionStats const& assertionStats) override {
  3590. assert(!m_sectionStack.empty());
  3591. // AssertionResult holds a pointer to a temporary DecomposedExpression,
  3592. // which getExpandedExpression() calls to build the expression string.
  3593. // Our section stack copy of the assertionResult will likely outlive the
  3594. // temporary, so it must be expanded or discarded now to avoid calling
  3595. // a destroyed object later.
  3596. prepareExpandedExpression(const_cast<AssertionResult&>( assertionStats.assertionResult ) );
  3597. SectionNode& sectionNode = *m_sectionStack.back();
  3598. sectionNode.assertions.push_back(assertionStats);
  3599. return true;
  3600. }
  3601. void sectionEnded(SectionStats const& sectionStats) override {
  3602. assert(!m_sectionStack.empty());
  3603. SectionNode& node = *m_sectionStack.back();
  3604. node.stats = sectionStats;
  3605. m_sectionStack.pop_back();
  3606. }
  3607. void testCaseEnded(TestCaseStats const& testCaseStats) override {
  3608. auto node = std::make_shared<TestCaseNode>(testCaseStats);
  3609. assert(m_sectionStack.size() == 0);
  3610. node->children.push_back(m_rootSection);
  3611. m_testCases.push_back(node);
  3612. m_rootSection.reset();
  3613. assert(m_deepestSection);
  3614. m_deepestSection->stdOut = testCaseStats.stdOut;
  3615. m_deepestSection->stdErr = testCaseStats.stdErr;
  3616. }
  3617. void testGroupEnded(TestGroupStats const& testGroupStats) override {
  3618. auto node = std::make_shared<TestGroupNode>(testGroupStats);
  3619. node->children.swap(m_testCases);
  3620. m_testGroups.push_back(node);
  3621. }
  3622. void testRunEnded(TestRunStats const& testRunStats) override {
  3623. auto node = std::make_shared<TestRunNode>(testRunStats);
  3624. node->children.swap(m_testGroups);
  3625. m_testRuns.push_back(node);
  3626. testRunEndedCumulative();
  3627. }
  3628. virtual void testRunEndedCumulative() = 0;
  3629. void skipTest(TestCaseInfo const&) override {}
  3630. IConfigPtr m_config;
  3631. std::ostream& stream;
  3632. std::vector<AssertionStats> m_assertions;
  3633. std::vector<std::vector<std::shared_ptr<SectionNode>>> m_sections;
  3634. std::vector<std::shared_ptr<TestCaseNode>> m_testCases;
  3635. std::vector<std::shared_ptr<TestGroupNode>> m_testGroups;
  3636. std::vector<std::shared_ptr<TestRunNode>> m_testRuns;
  3637. std::shared_ptr<SectionNode> m_rootSection;
  3638. std::shared_ptr<SectionNode> m_deepestSection;
  3639. std::vector<std::shared_ptr<SectionNode>> m_sectionStack;
  3640. ReporterPreferences m_reporterPrefs;
  3641. };
  3642. template<char C>
  3643. char const* getLineOfChars() {
  3644. static char line[CATCH_CONFIG_CONSOLE_WIDTH] = {0};
  3645. if( !*line ) {
  3646. std::memset( line, C, CATCH_CONFIG_CONSOLE_WIDTH-1 );
  3647. line[CATCH_CONFIG_CONSOLE_WIDTH-1] = 0;
  3648. }
  3649. return line;
  3650. }
  3651. struct TestEventListenerBase : StreamingReporterBase<TestEventListenerBase> {
  3652. TestEventListenerBase( ReporterConfig const& _config );
  3653. void assertionStarting(AssertionInfo const&) override;
  3654. bool assertionEnded(AssertionStats const&) override;
  3655. };
  3656. } // end namespace Catch
  3657. // end catch_reporter_bases.hpp
  3658. // start catch_console_colour.h
  3659. namespace Catch {
  3660. struct Colour {
  3661. enum Code {
  3662. None = 0,
  3663. White,
  3664. Red,
  3665. Green,
  3666. Blue,
  3667. Cyan,
  3668. Yellow,
  3669. Grey,
  3670. Bright = 0x10,
  3671. BrightRed = Bright | Red,
  3672. BrightGreen = Bright | Green,
  3673. LightGrey = Bright | Grey,
  3674. BrightWhite = Bright | White,
  3675. BrightYellow = Bright | Yellow,
  3676. // By intention
  3677. FileName = LightGrey,
  3678. Warning = BrightYellow,
  3679. ResultError = BrightRed,
  3680. ResultSuccess = BrightGreen,
  3681. ResultExpectedFailure = Warning,
  3682. Error = BrightRed,
  3683. Success = Green,
  3684. OriginalExpression = Cyan,
  3685. ReconstructedExpression = BrightYellow,
  3686. SecondaryText = LightGrey,
  3687. Headers = White
  3688. };
  3689. // Use constructed object for RAII guard
  3690. Colour( Code _colourCode );
  3691. Colour( Colour&& other ) noexcept;
  3692. Colour& operator=( Colour&& other ) noexcept;
  3693. ~Colour();
  3694. // Use static method for one-shot changes
  3695. static void use( Code _colourCode );
  3696. private:
  3697. bool m_moved = false;
  3698. };
  3699. std::ostream& operator << ( std::ostream& os, Colour const& );
  3700. } // end namespace Catch
  3701. // end catch_console_colour.h
  3702. // start catch_reporter_registrars.hpp
  3703. namespace Catch {
  3704. template<typename T>
  3705. class ReporterRegistrar {
  3706. class ReporterFactory : public IReporterFactory {
  3707. virtual IStreamingReporterPtr create( ReporterConfig const& config ) const override {
  3708. return std::unique_ptr<T>( new T( config ) );
  3709. }
  3710. virtual std::string getDescription() const override {
  3711. return T::getDescription();
  3712. }
  3713. };
  3714. public:
  3715. explicit ReporterRegistrar( std::string const& name ) {
  3716. getMutableRegistryHub().registerReporter( name, std::make_shared<ReporterFactory>() );
  3717. }
  3718. };
  3719. template<typename T>
  3720. class ListenerRegistrar {
  3721. class ListenerFactory : public IReporterFactory {
  3722. virtual IStreamingReporterPtr create( ReporterConfig const& config ) const override {
  3723. return std::unique_ptr<T>( new T( config ) );
  3724. }
  3725. virtual std::string getDescription() const override {
  3726. return std::string();
  3727. }
  3728. };
  3729. public:
  3730. ListenerRegistrar() {
  3731. getMutableRegistryHub().registerListener( std::make_shared<ListenerFactory>() );
  3732. }
  3733. };
  3734. }
  3735. #if !defined(CATCH_CONFIG_DISABLE)
  3736. #define CATCH_REGISTER_REPORTER( name, reporterType ) \
  3737. CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
  3738. namespace{ Catch::ReporterRegistrar<reporterType> catch_internal_RegistrarFor##reporterType( name ); } \
  3739. CATCH_INTERNAL_UNSUPPRESS_GLOBALS_WARNINGS
  3740. #define CATCH_REGISTER_LISTENER( listenerType ) \
  3741. CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
  3742. namespace{ Catch::ListenerRegistrar<listenerType> catch_internal_RegistrarFor##listenerType; } \
  3743. CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS
  3744. #else // CATCH_CONFIG_DISABLE
  3745. #define CATCH_REGISTER_REPORTER(name, reporterType)
  3746. #define CATCH_REGISTER_LISTENER(listenerType)
  3747. #endif // CATCH_CONFIG_DISABLE
  3748. // end catch_reporter_registrars.hpp
  3749. // Allow users to base their work off existing reporters
  3750. // start catch_reporter_compact.h
  3751. namespace Catch {
  3752. struct CompactReporter : StreamingReporterBase<CompactReporter> {
  3753. using StreamingReporterBase::StreamingReporterBase;
  3754. ~CompactReporter() override;
  3755. static std::string getDescription();
  3756. ReporterPreferences getPreferences() const override;
  3757. void noMatchingTestCases(std::string const& spec) override;
  3758. void assertionStarting(AssertionInfo const&) override;
  3759. bool assertionEnded(AssertionStats const& _assertionStats) override;
  3760. void sectionEnded(SectionStats const& _sectionStats) override;
  3761. void testRunEnded(TestRunStats const& _testRunStats) override;
  3762. };
  3763. } // end namespace Catch
  3764. // end catch_reporter_compact.h
  3765. // start catch_reporter_console.h
  3766. #if defined(_MSC_VER)
  3767. #pragma warning(push)
  3768. #pragma warning(disable:4061) // Not all labels are EXPLICITLY handled in switch
  3769. // Note that 4062 (not all labels are handled
  3770. // and default is missing) is enabled
  3771. #endif
  3772. namespace Catch {
  3773. // Fwd decls
  3774. struct SummaryColumn;
  3775. class TablePrinter;
  3776. struct ConsoleReporter : StreamingReporterBase<ConsoleReporter> {
  3777. std::unique_ptr<TablePrinter> m_tablePrinter;
  3778. ConsoleReporter(ReporterConfig const& config);
  3779. ~ConsoleReporter() override;
  3780. static std::string getDescription();
  3781. void noMatchingTestCases(std::string const& spec) override;
  3782. void assertionStarting(AssertionInfo const&) override;
  3783. bool assertionEnded(AssertionStats const& _assertionStats) override;
  3784. void sectionStarting(SectionInfo const& _sectionInfo) override;
  3785. void sectionEnded(SectionStats const& _sectionStats) override;
  3786. void benchmarkStarting(BenchmarkInfo const& info) override;
  3787. void benchmarkEnded(BenchmarkStats const& stats) override;
  3788. void testCaseEnded(TestCaseStats const& _testCaseStats) override;
  3789. void testGroupEnded(TestGroupStats const& _testGroupStats) override;
  3790. void testRunEnded(TestRunStats const& _testRunStats) override;
  3791. private:
  3792. void lazyPrint();
  3793. void lazyPrintWithoutClosingBenchmarkTable();
  3794. void lazyPrintRunInfo();
  3795. void lazyPrintGroupInfo();
  3796. void printTestCaseAndSectionHeader();
  3797. void printClosedHeader(std::string const& _name);
  3798. void printOpenHeader(std::string const& _name);
  3799. // if string has a : in first line will set indent to follow it on
  3800. // subsequent lines
  3801. void printHeaderString(std::string const& _string, std::size_t indent = 0);
  3802. void printTotals(Totals const& totals);
  3803. void printSummaryRow(std::string const& label, std::vector<SummaryColumn> const& cols, std::size_t row);
  3804. void printTotalsDivider(Totals const& totals);
  3805. void printSummaryDivider();
  3806. private:
  3807. bool m_headerPrinted = false;
  3808. };
  3809. } // end namespace Catch
  3810. #if defined(_MSC_VER)
  3811. #pragma warning(pop)
  3812. #endif
  3813. // end catch_reporter_console.h
  3814. // start catch_reporter_junit.h
  3815. // start catch_xmlwriter.h
  3816. #include <vector>
  3817. namespace Catch {
  3818. class XmlEncode {
  3819. public:
  3820. enum ForWhat { ForTextNodes, ForAttributes };
  3821. XmlEncode( std::string const& str, ForWhat forWhat = ForTextNodes );
  3822. void encodeTo( std::ostream& os ) const;
  3823. friend std::ostream& operator << ( std::ostream& os, XmlEncode const& xmlEncode );
  3824. private:
  3825. std::string m_str;
  3826. ForWhat m_forWhat;
  3827. };
  3828. class XmlWriter {
  3829. public:
  3830. class ScopedElement {
  3831. public:
  3832. ScopedElement( XmlWriter* writer );
  3833. ScopedElement( ScopedElement&& other ) noexcept;
  3834. ScopedElement& operator=( ScopedElement&& other ) noexcept;
  3835. ~ScopedElement();
  3836. ScopedElement& writeText( std::string const& text, bool indent = true );
  3837. template<typename T>
  3838. ScopedElement& writeAttribute( std::string const& name, T const& attribute ) {
  3839. m_writer->writeAttribute( name, attribute );
  3840. return *this;
  3841. }
  3842. private:
  3843. mutable XmlWriter* m_writer = nullptr;
  3844. };
  3845. XmlWriter( std::ostream& os = Catch::cout() );
  3846. ~XmlWriter();
  3847. XmlWriter( XmlWriter const& ) = delete;
  3848. XmlWriter& operator=( XmlWriter const& ) = delete;
  3849. XmlWriter& startElement( std::string const& name );
  3850. ScopedElement scopedElement( std::string const& name );
  3851. XmlWriter& endElement();
  3852. XmlWriter& writeAttribute( std::string const& name, std::string const& attribute );
  3853. XmlWriter& writeAttribute( std::string const& name, bool attribute );
  3854. template<typename T>
  3855. XmlWriter& writeAttribute( std::string const& name, T const& attribute ) {
  3856. ReusableStringStream rss;
  3857. rss << attribute;
  3858. return writeAttribute( name, rss.str() );
  3859. }
  3860. XmlWriter& writeText( std::string const& text, bool indent = true );
  3861. XmlWriter& writeComment( std::string const& text );
  3862. void writeStylesheetRef( std::string const& url );
  3863. XmlWriter& writeBlankLine();
  3864. void ensureTagClosed();
  3865. private:
  3866. void writeDeclaration();
  3867. void newlineIfNecessary();
  3868. bool m_tagIsOpen = false;
  3869. bool m_needsNewline = false;
  3870. std::vector<std::string> m_tags;
  3871. std::string m_indent;
  3872. std::ostream& m_os;
  3873. };
  3874. }
  3875. // end catch_xmlwriter.h
  3876. namespace Catch {
  3877. class JunitReporter : public CumulativeReporterBase<JunitReporter> {
  3878. public:
  3879. JunitReporter(ReporterConfig const& _config);
  3880. ~JunitReporter() override;
  3881. static std::string getDescription();
  3882. void noMatchingTestCases(std::string const& /*spec*/) override;
  3883. void testRunStarting(TestRunInfo const& runInfo) override;
  3884. void testGroupStarting(GroupInfo const& groupInfo) override;
  3885. void testCaseStarting(TestCaseInfo const& testCaseInfo) override;
  3886. bool assertionEnded(AssertionStats const& assertionStats) override;
  3887. void testCaseEnded(TestCaseStats const& testCaseStats) override;
  3888. void testGroupEnded(TestGroupStats const& testGroupStats) override;
  3889. void testRunEndedCumulative() override;
  3890. void writeGroup(TestGroupNode const& groupNode, double suiteTime);
  3891. void writeTestCase(TestCaseNode const& testCaseNode);
  3892. void writeSection(std::string const& className,
  3893. std::string const& rootName,
  3894. SectionNode const& sectionNode);
  3895. void writeAssertions(SectionNode const& sectionNode);
  3896. void writeAssertion(AssertionStats const& stats);
  3897. XmlWriter xml;
  3898. Timer suiteTimer;
  3899. std::string stdOutForSuite;
  3900. std::string stdErrForSuite;
  3901. unsigned int unexpectedExceptions = 0;
  3902. bool m_okToFail = false;
  3903. };
  3904. } // end namespace Catch
  3905. // end catch_reporter_junit.h
  3906. // start catch_reporter_xml.h
  3907. namespace Catch {
  3908. class XmlReporter : public StreamingReporterBase<XmlReporter> {
  3909. public:
  3910. XmlReporter(ReporterConfig const& _config);
  3911. ~XmlReporter() override;
  3912. static std::string getDescription();
  3913. virtual std::string getStylesheetRef() const;
  3914. void writeSourceInfo(SourceLineInfo const& sourceInfo);
  3915. public: // StreamingReporterBase
  3916. void noMatchingTestCases(std::string const& s) override;
  3917. void testRunStarting(TestRunInfo const& testInfo) override;
  3918. void testGroupStarting(GroupInfo const& groupInfo) override;
  3919. void testCaseStarting(TestCaseInfo const& testInfo) override;
  3920. void sectionStarting(SectionInfo const& sectionInfo) override;
  3921. void assertionStarting(AssertionInfo const&) override;
  3922. bool assertionEnded(AssertionStats const& assertionStats) override;
  3923. void sectionEnded(SectionStats const& sectionStats) override;
  3924. void testCaseEnded(TestCaseStats const& testCaseStats) override;
  3925. void testGroupEnded(TestGroupStats const& testGroupStats) override;
  3926. void testRunEnded(TestRunStats const& testRunStats) override;
  3927. private:
  3928. Timer m_testCaseTimer;
  3929. XmlWriter m_xml;
  3930. int m_sectionDepth = 0;
  3931. };
  3932. } // end namespace Catch
  3933. // end catch_reporter_xml.h
  3934. // end catch_external_interfaces.h
  3935. #endif
  3936. #endif // ! CATCH_CONFIG_IMPL_ONLY
  3937. #ifdef CATCH_IMPL
  3938. // start catch_impl.hpp
  3939. #ifdef __clang__
  3940. #pragma clang diagnostic push
  3941. #pragma clang diagnostic ignored "-Wweak-vtables"
  3942. #endif
  3943. // Keep these here for external reporters
  3944. // start catch_test_case_tracker.h
  3945. #include <string>
  3946. #include <vector>
  3947. #include <memory>
  3948. namespace Catch {
  3949. namespace TestCaseTracking {
  3950. struct NameAndLocation {
  3951. std::string name;
  3952. SourceLineInfo location;
  3953. NameAndLocation( std::string const& _name, SourceLineInfo const& _location );
  3954. };
  3955. struct ITracker;
  3956. using ITrackerPtr = std::shared_ptr<ITracker>;
  3957. struct ITracker {
  3958. virtual ~ITracker();
  3959. // static queries
  3960. virtual NameAndLocation const& nameAndLocation() const = 0;
  3961. // dynamic queries
  3962. virtual bool isComplete() const = 0; // Successfully completed or failed
  3963. virtual bool isSuccessfullyCompleted() const = 0;
  3964. virtual bool isOpen() const = 0; // Started but not complete
  3965. virtual bool hasChildren() const = 0;
  3966. virtual ITracker& parent() = 0;
  3967. // actions
  3968. virtual void close() = 0; // Successfully complete
  3969. virtual void fail() = 0;
  3970. virtual void markAsNeedingAnotherRun() = 0;
  3971. virtual void addChild( ITrackerPtr const& child ) = 0;
  3972. virtual ITrackerPtr findChild( NameAndLocation const& nameAndLocation ) = 0;
  3973. virtual void openChild() = 0;
  3974. // Debug/ checking
  3975. virtual bool isSectionTracker() const = 0;
  3976. virtual bool isIndexTracker() const = 0;
  3977. };
  3978. class TrackerContext {
  3979. enum RunState {
  3980. NotStarted,
  3981. Executing,
  3982. CompletedCycle
  3983. };
  3984. ITrackerPtr m_rootTracker;
  3985. ITracker* m_currentTracker = nullptr;
  3986. RunState m_runState = NotStarted;
  3987. public:
  3988. static TrackerContext& instance();
  3989. ITracker& startRun();
  3990. void endRun();
  3991. void startCycle();
  3992. void completeCycle();
  3993. bool completedCycle() const;
  3994. ITracker& currentTracker();
  3995. void setCurrentTracker( ITracker* tracker );
  3996. };
  3997. class TrackerBase : public ITracker {
  3998. protected:
  3999. enum CycleState {
  4000. NotStarted,
  4001. Executing,
  4002. ExecutingChildren,
  4003. NeedsAnotherRun,
  4004. CompletedSuccessfully,
  4005. Failed
  4006. };
  4007. using Children = std::vector<ITrackerPtr>;
  4008. NameAndLocation m_nameAndLocation;
  4009. TrackerContext& m_ctx;
  4010. ITracker* m_parent;
  4011. Children m_children;
  4012. CycleState m_runState = NotStarted;
  4013. public:
  4014. TrackerBase( NameAndLocation const& nameAndLocation, TrackerContext& ctx, ITracker* parent );
  4015. NameAndLocation const& nameAndLocation() const override;
  4016. bool isComplete() const override;
  4017. bool isSuccessfullyCompleted() const override;
  4018. bool isOpen() const override;
  4019. bool hasChildren() const override;
  4020. void addChild( ITrackerPtr const& child ) override;
  4021. ITrackerPtr findChild( NameAndLocation const& nameAndLocation ) override;
  4022. ITracker& parent() override;
  4023. void openChild() override;
  4024. bool isSectionTracker() const override;
  4025. bool isIndexTracker() const override;
  4026. void open();
  4027. void close() override;
  4028. void fail() override;
  4029. void markAsNeedingAnotherRun() override;
  4030. private:
  4031. void moveToParent();
  4032. void moveToThis();
  4033. };
  4034. class SectionTracker : public TrackerBase {
  4035. std::vector<std::string> m_filters;
  4036. public:
  4037. SectionTracker( NameAndLocation const& nameAndLocation, TrackerContext& ctx, ITracker* parent );
  4038. bool isSectionTracker() const override;
  4039. static SectionTracker& acquire( TrackerContext& ctx, NameAndLocation const& nameAndLocation );
  4040. void tryOpen();
  4041. void addInitialFilters( std::vector<std::string> const& filters );
  4042. void addNextFilters( std::vector<std::string> const& filters );
  4043. };
  4044. class IndexTracker : public TrackerBase {
  4045. int m_size;
  4046. int m_index = -1;
  4047. public:
  4048. IndexTracker( NameAndLocation const& nameAndLocation, TrackerContext& ctx, ITracker* parent, int size );
  4049. bool isIndexTracker() const override;
  4050. void close() override;
  4051. static IndexTracker& acquire( TrackerContext& ctx, NameAndLocation const& nameAndLocation, int size );
  4052. int index() const;
  4053. void moveNext();
  4054. };
  4055. } // namespace TestCaseTracking
  4056. using TestCaseTracking::ITracker;
  4057. using TestCaseTracking::TrackerContext;
  4058. using TestCaseTracking::SectionTracker;
  4059. using TestCaseTracking::IndexTracker;
  4060. } // namespace Catch
  4061. // end catch_test_case_tracker.h
  4062. // start catch_leak_detector.h
  4063. namespace Catch {
  4064. struct LeakDetector {
  4065. LeakDetector();
  4066. };
  4067. }
  4068. // end catch_leak_detector.h
  4069. // Cpp files will be included in the single-header file here
  4070. // start catch_approx.cpp
  4071. #include <cmath>
  4072. #include <limits>
  4073. namespace {
  4074. // Performs equivalent check of std::fabs(lhs - rhs) <= margin
  4075. // But without the subtraction to allow for INFINITY in comparison
  4076. bool marginComparison(double lhs, double rhs, double margin) {
  4077. return (lhs + margin >= rhs) && (rhs + margin >= lhs);
  4078. }
  4079. }
  4080. namespace Catch {
  4081. namespace Detail {
  4082. Approx::Approx ( double value )
  4083. : m_epsilon( std::numeric_limits<float>::epsilon()*100 ),
  4084. m_margin( 0.0 ),
  4085. m_scale( 0.0 ),
  4086. m_value( value )
  4087. {}
  4088. Approx Approx::custom() {
  4089. return Approx( 0 );
  4090. }
  4091. Approx Approx::operator-() const {
  4092. auto temp(*this);
  4093. temp.m_value = -temp.m_value;
  4094. return temp;
  4095. }
  4096. std::string Approx::toString() const {
  4097. ReusableStringStream rss;
  4098. rss << "Approx( " << ::Catch::Detail::stringify( m_value ) << " )";
  4099. return rss.str();
  4100. }
  4101. bool Approx::equalityComparisonImpl(const double other) const {
  4102. // First try with fixed margin, then compute margin based on epsilon, scale and Approx's value
  4103. // Thanks to Richard Harris for his help refining the scaled margin value
  4104. return marginComparison(m_value, other, m_margin) || marginComparison(m_value, other, m_epsilon * (m_scale + std::fabs(m_value)));
  4105. }
  4106. void Approx::setMargin(double margin) {
  4107. CATCH_ENFORCE(margin >= 0,
  4108. "Invalid Approx::margin: " << margin << '.'
  4109. << " Approx::Margin has to be non-negative.");
  4110. m_margin = margin;
  4111. }
  4112. void Approx::setEpsilon(double epsilon) {
  4113. CATCH_ENFORCE(epsilon >= 0 && epsilon <= 1.0,
  4114. "Invalid Approx::epsilon: " << epsilon << '.'
  4115. << " Approx::epsilon has to be in [0, 1]");
  4116. m_epsilon = epsilon;
  4117. }
  4118. } // end namespace Detail
  4119. namespace literals {
  4120. Detail::Approx operator "" _a(long double val) {
  4121. return Detail::Approx(val);
  4122. }
  4123. Detail::Approx operator "" _a(unsigned long long val) {
  4124. return Detail::Approx(val);
  4125. }
  4126. } // end namespace literals
  4127. std::string StringMaker<Catch::Detail::Approx>::convert(Catch::Detail::Approx const& value) {
  4128. return value.toString();
  4129. }
  4130. } // end namespace Catch
  4131. // end catch_approx.cpp
  4132. // start catch_assertionhandler.cpp
  4133. // start catch_context.h
  4134. #include <memory>
  4135. namespace Catch {
  4136. struct IResultCapture;
  4137. struct IRunner;
  4138. struct IConfig;
  4139. struct IMutableContext;
  4140. using IConfigPtr = std::shared_ptr<IConfig const>;
  4141. struct IContext
  4142. {
  4143. virtual ~IContext();
  4144. virtual IResultCapture* getResultCapture() = 0;
  4145. virtual IRunner* getRunner() = 0;
  4146. virtual IConfigPtr const& getConfig() const = 0;
  4147. };
  4148. struct IMutableContext : IContext
  4149. {
  4150. virtual ~IMutableContext();
  4151. virtual void setResultCapture( IResultCapture* resultCapture ) = 0;
  4152. virtual void setRunner( IRunner* runner ) = 0;
  4153. virtual void setConfig( IConfigPtr const& config ) = 0;
  4154. private:
  4155. static IMutableContext *currentContext;
  4156. friend IMutableContext& getCurrentMutableContext();
  4157. friend void cleanUpContext();
  4158. static void createContext();
  4159. };
  4160. inline IMutableContext& getCurrentMutableContext()
  4161. {
  4162. if( !IMutableContext::currentContext )
  4163. IMutableContext::createContext();
  4164. return *IMutableContext::currentContext;
  4165. }
  4166. inline IContext& getCurrentContext()
  4167. {
  4168. return getCurrentMutableContext();
  4169. }
  4170. void cleanUpContext();
  4171. }
  4172. // end catch_context.h
  4173. // start catch_debugger.h
  4174. namespace Catch {
  4175. bool isDebuggerActive();
  4176. }
  4177. #ifdef CATCH_PLATFORM_MAC
  4178. #define CATCH_TRAP() __asm__("int $3\n" : : ) /* NOLINT */
  4179. #elif defined(CATCH_PLATFORM_LINUX)
  4180. // If we can use inline assembler, do it because this allows us to break
  4181. // directly at the location of the failing check instead of breaking inside
  4182. // raise() called from it, i.e. one stack frame below.
  4183. #if defined(__GNUC__) && (defined(__i386) || defined(__x86_64))
  4184. #define CATCH_TRAP() asm volatile ("int $3") /* NOLINT */
  4185. #else // Fall back to the generic way.
  4186. #include <signal.h>
  4187. #define CATCH_TRAP() raise(SIGTRAP)
  4188. #endif
  4189. #elif defined(_MSC_VER)
  4190. #define CATCH_TRAP() __debugbreak()
  4191. #elif defined(__MINGW32__)
  4192. extern "C" __declspec(dllimport) void __stdcall DebugBreak();
  4193. #define CATCH_TRAP() DebugBreak()
  4194. #endif
  4195. #ifdef CATCH_TRAP
  4196. #define CATCH_BREAK_INTO_DEBUGGER() if( Catch::isDebuggerActive() ) { CATCH_TRAP(); }
  4197. #else
  4198. namespace Catch {
  4199. inline void doNothing() {}
  4200. }
  4201. #define CATCH_BREAK_INTO_DEBUGGER() Catch::doNothing()
  4202. #endif
  4203. // end catch_debugger.h
  4204. // start catch_run_context.h
  4205. // start catch_fatal_condition.h
  4206. // start catch_windows_h_proxy.h
  4207. #if defined(CATCH_PLATFORM_WINDOWS)
  4208. #if !defined(NOMINMAX) && !defined(CATCH_CONFIG_NO_NOMINMAX)
  4209. # define CATCH_DEFINED_NOMINMAX
  4210. # define NOMINMAX
  4211. #endif
  4212. #if !defined(WIN32_LEAN_AND_MEAN) && !defined(CATCH_CONFIG_NO_WIN32_LEAN_AND_MEAN)
  4213. # define CATCH_DEFINED_WIN32_LEAN_AND_MEAN
  4214. # define WIN32_LEAN_AND_MEAN
  4215. #endif
  4216. #ifdef __AFXDLL
  4217. #include <AfxWin.h>
  4218. #else
  4219. #include <windows.h>
  4220. #endif
  4221. #ifdef CATCH_DEFINED_NOMINMAX
  4222. # undef NOMINMAX
  4223. #endif
  4224. #ifdef CATCH_DEFINED_WIN32_LEAN_AND_MEAN
  4225. # undef WIN32_LEAN_AND_MEAN
  4226. #endif
  4227. #endif // defined(CATCH_PLATFORM_WINDOWS)
  4228. // end catch_windows_h_proxy.h
  4229. #if defined( CATCH_CONFIG_WINDOWS_SEH )
  4230. namespace Catch {
  4231. struct FatalConditionHandler {
  4232. static LONG CALLBACK handleVectoredException(PEXCEPTION_POINTERS ExceptionInfo);
  4233. FatalConditionHandler();
  4234. static void reset();
  4235. ~FatalConditionHandler();
  4236. private:
  4237. static bool isSet;
  4238. static ULONG guaranteeSize;
  4239. static PVOID exceptionHandlerHandle;
  4240. };
  4241. } // namespace Catch
  4242. #elif defined ( CATCH_CONFIG_POSIX_SIGNALS )
  4243. #include <signal.h>
  4244. namespace Catch {
  4245. struct FatalConditionHandler {
  4246. static bool isSet;
  4247. static struct sigaction oldSigActions[];
  4248. static stack_t oldSigStack;
  4249. static char altStackMem[];
  4250. static void handleSignal( int sig );
  4251. FatalConditionHandler();
  4252. ~FatalConditionHandler();
  4253. static void reset();
  4254. };
  4255. } // namespace Catch
  4256. #else
  4257. namespace Catch {
  4258. struct FatalConditionHandler {
  4259. void reset();
  4260. };
  4261. }
  4262. #endif
  4263. // end catch_fatal_condition.h
  4264. #include <string>
  4265. namespace Catch {
  4266. struct IMutableContext;
  4267. ///////////////////////////////////////////////////////////////////////////
  4268. class RunContext : public IResultCapture, public IRunner {
  4269. public:
  4270. RunContext( RunContext const& ) = delete;
  4271. RunContext& operator =( RunContext const& ) = delete;
  4272. explicit RunContext( IConfigPtr const& _config, IStreamingReporterPtr&& reporter );
  4273. ~RunContext() override;
  4274. void testGroupStarting( std::string const& testSpec, std::size_t groupIndex, std::size_t groupsCount );
  4275. void testGroupEnded( std::string const& testSpec, Totals const& totals, std::size_t groupIndex, std::size_t groupsCount );
  4276. Totals runTest(TestCase const& testCase);
  4277. IConfigPtr config() const;
  4278. IStreamingReporter& reporter() const;
  4279. public: // IResultCapture
  4280. // Assertion handlers
  4281. void handleExpr
  4282. ( AssertionInfo const& info,
  4283. ITransientExpression const& expr,
  4284. AssertionReaction& reaction ) override;
  4285. void handleMessage
  4286. ( AssertionInfo const& info,
  4287. ResultWas::OfType resultType,
  4288. StringRef const& message,
  4289. AssertionReaction& reaction ) override;
  4290. void handleUnexpectedExceptionNotThrown
  4291. ( AssertionInfo const& info,
  4292. AssertionReaction& reaction ) override;
  4293. void handleUnexpectedInflightException
  4294. ( AssertionInfo const& info,
  4295. std::string const& message,
  4296. AssertionReaction& reaction ) override;
  4297. void handleIncomplete
  4298. ( AssertionInfo const& info ) override;
  4299. void handleNonExpr
  4300. ( AssertionInfo const &info,
  4301. ResultWas::OfType resultType,
  4302. AssertionReaction &reaction ) override;
  4303. bool sectionStarted( SectionInfo const& sectionInfo, Counts& assertions ) override;
  4304. void sectionEnded( SectionEndInfo const& endInfo ) override;
  4305. void sectionEndedEarly( SectionEndInfo const& endInfo ) override;
  4306. auto acquireGeneratorTracker( SourceLineInfo const& lineInfo ) -> IGeneratorTracker& override;
  4307. void benchmarkStarting( BenchmarkInfo const& info ) override;
  4308. void benchmarkEnded( BenchmarkStats const& stats ) override;
  4309. void pushScopedMessage( MessageInfo const& message ) override;
  4310. void popScopedMessage( MessageInfo const& message ) override;
  4311. std::string getCurrentTestName() const override;
  4312. const AssertionResult* getLastResult() const override;
  4313. void exceptionEarlyReported() override;
  4314. void handleFatalErrorCondition( StringRef message ) override;
  4315. bool lastAssertionPassed() override;
  4316. void assertionPassed() override;
  4317. public:
  4318. // !TBD We need to do this another way!
  4319. bool aborting() const final;
  4320. private:
  4321. void runCurrentTest( std::string& redirectedCout, std::string& redirectedCerr );
  4322. void invokeActiveTestCase();
  4323. void resetAssertionInfo();
  4324. bool testForMissingAssertions( Counts& assertions );
  4325. void assertionEnded( AssertionResult const& result );
  4326. void reportExpr
  4327. ( AssertionInfo const &info,
  4328. ResultWas::OfType resultType,
  4329. ITransientExpression const *expr,
  4330. bool negated );
  4331. void populateReaction( AssertionReaction& reaction );
  4332. private:
  4333. void handleUnfinishedSections();
  4334. TestRunInfo m_runInfo;
  4335. IMutableContext& m_context;
  4336. TestCase const* m_activeTestCase = nullptr;
  4337. ITracker* m_testCaseTracker;
  4338. Option<AssertionResult> m_lastResult;
  4339. IConfigPtr m_config;
  4340. Totals m_totals;
  4341. IStreamingReporterPtr m_reporter;
  4342. std::vector<MessageInfo> m_messages;
  4343. AssertionInfo m_lastAssertionInfo;
  4344. std::vector<SectionEndInfo> m_unfinishedSections;
  4345. std::vector<ITracker*> m_activeSections;
  4346. TrackerContext m_trackerContext;
  4347. bool m_lastAssertionPassed = false;
  4348. bool m_shouldReportUnexpected = true;
  4349. bool m_includeSuccessfulResults;
  4350. };
  4351. } // end namespace Catch
  4352. // end catch_run_context.h
  4353. namespace Catch {
  4354. namespace {
  4355. auto operator <<( std::ostream& os, ITransientExpression const& expr ) -> std::ostream& {
  4356. expr.streamReconstructedExpression( os );
  4357. return os;
  4358. }
  4359. }
  4360. LazyExpression::LazyExpression( bool isNegated )
  4361. : m_isNegated( isNegated )
  4362. {}
  4363. LazyExpression::LazyExpression( LazyExpression const& other ) : m_isNegated( other.m_isNegated ) {}
  4364. LazyExpression::operator bool() const {
  4365. return m_transientExpression != nullptr;
  4366. }
  4367. auto operator << ( std::ostream& os, LazyExpression const& lazyExpr ) -> std::ostream& {
  4368. if( lazyExpr.m_isNegated )
  4369. os << "!";
  4370. if( lazyExpr ) {
  4371. if( lazyExpr.m_isNegated && lazyExpr.m_transientExpression->isBinaryExpression() )
  4372. os << "(" << *lazyExpr.m_transientExpression << ")";
  4373. else
  4374. os << *lazyExpr.m_transientExpression;
  4375. }
  4376. else {
  4377. os << "{** error - unchecked empty expression requested **}";
  4378. }
  4379. return os;
  4380. }
  4381. AssertionHandler::AssertionHandler
  4382. ( StringRef const& macroName,
  4383. SourceLineInfo const& lineInfo,
  4384. StringRef capturedExpression,
  4385. ResultDisposition::Flags resultDisposition )
  4386. : m_assertionInfo{ macroName, lineInfo, capturedExpression, resultDisposition },
  4387. m_resultCapture( getResultCapture() )
  4388. {}
  4389. void AssertionHandler::handleExpr( ITransientExpression const& expr ) {
  4390. m_resultCapture.handleExpr( m_assertionInfo, expr, m_reaction );
  4391. }
  4392. void AssertionHandler::handleMessage(ResultWas::OfType resultType, StringRef const& message) {
  4393. m_resultCapture.handleMessage( m_assertionInfo, resultType, message, m_reaction );
  4394. }
  4395. auto AssertionHandler::allowThrows() const -> bool {
  4396. return getCurrentContext().getConfig()->allowThrows();
  4397. }
  4398. void AssertionHandler::complete() {
  4399. setCompleted();
  4400. if( m_reaction.shouldDebugBreak ) {
  4401. // If you find your debugger stopping you here then go one level up on the
  4402. // call-stack for the code that caused it (typically a failed assertion)
  4403. // (To go back to the test and change execution, jump over the throw, next)
  4404. CATCH_BREAK_INTO_DEBUGGER();
  4405. }
  4406. if (m_reaction.shouldThrow) {
  4407. #if !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
  4408. throw Catch::TestFailureException();
  4409. #else
  4410. CATCH_ERROR( "Test failure requires aborting test!" );
  4411. #endif
  4412. }
  4413. }
  4414. void AssertionHandler::setCompleted() {
  4415. m_completed = true;
  4416. }
  4417. void AssertionHandler::handleUnexpectedInflightException() {
  4418. m_resultCapture.handleUnexpectedInflightException( m_assertionInfo, Catch::translateActiveException(), m_reaction );
  4419. }
  4420. void AssertionHandler::handleExceptionThrownAsExpected() {
  4421. m_resultCapture.handleNonExpr(m_assertionInfo, ResultWas::Ok, m_reaction);
  4422. }
  4423. void AssertionHandler::handleExceptionNotThrownAsExpected() {
  4424. m_resultCapture.handleNonExpr(m_assertionInfo, ResultWas::Ok, m_reaction);
  4425. }
  4426. void AssertionHandler::handleUnexpectedExceptionNotThrown() {
  4427. m_resultCapture.handleUnexpectedExceptionNotThrown( m_assertionInfo, m_reaction );
  4428. }
  4429. void AssertionHandler::handleThrowingCallSkipped() {
  4430. m_resultCapture.handleNonExpr(m_assertionInfo, ResultWas::Ok, m_reaction);
  4431. }
  4432. // This is the overload that takes a string and infers the Equals matcher from it
  4433. // The more general overload, that takes any string matcher, is in catch_capture_matchers.cpp
  4434. void handleExceptionMatchExpr( AssertionHandler& handler, std::string const& str, StringRef const& matcherString ) {
  4435. handleExceptionMatchExpr( handler, Matchers::Equals( str ), matcherString );
  4436. }
  4437. } // namespace Catch
  4438. // end catch_assertionhandler.cpp
  4439. // start catch_assertionresult.cpp
  4440. namespace Catch {
  4441. AssertionResultData::AssertionResultData(ResultWas::OfType _resultType, LazyExpression const & _lazyExpression):
  4442. lazyExpression(_lazyExpression),
  4443. resultType(_resultType) {}
  4444. std::string AssertionResultData::reconstructExpression() const {
  4445. if( reconstructedExpression.empty() ) {
  4446. if( lazyExpression ) {
  4447. ReusableStringStream rss;
  4448. rss << lazyExpression;
  4449. reconstructedExpression = rss.str();
  4450. }
  4451. }
  4452. return reconstructedExpression;
  4453. }
  4454. AssertionResult::AssertionResult( AssertionInfo const& info, AssertionResultData const& data )
  4455. : m_info( info ),
  4456. m_resultData( data )
  4457. {}
  4458. // Result was a success
  4459. bool AssertionResult::succeeded() const {
  4460. return Catch::isOk( m_resultData.resultType );
  4461. }
  4462. // Result was a success, or failure is suppressed
  4463. bool AssertionResult::isOk() const {
  4464. return Catch::isOk( m_resultData.resultType ) || shouldSuppressFailure( m_info.resultDisposition );
  4465. }
  4466. ResultWas::OfType AssertionResult::getResultType() const {
  4467. return m_resultData.resultType;
  4468. }
  4469. bool AssertionResult::hasExpression() const {
  4470. return m_info.capturedExpression[0] != 0;
  4471. }
  4472. bool AssertionResult::hasMessage() const {
  4473. return !m_resultData.message.empty();
  4474. }
  4475. std::string AssertionResult::getExpression() const {
  4476. if( isFalseTest( m_info.resultDisposition ) )
  4477. return "!(" + m_info.capturedExpression + ")";
  4478. else
  4479. return m_info.capturedExpression;
  4480. }
  4481. std::string AssertionResult::getExpressionInMacro() const {
  4482. std::string expr;
  4483. if( m_info.macroName[0] == 0 )
  4484. expr = m_info.capturedExpression;
  4485. else {
  4486. expr.reserve( m_info.macroName.size() + m_info.capturedExpression.size() + 4 );
  4487. expr += m_info.macroName;
  4488. expr += "( ";
  4489. expr += m_info.capturedExpression;
  4490. expr += " )";
  4491. }
  4492. return expr;
  4493. }
  4494. bool AssertionResult::hasExpandedExpression() const {
  4495. return hasExpression() && getExpandedExpression() != getExpression();
  4496. }
  4497. std::string AssertionResult::getExpandedExpression() const {
  4498. std::string expr = m_resultData.reconstructExpression();
  4499. return expr.empty()
  4500. ? getExpression()
  4501. : expr;
  4502. }
  4503. std::string AssertionResult::getMessage() const {
  4504. return m_resultData.message;
  4505. }
  4506. SourceLineInfo AssertionResult::getSourceInfo() const {
  4507. return m_info.lineInfo;
  4508. }
  4509. StringRef AssertionResult::getTestMacroName() const {
  4510. return m_info.macroName;
  4511. }
  4512. } // end namespace Catch
  4513. // end catch_assertionresult.cpp
  4514. // start catch_benchmark.cpp
  4515. namespace Catch {
  4516. auto BenchmarkLooper::getResolution() -> uint64_t {
  4517. return getEstimatedClockResolution() * getCurrentContext().getConfig()->benchmarkResolutionMultiple();
  4518. }
  4519. void BenchmarkLooper::reportStart() {
  4520. getResultCapture().benchmarkStarting( { m_name } );
  4521. }
  4522. auto BenchmarkLooper::needsMoreIterations() -> bool {
  4523. auto elapsed = m_timer.getElapsedNanoseconds();
  4524. // Exponentially increasing iterations until we're confident in our timer resolution
  4525. if( elapsed < m_resolution ) {
  4526. m_iterationsToRun *= 10;
  4527. return true;
  4528. }
  4529. getResultCapture().benchmarkEnded( { { m_name }, m_count, elapsed } );
  4530. return false;
  4531. }
  4532. } // end namespace Catch
  4533. // end catch_benchmark.cpp
  4534. // start catch_capture_matchers.cpp
  4535. namespace Catch {
  4536. using StringMatcher = Matchers::Impl::MatcherBase<std::string>;
  4537. // This is the general overload that takes a any string matcher
  4538. // There is another overload, in catch_assertionhandler.h/.cpp, that only takes a string and infers
  4539. // the Equals matcher (so the header does not mention matchers)
  4540. void handleExceptionMatchExpr( AssertionHandler& handler, StringMatcher const& matcher, StringRef const& matcherString ) {
  4541. std::string exceptionMessage = Catch::translateActiveException();
  4542. MatchExpr<std::string, StringMatcher const&> expr( exceptionMessage, matcher, matcherString );
  4543. handler.handleExpr( expr );
  4544. }
  4545. } // namespace Catch
  4546. // end catch_capture_matchers.cpp
  4547. // start catch_commandline.cpp
  4548. // start catch_commandline.h
  4549. // start catch_clara.h
  4550. // Use Catch's value for console width (store Clara's off to the side, if present)
  4551. #ifdef CLARA_CONFIG_CONSOLE_WIDTH
  4552. #define CATCH_TEMP_CLARA_CONFIG_CONSOLE_WIDTH CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH
  4553. #undef CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH
  4554. #endif
  4555. #define CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH CATCH_CONFIG_CONSOLE_WIDTH-1
  4556. #ifdef __clang__
  4557. #pragma clang diagnostic push
  4558. #pragma clang diagnostic ignored "-Wweak-vtables"
  4559. #pragma clang diagnostic ignored "-Wexit-time-destructors"
  4560. #pragma clang diagnostic ignored "-Wshadow"
  4561. #endif
  4562. // start clara.hpp
  4563. // Copyright 2017 Two Blue Cubes Ltd. All rights reserved.
  4564. //
  4565. // Distributed under the Boost Software License, Version 1.0. (See accompanying
  4566. // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
  4567. //
  4568. // See https://github.com/philsquared/Clara for more details
  4569. // Clara v1.1.4
  4570. #ifndef CATCH_CLARA_CONFIG_CONSOLE_WIDTH
  4571. #define CATCH_CLARA_CONFIG_CONSOLE_WIDTH 80
  4572. #endif
  4573. #ifndef CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH
  4574. #define CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH CATCH_CLARA_CONFIG_CONSOLE_WIDTH
  4575. #endif
  4576. #ifndef CLARA_CONFIG_OPTIONAL_TYPE
  4577. #ifdef __has_include
  4578. #if __has_include(<optional>) && __cplusplus >= 201703L
  4579. #include <optional>
  4580. #define CLARA_CONFIG_OPTIONAL_TYPE std::optional
  4581. #endif
  4582. #endif
  4583. #endif
  4584. // ----------- #included from clara_textflow.hpp -----------
  4585. // TextFlowCpp
  4586. //
  4587. // A single-header library for wrapping and laying out basic text, by Phil Nash
  4588. //
  4589. // This work is licensed under the BSD 2-Clause license.
  4590. // See the accompanying LICENSE file, or the one at https://opensource.org/licenses/BSD-2-Clause
  4591. //
  4592. // This project is hosted at https://github.com/philsquared/textflowcpp
  4593. #include <cassert>
  4594. #include <ostream>
  4595. #include <sstream>
  4596. #include <vector>
  4597. #ifndef CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH
  4598. #define CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH 80
  4599. #endif
  4600. namespace Catch { namespace clara { namespace TextFlow {
  4601. inline auto isWhitespace( char c ) -> bool {
  4602. static std::string chars = " \t\n\r";
  4603. return chars.find( c ) != std::string::npos;
  4604. }
  4605. inline auto isBreakableBefore( char c ) -> bool {
  4606. static std::string chars = "[({<|";
  4607. return chars.find( c ) != std::string::npos;
  4608. }
  4609. inline auto isBreakableAfter( char c ) -> bool {
  4610. static std::string chars = "])}>.,:;*+-=&/\\";
  4611. return chars.find( c ) != std::string::npos;
  4612. }
  4613. class Columns;
  4614. class Column {
  4615. std::vector<std::string> m_strings;
  4616. size_t m_width = CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH;
  4617. size_t m_indent = 0;
  4618. size_t m_initialIndent = std::string::npos;
  4619. public:
  4620. class iterator {
  4621. friend Column;
  4622. Column const& m_column;
  4623. size_t m_stringIndex = 0;
  4624. size_t m_pos = 0;
  4625. size_t m_len = 0;
  4626. size_t m_end = 0;
  4627. bool m_suffix = false;
  4628. iterator( Column const& column, size_t stringIndex )
  4629. : m_column( column ),
  4630. m_stringIndex( stringIndex )
  4631. {}
  4632. auto line() const -> std::string const& { return m_column.m_strings[m_stringIndex]; }
  4633. auto isBoundary( size_t at ) const -> bool {
  4634. assert( at > 0 );
  4635. assert( at <= line().size() );
  4636. return at == line().size() ||
  4637. ( isWhitespace( line()[at] ) && !isWhitespace( line()[at-1] ) ) ||
  4638. isBreakableBefore( line()[at] ) ||
  4639. isBreakableAfter( line()[at-1] );
  4640. }
  4641. void calcLength() {
  4642. assert( m_stringIndex < m_column.m_strings.size() );
  4643. m_suffix = false;
  4644. auto width = m_column.m_width-indent();
  4645. m_end = m_pos;
  4646. while( m_end < line().size() && line()[m_end] != '\n' )
  4647. ++m_end;
  4648. if( m_end < m_pos + width ) {
  4649. m_len = m_end - m_pos;
  4650. }
  4651. else {
  4652. size_t len = width;
  4653. while (len > 0 && !isBoundary(m_pos + len))
  4654. --len;
  4655. while (len > 0 && isWhitespace( line()[m_pos + len - 1] ))
  4656. --len;
  4657. if (len > 0) {
  4658. m_len = len;
  4659. } else {
  4660. m_suffix = true;
  4661. m_len = width - 1;
  4662. }
  4663. }
  4664. }
  4665. auto indent() const -> size_t {
  4666. auto initial = m_pos == 0 && m_stringIndex == 0 ? m_column.m_initialIndent : std::string::npos;
  4667. return initial == std::string::npos ? m_column.m_indent : initial;
  4668. }
  4669. auto addIndentAndSuffix(std::string const &plain) const -> std::string {
  4670. return std::string( indent(), ' ' ) + (m_suffix ? plain + "-" : plain);
  4671. }
  4672. public:
  4673. explicit iterator( Column const& column ) : m_column( column ) {
  4674. assert( m_column.m_width > m_column.m_indent );
  4675. assert( m_column.m_initialIndent == std::string::npos || m_column.m_width > m_column.m_initialIndent );
  4676. calcLength();
  4677. if( m_len == 0 )
  4678. m_stringIndex++; // Empty string
  4679. }
  4680. auto operator *() const -> std::string {
  4681. assert( m_stringIndex < m_column.m_strings.size() );
  4682. assert( m_pos <= m_end );
  4683. if( m_pos + m_column.m_width < m_end )
  4684. return addIndentAndSuffix(line().substr(m_pos, m_len));
  4685. else
  4686. return addIndentAndSuffix(line().substr(m_pos, m_end - m_pos));
  4687. }
  4688. auto operator ++() -> iterator& {
  4689. m_pos += m_len;
  4690. if( m_pos < line().size() && line()[m_pos] == '\n' )
  4691. m_pos += 1;
  4692. else
  4693. while( m_pos < line().size() && isWhitespace( line()[m_pos] ) )
  4694. ++m_pos;
  4695. if( m_pos == line().size() ) {
  4696. m_pos = 0;
  4697. ++m_stringIndex;
  4698. }
  4699. if( m_stringIndex < m_column.m_strings.size() )
  4700. calcLength();
  4701. return *this;
  4702. }
  4703. auto operator ++(int) -> iterator {
  4704. iterator prev( *this );
  4705. operator++();
  4706. return prev;
  4707. }
  4708. auto operator ==( iterator const& other ) const -> bool {
  4709. return
  4710. m_pos == other.m_pos &&
  4711. m_stringIndex == other.m_stringIndex &&
  4712. &m_column == &other.m_column;
  4713. }
  4714. auto operator !=( iterator const& other ) const -> bool {
  4715. return !operator==( other );
  4716. }
  4717. };
  4718. using const_iterator = iterator;
  4719. explicit Column( std::string const& text ) { m_strings.push_back( text ); }
  4720. auto width( size_t newWidth ) -> Column& {
  4721. assert( newWidth > 0 );
  4722. m_width = newWidth;
  4723. return *this;
  4724. }
  4725. auto indent( size_t newIndent ) -> Column& {
  4726. m_indent = newIndent;
  4727. return *this;
  4728. }
  4729. auto initialIndent( size_t newIndent ) -> Column& {
  4730. m_initialIndent = newIndent;
  4731. return *this;
  4732. }
  4733. auto width() const -> size_t { return m_width; }
  4734. auto begin() const -> iterator { return iterator( *this ); }
  4735. auto end() const -> iterator { return { *this, m_strings.size() }; }
  4736. inline friend std::ostream& operator << ( std::ostream& os, Column const& col ) {
  4737. bool first = true;
  4738. for( auto line : col ) {
  4739. if( first )
  4740. first = false;
  4741. else
  4742. os << "\n";
  4743. os << line;
  4744. }
  4745. return os;
  4746. }
  4747. auto operator + ( Column const& other ) -> Columns;
  4748. auto toString() const -> std::string {
  4749. std::ostringstream oss;
  4750. oss << *this;
  4751. return oss.str();
  4752. }
  4753. };
  4754. class Spacer : public Column {
  4755. public:
  4756. explicit Spacer( size_t spaceWidth ) : Column( "" ) {
  4757. width( spaceWidth );
  4758. }
  4759. };
  4760. class Columns {
  4761. std::vector<Column> m_columns;
  4762. public:
  4763. class iterator {
  4764. friend Columns;
  4765. struct EndTag {};
  4766. std::vector<Column> const& m_columns;
  4767. std::vector<Column::iterator> m_iterators;
  4768. size_t m_activeIterators;
  4769. iterator( Columns const& columns, EndTag )
  4770. : m_columns( columns.m_columns ),
  4771. m_activeIterators( 0 )
  4772. {
  4773. m_iterators.reserve( m_columns.size() );
  4774. for( auto const& col : m_columns )
  4775. m_iterators.push_back( col.end() );
  4776. }
  4777. public:
  4778. explicit iterator( Columns const& columns )
  4779. : m_columns( columns.m_columns ),
  4780. m_activeIterators( m_columns.size() )
  4781. {
  4782. m_iterators.reserve( m_columns.size() );
  4783. for( auto const& col : m_columns )
  4784. m_iterators.push_back( col.begin() );
  4785. }
  4786. auto operator ==( iterator const& other ) const -> bool {
  4787. return m_iterators == other.m_iterators;
  4788. }
  4789. auto operator !=( iterator const& other ) const -> bool {
  4790. return m_iterators != other.m_iterators;
  4791. }
  4792. auto operator *() const -> std::string {
  4793. std::string row, padding;
  4794. for( size_t i = 0; i < m_columns.size(); ++i ) {
  4795. auto width = m_columns[i].width();
  4796. if( m_iterators[i] != m_columns[i].end() ) {
  4797. std::string col = *m_iterators[i];
  4798. row += padding + col;
  4799. if( col.size() < width )
  4800. padding = std::string( width - col.size(), ' ' );
  4801. else
  4802. padding = "";
  4803. }
  4804. else {
  4805. padding += std::string( width, ' ' );
  4806. }
  4807. }
  4808. return row;
  4809. }
  4810. auto operator ++() -> iterator& {
  4811. for( size_t i = 0; i < m_columns.size(); ++i ) {
  4812. if (m_iterators[i] != m_columns[i].end())
  4813. ++m_iterators[i];
  4814. }
  4815. return *this;
  4816. }
  4817. auto operator ++(int) -> iterator {
  4818. iterator prev( *this );
  4819. operator++();
  4820. return prev;
  4821. }
  4822. };
  4823. using const_iterator = iterator;
  4824. auto begin() const -> iterator { return iterator( *this ); }
  4825. auto end() const -> iterator { return { *this, iterator::EndTag() }; }
  4826. auto operator += ( Column const& col ) -> Columns& {
  4827. m_columns.push_back( col );
  4828. return *this;
  4829. }
  4830. auto operator + ( Column const& col ) -> Columns {
  4831. Columns combined = *this;
  4832. combined += col;
  4833. return combined;
  4834. }
  4835. inline friend std::ostream& operator << ( std::ostream& os, Columns const& cols ) {
  4836. bool first = true;
  4837. for( auto line : cols ) {
  4838. if( first )
  4839. first = false;
  4840. else
  4841. os << "\n";
  4842. os << line;
  4843. }
  4844. return os;
  4845. }
  4846. auto toString() const -> std::string {
  4847. std::ostringstream oss;
  4848. oss << *this;
  4849. return oss.str();
  4850. }
  4851. };
  4852. inline auto Column::operator + ( Column const& other ) -> Columns {
  4853. Columns cols;
  4854. cols += *this;
  4855. cols += other;
  4856. return cols;
  4857. }
  4858. }}} // namespace Catch::clara::TextFlow
  4859. // ----------- end of #include from clara_textflow.hpp -----------
  4860. // ........... back in clara.hpp
  4861. #include <memory>
  4862. #include <set>
  4863. #include <algorithm>
  4864. #if !defined(CATCH_PLATFORM_WINDOWS) && ( defined(WIN32) || defined(__WIN32__) || defined(_WIN32) || defined(_MSC_VER) )
  4865. #define CATCH_PLATFORM_WINDOWS
  4866. #endif
  4867. namespace Catch { namespace clara {
  4868. namespace detail {
  4869. // Traits for extracting arg and return type of lambdas (for single argument lambdas)
  4870. template<typename L>
  4871. struct UnaryLambdaTraits : UnaryLambdaTraits<decltype( &L::operator() )> {};
  4872. template<typename ClassT, typename ReturnT, typename... Args>
  4873. struct UnaryLambdaTraits<ReturnT( ClassT::* )( Args... ) const> {
  4874. static const bool isValid = false;
  4875. };
  4876. template<typename ClassT, typename ReturnT, typename ArgT>
  4877. struct UnaryLambdaTraits<ReturnT( ClassT::* )( ArgT ) const> {
  4878. static const bool isValid = true;
  4879. using ArgType = typename std::remove_const<typename std::remove_reference<ArgT>::type>::type;
  4880. using ReturnType = ReturnT;
  4881. };
  4882. class TokenStream;
  4883. // Transport for raw args (copied from main args, or supplied via init list for testing)
  4884. class Args {
  4885. friend TokenStream;
  4886. std::string m_exeName;
  4887. std::vector<std::string> m_args;
  4888. public:
  4889. Args( int argc, char const* const* argv )
  4890. : m_exeName(argv[0]),
  4891. m_args(argv + 1, argv + argc) {}
  4892. Args( std::initializer_list<std::string> args )
  4893. : m_exeName( *args.begin() ),
  4894. m_args( args.begin()+1, args.end() )
  4895. {}
  4896. auto exeName() const -> std::string {
  4897. return m_exeName;
  4898. }
  4899. };
  4900. // Wraps a token coming from a token stream. These may not directly correspond to strings as a single string
  4901. // may encode an option + its argument if the : or = form is used
  4902. enum class TokenType {
  4903. Option, Argument
  4904. };
  4905. struct Token {
  4906. TokenType type;
  4907. std::string token;
  4908. };
  4909. inline auto isOptPrefix( char c ) -> bool {
  4910. return c == '-'
  4911. #ifdef CATCH_PLATFORM_WINDOWS
  4912. || c == '/'
  4913. #endif
  4914. ;
  4915. }
  4916. // Abstracts iterators into args as a stream of tokens, with option arguments uniformly handled
  4917. class TokenStream {
  4918. using Iterator = std::vector<std::string>::const_iterator;
  4919. Iterator it;
  4920. Iterator itEnd;
  4921. std::vector<Token> m_tokenBuffer;
  4922. void loadBuffer() {
  4923. m_tokenBuffer.resize( 0 );
  4924. // Skip any empty strings
  4925. while( it != itEnd && it->empty() )
  4926. ++it;
  4927. if( it != itEnd ) {
  4928. auto const &next = *it;
  4929. if( isOptPrefix( next[0] ) ) {
  4930. auto delimiterPos = next.find_first_of( " :=" );
  4931. if( delimiterPos != std::string::npos ) {
  4932. m_tokenBuffer.push_back( { TokenType::Option, next.substr( 0, delimiterPos ) } );
  4933. m_tokenBuffer.push_back( { TokenType::Argument, next.substr( delimiterPos + 1 ) } );
  4934. } else {
  4935. if( next[1] != '-' && next.size() > 2 ) {
  4936. std::string opt = "- ";
  4937. for( size_t i = 1; i < next.size(); ++i ) {
  4938. opt[1] = next[i];
  4939. m_tokenBuffer.push_back( { TokenType::Option, opt } );
  4940. }
  4941. } else {
  4942. m_tokenBuffer.push_back( { TokenType::Option, next } );
  4943. }
  4944. }
  4945. } else {
  4946. m_tokenBuffer.push_back( { TokenType::Argument, next } );
  4947. }
  4948. }
  4949. }
  4950. public:
  4951. explicit TokenStream( Args const &args ) : TokenStream( args.m_args.begin(), args.m_args.end() ) {}
  4952. TokenStream( Iterator it, Iterator itEnd ) : it( it ), itEnd( itEnd ) {
  4953. loadBuffer();
  4954. }
  4955. explicit operator bool() const {
  4956. return !m_tokenBuffer.empty() || it != itEnd;
  4957. }
  4958. auto count() const -> size_t { return m_tokenBuffer.size() + (itEnd - it); }
  4959. auto operator*() const -> Token {
  4960. assert( !m_tokenBuffer.empty() );
  4961. return m_tokenBuffer.front();
  4962. }
  4963. auto operator->() const -> Token const * {
  4964. assert( !m_tokenBuffer.empty() );
  4965. return &m_tokenBuffer.front();
  4966. }
  4967. auto operator++() -> TokenStream & {
  4968. if( m_tokenBuffer.size() >= 2 ) {
  4969. m_tokenBuffer.erase( m_tokenBuffer.begin() );
  4970. } else {
  4971. if( it != itEnd )
  4972. ++it;
  4973. loadBuffer();
  4974. }
  4975. return *this;
  4976. }
  4977. };
  4978. class ResultBase {
  4979. public:
  4980. enum Type {
  4981. Ok, LogicError, RuntimeError
  4982. };
  4983. protected:
  4984. ResultBase( Type type ) : m_type( type ) {}
  4985. virtual ~ResultBase() = default;
  4986. virtual void enforceOk() const = 0;
  4987. Type m_type;
  4988. };
  4989. template<typename T>
  4990. class ResultValueBase : public ResultBase {
  4991. public:
  4992. auto value() const -> T const & {
  4993. enforceOk();
  4994. return m_value;
  4995. }
  4996. protected:
  4997. ResultValueBase( Type type ) : ResultBase( type ) {}
  4998. ResultValueBase( ResultValueBase const &other ) : ResultBase( other ) {
  4999. if( m_type == ResultBase::Ok )
  5000. new( &m_value ) T( other.m_value );
  5001. }
  5002. ResultValueBase( Type, T const &value ) : ResultBase( Ok ) {
  5003. new( &m_value ) T( value );
  5004. }
  5005. auto operator=( ResultValueBase const &other ) -> ResultValueBase & {
  5006. if( m_type == ResultBase::Ok )
  5007. m_value.~T();
  5008. ResultBase::operator=(other);
  5009. if( m_type == ResultBase::Ok )
  5010. new( &m_value ) T( other.m_value );
  5011. return *this;
  5012. }
  5013. ~ResultValueBase() override {
  5014. if( m_type == Ok )
  5015. m_value.~T();
  5016. }
  5017. union {
  5018. T m_value;
  5019. };
  5020. };
  5021. template<>
  5022. class ResultValueBase<void> : public ResultBase {
  5023. protected:
  5024. using ResultBase::ResultBase;
  5025. };
  5026. template<typename T = void>
  5027. class BasicResult : public ResultValueBase<T> {
  5028. public:
  5029. template<typename U>
  5030. explicit BasicResult( BasicResult<U> const &other )
  5031. : ResultValueBase<T>( other.type() ),
  5032. m_errorMessage( other.errorMessage() )
  5033. {
  5034. assert( type() != ResultBase::Ok );
  5035. }
  5036. template<typename U>
  5037. static auto ok( U const &value ) -> BasicResult { return { ResultBase::Ok, value }; }
  5038. static auto ok() -> BasicResult { return { ResultBase::Ok }; }
  5039. static auto logicError( std::string const &message ) -> BasicResult { return { ResultBase::LogicError, message }; }
  5040. static auto runtimeError( std::string const &message ) -> BasicResult { return { ResultBase::RuntimeError, message }; }
  5041. explicit operator bool() const { return m_type == ResultBase::Ok; }
  5042. auto type() const -> ResultBase::Type { return m_type; }
  5043. auto errorMessage() const -> std::string { return m_errorMessage; }
  5044. protected:
  5045. void enforceOk() const override {
  5046. // Errors shouldn't reach this point, but if they do
  5047. // the actual error message will be in m_errorMessage
  5048. assert( m_type != ResultBase::LogicError );
  5049. assert( m_type != ResultBase::RuntimeError );
  5050. if( m_type != ResultBase::Ok )
  5051. std::abort();
  5052. }
  5053. std::string m_errorMessage; // Only populated if resultType is an error
  5054. BasicResult( ResultBase::Type type, std::string const &message )
  5055. : ResultValueBase<T>(type),
  5056. m_errorMessage(message)
  5057. {
  5058. assert( m_type != ResultBase::Ok );
  5059. }
  5060. using ResultValueBase<T>::ResultValueBase;
  5061. using ResultBase::m_type;
  5062. };
  5063. enum class ParseResultType {
  5064. Matched, NoMatch, ShortCircuitAll, ShortCircuitSame
  5065. };
  5066. class ParseState {
  5067. public:
  5068. ParseState( ParseResultType type, TokenStream const &remainingTokens )
  5069. : m_type(type),
  5070. m_remainingTokens( remainingTokens )
  5071. {}
  5072. auto type() const -> ParseResultType { return m_type; }
  5073. auto remainingTokens() const -> TokenStream { return m_remainingTokens; }
  5074. private:
  5075. ParseResultType m_type;
  5076. TokenStream m_remainingTokens;
  5077. };
  5078. using Result = BasicResult<void>;
  5079. using ParserResult = BasicResult<ParseResultType>;
  5080. using InternalParseResult = BasicResult<ParseState>;
  5081. struct HelpColumns {
  5082. std::string left;
  5083. std::string right;
  5084. };
  5085. template<typename T>
  5086. inline auto convertInto( std::string const &source, T& target ) -> ParserResult {
  5087. std::stringstream ss;
  5088. ss << source;
  5089. ss >> target;
  5090. if( ss.fail() )
  5091. return ParserResult::runtimeError( "Unable to convert '" + source + "' to destination type" );
  5092. else
  5093. return ParserResult::ok( ParseResultType::Matched );
  5094. }
  5095. inline auto convertInto( std::string const &source, std::string& target ) -> ParserResult {
  5096. target = source;
  5097. return ParserResult::ok( ParseResultType::Matched );
  5098. }
  5099. inline auto convertInto( std::string const &source, bool &target ) -> ParserResult {
  5100. std::string srcLC = source;
  5101. std::transform( srcLC.begin(), srcLC.end(), srcLC.begin(), []( char c ) { return static_cast<char>( ::tolower(c) ); } );
  5102. if (srcLC == "y" || srcLC == "1" || srcLC == "true" || srcLC == "yes" || srcLC == "on")
  5103. target = true;
  5104. else if (srcLC == "n" || srcLC == "0" || srcLC == "false" || srcLC == "no" || srcLC == "off")
  5105. target = false;
  5106. else
  5107. return ParserResult::runtimeError( "Expected a boolean value but did not recognise: '" + source + "'" );
  5108. return ParserResult::ok( ParseResultType::Matched );
  5109. }
  5110. #ifdef CLARA_CONFIG_OPTIONAL_TYPE
  5111. template<typename T>
  5112. inline auto convertInto( std::string const &source, CLARA_CONFIG_OPTIONAL_TYPE<T>& target ) -> ParserResult {
  5113. T temp;
  5114. auto result = convertInto( source, temp );
  5115. if( result )
  5116. target = std::move(temp);
  5117. return result;
  5118. }
  5119. #endif // CLARA_CONFIG_OPTIONAL_TYPE
  5120. struct NonCopyable {
  5121. NonCopyable() = default;
  5122. NonCopyable( NonCopyable const & ) = delete;
  5123. NonCopyable( NonCopyable && ) = delete;
  5124. NonCopyable &operator=( NonCopyable const & ) = delete;
  5125. NonCopyable &operator=( NonCopyable && ) = delete;
  5126. };
  5127. struct BoundRef : NonCopyable {
  5128. virtual ~BoundRef() = default;
  5129. virtual auto isContainer() const -> bool { return false; }
  5130. virtual auto isFlag() const -> bool { return false; }
  5131. };
  5132. struct BoundValueRefBase : BoundRef {
  5133. virtual auto setValue( std::string const &arg ) -> ParserResult = 0;
  5134. };
  5135. struct BoundFlagRefBase : BoundRef {
  5136. virtual auto setFlag( bool flag ) -> ParserResult = 0;
  5137. virtual auto isFlag() const -> bool { return true; }
  5138. };
  5139. template<typename T>
  5140. struct BoundValueRef : BoundValueRefBase {
  5141. T &m_ref;
  5142. explicit BoundValueRef( T &ref ) : m_ref( ref ) {}
  5143. auto setValue( std::string const &arg ) -> ParserResult override {
  5144. return convertInto( arg, m_ref );
  5145. }
  5146. };
  5147. template<typename T>
  5148. struct BoundValueRef<std::vector<T>> : BoundValueRefBase {
  5149. std::vector<T> &m_ref;
  5150. explicit BoundValueRef( std::vector<T> &ref ) : m_ref( ref ) {}
  5151. auto isContainer() const -> bool override { return true; }
  5152. auto setValue( std::string const &arg ) -> ParserResult override {
  5153. T temp;
  5154. auto result = convertInto( arg, temp );
  5155. if( result )
  5156. m_ref.push_back( temp );
  5157. return result;
  5158. }
  5159. };
  5160. struct BoundFlagRef : BoundFlagRefBase {
  5161. bool &m_ref;
  5162. explicit BoundFlagRef( bool &ref ) : m_ref( ref ) {}
  5163. auto setFlag( bool flag ) -> ParserResult override {
  5164. m_ref = flag;
  5165. return ParserResult::ok( ParseResultType::Matched );
  5166. }
  5167. };
  5168. template<typename ReturnType>
  5169. struct LambdaInvoker {
  5170. static_assert( std::is_same<ReturnType, ParserResult>::value, "Lambda must return void or clara::ParserResult" );
  5171. template<typename L, typename ArgType>
  5172. static auto invoke( L const &lambda, ArgType const &arg ) -> ParserResult {
  5173. return lambda( arg );
  5174. }
  5175. };
  5176. template<>
  5177. struct LambdaInvoker<void> {
  5178. template<typename L, typename ArgType>
  5179. static auto invoke( L const &lambda, ArgType const &arg ) -> ParserResult {
  5180. lambda( arg );
  5181. return ParserResult::ok( ParseResultType::Matched );
  5182. }
  5183. };
  5184. template<typename ArgType, typename L>
  5185. inline auto invokeLambda( L const &lambda, std::string const &arg ) -> ParserResult {
  5186. ArgType temp{};
  5187. auto result = convertInto( arg, temp );
  5188. return !result
  5189. ? result
  5190. : LambdaInvoker<typename UnaryLambdaTraits<L>::ReturnType>::invoke( lambda, temp );
  5191. }
  5192. template<typename L>
  5193. struct BoundLambda : BoundValueRefBase {
  5194. L m_lambda;
  5195. static_assert( UnaryLambdaTraits<L>::isValid, "Supplied lambda must take exactly one argument" );
  5196. explicit BoundLambda( L const &lambda ) : m_lambda( lambda ) {}
  5197. auto setValue( std::string const &arg ) -> ParserResult override {
  5198. return invokeLambda<typename UnaryLambdaTraits<L>::ArgType>( m_lambda, arg );
  5199. }
  5200. };
  5201. template<typename L>
  5202. struct BoundFlagLambda : BoundFlagRefBase {
  5203. L m_lambda;
  5204. static_assert( UnaryLambdaTraits<L>::isValid, "Supplied lambda must take exactly one argument" );
  5205. static_assert( std::is_same<typename UnaryLambdaTraits<L>::ArgType, bool>::value, "flags must be boolean" );
  5206. explicit BoundFlagLambda( L const &lambda ) : m_lambda( lambda ) {}
  5207. auto setFlag( bool flag ) -> ParserResult override {
  5208. return LambdaInvoker<typename UnaryLambdaTraits<L>::ReturnType>::invoke( m_lambda, flag );
  5209. }
  5210. };
  5211. enum class Optionality { Optional, Required };
  5212. struct Parser;
  5213. class ParserBase {
  5214. public:
  5215. virtual ~ParserBase() = default;
  5216. virtual auto validate() const -> Result { return Result::ok(); }
  5217. virtual auto parse( std::string const& exeName, TokenStream const &tokens) const -> InternalParseResult = 0;
  5218. virtual auto cardinality() const -> size_t { return 1; }
  5219. auto parse( Args const &args ) const -> InternalParseResult {
  5220. return parse( args.exeName(), TokenStream( args ) );
  5221. }
  5222. };
  5223. template<typename DerivedT>
  5224. class ComposableParserImpl : public ParserBase {
  5225. public:
  5226. template<typename T>
  5227. auto operator|( T const &other ) const -> Parser;
  5228. template<typename T>
  5229. auto operator+( T const &other ) const -> Parser;
  5230. };
  5231. // Common code and state for Args and Opts
  5232. template<typename DerivedT>
  5233. class ParserRefImpl : public ComposableParserImpl<DerivedT> {
  5234. protected:
  5235. Optionality m_optionality = Optionality::Optional;
  5236. std::shared_ptr<BoundRef> m_ref;
  5237. std::string m_hint;
  5238. std::string m_description;
  5239. explicit ParserRefImpl( std::shared_ptr<BoundRef> const &ref ) : m_ref( ref ) {}
  5240. public:
  5241. template<typename T>
  5242. ParserRefImpl( T &ref, std::string const &hint )
  5243. : m_ref( std::make_shared<BoundValueRef<T>>( ref ) ),
  5244. m_hint( hint )
  5245. {}
  5246. template<typename LambdaT>
  5247. ParserRefImpl( LambdaT const &ref, std::string const &hint )
  5248. : m_ref( std::make_shared<BoundLambda<LambdaT>>( ref ) ),
  5249. m_hint(hint)
  5250. {}
  5251. auto operator()( std::string const &description ) -> DerivedT & {
  5252. m_description = description;
  5253. return static_cast<DerivedT &>( *this );
  5254. }
  5255. auto optional() -> DerivedT & {
  5256. m_optionality = Optionality::Optional;
  5257. return static_cast<DerivedT &>( *this );
  5258. };
  5259. auto required() -> DerivedT & {
  5260. m_optionality = Optionality::Required;
  5261. return static_cast<DerivedT &>( *this );
  5262. };
  5263. auto isOptional() const -> bool {
  5264. return m_optionality == Optionality::Optional;
  5265. }
  5266. auto cardinality() const -> size_t override {
  5267. if( m_ref->isContainer() )
  5268. return 0;
  5269. else
  5270. return 1;
  5271. }
  5272. auto hint() const -> std::string { return m_hint; }
  5273. };
  5274. class ExeName : public ComposableParserImpl<ExeName> {
  5275. std::shared_ptr<std::string> m_name;
  5276. std::shared_ptr<BoundValueRefBase> m_ref;
  5277. template<typename LambdaT>
  5278. static auto makeRef(LambdaT const &lambda) -> std::shared_ptr<BoundValueRefBase> {
  5279. return std::make_shared<BoundLambda<LambdaT>>( lambda) ;
  5280. }
  5281. public:
  5282. ExeName() : m_name( std::make_shared<std::string>( "<executable>" ) ) {}
  5283. explicit ExeName( std::string &ref ) : ExeName() {
  5284. m_ref = std::make_shared<BoundValueRef<std::string>>( ref );
  5285. }
  5286. template<typename LambdaT>
  5287. explicit ExeName( LambdaT const& lambda ) : ExeName() {
  5288. m_ref = std::make_shared<BoundLambda<LambdaT>>( lambda );
  5289. }
  5290. // The exe name is not parsed out of the normal tokens, but is handled specially
  5291. auto parse( std::string const&, TokenStream const &tokens ) const -> InternalParseResult override {
  5292. return InternalParseResult::ok( ParseState( ParseResultType::NoMatch, tokens ) );
  5293. }
  5294. auto name() const -> std::string { return *m_name; }
  5295. auto set( std::string const& newName ) -> ParserResult {
  5296. auto lastSlash = newName.find_last_of( "\\/" );
  5297. auto filename = ( lastSlash == std::string::npos )
  5298. ? newName
  5299. : newName.substr( lastSlash+1 );
  5300. *m_name = filename;
  5301. if( m_ref )
  5302. return m_ref->setValue( filename );
  5303. else
  5304. return ParserResult::ok( ParseResultType::Matched );
  5305. }
  5306. };
  5307. class Arg : public ParserRefImpl<Arg> {
  5308. public:
  5309. using ParserRefImpl::ParserRefImpl;
  5310. auto parse( std::string const &, TokenStream const &tokens ) const -> InternalParseResult override {
  5311. auto validationResult = validate();
  5312. if( !validationResult )
  5313. return InternalParseResult( validationResult );
  5314. auto remainingTokens = tokens;
  5315. auto const &token = *remainingTokens;
  5316. if( token.type != TokenType::Argument )
  5317. return InternalParseResult::ok( ParseState( ParseResultType::NoMatch, remainingTokens ) );
  5318. assert( !m_ref->isFlag() );
  5319. auto valueRef = static_cast<detail::BoundValueRefBase*>( m_ref.get() );
  5320. auto result = valueRef->setValue( remainingTokens->token );
  5321. if( !result )
  5322. return InternalParseResult( result );
  5323. else
  5324. return InternalParseResult::ok( ParseState( ParseResultType::Matched, ++remainingTokens ) );
  5325. }
  5326. };
  5327. inline auto normaliseOpt( std::string const &optName ) -> std::string {
  5328. #ifdef CATCH_PLATFORM_WINDOWS
  5329. if( optName[0] == '/' )
  5330. return "-" + optName.substr( 1 );
  5331. else
  5332. #endif
  5333. return optName;
  5334. }
  5335. class Opt : public ParserRefImpl<Opt> {
  5336. protected:
  5337. std::vector<std::string> m_optNames;
  5338. public:
  5339. template<typename LambdaT>
  5340. explicit Opt( LambdaT const &ref ) : ParserRefImpl( std::make_shared<BoundFlagLambda<LambdaT>>( ref ) ) {}
  5341. explicit Opt( bool &ref ) : ParserRefImpl( std::make_shared<BoundFlagRef>( ref ) ) {}
  5342. template<typename LambdaT>
  5343. Opt( LambdaT const &ref, std::string const &hint ) : ParserRefImpl( ref, hint ) {}
  5344. template<typename T>
  5345. Opt( T &ref, std::string const &hint ) : ParserRefImpl( ref, hint ) {}
  5346. auto operator[]( std::string const &optName ) -> Opt & {
  5347. m_optNames.push_back( optName );
  5348. return *this;
  5349. }
  5350. auto getHelpColumns() const -> std::vector<HelpColumns> {
  5351. std::ostringstream oss;
  5352. bool first = true;
  5353. for( auto const &opt : m_optNames ) {
  5354. if (first)
  5355. first = false;
  5356. else
  5357. oss << ", ";
  5358. oss << opt;
  5359. }
  5360. if( !m_hint.empty() )
  5361. oss << " <" << m_hint << ">";
  5362. return { { oss.str(), m_description } };
  5363. }
  5364. auto isMatch( std::string const &optToken ) const -> bool {
  5365. auto normalisedToken = normaliseOpt( optToken );
  5366. for( auto const &name : m_optNames ) {
  5367. if( normaliseOpt( name ) == normalisedToken )
  5368. return true;
  5369. }
  5370. return false;
  5371. }
  5372. using ParserBase::parse;
  5373. auto parse( std::string const&, TokenStream const &tokens ) const -> InternalParseResult override {
  5374. auto validationResult = validate();
  5375. if( !validationResult )
  5376. return InternalParseResult( validationResult );
  5377. auto remainingTokens = tokens;
  5378. if( remainingTokens && remainingTokens->type == TokenType::Option ) {
  5379. auto const &token = *remainingTokens;
  5380. if( isMatch(token.token ) ) {
  5381. if( m_ref->isFlag() ) {
  5382. auto flagRef = static_cast<detail::BoundFlagRefBase*>( m_ref.get() );
  5383. auto result = flagRef->setFlag( true );
  5384. if( !result )
  5385. return InternalParseResult( result );
  5386. if( result.value() == ParseResultType::ShortCircuitAll )
  5387. return InternalParseResult::ok( ParseState( result.value(), remainingTokens ) );
  5388. } else {
  5389. auto valueRef = static_cast<detail::BoundValueRefBase*>( m_ref.get() );
  5390. ++remainingTokens;
  5391. if( !remainingTokens )
  5392. return InternalParseResult::runtimeError( "Expected argument following " + token.token );
  5393. auto const &argToken = *remainingTokens;
  5394. if( argToken.type != TokenType::Argument )
  5395. return InternalParseResult::runtimeError( "Expected argument following " + token.token );
  5396. auto result = valueRef->setValue( argToken.token );
  5397. if( !result )
  5398. return InternalParseResult( result );
  5399. if( result.value() == ParseResultType::ShortCircuitAll )
  5400. return InternalParseResult::ok( ParseState( result.value(), remainingTokens ) );
  5401. }
  5402. return InternalParseResult::ok( ParseState( ParseResultType::Matched, ++remainingTokens ) );
  5403. }
  5404. }
  5405. return InternalParseResult::ok( ParseState( ParseResultType::NoMatch, remainingTokens ) );
  5406. }
  5407. auto validate() const -> Result override {
  5408. if( m_optNames.empty() )
  5409. return Result::logicError( "No options supplied to Opt" );
  5410. for( auto const &name : m_optNames ) {
  5411. if( name.empty() )
  5412. return Result::logicError( "Option name cannot be empty" );
  5413. #ifdef CATCH_PLATFORM_WINDOWS
  5414. if( name[0] != '-' && name[0] != '/' )
  5415. return Result::logicError( "Option name must begin with '-' or '/'" );
  5416. #else
  5417. if( name[0] != '-' )
  5418. return Result::logicError( "Option name must begin with '-'" );
  5419. #endif
  5420. }
  5421. return ParserRefImpl::validate();
  5422. }
  5423. };
  5424. struct Help : Opt {
  5425. Help( bool &showHelpFlag )
  5426. : Opt([&]( bool flag ) {
  5427. showHelpFlag = flag;
  5428. return ParserResult::ok( ParseResultType::ShortCircuitAll );
  5429. })
  5430. {
  5431. static_cast<Opt &>( *this )
  5432. ("display usage information")
  5433. ["-?"]["-h"]["--help"]
  5434. .optional();
  5435. }
  5436. };
  5437. struct Parser : ParserBase {
  5438. mutable ExeName m_exeName;
  5439. std::vector<Opt> m_options;
  5440. std::vector<Arg> m_args;
  5441. auto operator|=( ExeName const &exeName ) -> Parser & {
  5442. m_exeName = exeName;
  5443. return *this;
  5444. }
  5445. auto operator|=( Arg const &arg ) -> Parser & {
  5446. m_args.push_back(arg);
  5447. return *this;
  5448. }
  5449. auto operator|=( Opt const &opt ) -> Parser & {
  5450. m_options.push_back(opt);
  5451. return *this;
  5452. }
  5453. auto operator|=( Parser const &other ) -> Parser & {
  5454. m_options.insert(m_options.end(), other.m_options.begin(), other.m_options.end());
  5455. m_args.insert(m_args.end(), other.m_args.begin(), other.m_args.end());
  5456. return *this;
  5457. }
  5458. template<typename T>
  5459. auto operator|( T const &other ) const -> Parser {
  5460. return Parser( *this ) |= other;
  5461. }
  5462. // Forward deprecated interface with '+' instead of '|'
  5463. template<typename T>
  5464. auto operator+=( T const &other ) -> Parser & { return operator|=( other ); }
  5465. template<typename T>
  5466. auto operator+( T const &other ) const -> Parser { return operator|( other ); }
  5467. auto getHelpColumns() const -> std::vector<HelpColumns> {
  5468. std::vector<HelpColumns> cols;
  5469. for (auto const &o : m_options) {
  5470. auto childCols = o.getHelpColumns();
  5471. cols.insert( cols.end(), childCols.begin(), childCols.end() );
  5472. }
  5473. return cols;
  5474. }
  5475. void writeToStream( std::ostream &os ) const {
  5476. if (!m_exeName.name().empty()) {
  5477. os << "usage:\n" << " " << m_exeName.name() << " ";
  5478. bool required = true, first = true;
  5479. for( auto const &arg : m_args ) {
  5480. if (first)
  5481. first = false;
  5482. else
  5483. os << " ";
  5484. if( arg.isOptional() && required ) {
  5485. os << "[";
  5486. required = false;
  5487. }
  5488. os << "<" << arg.hint() << ">";
  5489. if( arg.cardinality() == 0 )
  5490. os << " ... ";
  5491. }
  5492. if( !required )
  5493. os << "]";
  5494. if( !m_options.empty() )
  5495. os << " options";
  5496. os << "\n\nwhere options are:" << std::endl;
  5497. }
  5498. auto rows = getHelpColumns();
  5499. size_t consoleWidth = CATCH_CLARA_CONFIG_CONSOLE_WIDTH;
  5500. size_t optWidth = 0;
  5501. for( auto const &cols : rows )
  5502. optWidth = (std::max)(optWidth, cols.left.size() + 2);
  5503. optWidth = (std::min)(optWidth, consoleWidth/2);
  5504. for( auto const &cols : rows ) {
  5505. auto row =
  5506. TextFlow::Column( cols.left ).width( optWidth ).indent( 2 ) +
  5507. TextFlow::Spacer(4) +
  5508. TextFlow::Column( cols.right ).width( consoleWidth - 7 - optWidth );
  5509. os << row << std::endl;
  5510. }
  5511. }
  5512. friend auto operator<<( std::ostream &os, Parser const &parser ) -> std::ostream& {
  5513. parser.writeToStream( os );
  5514. return os;
  5515. }
  5516. auto validate() const -> Result override {
  5517. for( auto const &opt : m_options ) {
  5518. auto result = opt.validate();
  5519. if( !result )
  5520. return result;
  5521. }
  5522. for( auto const &arg : m_args ) {
  5523. auto result = arg.validate();
  5524. if( !result )
  5525. return result;
  5526. }
  5527. return Result::ok();
  5528. }
  5529. using ParserBase::parse;
  5530. auto parse( std::string const& exeName, TokenStream const &tokens ) const -> InternalParseResult override {
  5531. struct ParserInfo {
  5532. ParserBase const* parser = nullptr;
  5533. size_t count = 0;
  5534. };
  5535. const size_t totalParsers = m_options.size() + m_args.size();
  5536. assert( totalParsers < 512 );
  5537. // ParserInfo parseInfos[totalParsers]; // <-- this is what we really want to do
  5538. ParserInfo parseInfos[512];
  5539. {
  5540. size_t i = 0;
  5541. for (auto const &opt : m_options) parseInfos[i++].parser = &opt;
  5542. for (auto const &arg : m_args) parseInfos[i++].parser = &arg;
  5543. }
  5544. m_exeName.set( exeName );
  5545. auto result = InternalParseResult::ok( ParseState( ParseResultType::NoMatch, tokens ) );
  5546. while( result.value().remainingTokens() ) {
  5547. bool tokenParsed = false;
  5548. for( size_t i = 0; i < totalParsers; ++i ) {
  5549. auto& parseInfo = parseInfos[i];
  5550. if( parseInfo.parser->cardinality() == 0 || parseInfo.count < parseInfo.parser->cardinality() ) {
  5551. result = parseInfo.parser->parse(exeName, result.value().remainingTokens());
  5552. if (!result)
  5553. return result;
  5554. if (result.value().type() != ParseResultType::NoMatch) {
  5555. tokenParsed = true;
  5556. ++parseInfo.count;
  5557. break;
  5558. }
  5559. }
  5560. }
  5561. if( result.value().type() == ParseResultType::ShortCircuitAll )
  5562. return result;
  5563. if( !tokenParsed )
  5564. return InternalParseResult::runtimeError( "Unrecognised token: " + result.value().remainingTokens()->token );
  5565. }
  5566. // !TBD Check missing required options
  5567. return result;
  5568. }
  5569. };
  5570. template<typename DerivedT>
  5571. template<typename T>
  5572. auto ComposableParserImpl<DerivedT>::operator|( T const &other ) const -> Parser {
  5573. return Parser() | static_cast<DerivedT const &>( *this ) | other;
  5574. }
  5575. } // namespace detail
  5576. // A Combined parser
  5577. using detail::Parser;
  5578. // A parser for options
  5579. using detail::Opt;
  5580. // A parser for arguments
  5581. using detail::Arg;
  5582. // Wrapper for argc, argv from main()
  5583. using detail::Args;
  5584. // Specifies the name of the executable
  5585. using detail::ExeName;
  5586. // Convenience wrapper for option parser that specifies the help option
  5587. using detail::Help;
  5588. // enum of result types from a parse
  5589. using detail::ParseResultType;
  5590. // Result type for parser operation
  5591. using detail::ParserResult;
  5592. }} // namespace Catch::clara
  5593. // end clara.hpp
  5594. #ifdef __clang__
  5595. #pragma clang diagnostic pop
  5596. #endif
  5597. // Restore Clara's value for console width, if present
  5598. #ifdef CATCH_TEMP_CLARA_CONFIG_CONSOLE_WIDTH
  5599. #define CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH CATCH_TEMP_CLARA_CONFIG_CONSOLE_WIDTH
  5600. #undef CATCH_TEMP_CLARA_CONFIG_CONSOLE_WIDTH
  5601. #endif
  5602. // end catch_clara.h
  5603. namespace Catch {
  5604. clara::Parser makeCommandLineParser( ConfigData& config );
  5605. } // end namespace Catch
  5606. // end catch_commandline.h
  5607. #include <fstream>
  5608. #include <ctime>
  5609. namespace Catch {
  5610. clara::Parser makeCommandLineParser( ConfigData& config ) {
  5611. using namespace clara;
  5612. auto const setWarning = [&]( std::string const& warning ) {
  5613. auto warningSet = [&]() {
  5614. if( warning == "NoAssertions" )
  5615. return WarnAbout::NoAssertions;
  5616. if ( warning == "NoTests" )
  5617. return WarnAbout::NoTests;
  5618. return WarnAbout::Nothing;
  5619. }();
  5620. if (warningSet == WarnAbout::Nothing)
  5621. return ParserResult::runtimeError( "Unrecognised warning: '" + warning + "'" );
  5622. config.warnings = static_cast<WarnAbout::What>( config.warnings | warningSet );
  5623. return ParserResult::ok( ParseResultType::Matched );
  5624. };
  5625. auto const loadTestNamesFromFile = [&]( std::string const& filename ) {
  5626. std::ifstream f( filename.c_str() );
  5627. if( !f.is_open() )
  5628. return ParserResult::runtimeError( "Unable to load input file: '" + filename + "'" );
  5629. std::string line;
  5630. while( std::getline( f, line ) ) {
  5631. line = trim(line);
  5632. if( !line.empty() && !startsWith( line, '#' ) ) {
  5633. if( !startsWith( line, '"' ) )
  5634. line = '"' + line + '"';
  5635. config.testsOrTags.push_back( line + ',' );
  5636. }
  5637. }
  5638. return ParserResult::ok( ParseResultType::Matched );
  5639. };
  5640. auto const setTestOrder = [&]( std::string const& order ) {
  5641. if( startsWith( "declared", order ) )
  5642. config.runOrder = RunTests::InDeclarationOrder;
  5643. else if( startsWith( "lexical", order ) )
  5644. config.runOrder = RunTests::InLexicographicalOrder;
  5645. else if( startsWith( "random", order ) )
  5646. config.runOrder = RunTests::InRandomOrder;
  5647. else
  5648. return clara::ParserResult::runtimeError( "Unrecognised ordering: '" + order + "'" );
  5649. return ParserResult::ok( ParseResultType::Matched );
  5650. };
  5651. auto const setRngSeed = [&]( std::string const& seed ) {
  5652. if( seed != "time" )
  5653. return clara::detail::convertInto( seed, config.rngSeed );
  5654. config.rngSeed = static_cast<unsigned int>( std::time(nullptr) );
  5655. return ParserResult::ok( ParseResultType::Matched );
  5656. };
  5657. auto const setColourUsage = [&]( std::string const& useColour ) {
  5658. auto mode = toLower( useColour );
  5659. if( mode == "yes" )
  5660. config.useColour = UseColour::Yes;
  5661. else if( mode == "no" )
  5662. config.useColour = UseColour::No;
  5663. else if( mode == "auto" )
  5664. config.useColour = UseColour::Auto;
  5665. else
  5666. return ParserResult::runtimeError( "colour mode must be one of: auto, yes or no. '" + useColour + "' not recognised" );
  5667. return ParserResult::ok( ParseResultType::Matched );
  5668. };
  5669. auto const setWaitForKeypress = [&]( std::string const& keypress ) {
  5670. auto keypressLc = toLower( keypress );
  5671. if( keypressLc == "start" )
  5672. config.waitForKeypress = WaitForKeypress::BeforeStart;
  5673. else if( keypressLc == "exit" )
  5674. config.waitForKeypress = WaitForKeypress::BeforeExit;
  5675. else if( keypressLc == "both" )
  5676. config.waitForKeypress = WaitForKeypress::BeforeStartAndExit;
  5677. else
  5678. return ParserResult::runtimeError( "keypress argument must be one of: start, exit or both. '" + keypress + "' not recognised" );
  5679. return ParserResult::ok( ParseResultType::Matched );
  5680. };
  5681. auto const setVerbosity = [&]( std::string const& verbosity ) {
  5682. auto lcVerbosity = toLower( verbosity );
  5683. if( lcVerbosity == "quiet" )
  5684. config.verbosity = Verbosity::Quiet;
  5685. else if( lcVerbosity == "normal" )
  5686. config.verbosity = Verbosity::Normal;
  5687. else if( lcVerbosity == "high" )
  5688. config.verbosity = Verbosity::High;
  5689. else
  5690. return ParserResult::runtimeError( "Unrecognised verbosity, '" + verbosity + "'" );
  5691. return ParserResult::ok( ParseResultType::Matched );
  5692. };
  5693. auto cli
  5694. = ExeName( config.processName )
  5695. | Help( config.showHelp )
  5696. | Opt( config.listTests )
  5697. ["-l"]["--list-tests"]
  5698. ( "list all/matching test cases" )
  5699. | Opt( config.listTags )
  5700. ["-t"]["--list-tags"]
  5701. ( "list all/matching tags" )
  5702. | Opt( config.showSuccessfulTests )
  5703. ["-s"]["--success"]
  5704. ( "include successful tests in output" )
  5705. | Opt( config.shouldDebugBreak )
  5706. ["-b"]["--break"]
  5707. ( "break into debugger on failure" )
  5708. | Opt( config.noThrow )
  5709. ["-e"]["--nothrow"]
  5710. ( "skip exception tests" )
  5711. | Opt( config.showInvisibles )
  5712. ["-i"]["--invisibles"]
  5713. ( "show invisibles (tabs, newlines)" )
  5714. | Opt( config.outputFilename, "filename" )
  5715. ["-o"]["--out"]
  5716. ( "output filename" )
  5717. | Opt( config.reporterName, "name" )
  5718. ["-r"]["--reporter"]
  5719. ( "reporter to use (defaults to console)" )
  5720. | Opt( config.name, "name" )
  5721. ["-n"]["--name"]
  5722. ( "suite name" )
  5723. | Opt( [&]( bool ){ config.abortAfter = 1; } )
  5724. ["-a"]["--abort"]
  5725. ( "abort at first failure" )
  5726. | Opt( [&]( int x ){ config.abortAfter = x; }, "no. failures" )
  5727. ["-x"]["--abortx"]
  5728. ( "abort after x failures" )
  5729. | Opt( setWarning, "warning name" )
  5730. ["-w"]["--warn"]
  5731. ( "enable warnings" )
  5732. | Opt( [&]( bool flag ) { config.showDurations = flag ? ShowDurations::Always : ShowDurations::Never; }, "yes|no" )
  5733. ["-d"]["--durations"]
  5734. ( "show test durations" )
  5735. | Opt( loadTestNamesFromFile, "filename" )
  5736. ["-f"]["--input-file"]
  5737. ( "load test names to run from a file" )
  5738. | Opt( config.filenamesAsTags )
  5739. ["-#"]["--filenames-as-tags"]
  5740. ( "adds a tag for the filename" )
  5741. | Opt( config.sectionsToRun, "section name" )
  5742. ["-c"]["--section"]
  5743. ( "specify section to run" )
  5744. | Opt( setVerbosity, "quiet|normal|high" )
  5745. ["-v"]["--verbosity"]
  5746. ( "set output verbosity" )
  5747. | Opt( config.listTestNamesOnly )
  5748. ["--list-test-names-only"]
  5749. ( "list all/matching test cases names only" )
  5750. | Opt( config.listReporters )
  5751. ["--list-reporters"]
  5752. ( "list all reporters" )
  5753. | Opt( setTestOrder, "decl|lex|rand" )
  5754. ["--order"]
  5755. ( "test case order (defaults to decl)" )
  5756. | Opt( setRngSeed, "'time'|number" )
  5757. ["--rng-seed"]
  5758. ( "set a specific seed for random numbers" )
  5759. | Opt( setColourUsage, "yes|no" )
  5760. ["--use-colour"]
  5761. ( "should output be colourised" )
  5762. | Opt( config.libIdentify )
  5763. ["--libidentify"]
  5764. ( "report name and version according to libidentify standard" )
  5765. | Opt( setWaitForKeypress, "start|exit|both" )
  5766. ["--wait-for-keypress"]
  5767. ( "waits for a keypress before exiting" )
  5768. | Opt( config.benchmarkResolutionMultiple, "multiplier" )
  5769. ["--benchmark-resolution-multiple"]
  5770. ( "multiple of clock resolution to run benchmarks" )
  5771. | Arg( config.testsOrTags, "test name|pattern|tags" )
  5772. ( "which test or tests to use" );
  5773. return cli;
  5774. }
  5775. } // end namespace Catch
  5776. // end catch_commandline.cpp
  5777. // start catch_common.cpp
  5778. #include <cstring>
  5779. #include <ostream>
  5780. namespace Catch {
  5781. bool SourceLineInfo::empty() const noexcept {
  5782. return file[0] == '\0';
  5783. }
  5784. bool SourceLineInfo::operator == ( SourceLineInfo const& other ) const noexcept {
  5785. return line == other.line && (file == other.file || std::strcmp(file, other.file) == 0);
  5786. }
  5787. bool SourceLineInfo::operator < ( SourceLineInfo const& other ) const noexcept {
  5788. // We can assume that the same file will usually have the same pointer.
  5789. // Thus, if the pointers are the same, there is no point in calling the strcmp
  5790. return line < other.line || ( line == other.line && file != other.file && (std::strcmp(file, other.file) < 0));
  5791. }
  5792. std::ostream& operator << ( std::ostream& os, SourceLineInfo const& info ) {
  5793. #ifndef __GNUG__
  5794. os << info.file << '(' << info.line << ')';
  5795. #else
  5796. os << info.file << ':' << info.line;
  5797. #endif
  5798. return os;
  5799. }
  5800. std::string StreamEndStop::operator+() const {
  5801. return std::string();
  5802. }
  5803. NonCopyable::NonCopyable() = default;
  5804. NonCopyable::~NonCopyable() = default;
  5805. }
  5806. // end catch_common.cpp
  5807. // start catch_config.cpp
  5808. namespace Catch {
  5809. Config::Config( ConfigData const& data )
  5810. : m_data( data ),
  5811. m_stream( openStream() )
  5812. {
  5813. TestSpecParser parser(ITagAliasRegistry::get());
  5814. if (data.testsOrTags.empty()) {
  5815. parser.parse("~[.]"); // All not hidden tests
  5816. }
  5817. else {
  5818. m_hasTestFilters = true;
  5819. for( auto const& testOrTags : data.testsOrTags )
  5820. parser.parse( testOrTags );
  5821. }
  5822. m_testSpec = parser.testSpec();
  5823. }
  5824. std::string const& Config::getFilename() const {
  5825. return m_data.outputFilename ;
  5826. }
  5827. bool Config::listTests() const { return m_data.listTests; }
  5828. bool Config::listTestNamesOnly() const { return m_data.listTestNamesOnly; }
  5829. bool Config::listTags() const { return m_data.listTags; }
  5830. bool Config::listReporters() const { return m_data.listReporters; }
  5831. std::string Config::getProcessName() const { return m_data.processName; }
  5832. std::string const& Config::getReporterName() const { return m_data.reporterName; }
  5833. std::vector<std::string> const& Config::getTestsOrTags() const { return m_data.testsOrTags; }
  5834. std::vector<std::string> const& Config::getSectionsToRun() const { return m_data.sectionsToRun; }
  5835. TestSpec const& Config::testSpec() const { return m_testSpec; }
  5836. bool Config::hasTestFilters() const { return m_hasTestFilters; }
  5837. bool Config::showHelp() const { return m_data.showHelp; }
  5838. // IConfig interface
  5839. bool Config::allowThrows() const { return !m_data.noThrow; }
  5840. std::ostream& Config::stream() const { return m_stream->stream(); }
  5841. std::string Config::name() const { return m_data.name.empty() ? m_data.processName : m_data.name; }
  5842. bool Config::includeSuccessfulResults() const { return m_data.showSuccessfulTests; }
  5843. bool Config::warnAboutMissingAssertions() const { return !!(m_data.warnings & WarnAbout::NoAssertions); }
  5844. bool Config::warnAboutNoTests() const { return !!(m_data.warnings & WarnAbout::NoTests); }
  5845. ShowDurations::OrNot Config::showDurations() const { return m_data.showDurations; }
  5846. RunTests::InWhatOrder Config::runOrder() const { return m_data.runOrder; }
  5847. unsigned int Config::rngSeed() const { return m_data.rngSeed; }
  5848. int Config::benchmarkResolutionMultiple() const { return m_data.benchmarkResolutionMultiple; }
  5849. UseColour::YesOrNo Config::useColour() const { return m_data.useColour; }
  5850. bool Config::shouldDebugBreak() const { return m_data.shouldDebugBreak; }
  5851. int Config::abortAfter() const { return m_data.abortAfter; }
  5852. bool Config::showInvisibles() const { return m_data.showInvisibles; }
  5853. Verbosity Config::verbosity() const { return m_data.verbosity; }
  5854. IStream const* Config::openStream() {
  5855. return Catch::makeStream(m_data.outputFilename);
  5856. }
  5857. } // end namespace Catch
  5858. // end catch_config.cpp
  5859. // start catch_console_colour.cpp
  5860. #if defined(__clang__)
  5861. # pragma clang diagnostic push
  5862. # pragma clang diagnostic ignored "-Wexit-time-destructors"
  5863. #endif
  5864. // start catch_errno_guard.h
  5865. namespace Catch {
  5866. class ErrnoGuard {
  5867. public:
  5868. ErrnoGuard();
  5869. ~ErrnoGuard();
  5870. private:
  5871. int m_oldErrno;
  5872. };
  5873. }
  5874. // end catch_errno_guard.h
  5875. #include <sstream>
  5876. namespace Catch {
  5877. namespace {
  5878. struct IColourImpl {
  5879. virtual ~IColourImpl() = default;
  5880. virtual void use( Colour::Code _colourCode ) = 0;
  5881. };
  5882. struct NoColourImpl : IColourImpl {
  5883. void use( Colour::Code ) {}
  5884. static IColourImpl* instance() {
  5885. static NoColourImpl s_instance;
  5886. return &s_instance;
  5887. }
  5888. };
  5889. } // anon namespace
  5890. } // namespace Catch
  5891. #if !defined( CATCH_CONFIG_COLOUR_NONE ) && !defined( CATCH_CONFIG_COLOUR_WINDOWS ) && !defined( CATCH_CONFIG_COLOUR_ANSI )
  5892. # ifdef CATCH_PLATFORM_WINDOWS
  5893. # define CATCH_CONFIG_COLOUR_WINDOWS
  5894. # else
  5895. # define CATCH_CONFIG_COLOUR_ANSI
  5896. # endif
  5897. #endif
  5898. #if defined ( CATCH_CONFIG_COLOUR_WINDOWS ) /////////////////////////////////////////
  5899. namespace Catch {
  5900. namespace {
  5901. class Win32ColourImpl : public IColourImpl {
  5902. public:
  5903. Win32ColourImpl() : stdoutHandle( GetStdHandle(STD_OUTPUT_HANDLE) )
  5904. {
  5905. CONSOLE_SCREEN_BUFFER_INFO csbiInfo;
  5906. GetConsoleScreenBufferInfo( stdoutHandle, &csbiInfo );
  5907. originalForegroundAttributes = csbiInfo.wAttributes & ~( BACKGROUND_GREEN | BACKGROUND_RED | BACKGROUND_BLUE | BACKGROUND_INTENSITY );
  5908. originalBackgroundAttributes = csbiInfo.wAttributes & ~( FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_BLUE | FOREGROUND_INTENSITY );
  5909. }
  5910. virtual void use( Colour::Code _colourCode ) override {
  5911. switch( _colourCode ) {
  5912. case Colour::None: return setTextAttribute( originalForegroundAttributes );
  5913. case Colour::White: return setTextAttribute( FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_BLUE );
  5914. case Colour::Red: return setTextAttribute( FOREGROUND_RED );
  5915. case Colour::Green: return setTextAttribute( FOREGROUND_GREEN );
  5916. case Colour::Blue: return setTextAttribute( FOREGROUND_BLUE );
  5917. case Colour::Cyan: return setTextAttribute( FOREGROUND_BLUE | FOREGROUND_GREEN );
  5918. case Colour::Yellow: return setTextAttribute( FOREGROUND_RED | FOREGROUND_GREEN );
  5919. case Colour::Grey: return setTextAttribute( 0 );
  5920. case Colour::LightGrey: return setTextAttribute( FOREGROUND_INTENSITY );
  5921. case Colour::BrightRed: return setTextAttribute( FOREGROUND_INTENSITY | FOREGROUND_RED );
  5922. case Colour::BrightGreen: return setTextAttribute( FOREGROUND_INTENSITY | FOREGROUND_GREEN );
  5923. case Colour::BrightWhite: return setTextAttribute( FOREGROUND_INTENSITY | FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_BLUE );
  5924. case Colour::BrightYellow: return setTextAttribute( FOREGROUND_INTENSITY | FOREGROUND_RED | FOREGROUND_GREEN );
  5925. case Colour::Bright: CATCH_INTERNAL_ERROR( "not a colour" );
  5926. default:
  5927. CATCH_ERROR( "Unknown colour requested" );
  5928. }
  5929. }
  5930. private:
  5931. void setTextAttribute( WORD _textAttribute ) {
  5932. SetConsoleTextAttribute( stdoutHandle, _textAttribute | originalBackgroundAttributes );
  5933. }
  5934. HANDLE stdoutHandle;
  5935. WORD originalForegroundAttributes;
  5936. WORD originalBackgroundAttributes;
  5937. };
  5938. IColourImpl* platformColourInstance() {
  5939. static Win32ColourImpl s_instance;
  5940. IConfigPtr config = getCurrentContext().getConfig();
  5941. UseColour::YesOrNo colourMode = config
  5942. ? config->useColour()
  5943. : UseColour::Auto;
  5944. if( colourMode == UseColour::Auto )
  5945. colourMode = UseColour::Yes;
  5946. return colourMode == UseColour::Yes
  5947. ? &s_instance
  5948. : NoColourImpl::instance();
  5949. }
  5950. } // end anon namespace
  5951. } // end namespace Catch
  5952. #elif defined( CATCH_CONFIG_COLOUR_ANSI ) //////////////////////////////////////
  5953. #include <unistd.h>
  5954. namespace Catch {
  5955. namespace {
  5956. // use POSIX/ ANSI console terminal codes
  5957. // Thanks to Adam Strzelecki for original contribution
  5958. // (http://github.com/nanoant)
  5959. // https://github.com/philsquared/Catch/pull/131
  5960. class PosixColourImpl : public IColourImpl {
  5961. public:
  5962. virtual void use( Colour::Code _colourCode ) override {
  5963. switch( _colourCode ) {
  5964. case Colour::None:
  5965. case Colour::White: return setColour( "[0m" );
  5966. case Colour::Red: return setColour( "[0;31m" );
  5967. case Colour::Green: return setColour( "[0;32m" );
  5968. case Colour::Blue: return setColour( "[0;34m" );
  5969. case Colour::Cyan: return setColour( "[0;36m" );
  5970. case Colour::Yellow: return setColour( "[0;33m" );
  5971. case Colour::Grey: return setColour( "[1;30m" );
  5972. case Colour::LightGrey: return setColour( "[0;37m" );
  5973. case Colour::BrightRed: return setColour( "[1;31m" );
  5974. case Colour::BrightGreen: return setColour( "[1;32m" );
  5975. case Colour::BrightWhite: return setColour( "[1;37m" );
  5976. case Colour::BrightYellow: return setColour( "[1;33m" );
  5977. case Colour::Bright: CATCH_INTERNAL_ERROR( "not a colour" );
  5978. default: CATCH_INTERNAL_ERROR( "Unknown colour requested" );
  5979. }
  5980. }
  5981. static IColourImpl* instance() {
  5982. static PosixColourImpl s_instance;
  5983. return &s_instance;
  5984. }
  5985. private:
  5986. void setColour( const char* _escapeCode ) {
  5987. Catch::cout() << '\033' << _escapeCode;
  5988. }
  5989. };
  5990. bool useColourOnPlatform() {
  5991. return
  5992. #ifdef CATCH_PLATFORM_MAC
  5993. !isDebuggerActive() &&
  5994. #endif
  5995. #if !(defined(__DJGPP__) && defined(__STRICT_ANSI__))
  5996. isatty(STDOUT_FILENO)
  5997. #else
  5998. false
  5999. #endif
  6000. ;
  6001. }
  6002. IColourImpl* platformColourInstance() {
  6003. ErrnoGuard guard;
  6004. IConfigPtr config = getCurrentContext().getConfig();
  6005. UseColour::YesOrNo colourMode = config
  6006. ? config->useColour()
  6007. : UseColour::Auto;
  6008. if( colourMode == UseColour::Auto )
  6009. colourMode = useColourOnPlatform()
  6010. ? UseColour::Yes
  6011. : UseColour::No;
  6012. return colourMode == UseColour::Yes
  6013. ? PosixColourImpl::instance()
  6014. : NoColourImpl::instance();
  6015. }
  6016. } // end anon namespace
  6017. } // end namespace Catch
  6018. #else // not Windows or ANSI ///////////////////////////////////////////////
  6019. namespace Catch {
  6020. static IColourImpl* platformColourInstance() { return NoColourImpl::instance(); }
  6021. } // end namespace Catch
  6022. #endif // Windows/ ANSI/ None
  6023. namespace Catch {
  6024. Colour::Colour( Code _colourCode ) { use( _colourCode ); }
  6025. Colour::Colour( Colour&& rhs ) noexcept {
  6026. m_moved = rhs.m_moved;
  6027. rhs.m_moved = true;
  6028. }
  6029. Colour& Colour::operator=( Colour&& rhs ) noexcept {
  6030. m_moved = rhs.m_moved;
  6031. rhs.m_moved = true;
  6032. return *this;
  6033. }
  6034. Colour::~Colour(){ if( !m_moved ) use( None ); }
  6035. void Colour::use( Code _colourCode ) {
  6036. static IColourImpl* impl = platformColourInstance();
  6037. impl->use( _colourCode );
  6038. }
  6039. std::ostream& operator << ( std::ostream& os, Colour const& ) {
  6040. return os;
  6041. }
  6042. } // end namespace Catch
  6043. #if defined(__clang__)
  6044. # pragma clang diagnostic pop
  6045. #endif
  6046. // end catch_console_colour.cpp
  6047. // start catch_context.cpp
  6048. namespace Catch {
  6049. class Context : public IMutableContext, NonCopyable {
  6050. public: // IContext
  6051. virtual IResultCapture* getResultCapture() override {
  6052. return m_resultCapture;
  6053. }
  6054. virtual IRunner* getRunner() override {
  6055. return m_runner;
  6056. }
  6057. virtual IConfigPtr const& getConfig() const override {
  6058. return m_config;
  6059. }
  6060. virtual ~Context() override;
  6061. public: // IMutableContext
  6062. virtual void setResultCapture( IResultCapture* resultCapture ) override {
  6063. m_resultCapture = resultCapture;
  6064. }
  6065. virtual void setRunner( IRunner* runner ) override {
  6066. m_runner = runner;
  6067. }
  6068. virtual void setConfig( IConfigPtr const& config ) override {
  6069. m_config = config;
  6070. }
  6071. friend IMutableContext& getCurrentMutableContext();
  6072. private:
  6073. IConfigPtr m_config;
  6074. IRunner* m_runner = nullptr;
  6075. IResultCapture* m_resultCapture = nullptr;
  6076. };
  6077. IMutableContext *IMutableContext::currentContext = nullptr;
  6078. void IMutableContext::createContext()
  6079. {
  6080. currentContext = new Context();
  6081. }
  6082. void cleanUpContext() {
  6083. delete IMutableContext::currentContext;
  6084. IMutableContext::currentContext = nullptr;
  6085. }
  6086. IContext::~IContext() = default;
  6087. IMutableContext::~IMutableContext() = default;
  6088. Context::~Context() = default;
  6089. }
  6090. // end catch_context.cpp
  6091. // start catch_debug_console.cpp
  6092. // start catch_debug_console.h
  6093. #include <string>
  6094. namespace Catch {
  6095. void writeToDebugConsole( std::string const& text );
  6096. }
  6097. // end catch_debug_console.h
  6098. #ifdef CATCH_PLATFORM_WINDOWS
  6099. namespace Catch {
  6100. void writeToDebugConsole( std::string const& text ) {
  6101. ::OutputDebugStringA( text.c_str() );
  6102. }
  6103. }
  6104. #else
  6105. namespace Catch {
  6106. void writeToDebugConsole( std::string const& text ) {
  6107. // !TBD: Need a version for Mac/ XCode and other IDEs
  6108. Catch::cout() << text;
  6109. }
  6110. }
  6111. #endif // Platform
  6112. // end catch_debug_console.cpp
  6113. // start catch_debugger.cpp
  6114. #ifdef CATCH_PLATFORM_MAC
  6115. # include <assert.h>
  6116. # include <stdbool.h>
  6117. # include <sys/types.h>
  6118. # include <unistd.h>
  6119. # include <sys/sysctl.h>
  6120. # include <cstddef>
  6121. # include <ostream>
  6122. namespace Catch {
  6123. // The following function is taken directly from the following technical note:
  6124. // http://developer.apple.com/library/mac/#qa/qa2004/qa1361.html
  6125. // Returns true if the current process is being debugged (either
  6126. // running under the debugger or has a debugger attached post facto).
  6127. bool isDebuggerActive(){
  6128. int mib[4];
  6129. struct kinfo_proc info;
  6130. std::size_t size;
  6131. // Initialize the flags so that, if sysctl fails for some bizarre
  6132. // reason, we get a predictable result.
  6133. info.kp_proc.p_flag = 0;
  6134. // Initialize mib, which tells sysctl the info we want, in this case
  6135. // we're looking for information about a specific process ID.
  6136. mib[0] = CTL_KERN;
  6137. mib[1] = KERN_PROC;
  6138. mib[2] = KERN_PROC_PID;
  6139. mib[3] = getpid();
  6140. // Call sysctl.
  6141. size = sizeof(info);
  6142. if( sysctl(mib, sizeof(mib) / sizeof(*mib), &info, &size, nullptr, 0) != 0 ) {
  6143. Catch::cerr() << "\n** Call to sysctl failed - unable to determine if debugger is active **\n" << std::endl;
  6144. return false;
  6145. }
  6146. // We're being debugged if the P_TRACED flag is set.
  6147. return ( (info.kp_proc.p_flag & P_TRACED) != 0 );
  6148. }
  6149. } // namespace Catch
  6150. #elif defined(CATCH_PLATFORM_LINUX)
  6151. #include <fstream>
  6152. #include <string>
  6153. namespace Catch{
  6154. // The standard POSIX way of detecting a debugger is to attempt to
  6155. // ptrace() the process, but this needs to be done from a child and not
  6156. // this process itself to still allow attaching to this process later
  6157. // if wanted, so is rather heavy. Under Linux we have the PID of the
  6158. // "debugger" (which doesn't need to be gdb, of course, it could also
  6159. // be strace, for example) in /proc/$PID/status, so just get it from
  6160. // there instead.
  6161. bool isDebuggerActive(){
  6162. // Libstdc++ has a bug, where std::ifstream sets errno to 0
  6163. // This way our users can properly assert over errno values
  6164. ErrnoGuard guard;
  6165. std::ifstream in("/proc/self/status");
  6166. for( std::string line; std::getline(in, line); ) {
  6167. static const int PREFIX_LEN = 11;
  6168. if( line.compare(0, PREFIX_LEN, "TracerPid:\t") == 0 ) {
  6169. // We're traced if the PID is not 0 and no other PID starts
  6170. // with 0 digit, so it's enough to check for just a single
  6171. // character.
  6172. return line.length() > PREFIX_LEN && line[PREFIX_LEN] != '0';
  6173. }
  6174. }
  6175. return false;
  6176. }
  6177. } // namespace Catch
  6178. #elif defined(_MSC_VER)
  6179. extern "C" __declspec(dllimport) int __stdcall IsDebuggerPresent();
  6180. namespace Catch {
  6181. bool isDebuggerActive() {
  6182. return IsDebuggerPresent() != 0;
  6183. }
  6184. }
  6185. #elif defined(__MINGW32__)
  6186. extern "C" __declspec(dllimport) int __stdcall IsDebuggerPresent();
  6187. namespace Catch {
  6188. bool isDebuggerActive() {
  6189. return IsDebuggerPresent() != 0;
  6190. }
  6191. }
  6192. #else
  6193. namespace Catch {
  6194. bool isDebuggerActive() { return false; }
  6195. }
  6196. #endif // Platform
  6197. // end catch_debugger.cpp
  6198. // start catch_decomposer.cpp
  6199. namespace Catch {
  6200. ITransientExpression::~ITransientExpression() = default;
  6201. void formatReconstructedExpression( std::ostream &os, std::string const& lhs, StringRef op, std::string const& rhs ) {
  6202. if( lhs.size() + rhs.size() < 40 &&
  6203. lhs.find('\n') == std::string::npos &&
  6204. rhs.find('\n') == std::string::npos )
  6205. os << lhs << " " << op << " " << rhs;
  6206. else
  6207. os << lhs << "\n" << op << "\n" << rhs;
  6208. }
  6209. }
  6210. // end catch_decomposer.cpp
  6211. // start catch_enforce.cpp
  6212. namespace Catch {
  6213. #if defined(CATCH_CONFIG_DISABLE_EXCEPTIONS) && !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS_CUSTOM_HANDLER)
  6214. [[noreturn]]
  6215. void throw_exception(std::exception const& e) {
  6216. Catch::cerr() << "Catch will terminate because it needed to throw an exception.\n"
  6217. << "The message was: " << e.what() << '\n';
  6218. std::terminate();
  6219. }
  6220. #endif
  6221. } // namespace Catch;
  6222. // end catch_enforce.cpp
  6223. // start catch_errno_guard.cpp
  6224. #include <cerrno>
  6225. namespace Catch {
  6226. ErrnoGuard::ErrnoGuard():m_oldErrno(errno){}
  6227. ErrnoGuard::~ErrnoGuard() { errno = m_oldErrno; }
  6228. }
  6229. // end catch_errno_guard.cpp
  6230. // start catch_exception_translator_registry.cpp
  6231. // start catch_exception_translator_registry.h
  6232. #include <vector>
  6233. #include <string>
  6234. #include <memory>
  6235. namespace Catch {
  6236. class ExceptionTranslatorRegistry : public IExceptionTranslatorRegistry {
  6237. public:
  6238. ~ExceptionTranslatorRegistry();
  6239. virtual void registerTranslator( const IExceptionTranslator* translator );
  6240. virtual std::string translateActiveException() const override;
  6241. std::string tryTranslators() const;
  6242. private:
  6243. std::vector<std::unique_ptr<IExceptionTranslator const>> m_translators;
  6244. };
  6245. }
  6246. // end catch_exception_translator_registry.h
  6247. #ifdef __OBJC__
  6248. #import "Foundation/Foundation.h"
  6249. #endif
  6250. namespace Catch {
  6251. ExceptionTranslatorRegistry::~ExceptionTranslatorRegistry() {
  6252. }
  6253. void ExceptionTranslatorRegistry::registerTranslator( const IExceptionTranslator* translator ) {
  6254. m_translators.push_back( std::unique_ptr<const IExceptionTranslator>( translator ) );
  6255. }
  6256. #if !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
  6257. std::string ExceptionTranslatorRegistry::translateActiveException() const {
  6258. try {
  6259. #ifdef __OBJC__
  6260. // In Objective-C try objective-c exceptions first
  6261. @try {
  6262. return tryTranslators();
  6263. }
  6264. @catch (NSException *exception) {
  6265. return Catch::Detail::stringify( [exception description] );
  6266. }
  6267. #else
  6268. // Compiling a mixed mode project with MSVC means that CLR
  6269. // exceptions will be caught in (...) as well. However, these
  6270. // do not fill-in std::current_exception and thus lead to crash
  6271. // when attempting rethrow.
  6272. // /EHa switch also causes structured exceptions to be caught
  6273. // here, but they fill-in current_exception properly, so
  6274. // at worst the output should be a little weird, instead of
  6275. // causing a crash.
  6276. if (std::current_exception() == nullptr) {
  6277. return "Non C++ exception. Possibly a CLR exception.";
  6278. }
  6279. return tryTranslators();
  6280. #endif
  6281. }
  6282. catch( TestFailureException& ) {
  6283. std::rethrow_exception(std::current_exception());
  6284. }
  6285. catch( std::exception& ex ) {
  6286. return ex.what();
  6287. }
  6288. catch( std::string& msg ) {
  6289. return msg;
  6290. }
  6291. catch( const char* msg ) {
  6292. return msg;
  6293. }
  6294. catch(...) {
  6295. return "Unknown exception";
  6296. }
  6297. }
  6298. #else // ^^ Exceptions are enabled // Exceptions are disabled vv
  6299. std::string ExceptionTranslatorRegistry::translateActiveException() const {
  6300. CATCH_INTERNAL_ERROR("Attempted to translate active exception under CATCH_CONFIG_DISABLE_EXCEPTIONS!");
  6301. }
  6302. #endif
  6303. std::string ExceptionTranslatorRegistry::tryTranslators() const {
  6304. if( m_translators.empty() )
  6305. std::rethrow_exception(std::current_exception());
  6306. else
  6307. return m_translators[0]->translate( m_translators.begin()+1, m_translators.end() );
  6308. }
  6309. }
  6310. // end catch_exception_translator_registry.cpp
  6311. // start catch_fatal_condition.cpp
  6312. #if defined(__GNUC__)
  6313. # pragma GCC diagnostic push
  6314. # pragma GCC diagnostic ignored "-Wmissing-field-initializers"
  6315. #endif
  6316. #if defined( CATCH_CONFIG_WINDOWS_SEH ) || defined( CATCH_CONFIG_POSIX_SIGNALS )
  6317. namespace {
  6318. // Report the error condition
  6319. void reportFatal( char const * const message ) {
  6320. Catch::getCurrentContext().getResultCapture()->handleFatalErrorCondition( message );
  6321. }
  6322. }
  6323. #endif // signals/SEH handling
  6324. #if defined( CATCH_CONFIG_WINDOWS_SEH )
  6325. namespace Catch {
  6326. struct SignalDefs { DWORD id; const char* name; };
  6327. // There is no 1-1 mapping between signals and windows exceptions.
  6328. // Windows can easily distinguish between SO and SigSegV,
  6329. // but SigInt, SigTerm, etc are handled differently.
  6330. static SignalDefs signalDefs[] = {
  6331. { EXCEPTION_ILLEGAL_INSTRUCTION, "SIGILL - Illegal instruction signal" },
  6332. { EXCEPTION_STACK_OVERFLOW, "SIGSEGV - Stack overflow" },
  6333. { EXCEPTION_ACCESS_VIOLATION, "SIGSEGV - Segmentation violation signal" },
  6334. { EXCEPTION_INT_DIVIDE_BY_ZERO, "Divide by zero error" },
  6335. };
  6336. LONG CALLBACK FatalConditionHandler::handleVectoredException(PEXCEPTION_POINTERS ExceptionInfo) {
  6337. for (auto const& def : signalDefs) {
  6338. if (ExceptionInfo->ExceptionRecord->ExceptionCode == def.id) {
  6339. reportFatal(def.name);
  6340. }
  6341. }
  6342. // If its not an exception we care about, pass it along.
  6343. // This stops us from eating debugger breaks etc.
  6344. return EXCEPTION_CONTINUE_SEARCH;
  6345. }
  6346. FatalConditionHandler::FatalConditionHandler() {
  6347. isSet = true;
  6348. // 32k seems enough for Catch to handle stack overflow,
  6349. // but the value was found experimentally, so there is no strong guarantee
  6350. guaranteeSize = 32 * 1024;
  6351. exceptionHandlerHandle = nullptr;
  6352. // Register as first handler in current chain
  6353. exceptionHandlerHandle = AddVectoredExceptionHandler(1, handleVectoredException);
  6354. // Pass in guarantee size to be filled
  6355. SetThreadStackGuarantee(&guaranteeSize);
  6356. }
  6357. void FatalConditionHandler::reset() {
  6358. if (isSet) {
  6359. RemoveVectoredExceptionHandler(exceptionHandlerHandle);
  6360. SetThreadStackGuarantee(&guaranteeSize);
  6361. exceptionHandlerHandle = nullptr;
  6362. isSet = false;
  6363. }
  6364. }
  6365. FatalConditionHandler::~FatalConditionHandler() {
  6366. reset();
  6367. }
  6368. bool FatalConditionHandler::isSet = false;
  6369. ULONG FatalConditionHandler::guaranteeSize = 0;
  6370. PVOID FatalConditionHandler::exceptionHandlerHandle = nullptr;
  6371. } // namespace Catch
  6372. #elif defined( CATCH_CONFIG_POSIX_SIGNALS )
  6373. namespace Catch {
  6374. struct SignalDefs {
  6375. int id;
  6376. const char* name;
  6377. };
  6378. // 32kb for the alternate stack seems to be sufficient. However, this value
  6379. // is experimentally determined, so that's not guaranteed.
  6380. constexpr static std::size_t sigStackSize = 32768 >= MINSIGSTKSZ ? 32768 : MINSIGSTKSZ;
  6381. static SignalDefs signalDefs[] = {
  6382. { SIGINT, "SIGINT - Terminal interrupt signal" },
  6383. { SIGILL, "SIGILL - Illegal instruction signal" },
  6384. { SIGFPE, "SIGFPE - Floating point error signal" },
  6385. { SIGSEGV, "SIGSEGV - Segmentation violation signal" },
  6386. { SIGTERM, "SIGTERM - Termination request signal" },
  6387. { SIGABRT, "SIGABRT - Abort (abnormal termination) signal" }
  6388. };
  6389. void FatalConditionHandler::handleSignal( int sig ) {
  6390. char const * name = "<unknown signal>";
  6391. for (auto const& def : signalDefs) {
  6392. if (sig == def.id) {
  6393. name = def.name;
  6394. break;
  6395. }
  6396. }
  6397. reset();
  6398. reportFatal(name);
  6399. raise( sig );
  6400. }
  6401. FatalConditionHandler::FatalConditionHandler() {
  6402. isSet = true;
  6403. stack_t sigStack;
  6404. sigStack.ss_sp = altStackMem;
  6405. sigStack.ss_size = sigStackSize;
  6406. sigStack.ss_flags = 0;
  6407. sigaltstack(&sigStack, &oldSigStack);
  6408. struct sigaction sa = { };
  6409. sa.sa_handler = handleSignal;
  6410. sa.sa_flags = SA_ONSTACK;
  6411. for (std::size_t i = 0; i < sizeof(signalDefs)/sizeof(SignalDefs); ++i) {
  6412. sigaction(signalDefs[i].id, &sa, &oldSigActions[i]);
  6413. }
  6414. }
  6415. FatalConditionHandler::~FatalConditionHandler() {
  6416. reset();
  6417. }
  6418. void FatalConditionHandler::reset() {
  6419. if( isSet ) {
  6420. // Set signals back to previous values -- hopefully nobody overwrote them in the meantime
  6421. for( std::size_t i = 0; i < sizeof(signalDefs)/sizeof(SignalDefs); ++i ) {
  6422. sigaction(signalDefs[i].id, &oldSigActions[i], nullptr);
  6423. }
  6424. // Return the old stack
  6425. sigaltstack(&oldSigStack, nullptr);
  6426. isSet = false;
  6427. }
  6428. }
  6429. bool FatalConditionHandler::isSet = false;
  6430. struct sigaction FatalConditionHandler::oldSigActions[sizeof(signalDefs)/sizeof(SignalDefs)] = {};
  6431. stack_t FatalConditionHandler::oldSigStack = {};
  6432. char FatalConditionHandler::altStackMem[sigStackSize] = {};
  6433. } // namespace Catch
  6434. #else
  6435. namespace Catch {
  6436. void FatalConditionHandler::reset() {}
  6437. }
  6438. #endif // signals/SEH handling
  6439. #if defined(__GNUC__)
  6440. # pragma GCC diagnostic pop
  6441. #endif
  6442. // end catch_fatal_condition.cpp
  6443. // start catch_generators.cpp
  6444. // start catch_random_number_generator.h
  6445. #include <algorithm>
  6446. #include <random>
  6447. namespace Catch {
  6448. struct IConfig;
  6449. std::mt19937& rng();
  6450. void seedRng( IConfig const& config );
  6451. unsigned int rngSeed();
  6452. }
  6453. // end catch_random_number_generator.h
  6454. #include <limits>
  6455. #include <set>
  6456. namespace Catch {
  6457. IGeneratorTracker::~IGeneratorTracker() {}
  6458. namespace Generators {
  6459. GeneratorBase::~GeneratorBase() {}
  6460. std::vector<size_t> randomiseIndices( size_t selectionSize, size_t sourceSize ) {
  6461. assert( selectionSize <= sourceSize );
  6462. std::vector<size_t> indices;
  6463. indices.reserve( selectionSize );
  6464. std::uniform_int_distribution<size_t> uid( 0, sourceSize-1 );
  6465. std::set<size_t> seen;
  6466. // !TBD: improve this algorithm
  6467. while( indices.size() < selectionSize ) {
  6468. auto index = uid( rng() );
  6469. if( seen.insert( index ).second )
  6470. indices.push_back( index );
  6471. }
  6472. return indices;
  6473. }
  6474. auto acquireGeneratorTracker( SourceLineInfo const& lineInfo ) -> IGeneratorTracker& {
  6475. return getResultCapture().acquireGeneratorTracker( lineInfo );
  6476. }
  6477. template<>
  6478. auto all<int>() -> Generator<int> {
  6479. return range( std::numeric_limits<int>::min(), std::numeric_limits<int>::max() );
  6480. }
  6481. } // namespace Generators
  6482. } // namespace Catch
  6483. // end catch_generators.cpp
  6484. // start catch_interfaces_capture.cpp
  6485. namespace Catch {
  6486. IResultCapture::~IResultCapture() = default;
  6487. }
  6488. // end catch_interfaces_capture.cpp
  6489. // start catch_interfaces_config.cpp
  6490. namespace Catch {
  6491. IConfig::~IConfig() = default;
  6492. }
  6493. // end catch_interfaces_config.cpp
  6494. // start catch_interfaces_exception.cpp
  6495. namespace Catch {
  6496. IExceptionTranslator::~IExceptionTranslator() = default;
  6497. IExceptionTranslatorRegistry::~IExceptionTranslatorRegistry() = default;
  6498. }
  6499. // end catch_interfaces_exception.cpp
  6500. // start catch_interfaces_registry_hub.cpp
  6501. namespace Catch {
  6502. IRegistryHub::~IRegistryHub() = default;
  6503. IMutableRegistryHub::~IMutableRegistryHub() = default;
  6504. }
  6505. // end catch_interfaces_registry_hub.cpp
  6506. // start catch_interfaces_reporter.cpp
  6507. // start catch_reporter_listening.h
  6508. namespace Catch {
  6509. class ListeningReporter : public IStreamingReporter {
  6510. using Reporters = std::vector<IStreamingReporterPtr>;
  6511. Reporters m_listeners;
  6512. IStreamingReporterPtr m_reporter = nullptr;
  6513. ReporterPreferences m_preferences;
  6514. public:
  6515. ListeningReporter();
  6516. void addListener( IStreamingReporterPtr&& listener );
  6517. void addReporter( IStreamingReporterPtr&& reporter );
  6518. public: // IStreamingReporter
  6519. ReporterPreferences getPreferences() const override;
  6520. void noMatchingTestCases( std::string const& spec ) override;
  6521. static std::set<Verbosity> getSupportedVerbosities();
  6522. void benchmarkStarting( BenchmarkInfo const& benchmarkInfo ) override;
  6523. void benchmarkEnded( BenchmarkStats const& benchmarkStats ) override;
  6524. void testRunStarting( TestRunInfo const& testRunInfo ) override;
  6525. void testGroupStarting( GroupInfo const& groupInfo ) override;
  6526. void testCaseStarting( TestCaseInfo const& testInfo ) override;
  6527. void sectionStarting( SectionInfo const& sectionInfo ) override;
  6528. void assertionStarting( AssertionInfo const& assertionInfo ) override;
  6529. // The return value indicates if the messages buffer should be cleared:
  6530. bool assertionEnded( AssertionStats const& assertionStats ) override;
  6531. void sectionEnded( SectionStats const& sectionStats ) override;
  6532. void testCaseEnded( TestCaseStats const& testCaseStats ) override;
  6533. void testGroupEnded( TestGroupStats const& testGroupStats ) override;
  6534. void testRunEnded( TestRunStats const& testRunStats ) override;
  6535. void skipTest( TestCaseInfo const& testInfo ) override;
  6536. bool isMulti() const override;
  6537. };
  6538. } // end namespace Catch
  6539. // end catch_reporter_listening.h
  6540. namespace Catch {
  6541. ReporterConfig::ReporterConfig( IConfigPtr const& _fullConfig )
  6542. : m_stream( &_fullConfig->stream() ), m_fullConfig( _fullConfig ) {}
  6543. ReporterConfig::ReporterConfig( IConfigPtr const& _fullConfig, std::ostream& _stream )
  6544. : m_stream( &_stream ), m_fullConfig( _fullConfig ) {}
  6545. std::ostream& ReporterConfig::stream() const { return *m_stream; }
  6546. IConfigPtr ReporterConfig::fullConfig() const { return m_fullConfig; }
  6547. TestRunInfo::TestRunInfo( std::string const& _name ) : name( _name ) {}
  6548. GroupInfo::GroupInfo( std::string const& _name,
  6549. std::size_t _groupIndex,
  6550. std::size_t _groupsCount )
  6551. : name( _name ),
  6552. groupIndex( _groupIndex ),
  6553. groupsCounts( _groupsCount )
  6554. {}
  6555. AssertionStats::AssertionStats( AssertionResult const& _assertionResult,
  6556. std::vector<MessageInfo> const& _infoMessages,
  6557. Totals const& _totals )
  6558. : assertionResult( _assertionResult ),
  6559. infoMessages( _infoMessages ),
  6560. totals( _totals )
  6561. {
  6562. assertionResult.m_resultData.lazyExpression.m_transientExpression = _assertionResult.m_resultData.lazyExpression.m_transientExpression;
  6563. if( assertionResult.hasMessage() ) {
  6564. // Copy message into messages list.
  6565. // !TBD This should have been done earlier, somewhere
  6566. MessageBuilder builder( assertionResult.getTestMacroName(), assertionResult.getSourceInfo(), assertionResult.getResultType() );
  6567. builder << assertionResult.getMessage();
  6568. builder.m_info.message = builder.m_stream.str();
  6569. infoMessages.push_back( builder.m_info );
  6570. }
  6571. }
  6572. AssertionStats::~AssertionStats() = default;
  6573. SectionStats::SectionStats( SectionInfo const& _sectionInfo,
  6574. Counts const& _assertions,
  6575. double _durationInSeconds,
  6576. bool _missingAssertions )
  6577. : sectionInfo( _sectionInfo ),
  6578. assertions( _assertions ),
  6579. durationInSeconds( _durationInSeconds ),
  6580. missingAssertions( _missingAssertions )
  6581. {}
  6582. SectionStats::~SectionStats() = default;
  6583. TestCaseStats::TestCaseStats( TestCaseInfo const& _testInfo,
  6584. Totals const& _totals,
  6585. std::string const& _stdOut,
  6586. std::string const& _stdErr,
  6587. bool _aborting )
  6588. : testInfo( _testInfo ),
  6589. totals( _totals ),
  6590. stdOut( _stdOut ),
  6591. stdErr( _stdErr ),
  6592. aborting( _aborting )
  6593. {}
  6594. TestCaseStats::~TestCaseStats() = default;
  6595. TestGroupStats::TestGroupStats( GroupInfo const& _groupInfo,
  6596. Totals const& _totals,
  6597. bool _aborting )
  6598. : groupInfo( _groupInfo ),
  6599. totals( _totals ),
  6600. aborting( _aborting )
  6601. {}
  6602. TestGroupStats::TestGroupStats( GroupInfo const& _groupInfo )
  6603. : groupInfo( _groupInfo ),
  6604. aborting( false )
  6605. {}
  6606. TestGroupStats::~TestGroupStats() = default;
  6607. TestRunStats::TestRunStats( TestRunInfo const& _runInfo,
  6608. Totals const& _totals,
  6609. bool _aborting )
  6610. : runInfo( _runInfo ),
  6611. totals( _totals ),
  6612. aborting( _aborting )
  6613. {}
  6614. TestRunStats::~TestRunStats() = default;
  6615. void IStreamingReporter::fatalErrorEncountered( StringRef ) {}
  6616. bool IStreamingReporter::isMulti() const { return false; }
  6617. IReporterFactory::~IReporterFactory() = default;
  6618. IReporterRegistry::~IReporterRegistry() = default;
  6619. } // end namespace Catch
  6620. // end catch_interfaces_reporter.cpp
  6621. // start catch_interfaces_runner.cpp
  6622. namespace Catch {
  6623. IRunner::~IRunner() = default;
  6624. }
  6625. // end catch_interfaces_runner.cpp
  6626. // start catch_interfaces_testcase.cpp
  6627. namespace Catch {
  6628. ITestInvoker::~ITestInvoker() = default;
  6629. ITestCaseRegistry::~ITestCaseRegistry() = default;
  6630. }
  6631. // end catch_interfaces_testcase.cpp
  6632. // start catch_leak_detector.cpp
  6633. #ifdef CATCH_CONFIG_WINDOWS_CRTDBG
  6634. #include <crtdbg.h>
  6635. namespace Catch {
  6636. LeakDetector::LeakDetector() {
  6637. int flag = _CrtSetDbgFlag(_CRTDBG_REPORT_FLAG);
  6638. flag |= _CRTDBG_LEAK_CHECK_DF;
  6639. flag |= _CRTDBG_ALLOC_MEM_DF;
  6640. _CrtSetDbgFlag(flag);
  6641. _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE | _CRTDBG_MODE_DEBUG);
  6642. _CrtSetReportFile(_CRT_WARN, _CRTDBG_FILE_STDERR);
  6643. // Change this to leaking allocation's number to break there
  6644. _CrtSetBreakAlloc(-1);
  6645. }
  6646. }
  6647. #else
  6648. Catch::LeakDetector::LeakDetector() {}
  6649. #endif
  6650. // end catch_leak_detector.cpp
  6651. // start catch_list.cpp
  6652. // start catch_list.h
  6653. #include <set>
  6654. namespace Catch {
  6655. std::size_t listTests( Config const& config );
  6656. std::size_t listTestsNamesOnly( Config const& config );
  6657. struct TagInfo {
  6658. void add( std::string const& spelling );
  6659. std::string all() const;
  6660. std::set<std::string> spellings;
  6661. std::size_t count = 0;
  6662. };
  6663. std::size_t listTags( Config const& config );
  6664. std::size_t listReporters( Config const& /*config*/ );
  6665. Option<std::size_t> list( Config const& config );
  6666. } // end namespace Catch
  6667. // end catch_list.h
  6668. // start catch_text.h
  6669. namespace Catch {
  6670. using namespace clara::TextFlow;
  6671. }
  6672. // end catch_text.h
  6673. #include <limits>
  6674. #include <algorithm>
  6675. #include <iomanip>
  6676. namespace Catch {
  6677. std::size_t listTests( Config const& config ) {
  6678. TestSpec testSpec = config.testSpec();
  6679. if( config.hasTestFilters() )
  6680. Catch::cout() << "Matching test cases:\n";
  6681. else {
  6682. Catch::cout() << "All available test cases:\n";
  6683. }
  6684. auto matchedTestCases = filterTests( getAllTestCasesSorted( config ), testSpec, config );
  6685. for( auto const& testCaseInfo : matchedTestCases ) {
  6686. Colour::Code colour = testCaseInfo.isHidden()
  6687. ? Colour::SecondaryText
  6688. : Colour::None;
  6689. Colour colourGuard( colour );
  6690. Catch::cout() << Column( testCaseInfo.name ).initialIndent( 2 ).indent( 4 ) << "\n";
  6691. if( config.verbosity() >= Verbosity::High ) {
  6692. Catch::cout() << Column( Catch::Detail::stringify( testCaseInfo.lineInfo ) ).indent(4) << std::endl;
  6693. std::string description = testCaseInfo.description;
  6694. if( description.empty() )
  6695. description = "(NO DESCRIPTION)";
  6696. Catch::cout() << Column( description ).indent(4) << std::endl;
  6697. }
  6698. if( !testCaseInfo.tags.empty() )
  6699. Catch::cout() << Column( testCaseInfo.tagsAsString() ).indent( 6 ) << "\n";
  6700. }
  6701. if( !config.hasTestFilters() )
  6702. Catch::cout() << pluralise( matchedTestCases.size(), "test case" ) << '\n' << std::endl;
  6703. else
  6704. Catch::cout() << pluralise( matchedTestCases.size(), "matching test case" ) << '\n' << std::endl;
  6705. return matchedTestCases.size();
  6706. }
  6707. std::size_t listTestsNamesOnly( Config const& config ) {
  6708. TestSpec testSpec = config.testSpec();
  6709. std::size_t matchedTests = 0;
  6710. std::vector<TestCase> matchedTestCases = filterTests( getAllTestCasesSorted( config ), testSpec, config );
  6711. for( auto const& testCaseInfo : matchedTestCases ) {
  6712. matchedTests++;
  6713. if( startsWith( testCaseInfo.name, '#' ) )
  6714. Catch::cout() << '"' << testCaseInfo.name << '"';
  6715. else
  6716. Catch::cout() << testCaseInfo.name;
  6717. if ( config.verbosity() >= Verbosity::High )
  6718. Catch::cout() << "\t@" << testCaseInfo.lineInfo;
  6719. Catch::cout() << std::endl;
  6720. }
  6721. return matchedTests;
  6722. }
  6723. void TagInfo::add( std::string const& spelling ) {
  6724. ++count;
  6725. spellings.insert( spelling );
  6726. }
  6727. std::string TagInfo::all() const {
  6728. std::string out;
  6729. for( auto const& spelling : spellings )
  6730. out += "[" + spelling + "]";
  6731. return out;
  6732. }
  6733. std::size_t listTags( Config const& config ) {
  6734. TestSpec testSpec = config.testSpec();
  6735. if( config.hasTestFilters() )
  6736. Catch::cout() << "Tags for matching test cases:\n";
  6737. else {
  6738. Catch::cout() << "All available tags:\n";
  6739. }
  6740. std::map<std::string, TagInfo> tagCounts;
  6741. std::vector<TestCase> matchedTestCases = filterTests( getAllTestCasesSorted( config ), testSpec, config );
  6742. for( auto const& testCase : matchedTestCases ) {
  6743. for( auto const& tagName : testCase.getTestCaseInfo().tags ) {
  6744. std::string lcaseTagName = toLower( tagName );
  6745. auto countIt = tagCounts.find( lcaseTagName );
  6746. if( countIt == tagCounts.end() )
  6747. countIt = tagCounts.insert( std::make_pair( lcaseTagName, TagInfo() ) ).first;
  6748. countIt->second.add( tagName );
  6749. }
  6750. }
  6751. for( auto const& tagCount : tagCounts ) {
  6752. ReusableStringStream rss;
  6753. rss << " " << std::setw(2) << tagCount.second.count << " ";
  6754. auto str = rss.str();
  6755. auto wrapper = Column( tagCount.second.all() )
  6756. .initialIndent( 0 )
  6757. .indent( str.size() )
  6758. .width( CATCH_CONFIG_CONSOLE_WIDTH-10 );
  6759. Catch::cout() << str << wrapper << '\n';
  6760. }
  6761. Catch::cout() << pluralise( tagCounts.size(), "tag" ) << '\n' << std::endl;
  6762. return tagCounts.size();
  6763. }
  6764. std::size_t listReporters( Config const& /*config*/ ) {
  6765. Catch::cout() << "Available reporters:\n";
  6766. IReporterRegistry::FactoryMap const& factories = getRegistryHub().getReporterRegistry().getFactories();
  6767. std::size_t maxNameLen = 0;
  6768. for( auto const& factoryKvp : factories )
  6769. maxNameLen = (std::max)( maxNameLen, factoryKvp.first.size() );
  6770. for( auto const& factoryKvp : factories ) {
  6771. Catch::cout()
  6772. << Column( factoryKvp.first + ":" )
  6773. .indent(2)
  6774. .width( 5+maxNameLen )
  6775. + Column( factoryKvp.second->getDescription() )
  6776. .initialIndent(0)
  6777. .indent(2)
  6778. .width( CATCH_CONFIG_CONSOLE_WIDTH - maxNameLen-8 )
  6779. << "\n";
  6780. }
  6781. Catch::cout() << std::endl;
  6782. return factories.size();
  6783. }
  6784. Option<std::size_t> list( Config const& config ) {
  6785. Option<std::size_t> listedCount;
  6786. if( config.listTests() )
  6787. listedCount = listedCount.valueOr(0) + listTests( config );
  6788. if( config.listTestNamesOnly() )
  6789. listedCount = listedCount.valueOr(0) + listTestsNamesOnly( config );
  6790. if( config.listTags() )
  6791. listedCount = listedCount.valueOr(0) + listTags( config );
  6792. if( config.listReporters() )
  6793. listedCount = listedCount.valueOr(0) + listReporters( config );
  6794. return listedCount;
  6795. }
  6796. } // end namespace Catch
  6797. // end catch_list.cpp
  6798. // start catch_matchers.cpp
  6799. namespace Catch {
  6800. namespace Matchers {
  6801. namespace Impl {
  6802. std::string MatcherUntypedBase::toString() const {
  6803. if( m_cachedToString.empty() )
  6804. m_cachedToString = describe();
  6805. return m_cachedToString;
  6806. }
  6807. MatcherUntypedBase::~MatcherUntypedBase() = default;
  6808. } // namespace Impl
  6809. } // namespace Matchers
  6810. using namespace Matchers;
  6811. using Matchers::Impl::MatcherBase;
  6812. } // namespace Catch
  6813. // end catch_matchers.cpp
  6814. // start catch_matchers_floating.cpp
  6815. // start catch_to_string.hpp
  6816. #include <string>
  6817. namespace Catch {
  6818. template <typename T>
  6819. std::string to_string(T const& t) {
  6820. #if defined(CATCH_CONFIG_CPP11_TO_STRING)
  6821. return std::to_string(t);
  6822. #else
  6823. ReusableStringStream rss;
  6824. rss << t;
  6825. return rss.str();
  6826. #endif
  6827. }
  6828. } // end namespace Catch
  6829. // end catch_to_string.hpp
  6830. #include <cstdlib>
  6831. #include <cstdint>
  6832. #include <cstring>
  6833. namespace Catch {
  6834. namespace Matchers {
  6835. namespace Floating {
  6836. enum class FloatingPointKind : uint8_t {
  6837. Float,
  6838. Double
  6839. };
  6840. }
  6841. }
  6842. }
  6843. namespace {
  6844. template <typename T>
  6845. struct Converter;
  6846. template <>
  6847. struct Converter<float> {
  6848. static_assert(sizeof(float) == sizeof(int32_t), "Important ULP matcher assumption violated");
  6849. Converter(float f) {
  6850. std::memcpy(&i, &f, sizeof(f));
  6851. }
  6852. int32_t i;
  6853. };
  6854. template <>
  6855. struct Converter<double> {
  6856. static_assert(sizeof(double) == sizeof(int64_t), "Important ULP matcher assumption violated");
  6857. Converter(double d) {
  6858. std::memcpy(&i, &d, sizeof(d));
  6859. }
  6860. int64_t i;
  6861. };
  6862. template <typename T>
  6863. auto convert(T t) -> Converter<T> {
  6864. return Converter<T>(t);
  6865. }
  6866. template <typename FP>
  6867. bool almostEqualUlps(FP lhs, FP rhs, int maxUlpDiff) {
  6868. // Comparison with NaN should always be false.
  6869. // This way we can rule it out before getting into the ugly details
  6870. if (std::isnan(lhs) || std::isnan(rhs)) {
  6871. return false;
  6872. }
  6873. auto lc = convert(lhs);
  6874. auto rc = convert(rhs);
  6875. if ((lc.i < 0) != (rc.i < 0)) {
  6876. // Potentially we can have +0 and -0
  6877. return lhs == rhs;
  6878. }
  6879. auto ulpDiff = std::abs(lc.i - rc.i);
  6880. return ulpDiff <= maxUlpDiff;
  6881. }
  6882. }
  6883. namespace Catch {
  6884. namespace Matchers {
  6885. namespace Floating {
  6886. WithinAbsMatcher::WithinAbsMatcher(double target, double margin)
  6887. :m_target{ target }, m_margin{ margin } {
  6888. CATCH_ENFORCE(margin >= 0, "Invalid margin: " << margin << '.'
  6889. << " Margin has to be non-negative.");
  6890. }
  6891. // Performs equivalent check of std::fabs(lhs - rhs) <= margin
  6892. // But without the subtraction to allow for INFINITY in comparison
  6893. bool WithinAbsMatcher::match(double const& matchee) const {
  6894. return (matchee + m_margin >= m_target) && (m_target + m_margin >= matchee);
  6895. }
  6896. std::string WithinAbsMatcher::describe() const {
  6897. return "is within " + ::Catch::Detail::stringify(m_margin) + " of " + ::Catch::Detail::stringify(m_target);
  6898. }
  6899. WithinUlpsMatcher::WithinUlpsMatcher(double target, int ulps, FloatingPointKind baseType)
  6900. :m_target{ target }, m_ulps{ ulps }, m_type{ baseType } {
  6901. CATCH_ENFORCE(ulps >= 0, "Invalid ULP setting: " << ulps << '.'
  6902. << " ULPs have to be non-negative.");
  6903. }
  6904. #if defined(__clang__)
  6905. #pragma clang diagnostic push
  6906. // Clang <3.5 reports on the default branch in the switch below
  6907. #pragma clang diagnostic ignored "-Wunreachable-code"
  6908. #endif
  6909. bool WithinUlpsMatcher::match(double const& matchee) const {
  6910. switch (m_type) {
  6911. case FloatingPointKind::Float:
  6912. return almostEqualUlps<float>(static_cast<float>(matchee), static_cast<float>(m_target), m_ulps);
  6913. case FloatingPointKind::Double:
  6914. return almostEqualUlps<double>(matchee, m_target, m_ulps);
  6915. default:
  6916. CATCH_INTERNAL_ERROR( "Unknown FloatingPointKind value" );
  6917. }
  6918. }
  6919. #if defined(__clang__)
  6920. #pragma clang diagnostic pop
  6921. #endif
  6922. std::string WithinUlpsMatcher::describe() const {
  6923. return "is within " + Catch::to_string(m_ulps) + " ULPs of " + ::Catch::Detail::stringify(m_target) + ((m_type == FloatingPointKind::Float)? "f" : "");
  6924. }
  6925. }// namespace Floating
  6926. Floating::WithinUlpsMatcher WithinULP(double target, int maxUlpDiff) {
  6927. return Floating::WithinUlpsMatcher(target, maxUlpDiff, Floating::FloatingPointKind::Double);
  6928. }
  6929. Floating::WithinUlpsMatcher WithinULP(float target, int maxUlpDiff) {
  6930. return Floating::WithinUlpsMatcher(target, maxUlpDiff, Floating::FloatingPointKind::Float);
  6931. }
  6932. Floating::WithinAbsMatcher WithinAbs(double target, double margin) {
  6933. return Floating::WithinAbsMatcher(target, margin);
  6934. }
  6935. } // namespace Matchers
  6936. } // namespace Catch
  6937. // end catch_matchers_floating.cpp
  6938. // start catch_matchers_generic.cpp
  6939. std::string Catch::Matchers::Generic::Detail::finalizeDescription(const std::string& desc) {
  6940. if (desc.empty()) {
  6941. return "matches undescribed predicate";
  6942. } else {
  6943. return "matches predicate: \"" + desc + '"';
  6944. }
  6945. }
  6946. // end catch_matchers_generic.cpp
  6947. // start catch_matchers_string.cpp
  6948. #include <regex>
  6949. namespace Catch {
  6950. namespace Matchers {
  6951. namespace StdString {
  6952. CasedString::CasedString( std::string const& str, CaseSensitive::Choice caseSensitivity )
  6953. : m_caseSensitivity( caseSensitivity ),
  6954. m_str( adjustString( str ) )
  6955. {}
  6956. std::string CasedString::adjustString( std::string const& str ) const {
  6957. return m_caseSensitivity == CaseSensitive::No
  6958. ? toLower( str )
  6959. : str;
  6960. }
  6961. std::string CasedString::caseSensitivitySuffix() const {
  6962. return m_caseSensitivity == CaseSensitive::No
  6963. ? " (case insensitive)"
  6964. : std::string();
  6965. }
  6966. StringMatcherBase::StringMatcherBase( std::string const& operation, CasedString const& comparator )
  6967. : m_comparator( comparator ),
  6968. m_operation( operation ) {
  6969. }
  6970. std::string StringMatcherBase::describe() const {
  6971. std::string description;
  6972. description.reserve(5 + m_operation.size() + m_comparator.m_str.size() +
  6973. m_comparator.caseSensitivitySuffix().size());
  6974. description += m_operation;
  6975. description += ": \"";
  6976. description += m_comparator.m_str;
  6977. description += "\"";
  6978. description += m_comparator.caseSensitivitySuffix();
  6979. return description;
  6980. }
  6981. EqualsMatcher::EqualsMatcher( CasedString const& comparator ) : StringMatcherBase( "equals", comparator ) {}
  6982. bool EqualsMatcher::match( std::string const& source ) const {
  6983. return m_comparator.adjustString( source ) == m_comparator.m_str;
  6984. }
  6985. ContainsMatcher::ContainsMatcher( CasedString const& comparator ) : StringMatcherBase( "contains", comparator ) {}
  6986. bool ContainsMatcher::match( std::string const& source ) const {
  6987. return contains( m_comparator.adjustString( source ), m_comparator.m_str );
  6988. }
  6989. StartsWithMatcher::StartsWithMatcher( CasedString const& comparator ) : StringMatcherBase( "starts with", comparator ) {}
  6990. bool StartsWithMatcher::match( std::string const& source ) const {
  6991. return startsWith( m_comparator.adjustString( source ), m_comparator.m_str );
  6992. }
  6993. EndsWithMatcher::EndsWithMatcher( CasedString const& comparator ) : StringMatcherBase( "ends with", comparator ) {}
  6994. bool EndsWithMatcher::match( std::string const& source ) const {
  6995. return endsWith( m_comparator.adjustString( source ), m_comparator.m_str );
  6996. }
  6997. RegexMatcher::RegexMatcher(std::string regex, CaseSensitive::Choice caseSensitivity): m_regex(std::move(regex)), m_caseSensitivity(caseSensitivity) {}
  6998. bool RegexMatcher::match(std::string const& matchee) const {
  6999. auto flags = std::regex::ECMAScript; // ECMAScript is the default syntax option anyway
  7000. if (m_caseSensitivity == CaseSensitive::Choice::No) {
  7001. flags |= std::regex::icase;
  7002. }
  7003. auto reg = std::regex(m_regex, flags);
  7004. return std::regex_match(matchee, reg);
  7005. }
  7006. std::string RegexMatcher::describe() const {
  7007. return "matches " + ::Catch::Detail::stringify(m_regex) + ((m_caseSensitivity == CaseSensitive::Choice::Yes)? " case sensitively" : " case insensitively");
  7008. }
  7009. } // namespace StdString
  7010. StdString::EqualsMatcher Equals( std::string const& str, CaseSensitive::Choice caseSensitivity ) {
  7011. return StdString::EqualsMatcher( StdString::CasedString( str, caseSensitivity) );
  7012. }
  7013. StdString::ContainsMatcher Contains( std::string const& str, CaseSensitive::Choice caseSensitivity ) {
  7014. return StdString::ContainsMatcher( StdString::CasedString( str, caseSensitivity) );
  7015. }
  7016. StdString::EndsWithMatcher EndsWith( std::string const& str, CaseSensitive::Choice caseSensitivity ) {
  7017. return StdString::EndsWithMatcher( StdString::CasedString( str, caseSensitivity) );
  7018. }
  7019. StdString::StartsWithMatcher StartsWith( std::string const& str, CaseSensitive::Choice caseSensitivity ) {
  7020. return StdString::StartsWithMatcher( StdString::CasedString( str, caseSensitivity) );
  7021. }
  7022. StdString::RegexMatcher Matches(std::string const& regex, CaseSensitive::Choice caseSensitivity) {
  7023. return StdString::RegexMatcher(regex, caseSensitivity);
  7024. }
  7025. } // namespace Matchers
  7026. } // namespace Catch
  7027. // end catch_matchers_string.cpp
  7028. // start catch_message.cpp
  7029. // start catch_uncaught_exceptions.h
  7030. namespace Catch {
  7031. bool uncaught_exceptions();
  7032. } // end namespace Catch
  7033. // end catch_uncaught_exceptions.h
  7034. #include <cassert>
  7035. namespace Catch {
  7036. MessageInfo::MessageInfo( StringRef const& _macroName,
  7037. SourceLineInfo const& _lineInfo,
  7038. ResultWas::OfType _type )
  7039. : macroName( _macroName ),
  7040. lineInfo( _lineInfo ),
  7041. type( _type ),
  7042. sequence( ++globalCount )
  7043. {}
  7044. bool MessageInfo::operator==( MessageInfo const& other ) const {
  7045. return sequence == other.sequence;
  7046. }
  7047. bool MessageInfo::operator<( MessageInfo const& other ) const {
  7048. return sequence < other.sequence;
  7049. }
  7050. // This may need protecting if threading support is added
  7051. unsigned int MessageInfo::globalCount = 0;
  7052. ////////////////////////////////////////////////////////////////////////////
  7053. Catch::MessageBuilder::MessageBuilder( StringRef const& macroName,
  7054. SourceLineInfo const& lineInfo,
  7055. ResultWas::OfType type )
  7056. :m_info(macroName, lineInfo, type) {}
  7057. ////////////////////////////////////////////////////////////////////////////
  7058. ScopedMessage::ScopedMessage( MessageBuilder const& builder )
  7059. : m_info( builder.m_info )
  7060. {
  7061. m_info.message = builder.m_stream.str();
  7062. getResultCapture().pushScopedMessage( m_info );
  7063. }
  7064. ScopedMessage::~ScopedMessage() {
  7065. if ( !uncaught_exceptions() ){
  7066. getResultCapture().popScopedMessage(m_info);
  7067. }
  7068. }
  7069. Capturer::Capturer( StringRef macroName, SourceLineInfo const& lineInfo, ResultWas::OfType resultType, StringRef names ) {
  7070. auto start = std::string::npos;
  7071. for( size_t pos = 0; pos <= names.size(); ++pos ) {
  7072. char c = names[pos];
  7073. if( pos == names.size() || c == ' ' || c == '\t' || c == ',' || c == ']' ) {
  7074. if( start != std::string::npos ) {
  7075. m_messages.push_back( MessageInfo( macroName, lineInfo, resultType ) );
  7076. m_messages.back().message = names.substr( start, pos-start) + " := ";
  7077. start = std::string::npos;
  7078. }
  7079. }
  7080. else if( c != '[' && c != ']' && start == std::string::npos )
  7081. start = pos;
  7082. }
  7083. }
  7084. Capturer::~Capturer() {
  7085. if ( !uncaught_exceptions() ){
  7086. assert( m_captured == m_messages.size() );
  7087. for( size_t i = 0; i < m_captured; ++i )
  7088. m_resultCapture.popScopedMessage( m_messages[i] );
  7089. }
  7090. }
  7091. void Capturer::captureValue( size_t index, StringRef value ) {
  7092. assert( index < m_messages.size() );
  7093. m_messages[index].message += value;
  7094. m_resultCapture.pushScopedMessage( m_messages[index] );
  7095. m_captured++;
  7096. }
  7097. } // end namespace Catch
  7098. // end catch_message.cpp
  7099. // start catch_output_redirect.cpp
  7100. // start catch_output_redirect.h
  7101. #ifndef TWOBLUECUBES_CATCH_OUTPUT_REDIRECT_H
  7102. #define TWOBLUECUBES_CATCH_OUTPUT_REDIRECT_H
  7103. #include <cstdio>
  7104. #include <iosfwd>
  7105. #include <string>
  7106. namespace Catch {
  7107. class RedirectedStream {
  7108. std::ostream& m_originalStream;
  7109. std::ostream& m_redirectionStream;
  7110. std::streambuf* m_prevBuf;
  7111. public:
  7112. RedirectedStream( std::ostream& originalStream, std::ostream& redirectionStream );
  7113. ~RedirectedStream();
  7114. };
  7115. class RedirectedStdOut {
  7116. ReusableStringStream m_rss;
  7117. RedirectedStream m_cout;
  7118. public:
  7119. RedirectedStdOut();
  7120. auto str() const -> std::string;
  7121. };
  7122. // StdErr has two constituent streams in C++, std::cerr and std::clog
  7123. // This means that we need to redirect 2 streams into 1 to keep proper
  7124. // order of writes
  7125. class RedirectedStdErr {
  7126. ReusableStringStream m_rss;
  7127. RedirectedStream m_cerr;
  7128. RedirectedStream m_clog;
  7129. public:
  7130. RedirectedStdErr();
  7131. auto str() const -> std::string;
  7132. };
  7133. #if defined(CATCH_CONFIG_NEW_CAPTURE)
  7134. // Windows's implementation of std::tmpfile is terrible (it tries
  7135. // to create a file inside system folder, thus requiring elevated
  7136. // privileges for the binary), so we have to use tmpnam(_s) and
  7137. // create the file ourselves there.
  7138. class TempFile {
  7139. public:
  7140. TempFile(TempFile const&) = delete;
  7141. TempFile& operator=(TempFile const&) = delete;
  7142. TempFile(TempFile&&) = delete;
  7143. TempFile& operator=(TempFile&&) = delete;
  7144. TempFile();
  7145. ~TempFile();
  7146. std::FILE* getFile();
  7147. std::string getContents();
  7148. private:
  7149. std::FILE* m_file = nullptr;
  7150. #if defined(_MSC_VER)
  7151. char m_buffer[L_tmpnam] = { 0 };
  7152. #endif
  7153. };
  7154. class OutputRedirect {
  7155. public:
  7156. OutputRedirect(OutputRedirect const&) = delete;
  7157. OutputRedirect& operator=(OutputRedirect const&) = delete;
  7158. OutputRedirect(OutputRedirect&&) = delete;
  7159. OutputRedirect& operator=(OutputRedirect&&) = delete;
  7160. OutputRedirect(std::string& stdout_dest, std::string& stderr_dest);
  7161. ~OutputRedirect();
  7162. private:
  7163. int m_originalStdout = -1;
  7164. int m_originalStderr = -1;
  7165. TempFile m_stdoutFile;
  7166. TempFile m_stderrFile;
  7167. std::string& m_stdoutDest;
  7168. std::string& m_stderrDest;
  7169. };
  7170. #endif
  7171. } // end namespace Catch
  7172. #endif // TWOBLUECUBES_CATCH_OUTPUT_REDIRECT_H
  7173. // end catch_output_redirect.h
  7174. #include <cstdio>
  7175. #include <cstring>
  7176. #include <fstream>
  7177. #include <sstream>
  7178. #include <stdexcept>
  7179. #if defined(CATCH_CONFIG_NEW_CAPTURE)
  7180. #if defined(_MSC_VER)
  7181. #include <io.h> //_dup and _dup2
  7182. #define dup _dup
  7183. #define dup2 _dup2
  7184. #define fileno _fileno
  7185. #else
  7186. #include <unistd.h> // dup and dup2
  7187. #endif
  7188. #endif
  7189. namespace Catch {
  7190. RedirectedStream::RedirectedStream( std::ostream& originalStream, std::ostream& redirectionStream )
  7191. : m_originalStream( originalStream ),
  7192. m_redirectionStream( redirectionStream ),
  7193. m_prevBuf( m_originalStream.rdbuf() )
  7194. {
  7195. m_originalStream.rdbuf( m_redirectionStream.rdbuf() );
  7196. }
  7197. RedirectedStream::~RedirectedStream() {
  7198. m_originalStream.rdbuf( m_prevBuf );
  7199. }
  7200. RedirectedStdOut::RedirectedStdOut() : m_cout( Catch::cout(), m_rss.get() ) {}
  7201. auto RedirectedStdOut::str() const -> std::string { return m_rss.str(); }
  7202. RedirectedStdErr::RedirectedStdErr()
  7203. : m_cerr( Catch::cerr(), m_rss.get() ),
  7204. m_clog( Catch::clog(), m_rss.get() )
  7205. {}
  7206. auto RedirectedStdErr::str() const -> std::string { return m_rss.str(); }
  7207. #if defined(CATCH_CONFIG_NEW_CAPTURE)
  7208. #if defined(_MSC_VER)
  7209. TempFile::TempFile() {
  7210. if (tmpnam_s(m_buffer)) {
  7211. CATCH_RUNTIME_ERROR("Could not get a temp filename");
  7212. }
  7213. if (fopen_s(&m_file, m_buffer, "w")) {
  7214. char buffer[100];
  7215. if (strerror_s(buffer, errno)) {
  7216. CATCH_RUNTIME_ERROR("Could not translate errno to a string");
  7217. }
  7218. CATCH_RUNTIME_ERROR("Coul dnot open the temp file: '" << m_buffer << "' because: " << buffer);
  7219. }
  7220. }
  7221. #else
  7222. TempFile::TempFile() {
  7223. m_file = std::tmpfile();
  7224. if (!m_file) {
  7225. CATCH_RUNTIME_ERROR("Could not create a temp file.");
  7226. }
  7227. }
  7228. #endif
  7229. TempFile::~TempFile() {
  7230. // TBD: What to do about errors here?
  7231. std::fclose(m_file);
  7232. // We manually create the file on Windows only, on Linux
  7233. // it will be autodeleted
  7234. #if defined(_MSC_VER)
  7235. std::remove(m_buffer);
  7236. #endif
  7237. }
  7238. FILE* TempFile::getFile() {
  7239. return m_file;
  7240. }
  7241. std::string TempFile::getContents() {
  7242. std::stringstream sstr;
  7243. char buffer[100] = {};
  7244. std::rewind(m_file);
  7245. while (std::fgets(buffer, sizeof(buffer), m_file)) {
  7246. sstr << buffer;
  7247. }
  7248. return sstr.str();
  7249. }
  7250. OutputRedirect::OutputRedirect(std::string& stdout_dest, std::string& stderr_dest) :
  7251. m_originalStdout(dup(1)),
  7252. m_originalStderr(dup(2)),
  7253. m_stdoutDest(stdout_dest),
  7254. m_stderrDest(stderr_dest) {
  7255. dup2(fileno(m_stdoutFile.getFile()), 1);
  7256. dup2(fileno(m_stderrFile.getFile()), 2);
  7257. }
  7258. OutputRedirect::~OutputRedirect() {
  7259. Catch::cout() << std::flush;
  7260. fflush(stdout);
  7261. // Since we support overriding these streams, we flush cerr
  7262. // even though std::cerr is unbuffered
  7263. Catch::cerr() << std::flush;
  7264. Catch::clog() << std::flush;
  7265. fflush(stderr);
  7266. dup2(m_originalStdout, 1);
  7267. dup2(m_originalStderr, 2);
  7268. m_stdoutDest += m_stdoutFile.getContents();
  7269. m_stderrDest += m_stderrFile.getContents();
  7270. }
  7271. #endif // CATCH_CONFIG_NEW_CAPTURE
  7272. } // namespace Catch
  7273. #if defined(CATCH_CONFIG_NEW_CAPTURE)
  7274. #if defined(_MSC_VER)
  7275. #undef dup
  7276. #undef dup2
  7277. #undef fileno
  7278. #endif
  7279. #endif
  7280. // end catch_output_redirect.cpp
  7281. // start catch_random_number_generator.cpp
  7282. namespace Catch {
  7283. std::mt19937& rng() {
  7284. static std::mt19937 s_rng;
  7285. return s_rng;
  7286. }
  7287. void seedRng( IConfig const& config ) {
  7288. if( config.rngSeed() != 0 ) {
  7289. std::srand( config.rngSeed() );
  7290. rng().seed( config.rngSeed() );
  7291. }
  7292. }
  7293. unsigned int rngSeed() {
  7294. return getCurrentContext().getConfig()->rngSeed();
  7295. }
  7296. }
  7297. // end catch_random_number_generator.cpp
  7298. // start catch_registry_hub.cpp
  7299. // start catch_test_case_registry_impl.h
  7300. #include <vector>
  7301. #include <set>
  7302. #include <algorithm>
  7303. #include <ios>
  7304. namespace Catch {
  7305. class TestCase;
  7306. struct IConfig;
  7307. std::vector<TestCase> sortTests( IConfig const& config, std::vector<TestCase> const& unsortedTestCases );
  7308. bool matchTest( TestCase const& testCase, TestSpec const& testSpec, IConfig const& config );
  7309. void enforceNoDuplicateTestCases( std::vector<TestCase> const& functions );
  7310. std::vector<TestCase> filterTests( std::vector<TestCase> const& testCases, TestSpec const& testSpec, IConfig const& config );
  7311. std::vector<TestCase> const& getAllTestCasesSorted( IConfig const& config );
  7312. class TestRegistry : public ITestCaseRegistry {
  7313. public:
  7314. virtual ~TestRegistry() = default;
  7315. virtual void registerTest( TestCase const& testCase );
  7316. std::vector<TestCase> const& getAllTests() const override;
  7317. std::vector<TestCase> const& getAllTestsSorted( IConfig const& config ) const override;
  7318. private:
  7319. std::vector<TestCase> m_functions;
  7320. mutable RunTests::InWhatOrder m_currentSortOrder = RunTests::InDeclarationOrder;
  7321. mutable std::vector<TestCase> m_sortedFunctions;
  7322. std::size_t m_unnamedCount = 0;
  7323. std::ios_base::Init m_ostreamInit; // Forces cout/ cerr to be initialised
  7324. };
  7325. ///////////////////////////////////////////////////////////////////////////
  7326. class TestInvokerAsFunction : public ITestInvoker {
  7327. void(*m_testAsFunction)();
  7328. public:
  7329. TestInvokerAsFunction( void(*testAsFunction)() ) noexcept;
  7330. void invoke() const override;
  7331. };
  7332. std::string extractClassName( StringRef const& classOrQualifiedMethodName );
  7333. ///////////////////////////////////////////////////////////////////////////
  7334. } // end namespace Catch
  7335. // end catch_test_case_registry_impl.h
  7336. // start catch_reporter_registry.h
  7337. #include <map>
  7338. namespace Catch {
  7339. class ReporterRegistry : public IReporterRegistry {
  7340. public:
  7341. ~ReporterRegistry() override;
  7342. IStreamingReporterPtr create( std::string const& name, IConfigPtr const& config ) const override;
  7343. void registerReporter( std::string const& name, IReporterFactoryPtr const& factory );
  7344. void registerListener( IReporterFactoryPtr const& factory );
  7345. FactoryMap const& getFactories() const override;
  7346. Listeners const& getListeners() const override;
  7347. private:
  7348. FactoryMap m_factories;
  7349. Listeners m_listeners;
  7350. };
  7351. }
  7352. // end catch_reporter_registry.h
  7353. // start catch_tag_alias_registry.h
  7354. // start catch_tag_alias.h
  7355. #include <string>
  7356. namespace Catch {
  7357. struct TagAlias {
  7358. TagAlias(std::string const& _tag, SourceLineInfo _lineInfo);
  7359. std::string tag;
  7360. SourceLineInfo lineInfo;
  7361. };
  7362. } // end namespace Catch
  7363. // end catch_tag_alias.h
  7364. #include <map>
  7365. namespace Catch {
  7366. class TagAliasRegistry : public ITagAliasRegistry {
  7367. public:
  7368. ~TagAliasRegistry() override;
  7369. TagAlias const* find( std::string const& alias ) const override;
  7370. std::string expandAliases( std::string const& unexpandedTestSpec ) const override;
  7371. void add( std::string const& alias, std::string const& tag, SourceLineInfo const& lineInfo );
  7372. private:
  7373. std::map<std::string, TagAlias> m_registry;
  7374. };
  7375. } // end namespace Catch
  7376. // end catch_tag_alias_registry.h
  7377. // start catch_startup_exception_registry.h
  7378. #include <vector>
  7379. #include <exception>
  7380. namespace Catch {
  7381. class StartupExceptionRegistry {
  7382. public:
  7383. void add(std::exception_ptr const& exception) noexcept;
  7384. std::vector<std::exception_ptr> const& getExceptions() const noexcept;
  7385. private:
  7386. std::vector<std::exception_ptr> m_exceptions;
  7387. };
  7388. } // end namespace Catch
  7389. // end catch_startup_exception_registry.h
  7390. // start catch_singletons.hpp
  7391. namespace Catch {
  7392. struct ISingleton {
  7393. virtual ~ISingleton();
  7394. };
  7395. void addSingleton( ISingleton* singleton );
  7396. void cleanupSingletons();
  7397. template<typename SingletonImplT, typename InterfaceT = SingletonImplT, typename MutableInterfaceT = InterfaceT>
  7398. class Singleton : SingletonImplT, public ISingleton {
  7399. static auto getInternal() -> Singleton* {
  7400. static Singleton* s_instance = nullptr;
  7401. if( !s_instance ) {
  7402. s_instance = new Singleton;
  7403. addSingleton( s_instance );
  7404. }
  7405. return s_instance;
  7406. }
  7407. public:
  7408. static auto get() -> InterfaceT const& {
  7409. return *getInternal();
  7410. }
  7411. static auto getMutable() -> MutableInterfaceT& {
  7412. return *getInternal();
  7413. }
  7414. };
  7415. } // namespace Catch
  7416. // end catch_singletons.hpp
  7417. namespace Catch {
  7418. namespace {
  7419. class RegistryHub : public IRegistryHub, public IMutableRegistryHub,
  7420. private NonCopyable {
  7421. public: // IRegistryHub
  7422. RegistryHub() = default;
  7423. IReporterRegistry const& getReporterRegistry() const override {
  7424. return m_reporterRegistry;
  7425. }
  7426. ITestCaseRegistry const& getTestCaseRegistry() const override {
  7427. return m_testCaseRegistry;
  7428. }
  7429. IExceptionTranslatorRegistry const& getExceptionTranslatorRegistry() const override {
  7430. return m_exceptionTranslatorRegistry;
  7431. }
  7432. ITagAliasRegistry const& getTagAliasRegistry() const override {
  7433. return m_tagAliasRegistry;
  7434. }
  7435. StartupExceptionRegistry const& getStartupExceptionRegistry() const override {
  7436. return m_exceptionRegistry;
  7437. }
  7438. public: // IMutableRegistryHub
  7439. void registerReporter( std::string const& name, IReporterFactoryPtr const& factory ) override {
  7440. m_reporterRegistry.registerReporter( name, factory );
  7441. }
  7442. void registerListener( IReporterFactoryPtr const& factory ) override {
  7443. m_reporterRegistry.registerListener( factory );
  7444. }
  7445. void registerTest( TestCase const& testInfo ) override {
  7446. m_testCaseRegistry.registerTest( testInfo );
  7447. }
  7448. void registerTranslator( const IExceptionTranslator* translator ) override {
  7449. m_exceptionTranslatorRegistry.registerTranslator( translator );
  7450. }
  7451. void registerTagAlias( std::string const& alias, std::string const& tag, SourceLineInfo const& lineInfo ) override {
  7452. m_tagAliasRegistry.add( alias, tag, lineInfo );
  7453. }
  7454. void registerStartupException() noexcept override {
  7455. m_exceptionRegistry.add(std::current_exception());
  7456. }
  7457. private:
  7458. TestRegistry m_testCaseRegistry;
  7459. ReporterRegistry m_reporterRegistry;
  7460. ExceptionTranslatorRegistry m_exceptionTranslatorRegistry;
  7461. TagAliasRegistry m_tagAliasRegistry;
  7462. StartupExceptionRegistry m_exceptionRegistry;
  7463. };
  7464. }
  7465. using RegistryHubSingleton = Singleton<RegistryHub, IRegistryHub, IMutableRegistryHub>;
  7466. IRegistryHub const& getRegistryHub() {
  7467. return RegistryHubSingleton::get();
  7468. }
  7469. IMutableRegistryHub& getMutableRegistryHub() {
  7470. return RegistryHubSingleton::getMutable();
  7471. }
  7472. void cleanUp() {
  7473. cleanupSingletons();
  7474. cleanUpContext();
  7475. }
  7476. std::string translateActiveException() {
  7477. return getRegistryHub().getExceptionTranslatorRegistry().translateActiveException();
  7478. }
  7479. } // end namespace Catch
  7480. // end catch_registry_hub.cpp
  7481. // start catch_reporter_registry.cpp
  7482. namespace Catch {
  7483. ReporterRegistry::~ReporterRegistry() = default;
  7484. IStreamingReporterPtr ReporterRegistry::create( std::string const& name, IConfigPtr const& config ) const {
  7485. auto it = m_factories.find( name );
  7486. if( it == m_factories.end() )
  7487. return nullptr;
  7488. return it->second->create( ReporterConfig( config ) );
  7489. }
  7490. void ReporterRegistry::registerReporter( std::string const& name, IReporterFactoryPtr const& factory ) {
  7491. m_factories.emplace(name, factory);
  7492. }
  7493. void ReporterRegistry::registerListener( IReporterFactoryPtr const& factory ) {
  7494. m_listeners.push_back( factory );
  7495. }
  7496. IReporterRegistry::FactoryMap const& ReporterRegistry::getFactories() const {
  7497. return m_factories;
  7498. }
  7499. IReporterRegistry::Listeners const& ReporterRegistry::getListeners() const {
  7500. return m_listeners;
  7501. }
  7502. }
  7503. // end catch_reporter_registry.cpp
  7504. // start catch_result_type.cpp
  7505. namespace Catch {
  7506. bool isOk( ResultWas::OfType resultType ) {
  7507. return ( resultType & ResultWas::FailureBit ) == 0;
  7508. }
  7509. bool isJustInfo( int flags ) {
  7510. return flags == ResultWas::Info;
  7511. }
  7512. ResultDisposition::Flags operator | ( ResultDisposition::Flags lhs, ResultDisposition::Flags rhs ) {
  7513. return static_cast<ResultDisposition::Flags>( static_cast<int>( lhs ) | static_cast<int>( rhs ) );
  7514. }
  7515. bool shouldContinueOnFailure( int flags ) { return ( flags & ResultDisposition::ContinueOnFailure ) != 0; }
  7516. bool shouldSuppressFailure( int flags ) { return ( flags & ResultDisposition::SuppressFail ) != 0; }
  7517. } // end namespace Catch
  7518. // end catch_result_type.cpp
  7519. // start catch_run_context.cpp
  7520. #include <cassert>
  7521. #include <algorithm>
  7522. #include <sstream>
  7523. namespace Catch {
  7524. namespace Generators {
  7525. struct GeneratorTracker : TestCaseTracking::TrackerBase, IGeneratorTracker {
  7526. size_t m_index = static_cast<size_t>( -1 );
  7527. GeneratorBasePtr m_generator;
  7528. GeneratorTracker( TestCaseTracking::NameAndLocation const& nameAndLocation, TrackerContext& ctx, ITracker* parent )
  7529. : TrackerBase( nameAndLocation, ctx, parent )
  7530. {}
  7531. ~GeneratorTracker();
  7532. static GeneratorTracker& acquire( TrackerContext& ctx, TestCaseTracking::NameAndLocation const& nameAndLocation ) {
  7533. std::shared_ptr<GeneratorTracker> tracker;
  7534. ITracker& currentTracker = ctx.currentTracker();
  7535. if( TestCaseTracking::ITrackerPtr childTracker = currentTracker.findChild( nameAndLocation ) ) {
  7536. assert( childTracker );
  7537. assert( childTracker->isIndexTracker() );
  7538. tracker = std::static_pointer_cast<GeneratorTracker>( childTracker );
  7539. }
  7540. else {
  7541. tracker = std::make_shared<GeneratorTracker>( nameAndLocation, ctx, &currentTracker );
  7542. currentTracker.addChild( tracker );
  7543. }
  7544. if( !ctx.completedCycle() && !tracker->isComplete() ) {
  7545. if( tracker->m_runState != ExecutingChildren && tracker->m_runState != NeedsAnotherRun )
  7546. tracker->moveNext();
  7547. tracker->open();
  7548. }
  7549. return *tracker;
  7550. }
  7551. void moveNext() {
  7552. m_index++;
  7553. m_children.clear();
  7554. }
  7555. // TrackerBase interface
  7556. bool isIndexTracker() const override { return true; }
  7557. auto hasGenerator() const -> bool override {
  7558. return !!m_generator;
  7559. }
  7560. void close() override {
  7561. TrackerBase::close();
  7562. if( m_runState == CompletedSuccessfully && m_index < m_generator->size()-1 )
  7563. m_runState = Executing;
  7564. }
  7565. // IGeneratorTracker interface
  7566. auto getGenerator() const -> GeneratorBasePtr const& override {
  7567. return m_generator;
  7568. }
  7569. void setGenerator( GeneratorBasePtr&& generator ) override {
  7570. m_generator = std::move( generator );
  7571. }
  7572. auto getIndex() const -> size_t override {
  7573. return m_index;
  7574. }
  7575. };
  7576. GeneratorTracker::~GeneratorTracker() {}
  7577. }
  7578. RunContext::RunContext(IConfigPtr const& _config, IStreamingReporterPtr&& reporter)
  7579. : m_runInfo(_config->name()),
  7580. m_context(getCurrentMutableContext()),
  7581. m_config(_config),
  7582. m_reporter(std::move(reporter)),
  7583. m_lastAssertionInfo{ StringRef(), SourceLineInfo("",0), StringRef(), ResultDisposition::Normal },
  7584. m_includeSuccessfulResults( m_config->includeSuccessfulResults() || m_reporter->getPreferences().shouldReportAllAssertions )
  7585. {
  7586. m_context.setRunner(this);
  7587. m_context.setConfig(m_config);
  7588. m_context.setResultCapture(this);
  7589. m_reporter->testRunStarting(m_runInfo);
  7590. }
  7591. RunContext::~RunContext() {
  7592. m_reporter->testRunEnded(TestRunStats(m_runInfo, m_totals, aborting()));
  7593. }
  7594. void RunContext::testGroupStarting(std::string const& testSpec, std::size_t groupIndex, std::size_t groupsCount) {
  7595. m_reporter->testGroupStarting(GroupInfo(testSpec, groupIndex, groupsCount));
  7596. }
  7597. void RunContext::testGroupEnded(std::string const& testSpec, Totals const& totals, std::size_t groupIndex, std::size_t groupsCount) {
  7598. m_reporter->testGroupEnded(TestGroupStats(GroupInfo(testSpec, groupIndex, groupsCount), totals, aborting()));
  7599. }
  7600. Totals RunContext::runTest(TestCase const& testCase) {
  7601. Totals prevTotals = m_totals;
  7602. std::string redirectedCout;
  7603. std::string redirectedCerr;
  7604. auto const& testInfo = testCase.getTestCaseInfo();
  7605. m_reporter->testCaseStarting(testInfo);
  7606. m_activeTestCase = &testCase;
  7607. ITracker& rootTracker = m_trackerContext.startRun();
  7608. assert(rootTracker.isSectionTracker());
  7609. static_cast<SectionTracker&>(rootTracker).addInitialFilters(m_config->getSectionsToRun());
  7610. do {
  7611. m_trackerContext.startCycle();
  7612. m_testCaseTracker = &SectionTracker::acquire(m_trackerContext, TestCaseTracking::NameAndLocation(testInfo.name, testInfo.lineInfo));
  7613. runCurrentTest(redirectedCout, redirectedCerr);
  7614. } while (!m_testCaseTracker->isSuccessfullyCompleted() && !aborting());
  7615. Totals deltaTotals = m_totals.delta(prevTotals);
  7616. if (testInfo.expectedToFail() && deltaTotals.testCases.passed > 0) {
  7617. deltaTotals.assertions.failed++;
  7618. deltaTotals.testCases.passed--;
  7619. deltaTotals.testCases.failed++;
  7620. }
  7621. m_totals.testCases += deltaTotals.testCases;
  7622. m_reporter->testCaseEnded(TestCaseStats(testInfo,
  7623. deltaTotals,
  7624. redirectedCout,
  7625. redirectedCerr,
  7626. aborting()));
  7627. m_activeTestCase = nullptr;
  7628. m_testCaseTracker = nullptr;
  7629. return deltaTotals;
  7630. }
  7631. IConfigPtr RunContext::config() const {
  7632. return m_config;
  7633. }
  7634. IStreamingReporter& RunContext::reporter() const {
  7635. return *m_reporter;
  7636. }
  7637. void RunContext::assertionEnded(AssertionResult const & result) {
  7638. if (result.getResultType() == ResultWas::Ok) {
  7639. m_totals.assertions.passed++;
  7640. m_lastAssertionPassed = true;
  7641. } else if (!result.isOk()) {
  7642. m_lastAssertionPassed = false;
  7643. if( m_activeTestCase->getTestCaseInfo().okToFail() )
  7644. m_totals.assertions.failedButOk++;
  7645. else
  7646. m_totals.assertions.failed++;
  7647. }
  7648. else {
  7649. m_lastAssertionPassed = true;
  7650. }
  7651. // We have no use for the return value (whether messages should be cleared), because messages were made scoped
  7652. // and should be let to clear themselves out.
  7653. static_cast<void>(m_reporter->assertionEnded(AssertionStats(result, m_messages, m_totals)));
  7654. // Reset working state
  7655. resetAssertionInfo();
  7656. m_lastResult = result;
  7657. }
  7658. void RunContext::resetAssertionInfo() {
  7659. m_lastAssertionInfo.macroName = StringRef();
  7660. m_lastAssertionInfo.capturedExpression = "{Unknown expression after the reported line}"_sr;
  7661. }
  7662. bool RunContext::sectionStarted(SectionInfo const & sectionInfo, Counts & assertions) {
  7663. ITracker& sectionTracker = SectionTracker::acquire(m_trackerContext, TestCaseTracking::NameAndLocation(sectionInfo.name, sectionInfo.lineInfo));
  7664. if (!sectionTracker.isOpen())
  7665. return false;
  7666. m_activeSections.push_back(&sectionTracker);
  7667. m_lastAssertionInfo.lineInfo = sectionInfo.lineInfo;
  7668. m_reporter->sectionStarting(sectionInfo);
  7669. assertions = m_totals.assertions;
  7670. return true;
  7671. }
  7672. auto RunContext::acquireGeneratorTracker( SourceLineInfo const& lineInfo ) -> IGeneratorTracker& {
  7673. using namespace Generators;
  7674. GeneratorTracker& tracker = GeneratorTracker::acquire( m_trackerContext, TestCaseTracking::NameAndLocation( "generator", lineInfo ) );
  7675. assert( tracker.isOpen() );
  7676. m_lastAssertionInfo.lineInfo = lineInfo;
  7677. return tracker;
  7678. }
  7679. bool RunContext::testForMissingAssertions(Counts& assertions) {
  7680. if (assertions.total() != 0)
  7681. return false;
  7682. if (!m_config->warnAboutMissingAssertions())
  7683. return false;
  7684. if (m_trackerContext.currentTracker().hasChildren())
  7685. return false;
  7686. m_totals.assertions.failed++;
  7687. assertions.failed++;
  7688. return true;
  7689. }
  7690. void RunContext::sectionEnded(SectionEndInfo const & endInfo) {
  7691. Counts assertions = m_totals.assertions - endInfo.prevAssertions;
  7692. bool missingAssertions = testForMissingAssertions(assertions);
  7693. if (!m_activeSections.empty()) {
  7694. m_activeSections.back()->close();
  7695. m_activeSections.pop_back();
  7696. }
  7697. m_reporter->sectionEnded(SectionStats(endInfo.sectionInfo, assertions, endInfo.durationInSeconds, missingAssertions));
  7698. m_messages.clear();
  7699. }
  7700. void RunContext::sectionEndedEarly(SectionEndInfo const & endInfo) {
  7701. if (m_unfinishedSections.empty())
  7702. m_activeSections.back()->fail();
  7703. else
  7704. m_activeSections.back()->close();
  7705. m_activeSections.pop_back();
  7706. m_unfinishedSections.push_back(endInfo);
  7707. }
  7708. void RunContext::benchmarkStarting( BenchmarkInfo const& info ) {
  7709. m_reporter->benchmarkStarting( info );
  7710. }
  7711. void RunContext::benchmarkEnded( BenchmarkStats const& stats ) {
  7712. m_reporter->benchmarkEnded( stats );
  7713. }
  7714. void RunContext::pushScopedMessage(MessageInfo const & message) {
  7715. m_messages.push_back(message);
  7716. }
  7717. void RunContext::popScopedMessage(MessageInfo const & message) {
  7718. m_messages.erase(std::remove(m_messages.begin(), m_messages.end(), message), m_messages.end());
  7719. }
  7720. std::string RunContext::getCurrentTestName() const {
  7721. return m_activeTestCase
  7722. ? m_activeTestCase->getTestCaseInfo().name
  7723. : std::string();
  7724. }
  7725. const AssertionResult * RunContext::getLastResult() const {
  7726. return &(*m_lastResult);
  7727. }
  7728. void RunContext::exceptionEarlyReported() {
  7729. m_shouldReportUnexpected = false;
  7730. }
  7731. void RunContext::handleFatalErrorCondition( StringRef message ) {
  7732. // First notify reporter that bad things happened
  7733. m_reporter->fatalErrorEncountered(message);
  7734. // Don't rebuild the result -- the stringification itself can cause more fatal errors
  7735. // Instead, fake a result data.
  7736. AssertionResultData tempResult( ResultWas::FatalErrorCondition, { false } );
  7737. tempResult.message = message;
  7738. AssertionResult result(m_lastAssertionInfo, tempResult);
  7739. assertionEnded(result);
  7740. handleUnfinishedSections();
  7741. // Recreate section for test case (as we will lose the one that was in scope)
  7742. auto const& testCaseInfo = m_activeTestCase->getTestCaseInfo();
  7743. SectionInfo testCaseSection(testCaseInfo.lineInfo, testCaseInfo.name);
  7744. Counts assertions;
  7745. assertions.failed = 1;
  7746. SectionStats testCaseSectionStats(testCaseSection, assertions, 0, false);
  7747. m_reporter->sectionEnded(testCaseSectionStats);
  7748. auto const& testInfo = m_activeTestCase->getTestCaseInfo();
  7749. Totals deltaTotals;
  7750. deltaTotals.testCases.failed = 1;
  7751. deltaTotals.assertions.failed = 1;
  7752. m_reporter->testCaseEnded(TestCaseStats(testInfo,
  7753. deltaTotals,
  7754. std::string(),
  7755. std::string(),
  7756. false));
  7757. m_totals.testCases.failed++;
  7758. testGroupEnded(std::string(), m_totals, 1, 1);
  7759. m_reporter->testRunEnded(TestRunStats(m_runInfo, m_totals, false));
  7760. }
  7761. bool RunContext::lastAssertionPassed() {
  7762. return m_lastAssertionPassed;
  7763. }
  7764. void RunContext::assertionPassed() {
  7765. m_lastAssertionPassed = true;
  7766. ++m_totals.assertions.passed;
  7767. resetAssertionInfo();
  7768. }
  7769. bool RunContext::aborting() const {
  7770. return m_totals.assertions.failed >= static_cast<std::size_t>(m_config->abortAfter());
  7771. }
  7772. void RunContext::runCurrentTest(std::string & redirectedCout, std::string & redirectedCerr) {
  7773. auto const& testCaseInfo = m_activeTestCase->getTestCaseInfo();
  7774. SectionInfo testCaseSection(testCaseInfo.lineInfo, testCaseInfo.name);
  7775. m_reporter->sectionStarting(testCaseSection);
  7776. Counts prevAssertions = m_totals.assertions;
  7777. double duration = 0;
  7778. m_shouldReportUnexpected = true;
  7779. m_lastAssertionInfo = { "TEST_CASE"_sr, testCaseInfo.lineInfo, StringRef(), ResultDisposition::Normal };
  7780. seedRng(*m_config);
  7781. Timer timer;
  7782. CATCH_TRY {
  7783. if (m_reporter->getPreferences().shouldRedirectStdOut) {
  7784. #if !defined(CATCH_CONFIG_EXPERIMENTAL_REDIRECT)
  7785. RedirectedStdOut redirectedStdOut;
  7786. RedirectedStdErr redirectedStdErr;
  7787. timer.start();
  7788. invokeActiveTestCase();
  7789. redirectedCout += redirectedStdOut.str();
  7790. redirectedCerr += redirectedStdErr.str();
  7791. #else
  7792. OutputRedirect r(redirectedCout, redirectedCerr);
  7793. timer.start();
  7794. invokeActiveTestCase();
  7795. #endif
  7796. } else {
  7797. timer.start();
  7798. invokeActiveTestCase();
  7799. }
  7800. duration = timer.getElapsedSeconds();
  7801. } CATCH_CATCH_ANON (TestFailureException&) {
  7802. // This just means the test was aborted due to failure
  7803. } CATCH_CATCH_ALL {
  7804. // Under CATCH_CONFIG_FAST_COMPILE, unexpected exceptions under REQUIRE assertions
  7805. // are reported without translation at the point of origin.
  7806. if( m_shouldReportUnexpected ) {
  7807. AssertionReaction dummyReaction;
  7808. handleUnexpectedInflightException( m_lastAssertionInfo, translateActiveException(), dummyReaction );
  7809. }
  7810. }
  7811. Counts assertions = m_totals.assertions - prevAssertions;
  7812. bool missingAssertions = testForMissingAssertions(assertions);
  7813. m_testCaseTracker->close();
  7814. handleUnfinishedSections();
  7815. m_messages.clear();
  7816. SectionStats testCaseSectionStats(testCaseSection, assertions, duration, missingAssertions);
  7817. m_reporter->sectionEnded(testCaseSectionStats);
  7818. }
  7819. void RunContext::invokeActiveTestCase() {
  7820. FatalConditionHandler fatalConditionHandler; // Handle signals
  7821. m_activeTestCase->invoke();
  7822. fatalConditionHandler.reset();
  7823. }
  7824. void RunContext::handleUnfinishedSections() {
  7825. // If sections ended prematurely due to an exception we stored their
  7826. // infos here so we can tear them down outside the unwind process.
  7827. for (auto it = m_unfinishedSections.rbegin(),
  7828. itEnd = m_unfinishedSections.rend();
  7829. it != itEnd;
  7830. ++it)
  7831. sectionEnded(*it);
  7832. m_unfinishedSections.clear();
  7833. }
  7834. void RunContext::handleExpr(
  7835. AssertionInfo const& info,
  7836. ITransientExpression const& expr,
  7837. AssertionReaction& reaction
  7838. ) {
  7839. m_reporter->assertionStarting( info );
  7840. bool negated = isFalseTest( info.resultDisposition );
  7841. bool result = expr.getResult() != negated;
  7842. if( result ) {
  7843. if (!m_includeSuccessfulResults) {
  7844. assertionPassed();
  7845. }
  7846. else {
  7847. reportExpr(info, ResultWas::Ok, &expr, negated);
  7848. }
  7849. }
  7850. else {
  7851. reportExpr(info, ResultWas::ExpressionFailed, &expr, negated );
  7852. populateReaction( reaction );
  7853. }
  7854. }
  7855. void RunContext::reportExpr(
  7856. AssertionInfo const &info,
  7857. ResultWas::OfType resultType,
  7858. ITransientExpression const *expr,
  7859. bool negated ) {
  7860. m_lastAssertionInfo = info;
  7861. AssertionResultData data( resultType, LazyExpression( negated ) );
  7862. AssertionResult assertionResult{ info, data };
  7863. assertionResult.m_resultData.lazyExpression.m_transientExpression = expr;
  7864. assertionEnded( assertionResult );
  7865. }
  7866. void RunContext::handleMessage(
  7867. AssertionInfo const& info,
  7868. ResultWas::OfType resultType,
  7869. StringRef const& message,
  7870. AssertionReaction& reaction
  7871. ) {
  7872. m_reporter->assertionStarting( info );
  7873. m_lastAssertionInfo = info;
  7874. AssertionResultData data( resultType, LazyExpression( false ) );
  7875. data.message = message;
  7876. AssertionResult assertionResult{ m_lastAssertionInfo, data };
  7877. assertionEnded( assertionResult );
  7878. if( !assertionResult.isOk() )
  7879. populateReaction( reaction );
  7880. }
  7881. void RunContext::handleUnexpectedExceptionNotThrown(
  7882. AssertionInfo const& info,
  7883. AssertionReaction& reaction
  7884. ) {
  7885. handleNonExpr(info, Catch::ResultWas::DidntThrowException, reaction);
  7886. }
  7887. void RunContext::handleUnexpectedInflightException(
  7888. AssertionInfo const& info,
  7889. std::string const& message,
  7890. AssertionReaction& reaction
  7891. ) {
  7892. m_lastAssertionInfo = info;
  7893. AssertionResultData data( ResultWas::ThrewException, LazyExpression( false ) );
  7894. data.message = message;
  7895. AssertionResult assertionResult{ info, data };
  7896. assertionEnded( assertionResult );
  7897. populateReaction( reaction );
  7898. }
  7899. void RunContext::populateReaction( AssertionReaction& reaction ) {
  7900. reaction.shouldDebugBreak = m_config->shouldDebugBreak();
  7901. reaction.shouldThrow = aborting() || (m_lastAssertionInfo.resultDisposition & ResultDisposition::Normal);
  7902. }
  7903. void RunContext::handleIncomplete(
  7904. AssertionInfo const& info
  7905. ) {
  7906. m_lastAssertionInfo = info;
  7907. AssertionResultData data( ResultWas::ThrewException, LazyExpression( false ) );
  7908. data.message = "Exception translation was disabled by CATCH_CONFIG_FAST_COMPILE";
  7909. AssertionResult assertionResult{ info, data };
  7910. assertionEnded( assertionResult );
  7911. }
  7912. void RunContext::handleNonExpr(
  7913. AssertionInfo const &info,
  7914. ResultWas::OfType resultType,
  7915. AssertionReaction &reaction
  7916. ) {
  7917. m_lastAssertionInfo = info;
  7918. AssertionResultData data( resultType, LazyExpression( false ) );
  7919. AssertionResult assertionResult{ info, data };
  7920. assertionEnded( assertionResult );
  7921. if( !assertionResult.isOk() )
  7922. populateReaction( reaction );
  7923. }
  7924. IResultCapture& getResultCapture() {
  7925. if (auto* capture = getCurrentContext().getResultCapture())
  7926. return *capture;
  7927. else
  7928. CATCH_INTERNAL_ERROR("No result capture instance");
  7929. }
  7930. }
  7931. // end catch_run_context.cpp
  7932. // start catch_section.cpp
  7933. namespace Catch {
  7934. Section::Section( SectionInfo const& info )
  7935. : m_info( info ),
  7936. m_sectionIncluded( getResultCapture().sectionStarted( m_info, m_assertions ) )
  7937. {
  7938. m_timer.start();
  7939. }
  7940. Section::~Section() {
  7941. if( m_sectionIncluded ) {
  7942. SectionEndInfo endInfo{ m_info, m_assertions, m_timer.getElapsedSeconds() };
  7943. if( uncaught_exceptions() )
  7944. getResultCapture().sectionEndedEarly( endInfo );
  7945. else
  7946. getResultCapture().sectionEnded( endInfo );
  7947. }
  7948. }
  7949. // This indicates whether the section should be executed or not
  7950. Section::operator bool() const {
  7951. return m_sectionIncluded;
  7952. }
  7953. } // end namespace Catch
  7954. // end catch_section.cpp
  7955. // start catch_section_info.cpp
  7956. namespace Catch {
  7957. SectionInfo::SectionInfo
  7958. ( SourceLineInfo const& _lineInfo,
  7959. std::string const& _name )
  7960. : name( _name ),
  7961. lineInfo( _lineInfo )
  7962. {}
  7963. } // end namespace Catch
  7964. // end catch_section_info.cpp
  7965. // start catch_session.cpp
  7966. // start catch_session.h
  7967. #include <memory>
  7968. namespace Catch {
  7969. class Session : NonCopyable {
  7970. public:
  7971. Session();
  7972. ~Session() override;
  7973. void showHelp() const;
  7974. void libIdentify();
  7975. int applyCommandLine( int argc, char const * const * argv );
  7976. void useConfigData( ConfigData const& configData );
  7977. int run( int argc, char* argv[] );
  7978. #if defined(CATCH_CONFIG_WCHAR) && defined(WIN32) && defined(UNICODE)
  7979. int run( int argc, wchar_t* const argv[] );
  7980. #endif
  7981. int run();
  7982. clara::Parser const& cli() const;
  7983. void cli( clara::Parser const& newParser );
  7984. ConfigData& configData();
  7985. Config& config();
  7986. private:
  7987. int runInternal();
  7988. clara::Parser m_cli;
  7989. ConfigData m_configData;
  7990. std::shared_ptr<Config> m_config;
  7991. bool m_startupExceptions = false;
  7992. };
  7993. } // end namespace Catch
  7994. // end catch_session.h
  7995. // start catch_version.h
  7996. #include <iosfwd>
  7997. namespace Catch {
  7998. // Versioning information
  7999. struct Version {
  8000. Version( Version const& ) = delete;
  8001. Version& operator=( Version const& ) = delete;
  8002. Version( unsigned int _majorVersion,
  8003. unsigned int _minorVersion,
  8004. unsigned int _patchNumber,
  8005. char const * const _branchName,
  8006. unsigned int _buildNumber );
  8007. unsigned int const majorVersion;
  8008. unsigned int const minorVersion;
  8009. unsigned int const patchNumber;
  8010. // buildNumber is only used if branchName is not null
  8011. char const * const branchName;
  8012. unsigned int const buildNumber;
  8013. friend std::ostream& operator << ( std::ostream& os, Version const& version );
  8014. };
  8015. Version const& libraryVersion();
  8016. }
  8017. // end catch_version.h
  8018. #include <cstdlib>
  8019. #include <iomanip>
  8020. namespace Catch {
  8021. namespace {
  8022. const int MaxExitCode = 255;
  8023. IStreamingReporterPtr createReporter(std::string const& reporterName, IConfigPtr const& config) {
  8024. auto reporter = Catch::getRegistryHub().getReporterRegistry().create(reporterName, config);
  8025. CATCH_ENFORCE(reporter, "No reporter registered with name: '" << reporterName << "'");
  8026. return reporter;
  8027. }
  8028. IStreamingReporterPtr makeReporter(std::shared_ptr<Config> const& config) {
  8029. if (Catch::getRegistryHub().getReporterRegistry().getListeners().empty()) {
  8030. return createReporter(config->getReporterName(), config);
  8031. }
  8032. auto multi = std::unique_ptr<ListeningReporter>(new ListeningReporter);
  8033. auto const& listeners = Catch::getRegistryHub().getReporterRegistry().getListeners();
  8034. for (auto const& listener : listeners) {
  8035. multi->addListener(listener->create(Catch::ReporterConfig(config)));
  8036. }
  8037. multi->addReporter(createReporter(config->getReporterName(), config));
  8038. return std::move(multi);
  8039. }
  8040. Catch::Totals runTests(std::shared_ptr<Config> const& config) {
  8041. // FixMe: Add listeners in order first, then add reporters.
  8042. auto reporter = makeReporter(config);
  8043. RunContext context(config, std::move(reporter));
  8044. Totals totals;
  8045. context.testGroupStarting(config->name(), 1, 1);
  8046. TestSpec testSpec = config->testSpec();
  8047. auto const& allTestCases = getAllTestCasesSorted(*config);
  8048. for (auto const& testCase : allTestCases) {
  8049. if (!context.aborting() && matchTest(testCase, testSpec, *config))
  8050. totals += context.runTest(testCase);
  8051. else
  8052. context.reporter().skipTest(testCase);
  8053. }
  8054. if (config->warnAboutNoTests() && totals.testCases.total() == 0) {
  8055. ReusableStringStream testConfig;
  8056. bool first = true;
  8057. for (const auto& input : config->getTestsOrTags()) {
  8058. if (!first) { testConfig << ' '; }
  8059. first = false;
  8060. testConfig << input;
  8061. }
  8062. context.reporter().noMatchingTestCases(testConfig.str());
  8063. totals.error = -1;
  8064. }
  8065. context.testGroupEnded(config->name(), totals, 1, 1);
  8066. return totals;
  8067. }
  8068. void applyFilenamesAsTags(Catch::IConfig const& config) {
  8069. auto& tests = const_cast<std::vector<TestCase>&>(getAllTestCasesSorted(config));
  8070. for (auto& testCase : tests) {
  8071. auto tags = testCase.tags;
  8072. std::string filename = testCase.lineInfo.file;
  8073. auto lastSlash = filename.find_last_of("\\/");
  8074. if (lastSlash != std::string::npos) {
  8075. filename.erase(0, lastSlash);
  8076. filename[0] = '#';
  8077. }
  8078. auto lastDot = filename.find_last_of('.');
  8079. if (lastDot != std::string::npos) {
  8080. filename.erase(lastDot);
  8081. }
  8082. tags.push_back(std::move(filename));
  8083. setTags(testCase, tags);
  8084. }
  8085. }
  8086. } // anon namespace
  8087. Session::Session() {
  8088. static bool alreadyInstantiated = false;
  8089. if( alreadyInstantiated ) {
  8090. CATCH_TRY { CATCH_INTERNAL_ERROR( "Only one instance of Catch::Session can ever be used" ); }
  8091. CATCH_CATCH_ALL { getMutableRegistryHub().registerStartupException(); }
  8092. }
  8093. // There cannot be exceptions at startup in no-exception mode.
  8094. #if !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
  8095. const auto& exceptions = getRegistryHub().getStartupExceptionRegistry().getExceptions();
  8096. if ( !exceptions.empty() ) {
  8097. m_startupExceptions = true;
  8098. Colour colourGuard( Colour::Red );
  8099. Catch::cerr() << "Errors occurred during startup!" << '\n';
  8100. // iterate over all exceptions and notify user
  8101. for ( const auto& ex_ptr : exceptions ) {
  8102. try {
  8103. std::rethrow_exception(ex_ptr);
  8104. } catch ( std::exception const& ex ) {
  8105. Catch::cerr() << Column( ex.what() ).indent(2) << '\n';
  8106. }
  8107. }
  8108. }
  8109. #endif
  8110. alreadyInstantiated = true;
  8111. m_cli = makeCommandLineParser( m_configData );
  8112. }
  8113. Session::~Session() {
  8114. Catch::cleanUp();
  8115. }
  8116. void Session::showHelp() const {
  8117. Catch::cout()
  8118. << "\nCatch v" << libraryVersion() << "\n"
  8119. << m_cli << std::endl
  8120. << "For more detailed usage please see the project docs\n" << std::endl;
  8121. }
  8122. void Session::libIdentify() {
  8123. Catch::cout()
  8124. << std::left << std::setw(16) << "description: " << "A Catch test executable\n"
  8125. << std::left << std::setw(16) << "category: " << "testframework\n"
  8126. << std::left << std::setw(16) << "framework: " << "Catch Test\n"
  8127. << std::left << std::setw(16) << "version: " << libraryVersion() << std::endl;
  8128. }
  8129. int Session::applyCommandLine( int argc, char const * const * argv ) {
  8130. if( m_startupExceptions )
  8131. return 1;
  8132. auto result = m_cli.parse( clara::Args( argc, argv ) );
  8133. if( !result ) {
  8134. Catch::cerr()
  8135. << Colour( Colour::Red )
  8136. << "\nError(s) in input:\n"
  8137. << Column( result.errorMessage() ).indent( 2 )
  8138. << "\n\n";
  8139. Catch::cerr() << "Run with -? for usage\n" << std::endl;
  8140. return MaxExitCode;
  8141. }
  8142. if( m_configData.showHelp )
  8143. showHelp();
  8144. if( m_configData.libIdentify )
  8145. libIdentify();
  8146. m_config.reset();
  8147. return 0;
  8148. }
  8149. void Session::useConfigData( ConfigData const& configData ) {
  8150. m_configData = configData;
  8151. m_config.reset();
  8152. }
  8153. int Session::run( int argc, char* argv[] ) {
  8154. if( m_startupExceptions )
  8155. return 1;
  8156. int returnCode = applyCommandLine( argc, argv );
  8157. if( returnCode == 0 )
  8158. returnCode = run();
  8159. return returnCode;
  8160. }
  8161. #if defined(CATCH_CONFIG_WCHAR) && defined(WIN32) && defined(UNICODE)
  8162. int Session::run( int argc, wchar_t* const argv[] ) {
  8163. char **utf8Argv = new char *[ argc ];
  8164. for ( int i = 0; i < argc; ++i ) {
  8165. int bufSize = WideCharToMultiByte( CP_UTF8, 0, argv[i], -1, NULL, 0, NULL, NULL );
  8166. utf8Argv[ i ] = new char[ bufSize ];
  8167. WideCharToMultiByte( CP_UTF8, 0, argv[i], -1, utf8Argv[i], bufSize, NULL, NULL );
  8168. }
  8169. int returnCode = run( argc, utf8Argv );
  8170. for ( int i = 0; i < argc; ++i )
  8171. delete [] utf8Argv[ i ];
  8172. delete [] utf8Argv;
  8173. return returnCode;
  8174. }
  8175. #endif
  8176. int Session::run() {
  8177. if( ( m_configData.waitForKeypress & WaitForKeypress::BeforeStart ) != 0 ) {
  8178. Catch::cout() << "...waiting for enter/ return before starting" << std::endl;
  8179. static_cast<void>(std::getchar());
  8180. }
  8181. int exitCode = runInternal();
  8182. if( ( m_configData.waitForKeypress & WaitForKeypress::BeforeExit ) != 0 ) {
  8183. Catch::cout() << "...waiting for enter/ return before exiting, with code: " << exitCode << std::endl;
  8184. static_cast<void>(std::getchar());
  8185. }
  8186. return exitCode;
  8187. }
  8188. clara::Parser const& Session::cli() const {
  8189. return m_cli;
  8190. }
  8191. void Session::cli( clara::Parser const& newParser ) {
  8192. m_cli = newParser;
  8193. }
  8194. ConfigData& Session::configData() {
  8195. return m_configData;
  8196. }
  8197. Config& Session::config() {
  8198. if( !m_config )
  8199. m_config = std::make_shared<Config>( m_configData );
  8200. return *m_config;
  8201. }
  8202. int Session::runInternal() {
  8203. if( m_startupExceptions )
  8204. return 1;
  8205. if (m_configData.showHelp || m_configData.libIdentify) {
  8206. return 0;
  8207. }
  8208. CATCH_TRY {
  8209. config(); // Force config to be constructed
  8210. seedRng( *m_config );
  8211. if( m_configData.filenamesAsTags )
  8212. applyFilenamesAsTags( *m_config );
  8213. // Handle list request
  8214. if( Option<std::size_t> listed = list( config() ) )
  8215. return static_cast<int>( *listed );
  8216. auto totals = runTests( m_config );
  8217. // Note that on unices only the lower 8 bits are usually used, clamping
  8218. // the return value to 255 prevents false negative when some multiple
  8219. // of 256 tests has failed
  8220. return (std::min) (MaxExitCode, (std::max) (totals.error, static_cast<int>(totals.assertions.failed)));
  8221. }
  8222. #if !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
  8223. catch( std::exception& ex ) {
  8224. Catch::cerr() << ex.what() << std::endl;
  8225. return MaxExitCode;
  8226. }
  8227. #endif
  8228. }
  8229. } // end namespace Catch
  8230. // end catch_session.cpp
  8231. // start catch_singletons.cpp
  8232. #include <vector>
  8233. namespace Catch {
  8234. namespace {
  8235. static auto getSingletons() -> std::vector<ISingleton*>*& {
  8236. static std::vector<ISingleton*>* g_singletons = nullptr;
  8237. if( !g_singletons )
  8238. g_singletons = new std::vector<ISingleton*>();
  8239. return g_singletons;
  8240. }
  8241. }
  8242. ISingleton::~ISingleton() {}
  8243. void addSingleton(ISingleton* singleton ) {
  8244. getSingletons()->push_back( singleton );
  8245. }
  8246. void cleanupSingletons() {
  8247. auto& singletons = getSingletons();
  8248. for( auto singleton : *singletons )
  8249. delete singleton;
  8250. delete singletons;
  8251. singletons = nullptr;
  8252. }
  8253. } // namespace Catch
  8254. // end catch_singletons.cpp
  8255. // start catch_startup_exception_registry.cpp
  8256. namespace Catch {
  8257. void StartupExceptionRegistry::add( std::exception_ptr const& exception ) noexcept {
  8258. CATCH_TRY {
  8259. m_exceptions.push_back(exception);
  8260. } CATCH_CATCH_ALL {
  8261. // If we run out of memory during start-up there's really not a lot more we can do about it
  8262. std::terminate();
  8263. }
  8264. }
  8265. std::vector<std::exception_ptr> const& StartupExceptionRegistry::getExceptions() const noexcept {
  8266. return m_exceptions;
  8267. }
  8268. } // end namespace Catch
  8269. // end catch_startup_exception_registry.cpp
  8270. // start catch_stream.cpp
  8271. #include <cstdio>
  8272. #include <iostream>
  8273. #include <fstream>
  8274. #include <sstream>
  8275. #include <vector>
  8276. #include <memory>
  8277. namespace Catch {
  8278. Catch::IStream::~IStream() = default;
  8279. namespace detail { namespace {
  8280. template<typename WriterF, std::size_t bufferSize=256>
  8281. class StreamBufImpl : public std::streambuf {
  8282. char data[bufferSize];
  8283. WriterF m_writer;
  8284. public:
  8285. StreamBufImpl() {
  8286. setp( data, data + sizeof(data) );
  8287. }
  8288. ~StreamBufImpl() noexcept {
  8289. StreamBufImpl::sync();
  8290. }
  8291. private:
  8292. int overflow( int c ) override {
  8293. sync();
  8294. if( c != EOF ) {
  8295. if( pbase() == epptr() )
  8296. m_writer( std::string( 1, static_cast<char>( c ) ) );
  8297. else
  8298. sputc( static_cast<char>( c ) );
  8299. }
  8300. return 0;
  8301. }
  8302. int sync() override {
  8303. if( pbase() != pptr() ) {
  8304. m_writer( std::string( pbase(), static_cast<std::string::size_type>( pptr() - pbase() ) ) );
  8305. setp( pbase(), epptr() );
  8306. }
  8307. return 0;
  8308. }
  8309. };
  8310. ///////////////////////////////////////////////////////////////////////////
  8311. struct OutputDebugWriter {
  8312. void operator()( std::string const&str ) {
  8313. writeToDebugConsole( str );
  8314. }
  8315. };
  8316. ///////////////////////////////////////////////////////////////////////////
  8317. class FileStream : public IStream {
  8318. mutable std::ofstream m_ofs;
  8319. public:
  8320. FileStream( StringRef filename ) {
  8321. m_ofs.open( filename.c_str() );
  8322. CATCH_ENFORCE( !m_ofs.fail(), "Unable to open file: '" << filename << "'" );
  8323. }
  8324. ~FileStream() override = default;
  8325. public: // IStream
  8326. std::ostream& stream() const override {
  8327. return m_ofs;
  8328. }
  8329. };
  8330. ///////////////////////////////////////////////////////////////////////////
  8331. class CoutStream : public IStream {
  8332. mutable std::ostream m_os;
  8333. public:
  8334. // Store the streambuf from cout up-front because
  8335. // cout may get redirected when running tests
  8336. CoutStream() : m_os( Catch::cout().rdbuf() ) {}
  8337. ~CoutStream() override = default;
  8338. public: // IStream
  8339. std::ostream& stream() const override { return m_os; }
  8340. };
  8341. ///////////////////////////////////////////////////////////////////////////
  8342. class DebugOutStream : public IStream {
  8343. std::unique_ptr<StreamBufImpl<OutputDebugWriter>> m_streamBuf;
  8344. mutable std::ostream m_os;
  8345. public:
  8346. DebugOutStream()
  8347. : m_streamBuf( new StreamBufImpl<OutputDebugWriter>() ),
  8348. m_os( m_streamBuf.get() )
  8349. {}
  8350. ~DebugOutStream() override = default;
  8351. public: // IStream
  8352. std::ostream& stream() const override { return m_os; }
  8353. };
  8354. }} // namespace anon::detail
  8355. ///////////////////////////////////////////////////////////////////////////
  8356. auto makeStream( StringRef const &filename ) -> IStream const* {
  8357. if( filename.empty() )
  8358. return new detail::CoutStream();
  8359. else if( filename[0] == '%' ) {
  8360. if( filename == "%debug" )
  8361. return new detail::DebugOutStream();
  8362. else
  8363. CATCH_ERROR( "Unrecognised stream: '" << filename << "'" );
  8364. }
  8365. else
  8366. return new detail::FileStream( filename );
  8367. }
  8368. // This class encapsulates the idea of a pool of ostringstreams that can be reused.
  8369. struct StringStreams {
  8370. std::vector<std::unique_ptr<std::ostringstream>> m_streams;
  8371. std::vector<std::size_t> m_unused;
  8372. std::ostringstream m_referenceStream; // Used for copy state/ flags from
  8373. auto add() -> std::size_t {
  8374. if( m_unused.empty() ) {
  8375. m_streams.push_back( std::unique_ptr<std::ostringstream>( new std::ostringstream ) );
  8376. return m_streams.size()-1;
  8377. }
  8378. else {
  8379. auto index = m_unused.back();
  8380. m_unused.pop_back();
  8381. return index;
  8382. }
  8383. }
  8384. void release( std::size_t index ) {
  8385. m_streams[index]->copyfmt( m_referenceStream ); // Restore initial flags and other state
  8386. m_unused.push_back(index);
  8387. }
  8388. };
  8389. ReusableStringStream::ReusableStringStream()
  8390. : m_index( Singleton<StringStreams>::getMutable().add() ),
  8391. m_oss( Singleton<StringStreams>::getMutable().m_streams[m_index].get() )
  8392. {}
  8393. ReusableStringStream::~ReusableStringStream() {
  8394. static_cast<std::ostringstream*>( m_oss )->str("");
  8395. m_oss->clear();
  8396. Singleton<StringStreams>::getMutable().release( m_index );
  8397. }
  8398. auto ReusableStringStream::str() const -> std::string {
  8399. return static_cast<std::ostringstream*>( m_oss )->str();
  8400. }
  8401. ///////////////////////////////////////////////////////////////////////////
  8402. #ifndef CATCH_CONFIG_NOSTDOUT // If you #define this you must implement these functions
  8403. std::ostream& cout() { return std::cout; }
  8404. std::ostream& cerr() { return std::cerr; }
  8405. std::ostream& clog() { return std::clog; }
  8406. #endif
  8407. }
  8408. // end catch_stream.cpp
  8409. // start catch_string_manip.cpp
  8410. #include <algorithm>
  8411. #include <ostream>
  8412. #include <cstring>
  8413. #include <cctype>
  8414. namespace Catch {
  8415. namespace {
  8416. char toLowerCh(char c) {
  8417. return static_cast<char>( std::tolower( c ) );
  8418. }
  8419. }
  8420. bool startsWith( std::string const& s, std::string const& prefix ) {
  8421. return s.size() >= prefix.size() && std::equal(prefix.begin(), prefix.end(), s.begin());
  8422. }
  8423. bool startsWith( std::string const& s, char prefix ) {
  8424. return !s.empty() && s[0] == prefix;
  8425. }
  8426. bool endsWith( std::string const& s, std::string const& suffix ) {
  8427. return s.size() >= suffix.size() && std::equal(suffix.rbegin(), suffix.rend(), s.rbegin());
  8428. }
  8429. bool endsWith( std::string const& s, char suffix ) {
  8430. return !s.empty() && s[s.size()-1] == suffix;
  8431. }
  8432. bool contains( std::string const& s, std::string const& infix ) {
  8433. return s.find( infix ) != std::string::npos;
  8434. }
  8435. void toLowerInPlace( std::string& s ) {
  8436. std::transform( s.begin(), s.end(), s.begin(), toLowerCh );
  8437. }
  8438. std::string toLower( std::string const& s ) {
  8439. std::string lc = s;
  8440. toLowerInPlace( lc );
  8441. return lc;
  8442. }
  8443. std::string trim( std::string const& str ) {
  8444. static char const* whitespaceChars = "\n\r\t ";
  8445. std::string::size_type start = str.find_first_not_of( whitespaceChars );
  8446. std::string::size_type end = str.find_last_not_of( whitespaceChars );
  8447. return start != std::string::npos ? str.substr( start, 1+end-start ) : std::string();
  8448. }
  8449. bool replaceInPlace( std::string& str, std::string const& replaceThis, std::string const& withThis ) {
  8450. bool replaced = false;
  8451. std::size_t i = str.find( replaceThis );
  8452. while( i != std::string::npos ) {
  8453. replaced = true;
  8454. str = str.substr( 0, i ) + withThis + str.substr( i+replaceThis.size() );
  8455. if( i < str.size()-withThis.size() )
  8456. i = str.find( replaceThis, i+withThis.size() );
  8457. else
  8458. i = std::string::npos;
  8459. }
  8460. return replaced;
  8461. }
  8462. pluralise::pluralise( std::size_t count, std::string const& label )
  8463. : m_count( count ),
  8464. m_label( label )
  8465. {}
  8466. std::ostream& operator << ( std::ostream& os, pluralise const& pluraliser ) {
  8467. os << pluraliser.m_count << ' ' << pluraliser.m_label;
  8468. if( pluraliser.m_count != 1 )
  8469. os << 's';
  8470. return os;
  8471. }
  8472. }
  8473. // end catch_string_manip.cpp
  8474. // start catch_stringref.cpp
  8475. #if defined(__clang__)
  8476. # pragma clang diagnostic push
  8477. # pragma clang diagnostic ignored "-Wexit-time-destructors"
  8478. #endif
  8479. #include <ostream>
  8480. #include <cstring>
  8481. #include <cstdint>
  8482. namespace {
  8483. const uint32_t byte_2_lead = 0xC0;
  8484. const uint32_t byte_3_lead = 0xE0;
  8485. const uint32_t byte_4_lead = 0xF0;
  8486. }
  8487. namespace Catch {
  8488. StringRef::StringRef( char const* rawChars ) noexcept
  8489. : StringRef( rawChars, static_cast<StringRef::size_type>(std::strlen(rawChars) ) )
  8490. {}
  8491. StringRef::operator std::string() const {
  8492. return std::string( m_start, m_size );
  8493. }
  8494. void StringRef::swap( StringRef& other ) noexcept {
  8495. std::swap( m_start, other.m_start );
  8496. std::swap( m_size, other.m_size );
  8497. std::swap( m_data, other.m_data );
  8498. }
  8499. auto StringRef::c_str() const -> char const* {
  8500. if( isSubstring() )
  8501. const_cast<StringRef*>( this )->takeOwnership();
  8502. return m_start;
  8503. }
  8504. auto StringRef::currentData() const noexcept -> char const* {
  8505. return m_start;
  8506. }
  8507. auto StringRef::isOwned() const noexcept -> bool {
  8508. return m_data != nullptr;
  8509. }
  8510. auto StringRef::isSubstring() const noexcept -> bool {
  8511. return m_start[m_size] != '\0';
  8512. }
  8513. void StringRef::takeOwnership() {
  8514. if( !isOwned() ) {
  8515. m_data = new char[m_size+1];
  8516. memcpy( m_data, m_start, m_size );
  8517. m_data[m_size] = '\0';
  8518. m_start = m_data;
  8519. }
  8520. }
  8521. auto StringRef::substr( size_type start, size_type size ) const noexcept -> StringRef {
  8522. if( start < m_size )
  8523. return StringRef( m_start+start, size );
  8524. else
  8525. return StringRef();
  8526. }
  8527. auto StringRef::operator == ( StringRef const& other ) const noexcept -> bool {
  8528. return
  8529. size() == other.size() &&
  8530. (std::strncmp( m_start, other.m_start, size() ) == 0);
  8531. }
  8532. auto StringRef::operator != ( StringRef const& other ) const noexcept -> bool {
  8533. return !operator==( other );
  8534. }
  8535. auto StringRef::operator[](size_type index) const noexcept -> char {
  8536. return m_start[index];
  8537. }
  8538. auto StringRef::numberOfCharacters() const noexcept -> size_type {
  8539. size_type noChars = m_size;
  8540. // Make adjustments for uft encodings
  8541. for( size_type i=0; i < m_size; ++i ) {
  8542. char c = m_start[i];
  8543. if( ( c & byte_2_lead ) == byte_2_lead ) {
  8544. noChars--;
  8545. if (( c & byte_3_lead ) == byte_3_lead )
  8546. noChars--;
  8547. if( ( c & byte_4_lead ) == byte_4_lead )
  8548. noChars--;
  8549. }
  8550. }
  8551. return noChars;
  8552. }
  8553. auto operator + ( StringRef const& lhs, StringRef const& rhs ) -> std::string {
  8554. std::string str;
  8555. str.reserve( lhs.size() + rhs.size() );
  8556. str += lhs;
  8557. str += rhs;
  8558. return str;
  8559. }
  8560. auto operator + ( StringRef const& lhs, const char* rhs ) -> std::string {
  8561. return std::string( lhs ) + std::string( rhs );
  8562. }
  8563. auto operator + ( char const* lhs, StringRef const& rhs ) -> std::string {
  8564. return std::string( lhs ) + std::string( rhs );
  8565. }
  8566. auto operator << ( std::ostream& os, StringRef const& str ) -> std::ostream& {
  8567. return os.write(str.currentData(), str.size());
  8568. }
  8569. auto operator+=( std::string& lhs, StringRef const& rhs ) -> std::string& {
  8570. lhs.append(rhs.currentData(), rhs.size());
  8571. return lhs;
  8572. }
  8573. } // namespace Catch
  8574. #if defined(__clang__)
  8575. # pragma clang diagnostic pop
  8576. #endif
  8577. // end catch_stringref.cpp
  8578. // start catch_tag_alias.cpp
  8579. namespace Catch {
  8580. TagAlias::TagAlias(std::string const & _tag, SourceLineInfo _lineInfo): tag(_tag), lineInfo(_lineInfo) {}
  8581. }
  8582. // end catch_tag_alias.cpp
  8583. // start catch_tag_alias_autoregistrar.cpp
  8584. namespace Catch {
  8585. RegistrarForTagAliases::RegistrarForTagAliases(char const* alias, char const* tag, SourceLineInfo const& lineInfo) {
  8586. CATCH_TRY {
  8587. getMutableRegistryHub().registerTagAlias(alias, tag, lineInfo);
  8588. } CATCH_CATCH_ALL {
  8589. // Do not throw when constructing global objects, instead register the exception to be processed later
  8590. getMutableRegistryHub().registerStartupException();
  8591. }
  8592. }
  8593. }
  8594. // end catch_tag_alias_autoregistrar.cpp
  8595. // start catch_tag_alias_registry.cpp
  8596. #include <sstream>
  8597. namespace Catch {
  8598. TagAliasRegistry::~TagAliasRegistry() {}
  8599. TagAlias const* TagAliasRegistry::find( std::string const& alias ) const {
  8600. auto it = m_registry.find( alias );
  8601. if( it != m_registry.end() )
  8602. return &(it->second);
  8603. else
  8604. return nullptr;
  8605. }
  8606. std::string TagAliasRegistry::expandAliases( std::string const& unexpandedTestSpec ) const {
  8607. std::string expandedTestSpec = unexpandedTestSpec;
  8608. for( auto const& registryKvp : m_registry ) {
  8609. std::size_t pos = expandedTestSpec.find( registryKvp.first );
  8610. if( pos != std::string::npos ) {
  8611. expandedTestSpec = expandedTestSpec.substr( 0, pos ) +
  8612. registryKvp.second.tag +
  8613. expandedTestSpec.substr( pos + registryKvp.first.size() );
  8614. }
  8615. }
  8616. return expandedTestSpec;
  8617. }
  8618. void TagAliasRegistry::add( std::string const& alias, std::string const& tag, SourceLineInfo const& lineInfo ) {
  8619. CATCH_ENFORCE( startsWith(alias, "[@") && endsWith(alias, ']'),
  8620. "error: tag alias, '" << alias << "' is not of the form [@alias name].\n" << lineInfo );
  8621. CATCH_ENFORCE( m_registry.insert(std::make_pair(alias, TagAlias(tag, lineInfo))).second,
  8622. "error: tag alias, '" << alias << "' already registered.\n"
  8623. << "\tFirst seen at: " << find(alias)->lineInfo << "\n"
  8624. << "\tRedefined at: " << lineInfo );
  8625. }
  8626. ITagAliasRegistry::~ITagAliasRegistry() {}
  8627. ITagAliasRegistry const& ITagAliasRegistry::get() {
  8628. return getRegistryHub().getTagAliasRegistry();
  8629. }
  8630. } // end namespace Catch
  8631. // end catch_tag_alias_registry.cpp
  8632. // start catch_test_case_info.cpp
  8633. #include <cctype>
  8634. #include <exception>
  8635. #include <algorithm>
  8636. #include <sstream>
  8637. namespace Catch {
  8638. namespace {
  8639. TestCaseInfo::SpecialProperties parseSpecialTag( std::string const& tag ) {
  8640. if( startsWith( tag, '.' ) ||
  8641. tag == "!hide" )
  8642. return TestCaseInfo::IsHidden;
  8643. else if( tag == "!throws" )
  8644. return TestCaseInfo::Throws;
  8645. else if( tag == "!shouldfail" )
  8646. return TestCaseInfo::ShouldFail;
  8647. else if( tag == "!mayfail" )
  8648. return TestCaseInfo::MayFail;
  8649. else if( tag == "!nonportable" )
  8650. return TestCaseInfo::NonPortable;
  8651. else if( tag == "!benchmark" )
  8652. return static_cast<TestCaseInfo::SpecialProperties>( TestCaseInfo::Benchmark | TestCaseInfo::IsHidden );
  8653. else
  8654. return TestCaseInfo::None;
  8655. }
  8656. bool isReservedTag( std::string const& tag ) {
  8657. return parseSpecialTag( tag ) == TestCaseInfo::None && tag.size() > 0 && !std::isalnum( static_cast<unsigned char>(tag[0]) );
  8658. }
  8659. void enforceNotReservedTag( std::string const& tag, SourceLineInfo const& _lineInfo ) {
  8660. CATCH_ENFORCE( !isReservedTag(tag),
  8661. "Tag name: [" << tag << "] is not allowed.\n"
  8662. << "Tag names starting with non alpha-numeric characters are reserved\n"
  8663. << _lineInfo );
  8664. }
  8665. }
  8666. TestCase makeTestCase( ITestInvoker* _testCase,
  8667. std::string const& _className,
  8668. NameAndTags const& nameAndTags,
  8669. SourceLineInfo const& _lineInfo )
  8670. {
  8671. bool isHidden = false;
  8672. // Parse out tags
  8673. std::vector<std::string> tags;
  8674. std::string desc, tag;
  8675. bool inTag = false;
  8676. std::string _descOrTags = nameAndTags.tags;
  8677. for (char c : _descOrTags) {
  8678. if( !inTag ) {
  8679. if( c == '[' )
  8680. inTag = true;
  8681. else
  8682. desc += c;
  8683. }
  8684. else {
  8685. if( c == ']' ) {
  8686. TestCaseInfo::SpecialProperties prop = parseSpecialTag( tag );
  8687. if( ( prop & TestCaseInfo::IsHidden ) != 0 )
  8688. isHidden = true;
  8689. else if( prop == TestCaseInfo::None )
  8690. enforceNotReservedTag( tag, _lineInfo );
  8691. tags.push_back( tag );
  8692. tag.clear();
  8693. inTag = false;
  8694. }
  8695. else
  8696. tag += c;
  8697. }
  8698. }
  8699. if( isHidden ) {
  8700. tags.push_back( "." );
  8701. }
  8702. TestCaseInfo info( nameAndTags.name, _className, desc, tags, _lineInfo );
  8703. return TestCase( _testCase, std::move(info) );
  8704. }
  8705. void setTags( TestCaseInfo& testCaseInfo, std::vector<std::string> tags ) {
  8706. std::sort(begin(tags), end(tags));
  8707. tags.erase(std::unique(begin(tags), end(tags)), end(tags));
  8708. testCaseInfo.lcaseTags.clear();
  8709. for( auto const& tag : tags ) {
  8710. std::string lcaseTag = toLower( tag );
  8711. testCaseInfo.properties = static_cast<TestCaseInfo::SpecialProperties>( testCaseInfo.properties | parseSpecialTag( lcaseTag ) );
  8712. testCaseInfo.lcaseTags.push_back( lcaseTag );
  8713. }
  8714. testCaseInfo.tags = std::move(tags);
  8715. }
  8716. TestCaseInfo::TestCaseInfo( std::string const& _name,
  8717. std::string const& _className,
  8718. std::string const& _description,
  8719. std::vector<std::string> const& _tags,
  8720. SourceLineInfo const& _lineInfo )
  8721. : name( _name ),
  8722. className( _className ),
  8723. description( _description ),
  8724. lineInfo( _lineInfo ),
  8725. properties( None )
  8726. {
  8727. setTags( *this, _tags );
  8728. }
  8729. bool TestCaseInfo::isHidden() const {
  8730. return ( properties & IsHidden ) != 0;
  8731. }
  8732. bool TestCaseInfo::throws() const {
  8733. return ( properties & Throws ) != 0;
  8734. }
  8735. bool TestCaseInfo::okToFail() const {
  8736. return ( properties & (ShouldFail | MayFail ) ) != 0;
  8737. }
  8738. bool TestCaseInfo::expectedToFail() const {
  8739. return ( properties & (ShouldFail ) ) != 0;
  8740. }
  8741. std::string TestCaseInfo::tagsAsString() const {
  8742. std::string ret;
  8743. // '[' and ']' per tag
  8744. std::size_t full_size = 2 * tags.size();
  8745. for (const auto& tag : tags) {
  8746. full_size += tag.size();
  8747. }
  8748. ret.reserve(full_size);
  8749. for (const auto& tag : tags) {
  8750. ret.push_back('[');
  8751. ret.append(tag);
  8752. ret.push_back(']');
  8753. }
  8754. return ret;
  8755. }
  8756. TestCase::TestCase( ITestInvoker* testCase, TestCaseInfo&& info ) : TestCaseInfo( std::move(info) ), test( testCase ) {}
  8757. TestCase TestCase::withName( std::string const& _newName ) const {
  8758. TestCase other( *this );
  8759. other.name = _newName;
  8760. return other;
  8761. }
  8762. void TestCase::invoke() const {
  8763. test->invoke();
  8764. }
  8765. bool TestCase::operator == ( TestCase const& other ) const {
  8766. return test.get() == other.test.get() &&
  8767. name == other.name &&
  8768. className == other.className;
  8769. }
  8770. bool TestCase::operator < ( TestCase const& other ) const {
  8771. return name < other.name;
  8772. }
  8773. TestCaseInfo const& TestCase::getTestCaseInfo() const
  8774. {
  8775. return *this;
  8776. }
  8777. } // end namespace Catch
  8778. // end catch_test_case_info.cpp
  8779. // start catch_test_case_registry_impl.cpp
  8780. #include <sstream>
  8781. namespace Catch {
  8782. std::vector<TestCase> sortTests( IConfig const& config, std::vector<TestCase> const& unsortedTestCases ) {
  8783. std::vector<TestCase> sorted = unsortedTestCases;
  8784. switch( config.runOrder() ) {
  8785. case RunTests::InLexicographicalOrder:
  8786. std::sort( sorted.begin(), sorted.end() );
  8787. break;
  8788. case RunTests::InRandomOrder:
  8789. seedRng( config );
  8790. std::shuffle( sorted.begin(), sorted.end(), rng() );
  8791. break;
  8792. case RunTests::InDeclarationOrder:
  8793. // already in declaration order
  8794. break;
  8795. }
  8796. return sorted;
  8797. }
  8798. bool matchTest( TestCase const& testCase, TestSpec const& testSpec, IConfig const& config ) {
  8799. return testSpec.matches( testCase ) && ( config.allowThrows() || !testCase.throws() );
  8800. }
  8801. void enforceNoDuplicateTestCases( std::vector<TestCase> const& functions ) {
  8802. std::set<TestCase> seenFunctions;
  8803. for( auto const& function : functions ) {
  8804. auto prev = seenFunctions.insert( function );
  8805. CATCH_ENFORCE( prev.second,
  8806. "error: TEST_CASE( \"" << function.name << "\" ) already defined.\n"
  8807. << "\tFirst seen at " << prev.first->getTestCaseInfo().lineInfo << "\n"
  8808. << "\tRedefined at " << function.getTestCaseInfo().lineInfo );
  8809. }
  8810. }
  8811. std::vector<TestCase> filterTests( std::vector<TestCase> const& testCases, TestSpec const& testSpec, IConfig const& config ) {
  8812. std::vector<TestCase> filtered;
  8813. filtered.reserve( testCases.size() );
  8814. for( auto const& testCase : testCases )
  8815. if( matchTest( testCase, testSpec, config ) )
  8816. filtered.push_back( testCase );
  8817. return filtered;
  8818. }
  8819. std::vector<TestCase> const& getAllTestCasesSorted( IConfig const& config ) {
  8820. return getRegistryHub().getTestCaseRegistry().getAllTestsSorted( config );
  8821. }
  8822. void TestRegistry::registerTest( TestCase const& testCase ) {
  8823. std::string name = testCase.getTestCaseInfo().name;
  8824. if( name.empty() ) {
  8825. ReusableStringStream rss;
  8826. rss << "Anonymous test case " << ++m_unnamedCount;
  8827. return registerTest( testCase.withName( rss.str() ) );
  8828. }
  8829. m_functions.push_back( testCase );
  8830. }
  8831. std::vector<TestCase> const& TestRegistry::getAllTests() const {
  8832. return m_functions;
  8833. }
  8834. std::vector<TestCase> const& TestRegistry::getAllTestsSorted( IConfig const& config ) const {
  8835. if( m_sortedFunctions.empty() )
  8836. enforceNoDuplicateTestCases( m_functions );
  8837. if( m_currentSortOrder != config.runOrder() || m_sortedFunctions.empty() ) {
  8838. m_sortedFunctions = sortTests( config, m_functions );
  8839. m_currentSortOrder = config.runOrder();
  8840. }
  8841. return m_sortedFunctions;
  8842. }
  8843. ///////////////////////////////////////////////////////////////////////////
  8844. TestInvokerAsFunction::TestInvokerAsFunction( void(*testAsFunction)() ) noexcept : m_testAsFunction( testAsFunction ) {}
  8845. void TestInvokerAsFunction::invoke() const {
  8846. m_testAsFunction();
  8847. }
  8848. std::string extractClassName( StringRef const& classOrQualifiedMethodName ) {
  8849. std::string className = classOrQualifiedMethodName;
  8850. if( startsWith( className, '&' ) )
  8851. {
  8852. std::size_t lastColons = className.rfind( "::" );
  8853. std::size_t penultimateColons = className.rfind( "::", lastColons-1 );
  8854. if( penultimateColons == std::string::npos )
  8855. penultimateColons = 1;
  8856. className = className.substr( penultimateColons, lastColons-penultimateColons );
  8857. }
  8858. return className;
  8859. }
  8860. } // end namespace Catch
  8861. // end catch_test_case_registry_impl.cpp
  8862. // start catch_test_case_tracker.cpp
  8863. #include <algorithm>
  8864. #include <cassert>
  8865. #include <stdexcept>
  8866. #include <memory>
  8867. #include <sstream>
  8868. #if defined(__clang__)
  8869. # pragma clang diagnostic push
  8870. # pragma clang diagnostic ignored "-Wexit-time-destructors"
  8871. #endif
  8872. namespace Catch {
  8873. namespace TestCaseTracking {
  8874. NameAndLocation::NameAndLocation( std::string const& _name, SourceLineInfo const& _location )
  8875. : name( _name ),
  8876. location( _location )
  8877. {}
  8878. ITracker::~ITracker() = default;
  8879. TrackerContext& TrackerContext::instance() {
  8880. static TrackerContext s_instance;
  8881. return s_instance;
  8882. }
  8883. ITracker& TrackerContext::startRun() {
  8884. m_rootTracker = std::make_shared<SectionTracker>( NameAndLocation( "{root}", CATCH_INTERNAL_LINEINFO ), *this, nullptr );
  8885. m_currentTracker = nullptr;
  8886. m_runState = Executing;
  8887. return *m_rootTracker;
  8888. }
  8889. void TrackerContext::endRun() {
  8890. m_rootTracker.reset();
  8891. m_currentTracker = nullptr;
  8892. m_runState = NotStarted;
  8893. }
  8894. void TrackerContext::startCycle() {
  8895. m_currentTracker = m_rootTracker.get();
  8896. m_runState = Executing;
  8897. }
  8898. void TrackerContext::completeCycle() {
  8899. m_runState = CompletedCycle;
  8900. }
  8901. bool TrackerContext::completedCycle() const {
  8902. return m_runState == CompletedCycle;
  8903. }
  8904. ITracker& TrackerContext::currentTracker() {
  8905. return *m_currentTracker;
  8906. }
  8907. void TrackerContext::setCurrentTracker( ITracker* tracker ) {
  8908. m_currentTracker = tracker;
  8909. }
  8910. TrackerBase::TrackerBase( NameAndLocation const& nameAndLocation, TrackerContext& ctx, ITracker* parent )
  8911. : m_nameAndLocation( nameAndLocation ),
  8912. m_ctx( ctx ),
  8913. m_parent( parent )
  8914. {}
  8915. NameAndLocation const& TrackerBase::nameAndLocation() const {
  8916. return m_nameAndLocation;
  8917. }
  8918. bool TrackerBase::isComplete() const {
  8919. return m_runState == CompletedSuccessfully || m_runState == Failed;
  8920. }
  8921. bool TrackerBase::isSuccessfullyCompleted() const {
  8922. return m_runState == CompletedSuccessfully;
  8923. }
  8924. bool TrackerBase::isOpen() const {
  8925. return m_runState != NotStarted && !isComplete();
  8926. }
  8927. bool TrackerBase::hasChildren() const {
  8928. return !m_children.empty();
  8929. }
  8930. void TrackerBase::addChild( ITrackerPtr const& child ) {
  8931. m_children.push_back( child );
  8932. }
  8933. ITrackerPtr TrackerBase::findChild( NameAndLocation const& nameAndLocation ) {
  8934. auto it = std::find_if( m_children.begin(), m_children.end(),
  8935. [&nameAndLocation]( ITrackerPtr const& tracker ){
  8936. return
  8937. tracker->nameAndLocation().location == nameAndLocation.location &&
  8938. tracker->nameAndLocation().name == nameAndLocation.name;
  8939. } );
  8940. return( it != m_children.end() )
  8941. ? *it
  8942. : nullptr;
  8943. }
  8944. ITracker& TrackerBase::parent() {
  8945. assert( m_parent ); // Should always be non-null except for root
  8946. return *m_parent;
  8947. }
  8948. void TrackerBase::openChild() {
  8949. if( m_runState != ExecutingChildren ) {
  8950. m_runState = ExecutingChildren;
  8951. if( m_parent )
  8952. m_parent->openChild();
  8953. }
  8954. }
  8955. bool TrackerBase::isSectionTracker() const { return false; }
  8956. bool TrackerBase::isIndexTracker() const { return false; }
  8957. void TrackerBase::open() {
  8958. m_runState = Executing;
  8959. moveToThis();
  8960. if( m_parent )
  8961. m_parent->openChild();
  8962. }
  8963. void TrackerBase::close() {
  8964. // Close any still open children (e.g. generators)
  8965. while( &m_ctx.currentTracker() != this )
  8966. m_ctx.currentTracker().close();
  8967. switch( m_runState ) {
  8968. case NeedsAnotherRun:
  8969. break;
  8970. case Executing:
  8971. m_runState = CompletedSuccessfully;
  8972. break;
  8973. case ExecutingChildren:
  8974. if( m_children.empty() || m_children.back()->isComplete() )
  8975. m_runState = CompletedSuccessfully;
  8976. break;
  8977. case NotStarted:
  8978. case CompletedSuccessfully:
  8979. case Failed:
  8980. CATCH_INTERNAL_ERROR( "Illogical state: " << m_runState );
  8981. default:
  8982. CATCH_INTERNAL_ERROR( "Unknown state: " << m_runState );
  8983. }
  8984. moveToParent();
  8985. m_ctx.completeCycle();
  8986. }
  8987. void TrackerBase::fail() {
  8988. m_runState = Failed;
  8989. if( m_parent )
  8990. m_parent->markAsNeedingAnotherRun();
  8991. moveToParent();
  8992. m_ctx.completeCycle();
  8993. }
  8994. void TrackerBase::markAsNeedingAnotherRun() {
  8995. m_runState = NeedsAnotherRun;
  8996. }
  8997. void TrackerBase::moveToParent() {
  8998. assert( m_parent );
  8999. m_ctx.setCurrentTracker( m_parent );
  9000. }
  9001. void TrackerBase::moveToThis() {
  9002. m_ctx.setCurrentTracker( this );
  9003. }
  9004. SectionTracker::SectionTracker( NameAndLocation const& nameAndLocation, TrackerContext& ctx, ITracker* parent )
  9005. : TrackerBase( nameAndLocation, ctx, parent )
  9006. {
  9007. if( parent ) {
  9008. while( !parent->isSectionTracker() )
  9009. parent = &parent->parent();
  9010. SectionTracker& parentSection = static_cast<SectionTracker&>( *parent );
  9011. addNextFilters( parentSection.m_filters );
  9012. }
  9013. }
  9014. bool SectionTracker::isSectionTracker() const { return true; }
  9015. SectionTracker& SectionTracker::acquire( TrackerContext& ctx, NameAndLocation const& nameAndLocation ) {
  9016. std::shared_ptr<SectionTracker> section;
  9017. ITracker& currentTracker = ctx.currentTracker();
  9018. if( ITrackerPtr childTracker = currentTracker.findChild( nameAndLocation ) ) {
  9019. assert( childTracker );
  9020. assert( childTracker->isSectionTracker() );
  9021. section = std::static_pointer_cast<SectionTracker>( childTracker );
  9022. }
  9023. else {
  9024. section = std::make_shared<SectionTracker>( nameAndLocation, ctx, &currentTracker );
  9025. currentTracker.addChild( section );
  9026. }
  9027. if( !ctx.completedCycle() )
  9028. section->tryOpen();
  9029. return *section;
  9030. }
  9031. void SectionTracker::tryOpen() {
  9032. if( !isComplete() && (m_filters.empty() || m_filters[0].empty() || m_filters[0] == m_nameAndLocation.name ) )
  9033. open();
  9034. }
  9035. void SectionTracker::addInitialFilters( std::vector<std::string> const& filters ) {
  9036. if( !filters.empty() ) {
  9037. m_filters.push_back(""); // Root - should never be consulted
  9038. m_filters.push_back(""); // Test Case - not a section filter
  9039. m_filters.insert( m_filters.end(), filters.begin(), filters.end() );
  9040. }
  9041. }
  9042. void SectionTracker::addNextFilters( std::vector<std::string> const& filters ) {
  9043. if( filters.size() > 1 )
  9044. m_filters.insert( m_filters.end(), ++filters.begin(), filters.end() );
  9045. }
  9046. IndexTracker::IndexTracker( NameAndLocation const& nameAndLocation, TrackerContext& ctx, ITracker* parent, int size )
  9047. : TrackerBase( nameAndLocation, ctx, parent ),
  9048. m_size( size )
  9049. {}
  9050. bool IndexTracker::isIndexTracker() const { return true; }
  9051. IndexTracker& IndexTracker::acquire( TrackerContext& ctx, NameAndLocation const& nameAndLocation, int size ) {
  9052. std::shared_ptr<IndexTracker> tracker;
  9053. ITracker& currentTracker = ctx.currentTracker();
  9054. if( ITrackerPtr childTracker = currentTracker.findChild( nameAndLocation ) ) {
  9055. assert( childTracker );
  9056. assert( childTracker->isIndexTracker() );
  9057. tracker = std::static_pointer_cast<IndexTracker>( childTracker );
  9058. }
  9059. else {
  9060. tracker = std::make_shared<IndexTracker>( nameAndLocation, ctx, &currentTracker, size );
  9061. currentTracker.addChild( tracker );
  9062. }
  9063. if( !ctx.completedCycle() && !tracker->isComplete() ) {
  9064. if( tracker->m_runState != ExecutingChildren && tracker->m_runState != NeedsAnotherRun )
  9065. tracker->moveNext();
  9066. tracker->open();
  9067. }
  9068. return *tracker;
  9069. }
  9070. int IndexTracker::index() const { return m_index; }
  9071. void IndexTracker::moveNext() {
  9072. m_index++;
  9073. m_children.clear();
  9074. }
  9075. void IndexTracker::close() {
  9076. TrackerBase::close();
  9077. if( m_runState == CompletedSuccessfully && m_index < m_size-1 )
  9078. m_runState = Executing;
  9079. }
  9080. } // namespace TestCaseTracking
  9081. using TestCaseTracking::ITracker;
  9082. using TestCaseTracking::TrackerContext;
  9083. using TestCaseTracking::SectionTracker;
  9084. using TestCaseTracking::IndexTracker;
  9085. } // namespace Catch
  9086. #if defined(__clang__)
  9087. # pragma clang diagnostic pop
  9088. #endif
  9089. // end catch_test_case_tracker.cpp
  9090. // start catch_test_registry.cpp
  9091. namespace Catch {
  9092. auto makeTestInvoker( void(*testAsFunction)() ) noexcept -> ITestInvoker* {
  9093. return new(std::nothrow) TestInvokerAsFunction( testAsFunction );
  9094. }
  9095. NameAndTags::NameAndTags( StringRef const& name_ , StringRef const& tags_ ) noexcept : name( name_ ), tags( tags_ ) {}
  9096. AutoReg::AutoReg( ITestInvoker* invoker, SourceLineInfo const& lineInfo, StringRef const& classOrMethod, NameAndTags const& nameAndTags ) noexcept {
  9097. CATCH_TRY {
  9098. getMutableRegistryHub()
  9099. .registerTest(
  9100. makeTestCase(
  9101. invoker,
  9102. extractClassName( classOrMethod ),
  9103. nameAndTags,
  9104. lineInfo));
  9105. } CATCH_CATCH_ALL {
  9106. // Do not throw when constructing global objects, instead register the exception to be processed later
  9107. getMutableRegistryHub().registerStartupException();
  9108. }
  9109. }
  9110. AutoReg::~AutoReg() = default;
  9111. }
  9112. // end catch_test_registry.cpp
  9113. // start catch_test_spec.cpp
  9114. #include <algorithm>
  9115. #include <string>
  9116. #include <vector>
  9117. #include <memory>
  9118. namespace Catch {
  9119. TestSpec::Pattern::~Pattern() = default;
  9120. TestSpec::NamePattern::~NamePattern() = default;
  9121. TestSpec::TagPattern::~TagPattern() = default;
  9122. TestSpec::ExcludedPattern::~ExcludedPattern() = default;
  9123. TestSpec::NamePattern::NamePattern( std::string const& name )
  9124. : m_wildcardPattern( toLower( name ), CaseSensitive::No )
  9125. {}
  9126. bool TestSpec::NamePattern::matches( TestCaseInfo const& testCase ) const {
  9127. return m_wildcardPattern.matches( toLower( testCase.name ) );
  9128. }
  9129. TestSpec::TagPattern::TagPattern( std::string const& tag ) : m_tag( toLower( tag ) ) {}
  9130. bool TestSpec::TagPattern::matches( TestCaseInfo const& testCase ) const {
  9131. return std::find(begin(testCase.lcaseTags),
  9132. end(testCase.lcaseTags),
  9133. m_tag) != end(testCase.lcaseTags);
  9134. }
  9135. TestSpec::ExcludedPattern::ExcludedPattern( PatternPtr const& underlyingPattern ) : m_underlyingPattern( underlyingPattern ) {}
  9136. bool TestSpec::ExcludedPattern::matches( TestCaseInfo const& testCase ) const { return !m_underlyingPattern->matches( testCase ); }
  9137. bool TestSpec::Filter::matches( TestCaseInfo const& testCase ) const {
  9138. // All patterns in a filter must match for the filter to be a match
  9139. for( auto const& pattern : m_patterns ) {
  9140. if( !pattern->matches( testCase ) )
  9141. return false;
  9142. }
  9143. return true;
  9144. }
  9145. bool TestSpec::hasFilters() const {
  9146. return !m_filters.empty();
  9147. }
  9148. bool TestSpec::matches( TestCaseInfo const& testCase ) const {
  9149. // A TestSpec matches if any filter matches
  9150. for( auto const& filter : m_filters )
  9151. if( filter.matches( testCase ) )
  9152. return true;
  9153. return false;
  9154. }
  9155. }
  9156. // end catch_test_spec.cpp
  9157. // start catch_test_spec_parser.cpp
  9158. namespace Catch {
  9159. TestSpecParser::TestSpecParser( ITagAliasRegistry const& tagAliases ) : m_tagAliases( &tagAliases ) {}
  9160. TestSpecParser& TestSpecParser::parse( std::string const& arg ) {
  9161. m_mode = None;
  9162. m_exclusion = false;
  9163. m_start = std::string::npos;
  9164. m_arg = m_tagAliases->expandAliases( arg );
  9165. m_escapeChars.clear();
  9166. for( m_pos = 0; m_pos < m_arg.size(); ++m_pos )
  9167. visitChar( m_arg[m_pos] );
  9168. if( m_mode == Name )
  9169. addPattern<TestSpec::NamePattern>();
  9170. return *this;
  9171. }
  9172. TestSpec TestSpecParser::testSpec() {
  9173. addFilter();
  9174. return m_testSpec;
  9175. }
  9176. void TestSpecParser::visitChar( char c ) {
  9177. if( m_mode == None ) {
  9178. switch( c ) {
  9179. case ' ': return;
  9180. case '~': m_exclusion = true; return;
  9181. case '[': return startNewMode( Tag, ++m_pos );
  9182. case '"': return startNewMode( QuotedName, ++m_pos );
  9183. case '\\': return escape();
  9184. default: startNewMode( Name, m_pos ); break;
  9185. }
  9186. }
  9187. if( m_mode == Name ) {
  9188. if( c == ',' ) {
  9189. addPattern<TestSpec::NamePattern>();
  9190. addFilter();
  9191. }
  9192. else if( c == '[' ) {
  9193. if( subString() == "exclude:" )
  9194. m_exclusion = true;
  9195. else
  9196. addPattern<TestSpec::NamePattern>();
  9197. startNewMode( Tag, ++m_pos );
  9198. }
  9199. else if( c == '\\' )
  9200. escape();
  9201. }
  9202. else if( m_mode == EscapedName )
  9203. m_mode = Name;
  9204. else if( m_mode == QuotedName && c == '"' )
  9205. addPattern<TestSpec::NamePattern>();
  9206. else if( m_mode == Tag && c == ']' )
  9207. addPattern<TestSpec::TagPattern>();
  9208. }
  9209. void TestSpecParser::startNewMode( Mode mode, std::size_t start ) {
  9210. m_mode = mode;
  9211. m_start = start;
  9212. }
  9213. void TestSpecParser::escape() {
  9214. if( m_mode == None )
  9215. m_start = m_pos;
  9216. m_mode = EscapedName;
  9217. m_escapeChars.push_back( m_pos );
  9218. }
  9219. std::string TestSpecParser::subString() const { return m_arg.substr( m_start, m_pos - m_start ); }
  9220. void TestSpecParser::addFilter() {
  9221. if( !m_currentFilter.m_patterns.empty() ) {
  9222. m_testSpec.m_filters.push_back( m_currentFilter );
  9223. m_currentFilter = TestSpec::Filter();
  9224. }
  9225. }
  9226. TestSpec parseTestSpec( std::string const& arg ) {
  9227. return TestSpecParser( ITagAliasRegistry::get() ).parse( arg ).testSpec();
  9228. }
  9229. } // namespace Catch
  9230. // end catch_test_spec_parser.cpp
  9231. // start catch_timer.cpp
  9232. #include <chrono>
  9233. static const uint64_t nanosecondsInSecond = 1000000000;
  9234. namespace Catch {
  9235. auto getCurrentNanosecondsSinceEpoch() -> uint64_t {
  9236. return std::chrono::duration_cast<std::chrono::nanoseconds>( std::chrono::high_resolution_clock::now().time_since_epoch() ).count();
  9237. }
  9238. namespace {
  9239. auto estimateClockResolution() -> uint64_t {
  9240. uint64_t sum = 0;
  9241. static const uint64_t iterations = 1000000;
  9242. auto startTime = getCurrentNanosecondsSinceEpoch();
  9243. for( std::size_t i = 0; i < iterations; ++i ) {
  9244. uint64_t ticks;
  9245. uint64_t baseTicks = getCurrentNanosecondsSinceEpoch();
  9246. do {
  9247. ticks = getCurrentNanosecondsSinceEpoch();
  9248. } while( ticks == baseTicks );
  9249. auto delta = ticks - baseTicks;
  9250. sum += delta;
  9251. // If we have been calibrating for over 3 seconds -- the clock
  9252. // is terrible and we should move on.
  9253. // TBD: How to signal that the measured resolution is probably wrong?
  9254. if (ticks > startTime + 3 * nanosecondsInSecond) {
  9255. return sum / i;
  9256. }
  9257. }
  9258. // We're just taking the mean, here. To do better we could take the std. dev and exclude outliers
  9259. // - and potentially do more iterations if there's a high variance.
  9260. return sum/iterations;
  9261. }
  9262. }
  9263. auto getEstimatedClockResolution() -> uint64_t {
  9264. static auto s_resolution = estimateClockResolution();
  9265. return s_resolution;
  9266. }
  9267. void Timer::start() {
  9268. m_nanoseconds = getCurrentNanosecondsSinceEpoch();
  9269. }
  9270. auto Timer::getElapsedNanoseconds() const -> uint64_t {
  9271. return getCurrentNanosecondsSinceEpoch() - m_nanoseconds;
  9272. }
  9273. auto Timer::getElapsedMicroseconds() const -> uint64_t {
  9274. return getElapsedNanoseconds()/1000;
  9275. }
  9276. auto Timer::getElapsedMilliseconds() const -> unsigned int {
  9277. return static_cast<unsigned int>(getElapsedMicroseconds()/1000);
  9278. }
  9279. auto Timer::getElapsedSeconds() const -> double {
  9280. return getElapsedMicroseconds()/1000000.0;
  9281. }
  9282. } // namespace Catch
  9283. // end catch_timer.cpp
  9284. // start catch_tostring.cpp
  9285. #if defined(__clang__)
  9286. # pragma clang diagnostic push
  9287. # pragma clang diagnostic ignored "-Wexit-time-destructors"
  9288. # pragma clang diagnostic ignored "-Wglobal-constructors"
  9289. #endif
  9290. // Enable specific decls locally
  9291. #if !defined(CATCH_CONFIG_ENABLE_CHRONO_STRINGMAKER)
  9292. #define CATCH_CONFIG_ENABLE_CHRONO_STRINGMAKER
  9293. #endif
  9294. #include <cmath>
  9295. #include <iomanip>
  9296. namespace Catch {
  9297. namespace Detail {
  9298. const std::string unprintableString = "{?}";
  9299. namespace {
  9300. const int hexThreshold = 255;
  9301. struct Endianness {
  9302. enum Arch { Big, Little };
  9303. static Arch which() {
  9304. union _{
  9305. int asInt;
  9306. char asChar[sizeof (int)];
  9307. } u;
  9308. u.asInt = 1;
  9309. return ( u.asChar[sizeof(int)-1] == 1 ) ? Big : Little;
  9310. }
  9311. };
  9312. }
  9313. std::string rawMemoryToString( const void *object, std::size_t size ) {
  9314. // Reverse order for little endian architectures
  9315. int i = 0, end = static_cast<int>( size ), inc = 1;
  9316. if( Endianness::which() == Endianness::Little ) {
  9317. i = end-1;
  9318. end = inc = -1;
  9319. }
  9320. unsigned char const *bytes = static_cast<unsigned char const *>(object);
  9321. ReusableStringStream rss;
  9322. rss << "0x" << std::setfill('0') << std::hex;
  9323. for( ; i != end; i += inc )
  9324. rss << std::setw(2) << static_cast<unsigned>(bytes[i]);
  9325. return rss.str();
  9326. }
  9327. }
  9328. template<typename T>
  9329. std::string fpToString( T value, int precision ) {
  9330. if (std::isnan(value)) {
  9331. return "nan";
  9332. }
  9333. ReusableStringStream rss;
  9334. rss << std::setprecision( precision )
  9335. << std::fixed
  9336. << value;
  9337. std::string d = rss.str();
  9338. std::size_t i = d.find_last_not_of( '0' );
  9339. if( i != std::string::npos && i != d.size()-1 ) {
  9340. if( d[i] == '.' )
  9341. i++;
  9342. d = d.substr( 0, i+1 );
  9343. }
  9344. return d;
  9345. }
  9346. //// ======================================================= ////
  9347. //
  9348. // Out-of-line defs for full specialization of StringMaker
  9349. //
  9350. //// ======================================================= ////
  9351. std::string StringMaker<std::string>::convert(const std::string& str) {
  9352. if (!getCurrentContext().getConfig()->showInvisibles()) {
  9353. return '"' + str + '"';
  9354. }
  9355. std::string s("\"");
  9356. for (char c : str) {
  9357. switch (c) {
  9358. case '\n':
  9359. s.append("\\n");
  9360. break;
  9361. case '\t':
  9362. s.append("\\t");
  9363. break;
  9364. default:
  9365. s.push_back(c);
  9366. break;
  9367. }
  9368. }
  9369. s.append("\"");
  9370. return s;
  9371. }
  9372. #ifdef CATCH_CONFIG_CPP17_STRING_VIEW
  9373. std::string StringMaker<std::string_view>::convert(std::string_view str) {
  9374. return ::Catch::Detail::stringify(std::string{ str });
  9375. }
  9376. #endif
  9377. std::string StringMaker<char const*>::convert(char const* str) {
  9378. if (str) {
  9379. return ::Catch::Detail::stringify(std::string{ str });
  9380. } else {
  9381. return{ "{null string}" };
  9382. }
  9383. }
  9384. std::string StringMaker<char*>::convert(char* str) {
  9385. if (str) {
  9386. return ::Catch::Detail::stringify(std::string{ str });
  9387. } else {
  9388. return{ "{null string}" };
  9389. }
  9390. }
  9391. #ifdef CATCH_CONFIG_WCHAR
  9392. std::string StringMaker<std::wstring>::convert(const std::wstring& wstr) {
  9393. std::string s;
  9394. s.reserve(wstr.size());
  9395. for (auto c : wstr) {
  9396. s += (c <= 0xff) ? static_cast<char>(c) : '?';
  9397. }
  9398. return ::Catch::Detail::stringify(s);
  9399. }
  9400. # ifdef CATCH_CONFIG_CPP17_STRING_VIEW
  9401. std::string StringMaker<std::wstring_view>::convert(std::wstring_view str) {
  9402. return StringMaker<std::wstring>::convert(std::wstring(str));
  9403. }
  9404. # endif
  9405. std::string StringMaker<wchar_t const*>::convert(wchar_t const * str) {
  9406. if (str) {
  9407. return ::Catch::Detail::stringify(std::wstring{ str });
  9408. } else {
  9409. return{ "{null string}" };
  9410. }
  9411. }
  9412. std::string StringMaker<wchar_t *>::convert(wchar_t * str) {
  9413. if (str) {
  9414. return ::Catch::Detail::stringify(std::wstring{ str });
  9415. } else {
  9416. return{ "{null string}" };
  9417. }
  9418. }
  9419. #endif
  9420. std::string StringMaker<int>::convert(int value) {
  9421. return ::Catch::Detail::stringify(static_cast<long long>(value));
  9422. }
  9423. std::string StringMaker<long>::convert(long value) {
  9424. return ::Catch::Detail::stringify(static_cast<long long>(value));
  9425. }
  9426. std::string StringMaker<long long>::convert(long long value) {
  9427. ReusableStringStream rss;
  9428. rss << value;
  9429. if (value > Detail::hexThreshold) {
  9430. rss << " (0x" << std::hex << value << ')';
  9431. }
  9432. return rss.str();
  9433. }
  9434. std::string StringMaker<unsigned int>::convert(unsigned int value) {
  9435. return ::Catch::Detail::stringify(static_cast<unsigned long long>(value));
  9436. }
  9437. std::string StringMaker<unsigned long>::convert(unsigned long value) {
  9438. return ::Catch::Detail::stringify(static_cast<unsigned long long>(value));
  9439. }
  9440. std::string StringMaker<unsigned long long>::convert(unsigned long long value) {
  9441. ReusableStringStream rss;
  9442. rss << value;
  9443. if (value > Detail::hexThreshold) {
  9444. rss << " (0x" << std::hex << value << ')';
  9445. }
  9446. return rss.str();
  9447. }
  9448. std::string StringMaker<bool>::convert(bool b) {
  9449. return b ? "true" : "false";
  9450. }
  9451. std::string StringMaker<char>::convert(char value) {
  9452. if (value == '\r') {
  9453. return "'\\r'";
  9454. } else if (value == '\f') {
  9455. return "'\\f'";
  9456. } else if (value == '\n') {
  9457. return "'\\n'";
  9458. } else if (value == '\t') {
  9459. return "'\\t'";
  9460. } else if ('\0' <= value && value < ' ') {
  9461. return ::Catch::Detail::stringify(static_cast<unsigned int>(value));
  9462. } else {
  9463. char chstr[] = "' '";
  9464. chstr[1] = value;
  9465. return chstr;
  9466. }
  9467. }
  9468. std::string StringMaker<signed char>::convert(signed char c) {
  9469. return ::Catch::Detail::stringify(static_cast<char>(c));
  9470. }
  9471. std::string StringMaker<unsigned char>::convert(unsigned char c) {
  9472. return ::Catch::Detail::stringify(static_cast<char>(c));
  9473. }
  9474. std::string StringMaker<std::nullptr_t>::convert(std::nullptr_t) {
  9475. return "nullptr";
  9476. }
  9477. std::string StringMaker<float>::convert(float value) {
  9478. return fpToString(value, 5) + 'f';
  9479. }
  9480. std::string StringMaker<double>::convert(double value) {
  9481. return fpToString(value, 10);
  9482. }
  9483. std::string ratio_string<std::atto>::symbol() { return "a"; }
  9484. std::string ratio_string<std::femto>::symbol() { return "f"; }
  9485. std::string ratio_string<std::pico>::symbol() { return "p"; }
  9486. std::string ratio_string<std::nano>::symbol() { return "n"; }
  9487. std::string ratio_string<std::micro>::symbol() { return "u"; }
  9488. std::string ratio_string<std::milli>::symbol() { return "m"; }
  9489. } // end namespace Catch
  9490. #if defined(__clang__)
  9491. # pragma clang diagnostic pop
  9492. #endif
  9493. // end catch_tostring.cpp
  9494. // start catch_totals.cpp
  9495. namespace Catch {
  9496. Counts Counts::operator - ( Counts const& other ) const {
  9497. Counts diff;
  9498. diff.passed = passed - other.passed;
  9499. diff.failed = failed - other.failed;
  9500. diff.failedButOk = failedButOk - other.failedButOk;
  9501. return diff;
  9502. }
  9503. Counts& Counts::operator += ( Counts const& other ) {
  9504. passed += other.passed;
  9505. failed += other.failed;
  9506. failedButOk += other.failedButOk;
  9507. return *this;
  9508. }
  9509. std::size_t Counts::total() const {
  9510. return passed + failed + failedButOk;
  9511. }
  9512. bool Counts::allPassed() const {
  9513. return failed == 0 && failedButOk == 0;
  9514. }
  9515. bool Counts::allOk() const {
  9516. return failed == 0;
  9517. }
  9518. Totals Totals::operator - ( Totals const& other ) const {
  9519. Totals diff;
  9520. diff.assertions = assertions - other.assertions;
  9521. diff.testCases = testCases - other.testCases;
  9522. return diff;
  9523. }
  9524. Totals& Totals::operator += ( Totals const& other ) {
  9525. assertions += other.assertions;
  9526. testCases += other.testCases;
  9527. return *this;
  9528. }
  9529. Totals Totals::delta( Totals const& prevTotals ) const {
  9530. Totals diff = *this - prevTotals;
  9531. if( diff.assertions.failed > 0 )
  9532. ++diff.testCases.failed;
  9533. else if( diff.assertions.failedButOk > 0 )
  9534. ++diff.testCases.failedButOk;
  9535. else
  9536. ++diff.testCases.passed;
  9537. return diff;
  9538. }
  9539. }
  9540. // end catch_totals.cpp
  9541. // start catch_uncaught_exceptions.cpp
  9542. #include <exception>
  9543. namespace Catch {
  9544. bool uncaught_exceptions() {
  9545. #if defined(CATCH_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS)
  9546. return std::uncaught_exceptions() > 0;
  9547. #else
  9548. return std::uncaught_exception();
  9549. #endif
  9550. }
  9551. } // end namespace Catch
  9552. // end catch_uncaught_exceptions.cpp
  9553. // start catch_version.cpp
  9554. #include <ostream>
  9555. namespace Catch {
  9556. Version::Version
  9557. ( unsigned int _majorVersion,
  9558. unsigned int _minorVersion,
  9559. unsigned int _patchNumber,
  9560. char const * const _branchName,
  9561. unsigned int _buildNumber )
  9562. : majorVersion( _majorVersion ),
  9563. minorVersion( _minorVersion ),
  9564. patchNumber( _patchNumber ),
  9565. branchName( _branchName ),
  9566. buildNumber( _buildNumber )
  9567. {}
  9568. std::ostream& operator << ( std::ostream& os, Version const& version ) {
  9569. os << version.majorVersion << '.'
  9570. << version.minorVersion << '.'
  9571. << version.patchNumber;
  9572. // branchName is never null -> 0th char is \0 if it is empty
  9573. if (version.branchName[0]) {
  9574. os << '-' << version.branchName
  9575. << '.' << version.buildNumber;
  9576. }
  9577. return os;
  9578. }
  9579. Version const& libraryVersion() {
  9580. static Version version( 2, 4, 1, "", 0 );
  9581. return version;
  9582. }
  9583. }
  9584. // end catch_version.cpp
  9585. // start catch_wildcard_pattern.cpp
  9586. #include <sstream>
  9587. namespace Catch {
  9588. WildcardPattern::WildcardPattern( std::string const& pattern,
  9589. CaseSensitive::Choice caseSensitivity )
  9590. : m_caseSensitivity( caseSensitivity ),
  9591. m_pattern( adjustCase( pattern ) )
  9592. {
  9593. if( startsWith( m_pattern, '*' ) ) {
  9594. m_pattern = m_pattern.substr( 1 );
  9595. m_wildcard = WildcardAtStart;
  9596. }
  9597. if( endsWith( m_pattern, '*' ) ) {
  9598. m_pattern = m_pattern.substr( 0, m_pattern.size()-1 );
  9599. m_wildcard = static_cast<WildcardPosition>( m_wildcard | WildcardAtEnd );
  9600. }
  9601. }
  9602. bool WildcardPattern::matches( std::string const& str ) const {
  9603. switch( m_wildcard ) {
  9604. case NoWildcard:
  9605. return m_pattern == adjustCase( str );
  9606. case WildcardAtStart:
  9607. return endsWith( adjustCase( str ), m_pattern );
  9608. case WildcardAtEnd:
  9609. return startsWith( adjustCase( str ), m_pattern );
  9610. case WildcardAtBothEnds:
  9611. return contains( adjustCase( str ), m_pattern );
  9612. default:
  9613. CATCH_INTERNAL_ERROR( "Unknown enum" );
  9614. }
  9615. }
  9616. std::string WildcardPattern::adjustCase( std::string const& str ) const {
  9617. return m_caseSensitivity == CaseSensitive::No ? toLower( str ) : str;
  9618. }
  9619. }
  9620. // end catch_wildcard_pattern.cpp
  9621. // start catch_xmlwriter.cpp
  9622. #include <iomanip>
  9623. using uchar = unsigned char;
  9624. namespace Catch {
  9625. namespace {
  9626. size_t trailingBytes(unsigned char c) {
  9627. if ((c & 0xE0) == 0xC0) {
  9628. return 2;
  9629. }
  9630. if ((c & 0xF0) == 0xE0) {
  9631. return 3;
  9632. }
  9633. if ((c & 0xF8) == 0xF0) {
  9634. return 4;
  9635. }
  9636. CATCH_INTERNAL_ERROR("Invalid multibyte utf-8 start byte encountered");
  9637. }
  9638. uint32_t headerValue(unsigned char c) {
  9639. if ((c & 0xE0) == 0xC0) {
  9640. return c & 0x1F;
  9641. }
  9642. if ((c & 0xF0) == 0xE0) {
  9643. return c & 0x0F;
  9644. }
  9645. if ((c & 0xF8) == 0xF0) {
  9646. return c & 0x07;
  9647. }
  9648. CATCH_INTERNAL_ERROR("Invalid multibyte utf-8 start byte encountered");
  9649. }
  9650. void hexEscapeChar(std::ostream& os, unsigned char c) {
  9651. os << "\\x"
  9652. << std::uppercase << std::hex << std::setfill('0') << std::setw(2)
  9653. << static_cast<int>(c);
  9654. }
  9655. } // anonymous namespace
  9656. XmlEncode::XmlEncode( std::string const& str, ForWhat forWhat )
  9657. : m_str( str ),
  9658. m_forWhat( forWhat )
  9659. {}
  9660. void XmlEncode::encodeTo( std::ostream& os ) const {
  9661. // Apostrophe escaping not necessary if we always use " to write attributes
  9662. // (see: http://www.w3.org/TR/xml/#syntax)
  9663. for( std::size_t idx = 0; idx < m_str.size(); ++ idx ) {
  9664. uchar c = m_str[idx];
  9665. switch (c) {
  9666. case '<': os << "&lt;"; break;
  9667. case '&': os << "&amp;"; break;
  9668. case '>':
  9669. // See: http://www.w3.org/TR/xml/#syntax
  9670. if (idx > 2 && m_str[idx - 1] == ']' && m_str[idx - 2] == ']')
  9671. os << "&gt;";
  9672. else
  9673. os << c;
  9674. break;
  9675. case '\"':
  9676. if (m_forWhat == ForAttributes)
  9677. os << "&quot;";
  9678. else
  9679. os << c;
  9680. break;
  9681. default:
  9682. // Check for control characters and invalid utf-8
  9683. // Escape control characters in standard ascii
  9684. // see http://stackoverflow.com/questions/404107/why-are-control-characters-illegal-in-xml-1-0
  9685. if (c < 0x09 || (c > 0x0D && c < 0x20) || c == 0x7F) {
  9686. hexEscapeChar(os, c);
  9687. break;
  9688. }
  9689. // Plain ASCII: Write it to stream
  9690. if (c < 0x7F) {
  9691. os << c;
  9692. break;
  9693. }
  9694. // UTF-8 territory
  9695. // Check if the encoding is valid and if it is not, hex escape bytes.
  9696. // Important: We do not check the exact decoded values for validity, only the encoding format
  9697. // First check that this bytes is a valid lead byte:
  9698. // This means that it is not encoded as 1111 1XXX
  9699. // Or as 10XX XXXX
  9700. if (c < 0xC0 ||
  9701. c >= 0xF8) {
  9702. hexEscapeChar(os, c);
  9703. break;
  9704. }
  9705. auto encBytes = trailingBytes(c);
  9706. // Are there enough bytes left to avoid accessing out-of-bounds memory?
  9707. if (idx + encBytes - 1 >= m_str.size()) {
  9708. hexEscapeChar(os, c);
  9709. break;
  9710. }
  9711. // The header is valid, check data
  9712. // The next encBytes bytes must together be a valid utf-8
  9713. // This means: bitpattern 10XX XXXX and the extracted value is sane (ish)
  9714. bool valid = true;
  9715. uint32_t value = headerValue(c);
  9716. for (std::size_t n = 1; n < encBytes; ++n) {
  9717. uchar nc = m_str[idx + n];
  9718. valid &= ((nc & 0xC0) == 0x80);
  9719. value = (value << 6) | (nc & 0x3F);
  9720. }
  9721. if (
  9722. // Wrong bit pattern of following bytes
  9723. (!valid) ||
  9724. // Overlong encodings
  9725. (value < 0x80) ||
  9726. (0x80 <= value && value < 0x800 && encBytes > 2) ||
  9727. (0x800 < value && value < 0x10000 && encBytes > 3) ||
  9728. // Encoded value out of range
  9729. (value >= 0x110000)
  9730. ) {
  9731. hexEscapeChar(os, c);
  9732. break;
  9733. }
  9734. // If we got here, this is in fact a valid(ish) utf-8 sequence
  9735. for (std::size_t n = 0; n < encBytes; ++n) {
  9736. os << m_str[idx + n];
  9737. }
  9738. idx += encBytes - 1;
  9739. break;
  9740. }
  9741. }
  9742. }
  9743. std::ostream& operator << ( std::ostream& os, XmlEncode const& xmlEncode ) {
  9744. xmlEncode.encodeTo( os );
  9745. return os;
  9746. }
  9747. XmlWriter::ScopedElement::ScopedElement( XmlWriter* writer )
  9748. : m_writer( writer )
  9749. {}
  9750. XmlWriter::ScopedElement::ScopedElement( ScopedElement&& other ) noexcept
  9751. : m_writer( other.m_writer ){
  9752. other.m_writer = nullptr;
  9753. }
  9754. XmlWriter::ScopedElement& XmlWriter::ScopedElement::operator=( ScopedElement&& other ) noexcept {
  9755. if ( m_writer ) {
  9756. m_writer->endElement();
  9757. }
  9758. m_writer = other.m_writer;
  9759. other.m_writer = nullptr;
  9760. return *this;
  9761. }
  9762. XmlWriter::ScopedElement::~ScopedElement() {
  9763. if( m_writer )
  9764. m_writer->endElement();
  9765. }
  9766. XmlWriter::ScopedElement& XmlWriter::ScopedElement::writeText( std::string const& text, bool indent ) {
  9767. m_writer->writeText( text, indent );
  9768. return *this;
  9769. }
  9770. XmlWriter::XmlWriter( std::ostream& os ) : m_os( os )
  9771. {
  9772. writeDeclaration();
  9773. }
  9774. XmlWriter::~XmlWriter() {
  9775. while( !m_tags.empty() )
  9776. endElement();
  9777. }
  9778. XmlWriter& XmlWriter::startElement( std::string const& name ) {
  9779. ensureTagClosed();
  9780. newlineIfNecessary();
  9781. m_os << m_indent << '<' << name;
  9782. m_tags.push_back( name );
  9783. m_indent += " ";
  9784. m_tagIsOpen = true;
  9785. return *this;
  9786. }
  9787. XmlWriter::ScopedElement XmlWriter::scopedElement( std::string const& name ) {
  9788. ScopedElement scoped( this );
  9789. startElement( name );
  9790. return scoped;
  9791. }
  9792. XmlWriter& XmlWriter::endElement() {
  9793. newlineIfNecessary();
  9794. m_indent = m_indent.substr( 0, m_indent.size()-2 );
  9795. if( m_tagIsOpen ) {
  9796. m_os << "/>";
  9797. m_tagIsOpen = false;
  9798. }
  9799. else {
  9800. m_os << m_indent << "</" << m_tags.back() << ">";
  9801. }
  9802. m_os << std::endl;
  9803. m_tags.pop_back();
  9804. return *this;
  9805. }
  9806. XmlWriter& XmlWriter::writeAttribute( std::string const& name, std::string const& attribute ) {
  9807. if( !name.empty() && !attribute.empty() )
  9808. m_os << ' ' << name << "=\"" << XmlEncode( attribute, XmlEncode::ForAttributes ) << '"';
  9809. return *this;
  9810. }
  9811. XmlWriter& XmlWriter::writeAttribute( std::string const& name, bool attribute ) {
  9812. m_os << ' ' << name << "=\"" << ( attribute ? "true" : "false" ) << '"';
  9813. return *this;
  9814. }
  9815. XmlWriter& XmlWriter::writeText( std::string const& text, bool indent ) {
  9816. if( !text.empty() ){
  9817. bool tagWasOpen = m_tagIsOpen;
  9818. ensureTagClosed();
  9819. if( tagWasOpen && indent )
  9820. m_os << m_indent;
  9821. m_os << XmlEncode( text );
  9822. m_needsNewline = true;
  9823. }
  9824. return *this;
  9825. }
  9826. XmlWriter& XmlWriter::writeComment( std::string const& text ) {
  9827. ensureTagClosed();
  9828. m_os << m_indent << "<!--" << text << "-->";
  9829. m_needsNewline = true;
  9830. return *this;
  9831. }
  9832. void XmlWriter::writeStylesheetRef( std::string const& url ) {
  9833. m_os << "<?xml-stylesheet type=\"text/xsl\" href=\"" << url << "\"?>\n";
  9834. }
  9835. XmlWriter& XmlWriter::writeBlankLine() {
  9836. ensureTagClosed();
  9837. m_os << '\n';
  9838. return *this;
  9839. }
  9840. void XmlWriter::ensureTagClosed() {
  9841. if( m_tagIsOpen ) {
  9842. m_os << ">" << std::endl;
  9843. m_tagIsOpen = false;
  9844. }
  9845. }
  9846. void XmlWriter::writeDeclaration() {
  9847. m_os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
  9848. }
  9849. void XmlWriter::newlineIfNecessary() {
  9850. if( m_needsNewline ) {
  9851. m_os << std::endl;
  9852. m_needsNewline = false;
  9853. }
  9854. }
  9855. }
  9856. // end catch_xmlwriter.cpp
  9857. // start catch_reporter_bases.cpp
  9858. #include <cstring>
  9859. #include <cfloat>
  9860. #include <cstdio>
  9861. #include <cassert>
  9862. #include <memory>
  9863. namespace Catch {
  9864. void prepareExpandedExpression(AssertionResult& result) {
  9865. result.getExpandedExpression();
  9866. }
  9867. // Because formatting using c++ streams is stateful, drop down to C is required
  9868. // Alternatively we could use stringstream, but its performance is... not good.
  9869. std::string getFormattedDuration( double duration ) {
  9870. // Max exponent + 1 is required to represent the whole part
  9871. // + 1 for decimal point
  9872. // + 3 for the 3 decimal places
  9873. // + 1 for null terminator
  9874. const std::size_t maxDoubleSize = DBL_MAX_10_EXP + 1 + 1 + 3 + 1;
  9875. char buffer[maxDoubleSize];
  9876. // Save previous errno, to prevent sprintf from overwriting it
  9877. ErrnoGuard guard;
  9878. #ifdef _MSC_VER
  9879. sprintf_s(buffer, "%.3f", duration);
  9880. #else
  9881. sprintf(buffer, "%.3f", duration);
  9882. #endif
  9883. return std::string(buffer);
  9884. }
  9885. TestEventListenerBase::TestEventListenerBase(ReporterConfig const & _config)
  9886. :StreamingReporterBase(_config) {}
  9887. void TestEventListenerBase::assertionStarting(AssertionInfo const &) {}
  9888. bool TestEventListenerBase::assertionEnded(AssertionStats const &) {
  9889. return false;
  9890. }
  9891. } // end namespace Catch
  9892. // end catch_reporter_bases.cpp
  9893. // start catch_reporter_compact.cpp
  9894. namespace {
  9895. #ifdef CATCH_PLATFORM_MAC
  9896. const char* failedString() { return "FAILED"; }
  9897. const char* passedString() { return "PASSED"; }
  9898. #else
  9899. const char* failedString() { return "failed"; }
  9900. const char* passedString() { return "passed"; }
  9901. #endif
  9902. // Colour::LightGrey
  9903. Catch::Colour::Code dimColour() { return Catch::Colour::FileName; }
  9904. std::string bothOrAll( std::size_t count ) {
  9905. return count == 1 ? std::string() :
  9906. count == 2 ? "both " : "all " ;
  9907. }
  9908. } // anon namespace
  9909. namespace Catch {
  9910. namespace {
  9911. // Colour, message variants:
  9912. // - white: No tests ran.
  9913. // - red: Failed [both/all] N test cases, failed [both/all] M assertions.
  9914. // - white: Passed [both/all] N test cases (no assertions).
  9915. // - red: Failed N tests cases, failed M assertions.
  9916. // - green: Passed [both/all] N tests cases with M assertions.
  9917. void printTotals(std::ostream& out, const Totals& totals) {
  9918. if (totals.testCases.total() == 0) {
  9919. out << "No tests ran.";
  9920. } else if (totals.testCases.failed == totals.testCases.total()) {
  9921. Colour colour(Colour::ResultError);
  9922. const std::string qualify_assertions_failed =
  9923. totals.assertions.failed == totals.assertions.total() ?
  9924. bothOrAll(totals.assertions.failed) : std::string();
  9925. out <<
  9926. "Failed " << bothOrAll(totals.testCases.failed)
  9927. << pluralise(totals.testCases.failed, "test case") << ", "
  9928. "failed " << qualify_assertions_failed <<
  9929. pluralise(totals.assertions.failed, "assertion") << '.';
  9930. } else if (totals.assertions.total() == 0) {
  9931. out <<
  9932. "Passed " << bothOrAll(totals.testCases.total())
  9933. << pluralise(totals.testCases.total(), "test case")
  9934. << " (no assertions).";
  9935. } else if (totals.assertions.failed) {
  9936. Colour colour(Colour::ResultError);
  9937. out <<
  9938. "Failed " << pluralise(totals.testCases.failed, "test case") << ", "
  9939. "failed " << pluralise(totals.assertions.failed, "assertion") << '.';
  9940. } else {
  9941. Colour colour(Colour::ResultSuccess);
  9942. out <<
  9943. "Passed " << bothOrAll(totals.testCases.passed)
  9944. << pluralise(totals.testCases.passed, "test case") <<
  9945. " with " << pluralise(totals.assertions.passed, "assertion") << '.';
  9946. }
  9947. }
  9948. // Implementation of CompactReporter formatting
  9949. class AssertionPrinter {
  9950. public:
  9951. AssertionPrinter& operator= (AssertionPrinter const&) = delete;
  9952. AssertionPrinter(AssertionPrinter const&) = delete;
  9953. AssertionPrinter(std::ostream& _stream, AssertionStats const& _stats, bool _printInfoMessages)
  9954. : stream(_stream)
  9955. , result(_stats.assertionResult)
  9956. , messages(_stats.infoMessages)
  9957. , itMessage(_stats.infoMessages.begin())
  9958. , printInfoMessages(_printInfoMessages) {}
  9959. void print() {
  9960. printSourceInfo();
  9961. itMessage = messages.begin();
  9962. switch (result.getResultType()) {
  9963. case ResultWas::Ok:
  9964. printResultType(Colour::ResultSuccess, passedString());
  9965. printOriginalExpression();
  9966. printReconstructedExpression();
  9967. if (!result.hasExpression())
  9968. printRemainingMessages(Colour::None);
  9969. else
  9970. printRemainingMessages();
  9971. break;
  9972. case ResultWas::ExpressionFailed:
  9973. if (result.isOk())
  9974. printResultType(Colour::ResultSuccess, failedString() + std::string(" - but was ok"));
  9975. else
  9976. printResultType(Colour::Error, failedString());
  9977. printOriginalExpression();
  9978. printReconstructedExpression();
  9979. printRemainingMessages();
  9980. break;
  9981. case ResultWas::ThrewException:
  9982. printResultType(Colour::Error, failedString());
  9983. printIssue("unexpected exception with message:");
  9984. printMessage();
  9985. printExpressionWas();
  9986. printRemainingMessages();
  9987. break;
  9988. case ResultWas::FatalErrorCondition:
  9989. printResultType(Colour::Error, failedString());
  9990. printIssue("fatal error condition with message:");
  9991. printMessage();
  9992. printExpressionWas();
  9993. printRemainingMessages();
  9994. break;
  9995. case ResultWas::DidntThrowException:
  9996. printResultType(Colour::Error, failedString());
  9997. printIssue("expected exception, got none");
  9998. printExpressionWas();
  9999. printRemainingMessages();
  10000. break;
  10001. case ResultWas::Info:
  10002. printResultType(Colour::None, "info");
  10003. printMessage();
  10004. printRemainingMessages();
  10005. break;
  10006. case ResultWas::Warning:
  10007. printResultType(Colour::None, "warning");
  10008. printMessage();
  10009. printRemainingMessages();
  10010. break;
  10011. case ResultWas::ExplicitFailure:
  10012. printResultType(Colour::Error, failedString());
  10013. printIssue("explicitly");
  10014. printRemainingMessages(Colour::None);
  10015. break;
  10016. // These cases are here to prevent compiler warnings
  10017. case ResultWas::Unknown:
  10018. case ResultWas::FailureBit:
  10019. case ResultWas::Exception:
  10020. printResultType(Colour::Error, "** internal error **");
  10021. break;
  10022. }
  10023. }
  10024. private:
  10025. void printSourceInfo() const {
  10026. Colour colourGuard(Colour::FileName);
  10027. stream << result.getSourceInfo() << ':';
  10028. }
  10029. void printResultType(Colour::Code colour, std::string const& passOrFail) const {
  10030. if (!passOrFail.empty()) {
  10031. {
  10032. Colour colourGuard(colour);
  10033. stream << ' ' << passOrFail;
  10034. }
  10035. stream << ':';
  10036. }
  10037. }
  10038. void printIssue(std::string const& issue) const {
  10039. stream << ' ' << issue;
  10040. }
  10041. void printExpressionWas() {
  10042. if (result.hasExpression()) {
  10043. stream << ';';
  10044. {
  10045. Colour colour(dimColour());
  10046. stream << " expression was:";
  10047. }
  10048. printOriginalExpression();
  10049. }
  10050. }
  10051. void printOriginalExpression() const {
  10052. if (result.hasExpression()) {
  10053. stream << ' ' << result.getExpression();
  10054. }
  10055. }
  10056. void printReconstructedExpression() const {
  10057. if (result.hasExpandedExpression()) {
  10058. {
  10059. Colour colour(dimColour());
  10060. stream << " for: ";
  10061. }
  10062. stream << result.getExpandedExpression();
  10063. }
  10064. }
  10065. void printMessage() {
  10066. if (itMessage != messages.end()) {
  10067. stream << " '" << itMessage->message << '\'';
  10068. ++itMessage;
  10069. }
  10070. }
  10071. void printRemainingMessages(Colour::Code colour = dimColour()) {
  10072. if (itMessage == messages.end())
  10073. return;
  10074. // using messages.end() directly yields (or auto) compilation error:
  10075. std::vector<MessageInfo>::const_iterator itEnd = messages.end();
  10076. const std::size_t N = static_cast<std::size_t>(std::distance(itMessage, itEnd));
  10077. {
  10078. Colour colourGuard(colour);
  10079. stream << " with " << pluralise(N, "message") << ':';
  10080. }
  10081. for (; itMessage != itEnd; ) {
  10082. // If this assertion is a warning ignore any INFO messages
  10083. if (printInfoMessages || itMessage->type != ResultWas::Info) {
  10084. stream << " '" << itMessage->message << '\'';
  10085. if (++itMessage != itEnd) {
  10086. Colour colourGuard(dimColour());
  10087. stream << " and";
  10088. }
  10089. }
  10090. }
  10091. }
  10092. private:
  10093. std::ostream& stream;
  10094. AssertionResult const& result;
  10095. std::vector<MessageInfo> messages;
  10096. std::vector<MessageInfo>::const_iterator itMessage;
  10097. bool printInfoMessages;
  10098. };
  10099. } // anon namespace
  10100. std::string CompactReporter::getDescription() {
  10101. return "Reports test results on a single line, suitable for IDEs";
  10102. }
  10103. ReporterPreferences CompactReporter::getPreferences() const {
  10104. return m_reporterPrefs;
  10105. }
  10106. void CompactReporter::noMatchingTestCases( std::string const& spec ) {
  10107. stream << "No test cases matched '" << spec << '\'' << std::endl;
  10108. }
  10109. void CompactReporter::assertionStarting( AssertionInfo const& ) {}
  10110. bool CompactReporter::assertionEnded( AssertionStats const& _assertionStats ) {
  10111. AssertionResult const& result = _assertionStats.assertionResult;
  10112. bool printInfoMessages = true;
  10113. // Drop out if result was successful and we're not printing those
  10114. if( !m_config->includeSuccessfulResults() && result.isOk() ) {
  10115. if( result.getResultType() != ResultWas::Warning )
  10116. return false;
  10117. printInfoMessages = false;
  10118. }
  10119. AssertionPrinter printer( stream, _assertionStats, printInfoMessages );
  10120. printer.print();
  10121. stream << std::endl;
  10122. return true;
  10123. }
  10124. void CompactReporter::sectionEnded(SectionStats const& _sectionStats) {
  10125. if (m_config->showDurations() == ShowDurations::Always) {
  10126. stream << getFormattedDuration(_sectionStats.durationInSeconds) << " s: " << _sectionStats.sectionInfo.name << std::endl;
  10127. }
  10128. }
  10129. void CompactReporter::testRunEnded( TestRunStats const& _testRunStats ) {
  10130. printTotals( stream, _testRunStats.totals );
  10131. stream << '\n' << std::endl;
  10132. StreamingReporterBase::testRunEnded( _testRunStats );
  10133. }
  10134. CompactReporter::~CompactReporter() {}
  10135. CATCH_REGISTER_REPORTER( "compact", CompactReporter )
  10136. } // end namespace Catch
  10137. // end catch_reporter_compact.cpp
  10138. // start catch_reporter_console.cpp
  10139. #include <cfloat>
  10140. #include <cstdio>
  10141. #if defined(_MSC_VER)
  10142. #pragma warning(push)
  10143. #pragma warning(disable:4061) // Not all labels are EXPLICITLY handled in switch
  10144. // Note that 4062 (not all labels are handled
  10145. // and default is missing) is enabled
  10146. #endif
  10147. namespace Catch {
  10148. namespace {
  10149. // Formatter impl for ConsoleReporter
  10150. class ConsoleAssertionPrinter {
  10151. public:
  10152. ConsoleAssertionPrinter& operator= (ConsoleAssertionPrinter const&) = delete;
  10153. ConsoleAssertionPrinter(ConsoleAssertionPrinter const&) = delete;
  10154. ConsoleAssertionPrinter(std::ostream& _stream, AssertionStats const& _stats, bool _printInfoMessages)
  10155. : stream(_stream),
  10156. stats(_stats),
  10157. result(_stats.assertionResult),
  10158. colour(Colour::None),
  10159. message(result.getMessage()),
  10160. messages(_stats.infoMessages),
  10161. printInfoMessages(_printInfoMessages) {
  10162. switch (result.getResultType()) {
  10163. case ResultWas::Ok:
  10164. colour = Colour::Success;
  10165. passOrFail = "PASSED";
  10166. //if( result.hasMessage() )
  10167. if (_stats.infoMessages.size() == 1)
  10168. messageLabel = "with message";
  10169. if (_stats.infoMessages.size() > 1)
  10170. messageLabel = "with messages";
  10171. break;
  10172. case ResultWas::ExpressionFailed:
  10173. if (result.isOk()) {
  10174. colour = Colour::Success;
  10175. passOrFail = "FAILED - but was ok";
  10176. } else {
  10177. colour = Colour::Error;
  10178. passOrFail = "FAILED";
  10179. }
  10180. if (_stats.infoMessages.size() == 1)
  10181. messageLabel = "with message";
  10182. if (_stats.infoMessages.size() > 1)
  10183. messageLabel = "with messages";
  10184. break;
  10185. case ResultWas::ThrewException:
  10186. colour = Colour::Error;
  10187. passOrFail = "FAILED";
  10188. messageLabel = "due to unexpected exception with ";
  10189. if (_stats.infoMessages.size() == 1)
  10190. messageLabel += "message";
  10191. if (_stats.infoMessages.size() > 1)
  10192. messageLabel += "messages";
  10193. break;
  10194. case ResultWas::FatalErrorCondition:
  10195. colour = Colour::Error;
  10196. passOrFail = "FAILED";
  10197. messageLabel = "due to a fatal error condition";
  10198. break;
  10199. case ResultWas::DidntThrowException:
  10200. colour = Colour::Error;
  10201. passOrFail = "FAILED";
  10202. messageLabel = "because no exception was thrown where one was expected";
  10203. break;
  10204. case ResultWas::Info:
  10205. messageLabel = "info";
  10206. break;
  10207. case ResultWas::Warning:
  10208. messageLabel = "warning";
  10209. break;
  10210. case ResultWas::ExplicitFailure:
  10211. passOrFail = "FAILED";
  10212. colour = Colour::Error;
  10213. if (_stats.infoMessages.size() == 1)
  10214. messageLabel = "explicitly with message";
  10215. if (_stats.infoMessages.size() > 1)
  10216. messageLabel = "explicitly with messages";
  10217. break;
  10218. // These cases are here to prevent compiler warnings
  10219. case ResultWas::Unknown:
  10220. case ResultWas::FailureBit:
  10221. case ResultWas::Exception:
  10222. passOrFail = "** internal error **";
  10223. colour = Colour::Error;
  10224. break;
  10225. }
  10226. }
  10227. void print() const {
  10228. printSourceInfo();
  10229. if (stats.totals.assertions.total() > 0) {
  10230. if (result.isOk())
  10231. stream << '\n';
  10232. printResultType();
  10233. printOriginalExpression();
  10234. printReconstructedExpression();
  10235. } else {
  10236. stream << '\n';
  10237. }
  10238. printMessage();
  10239. }
  10240. private:
  10241. void printResultType() const {
  10242. if (!passOrFail.empty()) {
  10243. Colour colourGuard(colour);
  10244. stream << passOrFail << ":\n";
  10245. }
  10246. }
  10247. void printOriginalExpression() const {
  10248. if (result.hasExpression()) {
  10249. Colour colourGuard(Colour::OriginalExpression);
  10250. stream << " ";
  10251. stream << result.getExpressionInMacro();
  10252. stream << '\n';
  10253. }
  10254. }
  10255. void printReconstructedExpression() const {
  10256. if (result.hasExpandedExpression()) {
  10257. stream << "with expansion:\n";
  10258. Colour colourGuard(Colour::ReconstructedExpression);
  10259. stream << Column(result.getExpandedExpression()).indent(2) << '\n';
  10260. }
  10261. }
  10262. void printMessage() const {
  10263. if (!messageLabel.empty())
  10264. stream << messageLabel << ':' << '\n';
  10265. for (auto const& msg : messages) {
  10266. // If this assertion is a warning ignore any INFO messages
  10267. if (printInfoMessages || msg.type != ResultWas::Info)
  10268. stream << Column(msg.message).indent(2) << '\n';
  10269. }
  10270. }
  10271. void printSourceInfo() const {
  10272. Colour colourGuard(Colour::FileName);
  10273. stream << result.getSourceInfo() << ": ";
  10274. }
  10275. std::ostream& stream;
  10276. AssertionStats const& stats;
  10277. AssertionResult const& result;
  10278. Colour::Code colour;
  10279. std::string passOrFail;
  10280. std::string messageLabel;
  10281. std::string message;
  10282. std::vector<MessageInfo> messages;
  10283. bool printInfoMessages;
  10284. };
  10285. std::size_t makeRatio(std::size_t number, std::size_t total) {
  10286. std::size_t ratio = total > 0 ? CATCH_CONFIG_CONSOLE_WIDTH * number / total : 0;
  10287. return (ratio == 0 && number > 0) ? 1 : ratio;
  10288. }
  10289. std::size_t& findMax(std::size_t& i, std::size_t& j, std::size_t& k) {
  10290. if (i > j && i > k)
  10291. return i;
  10292. else if (j > k)
  10293. return j;
  10294. else
  10295. return k;
  10296. }
  10297. struct ColumnInfo {
  10298. enum Justification { Left, Right };
  10299. std::string name;
  10300. int width;
  10301. Justification justification;
  10302. };
  10303. struct ColumnBreak {};
  10304. struct RowBreak {};
  10305. class Duration {
  10306. enum class Unit {
  10307. Auto,
  10308. Nanoseconds,
  10309. Microseconds,
  10310. Milliseconds,
  10311. Seconds,
  10312. Minutes
  10313. };
  10314. static const uint64_t s_nanosecondsInAMicrosecond = 1000;
  10315. static const uint64_t s_nanosecondsInAMillisecond = 1000 * s_nanosecondsInAMicrosecond;
  10316. static const uint64_t s_nanosecondsInASecond = 1000 * s_nanosecondsInAMillisecond;
  10317. static const uint64_t s_nanosecondsInAMinute = 60 * s_nanosecondsInASecond;
  10318. uint64_t m_inNanoseconds;
  10319. Unit m_units;
  10320. public:
  10321. explicit Duration(uint64_t inNanoseconds, Unit units = Unit::Auto)
  10322. : m_inNanoseconds(inNanoseconds),
  10323. m_units(units) {
  10324. if (m_units == Unit::Auto) {
  10325. if (m_inNanoseconds < s_nanosecondsInAMicrosecond)
  10326. m_units = Unit::Nanoseconds;
  10327. else if (m_inNanoseconds < s_nanosecondsInAMillisecond)
  10328. m_units = Unit::Microseconds;
  10329. else if (m_inNanoseconds < s_nanosecondsInASecond)
  10330. m_units = Unit::Milliseconds;
  10331. else if (m_inNanoseconds < s_nanosecondsInAMinute)
  10332. m_units = Unit::Seconds;
  10333. else
  10334. m_units = Unit::Minutes;
  10335. }
  10336. }
  10337. auto value() const -> double {
  10338. switch (m_units) {
  10339. case Unit::Microseconds:
  10340. return m_inNanoseconds / static_cast<double>(s_nanosecondsInAMicrosecond);
  10341. case Unit::Milliseconds:
  10342. return m_inNanoseconds / static_cast<double>(s_nanosecondsInAMillisecond);
  10343. case Unit::Seconds:
  10344. return m_inNanoseconds / static_cast<double>(s_nanosecondsInASecond);
  10345. case Unit::Minutes:
  10346. return m_inNanoseconds / static_cast<double>(s_nanosecondsInAMinute);
  10347. default:
  10348. return static_cast<double>(m_inNanoseconds);
  10349. }
  10350. }
  10351. auto unitsAsString() const -> std::string {
  10352. switch (m_units) {
  10353. case Unit::Nanoseconds:
  10354. return "ns";
  10355. case Unit::Microseconds:
  10356. return "µs";
  10357. case Unit::Milliseconds:
  10358. return "ms";
  10359. case Unit::Seconds:
  10360. return "s";
  10361. case Unit::Minutes:
  10362. return "m";
  10363. default:
  10364. return "** internal error **";
  10365. }
  10366. }
  10367. friend auto operator << (std::ostream& os, Duration const& duration) -> std::ostream& {
  10368. return os << duration.value() << " " << duration.unitsAsString();
  10369. }
  10370. };
  10371. } // end anon namespace
  10372. class TablePrinter {
  10373. std::ostream& m_os;
  10374. std::vector<ColumnInfo> m_columnInfos;
  10375. std::ostringstream m_oss;
  10376. int m_currentColumn = -1;
  10377. bool m_isOpen = false;
  10378. public:
  10379. TablePrinter( std::ostream& os, std::vector<ColumnInfo> columnInfos )
  10380. : m_os( os ),
  10381. m_columnInfos( std::move( columnInfos ) ) {}
  10382. auto columnInfos() const -> std::vector<ColumnInfo> const& {
  10383. return m_columnInfos;
  10384. }
  10385. void open() {
  10386. if (!m_isOpen) {
  10387. m_isOpen = true;
  10388. *this << RowBreak();
  10389. for (auto const& info : m_columnInfos)
  10390. *this << info.name << ColumnBreak();
  10391. *this << RowBreak();
  10392. m_os << Catch::getLineOfChars<'-'>() << "\n";
  10393. }
  10394. }
  10395. void close() {
  10396. if (m_isOpen) {
  10397. *this << RowBreak();
  10398. m_os << std::endl;
  10399. m_isOpen = false;
  10400. }
  10401. }
  10402. template<typename T>
  10403. friend TablePrinter& operator << (TablePrinter& tp, T const& value) {
  10404. tp.m_oss << value;
  10405. return tp;
  10406. }
  10407. friend TablePrinter& operator << (TablePrinter& tp, ColumnBreak) {
  10408. auto colStr = tp.m_oss.str();
  10409. // This takes account of utf8 encodings
  10410. auto strSize = Catch::StringRef(colStr).numberOfCharacters();
  10411. tp.m_oss.str("");
  10412. tp.open();
  10413. if (tp.m_currentColumn == static_cast<int>(tp.m_columnInfos.size() - 1)) {
  10414. tp.m_currentColumn = -1;
  10415. tp.m_os << "\n";
  10416. }
  10417. tp.m_currentColumn++;
  10418. auto colInfo = tp.m_columnInfos[tp.m_currentColumn];
  10419. auto padding = (strSize + 2 < static_cast<std::size_t>(colInfo.width))
  10420. ? std::string(colInfo.width - (strSize + 2), ' ')
  10421. : std::string();
  10422. if (colInfo.justification == ColumnInfo::Left)
  10423. tp.m_os << colStr << padding << " ";
  10424. else
  10425. tp.m_os << padding << colStr << " ";
  10426. return tp;
  10427. }
  10428. friend TablePrinter& operator << (TablePrinter& tp, RowBreak) {
  10429. if (tp.m_currentColumn > 0) {
  10430. tp.m_os << "\n";
  10431. tp.m_currentColumn = -1;
  10432. }
  10433. return tp;
  10434. }
  10435. };
  10436. ConsoleReporter::ConsoleReporter(ReporterConfig const& config)
  10437. : StreamingReporterBase(config),
  10438. m_tablePrinter(new TablePrinter(config.stream(),
  10439. {
  10440. { "benchmark name", CATCH_CONFIG_CONSOLE_WIDTH - 32, ColumnInfo::Left },
  10441. { "iters", 8, ColumnInfo::Right },
  10442. { "elapsed ns", 14, ColumnInfo::Right },
  10443. { "average", 14, ColumnInfo::Right }
  10444. })) {}
  10445. ConsoleReporter::~ConsoleReporter() = default;
  10446. std::string ConsoleReporter::getDescription() {
  10447. return "Reports test results as plain lines of text";
  10448. }
  10449. void ConsoleReporter::noMatchingTestCases(std::string const& spec) {
  10450. stream << "No test cases matched '" << spec << '\'' << std::endl;
  10451. }
  10452. void ConsoleReporter::assertionStarting(AssertionInfo const&) {}
  10453. bool ConsoleReporter::assertionEnded(AssertionStats const& _assertionStats) {
  10454. AssertionResult const& result = _assertionStats.assertionResult;
  10455. bool includeResults = m_config->includeSuccessfulResults() || !result.isOk();
  10456. // Drop out if result was successful but we're not printing them.
  10457. if (!includeResults && result.getResultType() != ResultWas::Warning)
  10458. return false;
  10459. lazyPrint();
  10460. ConsoleAssertionPrinter printer(stream, _assertionStats, includeResults);
  10461. printer.print();
  10462. stream << std::endl;
  10463. return true;
  10464. }
  10465. void ConsoleReporter::sectionStarting(SectionInfo const& _sectionInfo) {
  10466. m_headerPrinted = false;
  10467. StreamingReporterBase::sectionStarting(_sectionInfo);
  10468. }
  10469. void ConsoleReporter::sectionEnded(SectionStats const& _sectionStats) {
  10470. m_tablePrinter->close();
  10471. if (_sectionStats.missingAssertions) {
  10472. lazyPrint();
  10473. Colour colour(Colour::ResultError);
  10474. if (m_sectionStack.size() > 1)
  10475. stream << "\nNo assertions in section";
  10476. else
  10477. stream << "\nNo assertions in test case";
  10478. stream << " '" << _sectionStats.sectionInfo.name << "'\n" << std::endl;
  10479. }
  10480. if (m_config->showDurations() == ShowDurations::Always) {
  10481. stream << getFormattedDuration(_sectionStats.durationInSeconds) << " s: " << _sectionStats.sectionInfo.name << std::endl;
  10482. }
  10483. if (m_headerPrinted) {
  10484. m_headerPrinted = false;
  10485. }
  10486. StreamingReporterBase::sectionEnded(_sectionStats);
  10487. }
  10488. void ConsoleReporter::benchmarkStarting(BenchmarkInfo const& info) {
  10489. lazyPrintWithoutClosingBenchmarkTable();
  10490. auto nameCol = Column( info.name ).width( static_cast<std::size_t>( m_tablePrinter->columnInfos()[0].width - 2 ) );
  10491. bool firstLine = true;
  10492. for (auto line : nameCol) {
  10493. if (!firstLine)
  10494. (*m_tablePrinter) << ColumnBreak() << ColumnBreak() << ColumnBreak();
  10495. else
  10496. firstLine = false;
  10497. (*m_tablePrinter) << line << ColumnBreak();
  10498. }
  10499. }
  10500. void ConsoleReporter::benchmarkEnded(BenchmarkStats const& stats) {
  10501. Duration average(stats.elapsedTimeInNanoseconds / stats.iterations);
  10502. (*m_tablePrinter)
  10503. << stats.iterations << ColumnBreak()
  10504. << stats.elapsedTimeInNanoseconds << ColumnBreak()
  10505. << average << ColumnBreak();
  10506. }
  10507. void ConsoleReporter::testCaseEnded(TestCaseStats const& _testCaseStats) {
  10508. m_tablePrinter->close();
  10509. StreamingReporterBase::testCaseEnded(_testCaseStats);
  10510. m_headerPrinted = false;
  10511. }
  10512. void ConsoleReporter::testGroupEnded(TestGroupStats const& _testGroupStats) {
  10513. if (currentGroupInfo.used) {
  10514. printSummaryDivider();
  10515. stream << "Summary for group '" << _testGroupStats.groupInfo.name << "':\n";
  10516. printTotals(_testGroupStats.totals);
  10517. stream << '\n' << std::endl;
  10518. }
  10519. StreamingReporterBase::testGroupEnded(_testGroupStats);
  10520. }
  10521. void ConsoleReporter::testRunEnded(TestRunStats const& _testRunStats) {
  10522. printTotalsDivider(_testRunStats.totals);
  10523. printTotals(_testRunStats.totals);
  10524. stream << std::endl;
  10525. StreamingReporterBase::testRunEnded(_testRunStats);
  10526. }
  10527. void ConsoleReporter::lazyPrint() {
  10528. m_tablePrinter->close();
  10529. lazyPrintWithoutClosingBenchmarkTable();
  10530. }
  10531. void ConsoleReporter::lazyPrintWithoutClosingBenchmarkTable() {
  10532. if (!currentTestRunInfo.used)
  10533. lazyPrintRunInfo();
  10534. if (!currentGroupInfo.used)
  10535. lazyPrintGroupInfo();
  10536. if (!m_headerPrinted) {
  10537. printTestCaseAndSectionHeader();
  10538. m_headerPrinted = true;
  10539. }
  10540. }
  10541. void ConsoleReporter::lazyPrintRunInfo() {
  10542. stream << '\n' << getLineOfChars<'~'>() << '\n';
  10543. Colour colour(Colour::SecondaryText);
  10544. stream << currentTestRunInfo->name
  10545. << " is a Catch v" << libraryVersion() << " host application.\n"
  10546. << "Run with -? for options\n\n";
  10547. if (m_config->rngSeed() != 0)
  10548. stream << "Randomness seeded to: " << m_config->rngSeed() << "\n\n";
  10549. currentTestRunInfo.used = true;
  10550. }
  10551. void ConsoleReporter::lazyPrintGroupInfo() {
  10552. if (!currentGroupInfo->name.empty() && currentGroupInfo->groupsCounts > 1) {
  10553. printClosedHeader("Group: " + currentGroupInfo->name);
  10554. currentGroupInfo.used = true;
  10555. }
  10556. }
  10557. void ConsoleReporter::printTestCaseAndSectionHeader() {
  10558. assert(!m_sectionStack.empty());
  10559. printOpenHeader(currentTestCaseInfo->name);
  10560. if (m_sectionStack.size() > 1) {
  10561. Colour colourGuard(Colour::Headers);
  10562. auto
  10563. it = m_sectionStack.begin() + 1, // Skip first section (test case)
  10564. itEnd = m_sectionStack.end();
  10565. for (; it != itEnd; ++it)
  10566. printHeaderString(it->name, 2);
  10567. }
  10568. SourceLineInfo lineInfo = m_sectionStack.back().lineInfo;
  10569. if (!lineInfo.empty()) {
  10570. stream << getLineOfChars<'-'>() << '\n';
  10571. Colour colourGuard(Colour::FileName);
  10572. stream << lineInfo << '\n';
  10573. }
  10574. stream << getLineOfChars<'.'>() << '\n' << std::endl;
  10575. }
  10576. void ConsoleReporter::printClosedHeader(std::string const& _name) {
  10577. printOpenHeader(_name);
  10578. stream << getLineOfChars<'.'>() << '\n';
  10579. }
  10580. void ConsoleReporter::printOpenHeader(std::string const& _name) {
  10581. stream << getLineOfChars<'-'>() << '\n';
  10582. {
  10583. Colour colourGuard(Colour::Headers);
  10584. printHeaderString(_name);
  10585. }
  10586. }
  10587. // if string has a : in first line will set indent to follow it on
  10588. // subsequent lines
  10589. void ConsoleReporter::printHeaderString(std::string const& _string, std::size_t indent) {
  10590. std::size_t i = _string.find(": ");
  10591. if (i != std::string::npos)
  10592. i += 2;
  10593. else
  10594. i = 0;
  10595. stream << Column(_string).indent(indent + i).initialIndent(indent) << '\n';
  10596. }
  10597. struct SummaryColumn {
  10598. SummaryColumn( std::string _label, Colour::Code _colour )
  10599. : label( std::move( _label ) ),
  10600. colour( _colour ) {}
  10601. SummaryColumn addRow( std::size_t count ) {
  10602. ReusableStringStream rss;
  10603. rss << count;
  10604. std::string row = rss.str();
  10605. for (auto& oldRow : rows) {
  10606. while (oldRow.size() < row.size())
  10607. oldRow = ' ' + oldRow;
  10608. while (oldRow.size() > row.size())
  10609. row = ' ' + row;
  10610. }
  10611. rows.push_back(row);
  10612. return *this;
  10613. }
  10614. std::string label;
  10615. Colour::Code colour;
  10616. std::vector<std::string> rows;
  10617. };
  10618. void ConsoleReporter::printTotals( Totals const& totals ) {
  10619. if (totals.testCases.total() == 0) {
  10620. stream << Colour(Colour::Warning) << "No tests ran\n";
  10621. } else if (totals.assertions.total() > 0 && totals.testCases.allPassed()) {
  10622. stream << Colour(Colour::ResultSuccess) << "All tests passed";
  10623. stream << " ("
  10624. << pluralise(totals.assertions.passed, "assertion") << " in "
  10625. << pluralise(totals.testCases.passed, "test case") << ')'
  10626. << '\n';
  10627. } else {
  10628. std::vector<SummaryColumn> columns;
  10629. columns.push_back(SummaryColumn("", Colour::None)
  10630. .addRow(totals.testCases.total())
  10631. .addRow(totals.assertions.total()));
  10632. columns.push_back(SummaryColumn("passed", Colour::Success)
  10633. .addRow(totals.testCases.passed)
  10634. .addRow(totals.assertions.passed));
  10635. columns.push_back(SummaryColumn("failed", Colour::ResultError)
  10636. .addRow(totals.testCases.failed)
  10637. .addRow(totals.assertions.failed));
  10638. columns.push_back(SummaryColumn("failed as expected", Colour::ResultExpectedFailure)
  10639. .addRow(totals.testCases.failedButOk)
  10640. .addRow(totals.assertions.failedButOk));
  10641. printSummaryRow("test cases", columns, 0);
  10642. printSummaryRow("assertions", columns, 1);
  10643. }
  10644. }
  10645. void ConsoleReporter::printSummaryRow(std::string const& label, std::vector<SummaryColumn> const& cols, std::size_t row) {
  10646. for (auto col : cols) {
  10647. std::string value = col.rows[row];
  10648. if (col.label.empty()) {
  10649. stream << label << ": ";
  10650. if (value != "0")
  10651. stream << value;
  10652. else
  10653. stream << Colour(Colour::Warning) << "- none -";
  10654. } else if (value != "0") {
  10655. stream << Colour(Colour::LightGrey) << " | ";
  10656. stream << Colour(col.colour)
  10657. << value << ' ' << col.label;
  10658. }
  10659. }
  10660. stream << '\n';
  10661. }
  10662. void ConsoleReporter::printTotalsDivider(Totals const& totals) {
  10663. if (totals.testCases.total() > 0) {
  10664. std::size_t failedRatio = makeRatio(totals.testCases.failed, totals.testCases.total());
  10665. std::size_t failedButOkRatio = makeRatio(totals.testCases.failedButOk, totals.testCases.total());
  10666. std::size_t passedRatio = makeRatio(totals.testCases.passed, totals.testCases.total());
  10667. while (failedRatio + failedButOkRatio + passedRatio < CATCH_CONFIG_CONSOLE_WIDTH - 1)
  10668. findMax(failedRatio, failedButOkRatio, passedRatio)++;
  10669. while (failedRatio + failedButOkRatio + passedRatio > CATCH_CONFIG_CONSOLE_WIDTH - 1)
  10670. findMax(failedRatio, failedButOkRatio, passedRatio)--;
  10671. stream << Colour(Colour::Error) << std::string(failedRatio, '=');
  10672. stream << Colour(Colour::ResultExpectedFailure) << std::string(failedButOkRatio, '=');
  10673. if (totals.testCases.allPassed())
  10674. stream << Colour(Colour::ResultSuccess) << std::string(passedRatio, '=');
  10675. else
  10676. stream << Colour(Colour::Success) << std::string(passedRatio, '=');
  10677. } else {
  10678. stream << Colour(Colour::Warning) << std::string(CATCH_CONFIG_CONSOLE_WIDTH - 1, '=');
  10679. }
  10680. stream << '\n';
  10681. }
  10682. void ConsoleReporter::printSummaryDivider() {
  10683. stream << getLineOfChars<'-'>() << '\n';
  10684. }
  10685. CATCH_REGISTER_REPORTER("console", ConsoleReporter)
  10686. } // end namespace Catch
  10687. #if defined(_MSC_VER)
  10688. #pragma warning(pop)
  10689. #endif
  10690. // end catch_reporter_console.cpp
  10691. // start catch_reporter_junit.cpp
  10692. #include <cassert>
  10693. #include <sstream>
  10694. #include <ctime>
  10695. #include <algorithm>
  10696. namespace Catch {
  10697. namespace {
  10698. std::string getCurrentTimestamp() {
  10699. // Beware, this is not reentrant because of backward compatibility issues
  10700. // Also, UTC only, again because of backward compatibility (%z is C++11)
  10701. time_t rawtime;
  10702. std::time(&rawtime);
  10703. auto const timeStampSize = sizeof("2017-01-16T17:06:45Z");
  10704. #ifdef _MSC_VER
  10705. std::tm timeInfo = {};
  10706. gmtime_s(&timeInfo, &rawtime);
  10707. #else
  10708. std::tm* timeInfo;
  10709. timeInfo = std::gmtime(&rawtime);
  10710. #endif
  10711. char timeStamp[timeStampSize];
  10712. const char * const fmt = "%Y-%m-%dT%H:%M:%SZ";
  10713. #ifdef _MSC_VER
  10714. std::strftime(timeStamp, timeStampSize, fmt, &timeInfo);
  10715. #else
  10716. std::strftime(timeStamp, timeStampSize, fmt, timeInfo);
  10717. #endif
  10718. return std::string(timeStamp);
  10719. }
  10720. std::string fileNameTag(const std::vector<std::string> &tags) {
  10721. auto it = std::find_if(begin(tags),
  10722. end(tags),
  10723. [] (std::string const& tag) {return tag.front() == '#'; });
  10724. if (it != tags.end())
  10725. return it->substr(1);
  10726. return std::string();
  10727. }
  10728. } // anonymous namespace
  10729. JunitReporter::JunitReporter( ReporterConfig const& _config )
  10730. : CumulativeReporterBase( _config ),
  10731. xml( _config.stream() )
  10732. {
  10733. m_reporterPrefs.shouldRedirectStdOut = true;
  10734. m_reporterPrefs.shouldReportAllAssertions = true;
  10735. }
  10736. JunitReporter::~JunitReporter() {}
  10737. std::string JunitReporter::getDescription() {
  10738. return "Reports test results in an XML format that looks like Ant's junitreport target";
  10739. }
  10740. void JunitReporter::noMatchingTestCases( std::string const& /*spec*/ ) {}
  10741. void JunitReporter::testRunStarting( TestRunInfo const& runInfo ) {
  10742. CumulativeReporterBase::testRunStarting( runInfo );
  10743. xml.startElement( "testsuites" );
  10744. }
  10745. void JunitReporter::testGroupStarting( GroupInfo const& groupInfo ) {
  10746. suiteTimer.start();
  10747. stdOutForSuite.clear();
  10748. stdErrForSuite.clear();
  10749. unexpectedExceptions = 0;
  10750. CumulativeReporterBase::testGroupStarting( groupInfo );
  10751. }
  10752. void JunitReporter::testCaseStarting( TestCaseInfo const& testCaseInfo ) {
  10753. m_okToFail = testCaseInfo.okToFail();
  10754. }
  10755. bool JunitReporter::assertionEnded( AssertionStats const& assertionStats ) {
  10756. if( assertionStats.assertionResult.getResultType() == ResultWas::ThrewException && !m_okToFail )
  10757. unexpectedExceptions++;
  10758. return CumulativeReporterBase::assertionEnded( assertionStats );
  10759. }
  10760. void JunitReporter::testCaseEnded( TestCaseStats const& testCaseStats ) {
  10761. stdOutForSuite += testCaseStats.stdOut;
  10762. stdErrForSuite += testCaseStats.stdErr;
  10763. CumulativeReporterBase::testCaseEnded( testCaseStats );
  10764. }
  10765. void JunitReporter::testGroupEnded( TestGroupStats const& testGroupStats ) {
  10766. double suiteTime = suiteTimer.getElapsedSeconds();
  10767. CumulativeReporterBase::testGroupEnded( testGroupStats );
  10768. writeGroup( *m_testGroups.back(), suiteTime );
  10769. }
  10770. void JunitReporter::testRunEndedCumulative() {
  10771. xml.endElement();
  10772. }
  10773. void JunitReporter::writeGroup( TestGroupNode const& groupNode, double suiteTime ) {
  10774. XmlWriter::ScopedElement e = xml.scopedElement( "testsuite" );
  10775. TestGroupStats const& stats = groupNode.value;
  10776. xml.writeAttribute( "name", stats.groupInfo.name );
  10777. xml.writeAttribute( "errors", unexpectedExceptions );
  10778. xml.writeAttribute( "failures", stats.totals.assertions.failed-unexpectedExceptions );
  10779. xml.writeAttribute( "tests", stats.totals.assertions.total() );
  10780. xml.writeAttribute( "hostname", "tbd" ); // !TBD
  10781. if( m_config->showDurations() == ShowDurations::Never )
  10782. xml.writeAttribute( "time", "" );
  10783. else
  10784. xml.writeAttribute( "time", suiteTime );
  10785. xml.writeAttribute( "timestamp", getCurrentTimestamp() );
  10786. // Write test cases
  10787. for( auto const& child : groupNode.children )
  10788. writeTestCase( *child );
  10789. xml.scopedElement( "system-out" ).writeText( trim( stdOutForSuite ), false );
  10790. xml.scopedElement( "system-err" ).writeText( trim( stdErrForSuite ), false );
  10791. }
  10792. void JunitReporter::writeTestCase( TestCaseNode const& testCaseNode ) {
  10793. TestCaseStats const& stats = testCaseNode.value;
  10794. // All test cases have exactly one section - which represents the
  10795. // test case itself. That section may have 0-n nested sections
  10796. assert( testCaseNode.children.size() == 1 );
  10797. SectionNode const& rootSection = *testCaseNode.children.front();
  10798. std::string className = stats.testInfo.className;
  10799. if( className.empty() ) {
  10800. className = fileNameTag(stats.testInfo.tags);
  10801. if ( className.empty() )
  10802. className = "global";
  10803. }
  10804. if ( !m_config->name().empty() )
  10805. className = m_config->name() + "." + className;
  10806. writeSection( className, "", rootSection );
  10807. }
  10808. void JunitReporter::writeSection( std::string const& className,
  10809. std::string const& rootName,
  10810. SectionNode const& sectionNode ) {
  10811. std::string name = trim( sectionNode.stats.sectionInfo.name );
  10812. if( !rootName.empty() )
  10813. name = rootName + '/' + name;
  10814. if( !sectionNode.assertions.empty() ||
  10815. !sectionNode.stdOut.empty() ||
  10816. !sectionNode.stdErr.empty() ) {
  10817. XmlWriter::ScopedElement e = xml.scopedElement( "testcase" );
  10818. if( className.empty() ) {
  10819. xml.writeAttribute( "classname", name );
  10820. xml.writeAttribute( "name", "root" );
  10821. }
  10822. else {
  10823. xml.writeAttribute( "classname", className );
  10824. xml.writeAttribute( "name", name );
  10825. }
  10826. xml.writeAttribute( "time", ::Catch::Detail::stringify( sectionNode.stats.durationInSeconds ) );
  10827. writeAssertions( sectionNode );
  10828. if( !sectionNode.stdOut.empty() )
  10829. xml.scopedElement( "system-out" ).writeText( trim( sectionNode.stdOut ), false );
  10830. if( !sectionNode.stdErr.empty() )
  10831. xml.scopedElement( "system-err" ).writeText( trim( sectionNode.stdErr ), false );
  10832. }
  10833. for( auto const& childNode : sectionNode.childSections )
  10834. if( className.empty() )
  10835. writeSection( name, "", *childNode );
  10836. else
  10837. writeSection( className, name, *childNode );
  10838. }
  10839. void JunitReporter::writeAssertions( SectionNode const& sectionNode ) {
  10840. for( auto const& assertion : sectionNode.assertions )
  10841. writeAssertion( assertion );
  10842. }
  10843. void JunitReporter::writeAssertion( AssertionStats const& stats ) {
  10844. AssertionResult const& result = stats.assertionResult;
  10845. if( !result.isOk() ) {
  10846. std::string elementName;
  10847. switch( result.getResultType() ) {
  10848. case ResultWas::ThrewException:
  10849. case ResultWas::FatalErrorCondition:
  10850. elementName = "error";
  10851. break;
  10852. case ResultWas::ExplicitFailure:
  10853. elementName = "failure";
  10854. break;
  10855. case ResultWas::ExpressionFailed:
  10856. elementName = "failure";
  10857. break;
  10858. case ResultWas::DidntThrowException:
  10859. elementName = "failure";
  10860. break;
  10861. // We should never see these here:
  10862. case ResultWas::Info:
  10863. case ResultWas::Warning:
  10864. case ResultWas::Ok:
  10865. case ResultWas::Unknown:
  10866. case ResultWas::FailureBit:
  10867. case ResultWas::Exception:
  10868. elementName = "internalError";
  10869. break;
  10870. }
  10871. XmlWriter::ScopedElement e = xml.scopedElement( elementName );
  10872. xml.writeAttribute( "message", result.getExpandedExpression() );
  10873. xml.writeAttribute( "type", result.getTestMacroName() );
  10874. ReusableStringStream rss;
  10875. if( !result.getMessage().empty() )
  10876. rss << result.getMessage() << '\n';
  10877. for( auto const& msg : stats.infoMessages )
  10878. if( msg.type == ResultWas::Info )
  10879. rss << msg.message << '\n';
  10880. rss << "at " << result.getSourceInfo();
  10881. xml.writeText( rss.str(), false );
  10882. }
  10883. }
  10884. CATCH_REGISTER_REPORTER( "junit", JunitReporter )
  10885. } // end namespace Catch
  10886. // end catch_reporter_junit.cpp
  10887. // start catch_reporter_listening.cpp
  10888. #include <cassert>
  10889. namespace Catch {
  10890. ListeningReporter::ListeningReporter() {
  10891. // We will assume that listeners will always want all assertions
  10892. m_preferences.shouldReportAllAssertions = true;
  10893. }
  10894. void ListeningReporter::addListener( IStreamingReporterPtr&& listener ) {
  10895. m_listeners.push_back( std::move( listener ) );
  10896. }
  10897. void ListeningReporter::addReporter(IStreamingReporterPtr&& reporter) {
  10898. assert(!m_reporter && "Listening reporter can wrap only 1 real reporter");
  10899. m_reporter = std::move( reporter );
  10900. m_preferences.shouldRedirectStdOut = m_reporter->getPreferences().shouldRedirectStdOut;
  10901. }
  10902. ReporterPreferences ListeningReporter::getPreferences() const {
  10903. return m_preferences;
  10904. }
  10905. std::set<Verbosity> ListeningReporter::getSupportedVerbosities() {
  10906. return std::set<Verbosity>{ };
  10907. }
  10908. void ListeningReporter::noMatchingTestCases( std::string const& spec ) {
  10909. for ( auto const& listener : m_listeners ) {
  10910. listener->noMatchingTestCases( spec );
  10911. }
  10912. m_reporter->noMatchingTestCases( spec );
  10913. }
  10914. void ListeningReporter::benchmarkStarting( BenchmarkInfo const& benchmarkInfo ) {
  10915. for ( auto const& listener : m_listeners ) {
  10916. listener->benchmarkStarting( benchmarkInfo );
  10917. }
  10918. m_reporter->benchmarkStarting( benchmarkInfo );
  10919. }
  10920. void ListeningReporter::benchmarkEnded( BenchmarkStats const& benchmarkStats ) {
  10921. for ( auto const& listener : m_listeners ) {
  10922. listener->benchmarkEnded( benchmarkStats );
  10923. }
  10924. m_reporter->benchmarkEnded( benchmarkStats );
  10925. }
  10926. void ListeningReporter::testRunStarting( TestRunInfo const& testRunInfo ) {
  10927. for ( auto const& listener : m_listeners ) {
  10928. listener->testRunStarting( testRunInfo );
  10929. }
  10930. m_reporter->testRunStarting( testRunInfo );
  10931. }
  10932. void ListeningReporter::testGroupStarting( GroupInfo const& groupInfo ) {
  10933. for ( auto const& listener : m_listeners ) {
  10934. listener->testGroupStarting( groupInfo );
  10935. }
  10936. m_reporter->testGroupStarting( groupInfo );
  10937. }
  10938. void ListeningReporter::testCaseStarting( TestCaseInfo const& testInfo ) {
  10939. for ( auto const& listener : m_listeners ) {
  10940. listener->testCaseStarting( testInfo );
  10941. }
  10942. m_reporter->testCaseStarting( testInfo );
  10943. }
  10944. void ListeningReporter::sectionStarting( SectionInfo const& sectionInfo ) {
  10945. for ( auto const& listener : m_listeners ) {
  10946. listener->sectionStarting( sectionInfo );
  10947. }
  10948. m_reporter->sectionStarting( sectionInfo );
  10949. }
  10950. void ListeningReporter::assertionStarting( AssertionInfo const& assertionInfo ) {
  10951. for ( auto const& listener : m_listeners ) {
  10952. listener->assertionStarting( assertionInfo );
  10953. }
  10954. m_reporter->assertionStarting( assertionInfo );
  10955. }
  10956. // The return value indicates if the messages buffer should be cleared:
  10957. bool ListeningReporter::assertionEnded( AssertionStats const& assertionStats ) {
  10958. for( auto const& listener : m_listeners ) {
  10959. static_cast<void>( listener->assertionEnded( assertionStats ) );
  10960. }
  10961. return m_reporter->assertionEnded( assertionStats );
  10962. }
  10963. void ListeningReporter::sectionEnded( SectionStats const& sectionStats ) {
  10964. for ( auto const& listener : m_listeners ) {
  10965. listener->sectionEnded( sectionStats );
  10966. }
  10967. m_reporter->sectionEnded( sectionStats );
  10968. }
  10969. void ListeningReporter::testCaseEnded( TestCaseStats const& testCaseStats ) {
  10970. for ( auto const& listener : m_listeners ) {
  10971. listener->testCaseEnded( testCaseStats );
  10972. }
  10973. m_reporter->testCaseEnded( testCaseStats );
  10974. }
  10975. void ListeningReporter::testGroupEnded( TestGroupStats const& testGroupStats ) {
  10976. for ( auto const& listener : m_listeners ) {
  10977. listener->testGroupEnded( testGroupStats );
  10978. }
  10979. m_reporter->testGroupEnded( testGroupStats );
  10980. }
  10981. void ListeningReporter::testRunEnded( TestRunStats const& testRunStats ) {
  10982. for ( auto const& listener : m_listeners ) {
  10983. listener->testRunEnded( testRunStats );
  10984. }
  10985. m_reporter->testRunEnded( testRunStats );
  10986. }
  10987. void ListeningReporter::skipTest( TestCaseInfo const& testInfo ) {
  10988. for ( auto const& listener : m_listeners ) {
  10989. listener->skipTest( testInfo );
  10990. }
  10991. m_reporter->skipTest( testInfo );
  10992. }
  10993. bool ListeningReporter::isMulti() const {
  10994. return true;
  10995. }
  10996. } // end namespace Catch
  10997. // end catch_reporter_listening.cpp
  10998. // start catch_reporter_xml.cpp
  10999. #if defined(_MSC_VER)
  11000. #pragma warning(push)
  11001. #pragma warning(disable:4061) // Not all labels are EXPLICITLY handled in switch
  11002. // Note that 4062 (not all labels are handled
  11003. // and default is missing) is enabled
  11004. #endif
  11005. namespace Catch {
  11006. XmlReporter::XmlReporter( ReporterConfig const& _config )
  11007. : StreamingReporterBase( _config ),
  11008. m_xml(_config.stream())
  11009. {
  11010. m_reporterPrefs.shouldRedirectStdOut = true;
  11011. m_reporterPrefs.shouldReportAllAssertions = true;
  11012. }
  11013. XmlReporter::~XmlReporter() = default;
  11014. std::string XmlReporter::getDescription() {
  11015. return "Reports test results as an XML document";
  11016. }
  11017. std::string XmlReporter::getStylesheetRef() const {
  11018. return std::string();
  11019. }
  11020. void XmlReporter::writeSourceInfo( SourceLineInfo const& sourceInfo ) {
  11021. m_xml
  11022. .writeAttribute( "filename", sourceInfo.file )
  11023. .writeAttribute( "line", sourceInfo.line );
  11024. }
  11025. void XmlReporter::noMatchingTestCases( std::string const& s ) {
  11026. StreamingReporterBase::noMatchingTestCases( s );
  11027. }
  11028. void XmlReporter::testRunStarting( TestRunInfo const& testInfo ) {
  11029. StreamingReporterBase::testRunStarting( testInfo );
  11030. std::string stylesheetRef = getStylesheetRef();
  11031. if( !stylesheetRef.empty() )
  11032. m_xml.writeStylesheetRef( stylesheetRef );
  11033. m_xml.startElement( "Catch" );
  11034. if( !m_config->name().empty() )
  11035. m_xml.writeAttribute( "name", m_config->name() );
  11036. }
  11037. void XmlReporter::testGroupStarting( GroupInfo const& groupInfo ) {
  11038. StreamingReporterBase::testGroupStarting( groupInfo );
  11039. m_xml.startElement( "Group" )
  11040. .writeAttribute( "name", groupInfo.name );
  11041. }
  11042. void XmlReporter::testCaseStarting( TestCaseInfo const& testInfo ) {
  11043. StreamingReporterBase::testCaseStarting(testInfo);
  11044. m_xml.startElement( "TestCase" )
  11045. .writeAttribute( "name", trim( testInfo.name ) )
  11046. .writeAttribute( "description", testInfo.description )
  11047. .writeAttribute( "tags", testInfo.tagsAsString() );
  11048. writeSourceInfo( testInfo.lineInfo );
  11049. if ( m_config->showDurations() == ShowDurations::Always )
  11050. m_testCaseTimer.start();
  11051. m_xml.ensureTagClosed();
  11052. }
  11053. void XmlReporter::sectionStarting( SectionInfo const& sectionInfo ) {
  11054. StreamingReporterBase::sectionStarting( sectionInfo );
  11055. if( m_sectionDepth++ > 0 ) {
  11056. m_xml.startElement( "Section" )
  11057. .writeAttribute( "name", trim( sectionInfo.name ) );
  11058. writeSourceInfo( sectionInfo.lineInfo );
  11059. m_xml.ensureTagClosed();
  11060. }
  11061. }
  11062. void XmlReporter::assertionStarting( AssertionInfo const& ) { }
  11063. bool XmlReporter::assertionEnded( AssertionStats const& assertionStats ) {
  11064. AssertionResult const& result = assertionStats.assertionResult;
  11065. bool includeResults = m_config->includeSuccessfulResults() || !result.isOk();
  11066. if( includeResults || result.getResultType() == ResultWas::Warning ) {
  11067. // Print any info messages in <Info> tags.
  11068. for( auto const& msg : assertionStats.infoMessages ) {
  11069. if( msg.type == ResultWas::Info && includeResults ) {
  11070. m_xml.scopedElement( "Info" )
  11071. .writeText( msg.message );
  11072. } else if ( msg.type == ResultWas::Warning ) {
  11073. m_xml.scopedElement( "Warning" )
  11074. .writeText( msg.message );
  11075. }
  11076. }
  11077. }
  11078. // Drop out if result was successful but we're not printing them.
  11079. if( !includeResults && result.getResultType() != ResultWas::Warning )
  11080. return true;
  11081. // Print the expression if there is one.
  11082. if( result.hasExpression() ) {
  11083. m_xml.startElement( "Expression" )
  11084. .writeAttribute( "success", result.succeeded() )
  11085. .writeAttribute( "type", result.getTestMacroName() );
  11086. writeSourceInfo( result.getSourceInfo() );
  11087. m_xml.scopedElement( "Original" )
  11088. .writeText( result.getExpression() );
  11089. m_xml.scopedElement( "Expanded" )
  11090. .writeText( result.getExpandedExpression() );
  11091. }
  11092. // And... Print a result applicable to each result type.
  11093. switch( result.getResultType() ) {
  11094. case ResultWas::ThrewException:
  11095. m_xml.startElement( "Exception" );
  11096. writeSourceInfo( result.getSourceInfo() );
  11097. m_xml.writeText( result.getMessage() );
  11098. m_xml.endElement();
  11099. break;
  11100. case ResultWas::FatalErrorCondition:
  11101. m_xml.startElement( "FatalErrorCondition" );
  11102. writeSourceInfo( result.getSourceInfo() );
  11103. m_xml.writeText( result.getMessage() );
  11104. m_xml.endElement();
  11105. break;
  11106. case ResultWas::Info:
  11107. m_xml.scopedElement( "Info" )
  11108. .writeText( result.getMessage() );
  11109. break;
  11110. case ResultWas::Warning:
  11111. // Warning will already have been written
  11112. break;
  11113. case ResultWas::ExplicitFailure:
  11114. m_xml.startElement( "Failure" );
  11115. writeSourceInfo( result.getSourceInfo() );
  11116. m_xml.writeText( result.getMessage() );
  11117. m_xml.endElement();
  11118. break;
  11119. default:
  11120. break;
  11121. }
  11122. if( result.hasExpression() )
  11123. m_xml.endElement();
  11124. return true;
  11125. }
  11126. void XmlReporter::sectionEnded( SectionStats const& sectionStats ) {
  11127. StreamingReporterBase::sectionEnded( sectionStats );
  11128. if( --m_sectionDepth > 0 ) {
  11129. XmlWriter::ScopedElement e = m_xml.scopedElement( "OverallResults" );
  11130. e.writeAttribute( "successes", sectionStats.assertions.passed );
  11131. e.writeAttribute( "failures", sectionStats.assertions.failed );
  11132. e.writeAttribute( "expectedFailures", sectionStats.assertions.failedButOk );
  11133. if ( m_config->showDurations() == ShowDurations::Always )
  11134. e.writeAttribute( "durationInSeconds", sectionStats.durationInSeconds );
  11135. m_xml.endElement();
  11136. }
  11137. }
  11138. void XmlReporter::testCaseEnded( TestCaseStats const& testCaseStats ) {
  11139. StreamingReporterBase::testCaseEnded( testCaseStats );
  11140. XmlWriter::ScopedElement e = m_xml.scopedElement( "OverallResult" );
  11141. e.writeAttribute( "success", testCaseStats.totals.assertions.allOk() );
  11142. if ( m_config->showDurations() == ShowDurations::Always )
  11143. e.writeAttribute( "durationInSeconds", m_testCaseTimer.getElapsedSeconds() );
  11144. if( !testCaseStats.stdOut.empty() )
  11145. m_xml.scopedElement( "StdOut" ).writeText( trim( testCaseStats.stdOut ), false );
  11146. if( !testCaseStats.stdErr.empty() )
  11147. m_xml.scopedElement( "StdErr" ).writeText( trim( testCaseStats.stdErr ), false );
  11148. m_xml.endElement();
  11149. }
  11150. void XmlReporter::testGroupEnded( TestGroupStats const& testGroupStats ) {
  11151. StreamingReporterBase::testGroupEnded( testGroupStats );
  11152. // TODO: Check testGroupStats.aborting and act accordingly.
  11153. m_xml.scopedElement( "OverallResults" )
  11154. .writeAttribute( "successes", testGroupStats.totals.assertions.passed )
  11155. .writeAttribute( "failures", testGroupStats.totals.assertions.failed )
  11156. .writeAttribute( "expectedFailures", testGroupStats.totals.assertions.failedButOk );
  11157. m_xml.endElement();
  11158. }
  11159. void XmlReporter::testRunEnded( TestRunStats const& testRunStats ) {
  11160. StreamingReporterBase::testRunEnded( testRunStats );
  11161. m_xml.scopedElement( "OverallResults" )
  11162. .writeAttribute( "successes", testRunStats.totals.assertions.passed )
  11163. .writeAttribute( "failures", testRunStats.totals.assertions.failed )
  11164. .writeAttribute( "expectedFailures", testRunStats.totals.assertions.failedButOk );
  11165. m_xml.endElement();
  11166. }
  11167. CATCH_REGISTER_REPORTER( "xml", XmlReporter )
  11168. } // end namespace Catch
  11169. #if defined(_MSC_VER)
  11170. #pragma warning(pop)
  11171. #endif
  11172. // end catch_reporter_xml.cpp
  11173. namespace Catch {
  11174. LeakDetector leakDetector;
  11175. }
  11176. #ifdef __clang__
  11177. #pragma clang diagnostic pop
  11178. #endif
  11179. // end catch_impl.hpp
  11180. #endif
  11181. #ifdef CATCH_CONFIG_MAIN
  11182. // start catch_default_main.hpp
  11183. #ifndef __OBJC__
  11184. #if defined(CATCH_CONFIG_WCHAR) && defined(WIN32) && defined(_UNICODE) && !defined(DO_NOT_USE_WMAIN)
  11185. // Standard C/C++ Win32 Unicode wmain entry point
  11186. extern "C" int wmain (int argc, wchar_t * argv[], wchar_t * []) {
  11187. #else
  11188. // Standard C/C++ main entry point
  11189. int main (int argc, char * argv[]) {
  11190. #endif
  11191. return Catch::Session().run( argc, argv );
  11192. }
  11193. #else // __OBJC__
  11194. // Objective-C entry point
  11195. int main (int argc, char * const argv[]) {
  11196. #if !CATCH_ARC_ENABLED
  11197. NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
  11198. #endif
  11199. Catch::registerTestMethods();
  11200. int result = Catch::Session().run( argc, (char**)argv );
  11201. #if !CATCH_ARC_ENABLED
  11202. [pool drain];
  11203. #endif
  11204. return result;
  11205. }
  11206. #endif // __OBJC__
  11207. // end catch_default_main.hpp
  11208. #endif
  11209. #if !defined(CATCH_CONFIG_IMPL_ONLY)
  11210. #ifdef CLARA_CONFIG_MAIN_NOT_DEFINED
  11211. # undef CLARA_CONFIG_MAIN
  11212. #endif
  11213. #if !defined(CATCH_CONFIG_DISABLE)
  11214. //////
  11215. // If this config identifier is defined then all CATCH macros are prefixed with CATCH_
  11216. #ifdef CATCH_CONFIG_PREFIX_ALL
  11217. #define CATCH_REQUIRE( ... ) INTERNAL_CATCH_TEST( "CATCH_REQUIRE", Catch::ResultDisposition::Normal, __VA_ARGS__ )
  11218. #define CATCH_REQUIRE_FALSE( ... ) INTERNAL_CATCH_TEST( "CATCH_REQUIRE_FALSE", Catch::ResultDisposition::Normal | Catch::ResultDisposition::FalseTest, __VA_ARGS__ )
  11219. #define CATCH_REQUIRE_THROWS( ... ) INTERNAL_CATCH_THROWS( "CATCH_REQUIRE_THROWS", Catch::ResultDisposition::Normal, "", __VA_ARGS__ )
  11220. #define CATCH_REQUIRE_THROWS_AS( expr, exceptionType ) INTERNAL_CATCH_THROWS_AS( "CATCH_REQUIRE_THROWS_AS", exceptionType, Catch::ResultDisposition::Normal, expr )
  11221. #define CATCH_REQUIRE_THROWS_WITH( expr, matcher ) INTERNAL_CATCH_THROWS_STR_MATCHES( "CATCH_REQUIRE_THROWS_WITH", Catch::ResultDisposition::Normal, matcher, expr )
  11222. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  11223. #define CATCH_REQUIRE_THROWS_MATCHES( expr, exceptionType, matcher ) INTERNAL_CATCH_THROWS_MATCHES( "CATCH_REQUIRE_THROWS_MATCHES", exceptionType, Catch::ResultDisposition::Normal, matcher, expr )
  11224. #endif// CATCH_CONFIG_DISABLE_MATCHERS
  11225. #define CATCH_REQUIRE_NOTHROW( ... ) INTERNAL_CATCH_NO_THROW( "CATCH_REQUIRE_NOTHROW", Catch::ResultDisposition::Normal, __VA_ARGS__ )
  11226. #define CATCH_CHECK( ... ) INTERNAL_CATCH_TEST( "CATCH_CHECK", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  11227. #define CATCH_CHECK_FALSE( ... ) INTERNAL_CATCH_TEST( "CATCH_CHECK_FALSE", Catch::ResultDisposition::ContinueOnFailure | Catch::ResultDisposition::FalseTest, __VA_ARGS__ )
  11228. #define CATCH_CHECKED_IF( ... ) INTERNAL_CATCH_IF( "CATCH_CHECKED_IF", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  11229. #define CATCH_CHECKED_ELSE( ... ) INTERNAL_CATCH_ELSE( "CATCH_CHECKED_ELSE", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  11230. #define CATCH_CHECK_NOFAIL( ... ) INTERNAL_CATCH_TEST( "CATCH_CHECK_NOFAIL", Catch::ResultDisposition::ContinueOnFailure | Catch::ResultDisposition::SuppressFail, __VA_ARGS__ )
  11231. #define CATCH_CHECK_THROWS( ... ) INTERNAL_CATCH_THROWS( "CATCH_CHECK_THROWS", Catch::ResultDisposition::ContinueOnFailure, "", __VA_ARGS__ )
  11232. #define CATCH_CHECK_THROWS_AS( expr, exceptionType ) INTERNAL_CATCH_THROWS_AS( "CATCH_CHECK_THROWS_AS", exceptionType, Catch::ResultDisposition::ContinueOnFailure, expr )
  11233. #define CATCH_CHECK_THROWS_WITH( expr, matcher ) INTERNAL_CATCH_THROWS_STR_MATCHES( "CATCH_CHECK_THROWS_WITH", Catch::ResultDisposition::ContinueOnFailure, matcher, expr )
  11234. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  11235. #define CATCH_CHECK_THROWS_MATCHES( expr, exceptionType, matcher ) INTERNAL_CATCH_THROWS_MATCHES( "CATCH_CHECK_THROWS_MATCHES", exceptionType, Catch::ResultDisposition::ContinueOnFailure, matcher, expr )
  11236. #endif // CATCH_CONFIG_DISABLE_MATCHERS
  11237. #define CATCH_CHECK_NOTHROW( ... ) INTERNAL_CATCH_NO_THROW( "CATCH_CHECK_NOTHROW", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  11238. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  11239. #define CATCH_CHECK_THAT( arg, matcher ) INTERNAL_CHECK_THAT( "CATCH_CHECK_THAT", matcher, Catch::ResultDisposition::ContinueOnFailure, arg )
  11240. #define CATCH_REQUIRE_THAT( arg, matcher ) INTERNAL_CHECK_THAT( "CATCH_REQUIRE_THAT", matcher, Catch::ResultDisposition::Normal, arg )
  11241. #endif // CATCH_CONFIG_DISABLE_MATCHERS
  11242. #define CATCH_INFO( msg ) INTERNAL_CATCH_INFO( "CATCH_INFO", msg )
  11243. #define CATCH_WARN( msg ) INTERNAL_CATCH_MSG( "CATCH_WARN", Catch::ResultWas::Warning, Catch::ResultDisposition::ContinueOnFailure, msg )
  11244. #define CATCH_CAPTURE( ... ) INTERNAL_CATCH_CAPTURE( INTERNAL_CATCH_UNIQUE_NAME(capturer), "CATCH_CAPTURE",__VA_ARGS__ )
  11245. #define CATCH_TEST_CASE( ... ) INTERNAL_CATCH_TESTCASE( __VA_ARGS__ )
  11246. #define CATCH_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEST_CASE_METHOD( className, __VA_ARGS__ )
  11247. #define CATCH_METHOD_AS_TEST_CASE( method, ... ) INTERNAL_CATCH_METHOD_AS_TEST_CASE( method, __VA_ARGS__ )
  11248. #define CATCH_REGISTER_TEST_CASE( Function, ... ) INTERNAL_CATCH_REGISTER_TESTCASE( Function, __VA_ARGS__ )
  11249. #define CATCH_SECTION( ... ) INTERNAL_CATCH_SECTION( __VA_ARGS__ )
  11250. #define CATCH_DYNAMIC_SECTION( ... ) INTERNAL_CATCH_DYNAMIC_SECTION( __VA_ARGS__ )
  11251. #define CATCH_FAIL( ... ) INTERNAL_CATCH_MSG( "CATCH_FAIL", Catch::ResultWas::ExplicitFailure, Catch::ResultDisposition::Normal, __VA_ARGS__ )
  11252. #define CATCH_FAIL_CHECK( ... ) INTERNAL_CATCH_MSG( "CATCH_FAIL_CHECK", Catch::ResultWas::ExplicitFailure, Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  11253. #define CATCH_SUCCEED( ... ) INTERNAL_CATCH_MSG( "CATCH_SUCCEED", Catch::ResultWas::Ok, Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  11254. #define CATCH_ANON_TEST_CASE() INTERNAL_CATCH_TESTCASE()
  11255. // "BDD-style" convenience wrappers
  11256. #define CATCH_SCENARIO( ... ) CATCH_TEST_CASE( "Scenario: " __VA_ARGS__ )
  11257. #define CATCH_SCENARIO_METHOD( className, ... ) INTERNAL_CATCH_TEST_CASE_METHOD( className, "Scenario: " __VA_ARGS__ )
  11258. #define CATCH_GIVEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " Given: " << desc )
  11259. #define CATCH_AND_GIVEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( "And given: " << desc )
  11260. #define CATCH_WHEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " When: " << desc )
  11261. #define CATCH_AND_WHEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " And when: " << desc )
  11262. #define CATCH_THEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " Then: " << desc )
  11263. #define CATCH_AND_THEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " And: " << desc )
  11264. // If CATCH_CONFIG_PREFIX_ALL is not defined then the CATCH_ prefix is not required
  11265. #else
  11266. #define REQUIRE( ... ) INTERNAL_CATCH_TEST( "REQUIRE", Catch::ResultDisposition::Normal, __VA_ARGS__ )
  11267. #define REQUIRE_FALSE( ... ) INTERNAL_CATCH_TEST( "REQUIRE_FALSE", Catch::ResultDisposition::Normal | Catch::ResultDisposition::FalseTest, __VA_ARGS__ )
  11268. #define REQUIRE_THROWS( ... ) INTERNAL_CATCH_THROWS( "REQUIRE_THROWS", Catch::ResultDisposition::Normal, __VA_ARGS__ )
  11269. #define REQUIRE_THROWS_AS( expr, exceptionType ) INTERNAL_CATCH_THROWS_AS( "REQUIRE_THROWS_AS", exceptionType, Catch::ResultDisposition::Normal, expr )
  11270. #define REQUIRE_THROWS_WITH( expr, matcher ) INTERNAL_CATCH_THROWS_STR_MATCHES( "REQUIRE_THROWS_WITH", Catch::ResultDisposition::Normal, matcher, expr )
  11271. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  11272. #define REQUIRE_THROWS_MATCHES( expr, exceptionType, matcher ) INTERNAL_CATCH_THROWS_MATCHES( "REQUIRE_THROWS_MATCHES", exceptionType, Catch::ResultDisposition::Normal, matcher, expr )
  11273. #endif // CATCH_CONFIG_DISABLE_MATCHERS
  11274. #define REQUIRE_NOTHROW( ... ) INTERNAL_CATCH_NO_THROW( "REQUIRE_NOTHROW", Catch::ResultDisposition::Normal, __VA_ARGS__ )
  11275. #define CHECK( ... ) INTERNAL_CATCH_TEST( "CHECK", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  11276. #define CHECK_FALSE( ... ) INTERNAL_CATCH_TEST( "CHECK_FALSE", Catch::ResultDisposition::ContinueOnFailure | Catch::ResultDisposition::FalseTest, __VA_ARGS__ )
  11277. #define CHECKED_IF( ... ) INTERNAL_CATCH_IF( "CHECKED_IF", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  11278. #define CHECKED_ELSE( ... ) INTERNAL_CATCH_ELSE( "CHECKED_ELSE", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  11279. #define CHECK_NOFAIL( ... ) INTERNAL_CATCH_TEST( "CHECK_NOFAIL", Catch::ResultDisposition::ContinueOnFailure | Catch::ResultDisposition::SuppressFail, __VA_ARGS__ )
  11280. #define CHECK_THROWS( ... ) INTERNAL_CATCH_THROWS( "CHECK_THROWS", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  11281. #define CHECK_THROWS_AS( expr, exceptionType ) INTERNAL_CATCH_THROWS_AS( "CHECK_THROWS_AS", exceptionType, Catch::ResultDisposition::ContinueOnFailure, expr )
  11282. #define CHECK_THROWS_WITH( expr, matcher ) INTERNAL_CATCH_THROWS_STR_MATCHES( "CHECK_THROWS_WITH", Catch::ResultDisposition::ContinueOnFailure, matcher, expr )
  11283. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  11284. #define CHECK_THROWS_MATCHES( expr, exceptionType, matcher ) INTERNAL_CATCH_THROWS_MATCHES( "CHECK_THROWS_MATCHES", exceptionType, Catch::ResultDisposition::ContinueOnFailure, matcher, expr )
  11285. #endif // CATCH_CONFIG_DISABLE_MATCHERS
  11286. #define CHECK_NOTHROW( ... ) INTERNAL_CATCH_NO_THROW( "CHECK_NOTHROW", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  11287. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  11288. #define CHECK_THAT( arg, matcher ) INTERNAL_CHECK_THAT( "CHECK_THAT", matcher, Catch::ResultDisposition::ContinueOnFailure, arg )
  11289. #define REQUIRE_THAT( arg, matcher ) INTERNAL_CHECK_THAT( "REQUIRE_THAT", matcher, Catch::ResultDisposition::Normal, arg )
  11290. #endif // CATCH_CONFIG_DISABLE_MATCHERS
  11291. #define INFO( msg ) INTERNAL_CATCH_INFO( "INFO", msg )
  11292. #define WARN( msg ) INTERNAL_CATCH_MSG( "WARN", Catch::ResultWas::Warning, Catch::ResultDisposition::ContinueOnFailure, msg )
  11293. #define CAPTURE( ... ) INTERNAL_CATCH_CAPTURE( INTERNAL_CATCH_UNIQUE_NAME(capturer), "CAPTURE",__VA_ARGS__ )
  11294. #define TEST_CASE( ... ) INTERNAL_CATCH_TESTCASE( __VA_ARGS__ )
  11295. #define TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEST_CASE_METHOD( className, __VA_ARGS__ )
  11296. #define METHOD_AS_TEST_CASE( method, ... ) INTERNAL_CATCH_METHOD_AS_TEST_CASE( method, __VA_ARGS__ )
  11297. #define REGISTER_TEST_CASE( Function, ... ) INTERNAL_CATCH_REGISTER_TESTCASE( Function, __VA_ARGS__ )
  11298. #define SECTION( ... ) INTERNAL_CATCH_SECTION( __VA_ARGS__ )
  11299. #define DYNAMIC_SECTION( ... ) INTERNAL_CATCH_DYNAMIC_SECTION( __VA_ARGS__ )
  11300. #define FAIL( ... ) INTERNAL_CATCH_MSG( "FAIL", Catch::ResultWas::ExplicitFailure, Catch::ResultDisposition::Normal, __VA_ARGS__ )
  11301. #define FAIL_CHECK( ... ) INTERNAL_CATCH_MSG( "FAIL_CHECK", Catch::ResultWas::ExplicitFailure, Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  11302. #define SUCCEED( ... ) INTERNAL_CATCH_MSG( "SUCCEED", Catch::ResultWas::Ok, Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  11303. #define ANON_TEST_CASE() INTERNAL_CATCH_TESTCASE()
  11304. #endif
  11305. #define CATCH_TRANSLATE_EXCEPTION( signature ) INTERNAL_CATCH_TRANSLATE_EXCEPTION( signature )
  11306. // "BDD-style" convenience wrappers
  11307. #define SCENARIO( ... ) TEST_CASE( "Scenario: " __VA_ARGS__ )
  11308. #define SCENARIO_METHOD( className, ... ) INTERNAL_CATCH_TEST_CASE_METHOD( className, "Scenario: " __VA_ARGS__ )
  11309. #define GIVEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " Given: " << desc )
  11310. #define AND_GIVEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( "And given: " << desc )
  11311. #define WHEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " When: " << desc )
  11312. #define AND_WHEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " And when: " << desc )
  11313. #define THEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " Then: " << desc )
  11314. #define AND_THEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " And: " << desc )
  11315. using Catch::Detail::Approx;
  11316. #else // CATCH_CONFIG_DISABLE
  11317. //////
  11318. // If this config identifier is defined then all CATCH macros are prefixed with CATCH_
  11319. #ifdef CATCH_CONFIG_PREFIX_ALL
  11320. #define CATCH_REQUIRE( ... ) (void)(0)
  11321. #define CATCH_REQUIRE_FALSE( ... ) (void)(0)
  11322. #define CATCH_REQUIRE_THROWS( ... ) (void)(0)
  11323. #define CATCH_REQUIRE_THROWS_AS( expr, exceptionType ) (void)(0)
  11324. #define CATCH_REQUIRE_THROWS_WITH( expr, matcher ) (void)(0)
  11325. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  11326. #define CATCH_REQUIRE_THROWS_MATCHES( expr, exceptionType, matcher ) (void)(0)
  11327. #endif// CATCH_CONFIG_DISABLE_MATCHERS
  11328. #define CATCH_REQUIRE_NOTHROW( ... ) (void)(0)
  11329. #define CATCH_CHECK( ... ) (void)(0)
  11330. #define CATCH_CHECK_FALSE( ... ) (void)(0)
  11331. #define CATCH_CHECKED_IF( ... ) if (__VA_ARGS__)
  11332. #define CATCH_CHECKED_ELSE( ... ) if (!(__VA_ARGS__))
  11333. #define CATCH_CHECK_NOFAIL( ... ) (void)(0)
  11334. #define CATCH_CHECK_THROWS( ... ) (void)(0)
  11335. #define CATCH_CHECK_THROWS_AS( expr, exceptionType ) (void)(0)
  11336. #define CATCH_CHECK_THROWS_WITH( expr, matcher ) (void)(0)
  11337. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  11338. #define CATCH_CHECK_THROWS_MATCHES( expr, exceptionType, matcher ) (void)(0)
  11339. #endif // CATCH_CONFIG_DISABLE_MATCHERS
  11340. #define CATCH_CHECK_NOTHROW( ... ) (void)(0)
  11341. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  11342. #define CATCH_CHECK_THAT( arg, matcher ) (void)(0)
  11343. #define CATCH_REQUIRE_THAT( arg, matcher ) (void)(0)
  11344. #endif // CATCH_CONFIG_DISABLE_MATCHERS
  11345. #define CATCH_INFO( msg ) (void)(0)
  11346. #define CATCH_WARN( msg ) (void)(0)
  11347. #define CATCH_CAPTURE( msg ) (void)(0)
  11348. #define CATCH_TEST_CASE( ... ) INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ))
  11349. #define CATCH_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ))
  11350. #define CATCH_METHOD_AS_TEST_CASE( method, ... )
  11351. #define CATCH_REGISTER_TEST_CASE( Function, ... ) (void)(0)
  11352. #define CATCH_SECTION( ... )
  11353. #define CATCH_DYNAMIC_SECTION( ... )
  11354. #define CATCH_FAIL( ... ) (void)(0)
  11355. #define CATCH_FAIL_CHECK( ... ) (void)(0)
  11356. #define CATCH_SUCCEED( ... ) (void)(0)
  11357. #define CATCH_ANON_TEST_CASE() INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ))
  11358. // "BDD-style" convenience wrappers
  11359. #define CATCH_SCENARIO( ... ) INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ))
  11360. #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 )
  11361. #define CATCH_GIVEN( desc )
  11362. #define CATCH_AND_GIVEN( desc )
  11363. #define CATCH_WHEN( desc )
  11364. #define CATCH_AND_WHEN( desc )
  11365. #define CATCH_THEN( desc )
  11366. #define CATCH_AND_THEN( desc )
  11367. // If CATCH_CONFIG_PREFIX_ALL is not defined then the CATCH_ prefix is not required
  11368. #else
  11369. #define REQUIRE( ... ) (void)(0)
  11370. #define REQUIRE_FALSE( ... ) (void)(0)
  11371. #define REQUIRE_THROWS( ... ) (void)(0)
  11372. #define REQUIRE_THROWS_AS( expr, exceptionType ) (void)(0)
  11373. #define REQUIRE_THROWS_WITH( expr, matcher ) (void)(0)
  11374. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  11375. #define REQUIRE_THROWS_MATCHES( expr, exceptionType, matcher ) (void)(0)
  11376. #endif // CATCH_CONFIG_DISABLE_MATCHERS
  11377. #define REQUIRE_NOTHROW( ... ) (void)(0)
  11378. #define CHECK( ... ) (void)(0)
  11379. #define CHECK_FALSE( ... ) (void)(0)
  11380. #define CHECKED_IF( ... ) if (__VA_ARGS__)
  11381. #define CHECKED_ELSE( ... ) if (!(__VA_ARGS__))
  11382. #define CHECK_NOFAIL( ... ) (void)(0)
  11383. #define CHECK_THROWS( ... ) (void)(0)
  11384. #define CHECK_THROWS_AS( expr, exceptionType ) (void)(0)
  11385. #define CHECK_THROWS_WITH( expr, matcher ) (void)(0)
  11386. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  11387. #define CHECK_THROWS_MATCHES( expr, exceptionType, matcher ) (void)(0)
  11388. #endif // CATCH_CONFIG_DISABLE_MATCHERS
  11389. #define CHECK_NOTHROW( ... ) (void)(0)
  11390. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  11391. #define CHECK_THAT( arg, matcher ) (void)(0)
  11392. #define REQUIRE_THAT( arg, matcher ) (void)(0)
  11393. #endif // CATCH_CONFIG_DISABLE_MATCHERS
  11394. #define INFO( msg ) (void)(0)
  11395. #define WARN( msg ) (void)(0)
  11396. #define CAPTURE( msg ) (void)(0)
  11397. #define TEST_CASE( ... ) INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ))
  11398. #define TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ))
  11399. #define METHOD_AS_TEST_CASE( method, ... )
  11400. #define REGISTER_TEST_CASE( Function, ... ) (void)(0)
  11401. #define SECTION( ... )
  11402. #define DYNAMIC_SECTION( ... )
  11403. #define FAIL( ... ) (void)(0)
  11404. #define FAIL_CHECK( ... ) (void)(0)
  11405. #define SUCCEED( ... ) (void)(0)
  11406. #define ANON_TEST_CASE() INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ))
  11407. #endif
  11408. #define CATCH_TRANSLATE_EXCEPTION( signature ) INTERNAL_CATCH_TRANSLATE_EXCEPTION_NO_REG( INTERNAL_CATCH_UNIQUE_NAME( catch_internal_ExceptionTranslator ), signature )
  11409. // "BDD-style" convenience wrappers
  11410. #define SCENARIO( ... ) INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ) )
  11411. #define SCENARIO_METHOD( className, ... ) INTERNAL_CATCH_TESTCASE_METHOD_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ), className )
  11412. #define GIVEN( desc )
  11413. #define AND_GIVEN( desc )
  11414. #define WHEN( desc )
  11415. #define AND_WHEN( desc )
  11416. #define THEN( desc )
  11417. #define AND_THEN( desc )
  11418. using Catch::Detail::Approx;
  11419. #endif
  11420. #endif // ! CATCH_CONFIG_IMPL_ONLY
  11421. // start catch_reenable_warnings.h
  11422. #ifdef __clang__
  11423. # ifdef __ICC // icpc defines the __clang__ macro
  11424. # pragma warning(pop)
  11425. # else
  11426. # pragma clang diagnostic pop
  11427. # endif
  11428. #elif defined __GNUC__
  11429. # pragma GCC diagnostic pop
  11430. #endif
  11431. // end catch_reenable_warnings.h
  11432. // end catch.hpp
  11433. #endif // TWOBLUECUBES_SINGLE_INCLUDE_CATCH_HPP_INCLUDED