選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

13051 行
433KB

  1. /*
  2. * Catch v2.2.2
  3. * Generated: 2018-04-06 12:05:03.186665
  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 2
  16. #define CATCH_VERSION_PATCH 2
  17. #ifdef __clang__
  18. # pragma clang system_header
  19. #elif defined __GNUC__
  20. # pragma GCC system_header
  21. #endif
  22. // start catch_suppress_warnings.h
  23. #ifdef __clang__
  24. # ifdef __ICC // icpc defines the __clang__ macro
  25. # pragma warning(push)
  26. # pragma warning(disable: 161 1682)
  27. # else // __ICC
  28. # pragma clang diagnostic ignored "-Wunused-variable"
  29. # pragma clang diagnostic push
  30. # pragma clang diagnostic ignored "-Wpadded"
  31. # pragma clang diagnostic ignored "-Wswitch-enum"
  32. # pragma clang diagnostic ignored "-Wcovered-switch-default"
  33. # endif
  34. #elif defined __GNUC__
  35. # pragma GCC diagnostic ignored "-Wparentheses"
  36. # pragma GCC diagnostic push
  37. # pragma GCC diagnostic ignored "-Wunused-variable"
  38. # pragma GCC diagnostic ignored "-Wpadded"
  39. #endif
  40. // end catch_suppress_warnings.h
  41. #if defined(CATCH_CONFIG_MAIN) || defined(CATCH_CONFIG_RUNNER)
  42. # define CATCH_IMPL
  43. # define CATCH_CONFIG_ALL_PARTS
  44. #endif
  45. // In the impl file, we want to have access to all parts of the headers
  46. // Can also be used to sanely support PCHs
  47. #if defined(CATCH_CONFIG_ALL_PARTS)
  48. # define CATCH_CONFIG_EXTERNAL_INTERFACES
  49. # if defined(CATCH_CONFIG_DISABLE_MATCHERS)
  50. # undef CATCH_CONFIG_DISABLE_MATCHERS
  51. # endif
  52. # define CATCH_CONFIG_ENABLE_CHRONO_STRINGMAKER
  53. #endif
  54. #if !defined(CATCH_CONFIG_IMPL_ONLY)
  55. // start catch_platform.h
  56. #ifdef __APPLE__
  57. # include <TargetConditionals.h>
  58. # if TARGET_OS_OSX == 1
  59. # define CATCH_PLATFORM_MAC
  60. # elif TARGET_OS_IPHONE == 1
  61. # define CATCH_PLATFORM_IPHONE
  62. # endif
  63. #elif defined(linux) || defined(__linux) || defined(__linux__)
  64. # define CATCH_PLATFORM_LINUX
  65. #elif defined(WIN32) || defined(__WIN32__) || defined(_WIN32) || defined(_MSC_VER)
  66. # define CATCH_PLATFORM_WINDOWS
  67. #endif
  68. // end catch_platform.h
  69. #ifdef CATCH_IMPL
  70. # ifndef CLARA_CONFIG_MAIN
  71. # define CLARA_CONFIG_MAIN_NOT_DEFINED
  72. # define CLARA_CONFIG_MAIN
  73. # endif
  74. #endif
  75. // start catch_user_interfaces.h
  76. namespace Catch {
  77. unsigned int rngSeed();
  78. }
  79. // end catch_user_interfaces.h
  80. // start catch_tag_alias_autoregistrar.h
  81. // start catch_common.h
  82. // start catch_compiler_capabilities.h
  83. // Detect a number of compiler features - by compiler
  84. // The following features are defined:
  85. //
  86. // CATCH_CONFIG_COUNTER : is the __COUNTER__ macro supported?
  87. // CATCH_CONFIG_WINDOWS_SEH : is Windows SEH supported?
  88. // CATCH_CONFIG_POSIX_SIGNALS : are POSIX signals supported?
  89. // ****************
  90. // Note to maintainers: if new toggles are added please document them
  91. // in configuration.md, too
  92. // ****************
  93. // In general each macro has a _NO_<feature name> form
  94. // (e.g. CATCH_CONFIG_NO_POSIX_SIGNALS) which disables the feature.
  95. // Many features, at point of detection, define an _INTERNAL_ macro, so they
  96. // can be combined, en-mass, with the _NO_ forms later.
  97. #ifdef __cplusplus
  98. # if __cplusplus >= 201402L
  99. # define CATCH_CPP14_OR_GREATER
  100. # endif
  101. # if __cplusplus >= 201703L
  102. # define CATCH_CPP17_OR_GREATER
  103. # endif
  104. #endif
  105. #if defined(CATCH_CPP17_OR_GREATER)
  106. # define CATCH_INTERNAL_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS
  107. #endif
  108. #ifdef __clang__
  109. # define CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
  110. _Pragma( "clang diagnostic push" ) \
  111. _Pragma( "clang diagnostic ignored \"-Wexit-time-destructors\"" ) \
  112. _Pragma( "clang diagnostic ignored \"-Wglobal-constructors\"")
  113. # define CATCH_INTERNAL_UNSUPPRESS_GLOBALS_WARNINGS \
  114. _Pragma( "clang diagnostic pop" )
  115. # define CATCH_INTERNAL_SUPPRESS_PARENTHESES_WARNINGS \
  116. _Pragma( "clang diagnostic push" ) \
  117. _Pragma( "clang diagnostic ignored \"-Wparentheses\"" )
  118. # define CATCH_INTERNAL_UNSUPPRESS_PARENTHESES_WARNINGS \
  119. _Pragma( "clang diagnostic pop" )
  120. #endif // __clang__
  121. ////////////////////////////////////////////////////////////////////////////////
  122. // Assume that non-Windows platforms support posix signals by default
  123. #if !defined(CATCH_PLATFORM_WINDOWS)
  124. #define CATCH_INTERNAL_CONFIG_POSIX_SIGNALS
  125. #endif
  126. ////////////////////////////////////////////////////////////////////////////////
  127. // We know some environments not to support full POSIX signals
  128. #if defined(__CYGWIN__) || defined(__QNX__) || defined(__EMSCRIPTEN__) || defined(__DJGPP__)
  129. #define CATCH_INTERNAL_CONFIG_NO_POSIX_SIGNALS
  130. #endif
  131. #ifdef __OS400__
  132. # define CATCH_INTERNAL_CONFIG_NO_POSIX_SIGNALS
  133. # define CATCH_CONFIG_COLOUR_NONE
  134. #endif
  135. ////////////////////////////////////////////////////////////////////////////////
  136. // Cygwin
  137. #ifdef __CYGWIN__
  138. // Required for some versions of Cygwin to declare gettimeofday
  139. // see: http://stackoverflow.com/questions/36901803/gettimeofday-not-declared-in-this-scope-cygwin
  140. # define _BSD_SOURCE
  141. #endif // __CYGWIN__
  142. ////////////////////////////////////////////////////////////////////////////////
  143. // Visual C++
  144. #ifdef _MSC_VER
  145. # if _MSC_VER >= 1900 // Visual Studio 2015 or newer
  146. # define CATCH_INTERNAL_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS
  147. # endif
  148. // Universal Windows platform does not support SEH
  149. // Or console colours (or console at all...)
  150. # if defined(WINAPI_FAMILY) && (WINAPI_FAMILY == WINAPI_FAMILY_APP)
  151. # define CATCH_CONFIG_COLOUR_NONE
  152. # else
  153. # define CATCH_INTERNAL_CONFIG_WINDOWS_SEH
  154. # endif
  155. #endif // _MSC_VER
  156. ////////////////////////////////////////////////////////////////////////////////
  157. // DJGPP
  158. #ifdef __DJGPP__
  159. # define CATCH_INTERNAL_CONFIG_NO_WCHAR
  160. #endif // __DJGPP__
  161. ////////////////////////////////////////////////////////////////////////////////
  162. // Use of __COUNTER__ is suppressed during code analysis in
  163. // CLion/AppCode 2017.2.x and former, because __COUNTER__ is not properly
  164. // handled by it.
  165. // Otherwise all supported compilers support COUNTER macro,
  166. // but user still might want to turn it off
  167. #if ( !defined(__JETBRAINS_IDE__) || __JETBRAINS_IDE__ >= 20170300L )
  168. #define CATCH_INTERNAL_CONFIG_COUNTER
  169. #endif
  170. #if defined(CATCH_INTERNAL_CONFIG_COUNTER) && !defined(CATCH_CONFIG_NO_COUNTER) && !defined(CATCH_CONFIG_COUNTER)
  171. # define CATCH_CONFIG_COUNTER
  172. #endif
  173. #if defined(CATCH_INTERNAL_CONFIG_WINDOWS_SEH) && !defined(CATCH_CONFIG_NO_WINDOWS_SEH) && !defined(CATCH_CONFIG_WINDOWS_SEH)
  174. # define CATCH_CONFIG_WINDOWS_SEH
  175. #endif
  176. // This is set by default, because we assume that unix compilers are posix-signal-compatible by default.
  177. #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)
  178. # define CATCH_CONFIG_POSIX_SIGNALS
  179. #endif
  180. // This is set by default, because we assume that compilers with no wchar_t support are just rare exceptions.
  181. #if !defined(CATCH_INTERNAL_CONFIG_NO_WCHAR) && !defined(CATCH_CONFIG_NO_WCHAR) && !defined(CATCH_CONFIG_WCHAR)
  182. # define CATCH_CONFIG_WCHAR
  183. #endif
  184. #if defined(CATCH_INTERNAL_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS) && !defined(CATCH_CONFIG_NO_CPP17_UNCAUGHT_EXCEPTIONS) && !defined(CATCH_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS)
  185. # define CATCH_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS
  186. #endif
  187. #if !defined(CATCH_INTERNAL_SUPPRESS_PARENTHESES_WARNINGS)
  188. # define CATCH_INTERNAL_SUPPRESS_PARENTHESES_WARNINGS
  189. # define CATCH_INTERNAL_UNSUPPRESS_PARENTHESES_WARNINGS
  190. #endif
  191. #if !defined(CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS)
  192. # define CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS
  193. # define CATCH_INTERNAL_UNSUPPRESS_GLOBALS_WARNINGS
  194. #endif
  195. // end catch_compiler_capabilities.h
  196. #define INTERNAL_CATCH_UNIQUE_NAME_LINE2( name, line ) name##line
  197. #define INTERNAL_CATCH_UNIQUE_NAME_LINE( name, line ) INTERNAL_CATCH_UNIQUE_NAME_LINE2( name, line )
  198. #ifdef CATCH_CONFIG_COUNTER
  199. # define INTERNAL_CATCH_UNIQUE_NAME( name ) INTERNAL_CATCH_UNIQUE_NAME_LINE( name, __COUNTER__ )
  200. #else
  201. # define INTERNAL_CATCH_UNIQUE_NAME( name ) INTERNAL_CATCH_UNIQUE_NAME_LINE( name, __LINE__ )
  202. #endif
  203. #include <iosfwd>
  204. #include <string>
  205. #include <cstdint>
  206. namespace Catch {
  207. struct CaseSensitive { enum Choice {
  208. Yes,
  209. No
  210. }; };
  211. class NonCopyable {
  212. NonCopyable( NonCopyable const& ) = delete;
  213. NonCopyable( NonCopyable && ) = delete;
  214. NonCopyable& operator = ( NonCopyable const& ) = delete;
  215. NonCopyable& operator = ( NonCopyable && ) = delete;
  216. protected:
  217. NonCopyable();
  218. virtual ~NonCopyable();
  219. };
  220. struct SourceLineInfo {
  221. SourceLineInfo() = delete;
  222. SourceLineInfo( char const* _file, std::size_t _line ) noexcept
  223. : file( _file ),
  224. line( _line )
  225. {}
  226. SourceLineInfo( SourceLineInfo const& other ) = default;
  227. SourceLineInfo( SourceLineInfo && ) = default;
  228. SourceLineInfo& operator = ( SourceLineInfo const& ) = default;
  229. SourceLineInfo& operator = ( SourceLineInfo && ) = default;
  230. bool empty() const noexcept;
  231. bool operator == ( SourceLineInfo const& other ) const noexcept;
  232. bool operator < ( SourceLineInfo const& other ) const noexcept;
  233. char const* file;
  234. std::size_t line;
  235. };
  236. std::ostream& operator << ( std::ostream& os, SourceLineInfo const& info );
  237. // Use this in variadic streaming macros to allow
  238. // >> +StreamEndStop
  239. // as well as
  240. // >> stuff +StreamEndStop
  241. struct StreamEndStop {
  242. std::string operator+() const;
  243. };
  244. template<typename T>
  245. T const& operator + ( T const& value, StreamEndStop ) {
  246. return value;
  247. }
  248. }
  249. #define CATCH_INTERNAL_LINEINFO \
  250. ::Catch::SourceLineInfo( __FILE__, static_cast<std::size_t>( __LINE__ ) )
  251. // end catch_common.h
  252. namespace Catch {
  253. struct RegistrarForTagAliases {
  254. RegistrarForTagAliases( char const* alias, char const* tag, SourceLineInfo const& lineInfo );
  255. };
  256. } // end namespace Catch
  257. #define CATCH_REGISTER_TAG_ALIAS( alias, spec ) \
  258. CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
  259. namespace{ Catch::RegistrarForTagAliases INTERNAL_CATCH_UNIQUE_NAME( AutoRegisterTagAlias )( alias, spec, CATCH_INTERNAL_LINEINFO ); } \
  260. CATCH_INTERNAL_UNSUPPRESS_GLOBALS_WARNINGS
  261. // end catch_tag_alias_autoregistrar.h
  262. // start catch_test_registry.h
  263. // start catch_interfaces_testcase.h
  264. #include <vector>
  265. #include <memory>
  266. namespace Catch {
  267. class TestSpec;
  268. struct ITestInvoker {
  269. virtual void invoke () const = 0;
  270. virtual ~ITestInvoker();
  271. };
  272. using ITestCasePtr = std::shared_ptr<ITestInvoker>;
  273. class TestCase;
  274. struct IConfig;
  275. struct ITestCaseRegistry {
  276. virtual ~ITestCaseRegistry();
  277. virtual std::vector<TestCase> const& getAllTests() const = 0;
  278. virtual std::vector<TestCase> const& getAllTestsSorted( IConfig const& config ) const = 0;
  279. };
  280. bool matchTest( TestCase const& testCase, TestSpec const& testSpec, IConfig const& config );
  281. std::vector<TestCase> filterTests( std::vector<TestCase> const& testCases, TestSpec const& testSpec, IConfig const& config );
  282. std::vector<TestCase> const& getAllTestCasesSorted( IConfig const& config );
  283. }
  284. // end catch_interfaces_testcase.h
  285. // start catch_stringref.h
  286. #include <cstddef>
  287. #include <string>
  288. #include <iosfwd>
  289. namespace Catch {
  290. class StringData;
  291. /// A non-owning string class (similar to the forthcoming std::string_view)
  292. /// Note that, because a StringRef may be a substring of another string,
  293. /// it may not be null terminated. c_str() must return a null terminated
  294. /// string, however, and so the StringRef will internally take ownership
  295. /// (taking a copy), if necessary. In theory this ownership is not externally
  296. /// visible - but it does mean (substring) StringRefs should not be shared between
  297. /// threads.
  298. class StringRef {
  299. public:
  300. using size_type = std::size_t;
  301. private:
  302. friend struct StringRefTestAccess;
  303. char const* m_start;
  304. size_type m_size;
  305. char* m_data = nullptr;
  306. void takeOwnership();
  307. static constexpr char const* const s_empty = "";
  308. public: // construction/ assignment
  309. StringRef() noexcept
  310. : StringRef( s_empty, 0 )
  311. {}
  312. StringRef( StringRef const& other ) noexcept
  313. : m_start( other.m_start ),
  314. m_size( other.m_size )
  315. {}
  316. StringRef( StringRef&& other ) noexcept
  317. : m_start( other.m_start ),
  318. m_size( other.m_size ),
  319. m_data( other.m_data )
  320. {
  321. other.m_data = nullptr;
  322. }
  323. StringRef( char const* rawChars ) noexcept;
  324. StringRef( char const* rawChars, size_type size ) noexcept
  325. : m_start( rawChars ),
  326. m_size( size )
  327. {}
  328. StringRef( std::string const& stdString ) noexcept
  329. : m_start( stdString.c_str() ),
  330. m_size( stdString.size() )
  331. {}
  332. ~StringRef() noexcept {
  333. delete[] m_data;
  334. }
  335. auto operator = ( StringRef const &other ) noexcept -> StringRef& {
  336. delete[] m_data;
  337. m_data = nullptr;
  338. m_start = other.m_start;
  339. m_size = other.m_size;
  340. return *this;
  341. }
  342. operator std::string() const;
  343. void swap( StringRef& other ) noexcept;
  344. public: // operators
  345. auto operator == ( StringRef const& other ) const noexcept -> bool;
  346. auto operator != ( StringRef const& other ) const noexcept -> bool;
  347. auto operator[] ( size_type index ) const noexcept -> char;
  348. public: // named queries
  349. auto empty() const noexcept -> bool {
  350. return m_size == 0;
  351. }
  352. auto size() const noexcept -> size_type {
  353. return m_size;
  354. }
  355. auto numberOfCharacters() const noexcept -> size_type;
  356. auto c_str() const -> char const*;
  357. public: // substrings and searches
  358. auto substr( size_type start, size_type size ) const noexcept -> StringRef;
  359. // Returns the current start pointer.
  360. // Note that the pointer can change when if the StringRef is a substring
  361. auto currentData() const noexcept -> char const*;
  362. private: // ownership queries - may not be consistent between calls
  363. auto isOwned() const noexcept -> bool;
  364. auto isSubstring() const noexcept -> bool;
  365. };
  366. auto operator + ( StringRef const& lhs, StringRef const& rhs ) -> std::string;
  367. auto operator + ( StringRef const& lhs, char const* rhs ) -> std::string;
  368. auto operator + ( char const* lhs, StringRef const& rhs ) -> std::string;
  369. auto operator += ( std::string& lhs, StringRef const& sr ) -> std::string&;
  370. auto operator << ( std::ostream& os, StringRef const& sr ) -> std::ostream&;
  371. inline auto operator "" _sr( char const* rawChars, std::size_t size ) noexcept -> StringRef {
  372. return StringRef( rawChars, size );
  373. }
  374. } // namespace Catch
  375. // end catch_stringref.h
  376. namespace Catch {
  377. template<typename C>
  378. class TestInvokerAsMethod : public ITestInvoker {
  379. void (C::*m_testAsMethod)();
  380. public:
  381. TestInvokerAsMethod( void (C::*testAsMethod)() ) noexcept : m_testAsMethod( testAsMethod ) {}
  382. void invoke() const override {
  383. C obj;
  384. (obj.*m_testAsMethod)();
  385. }
  386. };
  387. auto makeTestInvoker( void(*testAsFunction)() ) noexcept -> ITestInvoker*;
  388. template<typename C>
  389. auto makeTestInvoker( void (C::*testAsMethod)() ) noexcept -> ITestInvoker* {
  390. return new(std::nothrow) TestInvokerAsMethod<C>( testAsMethod );
  391. }
  392. struct NameAndTags {
  393. NameAndTags( StringRef const& name_ = StringRef(), StringRef const& tags_ = StringRef() ) noexcept;
  394. StringRef name;
  395. StringRef tags;
  396. };
  397. struct AutoReg : NonCopyable {
  398. AutoReg( ITestInvoker* invoker, SourceLineInfo const& lineInfo, StringRef const& classOrMethod, NameAndTags const& nameAndTags ) noexcept;
  399. ~AutoReg();
  400. };
  401. } // end namespace Catch
  402. #if defined(CATCH_CONFIG_DISABLE)
  403. #define INTERNAL_CATCH_TESTCASE_NO_REGISTRATION( TestName, ... ) \
  404. static void TestName()
  405. #define INTERNAL_CATCH_TESTCASE_METHOD_NO_REGISTRATION( TestName, ClassName, ... ) \
  406. namespace{ \
  407. struct TestName : ClassName { \
  408. void test(); \
  409. }; \
  410. } \
  411. void TestName::test()
  412. #endif
  413. ///////////////////////////////////////////////////////////////////////////////
  414. #define INTERNAL_CATCH_TESTCASE2( TestName, ... ) \
  415. static void TestName(); \
  416. CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
  417. namespace{ Catch::AutoReg INTERNAL_CATCH_UNIQUE_NAME( autoRegistrar )( Catch::makeTestInvoker( &TestName ), CATCH_INTERNAL_LINEINFO, "", Catch::NameAndTags{ __VA_ARGS__ } ); } /* NOLINT */ \
  418. CATCH_INTERNAL_UNSUPPRESS_GLOBALS_WARNINGS \
  419. static void TestName()
  420. #define INTERNAL_CATCH_TESTCASE( ... ) \
  421. INTERNAL_CATCH_TESTCASE2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ), __VA_ARGS__ )
  422. ///////////////////////////////////////////////////////////////////////////////
  423. #define INTERNAL_CATCH_METHOD_AS_TEST_CASE( QualifiedMethod, ... ) \
  424. CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
  425. namespace{ Catch::AutoReg INTERNAL_CATCH_UNIQUE_NAME( autoRegistrar )( Catch::makeTestInvoker( &QualifiedMethod ), CATCH_INTERNAL_LINEINFO, "&" #QualifiedMethod, Catch::NameAndTags{ __VA_ARGS__ } ); } /* NOLINT */ \
  426. CATCH_INTERNAL_UNSUPPRESS_GLOBALS_WARNINGS
  427. ///////////////////////////////////////////////////////////////////////////////
  428. #define INTERNAL_CATCH_TEST_CASE_METHOD2( TestName, ClassName, ... )\
  429. CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
  430. namespace{ \
  431. struct TestName : ClassName{ \
  432. void test(); \
  433. }; \
  434. Catch::AutoReg INTERNAL_CATCH_UNIQUE_NAME( autoRegistrar ) ( Catch::makeTestInvoker( &TestName::test ), CATCH_INTERNAL_LINEINFO, #ClassName, Catch::NameAndTags{ __VA_ARGS__ } ); /* NOLINT */ \
  435. } \
  436. CATCH_INTERNAL_UNSUPPRESS_GLOBALS_WARNINGS \
  437. void TestName::test()
  438. #define INTERNAL_CATCH_TEST_CASE_METHOD( ClassName, ... ) \
  439. INTERNAL_CATCH_TEST_CASE_METHOD2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ), ClassName, __VA_ARGS__ )
  440. ///////////////////////////////////////////////////////////////////////////////
  441. #define INTERNAL_CATCH_REGISTER_TESTCASE( Function, ... ) \
  442. CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
  443. Catch::AutoReg INTERNAL_CATCH_UNIQUE_NAME( autoRegistrar )( Catch::makeTestInvoker( Function ), CATCH_INTERNAL_LINEINFO, "", Catch::NameAndTags{ __VA_ARGS__ } ); /* NOLINT */ \
  444. CATCH_INTERNAL_UNSUPPRESS_GLOBALS_WARNINGS
  445. // end catch_test_registry.h
  446. // start catch_capture.hpp
  447. // start catch_assertionhandler.h
  448. // start catch_assertioninfo.h
  449. // start catch_result_type.h
  450. namespace Catch {
  451. // ResultWas::OfType enum
  452. struct ResultWas { enum OfType {
  453. Unknown = -1,
  454. Ok = 0,
  455. Info = 1,
  456. Warning = 2,
  457. FailureBit = 0x10,
  458. ExpressionFailed = FailureBit | 1,
  459. ExplicitFailure = FailureBit | 2,
  460. Exception = 0x100 | FailureBit,
  461. ThrewException = Exception | 1,
  462. DidntThrowException = Exception | 2,
  463. FatalErrorCondition = 0x200 | FailureBit
  464. }; };
  465. bool isOk( ResultWas::OfType resultType );
  466. bool isJustInfo( int flags );
  467. // ResultDisposition::Flags enum
  468. struct ResultDisposition { enum Flags {
  469. Normal = 0x01,
  470. ContinueOnFailure = 0x02, // Failures fail test, but execution continues
  471. FalseTest = 0x04, // Prefix expression with !
  472. SuppressFail = 0x08 // Failures are reported but do not fail the test
  473. }; };
  474. ResultDisposition::Flags operator | ( ResultDisposition::Flags lhs, ResultDisposition::Flags rhs );
  475. bool shouldContinueOnFailure( int flags );
  476. inline bool isFalseTest( int flags ) { return ( flags & ResultDisposition::FalseTest ) != 0; }
  477. bool shouldSuppressFailure( int flags );
  478. } // end namespace Catch
  479. // end catch_result_type.h
  480. namespace Catch {
  481. struct AssertionInfo
  482. {
  483. StringRef macroName;
  484. SourceLineInfo lineInfo;
  485. StringRef capturedExpression;
  486. ResultDisposition::Flags resultDisposition;
  487. // We want to delete this constructor but a compiler bug in 4.8 means
  488. // the struct is then treated as non-aggregate
  489. //AssertionInfo() = delete;
  490. };
  491. } // end namespace Catch
  492. // end catch_assertioninfo.h
  493. // start catch_decomposer.h
  494. // start catch_tostring.h
  495. #include <vector>
  496. #include <cstddef>
  497. #include <type_traits>
  498. #include <string>
  499. // start catch_stream.h
  500. #include <iosfwd>
  501. #include <cstddef>
  502. #include <ostream>
  503. namespace Catch {
  504. std::ostream& cout();
  505. std::ostream& cerr();
  506. std::ostream& clog();
  507. class StringRef;
  508. struct IStream {
  509. virtual ~IStream();
  510. virtual std::ostream& stream() const = 0;
  511. };
  512. auto makeStream( StringRef const &filename ) -> IStream const*;
  513. class ReusableStringStream {
  514. std::size_t m_index;
  515. std::ostream* m_oss;
  516. public:
  517. ReusableStringStream();
  518. ~ReusableStringStream();
  519. auto str() const -> std::string;
  520. template<typename T>
  521. auto operator << ( T const& value ) -> ReusableStringStream& {
  522. *m_oss << value;
  523. return *this;
  524. }
  525. auto get() -> std::ostream& { return *m_oss; }
  526. static void cleanup();
  527. };
  528. }
  529. // end catch_stream.h
  530. #ifdef __OBJC__
  531. // start catch_objc_arc.hpp
  532. #import <Foundation/Foundation.h>
  533. #ifdef __has_feature
  534. #define CATCH_ARC_ENABLED __has_feature(objc_arc)
  535. #else
  536. #define CATCH_ARC_ENABLED 0
  537. #endif
  538. void arcSafeRelease( NSObject* obj );
  539. id performOptionalSelector( id obj, SEL sel );
  540. #if !CATCH_ARC_ENABLED
  541. inline void arcSafeRelease( NSObject* obj ) {
  542. [obj release];
  543. }
  544. inline id performOptionalSelector( id obj, SEL sel ) {
  545. if( [obj respondsToSelector: sel] )
  546. return [obj performSelector: sel];
  547. return nil;
  548. }
  549. #define CATCH_UNSAFE_UNRETAINED
  550. #define CATCH_ARC_STRONG
  551. #else
  552. inline void arcSafeRelease( NSObject* ){}
  553. inline id performOptionalSelector( id obj, SEL sel ) {
  554. #ifdef __clang__
  555. #pragma clang diagnostic push
  556. #pragma clang diagnostic ignored "-Warc-performSelector-leaks"
  557. #endif
  558. if( [obj respondsToSelector: sel] )
  559. return [obj performSelector: sel];
  560. #ifdef __clang__
  561. #pragma clang diagnostic pop
  562. #endif
  563. return nil;
  564. }
  565. #define CATCH_UNSAFE_UNRETAINED __unsafe_unretained
  566. #define CATCH_ARC_STRONG __strong
  567. #endif
  568. // end catch_objc_arc.hpp
  569. #endif
  570. #ifdef _MSC_VER
  571. #pragma warning(push)
  572. #pragma warning(disable:4180) // We attempt to stream a function (address) by const&, which MSVC complains about but is harmless
  573. #endif
  574. // We need a dummy global operator<< so we can bring it into Catch namespace later
  575. struct Catch_global_namespace_dummy {};
  576. std::ostream& operator<<(std::ostream&, Catch_global_namespace_dummy);
  577. namespace Catch {
  578. // Bring in operator<< from global namespace into Catch namespace
  579. using ::operator<<;
  580. namespace Detail {
  581. extern const std::string unprintableString;
  582. std::string rawMemoryToString( const void *object, std::size_t size );
  583. template<typename T>
  584. std::string rawMemoryToString( const T& object ) {
  585. return rawMemoryToString( &object, sizeof(object) );
  586. }
  587. template<typename T>
  588. class IsStreamInsertable {
  589. template<typename SS, typename TT>
  590. static auto test(int)
  591. -> decltype(std::declval<SS&>() << std::declval<TT>(), std::true_type());
  592. template<typename, typename>
  593. static auto test(...)->std::false_type;
  594. public:
  595. static const bool value = decltype(test<std::ostream, const T&>(0))::value;
  596. };
  597. template<typename E>
  598. std::string convertUnknownEnumToString( E e );
  599. template<typename T>
  600. typename std::enable_if<!std::is_enum<T>::value, std::string>::type convertUnstreamable( T const& value ) {
  601. #if !defined(CATCH_CONFIG_FALLBACK_STRINGIFIER)
  602. (void)value;
  603. return Detail::unprintableString;
  604. #else
  605. return CATCH_CONFIG_FALLBACK_STRINGIFIER(value);
  606. #endif
  607. }
  608. template<typename T>
  609. typename std::enable_if<std::is_enum<T>::value, std::string>::type convertUnstreamable( T const& value ) {
  610. return convertUnknownEnumToString( value );
  611. }
  612. #if defined(_MANAGED)
  613. //! Convert a CLR string to a utf8 std::string
  614. template<typename T>
  615. std::string clrReferenceToString( T^ ref ) {
  616. if (ref == nullptr)
  617. return std::string("null");
  618. auto bytes = System::Text::Encoding::UTF8->GetBytes(ref->ToString());
  619. cli::pin_ptr<System::Byte> p = &bytes[0];
  620. return std::string(reinterpret_cast<char const *>(p), bytes->Length);
  621. }
  622. #endif
  623. } // namespace Detail
  624. // If we decide for C++14, change these to enable_if_ts
  625. template <typename T, typename = void>
  626. struct StringMaker {
  627. template <typename Fake = T>
  628. static
  629. typename std::enable_if<::Catch::Detail::IsStreamInsertable<Fake>::value, std::string>::type
  630. convert(const Fake& value) {
  631. ReusableStringStream rss;
  632. rss << value;
  633. return rss.str();
  634. }
  635. template <typename Fake = T>
  636. static
  637. typename std::enable_if<!::Catch::Detail::IsStreamInsertable<Fake>::value, std::string>::type
  638. convert( const Fake& value ) {
  639. return Detail::convertUnstreamable( value );
  640. }
  641. };
  642. namespace Detail {
  643. // This function dispatches all stringification requests inside of Catch.
  644. // Should be preferably called fully qualified, like ::Catch::Detail::stringify
  645. template <typename T>
  646. std::string stringify(const T& e) {
  647. return ::Catch::StringMaker<typename std::remove_cv<typename std::remove_reference<T>::type>::type>::convert(e);
  648. }
  649. template<typename E>
  650. std::string convertUnknownEnumToString( E e ) {
  651. return ::Catch::Detail::stringify(static_cast<typename std::underlying_type<E>::type>(e));
  652. }
  653. #if defined(_MANAGED)
  654. template <typename T>
  655. std::string stringify( T^ e ) {
  656. return ::Catch::StringMaker<T^>::convert(e);
  657. }
  658. #endif
  659. } // namespace Detail
  660. // Some predefined specializations
  661. template<>
  662. struct StringMaker<std::string> {
  663. static std::string convert(const std::string& str);
  664. };
  665. #ifdef CATCH_CONFIG_WCHAR
  666. template<>
  667. struct StringMaker<std::wstring> {
  668. static std::string convert(const std::wstring& wstr);
  669. };
  670. #endif
  671. template<>
  672. struct StringMaker<char const *> {
  673. static std::string convert(char const * str);
  674. };
  675. template<>
  676. struct StringMaker<char *> {
  677. static std::string convert(char * str);
  678. };
  679. #ifdef CATCH_CONFIG_WCHAR
  680. template<>
  681. struct StringMaker<wchar_t const *> {
  682. static std::string convert(wchar_t const * str);
  683. };
  684. template<>
  685. struct StringMaker<wchar_t *> {
  686. static std::string convert(wchar_t * str);
  687. };
  688. #endif
  689. // TBD: Should we use `strnlen` to ensure that we don't go out of the buffer,
  690. // while keeping string semantics?
  691. template<int SZ>
  692. struct StringMaker<char[SZ]> {
  693. static std::string convert(char const* str) {
  694. return ::Catch::Detail::stringify(std::string{ str });
  695. }
  696. };
  697. template<int SZ>
  698. struct StringMaker<signed char[SZ]> {
  699. static std::string convert(signed char const* str) {
  700. return ::Catch::Detail::stringify(std::string{ reinterpret_cast<char const *>(str) });
  701. }
  702. };
  703. template<int SZ>
  704. struct StringMaker<unsigned char[SZ]> {
  705. static std::string convert(unsigned char const* str) {
  706. return ::Catch::Detail::stringify(std::string{ reinterpret_cast<char const *>(str) });
  707. }
  708. };
  709. template<>
  710. struct StringMaker<int> {
  711. static std::string convert(int value);
  712. };
  713. template<>
  714. struct StringMaker<long> {
  715. static std::string convert(long value);
  716. };
  717. template<>
  718. struct StringMaker<long long> {
  719. static std::string convert(long long value);
  720. };
  721. template<>
  722. struct StringMaker<unsigned int> {
  723. static std::string convert(unsigned int value);
  724. };
  725. template<>
  726. struct StringMaker<unsigned long> {
  727. static std::string convert(unsigned long value);
  728. };
  729. template<>
  730. struct StringMaker<unsigned long long> {
  731. static std::string convert(unsigned long long value);
  732. };
  733. template<>
  734. struct StringMaker<bool> {
  735. static std::string convert(bool b);
  736. };
  737. template<>
  738. struct StringMaker<char> {
  739. static std::string convert(char c);
  740. };
  741. template<>
  742. struct StringMaker<signed char> {
  743. static std::string convert(signed char c);
  744. };
  745. template<>
  746. struct StringMaker<unsigned char> {
  747. static std::string convert(unsigned char c);
  748. };
  749. template<>
  750. struct StringMaker<std::nullptr_t> {
  751. static std::string convert(std::nullptr_t);
  752. };
  753. template<>
  754. struct StringMaker<float> {
  755. static std::string convert(float value);
  756. };
  757. template<>
  758. struct StringMaker<double> {
  759. static std::string convert(double value);
  760. };
  761. template <typename T>
  762. struct StringMaker<T*> {
  763. template <typename U>
  764. static std::string convert(U* p) {
  765. if (p) {
  766. return ::Catch::Detail::rawMemoryToString(p);
  767. } else {
  768. return "nullptr";
  769. }
  770. }
  771. };
  772. template <typename R, typename C>
  773. struct StringMaker<R C::*> {
  774. static std::string convert(R C::* p) {
  775. if (p) {
  776. return ::Catch::Detail::rawMemoryToString(p);
  777. } else {
  778. return "nullptr";
  779. }
  780. }
  781. };
  782. #if defined(_MANAGED)
  783. template <typename T>
  784. struct StringMaker<T^> {
  785. static std::string convert( T^ ref ) {
  786. return ::Catch::Detail::clrReferenceToString(ref);
  787. }
  788. };
  789. #endif
  790. namespace Detail {
  791. template<typename InputIterator>
  792. std::string rangeToString(InputIterator first, InputIterator last) {
  793. ReusableStringStream rss;
  794. rss << "{ ";
  795. if (first != last) {
  796. rss << ::Catch::Detail::stringify(*first);
  797. for (++first; first != last; ++first)
  798. rss << ", " << ::Catch::Detail::stringify(*first);
  799. }
  800. rss << " }";
  801. return rss.str();
  802. }
  803. }
  804. #ifdef __OBJC__
  805. template<>
  806. struct StringMaker<NSString*> {
  807. static std::string convert(NSString * nsstring) {
  808. if (!nsstring)
  809. return "nil";
  810. return std::string("@") + [nsstring UTF8String];
  811. }
  812. };
  813. template<>
  814. struct StringMaker<NSObject*> {
  815. static std::string convert(NSObject* nsObject) {
  816. return ::Catch::Detail::stringify([nsObject description]);
  817. }
  818. };
  819. namespace Detail {
  820. inline std::string stringify( NSString* nsstring ) {
  821. return StringMaker<NSString*>::convert( nsstring );
  822. }
  823. } // namespace Detail
  824. #endif // __OBJC__
  825. } // namespace Catch
  826. //////////////////////////////////////////////////////
  827. // Separate std-lib types stringification, so it can be selectively enabled
  828. // This means that we do not bring in
  829. #if defined(CATCH_CONFIG_ENABLE_ALL_STRINGMAKERS)
  830. # define CATCH_CONFIG_ENABLE_PAIR_STRINGMAKER
  831. # define CATCH_CONFIG_ENABLE_TUPLE_STRINGMAKER
  832. # define CATCH_CONFIG_ENABLE_CHRONO_STRINGMAKER
  833. #endif
  834. // Separate std::pair specialization
  835. #if defined(CATCH_CONFIG_ENABLE_PAIR_STRINGMAKER)
  836. #include <utility>
  837. namespace Catch {
  838. template<typename T1, typename T2>
  839. struct StringMaker<std::pair<T1, T2> > {
  840. static std::string convert(const std::pair<T1, T2>& pair) {
  841. ReusableStringStream rss;
  842. rss << "{ "
  843. << ::Catch::Detail::stringify(pair.first)
  844. << ", "
  845. << ::Catch::Detail::stringify(pair.second)
  846. << " }";
  847. return rss.str();
  848. }
  849. };
  850. }
  851. #endif // CATCH_CONFIG_ENABLE_PAIR_STRINGMAKER
  852. // Separate std::tuple specialization
  853. #if defined(CATCH_CONFIG_ENABLE_TUPLE_STRINGMAKER)
  854. #include <tuple>
  855. namespace Catch {
  856. namespace Detail {
  857. template<
  858. typename Tuple,
  859. std::size_t N = 0,
  860. bool = (N < std::tuple_size<Tuple>::value)
  861. >
  862. struct TupleElementPrinter {
  863. static void print(const Tuple& tuple, std::ostream& os) {
  864. os << (N ? ", " : " ")
  865. << ::Catch::Detail::stringify(std::get<N>(tuple));
  866. TupleElementPrinter<Tuple, N + 1>::print(tuple, os);
  867. }
  868. };
  869. template<
  870. typename Tuple,
  871. std::size_t N
  872. >
  873. struct TupleElementPrinter<Tuple, N, false> {
  874. static void print(const Tuple&, std::ostream&) {}
  875. };
  876. }
  877. template<typename ...Types>
  878. struct StringMaker<std::tuple<Types...>> {
  879. static std::string convert(const std::tuple<Types...>& tuple) {
  880. ReusableStringStream rss;
  881. rss << '{';
  882. Detail::TupleElementPrinter<std::tuple<Types...>>::print(tuple, rss.get());
  883. rss << " }";
  884. return rss.str();
  885. }
  886. };
  887. }
  888. #endif // CATCH_CONFIG_ENABLE_TUPLE_STRINGMAKER
  889. namespace Catch {
  890. struct not_this_one {}; // Tag type for detecting which begin/ end are being selected
  891. // Import begin/ end from std here so they are considered alongside the fallback (...) overloads in this namespace
  892. using std::begin;
  893. using std::end;
  894. not_this_one begin( ... );
  895. not_this_one end( ... );
  896. template <typename T>
  897. struct is_range {
  898. static const bool value =
  899. !std::is_same<decltype(begin(std::declval<T>())), not_this_one>::value &&
  900. !std::is_same<decltype(end(std::declval<T>())), not_this_one>::value;
  901. };
  902. #if defined(_MANAGED) // Managed types are never ranges
  903. template <typename T>
  904. struct is_range<T^> {
  905. static const bool value = false;
  906. };
  907. #endif
  908. template<typename Range>
  909. std::string rangeToString( Range const& range ) {
  910. return ::Catch::Detail::rangeToString( begin( range ), end( range ) );
  911. }
  912. // Handle vector<bool> specially
  913. template<typename Allocator>
  914. std::string rangeToString( std::vector<bool, Allocator> const& v ) {
  915. ReusableStringStream rss;
  916. rss << "{ ";
  917. bool first = true;
  918. for( bool b : v ) {
  919. if( first )
  920. first = false;
  921. else
  922. rss << ", ";
  923. rss << ::Catch::Detail::stringify( b );
  924. }
  925. rss << " }";
  926. return rss.str();
  927. }
  928. template<typename R>
  929. struct StringMaker<R, typename std::enable_if<is_range<R>::value && !::Catch::Detail::IsStreamInsertable<R>::value>::type> {
  930. static std::string convert( R const& range ) {
  931. return rangeToString( range );
  932. }
  933. };
  934. template <typename T, int SZ>
  935. struct StringMaker<T[SZ]> {
  936. static std::string convert(T const(&arr)[SZ]) {
  937. return rangeToString(arr);
  938. }
  939. };
  940. } // namespace Catch
  941. // Separate std::chrono::duration specialization
  942. #if defined(CATCH_CONFIG_ENABLE_CHRONO_STRINGMAKER)
  943. #include <ctime>
  944. #include <ratio>
  945. #include <chrono>
  946. namespace Catch {
  947. template <class Ratio>
  948. struct ratio_string {
  949. static std::string symbol();
  950. };
  951. template <class Ratio>
  952. std::string ratio_string<Ratio>::symbol() {
  953. Catch::ReusableStringStream rss;
  954. rss << '[' << Ratio::num << '/'
  955. << Ratio::den << ']';
  956. return rss.str();
  957. }
  958. template <>
  959. struct ratio_string<std::atto> {
  960. static std::string symbol();
  961. };
  962. template <>
  963. struct ratio_string<std::femto> {
  964. static std::string symbol();
  965. };
  966. template <>
  967. struct ratio_string<std::pico> {
  968. static std::string symbol();
  969. };
  970. template <>
  971. struct ratio_string<std::nano> {
  972. static std::string symbol();
  973. };
  974. template <>
  975. struct ratio_string<std::micro> {
  976. static std::string symbol();
  977. };
  978. template <>
  979. struct ratio_string<std::milli> {
  980. static std::string symbol();
  981. };
  982. ////////////
  983. // std::chrono::duration specializations
  984. template<typename Value, typename Ratio>
  985. struct StringMaker<std::chrono::duration<Value, Ratio>> {
  986. static std::string convert(std::chrono::duration<Value, Ratio> const& duration) {
  987. ReusableStringStream rss;
  988. rss << duration.count() << ' ' << ratio_string<Ratio>::symbol() << 's';
  989. return rss.str();
  990. }
  991. };
  992. template<typename Value>
  993. struct StringMaker<std::chrono::duration<Value, std::ratio<1>>> {
  994. static std::string convert(std::chrono::duration<Value, std::ratio<1>> const& duration) {
  995. ReusableStringStream rss;
  996. rss << duration.count() << " s";
  997. return rss.str();
  998. }
  999. };
  1000. template<typename Value>
  1001. struct StringMaker<std::chrono::duration<Value, std::ratio<60>>> {
  1002. static std::string convert(std::chrono::duration<Value, std::ratio<60>> const& duration) {
  1003. ReusableStringStream rss;
  1004. rss << duration.count() << " m";
  1005. return rss.str();
  1006. }
  1007. };
  1008. template<typename Value>
  1009. struct StringMaker<std::chrono::duration<Value, std::ratio<3600>>> {
  1010. static std::string convert(std::chrono::duration<Value, std::ratio<3600>> const& duration) {
  1011. ReusableStringStream rss;
  1012. rss << duration.count() << " h";
  1013. return rss.str();
  1014. }
  1015. };
  1016. ////////////
  1017. // std::chrono::time_point specialization
  1018. // Generic time_point cannot be specialized, only std::chrono::time_point<system_clock>
  1019. template<typename Clock, typename Duration>
  1020. struct StringMaker<std::chrono::time_point<Clock, Duration>> {
  1021. static std::string convert(std::chrono::time_point<Clock, Duration> const& time_point) {
  1022. return ::Catch::Detail::stringify(time_point.time_since_epoch()) + " since epoch";
  1023. }
  1024. };
  1025. // std::chrono::time_point<system_clock> specialization
  1026. template<typename Duration>
  1027. struct StringMaker<std::chrono::time_point<std::chrono::system_clock, Duration>> {
  1028. static std::string convert(std::chrono::time_point<std::chrono::system_clock, Duration> const& time_point) {
  1029. auto converted = std::chrono::system_clock::to_time_t(time_point);
  1030. #ifdef _MSC_VER
  1031. std::tm timeInfo = {};
  1032. gmtime_s(&timeInfo, &converted);
  1033. #else
  1034. std::tm* timeInfo = std::gmtime(&converted);
  1035. #endif
  1036. auto const timeStampSize = sizeof("2017-01-16T17:06:45Z");
  1037. char timeStamp[timeStampSize];
  1038. const char * const fmt = "%Y-%m-%dT%H:%M:%SZ";
  1039. #ifdef _MSC_VER
  1040. std::strftime(timeStamp, timeStampSize, fmt, &timeInfo);
  1041. #else
  1042. std::strftime(timeStamp, timeStampSize, fmt, timeInfo);
  1043. #endif
  1044. return std::string(timeStamp);
  1045. }
  1046. };
  1047. }
  1048. #endif // CATCH_CONFIG_ENABLE_CHRONO_STRINGMAKER
  1049. #ifdef _MSC_VER
  1050. #pragma warning(pop)
  1051. #endif
  1052. // end catch_tostring.h
  1053. #include <iosfwd>
  1054. #ifdef _MSC_VER
  1055. #pragma warning(push)
  1056. #pragma warning(disable:4389) // '==' : signed/unsigned mismatch
  1057. #pragma warning(disable:4018) // more "signed/unsigned mismatch"
  1058. #pragma warning(disable:4312) // Converting int to T* using reinterpret_cast (issue on x64 platform)
  1059. #pragma warning(disable:4180) // qualifier applied to function type has no meaning
  1060. #endif
  1061. namespace Catch {
  1062. struct ITransientExpression {
  1063. auto isBinaryExpression() const -> bool { return m_isBinaryExpression; }
  1064. auto getResult() const -> bool { return m_result; }
  1065. virtual void streamReconstructedExpression( std::ostream &os ) const = 0;
  1066. ITransientExpression( bool isBinaryExpression, bool result )
  1067. : m_isBinaryExpression( isBinaryExpression ),
  1068. m_result( result )
  1069. {}
  1070. // We don't actually need a virtual destructor, but many static analysers
  1071. // complain if it's not here :-(
  1072. virtual ~ITransientExpression();
  1073. bool m_isBinaryExpression;
  1074. bool m_result;
  1075. };
  1076. void formatReconstructedExpression( std::ostream &os, std::string const& lhs, StringRef op, std::string const& rhs );
  1077. template<typename LhsT, typename RhsT>
  1078. class BinaryExpr : public ITransientExpression {
  1079. LhsT m_lhs;
  1080. StringRef m_op;
  1081. RhsT m_rhs;
  1082. void streamReconstructedExpression( std::ostream &os ) const override {
  1083. formatReconstructedExpression
  1084. ( os, Catch::Detail::stringify( m_lhs ), m_op, Catch::Detail::stringify( m_rhs ) );
  1085. }
  1086. public:
  1087. BinaryExpr( bool comparisonResult, LhsT lhs, StringRef op, RhsT rhs )
  1088. : ITransientExpression{ true, comparisonResult },
  1089. m_lhs( lhs ),
  1090. m_op( op ),
  1091. m_rhs( rhs )
  1092. {}
  1093. };
  1094. template<typename LhsT>
  1095. class UnaryExpr : public ITransientExpression {
  1096. LhsT m_lhs;
  1097. void streamReconstructedExpression( std::ostream &os ) const override {
  1098. os << Catch::Detail::stringify( m_lhs );
  1099. }
  1100. public:
  1101. explicit UnaryExpr( LhsT lhs )
  1102. : ITransientExpression{ false, lhs ? true : false },
  1103. m_lhs( lhs )
  1104. {}
  1105. };
  1106. // Specialised comparison functions to handle equality comparisons between ints and pointers (NULL deduces as an int)
  1107. template<typename LhsT, typename RhsT>
  1108. auto compareEqual( LhsT const& lhs, RhsT const& rhs ) -> bool { return static_cast<bool>(lhs == rhs); }
  1109. template<typename T>
  1110. auto compareEqual( T* const& lhs, int rhs ) -> bool { return lhs == reinterpret_cast<void const*>( rhs ); }
  1111. template<typename T>
  1112. auto compareEqual( T* const& lhs, long rhs ) -> bool { return lhs == reinterpret_cast<void const*>( rhs ); }
  1113. template<typename T>
  1114. auto compareEqual( int lhs, T* const& rhs ) -> bool { return reinterpret_cast<void const*>( lhs ) == rhs; }
  1115. template<typename T>
  1116. auto compareEqual( long lhs, T* const& rhs ) -> bool { return reinterpret_cast<void const*>( lhs ) == rhs; }
  1117. template<typename LhsT, typename RhsT>
  1118. auto compareNotEqual( LhsT const& lhs, RhsT&& rhs ) -> bool { return static_cast<bool>(lhs != rhs); }
  1119. template<typename T>
  1120. auto compareNotEqual( T* const& lhs, int rhs ) -> bool { return lhs != reinterpret_cast<void const*>( rhs ); }
  1121. template<typename T>
  1122. auto compareNotEqual( T* const& lhs, long rhs ) -> bool { return lhs != reinterpret_cast<void const*>( rhs ); }
  1123. template<typename T>
  1124. auto compareNotEqual( int lhs, T* const& rhs ) -> bool { return reinterpret_cast<void const*>( lhs ) != rhs; }
  1125. template<typename T>
  1126. auto compareNotEqual( long lhs, T* const& rhs ) -> bool { return reinterpret_cast<void const*>( lhs ) != rhs; }
  1127. template<typename LhsT>
  1128. class ExprLhs {
  1129. LhsT m_lhs;
  1130. public:
  1131. explicit ExprLhs( LhsT lhs ) : m_lhs( lhs ) {}
  1132. template<typename RhsT>
  1133. auto operator == ( RhsT const& rhs ) -> BinaryExpr<LhsT, RhsT const&> const {
  1134. return { compareEqual( m_lhs, rhs ), m_lhs, "==", rhs };
  1135. }
  1136. auto operator == ( bool rhs ) -> BinaryExpr<LhsT, bool> const {
  1137. return { m_lhs == rhs, m_lhs, "==", rhs };
  1138. }
  1139. template<typename RhsT>
  1140. auto operator != ( RhsT const& rhs ) -> BinaryExpr<LhsT, RhsT const&> const {
  1141. return { compareNotEqual( m_lhs, rhs ), m_lhs, "!=", rhs };
  1142. }
  1143. auto operator != ( bool rhs ) -> BinaryExpr<LhsT, bool> const {
  1144. return { m_lhs != rhs, m_lhs, "!=", rhs };
  1145. }
  1146. template<typename RhsT>
  1147. auto operator > ( RhsT const& rhs ) -> BinaryExpr<LhsT, RhsT const&> const {
  1148. return { static_cast<bool>(m_lhs > rhs), m_lhs, ">", rhs };
  1149. }
  1150. template<typename RhsT>
  1151. auto operator < ( RhsT const& rhs ) -> BinaryExpr<LhsT, RhsT const&> const {
  1152. return { static_cast<bool>(m_lhs < rhs), m_lhs, "<", rhs };
  1153. }
  1154. template<typename RhsT>
  1155. auto operator >= ( RhsT const& rhs ) -> BinaryExpr<LhsT, RhsT const&> const {
  1156. return { static_cast<bool>(m_lhs >= rhs), m_lhs, ">=", rhs };
  1157. }
  1158. template<typename RhsT>
  1159. auto operator <= ( RhsT const& rhs ) -> BinaryExpr<LhsT, RhsT const&> const {
  1160. return { static_cast<bool>(m_lhs <= rhs), m_lhs, "<=", rhs };
  1161. }
  1162. auto makeUnaryExpr() const -> UnaryExpr<LhsT> {
  1163. return UnaryExpr<LhsT>{ m_lhs };
  1164. }
  1165. };
  1166. void handleExpression( ITransientExpression const& expr );
  1167. template<typename T>
  1168. void handleExpression( ExprLhs<T> const& expr ) {
  1169. handleExpression( expr.makeUnaryExpr() );
  1170. }
  1171. struct Decomposer {
  1172. template<typename T>
  1173. auto operator <= ( T const& lhs ) -> ExprLhs<T const&> {
  1174. return ExprLhs<T const&>{ lhs };
  1175. }
  1176. auto operator <=( bool value ) -> ExprLhs<bool> {
  1177. return ExprLhs<bool>{ value };
  1178. }
  1179. };
  1180. } // end namespace Catch
  1181. #ifdef _MSC_VER
  1182. #pragma warning(pop)
  1183. #endif
  1184. // end catch_decomposer.h
  1185. // start catch_interfaces_capture.h
  1186. #include <string>
  1187. namespace Catch {
  1188. class AssertionResult;
  1189. struct AssertionInfo;
  1190. struct SectionInfo;
  1191. struct SectionEndInfo;
  1192. struct MessageInfo;
  1193. struct Counts;
  1194. struct BenchmarkInfo;
  1195. struct BenchmarkStats;
  1196. struct AssertionReaction;
  1197. struct ITransientExpression;
  1198. struct IResultCapture {
  1199. virtual ~IResultCapture();
  1200. virtual bool sectionStarted( SectionInfo const& sectionInfo,
  1201. Counts& assertions ) = 0;
  1202. virtual void sectionEnded( SectionEndInfo const& endInfo ) = 0;
  1203. virtual void sectionEndedEarly( SectionEndInfo const& endInfo ) = 0;
  1204. virtual void benchmarkStarting( BenchmarkInfo const& info ) = 0;
  1205. virtual void benchmarkEnded( BenchmarkStats const& stats ) = 0;
  1206. virtual void pushScopedMessage( MessageInfo const& message ) = 0;
  1207. virtual void popScopedMessage( MessageInfo const& message ) = 0;
  1208. virtual void handleFatalErrorCondition( StringRef message ) = 0;
  1209. virtual void handleExpr
  1210. ( AssertionInfo const& info,
  1211. ITransientExpression const& expr,
  1212. AssertionReaction& reaction ) = 0;
  1213. virtual void handleMessage
  1214. ( AssertionInfo const& info,
  1215. ResultWas::OfType resultType,
  1216. StringRef const& message,
  1217. AssertionReaction& reaction ) = 0;
  1218. virtual void handleUnexpectedExceptionNotThrown
  1219. ( AssertionInfo const& info,
  1220. AssertionReaction& reaction ) = 0;
  1221. virtual void handleUnexpectedInflightException
  1222. ( AssertionInfo const& info,
  1223. std::string const& message,
  1224. AssertionReaction& reaction ) = 0;
  1225. virtual void handleIncomplete
  1226. ( AssertionInfo const& info ) = 0;
  1227. virtual void handleNonExpr
  1228. ( AssertionInfo const &info,
  1229. ResultWas::OfType resultType,
  1230. AssertionReaction &reaction ) = 0;
  1231. virtual bool lastAssertionPassed() = 0;
  1232. virtual void assertionPassed() = 0;
  1233. // Deprecated, do not use:
  1234. virtual std::string getCurrentTestName() const = 0;
  1235. virtual const AssertionResult* getLastResult() const = 0;
  1236. virtual void exceptionEarlyReported() = 0;
  1237. };
  1238. IResultCapture& getResultCapture();
  1239. }
  1240. // end catch_interfaces_capture.h
  1241. namespace Catch {
  1242. struct TestFailureException{};
  1243. struct AssertionResultData;
  1244. struct IResultCapture;
  1245. class RunContext;
  1246. class LazyExpression {
  1247. friend class AssertionHandler;
  1248. friend struct AssertionStats;
  1249. friend class RunContext;
  1250. ITransientExpression const* m_transientExpression = nullptr;
  1251. bool m_isNegated;
  1252. public:
  1253. LazyExpression( bool isNegated );
  1254. LazyExpression( LazyExpression const& other );
  1255. LazyExpression& operator = ( LazyExpression const& ) = delete;
  1256. explicit operator bool() const;
  1257. friend auto operator << ( std::ostream& os, LazyExpression const& lazyExpr ) -> std::ostream&;
  1258. };
  1259. struct AssertionReaction {
  1260. bool shouldDebugBreak = false;
  1261. bool shouldThrow = false;
  1262. };
  1263. class AssertionHandler {
  1264. AssertionInfo m_assertionInfo;
  1265. AssertionReaction m_reaction;
  1266. bool m_completed = false;
  1267. IResultCapture& m_resultCapture;
  1268. public:
  1269. AssertionHandler
  1270. ( StringRef macroName,
  1271. SourceLineInfo const& lineInfo,
  1272. StringRef capturedExpression,
  1273. ResultDisposition::Flags resultDisposition );
  1274. ~AssertionHandler() {
  1275. if ( !m_completed ) {
  1276. m_resultCapture.handleIncomplete( m_assertionInfo );
  1277. }
  1278. }
  1279. template<typename T>
  1280. void handleExpr( ExprLhs<T> const& expr ) {
  1281. handleExpr( expr.makeUnaryExpr() );
  1282. }
  1283. void handleExpr( ITransientExpression const& expr );
  1284. void handleMessage(ResultWas::OfType resultType, StringRef const& message);
  1285. void handleExceptionThrownAsExpected();
  1286. void handleUnexpectedExceptionNotThrown();
  1287. void handleExceptionNotThrownAsExpected();
  1288. void handleThrowingCallSkipped();
  1289. void handleUnexpectedInflightException();
  1290. void complete();
  1291. void setCompleted();
  1292. // query
  1293. auto allowThrows() const -> bool;
  1294. };
  1295. void handleExceptionMatchExpr( AssertionHandler& handler, std::string const& str, StringRef matcherString );
  1296. } // namespace Catch
  1297. // end catch_assertionhandler.h
  1298. // start catch_message.h
  1299. #include <string>
  1300. namespace Catch {
  1301. struct MessageInfo {
  1302. MessageInfo( std::string const& _macroName,
  1303. SourceLineInfo const& _lineInfo,
  1304. ResultWas::OfType _type );
  1305. std::string macroName;
  1306. std::string message;
  1307. SourceLineInfo lineInfo;
  1308. ResultWas::OfType type;
  1309. unsigned int sequence;
  1310. bool operator == ( MessageInfo const& other ) const;
  1311. bool operator < ( MessageInfo const& other ) const;
  1312. private:
  1313. static unsigned int globalCount;
  1314. };
  1315. struct MessageStream {
  1316. template<typename T>
  1317. MessageStream& operator << ( T const& value ) {
  1318. m_stream << value;
  1319. return *this;
  1320. }
  1321. ReusableStringStream m_stream;
  1322. };
  1323. struct MessageBuilder : MessageStream {
  1324. MessageBuilder( std::string const& macroName,
  1325. SourceLineInfo const& lineInfo,
  1326. ResultWas::OfType type );
  1327. template<typename T>
  1328. MessageBuilder& operator << ( T const& value ) {
  1329. m_stream << value;
  1330. return *this;
  1331. }
  1332. MessageInfo m_info;
  1333. };
  1334. class ScopedMessage {
  1335. public:
  1336. explicit ScopedMessage( MessageBuilder const& builder );
  1337. ~ScopedMessage();
  1338. MessageInfo m_info;
  1339. };
  1340. } // end namespace Catch
  1341. // end catch_message.h
  1342. #if !defined(CATCH_CONFIG_DISABLE)
  1343. #if !defined(CATCH_CONFIG_DISABLE_STRINGIFICATION)
  1344. #define CATCH_INTERNAL_STRINGIFY(...) #__VA_ARGS__
  1345. #else
  1346. #define CATCH_INTERNAL_STRINGIFY(...) "Disabled by CATCH_CONFIG_DISABLE_STRINGIFICATION"
  1347. #endif
  1348. #if defined(CATCH_CONFIG_FAST_COMPILE)
  1349. ///////////////////////////////////////////////////////////////////////////////
  1350. // Another way to speed-up compilation is to omit local try-catch for REQUIRE*
  1351. // macros.
  1352. #define INTERNAL_CATCH_TRY
  1353. #define INTERNAL_CATCH_CATCH( capturer )
  1354. #else // CATCH_CONFIG_FAST_COMPILE
  1355. #define INTERNAL_CATCH_TRY try
  1356. #define INTERNAL_CATCH_CATCH( handler ) catch(...) { handler.handleUnexpectedInflightException(); }
  1357. #endif
  1358. #define INTERNAL_CATCH_REACT( handler ) handler.complete();
  1359. ///////////////////////////////////////////////////////////////////////////////
  1360. #define INTERNAL_CATCH_TEST( macroName, resultDisposition, ... ) \
  1361. do { \
  1362. Catch::AssertionHandler catchAssertionHandler( macroName, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(__VA_ARGS__), resultDisposition ); \
  1363. INTERNAL_CATCH_TRY { \
  1364. CATCH_INTERNAL_SUPPRESS_PARENTHESES_WARNINGS \
  1365. catchAssertionHandler.handleExpr( Catch::Decomposer() <= __VA_ARGS__ ); \
  1366. CATCH_INTERNAL_UNSUPPRESS_PARENTHESES_WARNINGS \
  1367. } INTERNAL_CATCH_CATCH( catchAssertionHandler ) \
  1368. INTERNAL_CATCH_REACT( catchAssertionHandler ) \
  1369. } 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
  1370. // The double negation silences MSVC's C4800 warning, the static_cast forces short-circuit evaluation if the type has overloaded &&.
  1371. ///////////////////////////////////////////////////////////////////////////////
  1372. #define INTERNAL_CATCH_IF( macroName, resultDisposition, ... ) \
  1373. INTERNAL_CATCH_TEST( macroName, resultDisposition, __VA_ARGS__ ); \
  1374. if( Catch::getResultCapture().lastAssertionPassed() )
  1375. ///////////////////////////////////////////////////////////////////////////////
  1376. #define INTERNAL_CATCH_ELSE( macroName, resultDisposition, ... ) \
  1377. INTERNAL_CATCH_TEST( macroName, resultDisposition, __VA_ARGS__ ); \
  1378. if( !Catch::getResultCapture().lastAssertionPassed() )
  1379. ///////////////////////////////////////////////////////////////////////////////
  1380. #define INTERNAL_CATCH_NO_THROW( macroName, resultDisposition, ... ) \
  1381. do { \
  1382. Catch::AssertionHandler catchAssertionHandler( macroName, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(__VA_ARGS__), resultDisposition ); \
  1383. try { \
  1384. static_cast<void>(__VA_ARGS__); \
  1385. catchAssertionHandler.handleExceptionNotThrownAsExpected(); \
  1386. } \
  1387. catch( ... ) { \
  1388. catchAssertionHandler.handleUnexpectedInflightException(); \
  1389. } \
  1390. INTERNAL_CATCH_REACT( catchAssertionHandler ) \
  1391. } while( false )
  1392. ///////////////////////////////////////////////////////////////////////////////
  1393. #define INTERNAL_CATCH_THROWS( macroName, resultDisposition, ... ) \
  1394. do { \
  1395. Catch::AssertionHandler catchAssertionHandler( macroName, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(__VA_ARGS__), resultDisposition); \
  1396. if( catchAssertionHandler.allowThrows() ) \
  1397. try { \
  1398. static_cast<void>(__VA_ARGS__); \
  1399. catchAssertionHandler.handleUnexpectedExceptionNotThrown(); \
  1400. } \
  1401. catch( ... ) { \
  1402. catchAssertionHandler.handleExceptionThrownAsExpected(); \
  1403. } \
  1404. else \
  1405. catchAssertionHandler.handleThrowingCallSkipped(); \
  1406. INTERNAL_CATCH_REACT( catchAssertionHandler ) \
  1407. } while( false )
  1408. ///////////////////////////////////////////////////////////////////////////////
  1409. #define INTERNAL_CATCH_THROWS_AS( macroName, exceptionType, resultDisposition, expr ) \
  1410. do { \
  1411. Catch::AssertionHandler catchAssertionHandler( macroName, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(expr) ", " CATCH_INTERNAL_STRINGIFY(exceptionType), resultDisposition ); \
  1412. if( catchAssertionHandler.allowThrows() ) \
  1413. try { \
  1414. static_cast<void>(expr); \
  1415. catchAssertionHandler.handleUnexpectedExceptionNotThrown(); \
  1416. } \
  1417. catch( exceptionType const& ) { \
  1418. catchAssertionHandler.handleExceptionThrownAsExpected(); \
  1419. } \
  1420. catch( ... ) { \
  1421. catchAssertionHandler.handleUnexpectedInflightException(); \
  1422. } \
  1423. else \
  1424. catchAssertionHandler.handleThrowingCallSkipped(); \
  1425. INTERNAL_CATCH_REACT( catchAssertionHandler ) \
  1426. } while( false )
  1427. ///////////////////////////////////////////////////////////////////////////////
  1428. #define INTERNAL_CATCH_MSG( macroName, messageType, resultDisposition, ... ) \
  1429. do { \
  1430. Catch::AssertionHandler catchAssertionHandler( macroName, CATCH_INTERNAL_LINEINFO, "", resultDisposition ); \
  1431. catchAssertionHandler.handleMessage( messageType, ( Catch::MessageStream() << __VA_ARGS__ + ::Catch::StreamEndStop() ).m_stream.str() ); \
  1432. INTERNAL_CATCH_REACT( catchAssertionHandler ) \
  1433. } while( false )
  1434. ///////////////////////////////////////////////////////////////////////////////
  1435. #define INTERNAL_CATCH_INFO( macroName, log ) \
  1436. Catch::ScopedMessage INTERNAL_CATCH_UNIQUE_NAME( scopedMessage )( Catch::MessageBuilder( macroName, CATCH_INTERNAL_LINEINFO, Catch::ResultWas::Info ) << log );
  1437. ///////////////////////////////////////////////////////////////////////////////
  1438. // Although this is matcher-based, it can be used with just a string
  1439. #define INTERNAL_CATCH_THROWS_STR_MATCHES( macroName, resultDisposition, matcher, ... ) \
  1440. do { \
  1441. Catch::AssertionHandler catchAssertionHandler( macroName, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(__VA_ARGS__) ", " CATCH_INTERNAL_STRINGIFY(matcher), resultDisposition ); \
  1442. if( catchAssertionHandler.allowThrows() ) \
  1443. try { \
  1444. static_cast<void>(__VA_ARGS__); \
  1445. catchAssertionHandler.handleUnexpectedExceptionNotThrown(); \
  1446. } \
  1447. catch( ... ) { \
  1448. Catch::handleExceptionMatchExpr( catchAssertionHandler, matcher, #matcher ); \
  1449. } \
  1450. else \
  1451. catchAssertionHandler.handleThrowingCallSkipped(); \
  1452. INTERNAL_CATCH_REACT( catchAssertionHandler ) \
  1453. } while( false )
  1454. #endif // CATCH_CONFIG_DISABLE
  1455. // end catch_capture.hpp
  1456. // start catch_section.h
  1457. // start catch_section_info.h
  1458. // start catch_totals.h
  1459. #include <cstddef>
  1460. namespace Catch {
  1461. struct Counts {
  1462. Counts operator - ( Counts const& other ) const;
  1463. Counts& operator += ( Counts const& other );
  1464. std::size_t total() const;
  1465. bool allPassed() const;
  1466. bool allOk() const;
  1467. std::size_t passed = 0;
  1468. std::size_t failed = 0;
  1469. std::size_t failedButOk = 0;
  1470. };
  1471. struct Totals {
  1472. Totals operator - ( Totals const& other ) const;
  1473. Totals& operator += ( Totals const& other );
  1474. Totals delta( Totals const& prevTotals ) const;
  1475. int error = 0;
  1476. Counts assertions;
  1477. Counts testCases;
  1478. };
  1479. }
  1480. // end catch_totals.h
  1481. #include <string>
  1482. namespace Catch {
  1483. struct SectionInfo {
  1484. SectionInfo
  1485. ( SourceLineInfo const& _lineInfo,
  1486. std::string const& _name,
  1487. std::string const& _description = std::string() );
  1488. std::string name;
  1489. std::string description;
  1490. SourceLineInfo lineInfo;
  1491. };
  1492. struct SectionEndInfo {
  1493. SectionEndInfo( SectionInfo const& _sectionInfo, Counts const& _prevAssertions, double _durationInSeconds );
  1494. SectionInfo sectionInfo;
  1495. Counts prevAssertions;
  1496. double durationInSeconds;
  1497. };
  1498. } // end namespace Catch
  1499. // end catch_section_info.h
  1500. // start catch_timer.h
  1501. #include <cstdint>
  1502. namespace Catch {
  1503. auto getCurrentNanosecondsSinceEpoch() -> uint64_t;
  1504. auto getEstimatedClockResolution() -> uint64_t;
  1505. class Timer {
  1506. uint64_t m_nanoseconds = 0;
  1507. public:
  1508. void start();
  1509. auto getElapsedNanoseconds() const -> uint64_t;
  1510. auto getElapsedMicroseconds() const -> uint64_t;
  1511. auto getElapsedMilliseconds() const -> unsigned int;
  1512. auto getElapsedSeconds() const -> double;
  1513. };
  1514. } // namespace Catch
  1515. // end catch_timer.h
  1516. #include <string>
  1517. namespace Catch {
  1518. class Section : NonCopyable {
  1519. public:
  1520. Section( SectionInfo const& info );
  1521. ~Section();
  1522. // This indicates whether the section should be executed or not
  1523. explicit operator bool() const;
  1524. private:
  1525. SectionInfo m_info;
  1526. std::string m_name;
  1527. Counts m_assertions;
  1528. bool m_sectionIncluded;
  1529. Timer m_timer;
  1530. };
  1531. } // end namespace Catch
  1532. #define INTERNAL_CATCH_SECTION( ... ) \
  1533. if( Catch::Section const& INTERNAL_CATCH_UNIQUE_NAME( catch_internal_Section ) = Catch::SectionInfo( CATCH_INTERNAL_LINEINFO, __VA_ARGS__ ) )
  1534. // end catch_section.h
  1535. // start catch_benchmark.h
  1536. #include <cstdint>
  1537. #include <string>
  1538. namespace Catch {
  1539. class BenchmarkLooper {
  1540. std::string m_name;
  1541. std::size_t m_count = 0;
  1542. std::size_t m_iterationsToRun = 1;
  1543. uint64_t m_resolution;
  1544. Timer m_timer;
  1545. static auto getResolution() -> uint64_t;
  1546. public:
  1547. // Keep most of this inline as it's on the code path that is being timed
  1548. BenchmarkLooper( StringRef name )
  1549. : m_name( name ),
  1550. m_resolution( getResolution() )
  1551. {
  1552. reportStart();
  1553. m_timer.start();
  1554. }
  1555. explicit operator bool() {
  1556. if( m_count < m_iterationsToRun )
  1557. return true;
  1558. return needsMoreIterations();
  1559. }
  1560. void increment() {
  1561. ++m_count;
  1562. }
  1563. void reportStart();
  1564. auto needsMoreIterations() -> bool;
  1565. };
  1566. } // end namespace Catch
  1567. #define BENCHMARK( name ) \
  1568. for( Catch::BenchmarkLooper looper( name ); looper; looper.increment() )
  1569. // end catch_benchmark.h
  1570. // start catch_interfaces_exception.h
  1571. // start catch_interfaces_registry_hub.h
  1572. #include <string>
  1573. #include <memory>
  1574. namespace Catch {
  1575. class TestCase;
  1576. struct ITestCaseRegistry;
  1577. struct IExceptionTranslatorRegistry;
  1578. struct IExceptionTranslator;
  1579. struct IReporterRegistry;
  1580. struct IReporterFactory;
  1581. struct ITagAliasRegistry;
  1582. class StartupExceptionRegistry;
  1583. using IReporterFactoryPtr = std::shared_ptr<IReporterFactory>;
  1584. struct IRegistryHub {
  1585. virtual ~IRegistryHub();
  1586. virtual IReporterRegistry const& getReporterRegistry() const = 0;
  1587. virtual ITestCaseRegistry const& getTestCaseRegistry() const = 0;
  1588. virtual ITagAliasRegistry const& getTagAliasRegistry() const = 0;
  1589. virtual IExceptionTranslatorRegistry& getExceptionTranslatorRegistry() = 0;
  1590. virtual StartupExceptionRegistry const& getStartupExceptionRegistry() const = 0;
  1591. };
  1592. struct IMutableRegistryHub {
  1593. virtual ~IMutableRegistryHub();
  1594. virtual void registerReporter( std::string const& name, IReporterFactoryPtr const& factory ) = 0;
  1595. virtual void registerListener( IReporterFactoryPtr const& factory ) = 0;
  1596. virtual void registerTest( TestCase const& testInfo ) = 0;
  1597. virtual void registerTranslator( const IExceptionTranslator* translator ) = 0;
  1598. virtual void registerTagAlias( std::string const& alias, std::string const& tag, SourceLineInfo const& lineInfo ) = 0;
  1599. virtual void registerStartupException() noexcept = 0;
  1600. };
  1601. IRegistryHub& getRegistryHub();
  1602. IMutableRegistryHub& getMutableRegistryHub();
  1603. void cleanUp();
  1604. std::string translateActiveException();
  1605. }
  1606. // end catch_interfaces_registry_hub.h
  1607. #if defined(CATCH_CONFIG_DISABLE)
  1608. #define INTERNAL_CATCH_TRANSLATE_EXCEPTION_NO_REG( translatorName, signature) \
  1609. static std::string translatorName( signature )
  1610. #endif
  1611. #include <exception>
  1612. #include <string>
  1613. #include <vector>
  1614. namespace Catch {
  1615. using exceptionTranslateFunction = std::string(*)();
  1616. struct IExceptionTranslator;
  1617. using ExceptionTranslators = std::vector<std::unique_ptr<IExceptionTranslator const>>;
  1618. struct IExceptionTranslator {
  1619. virtual ~IExceptionTranslator();
  1620. virtual std::string translate( ExceptionTranslators::const_iterator it, ExceptionTranslators::const_iterator itEnd ) const = 0;
  1621. };
  1622. struct IExceptionTranslatorRegistry {
  1623. virtual ~IExceptionTranslatorRegistry();
  1624. virtual std::string translateActiveException() const = 0;
  1625. };
  1626. class ExceptionTranslatorRegistrar {
  1627. template<typename T>
  1628. class ExceptionTranslator : public IExceptionTranslator {
  1629. public:
  1630. ExceptionTranslator( std::string(*translateFunction)( T& ) )
  1631. : m_translateFunction( translateFunction )
  1632. {}
  1633. std::string translate( ExceptionTranslators::const_iterator it, ExceptionTranslators::const_iterator itEnd ) const override {
  1634. try {
  1635. if( it == itEnd )
  1636. std::rethrow_exception(std::current_exception());
  1637. else
  1638. return (*it)->translate( it+1, itEnd );
  1639. }
  1640. catch( T& ex ) {
  1641. return m_translateFunction( ex );
  1642. }
  1643. }
  1644. protected:
  1645. std::string(*m_translateFunction)( T& );
  1646. };
  1647. public:
  1648. template<typename T>
  1649. ExceptionTranslatorRegistrar( std::string(*translateFunction)( T& ) ) {
  1650. getMutableRegistryHub().registerTranslator
  1651. ( new ExceptionTranslator<T>( translateFunction ) );
  1652. }
  1653. };
  1654. }
  1655. ///////////////////////////////////////////////////////////////////////////////
  1656. #define INTERNAL_CATCH_TRANSLATE_EXCEPTION2( translatorName, signature ) \
  1657. static std::string translatorName( signature ); \
  1658. CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
  1659. namespace{ Catch::ExceptionTranslatorRegistrar INTERNAL_CATCH_UNIQUE_NAME( catch_internal_ExceptionRegistrar )( &translatorName ); } \
  1660. CATCH_INTERNAL_UNSUPPRESS_GLOBALS_WARNINGS \
  1661. static std::string translatorName( signature )
  1662. #define INTERNAL_CATCH_TRANSLATE_EXCEPTION( signature ) INTERNAL_CATCH_TRANSLATE_EXCEPTION2( INTERNAL_CATCH_UNIQUE_NAME( catch_internal_ExceptionTranslator ), signature )
  1663. // end catch_interfaces_exception.h
  1664. // start catch_approx.h
  1665. #include <type_traits>
  1666. #include <stdexcept>
  1667. namespace Catch {
  1668. namespace Detail {
  1669. class Approx {
  1670. private:
  1671. bool equalityComparisonImpl(double other) const;
  1672. public:
  1673. explicit Approx ( double value );
  1674. static Approx custom();
  1675. template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
  1676. Approx operator()( T const& value ) {
  1677. Approx approx( static_cast<double>(value) );
  1678. approx.epsilon( m_epsilon );
  1679. approx.margin( m_margin );
  1680. approx.scale( m_scale );
  1681. return approx;
  1682. }
  1683. template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
  1684. explicit Approx( T const& value ): Approx(static_cast<double>(value))
  1685. {}
  1686. template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
  1687. friend bool operator == ( const T& lhs, Approx const& rhs ) {
  1688. auto lhs_v = static_cast<double>(lhs);
  1689. return rhs.equalityComparisonImpl(lhs_v);
  1690. }
  1691. template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
  1692. friend bool operator == ( Approx const& lhs, const T& rhs ) {
  1693. return operator==( rhs, lhs );
  1694. }
  1695. template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
  1696. friend bool operator != ( T const& lhs, Approx const& rhs ) {
  1697. return !operator==( lhs, rhs );
  1698. }
  1699. template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
  1700. friend bool operator != ( Approx const& lhs, T const& rhs ) {
  1701. return !operator==( rhs, lhs );
  1702. }
  1703. template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
  1704. friend bool operator <= ( T const& lhs, Approx const& rhs ) {
  1705. return static_cast<double>(lhs) < rhs.m_value || lhs == rhs;
  1706. }
  1707. template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
  1708. friend bool operator <= ( Approx const& lhs, T const& rhs ) {
  1709. return lhs.m_value < static_cast<double>(rhs) || lhs == rhs;
  1710. }
  1711. template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
  1712. friend bool operator >= ( T const& lhs, Approx const& rhs ) {
  1713. return static_cast<double>(lhs) > rhs.m_value || lhs == rhs;
  1714. }
  1715. template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
  1716. friend bool operator >= ( Approx const& lhs, T const& rhs ) {
  1717. return lhs.m_value > static_cast<double>(rhs) || lhs == rhs;
  1718. }
  1719. template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
  1720. Approx& epsilon( T const& newEpsilon ) {
  1721. double epsilonAsDouble = static_cast<double>(newEpsilon);
  1722. if( epsilonAsDouble < 0 || epsilonAsDouble > 1.0 ) {
  1723. throw std::domain_error
  1724. ( "Invalid Approx::epsilon: " +
  1725. Catch::Detail::stringify( epsilonAsDouble ) +
  1726. ", Approx::epsilon has to be between 0 and 1" );
  1727. }
  1728. m_epsilon = epsilonAsDouble;
  1729. return *this;
  1730. }
  1731. template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
  1732. Approx& margin( T const& newMargin ) {
  1733. double marginAsDouble = static_cast<double>(newMargin);
  1734. if( marginAsDouble < 0 ) {
  1735. throw std::domain_error
  1736. ( "Invalid Approx::margin: " +
  1737. Catch::Detail::stringify( marginAsDouble ) +
  1738. ", Approx::Margin has to be non-negative." );
  1739. }
  1740. m_margin = marginAsDouble;
  1741. return *this;
  1742. }
  1743. template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
  1744. Approx& scale( T const& newScale ) {
  1745. m_scale = static_cast<double>(newScale);
  1746. return *this;
  1747. }
  1748. std::string toString() const;
  1749. private:
  1750. double m_epsilon;
  1751. double m_margin;
  1752. double m_scale;
  1753. double m_value;
  1754. };
  1755. }
  1756. template<>
  1757. struct StringMaker<Catch::Detail::Approx> {
  1758. static std::string convert(Catch::Detail::Approx const& value);
  1759. };
  1760. } // end namespace Catch
  1761. // end catch_approx.h
  1762. // start catch_string_manip.h
  1763. #include <string>
  1764. #include <iosfwd>
  1765. namespace Catch {
  1766. bool startsWith( std::string const& s, std::string const& prefix );
  1767. bool startsWith( std::string const& s, char prefix );
  1768. bool endsWith( std::string const& s, std::string const& suffix );
  1769. bool endsWith( std::string const& s, char suffix );
  1770. bool contains( std::string const& s, std::string const& infix );
  1771. void toLowerInPlace( std::string& s );
  1772. std::string toLower( std::string const& s );
  1773. std::string trim( std::string const& str );
  1774. bool replaceInPlace( std::string& str, std::string const& replaceThis, std::string const& withThis );
  1775. struct pluralise {
  1776. pluralise( std::size_t count, std::string const& label );
  1777. friend std::ostream& operator << ( std::ostream& os, pluralise const& pluraliser );
  1778. std::size_t m_count;
  1779. std::string m_label;
  1780. };
  1781. }
  1782. // end catch_string_manip.h
  1783. #ifndef CATCH_CONFIG_DISABLE_MATCHERS
  1784. // start catch_capture_matchers.h
  1785. // start catch_matchers.h
  1786. #include <string>
  1787. #include <vector>
  1788. namespace Catch {
  1789. namespace Matchers {
  1790. namespace Impl {
  1791. template<typename ArgT> struct MatchAllOf;
  1792. template<typename ArgT> struct MatchAnyOf;
  1793. template<typename ArgT> struct MatchNotOf;
  1794. class MatcherUntypedBase {
  1795. public:
  1796. MatcherUntypedBase() = default;
  1797. MatcherUntypedBase ( MatcherUntypedBase const& ) = default;
  1798. MatcherUntypedBase& operator = ( MatcherUntypedBase const& ) = delete;
  1799. std::string toString() const;
  1800. protected:
  1801. virtual ~MatcherUntypedBase();
  1802. virtual std::string describe() const = 0;
  1803. mutable std::string m_cachedToString;
  1804. };
  1805. template<typename ObjectT>
  1806. struct MatcherMethod {
  1807. virtual bool match( ObjectT const& arg ) const = 0;
  1808. };
  1809. template<typename PtrT>
  1810. struct MatcherMethod<PtrT*> {
  1811. virtual bool match( PtrT* arg ) const = 0;
  1812. };
  1813. template<typename T>
  1814. struct MatcherBase : MatcherUntypedBase, MatcherMethod<T> {
  1815. MatchAllOf<T> operator && ( MatcherBase const& other ) const;
  1816. MatchAnyOf<T> operator || ( MatcherBase const& other ) const;
  1817. MatchNotOf<T> operator ! () const;
  1818. };
  1819. template<typename ArgT>
  1820. struct MatchAllOf : MatcherBase<ArgT> {
  1821. bool match( ArgT const& arg ) const override {
  1822. for( auto matcher : m_matchers ) {
  1823. if (!matcher->match(arg))
  1824. return false;
  1825. }
  1826. return true;
  1827. }
  1828. std::string describe() const override {
  1829. std::string description;
  1830. description.reserve( 4 + m_matchers.size()*32 );
  1831. description += "( ";
  1832. bool first = true;
  1833. for( auto matcher : m_matchers ) {
  1834. if( first )
  1835. first = false;
  1836. else
  1837. description += " and ";
  1838. description += matcher->toString();
  1839. }
  1840. description += " )";
  1841. return description;
  1842. }
  1843. MatchAllOf<ArgT>& operator && ( MatcherBase<ArgT> const& other ) {
  1844. m_matchers.push_back( &other );
  1845. return *this;
  1846. }
  1847. std::vector<MatcherBase<ArgT> const*> m_matchers;
  1848. };
  1849. template<typename ArgT>
  1850. struct MatchAnyOf : MatcherBase<ArgT> {
  1851. bool match( ArgT const& arg ) const override {
  1852. for( auto matcher : m_matchers ) {
  1853. if (matcher->match(arg))
  1854. return true;
  1855. }
  1856. return false;
  1857. }
  1858. std::string describe() const override {
  1859. std::string description;
  1860. description.reserve( 4 + m_matchers.size()*32 );
  1861. description += "( ";
  1862. bool first = true;
  1863. for( auto matcher : m_matchers ) {
  1864. if( first )
  1865. first = false;
  1866. else
  1867. description += " or ";
  1868. description += matcher->toString();
  1869. }
  1870. description += " )";
  1871. return description;
  1872. }
  1873. MatchAnyOf<ArgT>& operator || ( MatcherBase<ArgT> const& other ) {
  1874. m_matchers.push_back( &other );
  1875. return *this;
  1876. }
  1877. std::vector<MatcherBase<ArgT> const*> m_matchers;
  1878. };
  1879. template<typename ArgT>
  1880. struct MatchNotOf : MatcherBase<ArgT> {
  1881. MatchNotOf( MatcherBase<ArgT> const& underlyingMatcher ) : m_underlyingMatcher( underlyingMatcher ) {}
  1882. bool match( ArgT const& arg ) const override {
  1883. return !m_underlyingMatcher.match( arg );
  1884. }
  1885. std::string describe() const override {
  1886. return "not " + m_underlyingMatcher.toString();
  1887. }
  1888. MatcherBase<ArgT> const& m_underlyingMatcher;
  1889. };
  1890. template<typename T>
  1891. MatchAllOf<T> MatcherBase<T>::operator && ( MatcherBase const& other ) const {
  1892. return MatchAllOf<T>() && *this && other;
  1893. }
  1894. template<typename T>
  1895. MatchAnyOf<T> MatcherBase<T>::operator || ( MatcherBase const& other ) const {
  1896. return MatchAnyOf<T>() || *this || other;
  1897. }
  1898. template<typename T>
  1899. MatchNotOf<T> MatcherBase<T>::operator ! () const {
  1900. return MatchNotOf<T>( *this );
  1901. }
  1902. } // namespace Impl
  1903. } // namespace Matchers
  1904. using namespace Matchers;
  1905. using Matchers::Impl::MatcherBase;
  1906. } // namespace Catch
  1907. // end catch_matchers.h
  1908. // start catch_matchers_floating.h
  1909. #include <type_traits>
  1910. #include <cmath>
  1911. namespace Catch {
  1912. namespace Matchers {
  1913. namespace Floating {
  1914. enum class FloatingPointKind : uint8_t;
  1915. struct WithinAbsMatcher : MatcherBase<double> {
  1916. WithinAbsMatcher(double target, double margin);
  1917. bool match(double const& matchee) const override;
  1918. std::string describe() const override;
  1919. private:
  1920. double m_target;
  1921. double m_margin;
  1922. };
  1923. struct WithinUlpsMatcher : MatcherBase<double> {
  1924. WithinUlpsMatcher(double target, int ulps, FloatingPointKind baseType);
  1925. bool match(double const& matchee) const override;
  1926. std::string describe() const override;
  1927. private:
  1928. double m_target;
  1929. int m_ulps;
  1930. FloatingPointKind m_type;
  1931. };
  1932. } // namespace Floating
  1933. // The following functions create the actual matcher objects.
  1934. // This allows the types to be inferred
  1935. Floating::WithinUlpsMatcher WithinULP(double target, int maxUlpDiff);
  1936. Floating::WithinUlpsMatcher WithinULP(float target, int maxUlpDiff);
  1937. Floating::WithinAbsMatcher WithinAbs(double target, double margin);
  1938. } // namespace Matchers
  1939. } // namespace Catch
  1940. // end catch_matchers_floating.h
  1941. // start catch_matchers_generic.hpp
  1942. #include <functional>
  1943. #include <string>
  1944. namespace Catch {
  1945. namespace Matchers {
  1946. namespace Generic {
  1947. namespace Detail {
  1948. std::string finalizeDescription(const std::string& desc);
  1949. }
  1950. template <typename T>
  1951. class PredicateMatcher : public MatcherBase<T> {
  1952. std::function<bool(T const&)> m_predicate;
  1953. std::string m_description;
  1954. public:
  1955. PredicateMatcher(std::function<bool(T const&)> const& elem, std::string const& descr)
  1956. :m_predicate(std::move(elem)),
  1957. m_description(Detail::finalizeDescription(descr))
  1958. {}
  1959. bool match( T const& item ) const override {
  1960. return m_predicate(item);
  1961. }
  1962. std::string describe() const override {
  1963. return m_description;
  1964. }
  1965. };
  1966. } // namespace Generic
  1967. // The following functions create the actual matcher objects.
  1968. // The user has to explicitly specify type to the function, because
  1969. // infering std::function<bool(T const&)> is hard (but possible) and
  1970. // requires a lot of TMP.
  1971. template<typename T>
  1972. Generic::PredicateMatcher<T> Predicate(std::function<bool(T const&)> const& predicate, std::string const& description = "") {
  1973. return Generic::PredicateMatcher<T>(predicate, description);
  1974. }
  1975. } // namespace Matchers
  1976. } // namespace Catch
  1977. // end catch_matchers_generic.hpp
  1978. // start catch_matchers_string.h
  1979. #include <string>
  1980. namespace Catch {
  1981. namespace Matchers {
  1982. namespace StdString {
  1983. struct CasedString
  1984. {
  1985. CasedString( std::string const& str, CaseSensitive::Choice caseSensitivity );
  1986. std::string adjustString( std::string const& str ) const;
  1987. std::string caseSensitivitySuffix() const;
  1988. CaseSensitive::Choice m_caseSensitivity;
  1989. std::string m_str;
  1990. };
  1991. struct StringMatcherBase : MatcherBase<std::string> {
  1992. StringMatcherBase( std::string const& operation, CasedString const& comparator );
  1993. std::string describe() const override;
  1994. CasedString m_comparator;
  1995. std::string m_operation;
  1996. };
  1997. struct EqualsMatcher : StringMatcherBase {
  1998. EqualsMatcher( CasedString const& comparator );
  1999. bool match( std::string const& source ) const override;
  2000. };
  2001. struct ContainsMatcher : StringMatcherBase {
  2002. ContainsMatcher( CasedString const& comparator );
  2003. bool match( std::string const& source ) const override;
  2004. };
  2005. struct StartsWithMatcher : StringMatcherBase {
  2006. StartsWithMatcher( CasedString const& comparator );
  2007. bool match( std::string const& source ) const override;
  2008. };
  2009. struct EndsWithMatcher : StringMatcherBase {
  2010. EndsWithMatcher( CasedString const& comparator );
  2011. bool match( std::string const& source ) const override;
  2012. };
  2013. struct RegexMatcher : MatcherBase<std::string> {
  2014. RegexMatcher( std::string regex, CaseSensitive::Choice caseSensitivity );
  2015. bool match( std::string const& matchee ) const override;
  2016. std::string describe() const override;
  2017. private:
  2018. std::string m_regex;
  2019. CaseSensitive::Choice m_caseSensitivity;
  2020. };
  2021. } // namespace StdString
  2022. // The following functions create the actual matcher objects.
  2023. // This allows the types to be inferred
  2024. StdString::EqualsMatcher Equals( std::string const& str, CaseSensitive::Choice caseSensitivity = CaseSensitive::Yes );
  2025. StdString::ContainsMatcher Contains( std::string const& str, CaseSensitive::Choice caseSensitivity = CaseSensitive::Yes );
  2026. StdString::EndsWithMatcher EndsWith( std::string const& str, CaseSensitive::Choice caseSensitivity = CaseSensitive::Yes );
  2027. StdString::StartsWithMatcher StartsWith( std::string const& str, CaseSensitive::Choice caseSensitivity = CaseSensitive::Yes );
  2028. StdString::RegexMatcher Matches( std::string const& regex, CaseSensitive::Choice caseSensitivity = CaseSensitive::Yes );
  2029. } // namespace Matchers
  2030. } // namespace Catch
  2031. // end catch_matchers_string.h
  2032. // start catch_matchers_vector.h
  2033. #include <algorithm>
  2034. namespace Catch {
  2035. namespace Matchers {
  2036. namespace Vector {
  2037. namespace Detail {
  2038. template <typename InputIterator, typename T>
  2039. size_t count(InputIterator first, InputIterator last, T const& item) {
  2040. size_t cnt = 0;
  2041. for (; first != last; ++first) {
  2042. if (*first == item) {
  2043. ++cnt;
  2044. }
  2045. }
  2046. return cnt;
  2047. }
  2048. template <typename InputIterator, typename T>
  2049. bool contains(InputIterator first, InputIterator last, T const& item) {
  2050. for (; first != last; ++first) {
  2051. if (*first == item) {
  2052. return true;
  2053. }
  2054. }
  2055. return false;
  2056. }
  2057. }
  2058. template<typename T>
  2059. struct ContainsElementMatcher : MatcherBase<std::vector<T>> {
  2060. ContainsElementMatcher(T const &comparator) : m_comparator( comparator) {}
  2061. bool match(std::vector<T> const &v) const override {
  2062. for (auto const& el : v) {
  2063. if (el == m_comparator) {
  2064. return true;
  2065. }
  2066. }
  2067. return false;
  2068. }
  2069. std::string describe() const override {
  2070. return "Contains: " + ::Catch::Detail::stringify( m_comparator );
  2071. }
  2072. T const& m_comparator;
  2073. };
  2074. template<typename T>
  2075. struct ContainsMatcher : MatcherBase<std::vector<T>> {
  2076. ContainsMatcher(std::vector<T> const &comparator) : m_comparator( comparator ) {}
  2077. bool match(std::vector<T> const &v) const override {
  2078. // !TBD: see note in EqualsMatcher
  2079. if (m_comparator.size() > v.size())
  2080. return false;
  2081. for (auto const& comparator : m_comparator) {
  2082. auto present = false;
  2083. for (const auto& el : v) {
  2084. if (el == comparator) {
  2085. present = true;
  2086. break;
  2087. }
  2088. }
  2089. if (!present) {
  2090. return false;
  2091. }
  2092. }
  2093. return true;
  2094. }
  2095. std::string describe() const override {
  2096. return "Contains: " + ::Catch::Detail::stringify( m_comparator );
  2097. }
  2098. std::vector<T> const& m_comparator;
  2099. };
  2100. template<typename T>
  2101. struct EqualsMatcher : MatcherBase<std::vector<T>> {
  2102. EqualsMatcher(std::vector<T> const &comparator) : m_comparator( comparator ) {}
  2103. bool match(std::vector<T> const &v) const override {
  2104. // !TBD: This currently works if all elements can be compared using !=
  2105. // - a more general approach would be via a compare template that defaults
  2106. // to using !=. but could be specialised for, e.g. std::vector<T> etc
  2107. // - then just call that directly
  2108. if (m_comparator.size() != v.size())
  2109. return false;
  2110. for (std::size_t i = 0; i < v.size(); ++i)
  2111. if (m_comparator[i] != v[i])
  2112. return false;
  2113. return true;
  2114. }
  2115. std::string describe() const override {
  2116. return "Equals: " + ::Catch::Detail::stringify( m_comparator );
  2117. }
  2118. std::vector<T> const& m_comparator;
  2119. };
  2120. template<typename T>
  2121. struct UnorderedEqualsMatcher : MatcherBase<std::vector<T>> {
  2122. UnorderedEqualsMatcher(std::vector<T> const& target) : m_target(target) {}
  2123. bool match(std::vector<T> const& vec) const override {
  2124. // Note: This is a reimplementation of std::is_permutation,
  2125. // because I don't want to include <algorithm> inside the common path
  2126. if (m_target.size() != vec.size()) {
  2127. return false;
  2128. }
  2129. auto lfirst = m_target.begin(), llast = m_target.end();
  2130. auto rfirst = vec.begin(), rlast = vec.end();
  2131. // Cut common prefix to optimize checking of permuted parts
  2132. while (lfirst != llast && *lfirst != *rfirst) {
  2133. ++lfirst; ++rfirst;
  2134. }
  2135. if (lfirst == llast) {
  2136. return true;
  2137. }
  2138. for (auto mid = lfirst; mid != llast; ++mid) {
  2139. // Skip already counted items
  2140. if (Detail::contains(lfirst, mid, *mid)) {
  2141. continue;
  2142. }
  2143. size_t num_vec = Detail::count(rfirst, rlast, *mid);
  2144. if (num_vec == 0 || Detail::count(lfirst, llast, *mid) != num_vec) {
  2145. return false;
  2146. }
  2147. }
  2148. return true;
  2149. }
  2150. std::string describe() const override {
  2151. return "UnorderedEquals: " + ::Catch::Detail::stringify(m_target);
  2152. }
  2153. private:
  2154. std::vector<T> const& m_target;
  2155. };
  2156. } // namespace Vector
  2157. // The following functions create the actual matcher objects.
  2158. // This allows the types to be inferred
  2159. template<typename T>
  2160. Vector::ContainsMatcher<T> Contains( std::vector<T> const& comparator ) {
  2161. return Vector::ContainsMatcher<T>( comparator );
  2162. }
  2163. template<typename T>
  2164. Vector::ContainsElementMatcher<T> VectorContains( T const& comparator ) {
  2165. return Vector::ContainsElementMatcher<T>( comparator );
  2166. }
  2167. template<typename T>
  2168. Vector::EqualsMatcher<T> Equals( std::vector<T> const& comparator ) {
  2169. return Vector::EqualsMatcher<T>( comparator );
  2170. }
  2171. template<typename T>
  2172. Vector::UnorderedEqualsMatcher<T> UnorderedEquals(std::vector<T> const& target) {
  2173. return Vector::UnorderedEqualsMatcher<T>(target);
  2174. }
  2175. } // namespace Matchers
  2176. } // namespace Catch
  2177. // end catch_matchers_vector.h
  2178. namespace Catch {
  2179. template<typename ArgT, typename MatcherT>
  2180. class MatchExpr : public ITransientExpression {
  2181. ArgT const& m_arg;
  2182. MatcherT m_matcher;
  2183. StringRef m_matcherString;
  2184. public:
  2185. MatchExpr( ArgT const& arg, MatcherT const& matcher, StringRef matcherString )
  2186. : ITransientExpression{ true, matcher.match( arg ) },
  2187. m_arg( arg ),
  2188. m_matcher( matcher ),
  2189. m_matcherString( matcherString )
  2190. {}
  2191. void streamReconstructedExpression( std::ostream &os ) const override {
  2192. auto matcherAsString = m_matcher.toString();
  2193. os << Catch::Detail::stringify( m_arg ) << ' ';
  2194. if( matcherAsString == Detail::unprintableString )
  2195. os << m_matcherString;
  2196. else
  2197. os << matcherAsString;
  2198. }
  2199. };
  2200. using StringMatcher = Matchers::Impl::MatcherBase<std::string>;
  2201. void handleExceptionMatchExpr( AssertionHandler& handler, StringMatcher const& matcher, StringRef matcherString );
  2202. template<typename ArgT, typename MatcherT>
  2203. auto makeMatchExpr( ArgT const& arg, MatcherT const& matcher, StringRef matcherString ) -> MatchExpr<ArgT, MatcherT> {
  2204. return MatchExpr<ArgT, MatcherT>( arg, matcher, matcherString );
  2205. }
  2206. } // namespace Catch
  2207. ///////////////////////////////////////////////////////////////////////////////
  2208. #define INTERNAL_CHECK_THAT( macroName, matcher, resultDisposition, arg ) \
  2209. do { \
  2210. Catch::AssertionHandler catchAssertionHandler( macroName, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(arg) ", " CATCH_INTERNAL_STRINGIFY(matcher), resultDisposition ); \
  2211. INTERNAL_CATCH_TRY { \
  2212. catchAssertionHandler.handleExpr( Catch::makeMatchExpr( arg, matcher, #matcher ) ); \
  2213. } INTERNAL_CATCH_CATCH( catchAssertionHandler ) \
  2214. INTERNAL_CATCH_REACT( catchAssertionHandler ) \
  2215. } while( false )
  2216. ///////////////////////////////////////////////////////////////////////////////
  2217. #define INTERNAL_CATCH_THROWS_MATCHES( macroName, exceptionType, resultDisposition, matcher, ... ) \
  2218. do { \
  2219. Catch::AssertionHandler catchAssertionHandler( macroName, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(__VA_ARGS__) ", " CATCH_INTERNAL_STRINGIFY(exceptionType) ", " CATCH_INTERNAL_STRINGIFY(matcher), resultDisposition ); \
  2220. if( catchAssertionHandler.allowThrows() ) \
  2221. try { \
  2222. static_cast<void>(__VA_ARGS__ ); \
  2223. catchAssertionHandler.handleUnexpectedExceptionNotThrown(); \
  2224. } \
  2225. catch( exceptionType const& ex ) { \
  2226. catchAssertionHandler.handleExpr( Catch::makeMatchExpr( ex, matcher, #matcher ) ); \
  2227. } \
  2228. catch( ... ) { \
  2229. catchAssertionHandler.handleUnexpectedInflightException(); \
  2230. } \
  2231. else \
  2232. catchAssertionHandler.handleThrowingCallSkipped(); \
  2233. INTERNAL_CATCH_REACT( catchAssertionHandler ) \
  2234. } while( false )
  2235. // end catch_capture_matchers.h
  2236. #endif
  2237. // These files are included here so the single_include script doesn't put them
  2238. // in the conditionally compiled sections
  2239. // start catch_test_case_info.h
  2240. #include <string>
  2241. #include <vector>
  2242. #include <memory>
  2243. #ifdef __clang__
  2244. #pragma clang diagnostic push
  2245. #pragma clang diagnostic ignored "-Wpadded"
  2246. #endif
  2247. namespace Catch {
  2248. struct ITestInvoker;
  2249. struct TestCaseInfo {
  2250. enum SpecialProperties{
  2251. None = 0,
  2252. IsHidden = 1 << 1,
  2253. ShouldFail = 1 << 2,
  2254. MayFail = 1 << 3,
  2255. Throws = 1 << 4,
  2256. NonPortable = 1 << 5,
  2257. Benchmark = 1 << 6
  2258. };
  2259. TestCaseInfo( std::string const& _name,
  2260. std::string const& _className,
  2261. std::string const& _description,
  2262. std::vector<std::string> const& _tags,
  2263. SourceLineInfo const& _lineInfo );
  2264. friend void setTags( TestCaseInfo& testCaseInfo, std::vector<std::string> tags );
  2265. bool isHidden() const;
  2266. bool throws() const;
  2267. bool okToFail() const;
  2268. bool expectedToFail() const;
  2269. std::string tagsAsString() const;
  2270. std::string name;
  2271. std::string className;
  2272. std::string description;
  2273. std::vector<std::string> tags;
  2274. std::vector<std::string> lcaseTags;
  2275. SourceLineInfo lineInfo;
  2276. SpecialProperties properties;
  2277. };
  2278. class TestCase : public TestCaseInfo {
  2279. public:
  2280. TestCase( ITestInvoker* testCase, TestCaseInfo&& info );
  2281. TestCase withName( std::string const& _newName ) const;
  2282. void invoke() const;
  2283. TestCaseInfo const& getTestCaseInfo() const;
  2284. bool operator == ( TestCase const& other ) const;
  2285. bool operator < ( TestCase const& other ) const;
  2286. private:
  2287. std::shared_ptr<ITestInvoker> test;
  2288. };
  2289. TestCase makeTestCase( ITestInvoker* testCase,
  2290. std::string const& className,
  2291. NameAndTags const& nameAndTags,
  2292. SourceLineInfo const& lineInfo );
  2293. }
  2294. #ifdef __clang__
  2295. #pragma clang diagnostic pop
  2296. #endif
  2297. // end catch_test_case_info.h
  2298. // start catch_interfaces_runner.h
  2299. namespace Catch {
  2300. struct IRunner {
  2301. virtual ~IRunner();
  2302. virtual bool aborting() const = 0;
  2303. };
  2304. }
  2305. // end catch_interfaces_runner.h
  2306. #ifdef __OBJC__
  2307. // start catch_objc.hpp
  2308. #import <objc/runtime.h>
  2309. #include <string>
  2310. // NB. Any general catch headers included here must be included
  2311. // in catch.hpp first to make sure they are included by the single
  2312. // header for non obj-usage
  2313. ///////////////////////////////////////////////////////////////////////////////
  2314. // This protocol is really only here for (self) documenting purposes, since
  2315. // all its methods are optional.
  2316. @protocol OcFixture
  2317. @optional
  2318. -(void) setUp;
  2319. -(void) tearDown;
  2320. @end
  2321. namespace Catch {
  2322. class OcMethod : public ITestInvoker {
  2323. public:
  2324. OcMethod( Class cls, SEL sel ) : m_cls( cls ), m_sel( sel ) {}
  2325. virtual void invoke() const {
  2326. id obj = [[m_cls alloc] init];
  2327. performOptionalSelector( obj, @selector(setUp) );
  2328. performOptionalSelector( obj, m_sel );
  2329. performOptionalSelector( obj, @selector(tearDown) );
  2330. arcSafeRelease( obj );
  2331. }
  2332. private:
  2333. virtual ~OcMethod() {}
  2334. Class m_cls;
  2335. SEL m_sel;
  2336. };
  2337. namespace Detail{
  2338. inline std::string getAnnotation( Class cls,
  2339. std::string const& annotationName,
  2340. std::string const& testCaseName ) {
  2341. NSString* selStr = [[NSString alloc] initWithFormat:@"Catch_%s_%s", annotationName.c_str(), testCaseName.c_str()];
  2342. SEL sel = NSSelectorFromString( selStr );
  2343. arcSafeRelease( selStr );
  2344. id value = performOptionalSelector( cls, sel );
  2345. if( value )
  2346. return [(NSString*)value UTF8String];
  2347. return "";
  2348. }
  2349. }
  2350. inline std::size_t registerTestMethods() {
  2351. std::size_t noTestMethods = 0;
  2352. int noClasses = objc_getClassList( nullptr, 0 );
  2353. Class* classes = (CATCH_UNSAFE_UNRETAINED Class *)malloc( sizeof(Class) * noClasses);
  2354. objc_getClassList( classes, noClasses );
  2355. for( int c = 0; c < noClasses; c++ ) {
  2356. Class cls = classes[c];
  2357. {
  2358. u_int count;
  2359. Method* methods = class_copyMethodList( cls, &count );
  2360. for( u_int m = 0; m < count ; m++ ) {
  2361. SEL selector = method_getName(methods[m]);
  2362. std::string methodName = sel_getName(selector);
  2363. if( startsWith( methodName, "Catch_TestCase_" ) ) {
  2364. std::string testCaseName = methodName.substr( 15 );
  2365. std::string name = Detail::getAnnotation( cls, "Name", testCaseName );
  2366. std::string desc = Detail::getAnnotation( cls, "Description", testCaseName );
  2367. const char* className = class_getName( cls );
  2368. getMutableRegistryHub().registerTest( makeTestCase( new OcMethod( cls, selector ), className, name.c_str(), desc.c_str(), SourceLineInfo("",0) ) );
  2369. noTestMethods++;
  2370. }
  2371. }
  2372. free(methods);
  2373. }
  2374. }
  2375. return noTestMethods;
  2376. }
  2377. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  2378. namespace Matchers {
  2379. namespace Impl {
  2380. namespace NSStringMatchers {
  2381. struct StringHolder : MatcherBase<NSString*>{
  2382. StringHolder( NSString* substr ) : m_substr( [substr copy] ){}
  2383. StringHolder( StringHolder const& other ) : m_substr( [other.m_substr copy] ){}
  2384. StringHolder() {
  2385. arcSafeRelease( m_substr );
  2386. }
  2387. bool match( NSString* arg ) const override {
  2388. return false;
  2389. }
  2390. NSString* CATCH_ARC_STRONG m_substr;
  2391. };
  2392. struct Equals : StringHolder {
  2393. Equals( NSString* substr ) : StringHolder( substr ){}
  2394. bool match( NSString* str ) const override {
  2395. return (str != nil || m_substr == nil ) &&
  2396. [str isEqualToString:m_substr];
  2397. }
  2398. std::string describe() const override {
  2399. return "equals string: " + Catch::Detail::stringify( m_substr );
  2400. }
  2401. };
  2402. struct Contains : StringHolder {
  2403. Contains( NSString* substr ) : StringHolder( substr ){}
  2404. bool match( NSString* str ) const {
  2405. return (str != nil || m_substr == nil ) &&
  2406. [str rangeOfString:m_substr].location != NSNotFound;
  2407. }
  2408. std::string describe() const override {
  2409. return "contains string: " + Catch::Detail::stringify( m_substr );
  2410. }
  2411. };
  2412. struct StartsWith : StringHolder {
  2413. StartsWith( NSString* substr ) : StringHolder( substr ){}
  2414. bool match( NSString* str ) const override {
  2415. return (str != nil || m_substr == nil ) &&
  2416. [str rangeOfString:m_substr].location == 0;
  2417. }
  2418. std::string describe() const override {
  2419. return "starts with: " + Catch::Detail::stringify( m_substr );
  2420. }
  2421. };
  2422. struct EndsWith : StringHolder {
  2423. EndsWith( NSString* substr ) : StringHolder( substr ){}
  2424. bool match( NSString* str ) const override {
  2425. return (str != nil || m_substr == nil ) &&
  2426. [str rangeOfString:m_substr].location == [str length] - [m_substr length];
  2427. }
  2428. std::string describe() const override {
  2429. return "ends with: " + Catch::Detail::stringify( m_substr );
  2430. }
  2431. };
  2432. } // namespace NSStringMatchers
  2433. } // namespace Impl
  2434. inline Impl::NSStringMatchers::Equals
  2435. Equals( NSString* substr ){ return Impl::NSStringMatchers::Equals( substr ); }
  2436. inline Impl::NSStringMatchers::Contains
  2437. Contains( NSString* substr ){ return Impl::NSStringMatchers::Contains( substr ); }
  2438. inline Impl::NSStringMatchers::StartsWith
  2439. StartsWith( NSString* substr ){ return Impl::NSStringMatchers::StartsWith( substr ); }
  2440. inline Impl::NSStringMatchers::EndsWith
  2441. EndsWith( NSString* substr ){ return Impl::NSStringMatchers::EndsWith( substr ); }
  2442. } // namespace Matchers
  2443. using namespace Matchers;
  2444. #endif // CATCH_CONFIG_DISABLE_MATCHERS
  2445. } // namespace Catch
  2446. ///////////////////////////////////////////////////////////////////////////////
  2447. #define OC_MAKE_UNIQUE_NAME( root, uniqueSuffix ) root##uniqueSuffix
  2448. #define OC_TEST_CASE2( name, desc, uniqueSuffix ) \
  2449. +(NSString*) OC_MAKE_UNIQUE_NAME( Catch_Name_test_, uniqueSuffix ) \
  2450. { \
  2451. return @ name; \
  2452. } \
  2453. +(NSString*) OC_MAKE_UNIQUE_NAME( Catch_Description_test_, uniqueSuffix ) \
  2454. { \
  2455. return @ desc; \
  2456. } \
  2457. -(void) OC_MAKE_UNIQUE_NAME( Catch_TestCase_test_, uniqueSuffix )
  2458. #define OC_TEST_CASE( name, desc ) OC_TEST_CASE2( name, desc, __LINE__ )
  2459. // end catch_objc.hpp
  2460. #endif
  2461. #ifdef CATCH_CONFIG_EXTERNAL_INTERFACES
  2462. // start catch_external_interfaces.h
  2463. // start catch_reporter_bases.hpp
  2464. // start catch_interfaces_reporter.h
  2465. // start catch_config.hpp
  2466. // start catch_test_spec_parser.h
  2467. #ifdef __clang__
  2468. #pragma clang diagnostic push
  2469. #pragma clang diagnostic ignored "-Wpadded"
  2470. #endif
  2471. // start catch_test_spec.h
  2472. #ifdef __clang__
  2473. #pragma clang diagnostic push
  2474. #pragma clang diagnostic ignored "-Wpadded"
  2475. #endif
  2476. // start catch_wildcard_pattern.h
  2477. namespace Catch
  2478. {
  2479. class WildcardPattern {
  2480. enum WildcardPosition {
  2481. NoWildcard = 0,
  2482. WildcardAtStart = 1,
  2483. WildcardAtEnd = 2,
  2484. WildcardAtBothEnds = WildcardAtStart | WildcardAtEnd
  2485. };
  2486. public:
  2487. WildcardPattern( std::string const& pattern, CaseSensitive::Choice caseSensitivity );
  2488. virtual ~WildcardPattern() = default;
  2489. virtual bool matches( std::string const& str ) const;
  2490. private:
  2491. std::string adjustCase( std::string const& str ) const;
  2492. CaseSensitive::Choice m_caseSensitivity;
  2493. WildcardPosition m_wildcard = NoWildcard;
  2494. std::string m_pattern;
  2495. };
  2496. }
  2497. // end catch_wildcard_pattern.h
  2498. #include <string>
  2499. #include <vector>
  2500. #include <memory>
  2501. namespace Catch {
  2502. class TestSpec {
  2503. struct Pattern {
  2504. virtual ~Pattern();
  2505. virtual bool matches( TestCaseInfo const& testCase ) const = 0;
  2506. };
  2507. using PatternPtr = std::shared_ptr<Pattern>;
  2508. class NamePattern : public Pattern {
  2509. public:
  2510. NamePattern( std::string const& name );
  2511. virtual ~NamePattern();
  2512. virtual bool matches( TestCaseInfo const& testCase ) const override;
  2513. private:
  2514. WildcardPattern m_wildcardPattern;
  2515. };
  2516. class TagPattern : public Pattern {
  2517. public:
  2518. TagPattern( std::string const& tag );
  2519. virtual ~TagPattern();
  2520. virtual bool matches( TestCaseInfo const& testCase ) const override;
  2521. private:
  2522. std::string m_tag;
  2523. };
  2524. class ExcludedPattern : public Pattern {
  2525. public:
  2526. ExcludedPattern( PatternPtr const& underlyingPattern );
  2527. virtual ~ExcludedPattern();
  2528. virtual bool matches( TestCaseInfo const& testCase ) const override;
  2529. private:
  2530. PatternPtr m_underlyingPattern;
  2531. };
  2532. struct Filter {
  2533. std::vector<PatternPtr> m_patterns;
  2534. bool matches( TestCaseInfo const& testCase ) const;
  2535. };
  2536. public:
  2537. bool hasFilters() const;
  2538. bool matches( TestCaseInfo const& testCase ) const;
  2539. private:
  2540. std::vector<Filter> m_filters;
  2541. friend class TestSpecParser;
  2542. };
  2543. }
  2544. #ifdef __clang__
  2545. #pragma clang diagnostic pop
  2546. #endif
  2547. // end catch_test_spec.h
  2548. // start catch_interfaces_tag_alias_registry.h
  2549. #include <string>
  2550. namespace Catch {
  2551. struct TagAlias;
  2552. struct ITagAliasRegistry {
  2553. virtual ~ITagAliasRegistry();
  2554. // Nullptr if not present
  2555. virtual TagAlias const* find( std::string const& alias ) const = 0;
  2556. virtual std::string expandAliases( std::string const& unexpandedTestSpec ) const = 0;
  2557. static ITagAliasRegistry const& get();
  2558. };
  2559. } // end namespace Catch
  2560. // end catch_interfaces_tag_alias_registry.h
  2561. namespace Catch {
  2562. class TestSpecParser {
  2563. enum Mode{ None, Name, QuotedName, Tag, EscapedName };
  2564. Mode m_mode = None;
  2565. bool m_exclusion = false;
  2566. std::size_t m_start = std::string::npos, m_pos = 0;
  2567. std::string m_arg;
  2568. std::vector<std::size_t> m_escapeChars;
  2569. TestSpec::Filter m_currentFilter;
  2570. TestSpec m_testSpec;
  2571. ITagAliasRegistry const* m_tagAliases = nullptr;
  2572. public:
  2573. TestSpecParser( ITagAliasRegistry const& tagAliases );
  2574. TestSpecParser& parse( std::string const& arg );
  2575. TestSpec testSpec();
  2576. private:
  2577. void visitChar( char c );
  2578. void startNewMode( Mode mode, std::size_t start );
  2579. void escape();
  2580. std::string subString() const;
  2581. template<typename T>
  2582. void addPattern() {
  2583. std::string token = subString();
  2584. for( std::size_t i = 0; i < m_escapeChars.size(); ++i )
  2585. token = token.substr( 0, m_escapeChars[i]-m_start-i ) + token.substr( m_escapeChars[i]-m_start-i+1 );
  2586. m_escapeChars.clear();
  2587. if( startsWith( token, "exclude:" ) ) {
  2588. m_exclusion = true;
  2589. token = token.substr( 8 );
  2590. }
  2591. if( !token.empty() ) {
  2592. TestSpec::PatternPtr pattern = std::make_shared<T>( token );
  2593. if( m_exclusion )
  2594. pattern = std::make_shared<TestSpec::ExcludedPattern>( pattern );
  2595. m_currentFilter.m_patterns.push_back( pattern );
  2596. }
  2597. m_exclusion = false;
  2598. m_mode = None;
  2599. }
  2600. void addFilter();
  2601. };
  2602. TestSpec parseTestSpec( std::string const& arg );
  2603. } // namespace Catch
  2604. #ifdef __clang__
  2605. #pragma clang diagnostic pop
  2606. #endif
  2607. // end catch_test_spec_parser.h
  2608. // start catch_interfaces_config.h
  2609. #include <iosfwd>
  2610. #include <string>
  2611. #include <vector>
  2612. #include <memory>
  2613. namespace Catch {
  2614. enum class Verbosity {
  2615. Quiet = 0,
  2616. Normal,
  2617. High
  2618. };
  2619. struct WarnAbout { enum What {
  2620. Nothing = 0x00,
  2621. NoAssertions = 0x01,
  2622. NoTests = 0x02
  2623. }; };
  2624. struct ShowDurations { enum OrNot {
  2625. DefaultForReporter,
  2626. Always,
  2627. Never
  2628. }; };
  2629. struct RunTests { enum InWhatOrder {
  2630. InDeclarationOrder,
  2631. InLexicographicalOrder,
  2632. InRandomOrder
  2633. }; };
  2634. struct UseColour { enum YesOrNo {
  2635. Auto,
  2636. Yes,
  2637. No
  2638. }; };
  2639. struct WaitForKeypress { enum When {
  2640. Never,
  2641. BeforeStart = 1,
  2642. BeforeExit = 2,
  2643. BeforeStartAndExit = BeforeStart | BeforeExit
  2644. }; };
  2645. class TestSpec;
  2646. struct IConfig : NonCopyable {
  2647. virtual ~IConfig();
  2648. virtual bool allowThrows() const = 0;
  2649. virtual std::ostream& stream() const = 0;
  2650. virtual std::string name() const = 0;
  2651. virtual bool includeSuccessfulResults() const = 0;
  2652. virtual bool shouldDebugBreak() const = 0;
  2653. virtual bool warnAboutMissingAssertions() const = 0;
  2654. virtual bool warnAboutNoTests() const = 0;
  2655. virtual int abortAfter() const = 0;
  2656. virtual bool showInvisibles() const = 0;
  2657. virtual ShowDurations::OrNot showDurations() const = 0;
  2658. virtual TestSpec const& testSpec() const = 0;
  2659. virtual bool hasTestFilters() const = 0;
  2660. virtual RunTests::InWhatOrder runOrder() const = 0;
  2661. virtual unsigned int rngSeed() const = 0;
  2662. virtual int benchmarkResolutionMultiple() const = 0;
  2663. virtual UseColour::YesOrNo useColour() const = 0;
  2664. virtual std::vector<std::string> const& getSectionsToRun() const = 0;
  2665. virtual Verbosity verbosity() const = 0;
  2666. };
  2667. using IConfigPtr = std::shared_ptr<IConfig const>;
  2668. }
  2669. // end catch_interfaces_config.h
  2670. // Libstdc++ doesn't like incomplete classes for unique_ptr
  2671. #include <memory>
  2672. #include <vector>
  2673. #include <string>
  2674. #ifndef CATCH_CONFIG_CONSOLE_WIDTH
  2675. #define CATCH_CONFIG_CONSOLE_WIDTH 80
  2676. #endif
  2677. namespace Catch {
  2678. struct IStream;
  2679. struct ConfigData {
  2680. bool listTests = false;
  2681. bool listTags = false;
  2682. bool listReporters = false;
  2683. bool listTestNamesOnly = false;
  2684. bool showSuccessfulTests = false;
  2685. bool shouldDebugBreak = false;
  2686. bool noThrow = false;
  2687. bool showHelp = false;
  2688. bool showInvisibles = false;
  2689. bool filenamesAsTags = false;
  2690. bool libIdentify = false;
  2691. int abortAfter = -1;
  2692. unsigned int rngSeed = 0;
  2693. int benchmarkResolutionMultiple = 100;
  2694. Verbosity verbosity = Verbosity::Normal;
  2695. WarnAbout::What warnings = WarnAbout::Nothing;
  2696. ShowDurations::OrNot showDurations = ShowDurations::DefaultForReporter;
  2697. RunTests::InWhatOrder runOrder = RunTests::InDeclarationOrder;
  2698. UseColour::YesOrNo useColour = UseColour::Auto;
  2699. WaitForKeypress::When waitForKeypress = WaitForKeypress::Never;
  2700. std::string outputFilename;
  2701. std::string name;
  2702. std::string processName;
  2703. std::vector<std::string> reporterNames;
  2704. std::vector<std::string> testsOrTags;
  2705. std::vector<std::string> sectionsToRun;
  2706. };
  2707. class Config : public IConfig {
  2708. public:
  2709. Config() = default;
  2710. Config( ConfigData const& data );
  2711. virtual ~Config() = default;
  2712. std::string const& getFilename() const;
  2713. bool listTests() const;
  2714. bool listTestNamesOnly() const;
  2715. bool listTags() const;
  2716. bool listReporters() const;
  2717. std::string getProcessName() const;
  2718. std::vector<std::string> const& getReporterNames() const;
  2719. std::vector<std::string> const& getTestsOrTags() const;
  2720. std::vector<std::string> const& getSectionsToRun() const override;
  2721. virtual TestSpec const& testSpec() const override;
  2722. bool hasTestFilters() const override;
  2723. bool showHelp() const;
  2724. // IConfig interface
  2725. bool allowThrows() const override;
  2726. std::ostream& stream() const override;
  2727. std::string name() const override;
  2728. bool includeSuccessfulResults() const override;
  2729. bool warnAboutMissingAssertions() const override;
  2730. bool warnAboutNoTests() const override;
  2731. ShowDurations::OrNot showDurations() const override;
  2732. RunTests::InWhatOrder runOrder() const override;
  2733. unsigned int rngSeed() const override;
  2734. int benchmarkResolutionMultiple() const override;
  2735. UseColour::YesOrNo useColour() const override;
  2736. bool shouldDebugBreak() const override;
  2737. int abortAfter() const override;
  2738. bool showInvisibles() const override;
  2739. Verbosity verbosity() const override;
  2740. private:
  2741. IStream const* openStream();
  2742. ConfigData m_data;
  2743. std::unique_ptr<IStream const> m_stream;
  2744. TestSpec m_testSpec;
  2745. bool m_hasTestFilters = false;
  2746. };
  2747. } // end namespace Catch
  2748. // end catch_config.hpp
  2749. // start catch_assertionresult.h
  2750. #include <string>
  2751. namespace Catch {
  2752. struct AssertionResultData
  2753. {
  2754. AssertionResultData() = delete;
  2755. AssertionResultData( ResultWas::OfType _resultType, LazyExpression const& _lazyExpression );
  2756. std::string message;
  2757. mutable std::string reconstructedExpression;
  2758. LazyExpression lazyExpression;
  2759. ResultWas::OfType resultType;
  2760. std::string reconstructExpression() const;
  2761. };
  2762. class AssertionResult {
  2763. public:
  2764. AssertionResult() = delete;
  2765. AssertionResult( AssertionInfo const& info, AssertionResultData const& data );
  2766. bool isOk() const;
  2767. bool succeeded() const;
  2768. ResultWas::OfType getResultType() const;
  2769. bool hasExpression() const;
  2770. bool hasMessage() const;
  2771. std::string getExpression() const;
  2772. std::string getExpressionInMacro() const;
  2773. bool hasExpandedExpression() const;
  2774. std::string getExpandedExpression() const;
  2775. std::string getMessage() const;
  2776. SourceLineInfo getSourceInfo() const;
  2777. StringRef getTestMacroName() const;
  2778. //protected:
  2779. AssertionInfo m_info;
  2780. AssertionResultData m_resultData;
  2781. };
  2782. } // end namespace Catch
  2783. // end catch_assertionresult.h
  2784. // start catch_option.hpp
  2785. namespace Catch {
  2786. // An optional type
  2787. template<typename T>
  2788. class Option {
  2789. public:
  2790. Option() : nullableValue( nullptr ) {}
  2791. Option( T const& _value )
  2792. : nullableValue( new( storage ) T( _value ) )
  2793. {}
  2794. Option( Option const& _other )
  2795. : nullableValue( _other ? new( storage ) T( *_other ) : nullptr )
  2796. {}
  2797. ~Option() {
  2798. reset();
  2799. }
  2800. Option& operator= ( Option const& _other ) {
  2801. if( &_other != this ) {
  2802. reset();
  2803. if( _other )
  2804. nullableValue = new( storage ) T( *_other );
  2805. }
  2806. return *this;
  2807. }
  2808. Option& operator = ( T const& _value ) {
  2809. reset();
  2810. nullableValue = new( storage ) T( _value );
  2811. return *this;
  2812. }
  2813. void reset() {
  2814. if( nullableValue )
  2815. nullableValue->~T();
  2816. nullableValue = nullptr;
  2817. }
  2818. T& operator*() { return *nullableValue; }
  2819. T const& operator*() const { return *nullableValue; }
  2820. T* operator->() { return nullableValue; }
  2821. const T* operator->() const { return nullableValue; }
  2822. T valueOr( T const& defaultValue ) const {
  2823. return nullableValue ? *nullableValue : defaultValue;
  2824. }
  2825. bool some() const { return nullableValue != nullptr; }
  2826. bool none() const { return nullableValue == nullptr; }
  2827. bool operator !() const { return nullableValue == nullptr; }
  2828. explicit operator bool() const {
  2829. return some();
  2830. }
  2831. private:
  2832. T *nullableValue;
  2833. alignas(alignof(T)) char storage[sizeof(T)];
  2834. };
  2835. } // end namespace Catch
  2836. // end catch_option.hpp
  2837. #include <string>
  2838. #include <iosfwd>
  2839. #include <map>
  2840. #include <set>
  2841. #include <memory>
  2842. namespace Catch {
  2843. struct ReporterConfig {
  2844. explicit ReporterConfig( IConfigPtr const& _fullConfig );
  2845. ReporterConfig( IConfigPtr const& _fullConfig, std::ostream& _stream );
  2846. std::ostream& stream() const;
  2847. IConfigPtr fullConfig() const;
  2848. private:
  2849. std::ostream* m_stream;
  2850. IConfigPtr m_fullConfig;
  2851. };
  2852. struct ReporterPreferences {
  2853. bool shouldRedirectStdOut = false;
  2854. };
  2855. template<typename T>
  2856. struct LazyStat : Option<T> {
  2857. LazyStat& operator=( T const& _value ) {
  2858. Option<T>::operator=( _value );
  2859. used = false;
  2860. return *this;
  2861. }
  2862. void reset() {
  2863. Option<T>::reset();
  2864. used = false;
  2865. }
  2866. bool used = false;
  2867. };
  2868. struct TestRunInfo {
  2869. TestRunInfo( std::string const& _name );
  2870. std::string name;
  2871. };
  2872. struct GroupInfo {
  2873. GroupInfo( std::string const& _name,
  2874. std::size_t _groupIndex,
  2875. std::size_t _groupsCount );
  2876. std::string name;
  2877. std::size_t groupIndex;
  2878. std::size_t groupsCounts;
  2879. };
  2880. struct AssertionStats {
  2881. AssertionStats( AssertionResult const& _assertionResult,
  2882. std::vector<MessageInfo> const& _infoMessages,
  2883. Totals const& _totals );
  2884. AssertionStats( AssertionStats const& ) = default;
  2885. AssertionStats( AssertionStats && ) = default;
  2886. AssertionStats& operator = ( AssertionStats const& ) = default;
  2887. AssertionStats& operator = ( AssertionStats && ) = default;
  2888. virtual ~AssertionStats();
  2889. AssertionResult assertionResult;
  2890. std::vector<MessageInfo> infoMessages;
  2891. Totals totals;
  2892. };
  2893. struct SectionStats {
  2894. SectionStats( SectionInfo const& _sectionInfo,
  2895. Counts const& _assertions,
  2896. double _durationInSeconds,
  2897. bool _missingAssertions );
  2898. SectionStats( SectionStats const& ) = default;
  2899. SectionStats( SectionStats && ) = default;
  2900. SectionStats& operator = ( SectionStats const& ) = default;
  2901. SectionStats& operator = ( SectionStats && ) = default;
  2902. virtual ~SectionStats();
  2903. SectionInfo sectionInfo;
  2904. Counts assertions;
  2905. double durationInSeconds;
  2906. bool missingAssertions;
  2907. };
  2908. struct TestCaseStats {
  2909. TestCaseStats( TestCaseInfo const& _testInfo,
  2910. Totals const& _totals,
  2911. std::string const& _stdOut,
  2912. std::string const& _stdErr,
  2913. bool _aborting );
  2914. TestCaseStats( TestCaseStats const& ) = default;
  2915. TestCaseStats( TestCaseStats && ) = default;
  2916. TestCaseStats& operator = ( TestCaseStats const& ) = default;
  2917. TestCaseStats& operator = ( TestCaseStats && ) = default;
  2918. virtual ~TestCaseStats();
  2919. TestCaseInfo testInfo;
  2920. Totals totals;
  2921. std::string stdOut;
  2922. std::string stdErr;
  2923. bool aborting;
  2924. };
  2925. struct TestGroupStats {
  2926. TestGroupStats( GroupInfo const& _groupInfo,
  2927. Totals const& _totals,
  2928. bool _aborting );
  2929. TestGroupStats( GroupInfo const& _groupInfo );
  2930. TestGroupStats( TestGroupStats const& ) = default;
  2931. TestGroupStats( TestGroupStats && ) = default;
  2932. TestGroupStats& operator = ( TestGroupStats const& ) = default;
  2933. TestGroupStats& operator = ( TestGroupStats && ) = default;
  2934. virtual ~TestGroupStats();
  2935. GroupInfo groupInfo;
  2936. Totals totals;
  2937. bool aborting;
  2938. };
  2939. struct TestRunStats {
  2940. TestRunStats( TestRunInfo const& _runInfo,
  2941. Totals const& _totals,
  2942. bool _aborting );
  2943. TestRunStats( TestRunStats const& ) = default;
  2944. TestRunStats( TestRunStats && ) = default;
  2945. TestRunStats& operator = ( TestRunStats const& ) = default;
  2946. TestRunStats& operator = ( TestRunStats && ) = default;
  2947. virtual ~TestRunStats();
  2948. TestRunInfo runInfo;
  2949. Totals totals;
  2950. bool aborting;
  2951. };
  2952. struct BenchmarkInfo {
  2953. std::string name;
  2954. };
  2955. struct BenchmarkStats {
  2956. BenchmarkInfo info;
  2957. std::size_t iterations;
  2958. uint64_t elapsedTimeInNanoseconds;
  2959. };
  2960. struct IStreamingReporter {
  2961. virtual ~IStreamingReporter() = default;
  2962. // Implementing class must also provide the following static methods:
  2963. // static std::string getDescription();
  2964. // static std::set<Verbosity> getSupportedVerbosities()
  2965. virtual ReporterPreferences getPreferences() const = 0;
  2966. virtual void noMatchingTestCases( std::string const& spec ) = 0;
  2967. virtual void testRunStarting( TestRunInfo const& testRunInfo ) = 0;
  2968. virtual void testGroupStarting( GroupInfo const& groupInfo ) = 0;
  2969. virtual void testCaseStarting( TestCaseInfo const& testInfo ) = 0;
  2970. virtual void sectionStarting( SectionInfo const& sectionInfo ) = 0;
  2971. // *** experimental ***
  2972. virtual void benchmarkStarting( BenchmarkInfo const& ) {}
  2973. virtual void assertionStarting( AssertionInfo const& assertionInfo ) = 0;
  2974. // The return value indicates if the messages buffer should be cleared:
  2975. virtual bool assertionEnded( AssertionStats const& assertionStats ) = 0;
  2976. // *** experimental ***
  2977. virtual void benchmarkEnded( BenchmarkStats const& ) {}
  2978. virtual void sectionEnded( SectionStats const& sectionStats ) = 0;
  2979. virtual void testCaseEnded( TestCaseStats const& testCaseStats ) = 0;
  2980. virtual void testGroupEnded( TestGroupStats const& testGroupStats ) = 0;
  2981. virtual void testRunEnded( TestRunStats const& testRunStats ) = 0;
  2982. virtual void skipTest( TestCaseInfo const& testInfo ) = 0;
  2983. // Default empty implementation provided
  2984. virtual void fatalErrorEncountered( StringRef name );
  2985. virtual bool isMulti() const;
  2986. };
  2987. using IStreamingReporterPtr = std::unique_ptr<IStreamingReporter>;
  2988. struct IReporterFactory {
  2989. virtual ~IReporterFactory();
  2990. virtual IStreamingReporterPtr create( ReporterConfig const& config ) const = 0;
  2991. virtual std::string getDescription() const = 0;
  2992. };
  2993. using IReporterFactoryPtr = std::shared_ptr<IReporterFactory>;
  2994. struct IReporterRegistry {
  2995. using FactoryMap = std::map<std::string, IReporterFactoryPtr>;
  2996. using Listeners = std::vector<IReporterFactoryPtr>;
  2997. virtual ~IReporterRegistry();
  2998. virtual IStreamingReporterPtr create( std::string const& name, IConfigPtr const& config ) const = 0;
  2999. virtual FactoryMap const& getFactories() const = 0;
  3000. virtual Listeners const& getListeners() const = 0;
  3001. };
  3002. void addReporter( IStreamingReporterPtr& existingReporter, IStreamingReporterPtr&& additionalReporter );
  3003. } // end namespace Catch
  3004. // end catch_interfaces_reporter.h
  3005. #include <algorithm>
  3006. #include <cstring>
  3007. #include <cfloat>
  3008. #include <cstdio>
  3009. #include <assert.h>
  3010. #include <memory>
  3011. #include <ostream>
  3012. namespace Catch {
  3013. void prepareExpandedExpression(AssertionResult& result);
  3014. // Returns double formatted as %.3f (format expected on output)
  3015. std::string getFormattedDuration( double duration );
  3016. template<typename DerivedT>
  3017. struct StreamingReporterBase : IStreamingReporter {
  3018. StreamingReporterBase( ReporterConfig const& _config )
  3019. : m_config( _config.fullConfig() ),
  3020. stream( _config.stream() )
  3021. {
  3022. m_reporterPrefs.shouldRedirectStdOut = false;
  3023. if( !DerivedT::getSupportedVerbosities().count( m_config->verbosity() ) )
  3024. throw std::domain_error( "Verbosity level not supported by this reporter" );
  3025. }
  3026. ReporterPreferences getPreferences() const override {
  3027. return m_reporterPrefs;
  3028. }
  3029. static std::set<Verbosity> getSupportedVerbosities() {
  3030. return { Verbosity::Normal };
  3031. }
  3032. ~StreamingReporterBase() override = default;
  3033. void noMatchingTestCases(std::string const&) override {}
  3034. void testRunStarting(TestRunInfo const& _testRunInfo) override {
  3035. currentTestRunInfo = _testRunInfo;
  3036. }
  3037. void testGroupStarting(GroupInfo const& _groupInfo) override {
  3038. currentGroupInfo = _groupInfo;
  3039. }
  3040. void testCaseStarting(TestCaseInfo const& _testInfo) override {
  3041. currentTestCaseInfo = _testInfo;
  3042. }
  3043. void sectionStarting(SectionInfo const& _sectionInfo) override {
  3044. m_sectionStack.push_back(_sectionInfo);
  3045. }
  3046. void sectionEnded(SectionStats const& /* _sectionStats */) override {
  3047. m_sectionStack.pop_back();
  3048. }
  3049. void testCaseEnded(TestCaseStats const& /* _testCaseStats */) override {
  3050. currentTestCaseInfo.reset();
  3051. }
  3052. void testGroupEnded(TestGroupStats const& /* _testGroupStats */) override {
  3053. currentGroupInfo.reset();
  3054. }
  3055. void testRunEnded(TestRunStats const& /* _testRunStats */) override {
  3056. currentTestCaseInfo.reset();
  3057. currentGroupInfo.reset();
  3058. currentTestRunInfo.reset();
  3059. }
  3060. void skipTest(TestCaseInfo const&) override {
  3061. // Don't do anything with this by default.
  3062. // It can optionally be overridden in the derived class.
  3063. }
  3064. IConfigPtr m_config;
  3065. std::ostream& stream;
  3066. LazyStat<TestRunInfo> currentTestRunInfo;
  3067. LazyStat<GroupInfo> currentGroupInfo;
  3068. LazyStat<TestCaseInfo> currentTestCaseInfo;
  3069. std::vector<SectionInfo> m_sectionStack;
  3070. ReporterPreferences m_reporterPrefs;
  3071. };
  3072. template<typename DerivedT>
  3073. struct CumulativeReporterBase : IStreamingReporter {
  3074. template<typename T, typename ChildNodeT>
  3075. struct Node {
  3076. explicit Node( T const& _value ) : value( _value ) {}
  3077. virtual ~Node() {}
  3078. using ChildNodes = std::vector<std::shared_ptr<ChildNodeT>>;
  3079. T value;
  3080. ChildNodes children;
  3081. };
  3082. struct SectionNode {
  3083. explicit SectionNode(SectionStats const& _stats) : stats(_stats) {}
  3084. virtual ~SectionNode() = default;
  3085. bool operator == (SectionNode const& other) const {
  3086. return stats.sectionInfo.lineInfo == other.stats.sectionInfo.lineInfo;
  3087. }
  3088. bool operator == (std::shared_ptr<SectionNode> const& other) const {
  3089. return operator==(*other);
  3090. }
  3091. SectionStats stats;
  3092. using ChildSections = std::vector<std::shared_ptr<SectionNode>>;
  3093. using Assertions = std::vector<AssertionStats>;
  3094. ChildSections childSections;
  3095. Assertions assertions;
  3096. std::string stdOut;
  3097. std::string stdErr;
  3098. };
  3099. struct BySectionInfo {
  3100. BySectionInfo( SectionInfo const& other ) : m_other( other ) {}
  3101. BySectionInfo( BySectionInfo const& other ) : m_other( other.m_other ) {}
  3102. bool operator() (std::shared_ptr<SectionNode> const& node) const {
  3103. return ((node->stats.sectionInfo.name == m_other.name) &&
  3104. (node->stats.sectionInfo.lineInfo == m_other.lineInfo));
  3105. }
  3106. void operator=(BySectionInfo const&) = delete;
  3107. private:
  3108. SectionInfo const& m_other;
  3109. };
  3110. using TestCaseNode = Node<TestCaseStats, SectionNode>;
  3111. using TestGroupNode = Node<TestGroupStats, TestCaseNode>;
  3112. using TestRunNode = Node<TestRunStats, TestGroupNode>;
  3113. CumulativeReporterBase( ReporterConfig const& _config )
  3114. : m_config( _config.fullConfig() ),
  3115. stream( _config.stream() )
  3116. {
  3117. m_reporterPrefs.shouldRedirectStdOut = false;
  3118. if( !DerivedT::getSupportedVerbosities().count( m_config->verbosity() ) )
  3119. throw std::domain_error( "Verbosity level not supported by this reporter" );
  3120. }
  3121. ~CumulativeReporterBase() override = default;
  3122. ReporterPreferences getPreferences() const override {
  3123. return m_reporterPrefs;
  3124. }
  3125. static std::set<Verbosity> getSupportedVerbosities() {
  3126. return { Verbosity::Normal };
  3127. }
  3128. void testRunStarting( TestRunInfo const& ) override {}
  3129. void testGroupStarting( GroupInfo const& ) override {}
  3130. void testCaseStarting( TestCaseInfo const& ) override {}
  3131. void sectionStarting( SectionInfo const& sectionInfo ) override {
  3132. SectionStats incompleteStats( sectionInfo, Counts(), 0, false );
  3133. std::shared_ptr<SectionNode> node;
  3134. if( m_sectionStack.empty() ) {
  3135. if( !m_rootSection )
  3136. m_rootSection = std::make_shared<SectionNode>( incompleteStats );
  3137. node = m_rootSection;
  3138. }
  3139. else {
  3140. SectionNode& parentNode = *m_sectionStack.back();
  3141. auto it =
  3142. std::find_if( parentNode.childSections.begin(),
  3143. parentNode.childSections.end(),
  3144. BySectionInfo( sectionInfo ) );
  3145. if( it == parentNode.childSections.end() ) {
  3146. node = std::make_shared<SectionNode>( incompleteStats );
  3147. parentNode.childSections.push_back( node );
  3148. }
  3149. else
  3150. node = *it;
  3151. }
  3152. m_sectionStack.push_back( node );
  3153. m_deepestSection = std::move(node);
  3154. }
  3155. void assertionStarting(AssertionInfo const&) override {}
  3156. bool assertionEnded(AssertionStats const& assertionStats) override {
  3157. assert(!m_sectionStack.empty());
  3158. // AssertionResult holds a pointer to a temporary DecomposedExpression,
  3159. // which getExpandedExpression() calls to build the expression string.
  3160. // Our section stack copy of the assertionResult will likely outlive the
  3161. // temporary, so it must be expanded or discarded now to avoid calling
  3162. // a destroyed object later.
  3163. prepareExpandedExpression(const_cast<AssertionResult&>( assertionStats.assertionResult ) );
  3164. SectionNode& sectionNode = *m_sectionStack.back();
  3165. sectionNode.assertions.push_back(assertionStats);
  3166. return true;
  3167. }
  3168. void sectionEnded(SectionStats const& sectionStats) override {
  3169. assert(!m_sectionStack.empty());
  3170. SectionNode& node = *m_sectionStack.back();
  3171. node.stats = sectionStats;
  3172. m_sectionStack.pop_back();
  3173. }
  3174. void testCaseEnded(TestCaseStats const& testCaseStats) override {
  3175. auto node = std::make_shared<TestCaseNode>(testCaseStats);
  3176. assert(m_sectionStack.size() == 0);
  3177. node->children.push_back(m_rootSection);
  3178. m_testCases.push_back(node);
  3179. m_rootSection.reset();
  3180. assert(m_deepestSection);
  3181. m_deepestSection->stdOut = testCaseStats.stdOut;
  3182. m_deepestSection->stdErr = testCaseStats.stdErr;
  3183. }
  3184. void testGroupEnded(TestGroupStats const& testGroupStats) override {
  3185. auto node = std::make_shared<TestGroupNode>(testGroupStats);
  3186. node->children.swap(m_testCases);
  3187. m_testGroups.push_back(node);
  3188. }
  3189. void testRunEnded(TestRunStats const& testRunStats) override {
  3190. auto node = std::make_shared<TestRunNode>(testRunStats);
  3191. node->children.swap(m_testGroups);
  3192. m_testRuns.push_back(node);
  3193. testRunEndedCumulative();
  3194. }
  3195. virtual void testRunEndedCumulative() = 0;
  3196. void skipTest(TestCaseInfo const&) override {}
  3197. IConfigPtr m_config;
  3198. std::ostream& stream;
  3199. std::vector<AssertionStats> m_assertions;
  3200. std::vector<std::vector<std::shared_ptr<SectionNode>>> m_sections;
  3201. std::vector<std::shared_ptr<TestCaseNode>> m_testCases;
  3202. std::vector<std::shared_ptr<TestGroupNode>> m_testGroups;
  3203. std::vector<std::shared_ptr<TestRunNode>> m_testRuns;
  3204. std::shared_ptr<SectionNode> m_rootSection;
  3205. std::shared_ptr<SectionNode> m_deepestSection;
  3206. std::vector<std::shared_ptr<SectionNode>> m_sectionStack;
  3207. ReporterPreferences m_reporterPrefs;
  3208. };
  3209. template<char C>
  3210. char const* getLineOfChars() {
  3211. static char line[CATCH_CONFIG_CONSOLE_WIDTH] = {0};
  3212. if( !*line ) {
  3213. std::memset( line, C, CATCH_CONFIG_CONSOLE_WIDTH-1 );
  3214. line[CATCH_CONFIG_CONSOLE_WIDTH-1] = 0;
  3215. }
  3216. return line;
  3217. }
  3218. struct TestEventListenerBase : StreamingReporterBase<TestEventListenerBase> {
  3219. TestEventListenerBase( ReporterConfig const& _config );
  3220. void assertionStarting(AssertionInfo const&) override;
  3221. bool assertionEnded(AssertionStats const&) override;
  3222. };
  3223. } // end namespace Catch
  3224. // end catch_reporter_bases.hpp
  3225. // start catch_console_colour.h
  3226. namespace Catch {
  3227. struct Colour {
  3228. enum Code {
  3229. None = 0,
  3230. White,
  3231. Red,
  3232. Green,
  3233. Blue,
  3234. Cyan,
  3235. Yellow,
  3236. Grey,
  3237. Bright = 0x10,
  3238. BrightRed = Bright | Red,
  3239. BrightGreen = Bright | Green,
  3240. LightGrey = Bright | Grey,
  3241. BrightWhite = Bright | White,
  3242. BrightYellow = Bright | Yellow,
  3243. // By intention
  3244. FileName = LightGrey,
  3245. Warning = BrightYellow,
  3246. ResultError = BrightRed,
  3247. ResultSuccess = BrightGreen,
  3248. ResultExpectedFailure = Warning,
  3249. Error = BrightRed,
  3250. Success = Green,
  3251. OriginalExpression = Cyan,
  3252. ReconstructedExpression = BrightYellow,
  3253. SecondaryText = LightGrey,
  3254. Headers = White
  3255. };
  3256. // Use constructed object for RAII guard
  3257. Colour( Code _colourCode );
  3258. Colour( Colour&& other ) noexcept;
  3259. Colour& operator=( Colour&& other ) noexcept;
  3260. ~Colour();
  3261. // Use static method for one-shot changes
  3262. static void use( Code _colourCode );
  3263. private:
  3264. bool m_moved = false;
  3265. };
  3266. std::ostream& operator << ( std::ostream& os, Colour const& );
  3267. } // end namespace Catch
  3268. // end catch_console_colour.h
  3269. // start catch_reporter_registrars.hpp
  3270. namespace Catch {
  3271. template<typename T>
  3272. class ReporterRegistrar {
  3273. class ReporterFactory : public IReporterFactory {
  3274. virtual IStreamingReporterPtr create( ReporterConfig const& config ) const override {
  3275. return std::unique_ptr<T>( new T( config ) );
  3276. }
  3277. virtual std::string getDescription() const override {
  3278. return T::getDescription();
  3279. }
  3280. };
  3281. public:
  3282. explicit ReporterRegistrar( std::string const& name ) {
  3283. getMutableRegistryHub().registerReporter( name, std::make_shared<ReporterFactory>() );
  3284. }
  3285. };
  3286. template<typename T>
  3287. class ListenerRegistrar {
  3288. class ListenerFactory : public IReporterFactory {
  3289. virtual IStreamingReporterPtr create( ReporterConfig const& config ) const override {
  3290. return std::unique_ptr<T>( new T( config ) );
  3291. }
  3292. virtual std::string getDescription() const override {
  3293. return std::string();
  3294. }
  3295. };
  3296. public:
  3297. ListenerRegistrar() {
  3298. getMutableRegistryHub().registerListener( std::make_shared<ListenerFactory>() );
  3299. }
  3300. };
  3301. }
  3302. #if !defined(CATCH_CONFIG_DISABLE)
  3303. #define CATCH_REGISTER_REPORTER( name, reporterType ) \
  3304. CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
  3305. namespace{ Catch::ReporterRegistrar<reporterType> catch_internal_RegistrarFor##reporterType( name ); } \
  3306. CATCH_INTERNAL_UNSUPPRESS_GLOBALS_WARNINGS
  3307. #define CATCH_REGISTER_LISTENER( listenerType ) \
  3308. CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
  3309. namespace{ Catch::ListenerRegistrar<listenerType> catch_internal_RegistrarFor##listenerType; } \
  3310. CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS
  3311. #else // CATCH_CONFIG_DISABLE
  3312. #define CATCH_REGISTER_REPORTER(name, reporterType)
  3313. #define CATCH_REGISTER_LISTENER(listenerType)
  3314. #endif // CATCH_CONFIG_DISABLE
  3315. // end catch_reporter_registrars.hpp
  3316. // Allow users to base their work off existing reporters
  3317. // start catch_reporter_compact.h
  3318. namespace Catch {
  3319. struct CompactReporter : StreamingReporterBase<CompactReporter> {
  3320. using StreamingReporterBase::StreamingReporterBase;
  3321. ~CompactReporter() override;
  3322. static std::string getDescription();
  3323. ReporterPreferences getPreferences() const override;
  3324. void noMatchingTestCases(std::string const& spec) override;
  3325. void assertionStarting(AssertionInfo const&) override;
  3326. bool assertionEnded(AssertionStats const& _assertionStats) override;
  3327. void sectionEnded(SectionStats const& _sectionStats) override;
  3328. void testRunEnded(TestRunStats const& _testRunStats) override;
  3329. };
  3330. } // end namespace Catch
  3331. // end catch_reporter_compact.h
  3332. // start catch_reporter_console.h
  3333. #if defined(_MSC_VER)
  3334. #pragma warning(push)
  3335. #pragma warning(disable:4061) // Not all labels are EXPLICITLY handled in switch
  3336. // Note that 4062 (not all labels are handled
  3337. // and default is missing) is enabled
  3338. #endif
  3339. namespace Catch {
  3340. // Fwd decls
  3341. struct SummaryColumn;
  3342. class TablePrinter;
  3343. struct ConsoleReporter : StreamingReporterBase<ConsoleReporter> {
  3344. std::unique_ptr<TablePrinter> m_tablePrinter;
  3345. ConsoleReporter(ReporterConfig const& config);
  3346. ~ConsoleReporter() override;
  3347. static std::string getDescription();
  3348. void noMatchingTestCases(std::string const& spec) override;
  3349. void assertionStarting(AssertionInfo const&) override;
  3350. bool assertionEnded(AssertionStats const& _assertionStats) override;
  3351. void sectionStarting(SectionInfo const& _sectionInfo) override;
  3352. void sectionEnded(SectionStats const& _sectionStats) override;
  3353. void benchmarkStarting(BenchmarkInfo const& info) override;
  3354. void benchmarkEnded(BenchmarkStats const& stats) override;
  3355. void testCaseEnded(TestCaseStats const& _testCaseStats) override;
  3356. void testGroupEnded(TestGroupStats const& _testGroupStats) override;
  3357. void testRunEnded(TestRunStats const& _testRunStats) override;
  3358. private:
  3359. void lazyPrint();
  3360. void lazyPrintWithoutClosingBenchmarkTable();
  3361. void lazyPrintRunInfo();
  3362. void lazyPrintGroupInfo();
  3363. void printTestCaseAndSectionHeader();
  3364. void printClosedHeader(std::string const& _name);
  3365. void printOpenHeader(std::string const& _name);
  3366. // if string has a : in first line will set indent to follow it on
  3367. // subsequent lines
  3368. void printHeaderString(std::string const& _string, std::size_t indent = 0);
  3369. void printTotals(Totals const& totals);
  3370. void printSummaryRow(std::string const& label, std::vector<SummaryColumn> const& cols, std::size_t row);
  3371. void printTotalsDivider(Totals const& totals);
  3372. void printSummaryDivider();
  3373. private:
  3374. bool m_headerPrinted = false;
  3375. };
  3376. } // end namespace Catch
  3377. #if defined(_MSC_VER)
  3378. #pragma warning(pop)
  3379. #endif
  3380. // end catch_reporter_console.h
  3381. // start catch_reporter_junit.h
  3382. // start catch_xmlwriter.h
  3383. #include <vector>
  3384. namespace Catch {
  3385. class XmlEncode {
  3386. public:
  3387. enum ForWhat { ForTextNodes, ForAttributes };
  3388. XmlEncode( std::string const& str, ForWhat forWhat = ForTextNodes );
  3389. void encodeTo( std::ostream& os ) const;
  3390. friend std::ostream& operator << ( std::ostream& os, XmlEncode const& xmlEncode );
  3391. private:
  3392. std::string m_str;
  3393. ForWhat m_forWhat;
  3394. };
  3395. class XmlWriter {
  3396. public:
  3397. class ScopedElement {
  3398. public:
  3399. ScopedElement( XmlWriter* writer );
  3400. ScopedElement( ScopedElement&& other ) noexcept;
  3401. ScopedElement& operator=( ScopedElement&& other ) noexcept;
  3402. ~ScopedElement();
  3403. ScopedElement& writeText( std::string const& text, bool indent = true );
  3404. template<typename T>
  3405. ScopedElement& writeAttribute( std::string const& name, T const& attribute ) {
  3406. m_writer->writeAttribute( name, attribute );
  3407. return *this;
  3408. }
  3409. private:
  3410. mutable XmlWriter* m_writer = nullptr;
  3411. };
  3412. XmlWriter( std::ostream& os = Catch::cout() );
  3413. ~XmlWriter();
  3414. XmlWriter( XmlWriter const& ) = delete;
  3415. XmlWriter& operator=( XmlWriter const& ) = delete;
  3416. XmlWriter& startElement( std::string const& name );
  3417. ScopedElement scopedElement( std::string const& name );
  3418. XmlWriter& endElement();
  3419. XmlWriter& writeAttribute( std::string const& name, std::string const& attribute );
  3420. XmlWriter& writeAttribute( std::string const& name, bool attribute );
  3421. template<typename T>
  3422. XmlWriter& writeAttribute( std::string const& name, T const& attribute ) {
  3423. ReusableStringStream rss;
  3424. rss << attribute;
  3425. return writeAttribute( name, rss.str() );
  3426. }
  3427. XmlWriter& writeText( std::string const& text, bool indent = true );
  3428. XmlWriter& writeComment( std::string const& text );
  3429. void writeStylesheetRef( std::string const& url );
  3430. XmlWriter& writeBlankLine();
  3431. void ensureTagClosed();
  3432. private:
  3433. void writeDeclaration();
  3434. void newlineIfNecessary();
  3435. bool m_tagIsOpen = false;
  3436. bool m_needsNewline = false;
  3437. std::vector<std::string> m_tags;
  3438. std::string m_indent;
  3439. std::ostream& m_os;
  3440. };
  3441. }
  3442. // end catch_xmlwriter.h
  3443. namespace Catch {
  3444. class JunitReporter : public CumulativeReporterBase<JunitReporter> {
  3445. public:
  3446. JunitReporter(ReporterConfig const& _config);
  3447. ~JunitReporter() override;
  3448. static std::string getDescription();
  3449. void noMatchingTestCases(std::string const& /*spec*/) override;
  3450. void testRunStarting(TestRunInfo const& runInfo) override;
  3451. void testGroupStarting(GroupInfo const& groupInfo) override;
  3452. void testCaseStarting(TestCaseInfo const& testCaseInfo) override;
  3453. bool assertionEnded(AssertionStats const& assertionStats) override;
  3454. void testCaseEnded(TestCaseStats const& testCaseStats) override;
  3455. void testGroupEnded(TestGroupStats const& testGroupStats) override;
  3456. void testRunEndedCumulative() override;
  3457. void writeGroup(TestGroupNode const& groupNode, double suiteTime);
  3458. void writeTestCase(TestCaseNode const& testCaseNode);
  3459. void writeSection(std::string const& className,
  3460. std::string const& rootName,
  3461. SectionNode const& sectionNode);
  3462. void writeAssertions(SectionNode const& sectionNode);
  3463. void writeAssertion(AssertionStats const& stats);
  3464. XmlWriter xml;
  3465. Timer suiteTimer;
  3466. std::string stdOutForSuite;
  3467. std::string stdErrForSuite;
  3468. unsigned int unexpectedExceptions = 0;
  3469. bool m_okToFail = false;
  3470. };
  3471. } // end namespace Catch
  3472. // end catch_reporter_junit.h
  3473. // start catch_reporter_xml.h
  3474. namespace Catch {
  3475. class XmlReporter : public StreamingReporterBase<XmlReporter> {
  3476. public:
  3477. XmlReporter(ReporterConfig const& _config);
  3478. ~XmlReporter() override;
  3479. static std::string getDescription();
  3480. virtual std::string getStylesheetRef() const;
  3481. void writeSourceInfo(SourceLineInfo const& sourceInfo);
  3482. public: // StreamingReporterBase
  3483. void noMatchingTestCases(std::string const& s) override;
  3484. void testRunStarting(TestRunInfo const& testInfo) override;
  3485. void testGroupStarting(GroupInfo const& groupInfo) override;
  3486. void testCaseStarting(TestCaseInfo const& testInfo) override;
  3487. void sectionStarting(SectionInfo const& sectionInfo) override;
  3488. void assertionStarting(AssertionInfo const&) override;
  3489. bool assertionEnded(AssertionStats const& assertionStats) override;
  3490. void sectionEnded(SectionStats const& sectionStats) override;
  3491. void testCaseEnded(TestCaseStats const& testCaseStats) override;
  3492. void testGroupEnded(TestGroupStats const& testGroupStats) override;
  3493. void testRunEnded(TestRunStats const& testRunStats) override;
  3494. private:
  3495. Timer m_testCaseTimer;
  3496. XmlWriter m_xml;
  3497. int m_sectionDepth = 0;
  3498. };
  3499. } // end namespace Catch
  3500. // end catch_reporter_xml.h
  3501. // end catch_external_interfaces.h
  3502. #endif
  3503. #endif // ! CATCH_CONFIG_IMPL_ONLY
  3504. #ifdef CATCH_IMPL
  3505. // start catch_impl.hpp
  3506. #ifdef __clang__
  3507. #pragma clang diagnostic push
  3508. #pragma clang diagnostic ignored "-Wweak-vtables"
  3509. #endif
  3510. // Keep these here for external reporters
  3511. // start catch_test_case_tracker.h
  3512. #include <string>
  3513. #include <vector>
  3514. #include <memory>
  3515. namespace Catch {
  3516. namespace TestCaseTracking {
  3517. struct NameAndLocation {
  3518. std::string name;
  3519. SourceLineInfo location;
  3520. NameAndLocation( std::string const& _name, SourceLineInfo const& _location );
  3521. };
  3522. struct ITracker;
  3523. using ITrackerPtr = std::shared_ptr<ITracker>;
  3524. struct ITracker {
  3525. virtual ~ITracker();
  3526. // static queries
  3527. virtual NameAndLocation const& nameAndLocation() const = 0;
  3528. // dynamic queries
  3529. virtual bool isComplete() const = 0; // Successfully completed or failed
  3530. virtual bool isSuccessfullyCompleted() const = 0;
  3531. virtual bool isOpen() const = 0; // Started but not complete
  3532. virtual bool hasChildren() const = 0;
  3533. virtual ITracker& parent() = 0;
  3534. // actions
  3535. virtual void close() = 0; // Successfully complete
  3536. virtual void fail() = 0;
  3537. virtual void markAsNeedingAnotherRun() = 0;
  3538. virtual void addChild( ITrackerPtr const& child ) = 0;
  3539. virtual ITrackerPtr findChild( NameAndLocation const& nameAndLocation ) = 0;
  3540. virtual void openChild() = 0;
  3541. // Debug/ checking
  3542. virtual bool isSectionTracker() const = 0;
  3543. virtual bool isIndexTracker() const = 0;
  3544. };
  3545. class TrackerContext {
  3546. enum RunState {
  3547. NotStarted,
  3548. Executing,
  3549. CompletedCycle
  3550. };
  3551. ITrackerPtr m_rootTracker;
  3552. ITracker* m_currentTracker = nullptr;
  3553. RunState m_runState = NotStarted;
  3554. public:
  3555. static TrackerContext& instance();
  3556. ITracker& startRun();
  3557. void endRun();
  3558. void startCycle();
  3559. void completeCycle();
  3560. bool completedCycle() const;
  3561. ITracker& currentTracker();
  3562. void setCurrentTracker( ITracker* tracker );
  3563. };
  3564. class TrackerBase : public ITracker {
  3565. protected:
  3566. enum CycleState {
  3567. NotStarted,
  3568. Executing,
  3569. ExecutingChildren,
  3570. NeedsAnotherRun,
  3571. CompletedSuccessfully,
  3572. Failed
  3573. };
  3574. class TrackerHasName {
  3575. NameAndLocation m_nameAndLocation;
  3576. public:
  3577. TrackerHasName( NameAndLocation const& nameAndLocation );
  3578. bool operator ()( ITrackerPtr const& tracker ) const;
  3579. };
  3580. using Children = std::vector<ITrackerPtr>;
  3581. NameAndLocation m_nameAndLocation;
  3582. TrackerContext& m_ctx;
  3583. ITracker* m_parent;
  3584. Children m_children;
  3585. CycleState m_runState = NotStarted;
  3586. public:
  3587. TrackerBase( NameAndLocation const& nameAndLocation, TrackerContext& ctx, ITracker* parent );
  3588. NameAndLocation const& nameAndLocation() const override;
  3589. bool isComplete() const override;
  3590. bool isSuccessfullyCompleted() const override;
  3591. bool isOpen() const override;
  3592. bool hasChildren() const override;
  3593. void addChild( ITrackerPtr const& child ) override;
  3594. ITrackerPtr findChild( NameAndLocation const& nameAndLocation ) override;
  3595. ITracker& parent() override;
  3596. void openChild() override;
  3597. bool isSectionTracker() const override;
  3598. bool isIndexTracker() const override;
  3599. void open();
  3600. void close() override;
  3601. void fail() override;
  3602. void markAsNeedingAnotherRun() override;
  3603. private:
  3604. void moveToParent();
  3605. void moveToThis();
  3606. };
  3607. class SectionTracker : public TrackerBase {
  3608. std::vector<std::string> m_filters;
  3609. public:
  3610. SectionTracker( NameAndLocation const& nameAndLocation, TrackerContext& ctx, ITracker* parent );
  3611. bool isSectionTracker() const override;
  3612. static SectionTracker& acquire( TrackerContext& ctx, NameAndLocation const& nameAndLocation );
  3613. void tryOpen();
  3614. void addInitialFilters( std::vector<std::string> const& filters );
  3615. void addNextFilters( std::vector<std::string> const& filters );
  3616. };
  3617. class IndexTracker : public TrackerBase {
  3618. int m_size;
  3619. int m_index = -1;
  3620. public:
  3621. IndexTracker( NameAndLocation const& nameAndLocation, TrackerContext& ctx, ITracker* parent, int size );
  3622. bool isIndexTracker() const override;
  3623. void close() override;
  3624. static IndexTracker& acquire( TrackerContext& ctx, NameAndLocation const& nameAndLocation, int size );
  3625. int index() const;
  3626. void moveNext();
  3627. };
  3628. } // namespace TestCaseTracking
  3629. using TestCaseTracking::ITracker;
  3630. using TestCaseTracking::TrackerContext;
  3631. using TestCaseTracking::SectionTracker;
  3632. using TestCaseTracking::IndexTracker;
  3633. } // namespace Catch
  3634. // end catch_test_case_tracker.h
  3635. // start catch_leak_detector.h
  3636. namespace Catch {
  3637. struct LeakDetector {
  3638. LeakDetector();
  3639. };
  3640. }
  3641. // end catch_leak_detector.h
  3642. // Cpp files will be included in the single-header file here
  3643. // start catch_approx.cpp
  3644. #include <cmath>
  3645. #include <limits>
  3646. namespace {
  3647. // Performs equivalent check of std::fabs(lhs - rhs) <= margin
  3648. // But without the subtraction to allow for INFINITY in comparison
  3649. bool marginComparison(double lhs, double rhs, double margin) {
  3650. return (lhs + margin >= rhs) && (rhs + margin >= lhs);
  3651. }
  3652. }
  3653. namespace Catch {
  3654. namespace Detail {
  3655. Approx::Approx ( double value )
  3656. : m_epsilon( std::numeric_limits<float>::epsilon()*100 ),
  3657. m_margin( 0.0 ),
  3658. m_scale( 0.0 ),
  3659. m_value( value )
  3660. {}
  3661. Approx Approx::custom() {
  3662. return Approx( 0 );
  3663. }
  3664. std::string Approx::toString() const {
  3665. ReusableStringStream rss;
  3666. rss << "Approx( " << ::Catch::Detail::stringify( m_value ) << " )";
  3667. return rss.str();
  3668. }
  3669. bool Approx::equalityComparisonImpl(const double other) const {
  3670. // First try with fixed margin, then compute margin based on epsilon, scale and Approx's value
  3671. // Thanks to Richard Harris for his help refining the scaled margin value
  3672. return marginComparison(m_value, other, m_margin) || marginComparison(m_value, other, m_epsilon * (m_scale + std::fabs(m_value)));
  3673. }
  3674. } // end namespace Detail
  3675. std::string StringMaker<Catch::Detail::Approx>::convert(Catch::Detail::Approx const& value) {
  3676. return value.toString();
  3677. }
  3678. } // end namespace Catch
  3679. // end catch_approx.cpp
  3680. // start catch_assertionhandler.cpp
  3681. // start catch_context.h
  3682. #include <memory>
  3683. namespace Catch {
  3684. struct IResultCapture;
  3685. struct IRunner;
  3686. struct IConfig;
  3687. struct IMutableContext;
  3688. using IConfigPtr = std::shared_ptr<IConfig const>;
  3689. struct IContext
  3690. {
  3691. virtual ~IContext();
  3692. virtual IResultCapture* getResultCapture() = 0;
  3693. virtual IRunner* getRunner() = 0;
  3694. virtual IConfigPtr const& getConfig() const = 0;
  3695. };
  3696. struct IMutableContext : IContext
  3697. {
  3698. virtual ~IMutableContext();
  3699. virtual void setResultCapture( IResultCapture* resultCapture ) = 0;
  3700. virtual void setRunner( IRunner* runner ) = 0;
  3701. virtual void setConfig( IConfigPtr const& config ) = 0;
  3702. private:
  3703. static IMutableContext *currentContext;
  3704. friend IMutableContext& getCurrentMutableContext();
  3705. friend void cleanUpContext();
  3706. static void createContext();
  3707. };
  3708. inline IMutableContext& getCurrentMutableContext()
  3709. {
  3710. if( !IMutableContext::currentContext )
  3711. IMutableContext::createContext();
  3712. return *IMutableContext::currentContext;
  3713. }
  3714. inline IContext& getCurrentContext()
  3715. {
  3716. return getCurrentMutableContext();
  3717. }
  3718. void cleanUpContext();
  3719. }
  3720. // end catch_context.h
  3721. // start catch_debugger.h
  3722. namespace Catch {
  3723. bool isDebuggerActive();
  3724. }
  3725. #ifdef CATCH_PLATFORM_MAC
  3726. #define CATCH_TRAP() __asm__("int $3\n" : : ) /* NOLINT */
  3727. #elif defined(CATCH_PLATFORM_LINUX)
  3728. // If we can use inline assembler, do it because this allows us to break
  3729. // directly at the location of the failing check instead of breaking inside
  3730. // raise() called from it, i.e. one stack frame below.
  3731. #if defined(__GNUC__) && (defined(__i386) || defined(__x86_64))
  3732. #define CATCH_TRAP() asm volatile ("int $3") /* NOLINT */
  3733. #else // Fall back to the generic way.
  3734. #include <signal.h>
  3735. #define CATCH_TRAP() raise(SIGTRAP)
  3736. #endif
  3737. #elif defined(_MSC_VER)
  3738. #define CATCH_TRAP() __debugbreak()
  3739. #elif defined(__MINGW32__)
  3740. extern "C" __declspec(dllimport) void __stdcall DebugBreak();
  3741. #define CATCH_TRAP() DebugBreak()
  3742. #endif
  3743. #ifdef CATCH_TRAP
  3744. #define CATCH_BREAK_INTO_DEBUGGER() if( Catch::isDebuggerActive() ) { CATCH_TRAP(); }
  3745. #else
  3746. namespace Catch {
  3747. inline void doNothing() {}
  3748. }
  3749. #define CATCH_BREAK_INTO_DEBUGGER() Catch::doNothing()
  3750. #endif
  3751. // end catch_debugger.h
  3752. // start catch_run_context.h
  3753. // start catch_fatal_condition.h
  3754. // start catch_windows_h_proxy.h
  3755. #if defined(CATCH_PLATFORM_WINDOWS)
  3756. #if !defined(NOMINMAX) && !defined(CATCH_CONFIG_NO_NOMINMAX)
  3757. # define CATCH_DEFINED_NOMINMAX
  3758. # define NOMINMAX
  3759. #endif
  3760. #if !defined(WIN32_LEAN_AND_MEAN) && !defined(CATCH_CONFIG_NO_WIN32_LEAN_AND_MEAN)
  3761. # define CATCH_DEFINED_WIN32_LEAN_AND_MEAN
  3762. # define WIN32_LEAN_AND_MEAN
  3763. #endif
  3764. #ifdef __AFXDLL
  3765. #include <AfxWin.h>
  3766. #else
  3767. #include <windows.h>
  3768. #endif
  3769. #ifdef CATCH_DEFINED_NOMINMAX
  3770. # undef NOMINMAX
  3771. #endif
  3772. #ifdef CATCH_DEFINED_WIN32_LEAN_AND_MEAN
  3773. # undef WIN32_LEAN_AND_MEAN
  3774. #endif
  3775. #endif // defined(CATCH_PLATFORM_WINDOWS)
  3776. // end catch_windows_h_proxy.h
  3777. #if defined( CATCH_CONFIG_WINDOWS_SEH )
  3778. namespace Catch {
  3779. struct FatalConditionHandler {
  3780. static LONG CALLBACK handleVectoredException(PEXCEPTION_POINTERS ExceptionInfo);
  3781. FatalConditionHandler();
  3782. static void reset();
  3783. ~FatalConditionHandler();
  3784. private:
  3785. static bool isSet;
  3786. static ULONG guaranteeSize;
  3787. static PVOID exceptionHandlerHandle;
  3788. };
  3789. } // namespace Catch
  3790. #elif defined ( CATCH_CONFIG_POSIX_SIGNALS )
  3791. #include <signal.h>
  3792. namespace Catch {
  3793. struct FatalConditionHandler {
  3794. static bool isSet;
  3795. static struct sigaction oldSigActions[];
  3796. static stack_t oldSigStack;
  3797. static char altStackMem[];
  3798. static void handleSignal( int sig );
  3799. FatalConditionHandler();
  3800. ~FatalConditionHandler();
  3801. static void reset();
  3802. };
  3803. } // namespace Catch
  3804. #else
  3805. namespace Catch {
  3806. struct FatalConditionHandler {
  3807. void reset();
  3808. };
  3809. }
  3810. #endif
  3811. // end catch_fatal_condition.h
  3812. #include <string>
  3813. namespace Catch {
  3814. struct IMutableContext;
  3815. ///////////////////////////////////////////////////////////////////////////
  3816. class RunContext : public IResultCapture, public IRunner {
  3817. public:
  3818. RunContext( RunContext const& ) = delete;
  3819. RunContext& operator =( RunContext const& ) = delete;
  3820. explicit RunContext( IConfigPtr const& _config, IStreamingReporterPtr&& reporter );
  3821. ~RunContext() override;
  3822. void testGroupStarting( std::string const& testSpec, std::size_t groupIndex, std::size_t groupsCount );
  3823. void testGroupEnded( std::string const& testSpec, Totals const& totals, std::size_t groupIndex, std::size_t groupsCount );
  3824. Totals runTest(TestCase const& testCase);
  3825. IConfigPtr config() const;
  3826. IStreamingReporter& reporter() const;
  3827. public: // IResultCapture
  3828. // Assertion handlers
  3829. void handleExpr
  3830. ( AssertionInfo const& info,
  3831. ITransientExpression const& expr,
  3832. AssertionReaction& reaction ) override;
  3833. void handleMessage
  3834. ( AssertionInfo const& info,
  3835. ResultWas::OfType resultType,
  3836. StringRef const& message,
  3837. AssertionReaction& reaction ) override;
  3838. void handleUnexpectedExceptionNotThrown
  3839. ( AssertionInfo const& info,
  3840. AssertionReaction& reaction ) override;
  3841. void handleUnexpectedInflightException
  3842. ( AssertionInfo const& info,
  3843. std::string const& message,
  3844. AssertionReaction& reaction ) override;
  3845. void handleIncomplete
  3846. ( AssertionInfo const& info ) override;
  3847. void handleNonExpr
  3848. ( AssertionInfo const &info,
  3849. ResultWas::OfType resultType,
  3850. AssertionReaction &reaction ) override;
  3851. bool sectionStarted( SectionInfo const& sectionInfo, Counts& assertions ) override;
  3852. void sectionEnded( SectionEndInfo const& endInfo ) override;
  3853. void sectionEndedEarly( SectionEndInfo const& endInfo ) override;
  3854. void benchmarkStarting( BenchmarkInfo const& info ) override;
  3855. void benchmarkEnded( BenchmarkStats const& stats ) override;
  3856. void pushScopedMessage( MessageInfo const& message ) override;
  3857. void popScopedMessage( MessageInfo const& message ) override;
  3858. std::string getCurrentTestName() const override;
  3859. const AssertionResult* getLastResult() const override;
  3860. void exceptionEarlyReported() override;
  3861. void handleFatalErrorCondition( StringRef message ) override;
  3862. bool lastAssertionPassed() override;
  3863. void assertionPassed() override;
  3864. public:
  3865. // !TBD We need to do this another way!
  3866. bool aborting() const final;
  3867. private:
  3868. void runCurrentTest( std::string& redirectedCout, std::string& redirectedCerr );
  3869. void invokeActiveTestCase();
  3870. void resetAssertionInfo();
  3871. bool testForMissingAssertions( Counts& assertions );
  3872. void assertionEnded( AssertionResult const& result );
  3873. void reportExpr
  3874. ( AssertionInfo const &info,
  3875. ResultWas::OfType resultType,
  3876. ITransientExpression const *expr,
  3877. bool negated );
  3878. void populateReaction( AssertionReaction& reaction );
  3879. private:
  3880. void handleUnfinishedSections();
  3881. TestRunInfo m_runInfo;
  3882. IMutableContext& m_context;
  3883. TestCase const* m_activeTestCase = nullptr;
  3884. ITracker* m_testCaseTracker;
  3885. Option<AssertionResult> m_lastResult;
  3886. IConfigPtr m_config;
  3887. Totals m_totals;
  3888. IStreamingReporterPtr m_reporter;
  3889. std::vector<MessageInfo> m_messages;
  3890. AssertionInfo m_lastAssertionInfo;
  3891. std::vector<SectionEndInfo> m_unfinishedSections;
  3892. std::vector<ITracker*> m_activeSections;
  3893. TrackerContext m_trackerContext;
  3894. bool m_lastAssertionPassed = false;
  3895. bool m_shouldReportUnexpected = true;
  3896. bool m_includeSuccessfulResults;
  3897. };
  3898. } // end namespace Catch
  3899. // end catch_run_context.h
  3900. namespace Catch {
  3901. auto operator <<( std::ostream& os, ITransientExpression const& expr ) -> std::ostream& {
  3902. expr.streamReconstructedExpression( os );
  3903. return os;
  3904. }
  3905. LazyExpression::LazyExpression( bool isNegated )
  3906. : m_isNegated( isNegated )
  3907. {}
  3908. LazyExpression::LazyExpression( LazyExpression const& other ) : m_isNegated( other.m_isNegated ) {}
  3909. LazyExpression::operator bool() const {
  3910. return m_transientExpression != nullptr;
  3911. }
  3912. auto operator << ( std::ostream& os, LazyExpression const& lazyExpr ) -> std::ostream& {
  3913. if( lazyExpr.m_isNegated )
  3914. os << "!";
  3915. if( lazyExpr ) {
  3916. if( lazyExpr.m_isNegated && lazyExpr.m_transientExpression->isBinaryExpression() )
  3917. os << "(" << *lazyExpr.m_transientExpression << ")";
  3918. else
  3919. os << *lazyExpr.m_transientExpression;
  3920. }
  3921. else {
  3922. os << "{** error - unchecked empty expression requested **}";
  3923. }
  3924. return os;
  3925. }
  3926. AssertionHandler::AssertionHandler
  3927. ( StringRef macroName,
  3928. SourceLineInfo const& lineInfo,
  3929. StringRef capturedExpression,
  3930. ResultDisposition::Flags resultDisposition )
  3931. : m_assertionInfo{ macroName, lineInfo, capturedExpression, resultDisposition },
  3932. m_resultCapture( getResultCapture() )
  3933. {}
  3934. void AssertionHandler::handleExpr( ITransientExpression const& expr ) {
  3935. m_resultCapture.handleExpr( m_assertionInfo, expr, m_reaction );
  3936. }
  3937. void AssertionHandler::handleMessage(ResultWas::OfType resultType, StringRef const& message) {
  3938. m_resultCapture.handleMessage( m_assertionInfo, resultType, message, m_reaction );
  3939. }
  3940. auto AssertionHandler::allowThrows() const -> bool {
  3941. return getCurrentContext().getConfig()->allowThrows();
  3942. }
  3943. void AssertionHandler::complete() {
  3944. setCompleted();
  3945. if( m_reaction.shouldDebugBreak ) {
  3946. // If you find your debugger stopping you here then go one level up on the
  3947. // call-stack for the code that caused it (typically a failed assertion)
  3948. // (To go back to the test and change execution, jump over the throw, next)
  3949. CATCH_BREAK_INTO_DEBUGGER();
  3950. }
  3951. if( m_reaction.shouldThrow )
  3952. throw Catch::TestFailureException();
  3953. }
  3954. void AssertionHandler::setCompleted() {
  3955. m_completed = true;
  3956. }
  3957. void AssertionHandler::handleUnexpectedInflightException() {
  3958. m_resultCapture.handleUnexpectedInflightException( m_assertionInfo, Catch::translateActiveException(), m_reaction );
  3959. }
  3960. void AssertionHandler::handleExceptionThrownAsExpected() {
  3961. m_resultCapture.handleNonExpr(m_assertionInfo, ResultWas::Ok, m_reaction);
  3962. }
  3963. void AssertionHandler::handleExceptionNotThrownAsExpected() {
  3964. m_resultCapture.handleNonExpr(m_assertionInfo, ResultWas::Ok, m_reaction);
  3965. }
  3966. void AssertionHandler::handleUnexpectedExceptionNotThrown() {
  3967. m_resultCapture.handleUnexpectedExceptionNotThrown( m_assertionInfo, m_reaction );
  3968. }
  3969. void AssertionHandler::handleThrowingCallSkipped() {
  3970. m_resultCapture.handleNonExpr(m_assertionInfo, ResultWas::Ok, m_reaction);
  3971. }
  3972. // This is the overload that takes a string and infers the Equals matcher from it
  3973. // The more general overload, that takes any string matcher, is in catch_capture_matchers.cpp
  3974. void handleExceptionMatchExpr( AssertionHandler& handler, std::string const& str, StringRef matcherString ) {
  3975. handleExceptionMatchExpr( handler, Matchers::Equals( str ), matcherString );
  3976. }
  3977. } // namespace Catch
  3978. // end catch_assertionhandler.cpp
  3979. // start catch_assertionresult.cpp
  3980. namespace Catch {
  3981. AssertionResultData::AssertionResultData(ResultWas::OfType _resultType, LazyExpression const & _lazyExpression):
  3982. lazyExpression(_lazyExpression),
  3983. resultType(_resultType) {}
  3984. std::string AssertionResultData::reconstructExpression() const {
  3985. if( reconstructedExpression.empty() ) {
  3986. if( lazyExpression ) {
  3987. ReusableStringStream rss;
  3988. rss << lazyExpression;
  3989. reconstructedExpression = rss.str();
  3990. }
  3991. }
  3992. return reconstructedExpression;
  3993. }
  3994. AssertionResult::AssertionResult( AssertionInfo const& info, AssertionResultData const& data )
  3995. : m_info( info ),
  3996. m_resultData( data )
  3997. {}
  3998. // Result was a success
  3999. bool AssertionResult::succeeded() const {
  4000. return Catch::isOk( m_resultData.resultType );
  4001. }
  4002. // Result was a success, or failure is suppressed
  4003. bool AssertionResult::isOk() const {
  4004. return Catch::isOk( m_resultData.resultType ) || shouldSuppressFailure( m_info.resultDisposition );
  4005. }
  4006. ResultWas::OfType AssertionResult::getResultType() const {
  4007. return m_resultData.resultType;
  4008. }
  4009. bool AssertionResult::hasExpression() const {
  4010. return m_info.capturedExpression[0] != 0;
  4011. }
  4012. bool AssertionResult::hasMessage() const {
  4013. return !m_resultData.message.empty();
  4014. }
  4015. std::string AssertionResult::getExpression() const {
  4016. if( isFalseTest( m_info.resultDisposition ) )
  4017. return "!(" + m_info.capturedExpression + ")";
  4018. else
  4019. return m_info.capturedExpression;
  4020. }
  4021. std::string AssertionResult::getExpressionInMacro() const {
  4022. std::string expr;
  4023. if( m_info.macroName[0] == 0 )
  4024. expr = m_info.capturedExpression;
  4025. else {
  4026. expr.reserve( m_info.macroName.size() + m_info.capturedExpression.size() + 4 );
  4027. expr += m_info.macroName;
  4028. expr += "( ";
  4029. expr += m_info.capturedExpression;
  4030. expr += " )";
  4031. }
  4032. return expr;
  4033. }
  4034. bool AssertionResult::hasExpandedExpression() const {
  4035. return hasExpression() && getExpandedExpression() != getExpression();
  4036. }
  4037. std::string AssertionResult::getExpandedExpression() const {
  4038. std::string expr = m_resultData.reconstructExpression();
  4039. return expr.empty()
  4040. ? getExpression()
  4041. : expr;
  4042. }
  4043. std::string AssertionResult::getMessage() const {
  4044. return m_resultData.message;
  4045. }
  4046. SourceLineInfo AssertionResult::getSourceInfo() const {
  4047. return m_info.lineInfo;
  4048. }
  4049. StringRef AssertionResult::getTestMacroName() const {
  4050. return m_info.macroName;
  4051. }
  4052. } // end namespace Catch
  4053. // end catch_assertionresult.cpp
  4054. // start catch_benchmark.cpp
  4055. namespace Catch {
  4056. auto BenchmarkLooper::getResolution() -> uint64_t {
  4057. return getEstimatedClockResolution() * getCurrentContext().getConfig()->benchmarkResolutionMultiple();
  4058. }
  4059. void BenchmarkLooper::reportStart() {
  4060. getResultCapture().benchmarkStarting( { m_name } );
  4061. }
  4062. auto BenchmarkLooper::needsMoreIterations() -> bool {
  4063. auto elapsed = m_timer.getElapsedNanoseconds();
  4064. // Exponentially increasing iterations until we're confident in our timer resolution
  4065. if( elapsed < m_resolution ) {
  4066. m_iterationsToRun *= 10;
  4067. return true;
  4068. }
  4069. getResultCapture().benchmarkEnded( { { m_name }, m_count, elapsed } );
  4070. return false;
  4071. }
  4072. } // end namespace Catch
  4073. // end catch_benchmark.cpp
  4074. // start catch_capture_matchers.cpp
  4075. namespace Catch {
  4076. using StringMatcher = Matchers::Impl::MatcherBase<std::string>;
  4077. // This is the general overload that takes a any string matcher
  4078. // There is another overload, in catch_assertionhandler.h/.cpp, that only takes a string and infers
  4079. // the Equals matcher (so the header does not mention matchers)
  4080. void handleExceptionMatchExpr( AssertionHandler& handler, StringMatcher const& matcher, StringRef matcherString ) {
  4081. std::string exceptionMessage = Catch::translateActiveException();
  4082. MatchExpr<std::string, StringMatcher const&> expr( exceptionMessage, matcher, matcherString );
  4083. handler.handleExpr( expr );
  4084. }
  4085. } // namespace Catch
  4086. // end catch_capture_matchers.cpp
  4087. // start catch_commandline.cpp
  4088. // start catch_commandline.h
  4089. // start catch_clara.h
  4090. // Use Catch's value for console width (store Clara's off to the side, if present)
  4091. #ifdef CLARA_CONFIG_CONSOLE_WIDTH
  4092. #define CATCH_TEMP_CLARA_CONFIG_CONSOLE_WIDTH CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH
  4093. #undef CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH
  4094. #endif
  4095. #define CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH CATCH_CONFIG_CONSOLE_WIDTH-1
  4096. #ifdef __clang__
  4097. #pragma clang diagnostic push
  4098. #pragma clang diagnostic ignored "-Wweak-vtables"
  4099. #pragma clang diagnostic ignored "-Wexit-time-destructors"
  4100. #pragma clang diagnostic ignored "-Wshadow"
  4101. #endif
  4102. // start clara.hpp
  4103. // Copyright 2017 Two Blue Cubes Ltd. All rights reserved.
  4104. //
  4105. // Distributed under the Boost Software License, Version 1.0. (See accompanying
  4106. // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
  4107. //
  4108. // See https://github.com/philsquared/Clara for more details
  4109. // Clara v1.1.4
  4110. #ifndef CATCH_CLARA_CONFIG_CONSOLE_WIDTH
  4111. #define CATCH_CLARA_CONFIG_CONSOLE_WIDTH 80
  4112. #endif
  4113. #ifndef CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH
  4114. #define CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH CATCH_CLARA_CONFIG_CONSOLE_WIDTH
  4115. #endif
  4116. #ifndef CLARA_CONFIG_OPTIONAL_TYPE
  4117. #ifdef __has_include
  4118. #if __has_include(<optional>) && __cplusplus >= 201703L
  4119. #include <optional>
  4120. #define CLARA_CONFIG_OPTIONAL_TYPE std::optional
  4121. #endif
  4122. #endif
  4123. #endif
  4124. // ----------- #included from clara_textflow.hpp -----------
  4125. // TextFlowCpp
  4126. //
  4127. // A single-header library for wrapping and laying out basic text, by Phil Nash
  4128. //
  4129. // This work is licensed under the BSD 2-Clause license.
  4130. // See the accompanying LICENSE file, or the one at https://opensource.org/licenses/BSD-2-Clause
  4131. //
  4132. // This project is hosted at https://github.com/philsquared/textflowcpp
  4133. #include <cassert>
  4134. #include <ostream>
  4135. #include <sstream>
  4136. #include <vector>
  4137. #ifndef CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH
  4138. #define CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH 80
  4139. #endif
  4140. namespace Catch { namespace clara { namespace TextFlow {
  4141. inline auto isWhitespace( char c ) -> bool {
  4142. static std::string chars = " \t\n\r";
  4143. return chars.find( c ) != std::string::npos;
  4144. }
  4145. inline auto isBreakableBefore( char c ) -> bool {
  4146. static std::string chars = "[({<|";
  4147. return chars.find( c ) != std::string::npos;
  4148. }
  4149. inline auto isBreakableAfter( char c ) -> bool {
  4150. static std::string chars = "])}>.,:;*+-=&/\\";
  4151. return chars.find( c ) != std::string::npos;
  4152. }
  4153. class Columns;
  4154. class Column {
  4155. std::vector<std::string> m_strings;
  4156. size_t m_width = CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH;
  4157. size_t m_indent = 0;
  4158. size_t m_initialIndent = std::string::npos;
  4159. public:
  4160. class iterator {
  4161. friend Column;
  4162. Column const& m_column;
  4163. size_t m_stringIndex = 0;
  4164. size_t m_pos = 0;
  4165. size_t m_len = 0;
  4166. size_t m_end = 0;
  4167. bool m_suffix = false;
  4168. iterator( Column const& column, size_t stringIndex )
  4169. : m_column( column ),
  4170. m_stringIndex( stringIndex )
  4171. {}
  4172. auto line() const -> std::string const& { return m_column.m_strings[m_stringIndex]; }
  4173. auto isBoundary( size_t at ) const -> bool {
  4174. assert( at > 0 );
  4175. assert( at <= line().size() );
  4176. return at == line().size() ||
  4177. ( isWhitespace( line()[at] ) && !isWhitespace( line()[at-1] ) ) ||
  4178. isBreakableBefore( line()[at] ) ||
  4179. isBreakableAfter( line()[at-1] );
  4180. }
  4181. void calcLength() {
  4182. assert( m_stringIndex < m_column.m_strings.size() );
  4183. m_suffix = false;
  4184. auto width = m_column.m_width-indent();
  4185. m_end = m_pos;
  4186. while( m_end < line().size() && line()[m_end] != '\n' )
  4187. ++m_end;
  4188. if( m_end < m_pos + width ) {
  4189. m_len = m_end - m_pos;
  4190. }
  4191. else {
  4192. size_t len = width;
  4193. while (len > 0 && !isBoundary(m_pos + len))
  4194. --len;
  4195. while (len > 0 && isWhitespace( line()[m_pos + len - 1] ))
  4196. --len;
  4197. if (len > 0) {
  4198. m_len = len;
  4199. } else {
  4200. m_suffix = true;
  4201. m_len = width - 1;
  4202. }
  4203. }
  4204. }
  4205. auto indent() const -> size_t {
  4206. auto initial = m_pos == 0 && m_stringIndex == 0 ? m_column.m_initialIndent : std::string::npos;
  4207. return initial == std::string::npos ? m_column.m_indent : initial;
  4208. }
  4209. auto addIndentAndSuffix(std::string const &plain) const -> std::string {
  4210. return std::string( indent(), ' ' ) + (m_suffix ? plain + "-" : plain);
  4211. }
  4212. public:
  4213. explicit iterator( Column const& column ) : m_column( column ) {
  4214. assert( m_column.m_width > m_column.m_indent );
  4215. assert( m_column.m_initialIndent == std::string::npos || m_column.m_width > m_column.m_initialIndent );
  4216. calcLength();
  4217. if( m_len == 0 )
  4218. m_stringIndex++; // Empty string
  4219. }
  4220. auto operator *() const -> std::string {
  4221. assert( m_stringIndex < m_column.m_strings.size() );
  4222. assert( m_pos <= m_end );
  4223. if( m_pos + m_column.m_width < m_end )
  4224. return addIndentAndSuffix(line().substr(m_pos, m_len));
  4225. else
  4226. return addIndentAndSuffix(line().substr(m_pos, m_end - m_pos));
  4227. }
  4228. auto operator ++() -> iterator& {
  4229. m_pos += m_len;
  4230. if( m_pos < line().size() && line()[m_pos] == '\n' )
  4231. m_pos += 1;
  4232. else
  4233. while( m_pos < line().size() && isWhitespace( line()[m_pos] ) )
  4234. ++m_pos;
  4235. if( m_pos == line().size() ) {
  4236. m_pos = 0;
  4237. ++m_stringIndex;
  4238. }
  4239. if( m_stringIndex < m_column.m_strings.size() )
  4240. calcLength();
  4241. return *this;
  4242. }
  4243. auto operator ++(int) -> iterator {
  4244. iterator prev( *this );
  4245. operator++();
  4246. return prev;
  4247. }
  4248. auto operator ==( iterator const& other ) const -> bool {
  4249. return
  4250. m_pos == other.m_pos &&
  4251. m_stringIndex == other.m_stringIndex &&
  4252. &m_column == &other.m_column;
  4253. }
  4254. auto operator !=( iterator const& other ) const -> bool {
  4255. return !operator==( other );
  4256. }
  4257. };
  4258. using const_iterator = iterator;
  4259. explicit Column( std::string const& text ) { m_strings.push_back( text ); }
  4260. auto width( size_t newWidth ) -> Column& {
  4261. assert( newWidth > 0 );
  4262. m_width = newWidth;
  4263. return *this;
  4264. }
  4265. auto indent( size_t newIndent ) -> Column& {
  4266. m_indent = newIndent;
  4267. return *this;
  4268. }
  4269. auto initialIndent( size_t newIndent ) -> Column& {
  4270. m_initialIndent = newIndent;
  4271. return *this;
  4272. }
  4273. auto width() const -> size_t { return m_width; }
  4274. auto begin() const -> iterator { return iterator( *this ); }
  4275. auto end() const -> iterator { return { *this, m_strings.size() }; }
  4276. inline friend std::ostream& operator << ( std::ostream& os, Column const& col ) {
  4277. bool first = true;
  4278. for( auto line : col ) {
  4279. if( first )
  4280. first = false;
  4281. else
  4282. os << "\n";
  4283. os << line;
  4284. }
  4285. return os;
  4286. }
  4287. auto operator + ( Column const& other ) -> Columns;
  4288. auto toString() const -> std::string {
  4289. std::ostringstream oss;
  4290. oss << *this;
  4291. return oss.str();
  4292. }
  4293. };
  4294. class Spacer : public Column {
  4295. public:
  4296. explicit Spacer( size_t spaceWidth ) : Column( "" ) {
  4297. width( spaceWidth );
  4298. }
  4299. };
  4300. class Columns {
  4301. std::vector<Column> m_columns;
  4302. public:
  4303. class iterator {
  4304. friend Columns;
  4305. struct EndTag {};
  4306. std::vector<Column> const& m_columns;
  4307. std::vector<Column::iterator> m_iterators;
  4308. size_t m_activeIterators;
  4309. iterator( Columns const& columns, EndTag )
  4310. : m_columns( columns.m_columns ),
  4311. m_activeIterators( 0 )
  4312. {
  4313. m_iterators.reserve( m_columns.size() );
  4314. for( auto const& col : m_columns )
  4315. m_iterators.push_back( col.end() );
  4316. }
  4317. public:
  4318. explicit iterator( Columns const& columns )
  4319. : m_columns( columns.m_columns ),
  4320. m_activeIterators( m_columns.size() )
  4321. {
  4322. m_iterators.reserve( m_columns.size() );
  4323. for( auto const& col : m_columns )
  4324. m_iterators.push_back( col.begin() );
  4325. }
  4326. auto operator ==( iterator const& other ) const -> bool {
  4327. return m_iterators == other.m_iterators;
  4328. }
  4329. auto operator !=( iterator const& other ) const -> bool {
  4330. return m_iterators != other.m_iterators;
  4331. }
  4332. auto operator *() const -> std::string {
  4333. std::string row, padding;
  4334. for( size_t i = 0; i < m_columns.size(); ++i ) {
  4335. auto width = m_columns[i].width();
  4336. if( m_iterators[i] != m_columns[i].end() ) {
  4337. std::string col = *m_iterators[i];
  4338. row += padding + col;
  4339. if( col.size() < width )
  4340. padding = std::string( width - col.size(), ' ' );
  4341. else
  4342. padding = "";
  4343. }
  4344. else {
  4345. padding += std::string( width, ' ' );
  4346. }
  4347. }
  4348. return row;
  4349. }
  4350. auto operator ++() -> iterator& {
  4351. for( size_t i = 0; i < m_columns.size(); ++i ) {
  4352. if (m_iterators[i] != m_columns[i].end())
  4353. ++m_iterators[i];
  4354. }
  4355. return *this;
  4356. }
  4357. auto operator ++(int) -> iterator {
  4358. iterator prev( *this );
  4359. operator++();
  4360. return prev;
  4361. }
  4362. };
  4363. using const_iterator = iterator;
  4364. auto begin() const -> iterator { return iterator( *this ); }
  4365. auto end() const -> iterator { return { *this, iterator::EndTag() }; }
  4366. auto operator += ( Column const& col ) -> Columns& {
  4367. m_columns.push_back( col );
  4368. return *this;
  4369. }
  4370. auto operator + ( Column const& col ) -> Columns {
  4371. Columns combined = *this;
  4372. combined += col;
  4373. return combined;
  4374. }
  4375. inline friend std::ostream& operator << ( std::ostream& os, Columns const& cols ) {
  4376. bool first = true;
  4377. for( auto line : cols ) {
  4378. if( first )
  4379. first = false;
  4380. else
  4381. os << "\n";
  4382. os << line;
  4383. }
  4384. return os;
  4385. }
  4386. auto toString() const -> std::string {
  4387. std::ostringstream oss;
  4388. oss << *this;
  4389. return oss.str();
  4390. }
  4391. };
  4392. inline auto Column::operator + ( Column const& other ) -> Columns {
  4393. Columns cols;
  4394. cols += *this;
  4395. cols += other;
  4396. return cols;
  4397. }
  4398. }}} // namespace Catch::clara::TextFlow
  4399. // ----------- end of #include from clara_textflow.hpp -----------
  4400. // ........... back in clara.hpp
  4401. #include <memory>
  4402. #include <set>
  4403. #include <algorithm>
  4404. #if !defined(CATCH_PLATFORM_WINDOWS) && ( defined(WIN32) || defined(__WIN32__) || defined(_WIN32) || defined(_MSC_VER) )
  4405. #define CATCH_PLATFORM_WINDOWS
  4406. #endif
  4407. namespace Catch { namespace clara {
  4408. namespace detail {
  4409. // Traits for extracting arg and return type of lambdas (for single argument lambdas)
  4410. template<typename L>
  4411. struct UnaryLambdaTraits : UnaryLambdaTraits<decltype( &L::operator() )> {};
  4412. template<typename ClassT, typename ReturnT, typename... Args>
  4413. struct UnaryLambdaTraits<ReturnT( ClassT::* )( Args... ) const> {
  4414. static const bool isValid = false;
  4415. };
  4416. template<typename ClassT, typename ReturnT, typename ArgT>
  4417. struct UnaryLambdaTraits<ReturnT( ClassT::* )( ArgT ) const> {
  4418. static const bool isValid = true;
  4419. using ArgType = typename std::remove_const<typename std::remove_reference<ArgT>::type>::type;
  4420. using ReturnType = ReturnT;
  4421. };
  4422. class TokenStream;
  4423. // Transport for raw args (copied from main args, or supplied via init list for testing)
  4424. class Args {
  4425. friend TokenStream;
  4426. std::string m_exeName;
  4427. std::vector<std::string> m_args;
  4428. public:
  4429. Args( int argc, char const* const* argv )
  4430. : m_exeName(argv[0]),
  4431. m_args(argv + 1, argv + argc) {}
  4432. Args( std::initializer_list<std::string> args )
  4433. : m_exeName( *args.begin() ),
  4434. m_args( args.begin()+1, args.end() )
  4435. {}
  4436. auto exeName() const -> std::string {
  4437. return m_exeName;
  4438. }
  4439. };
  4440. // Wraps a token coming from a token stream. These may not directly correspond to strings as a single string
  4441. // may encode an option + its argument if the : or = form is used
  4442. enum class TokenType {
  4443. Option, Argument
  4444. };
  4445. struct Token {
  4446. TokenType type;
  4447. std::string token;
  4448. };
  4449. inline auto isOptPrefix( char c ) -> bool {
  4450. return c == '-'
  4451. #ifdef CATCH_PLATFORM_WINDOWS
  4452. || c == '/'
  4453. #endif
  4454. ;
  4455. }
  4456. // Abstracts iterators into args as a stream of tokens, with option arguments uniformly handled
  4457. class TokenStream {
  4458. using Iterator = std::vector<std::string>::const_iterator;
  4459. Iterator it;
  4460. Iterator itEnd;
  4461. std::vector<Token> m_tokenBuffer;
  4462. void loadBuffer() {
  4463. m_tokenBuffer.resize( 0 );
  4464. // Skip any empty strings
  4465. while( it != itEnd && it->empty() )
  4466. ++it;
  4467. if( it != itEnd ) {
  4468. auto const &next = *it;
  4469. if( isOptPrefix( next[0] ) ) {
  4470. auto delimiterPos = next.find_first_of( " :=" );
  4471. if( delimiterPos != std::string::npos ) {
  4472. m_tokenBuffer.push_back( { TokenType::Option, next.substr( 0, delimiterPos ) } );
  4473. m_tokenBuffer.push_back( { TokenType::Argument, next.substr( delimiterPos + 1 ) } );
  4474. } else {
  4475. if( next[1] != '-' && next.size() > 2 ) {
  4476. std::string opt = "- ";
  4477. for( size_t i = 1; i < next.size(); ++i ) {
  4478. opt[1] = next[i];
  4479. m_tokenBuffer.push_back( { TokenType::Option, opt } );
  4480. }
  4481. } else {
  4482. m_tokenBuffer.push_back( { TokenType::Option, next } );
  4483. }
  4484. }
  4485. } else {
  4486. m_tokenBuffer.push_back( { TokenType::Argument, next } );
  4487. }
  4488. }
  4489. }
  4490. public:
  4491. explicit TokenStream( Args const &args ) : TokenStream( args.m_args.begin(), args.m_args.end() ) {}
  4492. TokenStream( Iterator it, Iterator itEnd ) : it( it ), itEnd( itEnd ) {
  4493. loadBuffer();
  4494. }
  4495. explicit operator bool() const {
  4496. return !m_tokenBuffer.empty() || it != itEnd;
  4497. }
  4498. auto count() const -> size_t { return m_tokenBuffer.size() + (itEnd - it); }
  4499. auto operator*() const -> Token {
  4500. assert( !m_tokenBuffer.empty() );
  4501. return m_tokenBuffer.front();
  4502. }
  4503. auto operator->() const -> Token const * {
  4504. assert( !m_tokenBuffer.empty() );
  4505. return &m_tokenBuffer.front();
  4506. }
  4507. auto operator++() -> TokenStream & {
  4508. if( m_tokenBuffer.size() >= 2 ) {
  4509. m_tokenBuffer.erase( m_tokenBuffer.begin() );
  4510. } else {
  4511. if( it != itEnd )
  4512. ++it;
  4513. loadBuffer();
  4514. }
  4515. return *this;
  4516. }
  4517. };
  4518. class ResultBase {
  4519. public:
  4520. enum Type {
  4521. Ok, LogicError, RuntimeError
  4522. };
  4523. protected:
  4524. ResultBase( Type type ) : m_type( type ) {}
  4525. virtual ~ResultBase() = default;
  4526. virtual void enforceOk() const = 0;
  4527. Type m_type;
  4528. };
  4529. template<typename T>
  4530. class ResultValueBase : public ResultBase {
  4531. public:
  4532. auto value() const -> T const & {
  4533. enforceOk();
  4534. return m_value;
  4535. }
  4536. protected:
  4537. ResultValueBase( Type type ) : ResultBase( type ) {}
  4538. ResultValueBase( ResultValueBase const &other ) : ResultBase( other ) {
  4539. if( m_type == ResultBase::Ok )
  4540. new( &m_value ) T( other.m_value );
  4541. }
  4542. ResultValueBase( Type, T const &value ) : ResultBase( Ok ) {
  4543. new( &m_value ) T( value );
  4544. }
  4545. auto operator=( ResultValueBase const &other ) -> ResultValueBase & {
  4546. if( m_type == ResultBase::Ok )
  4547. m_value.~T();
  4548. ResultBase::operator=(other);
  4549. if( m_type == ResultBase::Ok )
  4550. new( &m_value ) T( other.m_value );
  4551. return *this;
  4552. }
  4553. ~ResultValueBase() override {
  4554. if( m_type == Ok )
  4555. m_value.~T();
  4556. }
  4557. union {
  4558. T m_value;
  4559. };
  4560. };
  4561. template<>
  4562. class ResultValueBase<void> : public ResultBase {
  4563. protected:
  4564. using ResultBase::ResultBase;
  4565. };
  4566. template<typename T = void>
  4567. class BasicResult : public ResultValueBase<T> {
  4568. public:
  4569. template<typename U>
  4570. explicit BasicResult( BasicResult<U> const &other )
  4571. : ResultValueBase<T>( other.type() ),
  4572. m_errorMessage( other.errorMessage() )
  4573. {
  4574. assert( type() != ResultBase::Ok );
  4575. }
  4576. template<typename U>
  4577. static auto ok( U const &value ) -> BasicResult { return { ResultBase::Ok, value }; }
  4578. static auto ok() -> BasicResult { return { ResultBase::Ok }; }
  4579. static auto logicError( std::string const &message ) -> BasicResult { return { ResultBase::LogicError, message }; }
  4580. static auto runtimeError( std::string const &message ) -> BasicResult { return { ResultBase::RuntimeError, message }; }
  4581. explicit operator bool() const { return m_type == ResultBase::Ok; }
  4582. auto type() const -> ResultBase::Type { return m_type; }
  4583. auto errorMessage() const -> std::string { return m_errorMessage; }
  4584. protected:
  4585. void enforceOk() const override {
  4586. // Errors shouldn't reach this point, but if they do
  4587. // the actual error message will be in m_errorMessage
  4588. assert( m_type != ResultBase::LogicError );
  4589. assert( m_type != ResultBase::RuntimeError );
  4590. if( m_type != ResultBase::Ok )
  4591. std::abort();
  4592. }
  4593. std::string m_errorMessage; // Only populated if resultType is an error
  4594. BasicResult( ResultBase::Type type, std::string const &message )
  4595. : ResultValueBase<T>(type),
  4596. m_errorMessage(message)
  4597. {
  4598. assert( m_type != ResultBase::Ok );
  4599. }
  4600. using ResultValueBase<T>::ResultValueBase;
  4601. using ResultBase::m_type;
  4602. };
  4603. enum class ParseResultType {
  4604. Matched, NoMatch, ShortCircuitAll, ShortCircuitSame
  4605. };
  4606. class ParseState {
  4607. public:
  4608. ParseState( ParseResultType type, TokenStream const &remainingTokens )
  4609. : m_type(type),
  4610. m_remainingTokens( remainingTokens )
  4611. {}
  4612. auto type() const -> ParseResultType { return m_type; }
  4613. auto remainingTokens() const -> TokenStream { return m_remainingTokens; }
  4614. private:
  4615. ParseResultType m_type;
  4616. TokenStream m_remainingTokens;
  4617. };
  4618. using Result = BasicResult<void>;
  4619. using ParserResult = BasicResult<ParseResultType>;
  4620. using InternalParseResult = BasicResult<ParseState>;
  4621. struct HelpColumns {
  4622. std::string left;
  4623. std::string right;
  4624. };
  4625. template<typename T>
  4626. inline auto convertInto( std::string const &source, T& target ) -> ParserResult {
  4627. std::stringstream ss;
  4628. ss << source;
  4629. ss >> target;
  4630. if( ss.fail() )
  4631. return ParserResult::runtimeError( "Unable to convert '" + source + "' to destination type" );
  4632. else
  4633. return ParserResult::ok( ParseResultType::Matched );
  4634. }
  4635. inline auto convertInto( std::string const &source, std::string& target ) -> ParserResult {
  4636. target = source;
  4637. return ParserResult::ok( ParseResultType::Matched );
  4638. }
  4639. inline auto convertInto( std::string const &source, bool &target ) -> ParserResult {
  4640. std::string srcLC = source;
  4641. std::transform( srcLC.begin(), srcLC.end(), srcLC.begin(), []( char c ) { return static_cast<char>( ::tolower(c) ); } );
  4642. if (srcLC == "y" || srcLC == "1" || srcLC == "true" || srcLC == "yes" || srcLC == "on")
  4643. target = true;
  4644. else if (srcLC == "n" || srcLC == "0" || srcLC == "false" || srcLC == "no" || srcLC == "off")
  4645. target = false;
  4646. else
  4647. return ParserResult::runtimeError( "Expected a boolean value but did not recognise: '" + source + "'" );
  4648. return ParserResult::ok( ParseResultType::Matched );
  4649. }
  4650. #ifdef CLARA_CONFIG_OPTIONAL_TYPE
  4651. template<typename T>
  4652. inline auto convertInto( std::string const &source, CLARA_CONFIG_OPTIONAL_TYPE<T>& target ) -> ParserResult {
  4653. T temp;
  4654. auto result = convertInto( source, temp );
  4655. if( result )
  4656. target = std::move(temp);
  4657. return result;
  4658. }
  4659. #endif // CLARA_CONFIG_OPTIONAL_TYPE
  4660. struct NonCopyable {
  4661. NonCopyable() = default;
  4662. NonCopyable( NonCopyable const & ) = delete;
  4663. NonCopyable( NonCopyable && ) = delete;
  4664. NonCopyable &operator=( NonCopyable const & ) = delete;
  4665. NonCopyable &operator=( NonCopyable && ) = delete;
  4666. };
  4667. struct BoundRef : NonCopyable {
  4668. virtual ~BoundRef() = default;
  4669. virtual auto isContainer() const -> bool { return false; }
  4670. virtual auto isFlag() const -> bool { return false; }
  4671. };
  4672. struct BoundValueRefBase : BoundRef {
  4673. virtual auto setValue( std::string const &arg ) -> ParserResult = 0;
  4674. };
  4675. struct BoundFlagRefBase : BoundRef {
  4676. virtual auto setFlag( bool flag ) -> ParserResult = 0;
  4677. virtual auto isFlag() const -> bool { return true; }
  4678. };
  4679. template<typename T>
  4680. struct BoundValueRef : BoundValueRefBase {
  4681. T &m_ref;
  4682. explicit BoundValueRef( T &ref ) : m_ref( ref ) {}
  4683. auto setValue( std::string const &arg ) -> ParserResult override {
  4684. return convertInto( arg, m_ref );
  4685. }
  4686. };
  4687. template<typename T>
  4688. struct BoundValueRef<std::vector<T>> : BoundValueRefBase {
  4689. std::vector<T> &m_ref;
  4690. explicit BoundValueRef( std::vector<T> &ref ) : m_ref( ref ) {}
  4691. auto isContainer() const -> bool override { return true; }
  4692. auto setValue( std::string const &arg ) -> ParserResult override {
  4693. T temp;
  4694. auto result = convertInto( arg, temp );
  4695. if( result )
  4696. m_ref.push_back( temp );
  4697. return result;
  4698. }
  4699. };
  4700. struct BoundFlagRef : BoundFlagRefBase {
  4701. bool &m_ref;
  4702. explicit BoundFlagRef( bool &ref ) : m_ref( ref ) {}
  4703. auto setFlag( bool flag ) -> ParserResult override {
  4704. m_ref = flag;
  4705. return ParserResult::ok( ParseResultType::Matched );
  4706. }
  4707. };
  4708. template<typename ReturnType>
  4709. struct LambdaInvoker {
  4710. static_assert( std::is_same<ReturnType, ParserResult>::value, "Lambda must return void or clara::ParserResult" );
  4711. template<typename L, typename ArgType>
  4712. static auto invoke( L const &lambda, ArgType const &arg ) -> ParserResult {
  4713. return lambda( arg );
  4714. }
  4715. };
  4716. template<>
  4717. struct LambdaInvoker<void> {
  4718. template<typename L, typename ArgType>
  4719. static auto invoke( L const &lambda, ArgType const &arg ) -> ParserResult {
  4720. lambda( arg );
  4721. return ParserResult::ok( ParseResultType::Matched );
  4722. }
  4723. };
  4724. template<typename ArgType, typename L>
  4725. inline auto invokeLambda( L const &lambda, std::string const &arg ) -> ParserResult {
  4726. ArgType temp{};
  4727. auto result = convertInto( arg, temp );
  4728. return !result
  4729. ? result
  4730. : LambdaInvoker<typename UnaryLambdaTraits<L>::ReturnType>::invoke( lambda, temp );
  4731. }
  4732. template<typename L>
  4733. struct BoundLambda : BoundValueRefBase {
  4734. L m_lambda;
  4735. static_assert( UnaryLambdaTraits<L>::isValid, "Supplied lambda must take exactly one argument" );
  4736. explicit BoundLambda( L const &lambda ) : m_lambda( lambda ) {}
  4737. auto setValue( std::string const &arg ) -> ParserResult override {
  4738. return invokeLambda<typename UnaryLambdaTraits<L>::ArgType>( m_lambda, arg );
  4739. }
  4740. };
  4741. template<typename L>
  4742. struct BoundFlagLambda : BoundFlagRefBase {
  4743. L m_lambda;
  4744. static_assert( UnaryLambdaTraits<L>::isValid, "Supplied lambda must take exactly one argument" );
  4745. static_assert( std::is_same<typename UnaryLambdaTraits<L>::ArgType, bool>::value, "flags must be boolean" );
  4746. explicit BoundFlagLambda( L const &lambda ) : m_lambda( lambda ) {}
  4747. auto setFlag( bool flag ) -> ParserResult override {
  4748. return LambdaInvoker<typename UnaryLambdaTraits<L>::ReturnType>::invoke( m_lambda, flag );
  4749. }
  4750. };
  4751. enum class Optionality { Optional, Required };
  4752. struct Parser;
  4753. class ParserBase {
  4754. public:
  4755. virtual ~ParserBase() = default;
  4756. virtual auto validate() const -> Result { return Result::ok(); }
  4757. virtual auto parse( std::string const& exeName, TokenStream const &tokens) const -> InternalParseResult = 0;
  4758. virtual auto cardinality() const -> size_t { return 1; }
  4759. auto parse( Args const &args ) const -> InternalParseResult {
  4760. return parse( args.exeName(), TokenStream( args ) );
  4761. }
  4762. };
  4763. template<typename DerivedT>
  4764. class ComposableParserImpl : public ParserBase {
  4765. public:
  4766. template<typename T>
  4767. auto operator|( T const &other ) const -> Parser;
  4768. template<typename T>
  4769. auto operator+( T const &other ) const -> Parser;
  4770. };
  4771. // Common code and state for Args and Opts
  4772. template<typename DerivedT>
  4773. class ParserRefImpl : public ComposableParserImpl<DerivedT> {
  4774. protected:
  4775. Optionality m_optionality = Optionality::Optional;
  4776. std::shared_ptr<BoundRef> m_ref;
  4777. std::string m_hint;
  4778. std::string m_description;
  4779. explicit ParserRefImpl( std::shared_ptr<BoundRef> const &ref ) : m_ref( ref ) {}
  4780. public:
  4781. template<typename T>
  4782. ParserRefImpl( T &ref, std::string const &hint )
  4783. : m_ref( std::make_shared<BoundValueRef<T>>( ref ) ),
  4784. m_hint( hint )
  4785. {}
  4786. template<typename LambdaT>
  4787. ParserRefImpl( LambdaT const &ref, std::string const &hint )
  4788. : m_ref( std::make_shared<BoundLambda<LambdaT>>( ref ) ),
  4789. m_hint(hint)
  4790. {}
  4791. auto operator()( std::string const &description ) -> DerivedT & {
  4792. m_description = description;
  4793. return static_cast<DerivedT &>( *this );
  4794. }
  4795. auto optional() -> DerivedT & {
  4796. m_optionality = Optionality::Optional;
  4797. return static_cast<DerivedT &>( *this );
  4798. };
  4799. auto required() -> DerivedT & {
  4800. m_optionality = Optionality::Required;
  4801. return static_cast<DerivedT &>( *this );
  4802. };
  4803. auto isOptional() const -> bool {
  4804. return m_optionality == Optionality::Optional;
  4805. }
  4806. auto cardinality() const -> size_t override {
  4807. if( m_ref->isContainer() )
  4808. return 0;
  4809. else
  4810. return 1;
  4811. }
  4812. auto hint() const -> std::string { return m_hint; }
  4813. };
  4814. class ExeName : public ComposableParserImpl<ExeName> {
  4815. std::shared_ptr<std::string> m_name;
  4816. std::shared_ptr<BoundValueRefBase> m_ref;
  4817. template<typename LambdaT>
  4818. static auto makeRef(LambdaT const &lambda) -> std::shared_ptr<BoundValueRefBase> {
  4819. return std::make_shared<BoundLambda<LambdaT>>( lambda) ;
  4820. }
  4821. public:
  4822. ExeName() : m_name( std::make_shared<std::string>( "<executable>" ) ) {}
  4823. explicit ExeName( std::string &ref ) : ExeName() {
  4824. m_ref = std::make_shared<BoundValueRef<std::string>>( ref );
  4825. }
  4826. template<typename LambdaT>
  4827. explicit ExeName( LambdaT const& lambda ) : ExeName() {
  4828. m_ref = std::make_shared<BoundLambda<LambdaT>>( lambda );
  4829. }
  4830. // The exe name is not parsed out of the normal tokens, but is handled specially
  4831. auto parse( std::string const&, TokenStream const &tokens ) const -> InternalParseResult override {
  4832. return InternalParseResult::ok( ParseState( ParseResultType::NoMatch, tokens ) );
  4833. }
  4834. auto name() const -> std::string { return *m_name; }
  4835. auto set( std::string const& newName ) -> ParserResult {
  4836. auto lastSlash = newName.find_last_of( "\\/" );
  4837. auto filename = ( lastSlash == std::string::npos )
  4838. ? newName
  4839. : newName.substr( lastSlash+1 );
  4840. *m_name = filename;
  4841. if( m_ref )
  4842. return m_ref->setValue( filename );
  4843. else
  4844. return ParserResult::ok( ParseResultType::Matched );
  4845. }
  4846. };
  4847. class Arg : public ParserRefImpl<Arg> {
  4848. public:
  4849. using ParserRefImpl::ParserRefImpl;
  4850. auto parse( std::string const &, TokenStream const &tokens ) const -> InternalParseResult override {
  4851. auto validationResult = validate();
  4852. if( !validationResult )
  4853. return InternalParseResult( validationResult );
  4854. auto remainingTokens = tokens;
  4855. auto const &token = *remainingTokens;
  4856. if( token.type != TokenType::Argument )
  4857. return InternalParseResult::ok( ParseState( ParseResultType::NoMatch, remainingTokens ) );
  4858. assert( !m_ref->isFlag() );
  4859. auto valueRef = static_cast<detail::BoundValueRefBase*>( m_ref.get() );
  4860. auto result = valueRef->setValue( remainingTokens->token );
  4861. if( !result )
  4862. return InternalParseResult( result );
  4863. else
  4864. return InternalParseResult::ok( ParseState( ParseResultType::Matched, ++remainingTokens ) );
  4865. }
  4866. };
  4867. inline auto normaliseOpt( std::string const &optName ) -> std::string {
  4868. #ifdef CATCH_PLATFORM_WINDOWS
  4869. if( optName[0] == '/' )
  4870. return "-" + optName.substr( 1 );
  4871. else
  4872. #endif
  4873. return optName;
  4874. }
  4875. class Opt : public ParserRefImpl<Opt> {
  4876. protected:
  4877. std::vector<std::string> m_optNames;
  4878. public:
  4879. template<typename LambdaT>
  4880. explicit Opt( LambdaT const &ref ) : ParserRefImpl( std::make_shared<BoundFlagLambda<LambdaT>>( ref ) ) {}
  4881. explicit Opt( bool &ref ) : ParserRefImpl( std::make_shared<BoundFlagRef>( ref ) ) {}
  4882. template<typename LambdaT>
  4883. Opt( LambdaT const &ref, std::string const &hint ) : ParserRefImpl( ref, hint ) {}
  4884. template<typename T>
  4885. Opt( T &ref, std::string const &hint ) : ParserRefImpl( ref, hint ) {}
  4886. auto operator[]( std::string const &optName ) -> Opt & {
  4887. m_optNames.push_back( optName );
  4888. return *this;
  4889. }
  4890. auto getHelpColumns() const -> std::vector<HelpColumns> {
  4891. std::ostringstream oss;
  4892. bool first = true;
  4893. for( auto const &opt : m_optNames ) {
  4894. if (first)
  4895. first = false;
  4896. else
  4897. oss << ", ";
  4898. oss << opt;
  4899. }
  4900. if( !m_hint.empty() )
  4901. oss << " <" << m_hint << ">";
  4902. return { { oss.str(), m_description } };
  4903. }
  4904. auto isMatch( std::string const &optToken ) const -> bool {
  4905. auto normalisedToken = normaliseOpt( optToken );
  4906. for( auto const &name : m_optNames ) {
  4907. if( normaliseOpt( name ) == normalisedToken )
  4908. return true;
  4909. }
  4910. return false;
  4911. }
  4912. using ParserBase::parse;
  4913. auto parse( std::string const&, TokenStream const &tokens ) const -> InternalParseResult override {
  4914. auto validationResult = validate();
  4915. if( !validationResult )
  4916. return InternalParseResult( validationResult );
  4917. auto remainingTokens = tokens;
  4918. if( remainingTokens && remainingTokens->type == TokenType::Option ) {
  4919. auto const &token = *remainingTokens;
  4920. if( isMatch(token.token ) ) {
  4921. if( m_ref->isFlag() ) {
  4922. auto flagRef = static_cast<detail::BoundFlagRefBase*>( m_ref.get() );
  4923. auto result = flagRef->setFlag( true );
  4924. if( !result )
  4925. return InternalParseResult( result );
  4926. if( result.value() == ParseResultType::ShortCircuitAll )
  4927. return InternalParseResult::ok( ParseState( result.value(), remainingTokens ) );
  4928. } else {
  4929. auto valueRef = static_cast<detail::BoundValueRefBase*>( m_ref.get() );
  4930. ++remainingTokens;
  4931. if( !remainingTokens )
  4932. return InternalParseResult::runtimeError( "Expected argument following " + token.token );
  4933. auto const &argToken = *remainingTokens;
  4934. if( argToken.type != TokenType::Argument )
  4935. return InternalParseResult::runtimeError( "Expected argument following " + token.token );
  4936. auto result = valueRef->setValue( argToken.token );
  4937. if( !result )
  4938. return InternalParseResult( result );
  4939. if( result.value() == ParseResultType::ShortCircuitAll )
  4940. return InternalParseResult::ok( ParseState( result.value(), remainingTokens ) );
  4941. }
  4942. return InternalParseResult::ok( ParseState( ParseResultType::Matched, ++remainingTokens ) );
  4943. }
  4944. }
  4945. return InternalParseResult::ok( ParseState( ParseResultType::NoMatch, remainingTokens ) );
  4946. }
  4947. auto validate() const -> Result override {
  4948. if( m_optNames.empty() )
  4949. return Result::logicError( "No options supplied to Opt" );
  4950. for( auto const &name : m_optNames ) {
  4951. if( name.empty() )
  4952. return Result::logicError( "Option name cannot be empty" );
  4953. #ifdef CATCH_PLATFORM_WINDOWS
  4954. if( name[0] != '-' && name[0] != '/' )
  4955. return Result::logicError( "Option name must begin with '-' or '/'" );
  4956. #else
  4957. if( name[0] != '-' )
  4958. return Result::logicError( "Option name must begin with '-'" );
  4959. #endif
  4960. }
  4961. return ParserRefImpl::validate();
  4962. }
  4963. };
  4964. struct Help : Opt {
  4965. Help( bool &showHelpFlag )
  4966. : Opt([&]( bool flag ) {
  4967. showHelpFlag = flag;
  4968. return ParserResult::ok( ParseResultType::ShortCircuitAll );
  4969. })
  4970. {
  4971. static_cast<Opt &>( *this )
  4972. ("display usage information")
  4973. ["-?"]["-h"]["--help"]
  4974. .optional();
  4975. }
  4976. };
  4977. struct Parser : ParserBase {
  4978. mutable ExeName m_exeName;
  4979. std::vector<Opt> m_options;
  4980. std::vector<Arg> m_args;
  4981. auto operator|=( ExeName const &exeName ) -> Parser & {
  4982. m_exeName = exeName;
  4983. return *this;
  4984. }
  4985. auto operator|=( Arg const &arg ) -> Parser & {
  4986. m_args.push_back(arg);
  4987. return *this;
  4988. }
  4989. auto operator|=( Opt const &opt ) -> Parser & {
  4990. m_options.push_back(opt);
  4991. return *this;
  4992. }
  4993. auto operator|=( Parser const &other ) -> Parser & {
  4994. m_options.insert(m_options.end(), other.m_options.begin(), other.m_options.end());
  4995. m_args.insert(m_args.end(), other.m_args.begin(), other.m_args.end());
  4996. return *this;
  4997. }
  4998. template<typename T>
  4999. auto operator|( T const &other ) const -> Parser {
  5000. return Parser( *this ) |= other;
  5001. }
  5002. // Forward deprecated interface with '+' instead of '|'
  5003. template<typename T>
  5004. auto operator+=( T const &other ) -> Parser & { return operator|=( other ); }
  5005. template<typename T>
  5006. auto operator+( T const &other ) const -> Parser { return operator|( other ); }
  5007. auto getHelpColumns() const -> std::vector<HelpColumns> {
  5008. std::vector<HelpColumns> cols;
  5009. for (auto const &o : m_options) {
  5010. auto childCols = o.getHelpColumns();
  5011. cols.insert( cols.end(), childCols.begin(), childCols.end() );
  5012. }
  5013. return cols;
  5014. }
  5015. void writeToStream( std::ostream &os ) const {
  5016. if (!m_exeName.name().empty()) {
  5017. os << "usage:\n" << " " << m_exeName.name() << " ";
  5018. bool required = true, first = true;
  5019. for( auto const &arg : m_args ) {
  5020. if (first)
  5021. first = false;
  5022. else
  5023. os << " ";
  5024. if( arg.isOptional() && required ) {
  5025. os << "[";
  5026. required = false;
  5027. }
  5028. os << "<" << arg.hint() << ">";
  5029. if( arg.cardinality() == 0 )
  5030. os << " ... ";
  5031. }
  5032. if( !required )
  5033. os << "]";
  5034. if( !m_options.empty() )
  5035. os << " options";
  5036. os << "\n\nwhere options are:" << std::endl;
  5037. }
  5038. auto rows = getHelpColumns();
  5039. size_t consoleWidth = CATCH_CLARA_CONFIG_CONSOLE_WIDTH;
  5040. size_t optWidth = 0;
  5041. for( auto const &cols : rows )
  5042. optWidth = (std::max)(optWidth, cols.left.size() + 2);
  5043. optWidth = (std::min)(optWidth, consoleWidth/2);
  5044. for( auto const &cols : rows ) {
  5045. auto row =
  5046. TextFlow::Column( cols.left ).width( optWidth ).indent( 2 ) +
  5047. TextFlow::Spacer(4) +
  5048. TextFlow::Column( cols.right ).width( consoleWidth - 7 - optWidth );
  5049. os << row << std::endl;
  5050. }
  5051. }
  5052. friend auto operator<<( std::ostream &os, Parser const &parser ) -> std::ostream& {
  5053. parser.writeToStream( os );
  5054. return os;
  5055. }
  5056. auto validate() const -> Result override {
  5057. for( auto const &opt : m_options ) {
  5058. auto result = opt.validate();
  5059. if( !result )
  5060. return result;
  5061. }
  5062. for( auto const &arg : m_args ) {
  5063. auto result = arg.validate();
  5064. if( !result )
  5065. return result;
  5066. }
  5067. return Result::ok();
  5068. }
  5069. using ParserBase::parse;
  5070. auto parse( std::string const& exeName, TokenStream const &tokens ) const -> InternalParseResult override {
  5071. struct ParserInfo {
  5072. ParserBase const* parser = nullptr;
  5073. size_t count = 0;
  5074. };
  5075. const size_t totalParsers = m_options.size() + m_args.size();
  5076. assert( totalParsers < 512 );
  5077. // ParserInfo parseInfos[totalParsers]; // <-- this is what we really want to do
  5078. ParserInfo parseInfos[512];
  5079. {
  5080. size_t i = 0;
  5081. for (auto const &opt : m_options) parseInfos[i++].parser = &opt;
  5082. for (auto const &arg : m_args) parseInfos[i++].parser = &arg;
  5083. }
  5084. m_exeName.set( exeName );
  5085. auto result = InternalParseResult::ok( ParseState( ParseResultType::NoMatch, tokens ) );
  5086. while( result.value().remainingTokens() ) {
  5087. bool tokenParsed = false;
  5088. for( size_t i = 0; i < totalParsers; ++i ) {
  5089. auto& parseInfo = parseInfos[i];
  5090. if( parseInfo.parser->cardinality() == 0 || parseInfo.count < parseInfo.parser->cardinality() ) {
  5091. result = parseInfo.parser->parse(exeName, result.value().remainingTokens());
  5092. if (!result)
  5093. return result;
  5094. if (result.value().type() != ParseResultType::NoMatch) {
  5095. tokenParsed = true;
  5096. ++parseInfo.count;
  5097. break;
  5098. }
  5099. }
  5100. }
  5101. if( result.value().type() == ParseResultType::ShortCircuitAll )
  5102. return result;
  5103. if( !tokenParsed )
  5104. return InternalParseResult::runtimeError( "Unrecognised token: " + result.value().remainingTokens()->token );
  5105. }
  5106. // !TBD Check missing required options
  5107. return result;
  5108. }
  5109. };
  5110. template<typename DerivedT>
  5111. template<typename T>
  5112. auto ComposableParserImpl<DerivedT>::operator|( T const &other ) const -> Parser {
  5113. return Parser() | static_cast<DerivedT const &>( *this ) | other;
  5114. }
  5115. } // namespace detail
  5116. // A Combined parser
  5117. using detail::Parser;
  5118. // A parser for options
  5119. using detail::Opt;
  5120. // A parser for arguments
  5121. using detail::Arg;
  5122. // Wrapper for argc, argv from main()
  5123. using detail::Args;
  5124. // Specifies the name of the executable
  5125. using detail::ExeName;
  5126. // Convenience wrapper for option parser that specifies the help option
  5127. using detail::Help;
  5128. // enum of result types from a parse
  5129. using detail::ParseResultType;
  5130. // Result type for parser operation
  5131. using detail::ParserResult;
  5132. }} // namespace Catch::clara
  5133. // end clara.hpp
  5134. #ifdef __clang__
  5135. #pragma clang diagnostic pop
  5136. #endif
  5137. // Restore Clara's value for console width, if present
  5138. #ifdef CATCH_TEMP_CLARA_CONFIG_CONSOLE_WIDTH
  5139. #define CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH CATCH_TEMP_CLARA_CONFIG_CONSOLE_WIDTH
  5140. #undef CATCH_TEMP_CLARA_CONFIG_CONSOLE_WIDTH
  5141. #endif
  5142. // end catch_clara.h
  5143. namespace Catch {
  5144. clara::Parser makeCommandLineParser( ConfigData& config );
  5145. } // end namespace Catch
  5146. // end catch_commandline.h
  5147. #include <fstream>
  5148. #include <ctime>
  5149. namespace Catch {
  5150. clara::Parser makeCommandLineParser( ConfigData& config ) {
  5151. using namespace clara;
  5152. auto const setWarning = [&]( std::string const& warning ) {
  5153. auto warningSet = [&]() {
  5154. if( warning == "NoAssertions" )
  5155. return WarnAbout::NoAssertions;
  5156. if ( warning == "NoTests" )
  5157. return WarnAbout::NoTests;
  5158. return WarnAbout::Nothing;
  5159. }();
  5160. if (warningSet == WarnAbout::Nothing)
  5161. return ParserResult::runtimeError( "Unrecognised warning: '" + warning + "'" );
  5162. config.warnings = static_cast<WarnAbout::What>( config.warnings | warningSet );
  5163. return ParserResult::ok( ParseResultType::Matched );
  5164. };
  5165. auto const loadTestNamesFromFile = [&]( std::string const& filename ) {
  5166. std::ifstream f( filename.c_str() );
  5167. if( !f.is_open() )
  5168. return ParserResult::runtimeError( "Unable to load input file: '" + filename + "'" );
  5169. std::string line;
  5170. while( std::getline( f, line ) ) {
  5171. line = trim(line);
  5172. if( !line.empty() && !startsWith( line, '#' ) ) {
  5173. if( !startsWith( line, '"' ) )
  5174. line = '"' + line + '"';
  5175. config.testsOrTags.push_back( line + ',' );
  5176. }
  5177. }
  5178. return ParserResult::ok( ParseResultType::Matched );
  5179. };
  5180. auto const setTestOrder = [&]( std::string const& order ) {
  5181. if( startsWith( "declared", order ) )
  5182. config.runOrder = RunTests::InDeclarationOrder;
  5183. else if( startsWith( "lexical", order ) )
  5184. config.runOrder = RunTests::InLexicographicalOrder;
  5185. else if( startsWith( "random", order ) )
  5186. config.runOrder = RunTests::InRandomOrder;
  5187. else
  5188. return clara::ParserResult::runtimeError( "Unrecognised ordering: '" + order + "'" );
  5189. return ParserResult::ok( ParseResultType::Matched );
  5190. };
  5191. auto const setRngSeed = [&]( std::string const& seed ) {
  5192. if( seed != "time" )
  5193. return clara::detail::convertInto( seed, config.rngSeed );
  5194. config.rngSeed = static_cast<unsigned int>( std::time(nullptr) );
  5195. return ParserResult::ok( ParseResultType::Matched );
  5196. };
  5197. auto const setColourUsage = [&]( std::string const& useColour ) {
  5198. auto mode = toLower( useColour );
  5199. if( mode == "yes" )
  5200. config.useColour = UseColour::Yes;
  5201. else if( mode == "no" )
  5202. config.useColour = UseColour::No;
  5203. else if( mode == "auto" )
  5204. config.useColour = UseColour::Auto;
  5205. else
  5206. return ParserResult::runtimeError( "colour mode must be one of: auto, yes or no. '" + useColour + "' not recognised" );
  5207. return ParserResult::ok( ParseResultType::Matched );
  5208. };
  5209. auto const setWaitForKeypress = [&]( std::string const& keypress ) {
  5210. auto keypressLc = toLower( keypress );
  5211. if( keypressLc == "start" )
  5212. config.waitForKeypress = WaitForKeypress::BeforeStart;
  5213. else if( keypressLc == "exit" )
  5214. config.waitForKeypress = WaitForKeypress::BeforeExit;
  5215. else if( keypressLc == "both" )
  5216. config.waitForKeypress = WaitForKeypress::BeforeStartAndExit;
  5217. else
  5218. return ParserResult::runtimeError( "keypress argument must be one of: start, exit or both. '" + keypress + "' not recognised" );
  5219. return ParserResult::ok( ParseResultType::Matched );
  5220. };
  5221. auto const setVerbosity = [&]( std::string const& verbosity ) {
  5222. auto lcVerbosity = toLower( verbosity );
  5223. if( lcVerbosity == "quiet" )
  5224. config.verbosity = Verbosity::Quiet;
  5225. else if( lcVerbosity == "normal" )
  5226. config.verbosity = Verbosity::Normal;
  5227. else if( lcVerbosity == "high" )
  5228. config.verbosity = Verbosity::High;
  5229. else
  5230. return ParserResult::runtimeError( "Unrecognised verbosity, '" + verbosity + "'" );
  5231. return ParserResult::ok( ParseResultType::Matched );
  5232. };
  5233. auto cli
  5234. = ExeName( config.processName )
  5235. | Help( config.showHelp )
  5236. | Opt( config.listTests )
  5237. ["-l"]["--list-tests"]
  5238. ( "list all/matching test cases" )
  5239. | Opt( config.listTags )
  5240. ["-t"]["--list-tags"]
  5241. ( "list all/matching tags" )
  5242. | Opt( config.showSuccessfulTests )
  5243. ["-s"]["--success"]
  5244. ( "include successful tests in output" )
  5245. | Opt( config.shouldDebugBreak )
  5246. ["-b"]["--break"]
  5247. ( "break into debugger on failure" )
  5248. | Opt( config.noThrow )
  5249. ["-e"]["--nothrow"]
  5250. ( "skip exception tests" )
  5251. | Opt( config.showInvisibles )
  5252. ["-i"]["--invisibles"]
  5253. ( "show invisibles (tabs, newlines)" )
  5254. | Opt( config.outputFilename, "filename" )
  5255. ["-o"]["--out"]
  5256. ( "output filename" )
  5257. | Opt( config.reporterNames, "name" )
  5258. ["-r"]["--reporter"]
  5259. ( "reporter to use (defaults to console)" )
  5260. | Opt( config.name, "name" )
  5261. ["-n"]["--name"]
  5262. ( "suite name" )
  5263. | Opt( [&]( bool ){ config.abortAfter = 1; } )
  5264. ["-a"]["--abort"]
  5265. ( "abort at first failure" )
  5266. | Opt( [&]( int x ){ config.abortAfter = x; }, "no. failures" )
  5267. ["-x"]["--abortx"]
  5268. ( "abort after x failures" )
  5269. | Opt( setWarning, "warning name" )
  5270. ["-w"]["--warn"]
  5271. ( "enable warnings" )
  5272. | Opt( [&]( bool flag ) { config.showDurations = flag ? ShowDurations::Always : ShowDurations::Never; }, "yes|no" )
  5273. ["-d"]["--durations"]
  5274. ( "show test durations" )
  5275. | Opt( loadTestNamesFromFile, "filename" )
  5276. ["-f"]["--input-file"]
  5277. ( "load test names to run from a file" )
  5278. | Opt( config.filenamesAsTags )
  5279. ["-#"]["--filenames-as-tags"]
  5280. ( "adds a tag for the filename" )
  5281. | Opt( config.sectionsToRun, "section name" )
  5282. ["-c"]["--section"]
  5283. ( "specify section to run" )
  5284. | Opt( setVerbosity, "quiet|normal|high" )
  5285. ["-v"]["--verbosity"]
  5286. ( "set output verbosity" )
  5287. | Opt( config.listTestNamesOnly )
  5288. ["--list-test-names-only"]
  5289. ( "list all/matching test cases names only" )
  5290. | Opt( config.listReporters )
  5291. ["--list-reporters"]
  5292. ( "list all reporters" )
  5293. | Opt( setTestOrder, "decl|lex|rand" )
  5294. ["--order"]
  5295. ( "test case order (defaults to decl)" )
  5296. | Opt( setRngSeed, "'time'|number" )
  5297. ["--rng-seed"]
  5298. ( "set a specific seed for random numbers" )
  5299. | Opt( setColourUsage, "yes|no" )
  5300. ["--use-colour"]
  5301. ( "should output be colourised" )
  5302. | Opt( config.libIdentify )
  5303. ["--libidentify"]
  5304. ( "report name and version according to libidentify standard" )
  5305. | Opt( setWaitForKeypress, "start|exit|both" )
  5306. ["--wait-for-keypress"]
  5307. ( "waits for a keypress before exiting" )
  5308. | Opt( config.benchmarkResolutionMultiple, "multiplier" )
  5309. ["--benchmark-resolution-multiple"]
  5310. ( "multiple of clock resolution to run benchmarks" )
  5311. | Arg( config.testsOrTags, "test name|pattern|tags" )
  5312. ( "which test or tests to use" );
  5313. return cli;
  5314. }
  5315. } // end namespace Catch
  5316. // end catch_commandline.cpp
  5317. // start catch_common.cpp
  5318. #include <cstring>
  5319. #include <ostream>
  5320. namespace Catch {
  5321. bool SourceLineInfo::empty() const noexcept {
  5322. return file[0] == '\0';
  5323. }
  5324. bool SourceLineInfo::operator == ( SourceLineInfo const& other ) const noexcept {
  5325. return line == other.line && (file == other.file || std::strcmp(file, other.file) == 0);
  5326. }
  5327. bool SourceLineInfo::operator < ( SourceLineInfo const& other ) const noexcept {
  5328. return line < other.line || ( line == other.line && (std::strcmp(file, other.file) < 0));
  5329. }
  5330. std::ostream& operator << ( std::ostream& os, SourceLineInfo const& info ) {
  5331. #ifndef __GNUG__
  5332. os << info.file << '(' << info.line << ')';
  5333. #else
  5334. os << info.file << ':' << info.line;
  5335. #endif
  5336. return os;
  5337. }
  5338. std::string StreamEndStop::operator+() const {
  5339. return std::string();
  5340. }
  5341. NonCopyable::NonCopyable() = default;
  5342. NonCopyable::~NonCopyable() = default;
  5343. }
  5344. // end catch_common.cpp
  5345. // start catch_config.cpp
  5346. // start catch_enforce.h
  5347. #include <stdexcept>
  5348. #define CATCH_PREPARE_EXCEPTION( type, msg ) \
  5349. type( ( Catch::ReusableStringStream() << msg ).str() )
  5350. #define CATCH_INTERNAL_ERROR( msg ) \
  5351. throw CATCH_PREPARE_EXCEPTION( std::logic_error, CATCH_INTERNAL_LINEINFO << ": Internal Catch error: " << msg);
  5352. #define CATCH_ERROR( msg ) \
  5353. throw CATCH_PREPARE_EXCEPTION( std::domain_error, msg )
  5354. #define CATCH_ENFORCE( condition, msg ) \
  5355. do{ if( !(condition) ) CATCH_ERROR( msg ); } while(false)
  5356. // end catch_enforce.h
  5357. namespace Catch {
  5358. Config::Config( ConfigData const& data )
  5359. : m_data( data ),
  5360. m_stream( openStream() )
  5361. {
  5362. TestSpecParser parser(ITagAliasRegistry::get());
  5363. if (data.testsOrTags.empty()) {
  5364. parser.parse("~[.]"); // All not hidden tests
  5365. }
  5366. else {
  5367. m_hasTestFilters = true;
  5368. for( auto const& testOrTags : data.testsOrTags )
  5369. parser.parse( testOrTags );
  5370. }
  5371. m_testSpec = parser.testSpec();
  5372. }
  5373. std::string const& Config::getFilename() const {
  5374. return m_data.outputFilename ;
  5375. }
  5376. bool Config::listTests() const { return m_data.listTests; }
  5377. bool Config::listTestNamesOnly() const { return m_data.listTestNamesOnly; }
  5378. bool Config::listTags() const { return m_data.listTags; }
  5379. bool Config::listReporters() const { return m_data.listReporters; }
  5380. std::string Config::getProcessName() const { return m_data.processName; }
  5381. std::vector<std::string> const& Config::getReporterNames() const { return m_data.reporterNames; }
  5382. std::vector<std::string> const& Config::getTestsOrTags() const { return m_data.testsOrTags; }
  5383. std::vector<std::string> const& Config::getSectionsToRun() const { return m_data.sectionsToRun; }
  5384. TestSpec const& Config::testSpec() const { return m_testSpec; }
  5385. bool Config::hasTestFilters() const { return m_hasTestFilters; }
  5386. bool Config::showHelp() const { return m_data.showHelp; }
  5387. // IConfig interface
  5388. bool Config::allowThrows() const { return !m_data.noThrow; }
  5389. std::ostream& Config::stream() const { return m_stream->stream(); }
  5390. std::string Config::name() const { return m_data.name.empty() ? m_data.processName : m_data.name; }
  5391. bool Config::includeSuccessfulResults() const { return m_data.showSuccessfulTests; }
  5392. bool Config::warnAboutMissingAssertions() const { return !!(m_data.warnings & WarnAbout::NoAssertions); }
  5393. bool Config::warnAboutNoTests() const { return !!(m_data.warnings & WarnAbout::NoTests); }
  5394. ShowDurations::OrNot Config::showDurations() const { return m_data.showDurations; }
  5395. RunTests::InWhatOrder Config::runOrder() const { return m_data.runOrder; }
  5396. unsigned int Config::rngSeed() const { return m_data.rngSeed; }
  5397. int Config::benchmarkResolutionMultiple() const { return m_data.benchmarkResolutionMultiple; }
  5398. UseColour::YesOrNo Config::useColour() const { return m_data.useColour; }
  5399. bool Config::shouldDebugBreak() const { return m_data.shouldDebugBreak; }
  5400. int Config::abortAfter() const { return m_data.abortAfter; }
  5401. bool Config::showInvisibles() const { return m_data.showInvisibles; }
  5402. Verbosity Config::verbosity() const { return m_data.verbosity; }
  5403. IStream const* Config::openStream() {
  5404. return Catch::makeStream(m_data.outputFilename);
  5405. }
  5406. } // end namespace Catch
  5407. // end catch_config.cpp
  5408. // start catch_console_colour.cpp
  5409. #if defined(__clang__)
  5410. # pragma clang diagnostic push
  5411. # pragma clang diagnostic ignored "-Wexit-time-destructors"
  5412. #endif
  5413. // start catch_errno_guard.h
  5414. namespace Catch {
  5415. class ErrnoGuard {
  5416. public:
  5417. ErrnoGuard();
  5418. ~ErrnoGuard();
  5419. private:
  5420. int m_oldErrno;
  5421. };
  5422. }
  5423. // end catch_errno_guard.h
  5424. #include <sstream>
  5425. namespace Catch {
  5426. namespace {
  5427. struct IColourImpl {
  5428. virtual ~IColourImpl() = default;
  5429. virtual void use( Colour::Code _colourCode ) = 0;
  5430. };
  5431. struct NoColourImpl : IColourImpl {
  5432. void use( Colour::Code ) {}
  5433. static IColourImpl* instance() {
  5434. static NoColourImpl s_instance;
  5435. return &s_instance;
  5436. }
  5437. };
  5438. } // anon namespace
  5439. } // namespace Catch
  5440. #if !defined( CATCH_CONFIG_COLOUR_NONE ) && !defined( CATCH_CONFIG_COLOUR_WINDOWS ) && !defined( CATCH_CONFIG_COLOUR_ANSI )
  5441. # ifdef CATCH_PLATFORM_WINDOWS
  5442. # define CATCH_CONFIG_COLOUR_WINDOWS
  5443. # else
  5444. # define CATCH_CONFIG_COLOUR_ANSI
  5445. # endif
  5446. #endif
  5447. #if defined ( CATCH_CONFIG_COLOUR_WINDOWS ) /////////////////////////////////////////
  5448. namespace Catch {
  5449. namespace {
  5450. class Win32ColourImpl : public IColourImpl {
  5451. public:
  5452. Win32ColourImpl() : stdoutHandle( GetStdHandle(STD_OUTPUT_HANDLE) )
  5453. {
  5454. CONSOLE_SCREEN_BUFFER_INFO csbiInfo;
  5455. GetConsoleScreenBufferInfo( stdoutHandle, &csbiInfo );
  5456. originalForegroundAttributes = csbiInfo.wAttributes & ~( BACKGROUND_GREEN | BACKGROUND_RED | BACKGROUND_BLUE | BACKGROUND_INTENSITY );
  5457. originalBackgroundAttributes = csbiInfo.wAttributes & ~( FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_BLUE | FOREGROUND_INTENSITY );
  5458. }
  5459. virtual void use( Colour::Code _colourCode ) override {
  5460. switch( _colourCode ) {
  5461. case Colour::None: return setTextAttribute( originalForegroundAttributes );
  5462. case Colour::White: return setTextAttribute( FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_BLUE );
  5463. case Colour::Red: return setTextAttribute( FOREGROUND_RED );
  5464. case Colour::Green: return setTextAttribute( FOREGROUND_GREEN );
  5465. case Colour::Blue: return setTextAttribute( FOREGROUND_BLUE );
  5466. case Colour::Cyan: return setTextAttribute( FOREGROUND_BLUE | FOREGROUND_GREEN );
  5467. case Colour::Yellow: return setTextAttribute( FOREGROUND_RED | FOREGROUND_GREEN );
  5468. case Colour::Grey: return setTextAttribute( 0 );
  5469. case Colour::LightGrey: return setTextAttribute( FOREGROUND_INTENSITY );
  5470. case Colour::BrightRed: return setTextAttribute( FOREGROUND_INTENSITY | FOREGROUND_RED );
  5471. case Colour::BrightGreen: return setTextAttribute( FOREGROUND_INTENSITY | FOREGROUND_GREEN );
  5472. case Colour::BrightWhite: return setTextAttribute( FOREGROUND_INTENSITY | FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_BLUE );
  5473. case Colour::BrightYellow: return setTextAttribute( FOREGROUND_INTENSITY | FOREGROUND_RED | FOREGROUND_GREEN );
  5474. case Colour::Bright: CATCH_INTERNAL_ERROR( "not a colour" );
  5475. default:
  5476. CATCH_ERROR( "Unknown colour requested" );
  5477. }
  5478. }
  5479. private:
  5480. void setTextAttribute( WORD _textAttribute ) {
  5481. SetConsoleTextAttribute( stdoutHandle, _textAttribute | originalBackgroundAttributes );
  5482. }
  5483. HANDLE stdoutHandle;
  5484. WORD originalForegroundAttributes;
  5485. WORD originalBackgroundAttributes;
  5486. };
  5487. IColourImpl* platformColourInstance() {
  5488. static Win32ColourImpl s_instance;
  5489. IConfigPtr config = getCurrentContext().getConfig();
  5490. UseColour::YesOrNo colourMode = config
  5491. ? config->useColour()
  5492. : UseColour::Auto;
  5493. if( colourMode == UseColour::Auto )
  5494. colourMode = UseColour::Yes;
  5495. return colourMode == UseColour::Yes
  5496. ? &s_instance
  5497. : NoColourImpl::instance();
  5498. }
  5499. } // end anon namespace
  5500. } // end namespace Catch
  5501. #elif defined( CATCH_CONFIG_COLOUR_ANSI ) //////////////////////////////////////
  5502. #include <unistd.h>
  5503. namespace Catch {
  5504. namespace {
  5505. // use POSIX/ ANSI console terminal codes
  5506. // Thanks to Adam Strzelecki for original contribution
  5507. // (http://github.com/nanoant)
  5508. // https://github.com/philsquared/Catch/pull/131
  5509. class PosixColourImpl : public IColourImpl {
  5510. public:
  5511. virtual void use( Colour::Code _colourCode ) override {
  5512. switch( _colourCode ) {
  5513. case Colour::None:
  5514. case Colour::White: return setColour( "[0m" );
  5515. case Colour::Red: return setColour( "[0;31m" );
  5516. case Colour::Green: return setColour( "[0;32m" );
  5517. case Colour::Blue: return setColour( "[0;34m" );
  5518. case Colour::Cyan: return setColour( "[0;36m" );
  5519. case Colour::Yellow: return setColour( "[0;33m" );
  5520. case Colour::Grey: return setColour( "[1;30m" );
  5521. case Colour::LightGrey: return setColour( "[0;37m" );
  5522. case Colour::BrightRed: return setColour( "[1;31m" );
  5523. case Colour::BrightGreen: return setColour( "[1;32m" );
  5524. case Colour::BrightWhite: return setColour( "[1;37m" );
  5525. case Colour::BrightYellow: return setColour( "[1;33m" );
  5526. case Colour::Bright: CATCH_INTERNAL_ERROR( "not a colour" );
  5527. default: CATCH_INTERNAL_ERROR( "Unknown colour requested" );
  5528. }
  5529. }
  5530. static IColourImpl* instance() {
  5531. static PosixColourImpl s_instance;
  5532. return &s_instance;
  5533. }
  5534. private:
  5535. void setColour( const char* _escapeCode ) {
  5536. Catch::cout() << '\033' << _escapeCode;
  5537. }
  5538. };
  5539. bool useColourOnPlatform() {
  5540. return
  5541. #ifdef CATCH_PLATFORM_MAC
  5542. !isDebuggerActive() &&
  5543. #endif
  5544. #if !(defined(__DJGPP__) && defined(__STRICT_ANSI__))
  5545. isatty(STDOUT_FILENO)
  5546. #else
  5547. false
  5548. #endif
  5549. ;
  5550. }
  5551. IColourImpl* platformColourInstance() {
  5552. ErrnoGuard guard;
  5553. IConfigPtr config = getCurrentContext().getConfig();
  5554. UseColour::YesOrNo colourMode = config
  5555. ? config->useColour()
  5556. : UseColour::Auto;
  5557. if( colourMode == UseColour::Auto )
  5558. colourMode = useColourOnPlatform()
  5559. ? UseColour::Yes
  5560. : UseColour::No;
  5561. return colourMode == UseColour::Yes
  5562. ? PosixColourImpl::instance()
  5563. : NoColourImpl::instance();
  5564. }
  5565. } // end anon namespace
  5566. } // end namespace Catch
  5567. #else // not Windows or ANSI ///////////////////////////////////////////////
  5568. namespace Catch {
  5569. static IColourImpl* platformColourInstance() { return NoColourImpl::instance(); }
  5570. } // end namespace Catch
  5571. #endif // Windows/ ANSI/ None
  5572. namespace Catch {
  5573. Colour::Colour( Code _colourCode ) { use( _colourCode ); }
  5574. Colour::Colour( Colour&& rhs ) noexcept {
  5575. m_moved = rhs.m_moved;
  5576. rhs.m_moved = true;
  5577. }
  5578. Colour& Colour::operator=( Colour&& rhs ) noexcept {
  5579. m_moved = rhs.m_moved;
  5580. rhs.m_moved = true;
  5581. return *this;
  5582. }
  5583. Colour::~Colour(){ if( !m_moved ) use( None ); }
  5584. void Colour::use( Code _colourCode ) {
  5585. static IColourImpl* impl = platformColourInstance();
  5586. impl->use( _colourCode );
  5587. }
  5588. std::ostream& operator << ( std::ostream& os, Colour const& ) {
  5589. return os;
  5590. }
  5591. } // end namespace Catch
  5592. #if defined(__clang__)
  5593. # pragma clang diagnostic pop
  5594. #endif
  5595. // end catch_console_colour.cpp
  5596. // start catch_context.cpp
  5597. namespace Catch {
  5598. class Context : public IMutableContext, NonCopyable {
  5599. public: // IContext
  5600. virtual IResultCapture* getResultCapture() override {
  5601. return m_resultCapture;
  5602. }
  5603. virtual IRunner* getRunner() override {
  5604. return m_runner;
  5605. }
  5606. virtual IConfigPtr const& getConfig() const override {
  5607. return m_config;
  5608. }
  5609. virtual ~Context() override;
  5610. public: // IMutableContext
  5611. virtual void setResultCapture( IResultCapture* resultCapture ) override {
  5612. m_resultCapture = resultCapture;
  5613. }
  5614. virtual void setRunner( IRunner* runner ) override {
  5615. m_runner = runner;
  5616. }
  5617. virtual void setConfig( IConfigPtr const& config ) override {
  5618. m_config = config;
  5619. }
  5620. friend IMutableContext& getCurrentMutableContext();
  5621. private:
  5622. IConfigPtr m_config;
  5623. IRunner* m_runner = nullptr;
  5624. IResultCapture* m_resultCapture = nullptr;
  5625. };
  5626. IMutableContext *IMutableContext::currentContext = nullptr;
  5627. void IMutableContext::createContext()
  5628. {
  5629. currentContext = new Context();
  5630. }
  5631. void cleanUpContext() {
  5632. delete IMutableContext::currentContext;
  5633. IMutableContext::currentContext = nullptr;
  5634. }
  5635. IContext::~IContext() = default;
  5636. IMutableContext::~IMutableContext() = default;
  5637. Context::~Context() = default;
  5638. }
  5639. // end catch_context.cpp
  5640. // start catch_debug_console.cpp
  5641. // start catch_debug_console.h
  5642. #include <string>
  5643. namespace Catch {
  5644. void writeToDebugConsole( std::string const& text );
  5645. }
  5646. // end catch_debug_console.h
  5647. #ifdef CATCH_PLATFORM_WINDOWS
  5648. namespace Catch {
  5649. void writeToDebugConsole( std::string const& text ) {
  5650. ::OutputDebugStringA( text.c_str() );
  5651. }
  5652. }
  5653. #else
  5654. namespace Catch {
  5655. void writeToDebugConsole( std::string const& text ) {
  5656. // !TBD: Need a version for Mac/ XCode and other IDEs
  5657. Catch::cout() << text;
  5658. }
  5659. }
  5660. #endif // Platform
  5661. // end catch_debug_console.cpp
  5662. // start catch_debugger.cpp
  5663. #ifdef CATCH_PLATFORM_MAC
  5664. # include <assert.h>
  5665. # include <stdbool.h>
  5666. # include <sys/types.h>
  5667. # include <unistd.h>
  5668. # include <sys/sysctl.h>
  5669. # include <cstddef>
  5670. # include <ostream>
  5671. namespace Catch {
  5672. // The following function is taken directly from the following technical note:
  5673. // http://developer.apple.com/library/mac/#qa/qa2004/qa1361.html
  5674. // Returns true if the current process is being debugged (either
  5675. // running under the debugger or has a debugger attached post facto).
  5676. bool isDebuggerActive(){
  5677. int mib[4];
  5678. struct kinfo_proc info;
  5679. std::size_t size;
  5680. // Initialize the flags so that, if sysctl fails for some bizarre
  5681. // reason, we get a predictable result.
  5682. info.kp_proc.p_flag = 0;
  5683. // Initialize mib, which tells sysctl the info we want, in this case
  5684. // we're looking for information about a specific process ID.
  5685. mib[0] = CTL_KERN;
  5686. mib[1] = KERN_PROC;
  5687. mib[2] = KERN_PROC_PID;
  5688. mib[3] = getpid();
  5689. // Call sysctl.
  5690. size = sizeof(info);
  5691. if( sysctl(mib, sizeof(mib) / sizeof(*mib), &info, &size, nullptr, 0) != 0 ) {
  5692. Catch::cerr() << "\n** Call to sysctl failed - unable to determine if debugger is active **\n" << std::endl;
  5693. return false;
  5694. }
  5695. // We're being debugged if the P_TRACED flag is set.
  5696. return ( (info.kp_proc.p_flag & P_TRACED) != 0 );
  5697. }
  5698. } // namespace Catch
  5699. #elif defined(CATCH_PLATFORM_LINUX)
  5700. #include <fstream>
  5701. #include <string>
  5702. namespace Catch{
  5703. // The standard POSIX way of detecting a debugger is to attempt to
  5704. // ptrace() the process, but this needs to be done from a child and not
  5705. // this process itself to still allow attaching to this process later
  5706. // if wanted, so is rather heavy. Under Linux we have the PID of the
  5707. // "debugger" (which doesn't need to be gdb, of course, it could also
  5708. // be strace, for example) in /proc/$PID/status, so just get it from
  5709. // there instead.
  5710. bool isDebuggerActive(){
  5711. // Libstdc++ has a bug, where std::ifstream sets errno to 0
  5712. // This way our users can properly assert over errno values
  5713. ErrnoGuard guard;
  5714. std::ifstream in("/proc/self/status");
  5715. for( std::string line; std::getline(in, line); ) {
  5716. static const int PREFIX_LEN = 11;
  5717. if( line.compare(0, PREFIX_LEN, "TracerPid:\t") == 0 ) {
  5718. // We're traced if the PID is not 0 and no other PID starts
  5719. // with 0 digit, so it's enough to check for just a single
  5720. // character.
  5721. return line.length() > PREFIX_LEN && line[PREFIX_LEN] != '0';
  5722. }
  5723. }
  5724. return false;
  5725. }
  5726. } // namespace Catch
  5727. #elif defined(_MSC_VER)
  5728. extern "C" __declspec(dllimport) int __stdcall IsDebuggerPresent();
  5729. namespace Catch {
  5730. bool isDebuggerActive() {
  5731. return IsDebuggerPresent() != 0;
  5732. }
  5733. }
  5734. #elif defined(__MINGW32__)
  5735. extern "C" __declspec(dllimport) int __stdcall IsDebuggerPresent();
  5736. namespace Catch {
  5737. bool isDebuggerActive() {
  5738. return IsDebuggerPresent() != 0;
  5739. }
  5740. }
  5741. #else
  5742. namespace Catch {
  5743. bool isDebuggerActive() { return false; }
  5744. }
  5745. #endif // Platform
  5746. // end catch_debugger.cpp
  5747. // start catch_decomposer.cpp
  5748. namespace Catch {
  5749. ITransientExpression::~ITransientExpression() = default;
  5750. void formatReconstructedExpression( std::ostream &os, std::string const& lhs, StringRef op, std::string const& rhs ) {
  5751. if( lhs.size() + rhs.size() < 40 &&
  5752. lhs.find('\n') == std::string::npos &&
  5753. rhs.find('\n') == std::string::npos )
  5754. os << lhs << " " << op << " " << rhs;
  5755. else
  5756. os << lhs << "\n" << op << "\n" << rhs;
  5757. }
  5758. }
  5759. // end catch_decomposer.cpp
  5760. // start catch_errno_guard.cpp
  5761. #include <cerrno>
  5762. namespace Catch {
  5763. ErrnoGuard::ErrnoGuard():m_oldErrno(errno){}
  5764. ErrnoGuard::~ErrnoGuard() { errno = m_oldErrno; }
  5765. }
  5766. // end catch_errno_guard.cpp
  5767. // start catch_exception_translator_registry.cpp
  5768. // start catch_exception_translator_registry.h
  5769. #include <vector>
  5770. #include <string>
  5771. #include <memory>
  5772. namespace Catch {
  5773. class ExceptionTranslatorRegistry : public IExceptionTranslatorRegistry {
  5774. public:
  5775. ~ExceptionTranslatorRegistry();
  5776. virtual void registerTranslator( const IExceptionTranslator* translator );
  5777. virtual std::string translateActiveException() const override;
  5778. std::string tryTranslators() const;
  5779. private:
  5780. std::vector<std::unique_ptr<IExceptionTranslator const>> m_translators;
  5781. };
  5782. }
  5783. // end catch_exception_translator_registry.h
  5784. #ifdef __OBJC__
  5785. #import "Foundation/Foundation.h"
  5786. #endif
  5787. namespace Catch {
  5788. ExceptionTranslatorRegistry::~ExceptionTranslatorRegistry() {
  5789. }
  5790. void ExceptionTranslatorRegistry::registerTranslator( const IExceptionTranslator* translator ) {
  5791. m_translators.push_back( std::unique_ptr<const IExceptionTranslator>( translator ) );
  5792. }
  5793. std::string ExceptionTranslatorRegistry::translateActiveException() const {
  5794. try {
  5795. #ifdef __OBJC__
  5796. // In Objective-C try objective-c exceptions first
  5797. @try {
  5798. return tryTranslators();
  5799. }
  5800. @catch (NSException *exception) {
  5801. return Catch::Detail::stringify( [exception description] );
  5802. }
  5803. #else
  5804. // Compiling a mixed mode project with MSVC means that CLR
  5805. // exceptions will be caught in (...) as well. However, these
  5806. // do not fill-in std::current_exception and thus lead to crash
  5807. // when attempting rethrow.
  5808. // /EHa switch also causes structured exceptions to be caught
  5809. // here, but they fill-in current_exception properly, so
  5810. // at worst the output should be a little weird, instead of
  5811. // causing a crash.
  5812. if (std::current_exception() == nullptr) {
  5813. return "Non C++ exception. Possibly a CLR exception.";
  5814. }
  5815. return tryTranslators();
  5816. #endif
  5817. }
  5818. catch( TestFailureException& ) {
  5819. std::rethrow_exception(std::current_exception());
  5820. }
  5821. catch( std::exception& ex ) {
  5822. return ex.what();
  5823. }
  5824. catch( std::string& msg ) {
  5825. return msg;
  5826. }
  5827. catch( const char* msg ) {
  5828. return msg;
  5829. }
  5830. catch(...) {
  5831. return "Unknown exception";
  5832. }
  5833. }
  5834. std::string ExceptionTranslatorRegistry::tryTranslators() const {
  5835. if( m_translators.empty() )
  5836. std::rethrow_exception(std::current_exception());
  5837. else
  5838. return m_translators[0]->translate( m_translators.begin()+1, m_translators.end() );
  5839. }
  5840. }
  5841. // end catch_exception_translator_registry.cpp
  5842. // start catch_fatal_condition.cpp
  5843. #if defined(__GNUC__)
  5844. # pragma GCC diagnostic push
  5845. # pragma GCC diagnostic ignored "-Wmissing-field-initializers"
  5846. #endif
  5847. #if defined( CATCH_CONFIG_WINDOWS_SEH ) || defined( CATCH_CONFIG_POSIX_SIGNALS )
  5848. namespace {
  5849. // Report the error condition
  5850. void reportFatal( char const * const message ) {
  5851. Catch::getCurrentContext().getResultCapture()->handleFatalErrorCondition( message );
  5852. }
  5853. }
  5854. #endif // signals/SEH handling
  5855. #if defined( CATCH_CONFIG_WINDOWS_SEH )
  5856. namespace Catch {
  5857. struct SignalDefs { DWORD id; const char* name; };
  5858. // There is no 1-1 mapping between signals and windows exceptions.
  5859. // Windows can easily distinguish between SO and SigSegV,
  5860. // but SigInt, SigTerm, etc are handled differently.
  5861. static SignalDefs signalDefs[] = {
  5862. { EXCEPTION_ILLEGAL_INSTRUCTION, "SIGILL - Illegal instruction signal" },
  5863. { EXCEPTION_STACK_OVERFLOW, "SIGSEGV - Stack overflow" },
  5864. { EXCEPTION_ACCESS_VIOLATION, "SIGSEGV - Segmentation violation signal" },
  5865. { EXCEPTION_INT_DIVIDE_BY_ZERO, "Divide by zero error" },
  5866. };
  5867. LONG CALLBACK FatalConditionHandler::handleVectoredException(PEXCEPTION_POINTERS ExceptionInfo) {
  5868. for (auto const& def : signalDefs) {
  5869. if (ExceptionInfo->ExceptionRecord->ExceptionCode == def.id) {
  5870. reportFatal(def.name);
  5871. }
  5872. }
  5873. // If its not an exception we care about, pass it along.
  5874. // This stops us from eating debugger breaks etc.
  5875. return EXCEPTION_CONTINUE_SEARCH;
  5876. }
  5877. FatalConditionHandler::FatalConditionHandler() {
  5878. isSet = true;
  5879. // 32k seems enough for Catch to handle stack overflow,
  5880. // but the value was found experimentally, so there is no strong guarantee
  5881. guaranteeSize = 32 * 1024;
  5882. exceptionHandlerHandle = nullptr;
  5883. // Register as first handler in current chain
  5884. exceptionHandlerHandle = AddVectoredExceptionHandler(1, handleVectoredException);
  5885. // Pass in guarantee size to be filled
  5886. SetThreadStackGuarantee(&guaranteeSize);
  5887. }
  5888. void FatalConditionHandler::reset() {
  5889. if (isSet) {
  5890. RemoveVectoredExceptionHandler(exceptionHandlerHandle);
  5891. SetThreadStackGuarantee(&guaranteeSize);
  5892. exceptionHandlerHandle = nullptr;
  5893. isSet = false;
  5894. }
  5895. }
  5896. FatalConditionHandler::~FatalConditionHandler() {
  5897. reset();
  5898. }
  5899. bool FatalConditionHandler::isSet = false;
  5900. ULONG FatalConditionHandler::guaranteeSize = 0;
  5901. PVOID FatalConditionHandler::exceptionHandlerHandle = nullptr;
  5902. } // namespace Catch
  5903. #elif defined( CATCH_CONFIG_POSIX_SIGNALS )
  5904. namespace Catch {
  5905. struct SignalDefs {
  5906. int id;
  5907. const char* name;
  5908. };
  5909. static SignalDefs signalDefs[] = {
  5910. { SIGINT, "SIGINT - Terminal interrupt signal" },
  5911. { SIGILL, "SIGILL - Illegal instruction signal" },
  5912. { SIGFPE, "SIGFPE - Floating point error signal" },
  5913. { SIGSEGV, "SIGSEGV - Segmentation violation signal" },
  5914. { SIGTERM, "SIGTERM - Termination request signal" },
  5915. { SIGABRT, "SIGABRT - Abort (abnormal termination) signal" }
  5916. };
  5917. void FatalConditionHandler::handleSignal( int sig ) {
  5918. char const * name = "<unknown signal>";
  5919. for (auto const& def : signalDefs) {
  5920. if (sig == def.id) {
  5921. name = def.name;
  5922. break;
  5923. }
  5924. }
  5925. reset();
  5926. reportFatal(name);
  5927. raise( sig );
  5928. }
  5929. FatalConditionHandler::FatalConditionHandler() {
  5930. isSet = true;
  5931. stack_t sigStack;
  5932. sigStack.ss_sp = altStackMem;
  5933. sigStack.ss_size = SIGSTKSZ;
  5934. sigStack.ss_flags = 0;
  5935. sigaltstack(&sigStack, &oldSigStack);
  5936. struct sigaction sa = { };
  5937. sa.sa_handler = handleSignal;
  5938. sa.sa_flags = SA_ONSTACK;
  5939. for (std::size_t i = 0; i < sizeof(signalDefs)/sizeof(SignalDefs); ++i) {
  5940. sigaction(signalDefs[i].id, &sa, &oldSigActions[i]);
  5941. }
  5942. }
  5943. FatalConditionHandler::~FatalConditionHandler() {
  5944. reset();
  5945. }
  5946. void FatalConditionHandler::reset() {
  5947. if( isSet ) {
  5948. // Set signals back to previous values -- hopefully nobody overwrote them in the meantime
  5949. for( std::size_t i = 0; i < sizeof(signalDefs)/sizeof(SignalDefs); ++i ) {
  5950. sigaction(signalDefs[i].id, &oldSigActions[i], nullptr);
  5951. }
  5952. // Return the old stack
  5953. sigaltstack(&oldSigStack, nullptr);
  5954. isSet = false;
  5955. }
  5956. }
  5957. bool FatalConditionHandler::isSet = false;
  5958. struct sigaction FatalConditionHandler::oldSigActions[sizeof(signalDefs)/sizeof(SignalDefs)] = {};
  5959. stack_t FatalConditionHandler::oldSigStack = {};
  5960. char FatalConditionHandler::altStackMem[SIGSTKSZ] = {};
  5961. } // namespace Catch
  5962. #else
  5963. namespace Catch {
  5964. void FatalConditionHandler::reset() {}
  5965. }
  5966. #endif // signals/SEH handling
  5967. #if defined(__GNUC__)
  5968. # pragma GCC diagnostic pop
  5969. #endif
  5970. // end catch_fatal_condition.cpp
  5971. // start catch_interfaces_capture.cpp
  5972. namespace Catch {
  5973. IResultCapture::~IResultCapture() = default;
  5974. }
  5975. // end catch_interfaces_capture.cpp
  5976. // start catch_interfaces_config.cpp
  5977. namespace Catch {
  5978. IConfig::~IConfig() = default;
  5979. }
  5980. // end catch_interfaces_config.cpp
  5981. // start catch_interfaces_exception.cpp
  5982. namespace Catch {
  5983. IExceptionTranslator::~IExceptionTranslator() = default;
  5984. IExceptionTranslatorRegistry::~IExceptionTranslatorRegistry() = default;
  5985. }
  5986. // end catch_interfaces_exception.cpp
  5987. // start catch_interfaces_registry_hub.cpp
  5988. namespace Catch {
  5989. IRegistryHub::~IRegistryHub() = default;
  5990. IMutableRegistryHub::~IMutableRegistryHub() = default;
  5991. }
  5992. // end catch_interfaces_registry_hub.cpp
  5993. // start catch_interfaces_reporter.cpp
  5994. // start catch_reporter_multi.h
  5995. namespace Catch {
  5996. class MultipleReporters : public IStreamingReporter {
  5997. using Reporters = std::vector<IStreamingReporterPtr>;
  5998. Reporters m_reporters;
  5999. public:
  6000. void add( IStreamingReporterPtr&& reporter );
  6001. public: // IStreamingReporter
  6002. ReporterPreferences getPreferences() const override;
  6003. void noMatchingTestCases( std::string const& spec ) override;
  6004. static std::set<Verbosity> getSupportedVerbosities();
  6005. void benchmarkStarting( BenchmarkInfo const& benchmarkInfo ) override;
  6006. void benchmarkEnded( BenchmarkStats const& benchmarkStats ) override;
  6007. void testRunStarting( TestRunInfo const& testRunInfo ) override;
  6008. void testGroupStarting( GroupInfo const& groupInfo ) override;
  6009. void testCaseStarting( TestCaseInfo const& testInfo ) override;
  6010. void sectionStarting( SectionInfo const& sectionInfo ) override;
  6011. void assertionStarting( AssertionInfo const& assertionInfo ) override;
  6012. // The return value indicates if the messages buffer should be cleared:
  6013. bool assertionEnded( AssertionStats const& assertionStats ) override;
  6014. void sectionEnded( SectionStats const& sectionStats ) override;
  6015. void testCaseEnded( TestCaseStats const& testCaseStats ) override;
  6016. void testGroupEnded( TestGroupStats const& testGroupStats ) override;
  6017. void testRunEnded( TestRunStats const& testRunStats ) override;
  6018. void skipTest( TestCaseInfo const& testInfo ) override;
  6019. bool isMulti() const override;
  6020. };
  6021. } // end namespace Catch
  6022. // end catch_reporter_multi.h
  6023. namespace Catch {
  6024. ReporterConfig::ReporterConfig( IConfigPtr const& _fullConfig )
  6025. : m_stream( &_fullConfig->stream() ), m_fullConfig( _fullConfig ) {}
  6026. ReporterConfig::ReporterConfig( IConfigPtr const& _fullConfig, std::ostream& _stream )
  6027. : m_stream( &_stream ), m_fullConfig( _fullConfig ) {}
  6028. std::ostream& ReporterConfig::stream() const { return *m_stream; }
  6029. IConfigPtr ReporterConfig::fullConfig() const { return m_fullConfig; }
  6030. TestRunInfo::TestRunInfo( std::string const& _name ) : name( _name ) {}
  6031. GroupInfo::GroupInfo( std::string const& _name,
  6032. std::size_t _groupIndex,
  6033. std::size_t _groupsCount )
  6034. : name( _name ),
  6035. groupIndex( _groupIndex ),
  6036. groupsCounts( _groupsCount )
  6037. {}
  6038. AssertionStats::AssertionStats( AssertionResult const& _assertionResult,
  6039. std::vector<MessageInfo> const& _infoMessages,
  6040. Totals const& _totals )
  6041. : assertionResult( _assertionResult ),
  6042. infoMessages( _infoMessages ),
  6043. totals( _totals )
  6044. {
  6045. assertionResult.m_resultData.lazyExpression.m_transientExpression = _assertionResult.m_resultData.lazyExpression.m_transientExpression;
  6046. if( assertionResult.hasMessage() ) {
  6047. // Copy message into messages list.
  6048. // !TBD This should have been done earlier, somewhere
  6049. MessageBuilder builder( assertionResult.getTestMacroName(), assertionResult.getSourceInfo(), assertionResult.getResultType() );
  6050. builder << assertionResult.getMessage();
  6051. builder.m_info.message = builder.m_stream.str();
  6052. infoMessages.push_back( builder.m_info );
  6053. }
  6054. }
  6055. AssertionStats::~AssertionStats() = default;
  6056. SectionStats::SectionStats( SectionInfo const& _sectionInfo,
  6057. Counts const& _assertions,
  6058. double _durationInSeconds,
  6059. bool _missingAssertions )
  6060. : sectionInfo( _sectionInfo ),
  6061. assertions( _assertions ),
  6062. durationInSeconds( _durationInSeconds ),
  6063. missingAssertions( _missingAssertions )
  6064. {}
  6065. SectionStats::~SectionStats() = default;
  6066. TestCaseStats::TestCaseStats( TestCaseInfo const& _testInfo,
  6067. Totals const& _totals,
  6068. std::string const& _stdOut,
  6069. std::string const& _stdErr,
  6070. bool _aborting )
  6071. : testInfo( _testInfo ),
  6072. totals( _totals ),
  6073. stdOut( _stdOut ),
  6074. stdErr( _stdErr ),
  6075. aborting( _aborting )
  6076. {}
  6077. TestCaseStats::~TestCaseStats() = default;
  6078. TestGroupStats::TestGroupStats( GroupInfo const& _groupInfo,
  6079. Totals const& _totals,
  6080. bool _aborting )
  6081. : groupInfo( _groupInfo ),
  6082. totals( _totals ),
  6083. aborting( _aborting )
  6084. {}
  6085. TestGroupStats::TestGroupStats( GroupInfo const& _groupInfo )
  6086. : groupInfo( _groupInfo ),
  6087. aborting( false )
  6088. {}
  6089. TestGroupStats::~TestGroupStats() = default;
  6090. TestRunStats::TestRunStats( TestRunInfo const& _runInfo,
  6091. Totals const& _totals,
  6092. bool _aborting )
  6093. : runInfo( _runInfo ),
  6094. totals( _totals ),
  6095. aborting( _aborting )
  6096. {}
  6097. TestRunStats::~TestRunStats() = default;
  6098. void IStreamingReporter::fatalErrorEncountered( StringRef ) {}
  6099. bool IStreamingReporter::isMulti() const { return false; }
  6100. IReporterFactory::~IReporterFactory() = default;
  6101. IReporterRegistry::~IReporterRegistry() = default;
  6102. void addReporter( IStreamingReporterPtr& existingReporter, IStreamingReporterPtr&& additionalReporter ) {
  6103. if( !existingReporter ) {
  6104. existingReporter = std::move( additionalReporter );
  6105. return;
  6106. }
  6107. MultipleReporters* multi = nullptr;
  6108. if( existingReporter->isMulti() ) {
  6109. multi = static_cast<MultipleReporters*>( existingReporter.get() );
  6110. }
  6111. else {
  6112. auto newMulti = std::unique_ptr<MultipleReporters>( new MultipleReporters );
  6113. newMulti->add( std::move( existingReporter ) );
  6114. multi = newMulti.get();
  6115. existingReporter = std::move( newMulti );
  6116. }
  6117. multi->add( std::move( additionalReporter ) );
  6118. }
  6119. } // end namespace Catch
  6120. // end catch_interfaces_reporter.cpp
  6121. // start catch_interfaces_runner.cpp
  6122. namespace Catch {
  6123. IRunner::~IRunner() = default;
  6124. }
  6125. // end catch_interfaces_runner.cpp
  6126. // start catch_interfaces_testcase.cpp
  6127. namespace Catch {
  6128. ITestInvoker::~ITestInvoker() = default;
  6129. ITestCaseRegistry::~ITestCaseRegistry() = default;
  6130. }
  6131. // end catch_interfaces_testcase.cpp
  6132. // start catch_leak_detector.cpp
  6133. #ifdef CATCH_CONFIG_WINDOWS_CRTDBG
  6134. #include <crtdbg.h>
  6135. namespace Catch {
  6136. LeakDetector::LeakDetector() {
  6137. int flag = _CrtSetDbgFlag(_CRTDBG_REPORT_FLAG);
  6138. flag |= _CRTDBG_LEAK_CHECK_DF;
  6139. flag |= _CRTDBG_ALLOC_MEM_DF;
  6140. _CrtSetDbgFlag(flag);
  6141. _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE | _CRTDBG_MODE_DEBUG);
  6142. _CrtSetReportFile(_CRT_WARN, _CRTDBG_FILE_STDERR);
  6143. // Change this to leaking allocation's number to break there
  6144. _CrtSetBreakAlloc(-1);
  6145. }
  6146. }
  6147. #else
  6148. Catch::LeakDetector::LeakDetector() {}
  6149. #endif
  6150. // end catch_leak_detector.cpp
  6151. // start catch_list.cpp
  6152. // start catch_list.h
  6153. #include <set>
  6154. namespace Catch {
  6155. std::size_t listTests( Config const& config );
  6156. std::size_t listTestsNamesOnly( Config const& config );
  6157. struct TagInfo {
  6158. void add( std::string const& spelling );
  6159. std::string all() const;
  6160. std::set<std::string> spellings;
  6161. std::size_t count = 0;
  6162. };
  6163. std::size_t listTags( Config const& config );
  6164. std::size_t listReporters( Config const& /*config*/ );
  6165. Option<std::size_t> list( Config const& config );
  6166. } // end namespace Catch
  6167. // end catch_list.h
  6168. // start catch_text.h
  6169. namespace Catch {
  6170. using namespace clara::TextFlow;
  6171. }
  6172. // end catch_text.h
  6173. #include <limits>
  6174. #include <algorithm>
  6175. #include <iomanip>
  6176. namespace Catch {
  6177. std::size_t listTests( Config const& config ) {
  6178. TestSpec testSpec = config.testSpec();
  6179. if( config.hasTestFilters() )
  6180. Catch::cout() << "Matching test cases:\n";
  6181. else {
  6182. Catch::cout() << "All available test cases:\n";
  6183. }
  6184. auto matchedTestCases = filterTests( getAllTestCasesSorted( config ), testSpec, config );
  6185. for( auto const& testCaseInfo : matchedTestCases ) {
  6186. Colour::Code colour = testCaseInfo.isHidden()
  6187. ? Colour::SecondaryText
  6188. : Colour::None;
  6189. Colour colourGuard( colour );
  6190. Catch::cout() << Column( testCaseInfo.name ).initialIndent( 2 ).indent( 4 ) << "\n";
  6191. if( config.verbosity() >= Verbosity::High ) {
  6192. Catch::cout() << Column( Catch::Detail::stringify( testCaseInfo.lineInfo ) ).indent(4) << std::endl;
  6193. std::string description = testCaseInfo.description;
  6194. if( description.empty() )
  6195. description = "(NO DESCRIPTION)";
  6196. Catch::cout() << Column( description ).indent(4) << std::endl;
  6197. }
  6198. if( !testCaseInfo.tags.empty() )
  6199. Catch::cout() << Column( testCaseInfo.tagsAsString() ).indent( 6 ) << "\n";
  6200. }
  6201. if( !config.hasTestFilters() )
  6202. Catch::cout() << pluralise( matchedTestCases.size(), "test case" ) << '\n' << std::endl;
  6203. else
  6204. Catch::cout() << pluralise( matchedTestCases.size(), "matching test case" ) << '\n' << std::endl;
  6205. return matchedTestCases.size();
  6206. }
  6207. std::size_t listTestsNamesOnly( Config const& config ) {
  6208. TestSpec testSpec = config.testSpec();
  6209. std::size_t matchedTests = 0;
  6210. std::vector<TestCase> matchedTestCases = filterTests( getAllTestCasesSorted( config ), testSpec, config );
  6211. for( auto const& testCaseInfo : matchedTestCases ) {
  6212. matchedTests++;
  6213. if( startsWith( testCaseInfo.name, '#' ) )
  6214. Catch::cout() << '"' << testCaseInfo.name << '"';
  6215. else
  6216. Catch::cout() << testCaseInfo.name;
  6217. if ( config.verbosity() >= Verbosity::High )
  6218. Catch::cout() << "\t@" << testCaseInfo.lineInfo;
  6219. Catch::cout() << std::endl;
  6220. }
  6221. return matchedTests;
  6222. }
  6223. void TagInfo::add( std::string const& spelling ) {
  6224. ++count;
  6225. spellings.insert( spelling );
  6226. }
  6227. std::string TagInfo::all() const {
  6228. std::string out;
  6229. for( auto const& spelling : spellings )
  6230. out += "[" + spelling + "]";
  6231. return out;
  6232. }
  6233. std::size_t listTags( Config const& config ) {
  6234. TestSpec testSpec = config.testSpec();
  6235. if( config.hasTestFilters() )
  6236. Catch::cout() << "Tags for matching test cases:\n";
  6237. else {
  6238. Catch::cout() << "All available tags:\n";
  6239. }
  6240. std::map<std::string, TagInfo> tagCounts;
  6241. std::vector<TestCase> matchedTestCases = filterTests( getAllTestCasesSorted( config ), testSpec, config );
  6242. for( auto const& testCase : matchedTestCases ) {
  6243. for( auto const& tagName : testCase.getTestCaseInfo().tags ) {
  6244. std::string lcaseTagName = toLower( tagName );
  6245. auto countIt = tagCounts.find( lcaseTagName );
  6246. if( countIt == tagCounts.end() )
  6247. countIt = tagCounts.insert( std::make_pair( lcaseTagName, TagInfo() ) ).first;
  6248. countIt->second.add( tagName );
  6249. }
  6250. }
  6251. for( auto const& tagCount : tagCounts ) {
  6252. ReusableStringStream rss;
  6253. rss << " " << std::setw(2) << tagCount.second.count << " ";
  6254. auto str = rss.str();
  6255. auto wrapper = Column( tagCount.second.all() )
  6256. .initialIndent( 0 )
  6257. .indent( str.size() )
  6258. .width( CATCH_CONFIG_CONSOLE_WIDTH-10 );
  6259. Catch::cout() << str << wrapper << '\n';
  6260. }
  6261. Catch::cout() << pluralise( tagCounts.size(), "tag" ) << '\n' << std::endl;
  6262. return tagCounts.size();
  6263. }
  6264. std::size_t listReporters( Config const& /*config*/ ) {
  6265. Catch::cout() << "Available reporters:\n";
  6266. IReporterRegistry::FactoryMap const& factories = getRegistryHub().getReporterRegistry().getFactories();
  6267. std::size_t maxNameLen = 0;
  6268. for( auto const& factoryKvp : factories )
  6269. maxNameLen = (std::max)( maxNameLen, factoryKvp.first.size() );
  6270. for( auto const& factoryKvp : factories ) {
  6271. Catch::cout()
  6272. << Column( factoryKvp.first + ":" )
  6273. .indent(2)
  6274. .width( 5+maxNameLen )
  6275. + Column( factoryKvp.second->getDescription() )
  6276. .initialIndent(0)
  6277. .indent(2)
  6278. .width( CATCH_CONFIG_CONSOLE_WIDTH - maxNameLen-8 )
  6279. << "\n";
  6280. }
  6281. Catch::cout() << std::endl;
  6282. return factories.size();
  6283. }
  6284. Option<std::size_t> list( Config const& config ) {
  6285. Option<std::size_t> listedCount;
  6286. if( config.listTests() )
  6287. listedCount = listedCount.valueOr(0) + listTests( config );
  6288. if( config.listTestNamesOnly() )
  6289. listedCount = listedCount.valueOr(0) + listTestsNamesOnly( config );
  6290. if( config.listTags() )
  6291. listedCount = listedCount.valueOr(0) + listTags( config );
  6292. if( config.listReporters() )
  6293. listedCount = listedCount.valueOr(0) + listReporters( config );
  6294. return listedCount;
  6295. }
  6296. } // end namespace Catch
  6297. // end catch_list.cpp
  6298. // start catch_matchers.cpp
  6299. namespace Catch {
  6300. namespace Matchers {
  6301. namespace Impl {
  6302. std::string MatcherUntypedBase::toString() const {
  6303. if( m_cachedToString.empty() )
  6304. m_cachedToString = describe();
  6305. return m_cachedToString;
  6306. }
  6307. MatcherUntypedBase::~MatcherUntypedBase() = default;
  6308. } // namespace Impl
  6309. } // namespace Matchers
  6310. using namespace Matchers;
  6311. using Matchers::Impl::MatcherBase;
  6312. } // namespace Catch
  6313. // end catch_matchers.cpp
  6314. // start catch_matchers_floating.cpp
  6315. #include <cstdlib>
  6316. #include <cstdint>
  6317. #include <cstring>
  6318. #include <stdexcept>
  6319. namespace Catch {
  6320. namespace Matchers {
  6321. namespace Floating {
  6322. enum class FloatingPointKind : uint8_t {
  6323. Float,
  6324. Double
  6325. };
  6326. }
  6327. }
  6328. }
  6329. namespace {
  6330. template <typename T>
  6331. struct Converter;
  6332. template <>
  6333. struct Converter<float> {
  6334. static_assert(sizeof(float) == sizeof(int32_t), "Important ULP matcher assumption violated");
  6335. Converter(float f) {
  6336. std::memcpy(&i, &f, sizeof(f));
  6337. }
  6338. int32_t i;
  6339. };
  6340. template <>
  6341. struct Converter<double> {
  6342. static_assert(sizeof(double) == sizeof(int64_t), "Important ULP matcher assumption violated");
  6343. Converter(double d) {
  6344. std::memcpy(&i, &d, sizeof(d));
  6345. }
  6346. int64_t i;
  6347. };
  6348. template <typename T>
  6349. auto convert(T t) -> Converter<T> {
  6350. return Converter<T>(t);
  6351. }
  6352. template <typename FP>
  6353. bool almostEqualUlps(FP lhs, FP rhs, int maxUlpDiff) {
  6354. // Comparison with NaN should always be false.
  6355. // This way we can rule it out before getting into the ugly details
  6356. if (std::isnan(lhs) || std::isnan(rhs)) {
  6357. return false;
  6358. }
  6359. auto lc = convert(lhs);
  6360. auto rc = convert(rhs);
  6361. if ((lc.i < 0) != (rc.i < 0)) {
  6362. // Potentially we can have +0 and -0
  6363. return lhs == rhs;
  6364. }
  6365. auto ulpDiff = std::abs(lc.i - rc.i);
  6366. return ulpDiff <= maxUlpDiff;
  6367. }
  6368. }
  6369. namespace Catch {
  6370. namespace Matchers {
  6371. namespace Floating {
  6372. WithinAbsMatcher::WithinAbsMatcher(double target, double margin)
  6373. :m_target{ target }, m_margin{ margin } {
  6374. if (m_margin < 0) {
  6375. throw std::domain_error("Allowed margin difference has to be >= 0");
  6376. }
  6377. }
  6378. // Performs equivalent check of std::fabs(lhs - rhs) <= margin
  6379. // But without the subtraction to allow for INFINITY in comparison
  6380. bool WithinAbsMatcher::match(double const& matchee) const {
  6381. return (matchee + m_margin >= m_target) && (m_target + m_margin >= matchee);
  6382. }
  6383. std::string WithinAbsMatcher::describe() const {
  6384. return "is within " + ::Catch::Detail::stringify(m_margin) + " of " + ::Catch::Detail::stringify(m_target);
  6385. }
  6386. WithinUlpsMatcher::WithinUlpsMatcher(double target, int ulps, FloatingPointKind baseType)
  6387. :m_target{ target }, m_ulps{ ulps }, m_type{ baseType } {
  6388. if (m_ulps < 0) {
  6389. throw std::domain_error("Allowed ulp difference has to be >= 0");
  6390. }
  6391. }
  6392. bool WithinUlpsMatcher::match(double const& matchee) const {
  6393. switch (m_type) {
  6394. case FloatingPointKind::Float:
  6395. return almostEqualUlps<float>(static_cast<float>(matchee), static_cast<float>(m_target), m_ulps);
  6396. case FloatingPointKind::Double:
  6397. return almostEqualUlps<double>(matchee, m_target, m_ulps);
  6398. default:
  6399. throw std::domain_error("Unknown FloatingPointKind value");
  6400. }
  6401. }
  6402. std::string WithinUlpsMatcher::describe() const {
  6403. return "is within " + std::to_string(m_ulps) + " ULPs of " + ::Catch::Detail::stringify(m_target) + ((m_type == FloatingPointKind::Float)? "f" : "");
  6404. }
  6405. }// namespace Floating
  6406. Floating::WithinUlpsMatcher WithinULP(double target, int maxUlpDiff) {
  6407. return Floating::WithinUlpsMatcher(target, maxUlpDiff, Floating::FloatingPointKind::Double);
  6408. }
  6409. Floating::WithinUlpsMatcher WithinULP(float target, int maxUlpDiff) {
  6410. return Floating::WithinUlpsMatcher(target, maxUlpDiff, Floating::FloatingPointKind::Float);
  6411. }
  6412. Floating::WithinAbsMatcher WithinAbs(double target, double margin) {
  6413. return Floating::WithinAbsMatcher(target, margin);
  6414. }
  6415. } // namespace Matchers
  6416. } // namespace Catch
  6417. // end catch_matchers_floating.cpp
  6418. // start catch_matchers_generic.cpp
  6419. std::string Catch::Matchers::Generic::Detail::finalizeDescription(const std::string& desc) {
  6420. if (desc.empty()) {
  6421. return "matches undescribed predicate";
  6422. } else {
  6423. return "matches predicate: \"" + desc + '"';
  6424. }
  6425. }
  6426. // end catch_matchers_generic.cpp
  6427. // start catch_matchers_string.cpp
  6428. #include <regex>
  6429. namespace Catch {
  6430. namespace Matchers {
  6431. namespace StdString {
  6432. CasedString::CasedString( std::string const& str, CaseSensitive::Choice caseSensitivity )
  6433. : m_caseSensitivity( caseSensitivity ),
  6434. m_str( adjustString( str ) )
  6435. {}
  6436. std::string CasedString::adjustString( std::string const& str ) const {
  6437. return m_caseSensitivity == CaseSensitive::No
  6438. ? toLower( str )
  6439. : str;
  6440. }
  6441. std::string CasedString::caseSensitivitySuffix() const {
  6442. return m_caseSensitivity == CaseSensitive::No
  6443. ? " (case insensitive)"
  6444. : std::string();
  6445. }
  6446. StringMatcherBase::StringMatcherBase( std::string const& operation, CasedString const& comparator )
  6447. : m_comparator( comparator ),
  6448. m_operation( operation ) {
  6449. }
  6450. std::string StringMatcherBase::describe() const {
  6451. std::string description;
  6452. description.reserve(5 + m_operation.size() + m_comparator.m_str.size() +
  6453. m_comparator.caseSensitivitySuffix().size());
  6454. description += m_operation;
  6455. description += ": \"";
  6456. description += m_comparator.m_str;
  6457. description += "\"";
  6458. description += m_comparator.caseSensitivitySuffix();
  6459. return description;
  6460. }
  6461. EqualsMatcher::EqualsMatcher( CasedString const& comparator ) : StringMatcherBase( "equals", comparator ) {}
  6462. bool EqualsMatcher::match( std::string const& source ) const {
  6463. return m_comparator.adjustString( source ) == m_comparator.m_str;
  6464. }
  6465. ContainsMatcher::ContainsMatcher( CasedString const& comparator ) : StringMatcherBase( "contains", comparator ) {}
  6466. bool ContainsMatcher::match( std::string const& source ) const {
  6467. return contains( m_comparator.adjustString( source ), m_comparator.m_str );
  6468. }
  6469. StartsWithMatcher::StartsWithMatcher( CasedString const& comparator ) : StringMatcherBase( "starts with", comparator ) {}
  6470. bool StartsWithMatcher::match( std::string const& source ) const {
  6471. return startsWith( m_comparator.adjustString( source ), m_comparator.m_str );
  6472. }
  6473. EndsWithMatcher::EndsWithMatcher( CasedString const& comparator ) : StringMatcherBase( "ends with", comparator ) {}
  6474. bool EndsWithMatcher::match( std::string const& source ) const {
  6475. return endsWith( m_comparator.adjustString( source ), m_comparator.m_str );
  6476. }
  6477. RegexMatcher::RegexMatcher(std::string regex, CaseSensitive::Choice caseSensitivity): m_regex(std::move(regex)), m_caseSensitivity(caseSensitivity) {}
  6478. bool RegexMatcher::match(std::string const& matchee) const {
  6479. auto flags = std::regex::ECMAScript; // ECMAScript is the default syntax option anyway
  6480. if (m_caseSensitivity == CaseSensitive::Choice::No) {
  6481. flags |= std::regex::icase;
  6482. }
  6483. auto reg = std::regex(m_regex, flags);
  6484. return std::regex_match(matchee, reg);
  6485. }
  6486. std::string RegexMatcher::describe() const {
  6487. return "matches " + ::Catch::Detail::stringify(m_regex) + ((m_caseSensitivity == CaseSensitive::Choice::Yes)? " case sensitively" : " case insensitively");
  6488. }
  6489. } // namespace StdString
  6490. StdString::EqualsMatcher Equals( std::string const& str, CaseSensitive::Choice caseSensitivity ) {
  6491. return StdString::EqualsMatcher( StdString::CasedString( str, caseSensitivity) );
  6492. }
  6493. StdString::ContainsMatcher Contains( std::string const& str, CaseSensitive::Choice caseSensitivity ) {
  6494. return StdString::ContainsMatcher( StdString::CasedString( str, caseSensitivity) );
  6495. }
  6496. StdString::EndsWithMatcher EndsWith( std::string const& str, CaseSensitive::Choice caseSensitivity ) {
  6497. return StdString::EndsWithMatcher( StdString::CasedString( str, caseSensitivity) );
  6498. }
  6499. StdString::StartsWithMatcher StartsWith( std::string const& str, CaseSensitive::Choice caseSensitivity ) {
  6500. return StdString::StartsWithMatcher( StdString::CasedString( str, caseSensitivity) );
  6501. }
  6502. StdString::RegexMatcher Matches(std::string const& regex, CaseSensitive::Choice caseSensitivity) {
  6503. return StdString::RegexMatcher(regex, caseSensitivity);
  6504. }
  6505. } // namespace Matchers
  6506. } // namespace Catch
  6507. // end catch_matchers_string.cpp
  6508. // start catch_message.cpp
  6509. // start catch_uncaught_exceptions.h
  6510. namespace Catch {
  6511. bool uncaught_exceptions();
  6512. } // end namespace Catch
  6513. // end catch_uncaught_exceptions.h
  6514. namespace Catch {
  6515. MessageInfo::MessageInfo( std::string const& _macroName,
  6516. SourceLineInfo const& _lineInfo,
  6517. ResultWas::OfType _type )
  6518. : macroName( _macroName ),
  6519. lineInfo( _lineInfo ),
  6520. type( _type ),
  6521. sequence( ++globalCount )
  6522. {}
  6523. bool MessageInfo::operator==( MessageInfo const& other ) const {
  6524. return sequence == other.sequence;
  6525. }
  6526. bool MessageInfo::operator<( MessageInfo const& other ) const {
  6527. return sequence < other.sequence;
  6528. }
  6529. // This may need protecting if threading support is added
  6530. unsigned int MessageInfo::globalCount = 0;
  6531. ////////////////////////////////////////////////////////////////////////////
  6532. Catch::MessageBuilder::MessageBuilder( std::string const& macroName,
  6533. SourceLineInfo const& lineInfo,
  6534. ResultWas::OfType type )
  6535. :m_info(macroName, lineInfo, type) {}
  6536. ////////////////////////////////////////////////////////////////////////////
  6537. ScopedMessage::ScopedMessage( MessageBuilder const& builder )
  6538. : m_info( builder.m_info )
  6539. {
  6540. m_info.message = builder.m_stream.str();
  6541. getResultCapture().pushScopedMessage( m_info );
  6542. }
  6543. ScopedMessage::~ScopedMessage() {
  6544. if ( !uncaught_exceptions() ){
  6545. getResultCapture().popScopedMessage(m_info);
  6546. }
  6547. }
  6548. } // end namespace Catch
  6549. // end catch_message.cpp
  6550. // start catch_random_number_generator.cpp
  6551. // start catch_random_number_generator.h
  6552. #include <algorithm>
  6553. namespace Catch {
  6554. struct IConfig;
  6555. void seedRng( IConfig const& config );
  6556. unsigned int rngSeed();
  6557. struct RandomNumberGenerator {
  6558. using result_type = unsigned int;
  6559. static constexpr result_type (min)() { return 0; }
  6560. static constexpr result_type (max)() { return 1000000; }
  6561. result_type operator()( result_type n ) const;
  6562. result_type operator()() const;
  6563. template<typename V>
  6564. static void shuffle( V& vector ) {
  6565. RandomNumberGenerator rng;
  6566. std::shuffle( vector.begin(), vector.end(), rng );
  6567. }
  6568. };
  6569. }
  6570. // end catch_random_number_generator.h
  6571. #include <cstdlib>
  6572. namespace Catch {
  6573. void seedRng( IConfig const& config ) {
  6574. if( config.rngSeed() != 0 )
  6575. std::srand( config.rngSeed() );
  6576. }
  6577. unsigned int rngSeed() {
  6578. return getCurrentContext().getConfig()->rngSeed();
  6579. }
  6580. RandomNumberGenerator::result_type RandomNumberGenerator::operator()( result_type n ) const {
  6581. return std::rand() % n;
  6582. }
  6583. RandomNumberGenerator::result_type RandomNumberGenerator::operator()() const {
  6584. return std::rand() % (max)();
  6585. }
  6586. }
  6587. // end catch_random_number_generator.cpp
  6588. // start catch_registry_hub.cpp
  6589. // start catch_test_case_registry_impl.h
  6590. #include <vector>
  6591. #include <set>
  6592. #include <algorithm>
  6593. #include <ios>
  6594. namespace Catch {
  6595. class TestCase;
  6596. struct IConfig;
  6597. std::vector<TestCase> sortTests( IConfig const& config, std::vector<TestCase> const& unsortedTestCases );
  6598. bool matchTest( TestCase const& testCase, TestSpec const& testSpec, IConfig const& config );
  6599. void enforceNoDuplicateTestCases( std::vector<TestCase> const& functions );
  6600. std::vector<TestCase> filterTests( std::vector<TestCase> const& testCases, TestSpec const& testSpec, IConfig const& config );
  6601. std::vector<TestCase> const& getAllTestCasesSorted( IConfig const& config );
  6602. class TestRegistry : public ITestCaseRegistry {
  6603. public:
  6604. virtual ~TestRegistry() = default;
  6605. virtual void registerTest( TestCase const& testCase );
  6606. std::vector<TestCase> const& getAllTests() const override;
  6607. std::vector<TestCase> const& getAllTestsSorted( IConfig const& config ) const override;
  6608. private:
  6609. std::vector<TestCase> m_functions;
  6610. mutable RunTests::InWhatOrder m_currentSortOrder = RunTests::InDeclarationOrder;
  6611. mutable std::vector<TestCase> m_sortedFunctions;
  6612. std::size_t m_unnamedCount = 0;
  6613. std::ios_base::Init m_ostreamInit; // Forces cout/ cerr to be initialised
  6614. };
  6615. ///////////////////////////////////////////////////////////////////////////
  6616. class TestInvokerAsFunction : public ITestInvoker {
  6617. void(*m_testAsFunction)();
  6618. public:
  6619. TestInvokerAsFunction( void(*testAsFunction)() ) noexcept;
  6620. void invoke() const override;
  6621. };
  6622. std::string extractClassName( StringRef const& classOrQualifiedMethodName );
  6623. ///////////////////////////////////////////////////////////////////////////
  6624. } // end namespace Catch
  6625. // end catch_test_case_registry_impl.h
  6626. // start catch_reporter_registry.h
  6627. #include <map>
  6628. namespace Catch {
  6629. class ReporterRegistry : public IReporterRegistry {
  6630. public:
  6631. ~ReporterRegistry() override;
  6632. IStreamingReporterPtr create( std::string const& name, IConfigPtr const& config ) const override;
  6633. void registerReporter( std::string const& name, IReporterFactoryPtr const& factory );
  6634. void registerListener( IReporterFactoryPtr const& factory );
  6635. FactoryMap const& getFactories() const override;
  6636. Listeners const& getListeners() const override;
  6637. private:
  6638. FactoryMap m_factories;
  6639. Listeners m_listeners;
  6640. };
  6641. }
  6642. // end catch_reporter_registry.h
  6643. // start catch_tag_alias_registry.h
  6644. // start catch_tag_alias.h
  6645. #include <string>
  6646. namespace Catch {
  6647. struct TagAlias {
  6648. TagAlias(std::string const& _tag, SourceLineInfo _lineInfo);
  6649. std::string tag;
  6650. SourceLineInfo lineInfo;
  6651. };
  6652. } // end namespace Catch
  6653. // end catch_tag_alias.h
  6654. #include <map>
  6655. namespace Catch {
  6656. class TagAliasRegistry : public ITagAliasRegistry {
  6657. public:
  6658. ~TagAliasRegistry() override;
  6659. TagAlias const* find( std::string const& alias ) const override;
  6660. std::string expandAliases( std::string const& unexpandedTestSpec ) const override;
  6661. void add( std::string const& alias, std::string const& tag, SourceLineInfo const& lineInfo );
  6662. private:
  6663. std::map<std::string, TagAlias> m_registry;
  6664. };
  6665. } // end namespace Catch
  6666. // end catch_tag_alias_registry.h
  6667. // start catch_startup_exception_registry.h
  6668. #include <vector>
  6669. #include <exception>
  6670. namespace Catch {
  6671. class StartupExceptionRegistry {
  6672. public:
  6673. void add(std::exception_ptr const& exception) noexcept;
  6674. std::vector<std::exception_ptr> const& getExceptions() const noexcept;
  6675. private:
  6676. std::vector<std::exception_ptr> m_exceptions;
  6677. };
  6678. } // end namespace Catch
  6679. // end catch_startup_exception_registry.h
  6680. namespace Catch {
  6681. namespace {
  6682. class RegistryHub : public IRegistryHub, public IMutableRegistryHub,
  6683. private NonCopyable {
  6684. public: // IRegistryHub
  6685. RegistryHub() = default;
  6686. IReporterRegistry const& getReporterRegistry() const override {
  6687. return m_reporterRegistry;
  6688. }
  6689. ITestCaseRegistry const& getTestCaseRegistry() const override {
  6690. return m_testCaseRegistry;
  6691. }
  6692. IExceptionTranslatorRegistry& getExceptionTranslatorRegistry() override {
  6693. return m_exceptionTranslatorRegistry;
  6694. }
  6695. ITagAliasRegistry const& getTagAliasRegistry() const override {
  6696. return m_tagAliasRegistry;
  6697. }
  6698. StartupExceptionRegistry const& getStartupExceptionRegistry() const override {
  6699. return m_exceptionRegistry;
  6700. }
  6701. public: // IMutableRegistryHub
  6702. void registerReporter( std::string const& name, IReporterFactoryPtr const& factory ) override {
  6703. m_reporterRegistry.registerReporter( name, factory );
  6704. }
  6705. void registerListener( IReporterFactoryPtr const& factory ) override {
  6706. m_reporterRegistry.registerListener( factory );
  6707. }
  6708. void registerTest( TestCase const& testInfo ) override {
  6709. m_testCaseRegistry.registerTest( testInfo );
  6710. }
  6711. void registerTranslator( const IExceptionTranslator* translator ) override {
  6712. m_exceptionTranslatorRegistry.registerTranslator( translator );
  6713. }
  6714. void registerTagAlias( std::string const& alias, std::string const& tag, SourceLineInfo const& lineInfo ) override {
  6715. m_tagAliasRegistry.add( alias, tag, lineInfo );
  6716. }
  6717. void registerStartupException() noexcept override {
  6718. m_exceptionRegistry.add(std::current_exception());
  6719. }
  6720. private:
  6721. TestRegistry m_testCaseRegistry;
  6722. ReporterRegistry m_reporterRegistry;
  6723. ExceptionTranslatorRegistry m_exceptionTranslatorRegistry;
  6724. TagAliasRegistry m_tagAliasRegistry;
  6725. StartupExceptionRegistry m_exceptionRegistry;
  6726. };
  6727. // Single, global, instance
  6728. RegistryHub*& getTheRegistryHub() {
  6729. static RegistryHub* theRegistryHub = nullptr;
  6730. if( !theRegistryHub )
  6731. theRegistryHub = new RegistryHub();
  6732. return theRegistryHub;
  6733. }
  6734. }
  6735. IRegistryHub& getRegistryHub() {
  6736. return *getTheRegistryHub();
  6737. }
  6738. IMutableRegistryHub& getMutableRegistryHub() {
  6739. return *getTheRegistryHub();
  6740. }
  6741. void cleanUp() {
  6742. delete getTheRegistryHub();
  6743. getTheRegistryHub() = nullptr;
  6744. cleanUpContext();
  6745. ReusableStringStream::cleanup();
  6746. }
  6747. std::string translateActiveException() {
  6748. return getRegistryHub().getExceptionTranslatorRegistry().translateActiveException();
  6749. }
  6750. } // end namespace Catch
  6751. // end catch_registry_hub.cpp
  6752. // start catch_reporter_registry.cpp
  6753. namespace Catch {
  6754. ReporterRegistry::~ReporterRegistry() = default;
  6755. IStreamingReporterPtr ReporterRegistry::create( std::string const& name, IConfigPtr const& config ) const {
  6756. auto it = m_factories.find( name );
  6757. if( it == m_factories.end() )
  6758. return nullptr;
  6759. return it->second->create( ReporterConfig( config ) );
  6760. }
  6761. void ReporterRegistry::registerReporter( std::string const& name, IReporterFactoryPtr const& factory ) {
  6762. m_factories.emplace(name, factory);
  6763. }
  6764. void ReporterRegistry::registerListener( IReporterFactoryPtr const& factory ) {
  6765. m_listeners.push_back( factory );
  6766. }
  6767. IReporterRegistry::FactoryMap const& ReporterRegistry::getFactories() const {
  6768. return m_factories;
  6769. }
  6770. IReporterRegistry::Listeners const& ReporterRegistry::getListeners() const {
  6771. return m_listeners;
  6772. }
  6773. }
  6774. // end catch_reporter_registry.cpp
  6775. // start catch_result_type.cpp
  6776. namespace Catch {
  6777. bool isOk( ResultWas::OfType resultType ) {
  6778. return ( resultType & ResultWas::FailureBit ) == 0;
  6779. }
  6780. bool isJustInfo( int flags ) {
  6781. return flags == ResultWas::Info;
  6782. }
  6783. ResultDisposition::Flags operator | ( ResultDisposition::Flags lhs, ResultDisposition::Flags rhs ) {
  6784. return static_cast<ResultDisposition::Flags>( static_cast<int>( lhs ) | static_cast<int>( rhs ) );
  6785. }
  6786. bool shouldContinueOnFailure( int flags ) { return ( flags & ResultDisposition::ContinueOnFailure ) != 0; }
  6787. bool shouldSuppressFailure( int flags ) { return ( flags & ResultDisposition::SuppressFail ) != 0; }
  6788. } // end namespace Catch
  6789. // end catch_result_type.cpp
  6790. // start catch_run_context.cpp
  6791. #include <cassert>
  6792. #include <algorithm>
  6793. #include <sstream>
  6794. namespace Catch {
  6795. class RedirectedStream {
  6796. std::ostream& m_originalStream;
  6797. std::ostream& m_redirectionStream;
  6798. std::streambuf* m_prevBuf;
  6799. public:
  6800. RedirectedStream( std::ostream& originalStream, std::ostream& redirectionStream )
  6801. : m_originalStream( originalStream ),
  6802. m_redirectionStream( redirectionStream ),
  6803. m_prevBuf( m_originalStream.rdbuf() )
  6804. {
  6805. m_originalStream.rdbuf( m_redirectionStream.rdbuf() );
  6806. }
  6807. ~RedirectedStream() {
  6808. m_originalStream.rdbuf( m_prevBuf );
  6809. }
  6810. };
  6811. class RedirectedStdOut {
  6812. ReusableStringStream m_rss;
  6813. RedirectedStream m_cout;
  6814. public:
  6815. RedirectedStdOut() : m_cout( Catch::cout(), m_rss.get() ) {}
  6816. auto str() const -> std::string { return m_rss.str(); }
  6817. };
  6818. // StdErr has two constituent streams in C++, std::cerr and std::clog
  6819. // This means that we need to redirect 2 streams into 1 to keep proper
  6820. // order of writes
  6821. class RedirectedStdErr {
  6822. ReusableStringStream m_rss;
  6823. RedirectedStream m_cerr;
  6824. RedirectedStream m_clog;
  6825. public:
  6826. RedirectedStdErr()
  6827. : m_cerr( Catch::cerr(), m_rss.get() ),
  6828. m_clog( Catch::clog(), m_rss.get() )
  6829. {}
  6830. auto str() const -> std::string { return m_rss.str(); }
  6831. };
  6832. RunContext::RunContext(IConfigPtr const& _config, IStreamingReporterPtr&& reporter)
  6833. : m_runInfo(_config->name()),
  6834. m_context(getCurrentMutableContext()),
  6835. m_config(_config),
  6836. m_reporter(std::move(reporter)),
  6837. m_lastAssertionInfo{ StringRef(), SourceLineInfo("",0), StringRef(), ResultDisposition::Normal },
  6838. m_includeSuccessfulResults( m_config->includeSuccessfulResults() )
  6839. {
  6840. m_context.setRunner(this);
  6841. m_context.setConfig(m_config);
  6842. m_context.setResultCapture(this);
  6843. m_reporter->testRunStarting(m_runInfo);
  6844. }
  6845. RunContext::~RunContext() {
  6846. m_reporter->testRunEnded(TestRunStats(m_runInfo, m_totals, aborting()));
  6847. }
  6848. void RunContext::testGroupStarting(std::string const& testSpec, std::size_t groupIndex, std::size_t groupsCount) {
  6849. m_reporter->testGroupStarting(GroupInfo(testSpec, groupIndex, groupsCount));
  6850. }
  6851. void RunContext::testGroupEnded(std::string const& testSpec, Totals const& totals, std::size_t groupIndex, std::size_t groupsCount) {
  6852. m_reporter->testGroupEnded(TestGroupStats(GroupInfo(testSpec, groupIndex, groupsCount), totals, aborting()));
  6853. }
  6854. Totals RunContext::runTest(TestCase const& testCase) {
  6855. Totals prevTotals = m_totals;
  6856. std::string redirectedCout;
  6857. std::string redirectedCerr;
  6858. auto const& testInfo = testCase.getTestCaseInfo();
  6859. m_reporter->testCaseStarting(testInfo);
  6860. m_activeTestCase = &testCase;
  6861. ITracker& rootTracker = m_trackerContext.startRun();
  6862. assert(rootTracker.isSectionTracker());
  6863. static_cast<SectionTracker&>(rootTracker).addInitialFilters(m_config->getSectionsToRun());
  6864. do {
  6865. m_trackerContext.startCycle();
  6866. m_testCaseTracker = &SectionTracker::acquire(m_trackerContext, TestCaseTracking::NameAndLocation(testInfo.name, testInfo.lineInfo));
  6867. runCurrentTest(redirectedCout, redirectedCerr);
  6868. } while (!m_testCaseTracker->isSuccessfullyCompleted() && !aborting());
  6869. Totals deltaTotals = m_totals.delta(prevTotals);
  6870. if (testInfo.expectedToFail() && deltaTotals.testCases.passed > 0) {
  6871. deltaTotals.assertions.failed++;
  6872. deltaTotals.testCases.passed--;
  6873. deltaTotals.testCases.failed++;
  6874. }
  6875. m_totals.testCases += deltaTotals.testCases;
  6876. m_reporter->testCaseEnded(TestCaseStats(testInfo,
  6877. deltaTotals,
  6878. redirectedCout,
  6879. redirectedCerr,
  6880. aborting()));
  6881. m_activeTestCase = nullptr;
  6882. m_testCaseTracker = nullptr;
  6883. return deltaTotals;
  6884. }
  6885. IConfigPtr RunContext::config() const {
  6886. return m_config;
  6887. }
  6888. IStreamingReporter& RunContext::reporter() const {
  6889. return *m_reporter;
  6890. }
  6891. void RunContext::assertionEnded(AssertionResult const & result) {
  6892. if (result.getResultType() == ResultWas::Ok) {
  6893. m_totals.assertions.passed++;
  6894. m_lastAssertionPassed = true;
  6895. } else if (!result.isOk()) {
  6896. m_lastAssertionPassed = false;
  6897. if( m_activeTestCase->getTestCaseInfo().okToFail() )
  6898. m_totals.assertions.failedButOk++;
  6899. else
  6900. m_totals.assertions.failed++;
  6901. }
  6902. else {
  6903. m_lastAssertionPassed = true;
  6904. }
  6905. // We have no use for the return value (whether messages should be cleared), because messages were made scoped
  6906. // and should be let to clear themselves out.
  6907. static_cast<void>(m_reporter->assertionEnded(AssertionStats(result, m_messages, m_totals)));
  6908. // Reset working state
  6909. resetAssertionInfo();
  6910. m_lastResult = result;
  6911. }
  6912. void RunContext::resetAssertionInfo() {
  6913. m_lastAssertionInfo.macroName = StringRef();
  6914. m_lastAssertionInfo.capturedExpression = "{Unknown expression after the reported line}"_sr;
  6915. }
  6916. bool RunContext::sectionStarted(SectionInfo const & sectionInfo, Counts & assertions) {
  6917. ITracker& sectionTracker = SectionTracker::acquire(m_trackerContext, TestCaseTracking::NameAndLocation(sectionInfo.name, sectionInfo.lineInfo));
  6918. if (!sectionTracker.isOpen())
  6919. return false;
  6920. m_activeSections.push_back(&sectionTracker);
  6921. m_lastAssertionInfo.lineInfo = sectionInfo.lineInfo;
  6922. m_reporter->sectionStarting(sectionInfo);
  6923. assertions = m_totals.assertions;
  6924. return true;
  6925. }
  6926. bool RunContext::testForMissingAssertions(Counts& assertions) {
  6927. if (assertions.total() != 0)
  6928. return false;
  6929. if (!m_config->warnAboutMissingAssertions())
  6930. return false;
  6931. if (m_trackerContext.currentTracker().hasChildren())
  6932. return false;
  6933. m_totals.assertions.failed++;
  6934. assertions.failed++;
  6935. return true;
  6936. }
  6937. void RunContext::sectionEnded(SectionEndInfo const & endInfo) {
  6938. Counts assertions = m_totals.assertions - endInfo.prevAssertions;
  6939. bool missingAssertions = testForMissingAssertions(assertions);
  6940. if (!m_activeSections.empty()) {
  6941. m_activeSections.back()->close();
  6942. m_activeSections.pop_back();
  6943. }
  6944. m_reporter->sectionEnded(SectionStats(endInfo.sectionInfo, assertions, endInfo.durationInSeconds, missingAssertions));
  6945. m_messages.clear();
  6946. }
  6947. void RunContext::sectionEndedEarly(SectionEndInfo const & endInfo) {
  6948. if (m_unfinishedSections.empty())
  6949. m_activeSections.back()->fail();
  6950. else
  6951. m_activeSections.back()->close();
  6952. m_activeSections.pop_back();
  6953. m_unfinishedSections.push_back(endInfo);
  6954. }
  6955. void RunContext::benchmarkStarting( BenchmarkInfo const& info ) {
  6956. m_reporter->benchmarkStarting( info );
  6957. }
  6958. void RunContext::benchmarkEnded( BenchmarkStats const& stats ) {
  6959. m_reporter->benchmarkEnded( stats );
  6960. }
  6961. void RunContext::pushScopedMessage(MessageInfo const & message) {
  6962. m_messages.push_back(message);
  6963. }
  6964. void RunContext::popScopedMessage(MessageInfo const & message) {
  6965. m_messages.erase(std::remove(m_messages.begin(), m_messages.end(), message), m_messages.end());
  6966. }
  6967. std::string RunContext::getCurrentTestName() const {
  6968. return m_activeTestCase
  6969. ? m_activeTestCase->getTestCaseInfo().name
  6970. : std::string();
  6971. }
  6972. const AssertionResult * RunContext::getLastResult() const {
  6973. return &(*m_lastResult);
  6974. }
  6975. void RunContext::exceptionEarlyReported() {
  6976. m_shouldReportUnexpected = false;
  6977. }
  6978. void RunContext::handleFatalErrorCondition( StringRef message ) {
  6979. // First notify reporter that bad things happened
  6980. m_reporter->fatalErrorEncountered(message);
  6981. // Don't rebuild the result -- the stringification itself can cause more fatal errors
  6982. // Instead, fake a result data.
  6983. AssertionResultData tempResult( ResultWas::FatalErrorCondition, { false } );
  6984. tempResult.message = message;
  6985. AssertionResult result(m_lastAssertionInfo, tempResult);
  6986. assertionEnded(result);
  6987. handleUnfinishedSections();
  6988. // Recreate section for test case (as we will lose the one that was in scope)
  6989. auto const& testCaseInfo = m_activeTestCase->getTestCaseInfo();
  6990. SectionInfo testCaseSection(testCaseInfo.lineInfo, testCaseInfo.name, testCaseInfo.description);
  6991. Counts assertions;
  6992. assertions.failed = 1;
  6993. SectionStats testCaseSectionStats(testCaseSection, assertions, 0, false);
  6994. m_reporter->sectionEnded(testCaseSectionStats);
  6995. auto const& testInfo = m_activeTestCase->getTestCaseInfo();
  6996. Totals deltaTotals;
  6997. deltaTotals.testCases.failed = 1;
  6998. deltaTotals.assertions.failed = 1;
  6999. m_reporter->testCaseEnded(TestCaseStats(testInfo,
  7000. deltaTotals,
  7001. std::string(),
  7002. std::string(),
  7003. false));
  7004. m_totals.testCases.failed++;
  7005. testGroupEnded(std::string(), m_totals, 1, 1);
  7006. m_reporter->testRunEnded(TestRunStats(m_runInfo, m_totals, false));
  7007. }
  7008. bool RunContext::lastAssertionPassed() {
  7009. return m_lastAssertionPassed;
  7010. }
  7011. void RunContext::assertionPassed() {
  7012. m_lastAssertionPassed = true;
  7013. ++m_totals.assertions.passed;
  7014. resetAssertionInfo();
  7015. }
  7016. bool RunContext::aborting() const {
  7017. return m_totals.assertions.failed == static_cast<std::size_t>(m_config->abortAfter());
  7018. }
  7019. void RunContext::runCurrentTest(std::string & redirectedCout, std::string & redirectedCerr) {
  7020. auto const& testCaseInfo = m_activeTestCase->getTestCaseInfo();
  7021. SectionInfo testCaseSection(testCaseInfo.lineInfo, testCaseInfo.name, testCaseInfo.description);
  7022. m_reporter->sectionStarting(testCaseSection);
  7023. Counts prevAssertions = m_totals.assertions;
  7024. double duration = 0;
  7025. m_shouldReportUnexpected = true;
  7026. m_lastAssertionInfo = { "TEST_CASE"_sr, testCaseInfo.lineInfo, StringRef(), ResultDisposition::Normal };
  7027. seedRng(*m_config);
  7028. Timer timer;
  7029. try {
  7030. if (m_reporter->getPreferences().shouldRedirectStdOut) {
  7031. RedirectedStdOut redirectedStdOut;
  7032. RedirectedStdErr redirectedStdErr;
  7033. timer.start();
  7034. invokeActiveTestCase();
  7035. redirectedCout += redirectedStdOut.str();
  7036. redirectedCerr += redirectedStdErr.str();
  7037. } else {
  7038. timer.start();
  7039. invokeActiveTestCase();
  7040. }
  7041. duration = timer.getElapsedSeconds();
  7042. } catch (TestFailureException&) {
  7043. // This just means the test was aborted due to failure
  7044. } catch (...) {
  7045. // Under CATCH_CONFIG_FAST_COMPILE, unexpected exceptions under REQUIRE assertions
  7046. // are reported without translation at the point of origin.
  7047. if( m_shouldReportUnexpected ) {
  7048. AssertionReaction dummyReaction;
  7049. handleUnexpectedInflightException( m_lastAssertionInfo, translateActiveException(), dummyReaction );
  7050. }
  7051. }
  7052. Counts assertions = m_totals.assertions - prevAssertions;
  7053. bool missingAssertions = testForMissingAssertions(assertions);
  7054. m_testCaseTracker->close();
  7055. handleUnfinishedSections();
  7056. m_messages.clear();
  7057. SectionStats testCaseSectionStats(testCaseSection, assertions, duration, missingAssertions);
  7058. m_reporter->sectionEnded(testCaseSectionStats);
  7059. }
  7060. void RunContext::invokeActiveTestCase() {
  7061. FatalConditionHandler fatalConditionHandler; // Handle signals
  7062. m_activeTestCase->invoke();
  7063. fatalConditionHandler.reset();
  7064. }
  7065. void RunContext::handleUnfinishedSections() {
  7066. // If sections ended prematurely due to an exception we stored their
  7067. // infos here so we can tear them down outside the unwind process.
  7068. for (auto it = m_unfinishedSections.rbegin(),
  7069. itEnd = m_unfinishedSections.rend();
  7070. it != itEnd;
  7071. ++it)
  7072. sectionEnded(*it);
  7073. m_unfinishedSections.clear();
  7074. }
  7075. void RunContext::handleExpr(
  7076. AssertionInfo const& info,
  7077. ITransientExpression const& expr,
  7078. AssertionReaction& reaction
  7079. ) {
  7080. m_reporter->assertionStarting( info );
  7081. bool negated = isFalseTest( info.resultDisposition );
  7082. bool result = expr.getResult() != negated;
  7083. if( result ) {
  7084. if (!m_includeSuccessfulResults) {
  7085. assertionPassed();
  7086. }
  7087. else {
  7088. reportExpr(info, ResultWas::Ok, &expr, negated);
  7089. }
  7090. }
  7091. else {
  7092. reportExpr(info, ResultWas::ExpressionFailed, &expr, negated );
  7093. populateReaction( reaction );
  7094. }
  7095. }
  7096. void RunContext::reportExpr(
  7097. AssertionInfo const &info,
  7098. ResultWas::OfType resultType,
  7099. ITransientExpression const *expr,
  7100. bool negated ) {
  7101. m_lastAssertionInfo = info;
  7102. AssertionResultData data( resultType, LazyExpression( negated ) );
  7103. AssertionResult assertionResult{ info, data };
  7104. assertionResult.m_resultData.lazyExpression.m_transientExpression = expr;
  7105. assertionEnded( assertionResult );
  7106. }
  7107. void RunContext::handleMessage(
  7108. AssertionInfo const& info,
  7109. ResultWas::OfType resultType,
  7110. StringRef const& message,
  7111. AssertionReaction& reaction
  7112. ) {
  7113. m_reporter->assertionStarting( info );
  7114. m_lastAssertionInfo = info;
  7115. AssertionResultData data( resultType, LazyExpression( false ) );
  7116. data.message = message;
  7117. AssertionResult assertionResult{ m_lastAssertionInfo, data };
  7118. assertionEnded( assertionResult );
  7119. if( !assertionResult.isOk() )
  7120. populateReaction( reaction );
  7121. }
  7122. void RunContext::handleUnexpectedExceptionNotThrown(
  7123. AssertionInfo const& info,
  7124. AssertionReaction& reaction
  7125. ) {
  7126. handleNonExpr(info, Catch::ResultWas::DidntThrowException, reaction);
  7127. }
  7128. void RunContext::handleUnexpectedInflightException(
  7129. AssertionInfo const& info,
  7130. std::string const& message,
  7131. AssertionReaction& reaction
  7132. ) {
  7133. m_lastAssertionInfo = info;
  7134. AssertionResultData data( ResultWas::ThrewException, LazyExpression( false ) );
  7135. data.message = message;
  7136. AssertionResult assertionResult{ info, data };
  7137. assertionEnded( assertionResult );
  7138. populateReaction( reaction );
  7139. }
  7140. void RunContext::populateReaction( AssertionReaction& reaction ) {
  7141. reaction.shouldDebugBreak = m_config->shouldDebugBreak();
  7142. reaction.shouldThrow = aborting() || (m_lastAssertionInfo.resultDisposition & ResultDisposition::Normal);
  7143. }
  7144. void RunContext::handleIncomplete(
  7145. AssertionInfo const& info
  7146. ) {
  7147. m_lastAssertionInfo = info;
  7148. AssertionResultData data( ResultWas::ThrewException, LazyExpression( false ) );
  7149. data.message = "Exception translation was disabled by CATCH_CONFIG_FAST_COMPILE";
  7150. AssertionResult assertionResult{ info, data };
  7151. assertionEnded( assertionResult );
  7152. }
  7153. void RunContext::handleNonExpr(
  7154. AssertionInfo const &info,
  7155. ResultWas::OfType resultType,
  7156. AssertionReaction &reaction
  7157. ) {
  7158. m_lastAssertionInfo = info;
  7159. AssertionResultData data( resultType, LazyExpression( false ) );
  7160. AssertionResult assertionResult{ info, data };
  7161. assertionEnded( assertionResult );
  7162. if( !assertionResult.isOk() )
  7163. populateReaction( reaction );
  7164. }
  7165. IResultCapture& getResultCapture() {
  7166. if (auto* capture = getCurrentContext().getResultCapture())
  7167. return *capture;
  7168. else
  7169. CATCH_INTERNAL_ERROR("No result capture instance");
  7170. }
  7171. }
  7172. // end catch_run_context.cpp
  7173. // start catch_section.cpp
  7174. namespace Catch {
  7175. Section::Section( SectionInfo const& info )
  7176. : m_info( info ),
  7177. m_sectionIncluded( getResultCapture().sectionStarted( m_info, m_assertions ) )
  7178. {
  7179. m_timer.start();
  7180. }
  7181. Section::~Section() {
  7182. if( m_sectionIncluded ) {
  7183. SectionEndInfo endInfo( m_info, m_assertions, m_timer.getElapsedSeconds() );
  7184. if( uncaught_exceptions() )
  7185. getResultCapture().sectionEndedEarly( endInfo );
  7186. else
  7187. getResultCapture().sectionEnded( endInfo );
  7188. }
  7189. }
  7190. // This indicates whether the section should be executed or not
  7191. Section::operator bool() const {
  7192. return m_sectionIncluded;
  7193. }
  7194. } // end namespace Catch
  7195. // end catch_section.cpp
  7196. // start catch_section_info.cpp
  7197. namespace Catch {
  7198. SectionInfo::SectionInfo
  7199. ( SourceLineInfo const& _lineInfo,
  7200. std::string const& _name,
  7201. std::string const& _description )
  7202. : name( _name ),
  7203. description( _description ),
  7204. lineInfo( _lineInfo )
  7205. {}
  7206. SectionEndInfo::SectionEndInfo( SectionInfo const& _sectionInfo, Counts const& _prevAssertions, double _durationInSeconds )
  7207. : sectionInfo( _sectionInfo ), prevAssertions( _prevAssertions ), durationInSeconds( _durationInSeconds )
  7208. {}
  7209. } // end namespace Catch
  7210. // end catch_section_info.cpp
  7211. // start catch_session.cpp
  7212. // start catch_session.h
  7213. #include <memory>
  7214. namespace Catch {
  7215. class Session : NonCopyable {
  7216. public:
  7217. Session();
  7218. ~Session() override;
  7219. void showHelp() const;
  7220. void libIdentify();
  7221. int applyCommandLine( int argc, char const * const * argv );
  7222. void useConfigData( ConfigData const& configData );
  7223. int run( int argc, char* argv[] );
  7224. #if defined(CATCH_CONFIG_WCHAR) && defined(WIN32) && defined(UNICODE)
  7225. int run( int argc, wchar_t* const argv[] );
  7226. #endif
  7227. int run();
  7228. clara::Parser const& cli() const;
  7229. void cli( clara::Parser const& newParser );
  7230. ConfigData& configData();
  7231. Config& config();
  7232. private:
  7233. int runInternal();
  7234. clara::Parser m_cli;
  7235. ConfigData m_configData;
  7236. std::shared_ptr<Config> m_config;
  7237. bool m_startupExceptions = false;
  7238. };
  7239. } // end namespace Catch
  7240. // end catch_session.h
  7241. // start catch_version.h
  7242. #include <iosfwd>
  7243. namespace Catch {
  7244. // Versioning information
  7245. struct Version {
  7246. Version( Version const& ) = delete;
  7247. Version& operator=( Version const& ) = delete;
  7248. Version( unsigned int _majorVersion,
  7249. unsigned int _minorVersion,
  7250. unsigned int _patchNumber,
  7251. char const * const _branchName,
  7252. unsigned int _buildNumber );
  7253. unsigned int const majorVersion;
  7254. unsigned int const minorVersion;
  7255. unsigned int const patchNumber;
  7256. // buildNumber is only used if branchName is not null
  7257. char const * const branchName;
  7258. unsigned int const buildNumber;
  7259. friend std::ostream& operator << ( std::ostream& os, Version const& version );
  7260. };
  7261. Version const& libraryVersion();
  7262. }
  7263. // end catch_version.h
  7264. #include <cstdlib>
  7265. #include <iomanip>
  7266. namespace Catch {
  7267. namespace {
  7268. const int MaxExitCode = 255;
  7269. IStreamingReporterPtr createReporter(std::string const& reporterName, IConfigPtr const& config) {
  7270. auto reporter = Catch::getRegistryHub().getReporterRegistry().create(reporterName, config);
  7271. CATCH_ENFORCE(reporter, "No reporter registered with name: '" << reporterName << "'");
  7272. return reporter;
  7273. }
  7274. #ifndef CATCH_CONFIG_DEFAULT_REPORTER
  7275. #define CATCH_CONFIG_DEFAULT_REPORTER "console"
  7276. #endif
  7277. IStreamingReporterPtr makeReporter(std::shared_ptr<Config> const& config) {
  7278. auto const& reporterNames = config->getReporterNames();
  7279. if (reporterNames.empty())
  7280. return createReporter(CATCH_CONFIG_DEFAULT_REPORTER, config);
  7281. IStreamingReporterPtr reporter;
  7282. for (auto const& name : reporterNames)
  7283. addReporter(reporter, createReporter(name, config));
  7284. return reporter;
  7285. }
  7286. #undef CATCH_CONFIG_DEFAULT_REPORTER
  7287. void addListeners(IStreamingReporterPtr& reporters, IConfigPtr const& config) {
  7288. auto const& listeners = Catch::getRegistryHub().getReporterRegistry().getListeners();
  7289. for (auto const& listener : listeners)
  7290. addReporter(reporters, listener->create(Catch::ReporterConfig(config)));
  7291. }
  7292. Catch::Totals runTests(std::shared_ptr<Config> const& config) {
  7293. IStreamingReporterPtr reporter = makeReporter(config);
  7294. addListeners(reporter, config);
  7295. RunContext context(config, std::move(reporter));
  7296. Totals totals;
  7297. context.testGroupStarting(config->name(), 1, 1);
  7298. TestSpec testSpec = config->testSpec();
  7299. auto const& allTestCases = getAllTestCasesSorted(*config);
  7300. for (auto const& testCase : allTestCases) {
  7301. if (!context.aborting() && matchTest(testCase, testSpec, *config))
  7302. totals += context.runTest(testCase);
  7303. else
  7304. context.reporter().skipTest(testCase);
  7305. }
  7306. if (config->warnAboutNoTests() && totals.testCases.total() == 0) {
  7307. ReusableStringStream testConfig;
  7308. bool first = true;
  7309. for (const auto& input : config->getTestsOrTags()) {
  7310. if (!first) { testConfig << ' '; }
  7311. first = false;
  7312. testConfig << input;
  7313. }
  7314. context.reporter().noMatchingTestCases(testConfig.str());
  7315. totals.error = -1;
  7316. }
  7317. context.testGroupEnded(config->name(), totals, 1, 1);
  7318. return totals;
  7319. }
  7320. void applyFilenamesAsTags(Catch::IConfig const& config) {
  7321. auto& tests = const_cast<std::vector<TestCase>&>(getAllTestCasesSorted(config));
  7322. for (auto& testCase : tests) {
  7323. auto tags = testCase.tags;
  7324. std::string filename = testCase.lineInfo.file;
  7325. auto lastSlash = filename.find_last_of("\\/");
  7326. if (lastSlash != std::string::npos) {
  7327. filename.erase(0, lastSlash);
  7328. filename[0] = '#';
  7329. }
  7330. auto lastDot = filename.find_last_of('.');
  7331. if (lastDot != std::string::npos) {
  7332. filename.erase(lastDot);
  7333. }
  7334. tags.push_back(std::move(filename));
  7335. setTags(testCase, tags);
  7336. }
  7337. }
  7338. } // anon namespace
  7339. Session::Session() {
  7340. static bool alreadyInstantiated = false;
  7341. if( alreadyInstantiated ) {
  7342. try { CATCH_INTERNAL_ERROR( "Only one instance of Catch::Session can ever be used" ); }
  7343. catch(...) { getMutableRegistryHub().registerStartupException(); }
  7344. }
  7345. const auto& exceptions = getRegistryHub().getStartupExceptionRegistry().getExceptions();
  7346. if ( !exceptions.empty() ) {
  7347. m_startupExceptions = true;
  7348. Colour colourGuard( Colour::Red );
  7349. Catch::cerr() << "Errors occurred during startup!" << '\n';
  7350. // iterate over all exceptions and notify user
  7351. for ( const auto& ex_ptr : exceptions ) {
  7352. try {
  7353. std::rethrow_exception(ex_ptr);
  7354. } catch ( std::exception const& ex ) {
  7355. Catch::cerr() << Column( ex.what() ).indent(2) << '\n';
  7356. }
  7357. }
  7358. }
  7359. alreadyInstantiated = true;
  7360. m_cli = makeCommandLineParser( m_configData );
  7361. }
  7362. Session::~Session() {
  7363. Catch::cleanUp();
  7364. }
  7365. void Session::showHelp() const {
  7366. Catch::cout()
  7367. << "\nCatch v" << libraryVersion() << "\n"
  7368. << m_cli << std::endl
  7369. << "For more detailed usage please see the project docs\n" << std::endl;
  7370. }
  7371. void Session::libIdentify() {
  7372. Catch::cout()
  7373. << std::left << std::setw(16) << "description: " << "A Catch test executable\n"
  7374. << std::left << std::setw(16) << "category: " << "testframework\n"
  7375. << std::left << std::setw(16) << "framework: " << "Catch Test\n"
  7376. << std::left << std::setw(16) << "version: " << libraryVersion() << std::endl;
  7377. }
  7378. int Session::applyCommandLine( int argc, char const * const * argv ) {
  7379. if( m_startupExceptions )
  7380. return 1;
  7381. auto result = m_cli.parse( clara::Args( argc, argv ) );
  7382. if( !result ) {
  7383. Catch::cerr()
  7384. << Colour( Colour::Red )
  7385. << "\nError(s) in input:\n"
  7386. << Column( result.errorMessage() ).indent( 2 )
  7387. << "\n\n";
  7388. Catch::cerr() << "Run with -? for usage\n" << std::endl;
  7389. return MaxExitCode;
  7390. }
  7391. if( m_configData.showHelp )
  7392. showHelp();
  7393. if( m_configData.libIdentify )
  7394. libIdentify();
  7395. m_config.reset();
  7396. return 0;
  7397. }
  7398. void Session::useConfigData( ConfigData const& configData ) {
  7399. m_configData = configData;
  7400. m_config.reset();
  7401. }
  7402. int Session::run( int argc, char* argv[] ) {
  7403. if( m_startupExceptions )
  7404. return 1;
  7405. int returnCode = applyCommandLine( argc, argv );
  7406. if( returnCode == 0 )
  7407. returnCode = run();
  7408. return returnCode;
  7409. }
  7410. #if defined(CATCH_CONFIG_WCHAR) && defined(WIN32) && defined(UNICODE)
  7411. int Session::run( int argc, wchar_t* const argv[] ) {
  7412. char **utf8Argv = new char *[ argc ];
  7413. for ( int i = 0; i < argc; ++i ) {
  7414. int bufSize = WideCharToMultiByte( CP_UTF8, 0, argv[i], -1, NULL, 0, NULL, NULL );
  7415. utf8Argv[ i ] = new char[ bufSize ];
  7416. WideCharToMultiByte( CP_UTF8, 0, argv[i], -1, utf8Argv[i], bufSize, NULL, NULL );
  7417. }
  7418. int returnCode = run( argc, utf8Argv );
  7419. for ( int i = 0; i < argc; ++i )
  7420. delete [] utf8Argv[ i ];
  7421. delete [] utf8Argv;
  7422. return returnCode;
  7423. }
  7424. #endif
  7425. int Session::run() {
  7426. if( ( m_configData.waitForKeypress & WaitForKeypress::BeforeStart ) != 0 ) {
  7427. Catch::cout() << "...waiting for enter/ return before starting" << std::endl;
  7428. static_cast<void>(std::getchar());
  7429. }
  7430. int exitCode = runInternal();
  7431. if( ( m_configData.waitForKeypress & WaitForKeypress::BeforeExit ) != 0 ) {
  7432. Catch::cout() << "...waiting for enter/ return before exiting, with code: " << exitCode << std::endl;
  7433. static_cast<void>(std::getchar());
  7434. }
  7435. return exitCode;
  7436. }
  7437. clara::Parser const& Session::cli() const {
  7438. return m_cli;
  7439. }
  7440. void Session::cli( clara::Parser const& newParser ) {
  7441. m_cli = newParser;
  7442. }
  7443. ConfigData& Session::configData() {
  7444. return m_configData;
  7445. }
  7446. Config& Session::config() {
  7447. if( !m_config )
  7448. m_config = std::make_shared<Config>( m_configData );
  7449. return *m_config;
  7450. }
  7451. int Session::runInternal() {
  7452. if( m_startupExceptions )
  7453. return 1;
  7454. if( m_configData.showHelp || m_configData.libIdentify )
  7455. return 0;
  7456. try
  7457. {
  7458. config(); // Force config to be constructed
  7459. seedRng( *m_config );
  7460. if( m_configData.filenamesAsTags )
  7461. applyFilenamesAsTags( *m_config );
  7462. // Handle list request
  7463. if( Option<std::size_t> listed = list( config() ) )
  7464. return static_cast<int>( *listed );
  7465. auto totals = runTests( m_config );
  7466. // Note that on unices only the lower 8 bits are usually used, clamping
  7467. // the return value to 255 prevents false negative when some multiple
  7468. // of 256 tests has failed
  7469. return (std::min) (MaxExitCode, (std::max) (totals.error, static_cast<int>(totals.assertions.failed)));
  7470. }
  7471. catch( std::exception& ex ) {
  7472. Catch::cerr() << ex.what() << std::endl;
  7473. return MaxExitCode;
  7474. }
  7475. }
  7476. } // end namespace Catch
  7477. // end catch_session.cpp
  7478. // start catch_startup_exception_registry.cpp
  7479. namespace Catch {
  7480. void StartupExceptionRegistry::add( std::exception_ptr const& exception ) noexcept {
  7481. try {
  7482. m_exceptions.push_back(exception);
  7483. }
  7484. catch(...) {
  7485. // If we run out of memory during start-up there's really not a lot more we can do about it
  7486. std::terminate();
  7487. }
  7488. }
  7489. std::vector<std::exception_ptr> const& StartupExceptionRegistry::getExceptions() const noexcept {
  7490. return m_exceptions;
  7491. }
  7492. } // end namespace Catch
  7493. // end catch_startup_exception_registry.cpp
  7494. // start catch_stream.cpp
  7495. #include <cstdio>
  7496. #include <iostream>
  7497. #include <fstream>
  7498. #include <sstream>
  7499. #include <vector>
  7500. #include <memory>
  7501. #if defined(__clang__)
  7502. # pragma clang diagnostic push
  7503. # pragma clang diagnostic ignored "-Wexit-time-destructors"
  7504. #endif
  7505. namespace Catch {
  7506. Catch::IStream::~IStream() = default;
  7507. namespace detail { namespace {
  7508. template<typename WriterF, std::size_t bufferSize=256>
  7509. class StreamBufImpl : public std::streambuf {
  7510. char data[bufferSize];
  7511. WriterF m_writer;
  7512. public:
  7513. StreamBufImpl() {
  7514. setp( data, data + sizeof(data) );
  7515. }
  7516. ~StreamBufImpl() noexcept {
  7517. StreamBufImpl::sync();
  7518. }
  7519. private:
  7520. int overflow( int c ) override {
  7521. sync();
  7522. if( c != EOF ) {
  7523. if( pbase() == epptr() )
  7524. m_writer( std::string( 1, static_cast<char>( c ) ) );
  7525. else
  7526. sputc( static_cast<char>( c ) );
  7527. }
  7528. return 0;
  7529. }
  7530. int sync() override {
  7531. if( pbase() != pptr() ) {
  7532. m_writer( std::string( pbase(), static_cast<std::string::size_type>( pptr() - pbase() ) ) );
  7533. setp( pbase(), epptr() );
  7534. }
  7535. return 0;
  7536. }
  7537. };
  7538. ///////////////////////////////////////////////////////////////////////////
  7539. struct OutputDebugWriter {
  7540. void operator()( std::string const&str ) {
  7541. writeToDebugConsole( str );
  7542. }
  7543. };
  7544. ///////////////////////////////////////////////////////////////////////////
  7545. class FileStream : public IStream {
  7546. mutable std::ofstream m_ofs;
  7547. public:
  7548. FileStream( StringRef filename ) {
  7549. m_ofs.open( filename.c_str() );
  7550. CATCH_ENFORCE( !m_ofs.fail(), "Unable to open file: '" << filename << "'" );
  7551. }
  7552. ~FileStream() override = default;
  7553. public: // IStream
  7554. std::ostream& stream() const override {
  7555. return m_ofs;
  7556. }
  7557. };
  7558. ///////////////////////////////////////////////////////////////////////////
  7559. class CoutStream : public IStream {
  7560. mutable std::ostream m_os;
  7561. public:
  7562. // Store the streambuf from cout up-front because
  7563. // cout may get redirected when running tests
  7564. CoutStream() : m_os( Catch::cout().rdbuf() ) {}
  7565. ~CoutStream() override = default;
  7566. public: // IStream
  7567. std::ostream& stream() const override { return m_os; }
  7568. };
  7569. ///////////////////////////////////////////////////////////////////////////
  7570. class DebugOutStream : public IStream {
  7571. std::unique_ptr<StreamBufImpl<OutputDebugWriter>> m_streamBuf;
  7572. mutable std::ostream m_os;
  7573. public:
  7574. DebugOutStream()
  7575. : m_streamBuf( new StreamBufImpl<OutputDebugWriter>() ),
  7576. m_os( m_streamBuf.get() )
  7577. {}
  7578. ~DebugOutStream() override = default;
  7579. public: // IStream
  7580. std::ostream& stream() const override { return m_os; }
  7581. };
  7582. }} // namespace anon::detail
  7583. ///////////////////////////////////////////////////////////////////////////
  7584. auto makeStream( StringRef const &filename ) -> IStream const* {
  7585. if( filename.empty() )
  7586. return new detail::CoutStream();
  7587. else if( filename[0] == '%' ) {
  7588. if( filename == "%debug" )
  7589. return new detail::DebugOutStream();
  7590. else
  7591. CATCH_ERROR( "Unrecognised stream: '" << filename << "'" );
  7592. }
  7593. else
  7594. return new detail::FileStream( filename );
  7595. }
  7596. // This class encapsulates the idea of a pool of ostringstreams that can be reused.
  7597. struct StringStreams {
  7598. std::vector<std::unique_ptr<std::ostringstream>> m_streams;
  7599. std::vector<std::size_t> m_unused;
  7600. std::ostringstream m_referenceStream; // Used for copy state/ flags from
  7601. static StringStreams* s_instance;
  7602. auto add() -> std::size_t {
  7603. if( m_unused.empty() ) {
  7604. m_streams.push_back( std::unique_ptr<std::ostringstream>( new std::ostringstream ) );
  7605. return m_streams.size()-1;
  7606. }
  7607. else {
  7608. auto index = m_unused.back();
  7609. m_unused.pop_back();
  7610. return index;
  7611. }
  7612. }
  7613. void release( std::size_t index ) {
  7614. m_streams[index]->copyfmt( m_referenceStream ); // Restore initial flags and other state
  7615. m_unused.push_back(index);
  7616. }
  7617. // !TBD: put in TLS
  7618. static auto instance() -> StringStreams& {
  7619. if( !s_instance )
  7620. s_instance = new StringStreams();
  7621. return *s_instance;
  7622. }
  7623. static void cleanup() {
  7624. delete s_instance;
  7625. s_instance = nullptr;
  7626. }
  7627. };
  7628. StringStreams* StringStreams::s_instance = nullptr;
  7629. void ReusableStringStream::cleanup() {
  7630. StringStreams::cleanup();
  7631. }
  7632. ReusableStringStream::ReusableStringStream()
  7633. : m_index( StringStreams::instance().add() ),
  7634. m_oss( StringStreams::instance().m_streams[m_index].get() )
  7635. {}
  7636. ReusableStringStream::~ReusableStringStream() {
  7637. static_cast<std::ostringstream*>( m_oss )->str("");
  7638. m_oss->clear();
  7639. StringStreams::instance().release( m_index );
  7640. }
  7641. auto ReusableStringStream::str() const -> std::string {
  7642. return static_cast<std::ostringstream*>( m_oss )->str();
  7643. }
  7644. ///////////////////////////////////////////////////////////////////////////
  7645. #ifndef CATCH_CONFIG_NOSTDOUT // If you #define this you must implement these functions
  7646. std::ostream& cout() { return std::cout; }
  7647. std::ostream& cerr() { return std::cerr; }
  7648. std::ostream& clog() { return std::clog; }
  7649. #endif
  7650. }
  7651. #if defined(__clang__)
  7652. # pragma clang diagnostic pop
  7653. #endif
  7654. // end catch_stream.cpp
  7655. // start catch_string_manip.cpp
  7656. #include <algorithm>
  7657. #include <ostream>
  7658. #include <cstring>
  7659. #include <cctype>
  7660. namespace Catch {
  7661. bool startsWith( std::string const& s, std::string const& prefix ) {
  7662. return s.size() >= prefix.size() && std::equal(prefix.begin(), prefix.end(), s.begin());
  7663. }
  7664. bool startsWith( std::string const& s, char prefix ) {
  7665. return !s.empty() && s[0] == prefix;
  7666. }
  7667. bool endsWith( std::string const& s, std::string const& suffix ) {
  7668. return s.size() >= suffix.size() && std::equal(suffix.rbegin(), suffix.rend(), s.rbegin());
  7669. }
  7670. bool endsWith( std::string const& s, char suffix ) {
  7671. return !s.empty() && s[s.size()-1] == suffix;
  7672. }
  7673. bool contains( std::string const& s, std::string const& infix ) {
  7674. return s.find( infix ) != std::string::npos;
  7675. }
  7676. char toLowerCh(char c) {
  7677. return static_cast<char>( std::tolower( c ) );
  7678. }
  7679. void toLowerInPlace( std::string& s ) {
  7680. std::transform( s.begin(), s.end(), s.begin(), toLowerCh );
  7681. }
  7682. std::string toLower( std::string const& s ) {
  7683. std::string lc = s;
  7684. toLowerInPlace( lc );
  7685. return lc;
  7686. }
  7687. std::string trim( std::string const& str ) {
  7688. static char const* whitespaceChars = "\n\r\t ";
  7689. std::string::size_type start = str.find_first_not_of( whitespaceChars );
  7690. std::string::size_type end = str.find_last_not_of( whitespaceChars );
  7691. return start != std::string::npos ? str.substr( start, 1+end-start ) : std::string();
  7692. }
  7693. bool replaceInPlace( std::string& str, std::string const& replaceThis, std::string const& withThis ) {
  7694. bool replaced = false;
  7695. std::size_t i = str.find( replaceThis );
  7696. while( i != std::string::npos ) {
  7697. replaced = true;
  7698. str = str.substr( 0, i ) + withThis + str.substr( i+replaceThis.size() );
  7699. if( i < str.size()-withThis.size() )
  7700. i = str.find( replaceThis, i+withThis.size() );
  7701. else
  7702. i = std::string::npos;
  7703. }
  7704. return replaced;
  7705. }
  7706. pluralise::pluralise( std::size_t count, std::string const& label )
  7707. : m_count( count ),
  7708. m_label( label )
  7709. {}
  7710. std::ostream& operator << ( std::ostream& os, pluralise const& pluraliser ) {
  7711. os << pluraliser.m_count << ' ' << pluraliser.m_label;
  7712. if( pluraliser.m_count != 1 )
  7713. os << 's';
  7714. return os;
  7715. }
  7716. }
  7717. // end catch_string_manip.cpp
  7718. // start catch_stringref.cpp
  7719. #if defined(__clang__)
  7720. # pragma clang diagnostic push
  7721. # pragma clang diagnostic ignored "-Wexit-time-destructors"
  7722. #endif
  7723. #include <ostream>
  7724. #include <cstring>
  7725. #include <cstdint>
  7726. namespace {
  7727. const uint32_t byte_2_lead = 0xC0;
  7728. const uint32_t byte_3_lead = 0xE0;
  7729. const uint32_t byte_4_lead = 0xF0;
  7730. }
  7731. namespace Catch {
  7732. StringRef::StringRef( char const* rawChars ) noexcept
  7733. : StringRef( rawChars, static_cast<StringRef::size_type>(std::strlen(rawChars) ) )
  7734. {}
  7735. StringRef::operator std::string() const {
  7736. return std::string( m_start, m_size );
  7737. }
  7738. void StringRef::swap( StringRef& other ) noexcept {
  7739. std::swap( m_start, other.m_start );
  7740. std::swap( m_size, other.m_size );
  7741. std::swap( m_data, other.m_data );
  7742. }
  7743. auto StringRef::c_str() const -> char const* {
  7744. if( isSubstring() )
  7745. const_cast<StringRef*>( this )->takeOwnership();
  7746. return m_start;
  7747. }
  7748. auto StringRef::currentData() const noexcept -> char const* {
  7749. return m_start;
  7750. }
  7751. auto StringRef::isOwned() const noexcept -> bool {
  7752. return m_data != nullptr;
  7753. }
  7754. auto StringRef::isSubstring() const noexcept -> bool {
  7755. return m_start[m_size] != '\0';
  7756. }
  7757. void StringRef::takeOwnership() {
  7758. if( !isOwned() ) {
  7759. m_data = new char[m_size+1];
  7760. memcpy( m_data, m_start, m_size );
  7761. m_data[m_size] = '\0';
  7762. m_start = m_data;
  7763. }
  7764. }
  7765. auto StringRef::substr( size_type start, size_type size ) const noexcept -> StringRef {
  7766. if( start < m_size )
  7767. return StringRef( m_start+start, size );
  7768. else
  7769. return StringRef();
  7770. }
  7771. auto StringRef::operator == ( StringRef const& other ) const noexcept -> bool {
  7772. return
  7773. size() == other.size() &&
  7774. (std::strncmp( m_start, other.m_start, size() ) == 0);
  7775. }
  7776. auto StringRef::operator != ( StringRef const& other ) const noexcept -> bool {
  7777. return !operator==( other );
  7778. }
  7779. auto StringRef::operator[](size_type index) const noexcept -> char {
  7780. return m_start[index];
  7781. }
  7782. auto StringRef::numberOfCharacters() const noexcept -> size_type {
  7783. size_type noChars = m_size;
  7784. // Make adjustments for uft encodings
  7785. for( size_type i=0; i < m_size; ++i ) {
  7786. char c = m_start[i];
  7787. if( ( c & byte_2_lead ) == byte_2_lead ) {
  7788. noChars--;
  7789. if (( c & byte_3_lead ) == byte_3_lead )
  7790. noChars--;
  7791. if( ( c & byte_4_lead ) == byte_4_lead )
  7792. noChars--;
  7793. }
  7794. }
  7795. return noChars;
  7796. }
  7797. auto operator + ( StringRef const& lhs, StringRef const& rhs ) -> std::string {
  7798. std::string str;
  7799. str.reserve( lhs.size() + rhs.size() );
  7800. str += lhs;
  7801. str += rhs;
  7802. return str;
  7803. }
  7804. auto operator + ( StringRef const& lhs, const char* rhs ) -> std::string {
  7805. return std::string( lhs ) + std::string( rhs );
  7806. }
  7807. auto operator + ( char const* lhs, StringRef const& rhs ) -> std::string {
  7808. return std::string( lhs ) + std::string( rhs );
  7809. }
  7810. auto operator << ( std::ostream& os, StringRef const& str ) -> std::ostream& {
  7811. return os.write(str.currentData(), str.size());
  7812. }
  7813. auto operator+=( std::string& lhs, StringRef const& rhs ) -> std::string& {
  7814. lhs.append(rhs.currentData(), rhs.size());
  7815. return lhs;
  7816. }
  7817. } // namespace Catch
  7818. #if defined(__clang__)
  7819. # pragma clang diagnostic pop
  7820. #endif
  7821. // end catch_stringref.cpp
  7822. // start catch_tag_alias.cpp
  7823. namespace Catch {
  7824. TagAlias::TagAlias(std::string const & _tag, SourceLineInfo _lineInfo): tag(_tag), lineInfo(_lineInfo) {}
  7825. }
  7826. // end catch_tag_alias.cpp
  7827. // start catch_tag_alias_autoregistrar.cpp
  7828. namespace Catch {
  7829. RegistrarForTagAliases::RegistrarForTagAliases(char const* alias, char const* tag, SourceLineInfo const& lineInfo) {
  7830. try {
  7831. getMutableRegistryHub().registerTagAlias(alias, tag, lineInfo);
  7832. } catch (...) {
  7833. // Do not throw when constructing global objects, instead register the exception to be processed later
  7834. getMutableRegistryHub().registerStartupException();
  7835. }
  7836. }
  7837. }
  7838. // end catch_tag_alias_autoregistrar.cpp
  7839. // start catch_tag_alias_registry.cpp
  7840. #include <sstream>
  7841. namespace Catch {
  7842. TagAliasRegistry::~TagAliasRegistry() {}
  7843. TagAlias const* TagAliasRegistry::find( std::string const& alias ) const {
  7844. auto it = m_registry.find( alias );
  7845. if( it != m_registry.end() )
  7846. return &(it->second);
  7847. else
  7848. return nullptr;
  7849. }
  7850. std::string TagAliasRegistry::expandAliases( std::string const& unexpandedTestSpec ) const {
  7851. std::string expandedTestSpec = unexpandedTestSpec;
  7852. for( auto const& registryKvp : m_registry ) {
  7853. std::size_t pos = expandedTestSpec.find( registryKvp.first );
  7854. if( pos != std::string::npos ) {
  7855. expandedTestSpec = expandedTestSpec.substr( 0, pos ) +
  7856. registryKvp.second.tag +
  7857. expandedTestSpec.substr( pos + registryKvp.first.size() );
  7858. }
  7859. }
  7860. return expandedTestSpec;
  7861. }
  7862. void TagAliasRegistry::add( std::string const& alias, std::string const& tag, SourceLineInfo const& lineInfo ) {
  7863. CATCH_ENFORCE( startsWith(alias, "[@") && endsWith(alias, ']'),
  7864. "error: tag alias, '" << alias << "' is not of the form [@alias name].\n" << lineInfo );
  7865. CATCH_ENFORCE( m_registry.insert(std::make_pair(alias, TagAlias(tag, lineInfo))).second,
  7866. "error: tag alias, '" << alias << "' already registered.\n"
  7867. << "\tFirst seen at: " << find(alias)->lineInfo << "\n"
  7868. << "\tRedefined at: " << lineInfo );
  7869. }
  7870. ITagAliasRegistry::~ITagAliasRegistry() {}
  7871. ITagAliasRegistry const& ITagAliasRegistry::get() {
  7872. return getRegistryHub().getTagAliasRegistry();
  7873. }
  7874. } // end namespace Catch
  7875. // end catch_tag_alias_registry.cpp
  7876. // start catch_test_case_info.cpp
  7877. #include <cctype>
  7878. #include <exception>
  7879. #include <algorithm>
  7880. #include <sstream>
  7881. namespace Catch {
  7882. TestCaseInfo::SpecialProperties parseSpecialTag( std::string const& tag ) {
  7883. if( startsWith( tag, '.' ) ||
  7884. tag == "!hide" )
  7885. return TestCaseInfo::IsHidden;
  7886. else if( tag == "!throws" )
  7887. return TestCaseInfo::Throws;
  7888. else if( tag == "!shouldfail" )
  7889. return TestCaseInfo::ShouldFail;
  7890. else if( tag == "!mayfail" )
  7891. return TestCaseInfo::MayFail;
  7892. else if( tag == "!nonportable" )
  7893. return TestCaseInfo::NonPortable;
  7894. else if( tag == "!benchmark" )
  7895. return static_cast<TestCaseInfo::SpecialProperties>( TestCaseInfo::Benchmark | TestCaseInfo::IsHidden );
  7896. else
  7897. return TestCaseInfo::None;
  7898. }
  7899. bool isReservedTag( std::string const& tag ) {
  7900. return parseSpecialTag( tag ) == TestCaseInfo::None && tag.size() > 0 && !std::isalnum( tag[0] );
  7901. }
  7902. void enforceNotReservedTag( std::string const& tag, SourceLineInfo const& _lineInfo ) {
  7903. CATCH_ENFORCE( !isReservedTag(tag),
  7904. "Tag name: [" << tag << "] is not allowed.\n"
  7905. << "Tag names starting with non alpha-numeric characters are reserved\n"
  7906. << _lineInfo );
  7907. }
  7908. TestCase makeTestCase( ITestInvoker* _testCase,
  7909. std::string const& _className,
  7910. NameAndTags const& nameAndTags,
  7911. SourceLineInfo const& _lineInfo )
  7912. {
  7913. bool isHidden = false;
  7914. // Parse out tags
  7915. std::vector<std::string> tags;
  7916. std::string desc, tag;
  7917. bool inTag = false;
  7918. std::string _descOrTags = nameAndTags.tags;
  7919. for (char c : _descOrTags) {
  7920. if( !inTag ) {
  7921. if( c == '[' )
  7922. inTag = true;
  7923. else
  7924. desc += c;
  7925. }
  7926. else {
  7927. if( c == ']' ) {
  7928. TestCaseInfo::SpecialProperties prop = parseSpecialTag( tag );
  7929. if( ( prop & TestCaseInfo::IsHidden ) != 0 )
  7930. isHidden = true;
  7931. else if( prop == TestCaseInfo::None )
  7932. enforceNotReservedTag( tag, _lineInfo );
  7933. tags.push_back( tag );
  7934. tag.clear();
  7935. inTag = false;
  7936. }
  7937. else
  7938. tag += c;
  7939. }
  7940. }
  7941. if( isHidden ) {
  7942. tags.push_back( "." );
  7943. }
  7944. TestCaseInfo info( nameAndTags.name, _className, desc, tags, _lineInfo );
  7945. return TestCase( _testCase, std::move(info) );
  7946. }
  7947. void setTags( TestCaseInfo& testCaseInfo, std::vector<std::string> tags ) {
  7948. std::sort(begin(tags), end(tags));
  7949. tags.erase(std::unique(begin(tags), end(tags)), end(tags));
  7950. testCaseInfo.lcaseTags.clear();
  7951. for( auto const& tag : tags ) {
  7952. std::string lcaseTag = toLower( tag );
  7953. testCaseInfo.properties = static_cast<TestCaseInfo::SpecialProperties>( testCaseInfo.properties | parseSpecialTag( lcaseTag ) );
  7954. testCaseInfo.lcaseTags.push_back( lcaseTag );
  7955. }
  7956. testCaseInfo.tags = std::move(tags);
  7957. }
  7958. TestCaseInfo::TestCaseInfo( std::string const& _name,
  7959. std::string const& _className,
  7960. std::string const& _description,
  7961. std::vector<std::string> const& _tags,
  7962. SourceLineInfo const& _lineInfo )
  7963. : name( _name ),
  7964. className( _className ),
  7965. description( _description ),
  7966. lineInfo( _lineInfo ),
  7967. properties( None )
  7968. {
  7969. setTags( *this, _tags );
  7970. }
  7971. bool TestCaseInfo::isHidden() const {
  7972. return ( properties & IsHidden ) != 0;
  7973. }
  7974. bool TestCaseInfo::throws() const {
  7975. return ( properties & Throws ) != 0;
  7976. }
  7977. bool TestCaseInfo::okToFail() const {
  7978. return ( properties & (ShouldFail | MayFail ) ) != 0;
  7979. }
  7980. bool TestCaseInfo::expectedToFail() const {
  7981. return ( properties & (ShouldFail ) ) != 0;
  7982. }
  7983. std::string TestCaseInfo::tagsAsString() const {
  7984. std::string ret;
  7985. // '[' and ']' per tag
  7986. std::size_t full_size = 2 * tags.size();
  7987. for (const auto& tag : tags) {
  7988. full_size += tag.size();
  7989. }
  7990. ret.reserve(full_size);
  7991. for (const auto& tag : tags) {
  7992. ret.push_back('[');
  7993. ret.append(tag);
  7994. ret.push_back(']');
  7995. }
  7996. return ret;
  7997. }
  7998. TestCase::TestCase( ITestInvoker* testCase, TestCaseInfo&& info ) : TestCaseInfo( std::move(info) ), test( testCase ) {}
  7999. TestCase TestCase::withName( std::string const& _newName ) const {
  8000. TestCase other( *this );
  8001. other.name = _newName;
  8002. return other;
  8003. }
  8004. void TestCase::invoke() const {
  8005. test->invoke();
  8006. }
  8007. bool TestCase::operator == ( TestCase const& other ) const {
  8008. return test.get() == other.test.get() &&
  8009. name == other.name &&
  8010. className == other.className;
  8011. }
  8012. bool TestCase::operator < ( TestCase const& other ) const {
  8013. return name < other.name;
  8014. }
  8015. TestCaseInfo const& TestCase::getTestCaseInfo() const
  8016. {
  8017. return *this;
  8018. }
  8019. } // end namespace Catch
  8020. // end catch_test_case_info.cpp
  8021. // start catch_test_case_registry_impl.cpp
  8022. #include <sstream>
  8023. namespace Catch {
  8024. std::vector<TestCase> sortTests( IConfig const& config, std::vector<TestCase> const& unsortedTestCases ) {
  8025. std::vector<TestCase> sorted = unsortedTestCases;
  8026. switch( config.runOrder() ) {
  8027. case RunTests::InLexicographicalOrder:
  8028. std::sort( sorted.begin(), sorted.end() );
  8029. break;
  8030. case RunTests::InRandomOrder:
  8031. seedRng( config );
  8032. RandomNumberGenerator::shuffle( sorted );
  8033. break;
  8034. case RunTests::InDeclarationOrder:
  8035. // already in declaration order
  8036. break;
  8037. }
  8038. return sorted;
  8039. }
  8040. bool matchTest( TestCase const& testCase, TestSpec const& testSpec, IConfig const& config ) {
  8041. return testSpec.matches( testCase ) && ( config.allowThrows() || !testCase.throws() );
  8042. }
  8043. void enforceNoDuplicateTestCases( std::vector<TestCase> const& functions ) {
  8044. std::set<TestCase> seenFunctions;
  8045. for( auto const& function : functions ) {
  8046. auto prev = seenFunctions.insert( function );
  8047. CATCH_ENFORCE( prev.second,
  8048. "error: TEST_CASE( \"" << function.name << "\" ) already defined.\n"
  8049. << "\tFirst seen at " << prev.first->getTestCaseInfo().lineInfo << "\n"
  8050. << "\tRedefined at " << function.getTestCaseInfo().lineInfo );
  8051. }
  8052. }
  8053. std::vector<TestCase> filterTests( std::vector<TestCase> const& testCases, TestSpec const& testSpec, IConfig const& config ) {
  8054. std::vector<TestCase> filtered;
  8055. filtered.reserve( testCases.size() );
  8056. for( auto const& testCase : testCases )
  8057. if( matchTest( testCase, testSpec, config ) )
  8058. filtered.push_back( testCase );
  8059. return filtered;
  8060. }
  8061. std::vector<TestCase> const& getAllTestCasesSorted( IConfig const& config ) {
  8062. return getRegistryHub().getTestCaseRegistry().getAllTestsSorted( config );
  8063. }
  8064. void TestRegistry::registerTest( TestCase const& testCase ) {
  8065. std::string name = testCase.getTestCaseInfo().name;
  8066. if( name.empty() ) {
  8067. ReusableStringStream rss;
  8068. rss << "Anonymous test case " << ++m_unnamedCount;
  8069. return registerTest( testCase.withName( rss.str() ) );
  8070. }
  8071. m_functions.push_back( testCase );
  8072. }
  8073. std::vector<TestCase> const& TestRegistry::getAllTests() const {
  8074. return m_functions;
  8075. }
  8076. std::vector<TestCase> const& TestRegistry::getAllTestsSorted( IConfig const& config ) const {
  8077. if( m_sortedFunctions.empty() )
  8078. enforceNoDuplicateTestCases( m_functions );
  8079. if( m_currentSortOrder != config.runOrder() || m_sortedFunctions.empty() ) {
  8080. m_sortedFunctions = sortTests( config, m_functions );
  8081. m_currentSortOrder = config.runOrder();
  8082. }
  8083. return m_sortedFunctions;
  8084. }
  8085. ///////////////////////////////////////////////////////////////////////////
  8086. TestInvokerAsFunction::TestInvokerAsFunction( void(*testAsFunction)() ) noexcept : m_testAsFunction( testAsFunction ) {}
  8087. void TestInvokerAsFunction::invoke() const {
  8088. m_testAsFunction();
  8089. }
  8090. std::string extractClassName( StringRef const& classOrQualifiedMethodName ) {
  8091. std::string className = classOrQualifiedMethodName;
  8092. if( startsWith( className, '&' ) )
  8093. {
  8094. std::size_t lastColons = className.rfind( "::" );
  8095. std::size_t penultimateColons = className.rfind( "::", lastColons-1 );
  8096. if( penultimateColons == std::string::npos )
  8097. penultimateColons = 1;
  8098. className = className.substr( penultimateColons, lastColons-penultimateColons );
  8099. }
  8100. return className;
  8101. }
  8102. } // end namespace Catch
  8103. // end catch_test_case_registry_impl.cpp
  8104. // start catch_test_case_tracker.cpp
  8105. #include <algorithm>
  8106. #include <assert.h>
  8107. #include <stdexcept>
  8108. #include <memory>
  8109. #include <sstream>
  8110. #if defined(__clang__)
  8111. # pragma clang diagnostic push
  8112. # pragma clang diagnostic ignored "-Wexit-time-destructors"
  8113. #endif
  8114. namespace Catch {
  8115. namespace TestCaseTracking {
  8116. NameAndLocation::NameAndLocation( std::string const& _name, SourceLineInfo const& _location )
  8117. : name( _name ),
  8118. location( _location )
  8119. {}
  8120. ITracker::~ITracker() = default;
  8121. TrackerContext& TrackerContext::instance() {
  8122. static TrackerContext s_instance;
  8123. return s_instance;
  8124. }
  8125. ITracker& TrackerContext::startRun() {
  8126. m_rootTracker = std::make_shared<SectionTracker>( NameAndLocation( "{root}", CATCH_INTERNAL_LINEINFO ), *this, nullptr );
  8127. m_currentTracker = nullptr;
  8128. m_runState = Executing;
  8129. return *m_rootTracker;
  8130. }
  8131. void TrackerContext::endRun() {
  8132. m_rootTracker.reset();
  8133. m_currentTracker = nullptr;
  8134. m_runState = NotStarted;
  8135. }
  8136. void TrackerContext::startCycle() {
  8137. m_currentTracker = m_rootTracker.get();
  8138. m_runState = Executing;
  8139. }
  8140. void TrackerContext::completeCycle() {
  8141. m_runState = CompletedCycle;
  8142. }
  8143. bool TrackerContext::completedCycle() const {
  8144. return m_runState == CompletedCycle;
  8145. }
  8146. ITracker& TrackerContext::currentTracker() {
  8147. return *m_currentTracker;
  8148. }
  8149. void TrackerContext::setCurrentTracker( ITracker* tracker ) {
  8150. m_currentTracker = tracker;
  8151. }
  8152. TrackerBase::TrackerHasName::TrackerHasName( NameAndLocation const& nameAndLocation ) : m_nameAndLocation( nameAndLocation ) {}
  8153. bool TrackerBase::TrackerHasName::operator ()( ITrackerPtr const& tracker ) const {
  8154. return
  8155. tracker->nameAndLocation().name == m_nameAndLocation.name &&
  8156. tracker->nameAndLocation().location == m_nameAndLocation.location;
  8157. }
  8158. TrackerBase::TrackerBase( NameAndLocation const& nameAndLocation, TrackerContext& ctx, ITracker* parent )
  8159. : m_nameAndLocation( nameAndLocation ),
  8160. m_ctx( ctx ),
  8161. m_parent( parent )
  8162. {}
  8163. NameAndLocation const& TrackerBase::nameAndLocation() const {
  8164. return m_nameAndLocation;
  8165. }
  8166. bool TrackerBase::isComplete() const {
  8167. return m_runState == CompletedSuccessfully || m_runState == Failed;
  8168. }
  8169. bool TrackerBase::isSuccessfullyCompleted() const {
  8170. return m_runState == CompletedSuccessfully;
  8171. }
  8172. bool TrackerBase::isOpen() const {
  8173. return m_runState != NotStarted && !isComplete();
  8174. }
  8175. bool TrackerBase::hasChildren() const {
  8176. return !m_children.empty();
  8177. }
  8178. void TrackerBase::addChild( ITrackerPtr const& child ) {
  8179. m_children.push_back( child );
  8180. }
  8181. ITrackerPtr TrackerBase::findChild( NameAndLocation const& nameAndLocation ) {
  8182. auto it = std::find_if( m_children.begin(), m_children.end(), TrackerHasName( nameAndLocation ) );
  8183. return( it != m_children.end() )
  8184. ? *it
  8185. : nullptr;
  8186. }
  8187. ITracker& TrackerBase::parent() {
  8188. assert( m_parent ); // Should always be non-null except for root
  8189. return *m_parent;
  8190. }
  8191. void TrackerBase::openChild() {
  8192. if( m_runState != ExecutingChildren ) {
  8193. m_runState = ExecutingChildren;
  8194. if( m_parent )
  8195. m_parent->openChild();
  8196. }
  8197. }
  8198. bool TrackerBase::isSectionTracker() const { return false; }
  8199. bool TrackerBase::isIndexTracker() const { return false; }
  8200. void TrackerBase::open() {
  8201. m_runState = Executing;
  8202. moveToThis();
  8203. if( m_parent )
  8204. m_parent->openChild();
  8205. }
  8206. void TrackerBase::close() {
  8207. // Close any still open children (e.g. generators)
  8208. while( &m_ctx.currentTracker() != this )
  8209. m_ctx.currentTracker().close();
  8210. switch( m_runState ) {
  8211. case NeedsAnotherRun:
  8212. break;
  8213. case Executing:
  8214. m_runState = CompletedSuccessfully;
  8215. break;
  8216. case ExecutingChildren:
  8217. if( m_children.empty() || m_children.back()->isComplete() )
  8218. m_runState = CompletedSuccessfully;
  8219. break;
  8220. case NotStarted:
  8221. case CompletedSuccessfully:
  8222. case Failed:
  8223. CATCH_INTERNAL_ERROR( "Illogical state: " << m_runState );
  8224. default:
  8225. CATCH_INTERNAL_ERROR( "Unknown state: " << m_runState );
  8226. }
  8227. moveToParent();
  8228. m_ctx.completeCycle();
  8229. }
  8230. void TrackerBase::fail() {
  8231. m_runState = Failed;
  8232. if( m_parent )
  8233. m_parent->markAsNeedingAnotherRun();
  8234. moveToParent();
  8235. m_ctx.completeCycle();
  8236. }
  8237. void TrackerBase::markAsNeedingAnotherRun() {
  8238. m_runState = NeedsAnotherRun;
  8239. }
  8240. void TrackerBase::moveToParent() {
  8241. assert( m_parent );
  8242. m_ctx.setCurrentTracker( m_parent );
  8243. }
  8244. void TrackerBase::moveToThis() {
  8245. m_ctx.setCurrentTracker( this );
  8246. }
  8247. SectionTracker::SectionTracker( NameAndLocation const& nameAndLocation, TrackerContext& ctx, ITracker* parent )
  8248. : TrackerBase( nameAndLocation, ctx, parent )
  8249. {
  8250. if( parent ) {
  8251. while( !parent->isSectionTracker() )
  8252. parent = &parent->parent();
  8253. SectionTracker& parentSection = static_cast<SectionTracker&>( *parent );
  8254. addNextFilters( parentSection.m_filters );
  8255. }
  8256. }
  8257. bool SectionTracker::isSectionTracker() const { return true; }
  8258. SectionTracker& SectionTracker::acquire( TrackerContext& ctx, NameAndLocation const& nameAndLocation ) {
  8259. std::shared_ptr<SectionTracker> section;
  8260. ITracker& currentTracker = ctx.currentTracker();
  8261. if( ITrackerPtr childTracker = currentTracker.findChild( nameAndLocation ) ) {
  8262. assert( childTracker );
  8263. assert( childTracker->isSectionTracker() );
  8264. section = std::static_pointer_cast<SectionTracker>( childTracker );
  8265. }
  8266. else {
  8267. section = std::make_shared<SectionTracker>( nameAndLocation, ctx, &currentTracker );
  8268. currentTracker.addChild( section );
  8269. }
  8270. if( !ctx.completedCycle() )
  8271. section->tryOpen();
  8272. return *section;
  8273. }
  8274. void SectionTracker::tryOpen() {
  8275. if( !isComplete() && (m_filters.empty() || m_filters[0].empty() || m_filters[0] == m_nameAndLocation.name ) )
  8276. open();
  8277. }
  8278. void SectionTracker::addInitialFilters( std::vector<std::string> const& filters ) {
  8279. if( !filters.empty() ) {
  8280. m_filters.push_back(""); // Root - should never be consulted
  8281. m_filters.push_back(""); // Test Case - not a section filter
  8282. m_filters.insert( m_filters.end(), filters.begin(), filters.end() );
  8283. }
  8284. }
  8285. void SectionTracker::addNextFilters( std::vector<std::string> const& filters ) {
  8286. if( filters.size() > 1 )
  8287. m_filters.insert( m_filters.end(), ++filters.begin(), filters.end() );
  8288. }
  8289. IndexTracker::IndexTracker( NameAndLocation const& nameAndLocation, TrackerContext& ctx, ITracker* parent, int size )
  8290. : TrackerBase( nameAndLocation, ctx, parent ),
  8291. m_size( size )
  8292. {}
  8293. bool IndexTracker::isIndexTracker() const { return true; }
  8294. IndexTracker& IndexTracker::acquire( TrackerContext& ctx, NameAndLocation const& nameAndLocation, int size ) {
  8295. std::shared_ptr<IndexTracker> tracker;
  8296. ITracker& currentTracker = ctx.currentTracker();
  8297. if( ITrackerPtr childTracker = currentTracker.findChild( nameAndLocation ) ) {
  8298. assert( childTracker );
  8299. assert( childTracker->isIndexTracker() );
  8300. tracker = std::static_pointer_cast<IndexTracker>( childTracker );
  8301. }
  8302. else {
  8303. tracker = std::make_shared<IndexTracker>( nameAndLocation, ctx, &currentTracker, size );
  8304. currentTracker.addChild( tracker );
  8305. }
  8306. if( !ctx.completedCycle() && !tracker->isComplete() ) {
  8307. if( tracker->m_runState != ExecutingChildren && tracker->m_runState != NeedsAnotherRun )
  8308. tracker->moveNext();
  8309. tracker->open();
  8310. }
  8311. return *tracker;
  8312. }
  8313. int IndexTracker::index() const { return m_index; }
  8314. void IndexTracker::moveNext() {
  8315. m_index++;
  8316. m_children.clear();
  8317. }
  8318. void IndexTracker::close() {
  8319. TrackerBase::close();
  8320. if( m_runState == CompletedSuccessfully && m_index < m_size-1 )
  8321. m_runState = Executing;
  8322. }
  8323. } // namespace TestCaseTracking
  8324. using TestCaseTracking::ITracker;
  8325. using TestCaseTracking::TrackerContext;
  8326. using TestCaseTracking::SectionTracker;
  8327. using TestCaseTracking::IndexTracker;
  8328. } // namespace Catch
  8329. #if defined(__clang__)
  8330. # pragma clang diagnostic pop
  8331. #endif
  8332. // end catch_test_case_tracker.cpp
  8333. // start catch_test_registry.cpp
  8334. namespace Catch {
  8335. auto makeTestInvoker( void(*testAsFunction)() ) noexcept -> ITestInvoker* {
  8336. return new(std::nothrow) TestInvokerAsFunction( testAsFunction );
  8337. }
  8338. NameAndTags::NameAndTags( StringRef const& name_ , StringRef const& tags_ ) noexcept : name( name_ ), tags( tags_ ) {}
  8339. AutoReg::AutoReg( ITestInvoker* invoker, SourceLineInfo const& lineInfo, StringRef const& classOrMethod, NameAndTags const& nameAndTags ) noexcept {
  8340. try {
  8341. getMutableRegistryHub()
  8342. .registerTest(
  8343. makeTestCase(
  8344. invoker,
  8345. extractClassName( classOrMethod ),
  8346. nameAndTags,
  8347. lineInfo));
  8348. } catch (...) {
  8349. // Do not throw when constructing global objects, instead register the exception to be processed later
  8350. getMutableRegistryHub().registerStartupException();
  8351. }
  8352. }
  8353. AutoReg::~AutoReg() = default;
  8354. }
  8355. // end catch_test_registry.cpp
  8356. // start catch_test_spec.cpp
  8357. #include <algorithm>
  8358. #include <string>
  8359. #include <vector>
  8360. #include <memory>
  8361. namespace Catch {
  8362. TestSpec::Pattern::~Pattern() = default;
  8363. TestSpec::NamePattern::~NamePattern() = default;
  8364. TestSpec::TagPattern::~TagPattern() = default;
  8365. TestSpec::ExcludedPattern::~ExcludedPattern() = default;
  8366. TestSpec::NamePattern::NamePattern( std::string const& name )
  8367. : m_wildcardPattern( toLower( name ), CaseSensitive::No )
  8368. {}
  8369. bool TestSpec::NamePattern::matches( TestCaseInfo const& testCase ) const {
  8370. return m_wildcardPattern.matches( toLower( testCase.name ) );
  8371. }
  8372. TestSpec::TagPattern::TagPattern( std::string const& tag ) : m_tag( toLower( tag ) ) {}
  8373. bool TestSpec::TagPattern::matches( TestCaseInfo const& testCase ) const {
  8374. return std::find(begin(testCase.lcaseTags),
  8375. end(testCase.lcaseTags),
  8376. m_tag) != end(testCase.lcaseTags);
  8377. }
  8378. TestSpec::ExcludedPattern::ExcludedPattern( PatternPtr const& underlyingPattern ) : m_underlyingPattern( underlyingPattern ) {}
  8379. bool TestSpec::ExcludedPattern::matches( TestCaseInfo const& testCase ) const { return !m_underlyingPattern->matches( testCase ); }
  8380. bool TestSpec::Filter::matches( TestCaseInfo const& testCase ) const {
  8381. // All patterns in a filter must match for the filter to be a match
  8382. for( auto const& pattern : m_patterns ) {
  8383. if( !pattern->matches( testCase ) )
  8384. return false;
  8385. }
  8386. return true;
  8387. }
  8388. bool TestSpec::hasFilters() const {
  8389. return !m_filters.empty();
  8390. }
  8391. bool TestSpec::matches( TestCaseInfo const& testCase ) const {
  8392. // A TestSpec matches if any filter matches
  8393. for( auto const& filter : m_filters )
  8394. if( filter.matches( testCase ) )
  8395. return true;
  8396. return false;
  8397. }
  8398. }
  8399. // end catch_test_spec.cpp
  8400. // start catch_test_spec_parser.cpp
  8401. namespace Catch {
  8402. TestSpecParser::TestSpecParser( ITagAliasRegistry const& tagAliases ) : m_tagAliases( &tagAliases ) {}
  8403. TestSpecParser& TestSpecParser::parse( std::string const& arg ) {
  8404. m_mode = None;
  8405. m_exclusion = false;
  8406. m_start = std::string::npos;
  8407. m_arg = m_tagAliases->expandAliases( arg );
  8408. m_escapeChars.clear();
  8409. for( m_pos = 0; m_pos < m_arg.size(); ++m_pos )
  8410. visitChar( m_arg[m_pos] );
  8411. if( m_mode == Name )
  8412. addPattern<TestSpec::NamePattern>();
  8413. return *this;
  8414. }
  8415. TestSpec TestSpecParser::testSpec() {
  8416. addFilter();
  8417. return m_testSpec;
  8418. }
  8419. void TestSpecParser::visitChar( char c ) {
  8420. if( m_mode == None ) {
  8421. switch( c ) {
  8422. case ' ': return;
  8423. case '~': m_exclusion = true; return;
  8424. case '[': return startNewMode( Tag, ++m_pos );
  8425. case '"': return startNewMode( QuotedName, ++m_pos );
  8426. case '\\': return escape();
  8427. default: startNewMode( Name, m_pos ); break;
  8428. }
  8429. }
  8430. if( m_mode == Name ) {
  8431. if( c == ',' ) {
  8432. addPattern<TestSpec::NamePattern>();
  8433. addFilter();
  8434. }
  8435. else if( c == '[' ) {
  8436. if( subString() == "exclude:" )
  8437. m_exclusion = true;
  8438. else
  8439. addPattern<TestSpec::NamePattern>();
  8440. startNewMode( Tag, ++m_pos );
  8441. }
  8442. else if( c == '\\' )
  8443. escape();
  8444. }
  8445. else if( m_mode == EscapedName )
  8446. m_mode = Name;
  8447. else if( m_mode == QuotedName && c == '"' )
  8448. addPattern<TestSpec::NamePattern>();
  8449. else if( m_mode == Tag && c == ']' )
  8450. addPattern<TestSpec::TagPattern>();
  8451. }
  8452. void TestSpecParser::startNewMode( Mode mode, std::size_t start ) {
  8453. m_mode = mode;
  8454. m_start = start;
  8455. }
  8456. void TestSpecParser::escape() {
  8457. if( m_mode == None )
  8458. m_start = m_pos;
  8459. m_mode = EscapedName;
  8460. m_escapeChars.push_back( m_pos );
  8461. }
  8462. std::string TestSpecParser::subString() const { return m_arg.substr( m_start, m_pos - m_start ); }
  8463. void TestSpecParser::addFilter() {
  8464. if( !m_currentFilter.m_patterns.empty() ) {
  8465. m_testSpec.m_filters.push_back( m_currentFilter );
  8466. m_currentFilter = TestSpec::Filter();
  8467. }
  8468. }
  8469. TestSpec parseTestSpec( std::string const& arg ) {
  8470. return TestSpecParser( ITagAliasRegistry::get() ).parse( arg ).testSpec();
  8471. }
  8472. } // namespace Catch
  8473. // end catch_test_spec_parser.cpp
  8474. // start catch_timer.cpp
  8475. #include <chrono>
  8476. static const uint64_t nanosecondsInSecond = 1000000000;
  8477. namespace Catch {
  8478. auto getCurrentNanosecondsSinceEpoch() -> uint64_t {
  8479. return std::chrono::duration_cast<std::chrono::nanoseconds>( std::chrono::high_resolution_clock::now().time_since_epoch() ).count();
  8480. }
  8481. auto estimateClockResolution() -> uint64_t {
  8482. uint64_t sum = 0;
  8483. static const uint64_t iterations = 1000000;
  8484. auto startTime = getCurrentNanosecondsSinceEpoch();
  8485. for( std::size_t i = 0; i < iterations; ++i ) {
  8486. uint64_t ticks;
  8487. uint64_t baseTicks = getCurrentNanosecondsSinceEpoch();
  8488. do {
  8489. ticks = getCurrentNanosecondsSinceEpoch();
  8490. } while( ticks == baseTicks );
  8491. auto delta = ticks - baseTicks;
  8492. sum += delta;
  8493. // If we have been calibrating for over 3 seconds -- the clock
  8494. // is terrible and we should move on.
  8495. // TBD: How to signal that the measured resolution is probably wrong?
  8496. if (ticks > startTime + 3 * nanosecondsInSecond) {
  8497. return sum / i;
  8498. }
  8499. }
  8500. // We're just taking the mean, here. To do better we could take the std. dev and exclude outliers
  8501. // - and potentially do more iterations if there's a high variance.
  8502. return sum/iterations;
  8503. }
  8504. auto getEstimatedClockResolution() -> uint64_t {
  8505. static auto s_resolution = estimateClockResolution();
  8506. return s_resolution;
  8507. }
  8508. void Timer::start() {
  8509. m_nanoseconds = getCurrentNanosecondsSinceEpoch();
  8510. }
  8511. auto Timer::getElapsedNanoseconds() const -> uint64_t {
  8512. return getCurrentNanosecondsSinceEpoch() - m_nanoseconds;
  8513. }
  8514. auto Timer::getElapsedMicroseconds() const -> uint64_t {
  8515. return getElapsedNanoseconds()/1000;
  8516. }
  8517. auto Timer::getElapsedMilliseconds() const -> unsigned int {
  8518. return static_cast<unsigned int>(getElapsedMicroseconds()/1000);
  8519. }
  8520. auto Timer::getElapsedSeconds() const -> double {
  8521. return getElapsedMicroseconds()/1000000.0;
  8522. }
  8523. } // namespace Catch
  8524. // end catch_timer.cpp
  8525. // start catch_tostring.cpp
  8526. #if defined(__clang__)
  8527. # pragma clang diagnostic push
  8528. # pragma clang diagnostic ignored "-Wexit-time-destructors"
  8529. # pragma clang diagnostic ignored "-Wglobal-constructors"
  8530. #endif
  8531. // Enable specific decls locally
  8532. #if !defined(CATCH_CONFIG_ENABLE_CHRONO_STRINGMAKER)
  8533. #define CATCH_CONFIG_ENABLE_CHRONO_STRINGMAKER
  8534. #endif
  8535. #include <cmath>
  8536. #include <iomanip>
  8537. namespace Catch {
  8538. namespace Detail {
  8539. const std::string unprintableString = "{?}";
  8540. namespace {
  8541. const int hexThreshold = 255;
  8542. struct Endianness {
  8543. enum Arch { Big, Little };
  8544. static Arch which() {
  8545. union _{
  8546. int asInt;
  8547. char asChar[sizeof (int)];
  8548. } u;
  8549. u.asInt = 1;
  8550. return ( u.asChar[sizeof(int)-1] == 1 ) ? Big : Little;
  8551. }
  8552. };
  8553. }
  8554. std::string rawMemoryToString( const void *object, std::size_t size ) {
  8555. // Reverse order for little endian architectures
  8556. int i = 0, end = static_cast<int>( size ), inc = 1;
  8557. if( Endianness::which() == Endianness::Little ) {
  8558. i = end-1;
  8559. end = inc = -1;
  8560. }
  8561. unsigned char const *bytes = static_cast<unsigned char const *>(object);
  8562. ReusableStringStream rss;
  8563. rss << "0x" << std::setfill('0') << std::hex;
  8564. for( ; i != end; i += inc )
  8565. rss << std::setw(2) << static_cast<unsigned>(bytes[i]);
  8566. return rss.str();
  8567. }
  8568. }
  8569. template<typename T>
  8570. std::string fpToString( T value, int precision ) {
  8571. if (std::isnan(value)) {
  8572. return "nan";
  8573. }
  8574. ReusableStringStream rss;
  8575. rss << std::setprecision( precision )
  8576. << std::fixed
  8577. << value;
  8578. std::string d = rss.str();
  8579. std::size_t i = d.find_last_not_of( '0' );
  8580. if( i != std::string::npos && i != d.size()-1 ) {
  8581. if( d[i] == '.' )
  8582. i++;
  8583. d = d.substr( 0, i+1 );
  8584. }
  8585. return d;
  8586. }
  8587. //// ======================================================= ////
  8588. //
  8589. // Out-of-line defs for full specialization of StringMaker
  8590. //
  8591. //// ======================================================= ////
  8592. std::string StringMaker<std::string>::convert(const std::string& str) {
  8593. if (!getCurrentContext().getConfig()->showInvisibles()) {
  8594. return '"' + str + '"';
  8595. }
  8596. std::string s("\"");
  8597. for (char c : str) {
  8598. switch (c) {
  8599. case '\n':
  8600. s.append("\\n");
  8601. break;
  8602. case '\t':
  8603. s.append("\\t");
  8604. break;
  8605. default:
  8606. s.push_back(c);
  8607. break;
  8608. }
  8609. }
  8610. s.append("\"");
  8611. return s;
  8612. }
  8613. #ifdef CATCH_CONFIG_WCHAR
  8614. std::string StringMaker<std::wstring>::convert(const std::wstring& wstr) {
  8615. std::string s;
  8616. s.reserve(wstr.size());
  8617. for (auto c : wstr) {
  8618. s += (c <= 0xff) ? static_cast<char>(c) : '?';
  8619. }
  8620. return ::Catch::Detail::stringify(s);
  8621. }
  8622. #endif
  8623. std::string StringMaker<char const*>::convert(char const* str) {
  8624. if (str) {
  8625. return ::Catch::Detail::stringify(std::string{ str });
  8626. } else {
  8627. return{ "{null string}" };
  8628. }
  8629. }
  8630. std::string StringMaker<char*>::convert(char* str) {
  8631. if (str) {
  8632. return ::Catch::Detail::stringify(std::string{ str });
  8633. } else {
  8634. return{ "{null string}" };
  8635. }
  8636. }
  8637. #ifdef CATCH_CONFIG_WCHAR
  8638. std::string StringMaker<wchar_t const*>::convert(wchar_t const * str) {
  8639. if (str) {
  8640. return ::Catch::Detail::stringify(std::wstring{ str });
  8641. } else {
  8642. return{ "{null string}" };
  8643. }
  8644. }
  8645. std::string StringMaker<wchar_t *>::convert(wchar_t * str) {
  8646. if (str) {
  8647. return ::Catch::Detail::stringify(std::wstring{ str });
  8648. } else {
  8649. return{ "{null string}" };
  8650. }
  8651. }
  8652. #endif
  8653. std::string StringMaker<int>::convert(int value) {
  8654. return ::Catch::Detail::stringify(static_cast<long long>(value));
  8655. }
  8656. std::string StringMaker<long>::convert(long value) {
  8657. return ::Catch::Detail::stringify(static_cast<long long>(value));
  8658. }
  8659. std::string StringMaker<long long>::convert(long long value) {
  8660. ReusableStringStream rss;
  8661. rss << value;
  8662. if (value > Detail::hexThreshold) {
  8663. rss << " (0x" << std::hex << value << ')';
  8664. }
  8665. return rss.str();
  8666. }
  8667. std::string StringMaker<unsigned int>::convert(unsigned int value) {
  8668. return ::Catch::Detail::stringify(static_cast<unsigned long long>(value));
  8669. }
  8670. std::string StringMaker<unsigned long>::convert(unsigned long value) {
  8671. return ::Catch::Detail::stringify(static_cast<unsigned long long>(value));
  8672. }
  8673. std::string StringMaker<unsigned long long>::convert(unsigned long long value) {
  8674. ReusableStringStream rss;
  8675. rss << value;
  8676. if (value > Detail::hexThreshold) {
  8677. rss << " (0x" << std::hex << value << ')';
  8678. }
  8679. return rss.str();
  8680. }
  8681. std::string StringMaker<bool>::convert(bool b) {
  8682. return b ? "true" : "false";
  8683. }
  8684. std::string StringMaker<char>::convert(char value) {
  8685. if (value == '\r') {
  8686. return "'\\r'";
  8687. } else if (value == '\f') {
  8688. return "'\\f'";
  8689. } else if (value == '\n') {
  8690. return "'\\n'";
  8691. } else if (value == '\t') {
  8692. return "'\\t'";
  8693. } else if ('\0' <= value && value < ' ') {
  8694. return ::Catch::Detail::stringify(static_cast<unsigned int>(value));
  8695. } else {
  8696. char chstr[] = "' '";
  8697. chstr[1] = value;
  8698. return chstr;
  8699. }
  8700. }
  8701. std::string StringMaker<signed char>::convert(signed char c) {
  8702. return ::Catch::Detail::stringify(static_cast<char>(c));
  8703. }
  8704. std::string StringMaker<unsigned char>::convert(unsigned char c) {
  8705. return ::Catch::Detail::stringify(static_cast<char>(c));
  8706. }
  8707. std::string StringMaker<std::nullptr_t>::convert(std::nullptr_t) {
  8708. return "nullptr";
  8709. }
  8710. std::string StringMaker<float>::convert(float value) {
  8711. return fpToString(value, 5) + 'f';
  8712. }
  8713. std::string StringMaker<double>::convert(double value) {
  8714. return fpToString(value, 10);
  8715. }
  8716. std::string ratio_string<std::atto>::symbol() { return "a"; }
  8717. std::string ratio_string<std::femto>::symbol() { return "f"; }
  8718. std::string ratio_string<std::pico>::symbol() { return "p"; }
  8719. std::string ratio_string<std::nano>::symbol() { return "n"; }
  8720. std::string ratio_string<std::micro>::symbol() { return "u"; }
  8721. std::string ratio_string<std::milli>::symbol() { return "m"; }
  8722. } // end namespace Catch
  8723. #if defined(__clang__)
  8724. # pragma clang diagnostic pop
  8725. #endif
  8726. // end catch_tostring.cpp
  8727. // start catch_totals.cpp
  8728. namespace Catch {
  8729. Counts Counts::operator - ( Counts const& other ) const {
  8730. Counts diff;
  8731. diff.passed = passed - other.passed;
  8732. diff.failed = failed - other.failed;
  8733. diff.failedButOk = failedButOk - other.failedButOk;
  8734. return diff;
  8735. }
  8736. Counts& Counts::operator += ( Counts const& other ) {
  8737. passed += other.passed;
  8738. failed += other.failed;
  8739. failedButOk += other.failedButOk;
  8740. return *this;
  8741. }
  8742. std::size_t Counts::total() const {
  8743. return passed + failed + failedButOk;
  8744. }
  8745. bool Counts::allPassed() const {
  8746. return failed == 0 && failedButOk == 0;
  8747. }
  8748. bool Counts::allOk() const {
  8749. return failed == 0;
  8750. }
  8751. Totals Totals::operator - ( Totals const& other ) const {
  8752. Totals diff;
  8753. diff.assertions = assertions - other.assertions;
  8754. diff.testCases = testCases - other.testCases;
  8755. return diff;
  8756. }
  8757. Totals& Totals::operator += ( Totals const& other ) {
  8758. assertions += other.assertions;
  8759. testCases += other.testCases;
  8760. return *this;
  8761. }
  8762. Totals Totals::delta( Totals const& prevTotals ) const {
  8763. Totals diff = *this - prevTotals;
  8764. if( diff.assertions.failed > 0 )
  8765. ++diff.testCases.failed;
  8766. else if( diff.assertions.failedButOk > 0 )
  8767. ++diff.testCases.failedButOk;
  8768. else
  8769. ++diff.testCases.passed;
  8770. return diff;
  8771. }
  8772. }
  8773. // end catch_totals.cpp
  8774. // start catch_uncaught_exceptions.cpp
  8775. #include <exception>
  8776. namespace Catch {
  8777. bool uncaught_exceptions() {
  8778. #if defined(CATCH_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS)
  8779. return std::uncaught_exceptions() > 0;
  8780. #else
  8781. return std::uncaught_exception();
  8782. #endif
  8783. }
  8784. } // end namespace Catch
  8785. // end catch_uncaught_exceptions.cpp
  8786. // start catch_version.cpp
  8787. #include <ostream>
  8788. namespace Catch {
  8789. Version::Version
  8790. ( unsigned int _majorVersion,
  8791. unsigned int _minorVersion,
  8792. unsigned int _patchNumber,
  8793. char const * const _branchName,
  8794. unsigned int _buildNumber )
  8795. : majorVersion( _majorVersion ),
  8796. minorVersion( _minorVersion ),
  8797. patchNumber( _patchNumber ),
  8798. branchName( _branchName ),
  8799. buildNumber( _buildNumber )
  8800. {}
  8801. std::ostream& operator << ( std::ostream& os, Version const& version ) {
  8802. os << version.majorVersion << '.'
  8803. << version.minorVersion << '.'
  8804. << version.patchNumber;
  8805. // branchName is never null -> 0th char is \0 if it is empty
  8806. if (version.branchName[0]) {
  8807. os << '-' << version.branchName
  8808. << '.' << version.buildNumber;
  8809. }
  8810. return os;
  8811. }
  8812. Version const& libraryVersion() {
  8813. static Version version( 2, 2, 2, "", 0 );
  8814. return version;
  8815. }
  8816. }
  8817. // end catch_version.cpp
  8818. // start catch_wildcard_pattern.cpp
  8819. #include <sstream>
  8820. namespace Catch {
  8821. WildcardPattern::WildcardPattern( std::string const& pattern,
  8822. CaseSensitive::Choice caseSensitivity )
  8823. : m_caseSensitivity( caseSensitivity ),
  8824. m_pattern( adjustCase( pattern ) )
  8825. {
  8826. if( startsWith( m_pattern, '*' ) ) {
  8827. m_pattern = m_pattern.substr( 1 );
  8828. m_wildcard = WildcardAtStart;
  8829. }
  8830. if( endsWith( m_pattern, '*' ) ) {
  8831. m_pattern = m_pattern.substr( 0, m_pattern.size()-1 );
  8832. m_wildcard = static_cast<WildcardPosition>( m_wildcard | WildcardAtEnd );
  8833. }
  8834. }
  8835. bool WildcardPattern::matches( std::string const& str ) const {
  8836. switch( m_wildcard ) {
  8837. case NoWildcard:
  8838. return m_pattern == adjustCase( str );
  8839. case WildcardAtStart:
  8840. return endsWith( adjustCase( str ), m_pattern );
  8841. case WildcardAtEnd:
  8842. return startsWith( adjustCase( str ), m_pattern );
  8843. case WildcardAtBothEnds:
  8844. return contains( adjustCase( str ), m_pattern );
  8845. default:
  8846. CATCH_INTERNAL_ERROR( "Unknown enum" );
  8847. }
  8848. }
  8849. std::string WildcardPattern::adjustCase( std::string const& str ) const {
  8850. return m_caseSensitivity == CaseSensitive::No ? toLower( str ) : str;
  8851. }
  8852. }
  8853. // end catch_wildcard_pattern.cpp
  8854. // start catch_xmlwriter.cpp
  8855. #include <iomanip>
  8856. using uchar = unsigned char;
  8857. namespace Catch {
  8858. namespace {
  8859. size_t trailingBytes(unsigned char c) {
  8860. if ((c & 0xE0) == 0xC0) {
  8861. return 2;
  8862. }
  8863. if ((c & 0xF0) == 0xE0) {
  8864. return 3;
  8865. }
  8866. if ((c & 0xF8) == 0xF0) {
  8867. return 4;
  8868. }
  8869. CATCH_INTERNAL_ERROR("Invalid multibyte utf-8 start byte encountered");
  8870. }
  8871. uint32_t headerValue(unsigned char c) {
  8872. if ((c & 0xE0) == 0xC0) {
  8873. return c & 0x1F;
  8874. }
  8875. if ((c & 0xF0) == 0xE0) {
  8876. return c & 0x0F;
  8877. }
  8878. if ((c & 0xF8) == 0xF0) {
  8879. return c & 0x07;
  8880. }
  8881. CATCH_INTERNAL_ERROR("Invalid multibyte utf-8 start byte encountered");
  8882. }
  8883. void hexEscapeChar(std::ostream& os, unsigned char c) {
  8884. os << "\\x"
  8885. << std::uppercase << std::hex << std::setfill('0') << std::setw(2)
  8886. << static_cast<int>(c);
  8887. }
  8888. } // anonymous namespace
  8889. XmlEncode::XmlEncode( std::string const& str, ForWhat forWhat )
  8890. : m_str( str ),
  8891. m_forWhat( forWhat )
  8892. {}
  8893. void XmlEncode::encodeTo( std::ostream& os ) const {
  8894. // Apostrophe escaping not necessary if we always use " to write attributes
  8895. // (see: http://www.w3.org/TR/xml/#syntax)
  8896. for( std::size_t idx = 0; idx < m_str.size(); ++ idx ) {
  8897. uchar c = m_str[idx];
  8898. switch (c) {
  8899. case '<': os << "&lt;"; break;
  8900. case '&': os << "&amp;"; break;
  8901. case '>':
  8902. // See: http://www.w3.org/TR/xml/#syntax
  8903. if (idx > 2 && m_str[idx - 1] == ']' && m_str[idx - 2] == ']')
  8904. os << "&gt;";
  8905. else
  8906. os << c;
  8907. break;
  8908. case '\"':
  8909. if (m_forWhat == ForAttributes)
  8910. os << "&quot;";
  8911. else
  8912. os << c;
  8913. break;
  8914. default:
  8915. // Check for control characters and invalid utf-8
  8916. // Escape control characters in standard ascii
  8917. // see http://stackoverflow.com/questions/404107/why-are-control-characters-illegal-in-xml-1-0
  8918. if (c < 0x09 || (c > 0x0D && c < 0x20) || c == 0x7F) {
  8919. hexEscapeChar(os, c);
  8920. break;
  8921. }
  8922. // Plain ASCII: Write it to stream
  8923. if (c < 0x7F) {
  8924. os << c;
  8925. break;
  8926. }
  8927. // UTF-8 territory
  8928. // Check if the encoding is valid and if it is not, hex escape bytes.
  8929. // Important: We do not check the exact decoded values for validity, only the encoding format
  8930. // First check that this bytes is a valid lead byte:
  8931. // This means that it is not encoded as 1111 1XXX
  8932. // Or as 10XX XXXX
  8933. if (c < 0xC0 ||
  8934. c >= 0xF8) {
  8935. hexEscapeChar(os, c);
  8936. break;
  8937. }
  8938. auto encBytes = trailingBytes(c);
  8939. // Are there enough bytes left to avoid accessing out-of-bounds memory?
  8940. if (idx + encBytes - 1 >= m_str.size()) {
  8941. hexEscapeChar(os, c);
  8942. break;
  8943. }
  8944. // The header is valid, check data
  8945. // The next encBytes bytes must together be a valid utf-8
  8946. // This means: bitpattern 10XX XXXX and the extracted value is sane (ish)
  8947. bool valid = true;
  8948. uint32_t value = headerValue(c);
  8949. for (std::size_t n = 1; n < encBytes; ++n) {
  8950. uchar nc = m_str[idx + n];
  8951. valid &= ((nc & 0xC0) == 0x80);
  8952. value = (value << 6) | (nc & 0x3F);
  8953. }
  8954. if (
  8955. // Wrong bit pattern of following bytes
  8956. (!valid) ||
  8957. // Overlong encodings
  8958. (value < 0x80) ||
  8959. (0x80 <= value && value < 0x800 && encBytes > 2) ||
  8960. (0x800 < value && value < 0x10000 && encBytes > 3) ||
  8961. // Encoded value out of range
  8962. (value >= 0x110000)
  8963. ) {
  8964. hexEscapeChar(os, c);
  8965. break;
  8966. }
  8967. // If we got here, this is in fact a valid(ish) utf-8 sequence
  8968. for (std::size_t n = 0; n < encBytes; ++n) {
  8969. os << m_str[idx + n];
  8970. }
  8971. idx += encBytes - 1;
  8972. break;
  8973. }
  8974. }
  8975. }
  8976. std::ostream& operator << ( std::ostream& os, XmlEncode const& xmlEncode ) {
  8977. xmlEncode.encodeTo( os );
  8978. return os;
  8979. }
  8980. XmlWriter::ScopedElement::ScopedElement( XmlWriter* writer )
  8981. : m_writer( writer )
  8982. {}
  8983. XmlWriter::ScopedElement::ScopedElement( ScopedElement&& other ) noexcept
  8984. : m_writer( other.m_writer ){
  8985. other.m_writer = nullptr;
  8986. }
  8987. XmlWriter::ScopedElement& XmlWriter::ScopedElement::operator=( ScopedElement&& other ) noexcept {
  8988. if ( m_writer ) {
  8989. m_writer->endElement();
  8990. }
  8991. m_writer = other.m_writer;
  8992. other.m_writer = nullptr;
  8993. return *this;
  8994. }
  8995. XmlWriter::ScopedElement::~ScopedElement() {
  8996. if( m_writer )
  8997. m_writer->endElement();
  8998. }
  8999. XmlWriter::ScopedElement& XmlWriter::ScopedElement::writeText( std::string const& text, bool indent ) {
  9000. m_writer->writeText( text, indent );
  9001. return *this;
  9002. }
  9003. XmlWriter::XmlWriter( std::ostream& os ) : m_os( os )
  9004. {
  9005. writeDeclaration();
  9006. }
  9007. XmlWriter::~XmlWriter() {
  9008. while( !m_tags.empty() )
  9009. endElement();
  9010. }
  9011. XmlWriter& XmlWriter::startElement( std::string const& name ) {
  9012. ensureTagClosed();
  9013. newlineIfNecessary();
  9014. m_os << m_indent << '<' << name;
  9015. m_tags.push_back( name );
  9016. m_indent += " ";
  9017. m_tagIsOpen = true;
  9018. return *this;
  9019. }
  9020. XmlWriter::ScopedElement XmlWriter::scopedElement( std::string const& name ) {
  9021. ScopedElement scoped( this );
  9022. startElement( name );
  9023. return scoped;
  9024. }
  9025. XmlWriter& XmlWriter::endElement() {
  9026. newlineIfNecessary();
  9027. m_indent = m_indent.substr( 0, m_indent.size()-2 );
  9028. if( m_tagIsOpen ) {
  9029. m_os << "/>";
  9030. m_tagIsOpen = false;
  9031. }
  9032. else {
  9033. m_os << m_indent << "</" << m_tags.back() << ">";
  9034. }
  9035. m_os << std::endl;
  9036. m_tags.pop_back();
  9037. return *this;
  9038. }
  9039. XmlWriter& XmlWriter::writeAttribute( std::string const& name, std::string const& attribute ) {
  9040. if( !name.empty() && !attribute.empty() )
  9041. m_os << ' ' << name << "=\"" << XmlEncode( attribute, XmlEncode::ForAttributes ) << '"';
  9042. return *this;
  9043. }
  9044. XmlWriter& XmlWriter::writeAttribute( std::string const& name, bool attribute ) {
  9045. m_os << ' ' << name << "=\"" << ( attribute ? "true" : "false" ) << '"';
  9046. return *this;
  9047. }
  9048. XmlWriter& XmlWriter::writeText( std::string const& text, bool indent ) {
  9049. if( !text.empty() ){
  9050. bool tagWasOpen = m_tagIsOpen;
  9051. ensureTagClosed();
  9052. if( tagWasOpen && indent )
  9053. m_os << m_indent;
  9054. m_os << XmlEncode( text );
  9055. m_needsNewline = true;
  9056. }
  9057. return *this;
  9058. }
  9059. XmlWriter& XmlWriter::writeComment( std::string const& text ) {
  9060. ensureTagClosed();
  9061. m_os << m_indent << "<!--" << text << "-->";
  9062. m_needsNewline = true;
  9063. return *this;
  9064. }
  9065. void XmlWriter::writeStylesheetRef( std::string const& url ) {
  9066. m_os << "<?xml-stylesheet type=\"text/xsl\" href=\"" << url << "\"?>\n";
  9067. }
  9068. XmlWriter& XmlWriter::writeBlankLine() {
  9069. ensureTagClosed();
  9070. m_os << '\n';
  9071. return *this;
  9072. }
  9073. void XmlWriter::ensureTagClosed() {
  9074. if( m_tagIsOpen ) {
  9075. m_os << ">" << std::endl;
  9076. m_tagIsOpen = false;
  9077. }
  9078. }
  9079. void XmlWriter::writeDeclaration() {
  9080. m_os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
  9081. }
  9082. void XmlWriter::newlineIfNecessary() {
  9083. if( m_needsNewline ) {
  9084. m_os << std::endl;
  9085. m_needsNewline = false;
  9086. }
  9087. }
  9088. }
  9089. // end catch_xmlwriter.cpp
  9090. // start catch_reporter_bases.cpp
  9091. #include <cstring>
  9092. #include <cfloat>
  9093. #include <cstdio>
  9094. #include <assert.h>
  9095. #include <memory>
  9096. namespace Catch {
  9097. void prepareExpandedExpression(AssertionResult& result) {
  9098. result.getExpandedExpression();
  9099. }
  9100. // Because formatting using c++ streams is stateful, drop down to C is required
  9101. // Alternatively we could use stringstream, but its performance is... not good.
  9102. std::string getFormattedDuration( double duration ) {
  9103. // Max exponent + 1 is required to represent the whole part
  9104. // + 1 for decimal point
  9105. // + 3 for the 3 decimal places
  9106. // + 1 for null terminator
  9107. const std::size_t maxDoubleSize = DBL_MAX_10_EXP + 1 + 1 + 3 + 1;
  9108. char buffer[maxDoubleSize];
  9109. // Save previous errno, to prevent sprintf from overwriting it
  9110. ErrnoGuard guard;
  9111. #ifdef _MSC_VER
  9112. sprintf_s(buffer, "%.3f", duration);
  9113. #else
  9114. sprintf(buffer, "%.3f", duration);
  9115. #endif
  9116. return std::string(buffer);
  9117. }
  9118. TestEventListenerBase::TestEventListenerBase(ReporterConfig const & _config)
  9119. :StreamingReporterBase(_config) {}
  9120. void TestEventListenerBase::assertionStarting(AssertionInfo const &) {}
  9121. bool TestEventListenerBase::assertionEnded(AssertionStats const &) {
  9122. return false;
  9123. }
  9124. } // end namespace Catch
  9125. // end catch_reporter_bases.cpp
  9126. // start catch_reporter_compact.cpp
  9127. namespace {
  9128. #ifdef CATCH_PLATFORM_MAC
  9129. const char* failedString() { return "FAILED"; }
  9130. const char* passedString() { return "PASSED"; }
  9131. #else
  9132. const char* failedString() { return "failed"; }
  9133. const char* passedString() { return "passed"; }
  9134. #endif
  9135. // Colour::LightGrey
  9136. Catch::Colour::Code dimColour() { return Catch::Colour::FileName; }
  9137. std::string bothOrAll( std::size_t count ) {
  9138. return count == 1 ? std::string() :
  9139. count == 2 ? "both " : "all " ;
  9140. }
  9141. } // anon namespace
  9142. namespace Catch {
  9143. namespace {
  9144. // Colour, message variants:
  9145. // - white: No tests ran.
  9146. // - red: Failed [both/all] N test cases, failed [both/all] M assertions.
  9147. // - white: Passed [both/all] N test cases (no assertions).
  9148. // - red: Failed N tests cases, failed M assertions.
  9149. // - green: Passed [both/all] N tests cases with M assertions.
  9150. void printTotals(std::ostream& out, const Totals& totals) {
  9151. if (totals.testCases.total() == 0) {
  9152. out << "No tests ran.";
  9153. } else if (totals.testCases.failed == totals.testCases.total()) {
  9154. Colour colour(Colour::ResultError);
  9155. const std::string qualify_assertions_failed =
  9156. totals.assertions.failed == totals.assertions.total() ?
  9157. bothOrAll(totals.assertions.failed) : std::string();
  9158. out <<
  9159. "Failed " << bothOrAll(totals.testCases.failed)
  9160. << pluralise(totals.testCases.failed, "test case") << ", "
  9161. "failed " << qualify_assertions_failed <<
  9162. pluralise(totals.assertions.failed, "assertion") << '.';
  9163. } else if (totals.assertions.total() == 0) {
  9164. out <<
  9165. "Passed " << bothOrAll(totals.testCases.total())
  9166. << pluralise(totals.testCases.total(), "test case")
  9167. << " (no assertions).";
  9168. } else if (totals.assertions.failed) {
  9169. Colour colour(Colour::ResultError);
  9170. out <<
  9171. "Failed " << pluralise(totals.testCases.failed, "test case") << ", "
  9172. "failed " << pluralise(totals.assertions.failed, "assertion") << '.';
  9173. } else {
  9174. Colour colour(Colour::ResultSuccess);
  9175. out <<
  9176. "Passed " << bothOrAll(totals.testCases.passed)
  9177. << pluralise(totals.testCases.passed, "test case") <<
  9178. " with " << pluralise(totals.assertions.passed, "assertion") << '.';
  9179. }
  9180. }
  9181. // Implementation of CompactReporter formatting
  9182. class AssertionPrinter {
  9183. public:
  9184. AssertionPrinter& operator= (AssertionPrinter const&) = delete;
  9185. AssertionPrinter(AssertionPrinter const&) = delete;
  9186. AssertionPrinter(std::ostream& _stream, AssertionStats const& _stats, bool _printInfoMessages)
  9187. : stream(_stream)
  9188. , result(_stats.assertionResult)
  9189. , messages(_stats.infoMessages)
  9190. , itMessage(_stats.infoMessages.begin())
  9191. , printInfoMessages(_printInfoMessages) {}
  9192. void print() {
  9193. printSourceInfo();
  9194. itMessage = messages.begin();
  9195. switch (result.getResultType()) {
  9196. case ResultWas::Ok:
  9197. printResultType(Colour::ResultSuccess, passedString());
  9198. printOriginalExpression();
  9199. printReconstructedExpression();
  9200. if (!result.hasExpression())
  9201. printRemainingMessages(Colour::None);
  9202. else
  9203. printRemainingMessages();
  9204. break;
  9205. case ResultWas::ExpressionFailed:
  9206. if (result.isOk())
  9207. printResultType(Colour::ResultSuccess, failedString() + std::string(" - but was ok"));
  9208. else
  9209. printResultType(Colour::Error, failedString());
  9210. printOriginalExpression();
  9211. printReconstructedExpression();
  9212. printRemainingMessages();
  9213. break;
  9214. case ResultWas::ThrewException:
  9215. printResultType(Colour::Error, failedString());
  9216. printIssue("unexpected exception with message:");
  9217. printMessage();
  9218. printExpressionWas();
  9219. printRemainingMessages();
  9220. break;
  9221. case ResultWas::FatalErrorCondition:
  9222. printResultType(Colour::Error, failedString());
  9223. printIssue("fatal error condition with message:");
  9224. printMessage();
  9225. printExpressionWas();
  9226. printRemainingMessages();
  9227. break;
  9228. case ResultWas::DidntThrowException:
  9229. printResultType(Colour::Error, failedString());
  9230. printIssue("expected exception, got none");
  9231. printExpressionWas();
  9232. printRemainingMessages();
  9233. break;
  9234. case ResultWas::Info:
  9235. printResultType(Colour::None, "info");
  9236. printMessage();
  9237. printRemainingMessages();
  9238. break;
  9239. case ResultWas::Warning:
  9240. printResultType(Colour::None, "warning");
  9241. printMessage();
  9242. printRemainingMessages();
  9243. break;
  9244. case ResultWas::ExplicitFailure:
  9245. printResultType(Colour::Error, failedString());
  9246. printIssue("explicitly");
  9247. printRemainingMessages(Colour::None);
  9248. break;
  9249. // These cases are here to prevent compiler warnings
  9250. case ResultWas::Unknown:
  9251. case ResultWas::FailureBit:
  9252. case ResultWas::Exception:
  9253. printResultType(Colour::Error, "** internal error **");
  9254. break;
  9255. }
  9256. }
  9257. private:
  9258. void printSourceInfo() const {
  9259. Colour colourGuard(Colour::FileName);
  9260. stream << result.getSourceInfo() << ':';
  9261. }
  9262. void printResultType(Colour::Code colour, std::string const& passOrFail) const {
  9263. if (!passOrFail.empty()) {
  9264. {
  9265. Colour colourGuard(colour);
  9266. stream << ' ' << passOrFail;
  9267. }
  9268. stream << ':';
  9269. }
  9270. }
  9271. void printIssue(std::string const& issue) const {
  9272. stream << ' ' << issue;
  9273. }
  9274. void printExpressionWas() {
  9275. if (result.hasExpression()) {
  9276. stream << ';';
  9277. {
  9278. Colour colour(dimColour());
  9279. stream << " expression was:";
  9280. }
  9281. printOriginalExpression();
  9282. }
  9283. }
  9284. void printOriginalExpression() const {
  9285. if (result.hasExpression()) {
  9286. stream << ' ' << result.getExpression();
  9287. }
  9288. }
  9289. void printReconstructedExpression() const {
  9290. if (result.hasExpandedExpression()) {
  9291. {
  9292. Colour colour(dimColour());
  9293. stream << " for: ";
  9294. }
  9295. stream << result.getExpandedExpression();
  9296. }
  9297. }
  9298. void printMessage() {
  9299. if (itMessage != messages.end()) {
  9300. stream << " '" << itMessage->message << '\'';
  9301. ++itMessage;
  9302. }
  9303. }
  9304. void printRemainingMessages(Colour::Code colour = dimColour()) {
  9305. if (itMessage == messages.end())
  9306. return;
  9307. // using messages.end() directly yields (or auto) compilation error:
  9308. std::vector<MessageInfo>::const_iterator itEnd = messages.end();
  9309. const std::size_t N = static_cast<std::size_t>(std::distance(itMessage, itEnd));
  9310. {
  9311. Colour colourGuard(colour);
  9312. stream << " with " << pluralise(N, "message") << ':';
  9313. }
  9314. for (; itMessage != itEnd; ) {
  9315. // If this assertion is a warning ignore any INFO messages
  9316. if (printInfoMessages || itMessage->type != ResultWas::Info) {
  9317. stream << " '" << itMessage->message << '\'';
  9318. if (++itMessage != itEnd) {
  9319. Colour colourGuard(dimColour());
  9320. stream << " and";
  9321. }
  9322. }
  9323. }
  9324. }
  9325. private:
  9326. std::ostream& stream;
  9327. AssertionResult const& result;
  9328. std::vector<MessageInfo> messages;
  9329. std::vector<MessageInfo>::const_iterator itMessage;
  9330. bool printInfoMessages;
  9331. };
  9332. } // anon namespace
  9333. std::string CompactReporter::getDescription() {
  9334. return "Reports test results on a single line, suitable for IDEs";
  9335. }
  9336. ReporterPreferences CompactReporter::getPreferences() const {
  9337. ReporterPreferences prefs;
  9338. prefs.shouldRedirectStdOut = false;
  9339. return prefs;
  9340. }
  9341. void CompactReporter::noMatchingTestCases( std::string const& spec ) {
  9342. stream << "No test cases matched '" << spec << '\'' << std::endl;
  9343. }
  9344. void CompactReporter::assertionStarting( AssertionInfo const& ) {}
  9345. bool CompactReporter::assertionEnded( AssertionStats const& _assertionStats ) {
  9346. AssertionResult const& result = _assertionStats.assertionResult;
  9347. bool printInfoMessages = true;
  9348. // Drop out if result was successful and we're not printing those
  9349. if( !m_config->includeSuccessfulResults() && result.isOk() ) {
  9350. if( result.getResultType() != ResultWas::Warning )
  9351. return false;
  9352. printInfoMessages = false;
  9353. }
  9354. AssertionPrinter printer( stream, _assertionStats, printInfoMessages );
  9355. printer.print();
  9356. stream << std::endl;
  9357. return true;
  9358. }
  9359. void CompactReporter::sectionEnded(SectionStats const& _sectionStats) {
  9360. if (m_config->showDurations() == ShowDurations::Always) {
  9361. stream << getFormattedDuration(_sectionStats.durationInSeconds) << " s: " << _sectionStats.sectionInfo.name << std::endl;
  9362. }
  9363. }
  9364. void CompactReporter::testRunEnded( TestRunStats const& _testRunStats ) {
  9365. printTotals( stream, _testRunStats.totals );
  9366. stream << '\n' << std::endl;
  9367. StreamingReporterBase::testRunEnded( _testRunStats );
  9368. }
  9369. CompactReporter::~CompactReporter() {}
  9370. CATCH_REGISTER_REPORTER( "compact", CompactReporter )
  9371. } // end namespace Catch
  9372. // end catch_reporter_compact.cpp
  9373. // start catch_reporter_console.cpp
  9374. #include <cfloat>
  9375. #include <cstdio>
  9376. #if defined(_MSC_VER)
  9377. #pragma warning(push)
  9378. #pragma warning(disable:4061) // Not all labels are EXPLICITLY handled in switch
  9379. // Note that 4062 (not all labels are handled
  9380. // and default is missing) is enabled
  9381. #endif
  9382. namespace Catch {
  9383. namespace {
  9384. // Formatter impl for ConsoleReporter
  9385. class ConsoleAssertionPrinter {
  9386. public:
  9387. ConsoleAssertionPrinter& operator= (ConsoleAssertionPrinter const&) = delete;
  9388. ConsoleAssertionPrinter(ConsoleAssertionPrinter const&) = delete;
  9389. ConsoleAssertionPrinter(std::ostream& _stream, AssertionStats const& _stats, bool _printInfoMessages)
  9390. : stream(_stream),
  9391. stats(_stats),
  9392. result(_stats.assertionResult),
  9393. colour(Colour::None),
  9394. message(result.getMessage()),
  9395. messages(_stats.infoMessages),
  9396. printInfoMessages(_printInfoMessages) {
  9397. switch (result.getResultType()) {
  9398. case ResultWas::Ok:
  9399. colour = Colour::Success;
  9400. passOrFail = "PASSED";
  9401. //if( result.hasMessage() )
  9402. if (_stats.infoMessages.size() == 1)
  9403. messageLabel = "with message";
  9404. if (_stats.infoMessages.size() > 1)
  9405. messageLabel = "with messages";
  9406. break;
  9407. case ResultWas::ExpressionFailed:
  9408. if (result.isOk()) {
  9409. colour = Colour::Success;
  9410. passOrFail = "FAILED - but was ok";
  9411. } else {
  9412. colour = Colour::Error;
  9413. passOrFail = "FAILED";
  9414. }
  9415. if (_stats.infoMessages.size() == 1)
  9416. messageLabel = "with message";
  9417. if (_stats.infoMessages.size() > 1)
  9418. messageLabel = "with messages";
  9419. break;
  9420. case ResultWas::ThrewException:
  9421. colour = Colour::Error;
  9422. passOrFail = "FAILED";
  9423. messageLabel = "due to unexpected exception with ";
  9424. if (_stats.infoMessages.size() == 1)
  9425. messageLabel += "message";
  9426. if (_stats.infoMessages.size() > 1)
  9427. messageLabel += "messages";
  9428. break;
  9429. case ResultWas::FatalErrorCondition:
  9430. colour = Colour::Error;
  9431. passOrFail = "FAILED";
  9432. messageLabel = "due to a fatal error condition";
  9433. break;
  9434. case ResultWas::DidntThrowException:
  9435. colour = Colour::Error;
  9436. passOrFail = "FAILED";
  9437. messageLabel = "because no exception was thrown where one was expected";
  9438. break;
  9439. case ResultWas::Info:
  9440. messageLabel = "info";
  9441. break;
  9442. case ResultWas::Warning:
  9443. messageLabel = "warning";
  9444. break;
  9445. case ResultWas::ExplicitFailure:
  9446. passOrFail = "FAILED";
  9447. colour = Colour::Error;
  9448. if (_stats.infoMessages.size() == 1)
  9449. messageLabel = "explicitly with message";
  9450. if (_stats.infoMessages.size() > 1)
  9451. messageLabel = "explicitly with messages";
  9452. break;
  9453. // These cases are here to prevent compiler warnings
  9454. case ResultWas::Unknown:
  9455. case ResultWas::FailureBit:
  9456. case ResultWas::Exception:
  9457. passOrFail = "** internal error **";
  9458. colour = Colour::Error;
  9459. break;
  9460. }
  9461. }
  9462. void print() const {
  9463. printSourceInfo();
  9464. if (stats.totals.assertions.total() > 0) {
  9465. if (result.isOk())
  9466. stream << '\n';
  9467. printResultType();
  9468. printOriginalExpression();
  9469. printReconstructedExpression();
  9470. } else {
  9471. stream << '\n';
  9472. }
  9473. printMessage();
  9474. }
  9475. private:
  9476. void printResultType() const {
  9477. if (!passOrFail.empty()) {
  9478. Colour colourGuard(colour);
  9479. stream << passOrFail << ":\n";
  9480. }
  9481. }
  9482. void printOriginalExpression() const {
  9483. if (result.hasExpression()) {
  9484. Colour colourGuard(Colour::OriginalExpression);
  9485. stream << " ";
  9486. stream << result.getExpressionInMacro();
  9487. stream << '\n';
  9488. }
  9489. }
  9490. void printReconstructedExpression() const {
  9491. if (result.hasExpandedExpression()) {
  9492. stream << "with expansion:\n";
  9493. Colour colourGuard(Colour::ReconstructedExpression);
  9494. stream << Column(result.getExpandedExpression()).indent(2) << '\n';
  9495. }
  9496. }
  9497. void printMessage() const {
  9498. if (!messageLabel.empty())
  9499. stream << messageLabel << ':' << '\n';
  9500. for (auto const& msg : messages) {
  9501. // If this assertion is a warning ignore any INFO messages
  9502. if (printInfoMessages || msg.type != ResultWas::Info)
  9503. stream << Column(msg.message).indent(2) << '\n';
  9504. }
  9505. }
  9506. void printSourceInfo() const {
  9507. Colour colourGuard(Colour::FileName);
  9508. stream << result.getSourceInfo() << ": ";
  9509. }
  9510. std::ostream& stream;
  9511. AssertionStats const& stats;
  9512. AssertionResult const& result;
  9513. Colour::Code colour;
  9514. std::string passOrFail;
  9515. std::string messageLabel;
  9516. std::string message;
  9517. std::vector<MessageInfo> messages;
  9518. bool printInfoMessages;
  9519. };
  9520. std::size_t makeRatio(std::size_t number, std::size_t total) {
  9521. std::size_t ratio = total > 0 ? CATCH_CONFIG_CONSOLE_WIDTH * number / total : 0;
  9522. return (ratio == 0 && number > 0) ? 1 : ratio;
  9523. }
  9524. std::size_t& findMax(std::size_t& i, std::size_t& j, std::size_t& k) {
  9525. if (i > j && i > k)
  9526. return i;
  9527. else if (j > k)
  9528. return j;
  9529. else
  9530. return k;
  9531. }
  9532. struct ColumnInfo {
  9533. enum Justification { Left, Right };
  9534. std::string name;
  9535. int width;
  9536. Justification justification;
  9537. };
  9538. struct ColumnBreak {};
  9539. struct RowBreak {};
  9540. class Duration {
  9541. enum class Unit {
  9542. Auto,
  9543. Nanoseconds,
  9544. Microseconds,
  9545. Milliseconds,
  9546. Seconds,
  9547. Minutes
  9548. };
  9549. static const uint64_t s_nanosecondsInAMicrosecond = 1000;
  9550. static const uint64_t s_nanosecondsInAMillisecond = 1000 * s_nanosecondsInAMicrosecond;
  9551. static const uint64_t s_nanosecondsInASecond = 1000 * s_nanosecondsInAMillisecond;
  9552. static const uint64_t s_nanosecondsInAMinute = 60 * s_nanosecondsInASecond;
  9553. uint64_t m_inNanoseconds;
  9554. Unit m_units;
  9555. public:
  9556. explicit Duration(uint64_t inNanoseconds, Unit units = Unit::Auto)
  9557. : m_inNanoseconds(inNanoseconds),
  9558. m_units(units) {
  9559. if (m_units == Unit::Auto) {
  9560. if (m_inNanoseconds < s_nanosecondsInAMicrosecond)
  9561. m_units = Unit::Nanoseconds;
  9562. else if (m_inNanoseconds < s_nanosecondsInAMillisecond)
  9563. m_units = Unit::Microseconds;
  9564. else if (m_inNanoseconds < s_nanosecondsInASecond)
  9565. m_units = Unit::Milliseconds;
  9566. else if (m_inNanoseconds < s_nanosecondsInAMinute)
  9567. m_units = Unit::Seconds;
  9568. else
  9569. m_units = Unit::Minutes;
  9570. }
  9571. }
  9572. auto value() const -> double {
  9573. switch (m_units) {
  9574. case Unit::Microseconds:
  9575. return m_inNanoseconds / static_cast<double>(s_nanosecondsInAMicrosecond);
  9576. case Unit::Milliseconds:
  9577. return m_inNanoseconds / static_cast<double>(s_nanosecondsInAMillisecond);
  9578. case Unit::Seconds:
  9579. return m_inNanoseconds / static_cast<double>(s_nanosecondsInASecond);
  9580. case Unit::Minutes:
  9581. return m_inNanoseconds / static_cast<double>(s_nanosecondsInAMinute);
  9582. default:
  9583. return static_cast<double>(m_inNanoseconds);
  9584. }
  9585. }
  9586. auto unitsAsString() const -> std::string {
  9587. switch (m_units) {
  9588. case Unit::Nanoseconds:
  9589. return "ns";
  9590. case Unit::Microseconds:
  9591. return "µs";
  9592. case Unit::Milliseconds:
  9593. return "ms";
  9594. case Unit::Seconds:
  9595. return "s";
  9596. case Unit::Minutes:
  9597. return "m";
  9598. default:
  9599. return "** internal error **";
  9600. }
  9601. }
  9602. friend auto operator << (std::ostream& os, Duration const& duration) -> std::ostream& {
  9603. return os << duration.value() << " " << duration.unitsAsString();
  9604. }
  9605. };
  9606. } // end anon namespace
  9607. class TablePrinter {
  9608. std::ostream& m_os;
  9609. std::vector<ColumnInfo> m_columnInfos;
  9610. std::ostringstream m_oss;
  9611. int m_currentColumn = -1;
  9612. bool m_isOpen = false;
  9613. public:
  9614. TablePrinter( std::ostream& os, std::vector<ColumnInfo> columnInfos )
  9615. : m_os( os ),
  9616. m_columnInfos( std::move( columnInfos ) ) {}
  9617. auto columnInfos() const -> std::vector<ColumnInfo> const& {
  9618. return m_columnInfos;
  9619. }
  9620. void open() {
  9621. if (!m_isOpen) {
  9622. m_isOpen = true;
  9623. *this << RowBreak();
  9624. for (auto const& info : m_columnInfos)
  9625. *this << info.name << ColumnBreak();
  9626. *this << RowBreak();
  9627. m_os << Catch::getLineOfChars<'-'>() << "\n";
  9628. }
  9629. }
  9630. void close() {
  9631. if (m_isOpen) {
  9632. *this << RowBreak();
  9633. m_os << std::endl;
  9634. m_isOpen = false;
  9635. }
  9636. }
  9637. template<typename T>
  9638. friend TablePrinter& operator << (TablePrinter& tp, T const& value) {
  9639. tp.m_oss << value;
  9640. return tp;
  9641. }
  9642. friend TablePrinter& operator << (TablePrinter& tp, ColumnBreak) {
  9643. auto colStr = tp.m_oss.str();
  9644. // This takes account of utf8 encodings
  9645. auto strSize = Catch::StringRef(colStr).numberOfCharacters();
  9646. tp.m_oss.str("");
  9647. tp.open();
  9648. if (tp.m_currentColumn == static_cast<int>(tp.m_columnInfos.size() - 1)) {
  9649. tp.m_currentColumn = -1;
  9650. tp.m_os << "\n";
  9651. }
  9652. tp.m_currentColumn++;
  9653. auto colInfo = tp.m_columnInfos[tp.m_currentColumn];
  9654. auto padding = (strSize + 2 < static_cast<std::size_t>(colInfo.width))
  9655. ? std::string(colInfo.width - (strSize + 2), ' ')
  9656. : std::string();
  9657. if (colInfo.justification == ColumnInfo::Left)
  9658. tp.m_os << colStr << padding << " ";
  9659. else
  9660. tp.m_os << padding << colStr << " ";
  9661. return tp;
  9662. }
  9663. friend TablePrinter& operator << (TablePrinter& tp, RowBreak) {
  9664. if (tp.m_currentColumn > 0) {
  9665. tp.m_os << "\n";
  9666. tp.m_currentColumn = -1;
  9667. }
  9668. return tp;
  9669. }
  9670. };
  9671. ConsoleReporter::ConsoleReporter(ReporterConfig const& config)
  9672. : StreamingReporterBase(config),
  9673. m_tablePrinter(new TablePrinter(config.stream(),
  9674. {
  9675. { "benchmark name", CATCH_CONFIG_CONSOLE_WIDTH - 32, ColumnInfo::Left },
  9676. { "iters", 8, ColumnInfo::Right },
  9677. { "elapsed ns", 14, ColumnInfo::Right },
  9678. { "average", 14, ColumnInfo::Right }
  9679. })) {}
  9680. ConsoleReporter::~ConsoleReporter() = default;
  9681. std::string ConsoleReporter::getDescription() {
  9682. return "Reports test results as plain lines of text";
  9683. }
  9684. void ConsoleReporter::noMatchingTestCases(std::string const& spec) {
  9685. stream << "No test cases matched '" << spec << '\'' << std::endl;
  9686. }
  9687. void ConsoleReporter::assertionStarting(AssertionInfo const&) {}
  9688. bool ConsoleReporter::assertionEnded(AssertionStats const& _assertionStats) {
  9689. AssertionResult const& result = _assertionStats.assertionResult;
  9690. bool includeResults = m_config->includeSuccessfulResults() || !result.isOk();
  9691. // Drop out if result was successful but we're not printing them.
  9692. if (!includeResults && result.getResultType() != ResultWas::Warning)
  9693. return false;
  9694. lazyPrint();
  9695. ConsoleAssertionPrinter printer(stream, _assertionStats, includeResults);
  9696. printer.print();
  9697. stream << std::endl;
  9698. return true;
  9699. }
  9700. void ConsoleReporter::sectionStarting(SectionInfo const& _sectionInfo) {
  9701. m_headerPrinted = false;
  9702. StreamingReporterBase::sectionStarting(_sectionInfo);
  9703. }
  9704. void ConsoleReporter::sectionEnded(SectionStats const& _sectionStats) {
  9705. m_tablePrinter->close();
  9706. if (_sectionStats.missingAssertions) {
  9707. lazyPrint();
  9708. Colour colour(Colour::ResultError);
  9709. if (m_sectionStack.size() > 1)
  9710. stream << "\nNo assertions in section";
  9711. else
  9712. stream << "\nNo assertions in test case";
  9713. stream << " '" << _sectionStats.sectionInfo.name << "'\n" << std::endl;
  9714. }
  9715. if (m_config->showDurations() == ShowDurations::Always) {
  9716. stream << getFormattedDuration(_sectionStats.durationInSeconds) << " s: " << _sectionStats.sectionInfo.name << std::endl;
  9717. }
  9718. if (m_headerPrinted) {
  9719. m_headerPrinted = false;
  9720. }
  9721. StreamingReporterBase::sectionEnded(_sectionStats);
  9722. }
  9723. void ConsoleReporter::benchmarkStarting(BenchmarkInfo const& info) {
  9724. lazyPrintWithoutClosingBenchmarkTable();
  9725. auto nameCol = Column( info.name ).width( static_cast<std::size_t>( m_tablePrinter->columnInfos()[0].width - 2 ) );
  9726. bool firstLine = true;
  9727. for (auto line : nameCol) {
  9728. if (!firstLine)
  9729. (*m_tablePrinter) << ColumnBreak() << ColumnBreak() << ColumnBreak();
  9730. else
  9731. firstLine = false;
  9732. (*m_tablePrinter) << line << ColumnBreak();
  9733. }
  9734. }
  9735. void ConsoleReporter::benchmarkEnded(BenchmarkStats const& stats) {
  9736. Duration average(stats.elapsedTimeInNanoseconds / stats.iterations);
  9737. (*m_tablePrinter)
  9738. << stats.iterations << ColumnBreak()
  9739. << stats.elapsedTimeInNanoseconds << ColumnBreak()
  9740. << average << ColumnBreak();
  9741. }
  9742. void ConsoleReporter::testCaseEnded(TestCaseStats const& _testCaseStats) {
  9743. m_tablePrinter->close();
  9744. StreamingReporterBase::testCaseEnded(_testCaseStats);
  9745. m_headerPrinted = false;
  9746. }
  9747. void ConsoleReporter::testGroupEnded(TestGroupStats const& _testGroupStats) {
  9748. if (currentGroupInfo.used) {
  9749. printSummaryDivider();
  9750. stream << "Summary for group '" << _testGroupStats.groupInfo.name << "':\n";
  9751. printTotals(_testGroupStats.totals);
  9752. stream << '\n' << std::endl;
  9753. }
  9754. StreamingReporterBase::testGroupEnded(_testGroupStats);
  9755. }
  9756. void ConsoleReporter::testRunEnded(TestRunStats const& _testRunStats) {
  9757. printTotalsDivider(_testRunStats.totals);
  9758. printTotals(_testRunStats.totals);
  9759. stream << std::endl;
  9760. StreamingReporterBase::testRunEnded(_testRunStats);
  9761. }
  9762. void ConsoleReporter::lazyPrint() {
  9763. m_tablePrinter->close();
  9764. lazyPrintWithoutClosingBenchmarkTable();
  9765. }
  9766. void ConsoleReporter::lazyPrintWithoutClosingBenchmarkTable() {
  9767. if (!currentTestRunInfo.used)
  9768. lazyPrintRunInfo();
  9769. if (!currentGroupInfo.used)
  9770. lazyPrintGroupInfo();
  9771. if (!m_headerPrinted) {
  9772. printTestCaseAndSectionHeader();
  9773. m_headerPrinted = true;
  9774. }
  9775. }
  9776. void ConsoleReporter::lazyPrintRunInfo() {
  9777. stream << '\n' << getLineOfChars<'~'>() << '\n';
  9778. Colour colour(Colour::SecondaryText);
  9779. stream << currentTestRunInfo->name
  9780. << " is a Catch v" << libraryVersion() << " host application.\n"
  9781. << "Run with -? for options\n\n";
  9782. if (m_config->rngSeed() != 0)
  9783. stream << "Randomness seeded to: " << m_config->rngSeed() << "\n\n";
  9784. currentTestRunInfo.used = true;
  9785. }
  9786. void ConsoleReporter::lazyPrintGroupInfo() {
  9787. if (!currentGroupInfo->name.empty() && currentGroupInfo->groupsCounts > 1) {
  9788. printClosedHeader("Group: " + currentGroupInfo->name);
  9789. currentGroupInfo.used = true;
  9790. }
  9791. }
  9792. void ConsoleReporter::printTestCaseAndSectionHeader() {
  9793. assert(!m_sectionStack.empty());
  9794. printOpenHeader(currentTestCaseInfo->name);
  9795. if (m_sectionStack.size() > 1) {
  9796. Colour colourGuard(Colour::Headers);
  9797. auto
  9798. it = m_sectionStack.begin() + 1, // Skip first section (test case)
  9799. itEnd = m_sectionStack.end();
  9800. for (; it != itEnd; ++it)
  9801. printHeaderString(it->name, 2);
  9802. }
  9803. SourceLineInfo lineInfo = m_sectionStack.back().lineInfo;
  9804. if (!lineInfo.empty()) {
  9805. stream << getLineOfChars<'-'>() << '\n';
  9806. Colour colourGuard(Colour::FileName);
  9807. stream << lineInfo << '\n';
  9808. }
  9809. stream << getLineOfChars<'.'>() << '\n' << std::endl;
  9810. }
  9811. void ConsoleReporter::printClosedHeader(std::string const& _name) {
  9812. printOpenHeader(_name);
  9813. stream << getLineOfChars<'.'>() << '\n';
  9814. }
  9815. void ConsoleReporter::printOpenHeader(std::string const& _name) {
  9816. stream << getLineOfChars<'-'>() << '\n';
  9817. {
  9818. Colour colourGuard(Colour::Headers);
  9819. printHeaderString(_name);
  9820. }
  9821. }
  9822. // if string has a : in first line will set indent to follow it on
  9823. // subsequent lines
  9824. void ConsoleReporter::printHeaderString(std::string const& _string, std::size_t indent) {
  9825. std::size_t i = _string.find(": ");
  9826. if (i != std::string::npos)
  9827. i += 2;
  9828. else
  9829. i = 0;
  9830. stream << Column(_string).indent(indent + i).initialIndent(indent) << '\n';
  9831. }
  9832. struct SummaryColumn {
  9833. SummaryColumn( std::string _label, Colour::Code _colour )
  9834. : label( std::move( _label ) ),
  9835. colour( _colour ) {}
  9836. SummaryColumn addRow( std::size_t count ) {
  9837. ReusableStringStream rss;
  9838. rss << count;
  9839. std::string row = rss.str();
  9840. for (auto& oldRow : rows) {
  9841. while (oldRow.size() < row.size())
  9842. oldRow = ' ' + oldRow;
  9843. while (oldRow.size() > row.size())
  9844. row = ' ' + row;
  9845. }
  9846. rows.push_back(row);
  9847. return *this;
  9848. }
  9849. std::string label;
  9850. Colour::Code colour;
  9851. std::vector<std::string> rows;
  9852. };
  9853. void ConsoleReporter::printTotals( Totals const& totals ) {
  9854. if (totals.testCases.total() == 0) {
  9855. stream << Colour(Colour::Warning) << "No tests ran\n";
  9856. } else if (totals.assertions.total() > 0 && totals.testCases.allPassed()) {
  9857. stream << Colour(Colour::ResultSuccess) << "All tests passed";
  9858. stream << " ("
  9859. << pluralise(totals.assertions.passed, "assertion") << " in "
  9860. << pluralise(totals.testCases.passed, "test case") << ')'
  9861. << '\n';
  9862. } else {
  9863. std::vector<SummaryColumn> columns;
  9864. columns.push_back(SummaryColumn("", Colour::None)
  9865. .addRow(totals.testCases.total())
  9866. .addRow(totals.assertions.total()));
  9867. columns.push_back(SummaryColumn("passed", Colour::Success)
  9868. .addRow(totals.testCases.passed)
  9869. .addRow(totals.assertions.passed));
  9870. columns.push_back(SummaryColumn("failed", Colour::ResultError)
  9871. .addRow(totals.testCases.failed)
  9872. .addRow(totals.assertions.failed));
  9873. columns.push_back(SummaryColumn("failed as expected", Colour::ResultExpectedFailure)
  9874. .addRow(totals.testCases.failedButOk)
  9875. .addRow(totals.assertions.failedButOk));
  9876. printSummaryRow("test cases", columns, 0);
  9877. printSummaryRow("assertions", columns, 1);
  9878. }
  9879. }
  9880. void ConsoleReporter::printSummaryRow(std::string const& label, std::vector<SummaryColumn> const& cols, std::size_t row) {
  9881. for (auto col : cols) {
  9882. std::string value = col.rows[row];
  9883. if (col.label.empty()) {
  9884. stream << label << ": ";
  9885. if (value != "0")
  9886. stream << value;
  9887. else
  9888. stream << Colour(Colour::Warning) << "- none -";
  9889. } else if (value != "0") {
  9890. stream << Colour(Colour::LightGrey) << " | ";
  9891. stream << Colour(col.colour)
  9892. << value << ' ' << col.label;
  9893. }
  9894. }
  9895. stream << '\n';
  9896. }
  9897. void ConsoleReporter::printTotalsDivider(Totals const& totals) {
  9898. if (totals.testCases.total() > 0) {
  9899. std::size_t failedRatio = makeRatio(totals.testCases.failed, totals.testCases.total());
  9900. std::size_t failedButOkRatio = makeRatio(totals.testCases.failedButOk, totals.testCases.total());
  9901. std::size_t passedRatio = makeRatio(totals.testCases.passed, totals.testCases.total());
  9902. while (failedRatio + failedButOkRatio + passedRatio < CATCH_CONFIG_CONSOLE_WIDTH - 1)
  9903. findMax(failedRatio, failedButOkRatio, passedRatio)++;
  9904. while (failedRatio + failedButOkRatio + passedRatio > CATCH_CONFIG_CONSOLE_WIDTH - 1)
  9905. findMax(failedRatio, failedButOkRatio, passedRatio)--;
  9906. stream << Colour(Colour::Error) << std::string(failedRatio, '=');
  9907. stream << Colour(Colour::ResultExpectedFailure) << std::string(failedButOkRatio, '=');
  9908. if (totals.testCases.allPassed())
  9909. stream << Colour(Colour::ResultSuccess) << std::string(passedRatio, '=');
  9910. else
  9911. stream << Colour(Colour::Success) << std::string(passedRatio, '=');
  9912. } else {
  9913. stream << Colour(Colour::Warning) << std::string(CATCH_CONFIG_CONSOLE_WIDTH - 1, '=');
  9914. }
  9915. stream << '\n';
  9916. }
  9917. void ConsoleReporter::printSummaryDivider() {
  9918. stream << getLineOfChars<'-'>() << '\n';
  9919. }
  9920. CATCH_REGISTER_REPORTER("console", ConsoleReporter)
  9921. } // end namespace Catch
  9922. #if defined(_MSC_VER)
  9923. #pragma warning(pop)
  9924. #endif
  9925. // end catch_reporter_console.cpp
  9926. // start catch_reporter_junit.cpp
  9927. #include <assert.h>
  9928. #include <sstream>
  9929. #include <ctime>
  9930. #include <algorithm>
  9931. namespace Catch {
  9932. namespace {
  9933. std::string getCurrentTimestamp() {
  9934. // Beware, this is not reentrant because of backward compatibility issues
  9935. // Also, UTC only, again because of backward compatibility (%z is C++11)
  9936. time_t rawtime;
  9937. std::time(&rawtime);
  9938. auto const timeStampSize = sizeof("2017-01-16T17:06:45Z");
  9939. #ifdef _MSC_VER
  9940. std::tm timeInfo = {};
  9941. gmtime_s(&timeInfo, &rawtime);
  9942. #else
  9943. std::tm* timeInfo;
  9944. timeInfo = std::gmtime(&rawtime);
  9945. #endif
  9946. char timeStamp[timeStampSize];
  9947. const char * const fmt = "%Y-%m-%dT%H:%M:%SZ";
  9948. #ifdef _MSC_VER
  9949. std::strftime(timeStamp, timeStampSize, fmt, &timeInfo);
  9950. #else
  9951. std::strftime(timeStamp, timeStampSize, fmt, timeInfo);
  9952. #endif
  9953. return std::string(timeStamp);
  9954. }
  9955. std::string fileNameTag(const std::vector<std::string> &tags) {
  9956. auto it = std::find_if(begin(tags),
  9957. end(tags),
  9958. [] (std::string const& tag) {return tag.front() == '#'; });
  9959. if (it != tags.end())
  9960. return it->substr(1);
  9961. return std::string();
  9962. }
  9963. } // anonymous namespace
  9964. JunitReporter::JunitReporter( ReporterConfig const& _config )
  9965. : CumulativeReporterBase( _config ),
  9966. xml( _config.stream() )
  9967. {
  9968. m_reporterPrefs.shouldRedirectStdOut = true;
  9969. }
  9970. JunitReporter::~JunitReporter() {}
  9971. std::string JunitReporter::getDescription() {
  9972. return "Reports test results in an XML format that looks like Ant's junitreport target";
  9973. }
  9974. void JunitReporter::noMatchingTestCases( std::string const& /*spec*/ ) {}
  9975. void JunitReporter::testRunStarting( TestRunInfo const& runInfo ) {
  9976. CumulativeReporterBase::testRunStarting( runInfo );
  9977. xml.startElement( "testsuites" );
  9978. }
  9979. void JunitReporter::testGroupStarting( GroupInfo const& groupInfo ) {
  9980. suiteTimer.start();
  9981. stdOutForSuite.clear();
  9982. stdErrForSuite.clear();
  9983. unexpectedExceptions = 0;
  9984. CumulativeReporterBase::testGroupStarting( groupInfo );
  9985. }
  9986. void JunitReporter::testCaseStarting( TestCaseInfo const& testCaseInfo ) {
  9987. m_okToFail = testCaseInfo.okToFail();
  9988. }
  9989. bool JunitReporter::assertionEnded( AssertionStats const& assertionStats ) {
  9990. if( assertionStats.assertionResult.getResultType() == ResultWas::ThrewException && !m_okToFail )
  9991. unexpectedExceptions++;
  9992. return CumulativeReporterBase::assertionEnded( assertionStats );
  9993. }
  9994. void JunitReporter::testCaseEnded( TestCaseStats const& testCaseStats ) {
  9995. stdOutForSuite += testCaseStats.stdOut;
  9996. stdErrForSuite += testCaseStats.stdErr;
  9997. CumulativeReporterBase::testCaseEnded( testCaseStats );
  9998. }
  9999. void JunitReporter::testGroupEnded( TestGroupStats const& testGroupStats ) {
  10000. double suiteTime = suiteTimer.getElapsedSeconds();
  10001. CumulativeReporterBase::testGroupEnded( testGroupStats );
  10002. writeGroup( *m_testGroups.back(), suiteTime );
  10003. }
  10004. void JunitReporter::testRunEndedCumulative() {
  10005. xml.endElement();
  10006. }
  10007. void JunitReporter::writeGroup( TestGroupNode const& groupNode, double suiteTime ) {
  10008. XmlWriter::ScopedElement e = xml.scopedElement( "testsuite" );
  10009. TestGroupStats const& stats = groupNode.value;
  10010. xml.writeAttribute( "name", stats.groupInfo.name );
  10011. xml.writeAttribute( "errors", unexpectedExceptions );
  10012. xml.writeAttribute( "failures", stats.totals.assertions.failed-unexpectedExceptions );
  10013. xml.writeAttribute( "tests", stats.totals.assertions.total() );
  10014. xml.writeAttribute( "hostname", "tbd" ); // !TBD
  10015. if( m_config->showDurations() == ShowDurations::Never )
  10016. xml.writeAttribute( "time", "" );
  10017. else
  10018. xml.writeAttribute( "time", suiteTime );
  10019. xml.writeAttribute( "timestamp", getCurrentTimestamp() );
  10020. // Write test cases
  10021. for( auto const& child : groupNode.children )
  10022. writeTestCase( *child );
  10023. xml.scopedElement( "system-out" ).writeText( trim( stdOutForSuite ), false );
  10024. xml.scopedElement( "system-err" ).writeText( trim( stdErrForSuite ), false );
  10025. }
  10026. void JunitReporter::writeTestCase( TestCaseNode const& testCaseNode ) {
  10027. TestCaseStats const& stats = testCaseNode.value;
  10028. // All test cases have exactly one section - which represents the
  10029. // test case itself. That section may have 0-n nested sections
  10030. assert( testCaseNode.children.size() == 1 );
  10031. SectionNode const& rootSection = *testCaseNode.children.front();
  10032. std::string className = stats.testInfo.className;
  10033. if( className.empty() ) {
  10034. className = fileNameTag(stats.testInfo.tags);
  10035. if ( className.empty() )
  10036. className = "global";
  10037. }
  10038. if ( !m_config->name().empty() )
  10039. className = m_config->name() + "." + className;
  10040. writeSection( className, "", rootSection );
  10041. }
  10042. void JunitReporter::writeSection( std::string const& className,
  10043. std::string const& rootName,
  10044. SectionNode const& sectionNode ) {
  10045. std::string name = trim( sectionNode.stats.sectionInfo.name );
  10046. if( !rootName.empty() )
  10047. name = rootName + '/' + name;
  10048. if( !sectionNode.assertions.empty() ||
  10049. !sectionNode.stdOut.empty() ||
  10050. !sectionNode.stdErr.empty() ) {
  10051. XmlWriter::ScopedElement e = xml.scopedElement( "testcase" );
  10052. if( className.empty() ) {
  10053. xml.writeAttribute( "classname", name );
  10054. xml.writeAttribute( "name", "root" );
  10055. }
  10056. else {
  10057. xml.writeAttribute( "classname", className );
  10058. xml.writeAttribute( "name", name );
  10059. }
  10060. xml.writeAttribute( "time", ::Catch::Detail::stringify( sectionNode.stats.durationInSeconds ) );
  10061. writeAssertions( sectionNode );
  10062. if( !sectionNode.stdOut.empty() )
  10063. xml.scopedElement( "system-out" ).writeText( trim( sectionNode.stdOut ), false );
  10064. if( !sectionNode.stdErr.empty() )
  10065. xml.scopedElement( "system-err" ).writeText( trim( sectionNode.stdErr ), false );
  10066. }
  10067. for( auto const& childNode : sectionNode.childSections )
  10068. if( className.empty() )
  10069. writeSection( name, "", *childNode );
  10070. else
  10071. writeSection( className, name, *childNode );
  10072. }
  10073. void JunitReporter::writeAssertions( SectionNode const& sectionNode ) {
  10074. for( auto const& assertion : sectionNode.assertions )
  10075. writeAssertion( assertion );
  10076. }
  10077. void JunitReporter::writeAssertion( AssertionStats const& stats ) {
  10078. AssertionResult const& result = stats.assertionResult;
  10079. if( !result.isOk() ) {
  10080. std::string elementName;
  10081. switch( result.getResultType() ) {
  10082. case ResultWas::ThrewException:
  10083. case ResultWas::FatalErrorCondition:
  10084. elementName = "error";
  10085. break;
  10086. case ResultWas::ExplicitFailure:
  10087. elementName = "failure";
  10088. break;
  10089. case ResultWas::ExpressionFailed:
  10090. elementName = "failure";
  10091. break;
  10092. case ResultWas::DidntThrowException:
  10093. elementName = "failure";
  10094. break;
  10095. // We should never see these here:
  10096. case ResultWas::Info:
  10097. case ResultWas::Warning:
  10098. case ResultWas::Ok:
  10099. case ResultWas::Unknown:
  10100. case ResultWas::FailureBit:
  10101. case ResultWas::Exception:
  10102. elementName = "internalError";
  10103. break;
  10104. }
  10105. XmlWriter::ScopedElement e = xml.scopedElement( elementName );
  10106. xml.writeAttribute( "message", result.getExpandedExpression() );
  10107. xml.writeAttribute( "type", result.getTestMacroName() );
  10108. ReusableStringStream rss;
  10109. if( !result.getMessage().empty() )
  10110. rss << result.getMessage() << '\n';
  10111. for( auto const& msg : stats.infoMessages )
  10112. if( msg.type == ResultWas::Info )
  10113. rss << msg.message << '\n';
  10114. rss << "at " << result.getSourceInfo();
  10115. xml.writeText( rss.str(), false );
  10116. }
  10117. }
  10118. CATCH_REGISTER_REPORTER( "junit", JunitReporter )
  10119. } // end namespace Catch
  10120. // end catch_reporter_junit.cpp
  10121. // start catch_reporter_multi.cpp
  10122. namespace Catch {
  10123. void MultipleReporters::add( IStreamingReporterPtr&& reporter ) {
  10124. m_reporters.push_back( std::move( reporter ) );
  10125. }
  10126. ReporterPreferences MultipleReporters::getPreferences() const {
  10127. return m_reporters[0]->getPreferences();
  10128. }
  10129. std::set<Verbosity> MultipleReporters::getSupportedVerbosities() {
  10130. return std::set<Verbosity>{ };
  10131. }
  10132. void MultipleReporters::noMatchingTestCases( std::string const& spec ) {
  10133. for( auto const& reporter : m_reporters )
  10134. reporter->noMatchingTestCases( spec );
  10135. }
  10136. void MultipleReporters::benchmarkStarting( BenchmarkInfo const& benchmarkInfo ) {
  10137. for( auto const& reporter : m_reporters )
  10138. reporter->benchmarkStarting( benchmarkInfo );
  10139. }
  10140. void MultipleReporters::benchmarkEnded( BenchmarkStats const& benchmarkStats ) {
  10141. for( auto const& reporter : m_reporters )
  10142. reporter->benchmarkEnded( benchmarkStats );
  10143. }
  10144. void MultipleReporters::testRunStarting( TestRunInfo const& testRunInfo ) {
  10145. for( auto const& reporter : m_reporters )
  10146. reporter->testRunStarting( testRunInfo );
  10147. }
  10148. void MultipleReporters::testGroupStarting( GroupInfo const& groupInfo ) {
  10149. for( auto const& reporter : m_reporters )
  10150. reporter->testGroupStarting( groupInfo );
  10151. }
  10152. void MultipleReporters::testCaseStarting( TestCaseInfo const& testInfo ) {
  10153. for( auto const& reporter : m_reporters )
  10154. reporter->testCaseStarting( testInfo );
  10155. }
  10156. void MultipleReporters::sectionStarting( SectionInfo const& sectionInfo ) {
  10157. for( auto const& reporter : m_reporters )
  10158. reporter->sectionStarting( sectionInfo );
  10159. }
  10160. void MultipleReporters::assertionStarting( AssertionInfo const& assertionInfo ) {
  10161. for( auto const& reporter : m_reporters )
  10162. reporter->assertionStarting( assertionInfo );
  10163. }
  10164. // The return value indicates if the messages buffer should be cleared:
  10165. bool MultipleReporters::assertionEnded( AssertionStats const& assertionStats ) {
  10166. bool clearBuffer = false;
  10167. for( auto const& reporter : m_reporters )
  10168. clearBuffer |= reporter->assertionEnded( assertionStats );
  10169. return clearBuffer;
  10170. }
  10171. void MultipleReporters::sectionEnded( SectionStats const& sectionStats ) {
  10172. for( auto const& reporter : m_reporters )
  10173. reporter->sectionEnded( sectionStats );
  10174. }
  10175. void MultipleReporters::testCaseEnded( TestCaseStats const& testCaseStats ) {
  10176. for( auto const& reporter : m_reporters )
  10177. reporter->testCaseEnded( testCaseStats );
  10178. }
  10179. void MultipleReporters::testGroupEnded( TestGroupStats const& testGroupStats ) {
  10180. for( auto const& reporter : m_reporters )
  10181. reporter->testGroupEnded( testGroupStats );
  10182. }
  10183. void MultipleReporters::testRunEnded( TestRunStats const& testRunStats ) {
  10184. for( auto const& reporter : m_reporters )
  10185. reporter->testRunEnded( testRunStats );
  10186. }
  10187. void MultipleReporters::skipTest( TestCaseInfo const& testInfo ) {
  10188. for( auto const& reporter : m_reporters )
  10189. reporter->skipTest( testInfo );
  10190. }
  10191. bool MultipleReporters::isMulti() const {
  10192. return true;
  10193. }
  10194. } // end namespace Catch
  10195. // end catch_reporter_multi.cpp
  10196. // start catch_reporter_xml.cpp
  10197. #if defined(_MSC_VER)
  10198. #pragma warning(push)
  10199. #pragma warning(disable:4061) // Not all labels are EXPLICITLY handled in switch
  10200. // Note that 4062 (not all labels are handled
  10201. // and default is missing) is enabled
  10202. #endif
  10203. namespace Catch {
  10204. XmlReporter::XmlReporter( ReporterConfig const& _config )
  10205. : StreamingReporterBase( _config ),
  10206. m_xml(_config.stream())
  10207. {
  10208. m_reporterPrefs.shouldRedirectStdOut = true;
  10209. }
  10210. XmlReporter::~XmlReporter() = default;
  10211. std::string XmlReporter::getDescription() {
  10212. return "Reports test results as an XML document";
  10213. }
  10214. std::string XmlReporter::getStylesheetRef() const {
  10215. return std::string();
  10216. }
  10217. void XmlReporter::writeSourceInfo( SourceLineInfo const& sourceInfo ) {
  10218. m_xml
  10219. .writeAttribute( "filename", sourceInfo.file )
  10220. .writeAttribute( "line", sourceInfo.line );
  10221. }
  10222. void XmlReporter::noMatchingTestCases( std::string const& s ) {
  10223. StreamingReporterBase::noMatchingTestCases( s );
  10224. }
  10225. void XmlReporter::testRunStarting( TestRunInfo const& testInfo ) {
  10226. StreamingReporterBase::testRunStarting( testInfo );
  10227. std::string stylesheetRef = getStylesheetRef();
  10228. if( !stylesheetRef.empty() )
  10229. m_xml.writeStylesheetRef( stylesheetRef );
  10230. m_xml.startElement( "Catch" );
  10231. if( !m_config->name().empty() )
  10232. m_xml.writeAttribute( "name", m_config->name() );
  10233. }
  10234. void XmlReporter::testGroupStarting( GroupInfo const& groupInfo ) {
  10235. StreamingReporterBase::testGroupStarting( groupInfo );
  10236. m_xml.startElement( "Group" )
  10237. .writeAttribute( "name", groupInfo.name );
  10238. }
  10239. void XmlReporter::testCaseStarting( TestCaseInfo const& testInfo ) {
  10240. StreamingReporterBase::testCaseStarting(testInfo);
  10241. m_xml.startElement( "TestCase" )
  10242. .writeAttribute( "name", trim( testInfo.name ) )
  10243. .writeAttribute( "description", testInfo.description )
  10244. .writeAttribute( "tags", testInfo.tagsAsString() );
  10245. writeSourceInfo( testInfo.lineInfo );
  10246. if ( m_config->showDurations() == ShowDurations::Always )
  10247. m_testCaseTimer.start();
  10248. m_xml.ensureTagClosed();
  10249. }
  10250. void XmlReporter::sectionStarting( SectionInfo const& sectionInfo ) {
  10251. StreamingReporterBase::sectionStarting( sectionInfo );
  10252. if( m_sectionDepth++ > 0 ) {
  10253. m_xml.startElement( "Section" )
  10254. .writeAttribute( "name", trim( sectionInfo.name ) )
  10255. .writeAttribute( "description", sectionInfo.description );
  10256. writeSourceInfo( sectionInfo.lineInfo );
  10257. m_xml.ensureTagClosed();
  10258. }
  10259. }
  10260. void XmlReporter::assertionStarting( AssertionInfo const& ) { }
  10261. bool XmlReporter::assertionEnded( AssertionStats const& assertionStats ) {
  10262. AssertionResult const& result = assertionStats.assertionResult;
  10263. bool includeResults = m_config->includeSuccessfulResults() || !result.isOk();
  10264. if( includeResults || result.getResultType() == ResultWas::Warning ) {
  10265. // Print any info messages in <Info> tags.
  10266. for( auto const& msg : assertionStats.infoMessages ) {
  10267. if( msg.type == ResultWas::Info && includeResults ) {
  10268. m_xml.scopedElement( "Info" )
  10269. .writeText( msg.message );
  10270. } else if ( msg.type == ResultWas::Warning ) {
  10271. m_xml.scopedElement( "Warning" )
  10272. .writeText( msg.message );
  10273. }
  10274. }
  10275. }
  10276. // Drop out if result was successful but we're not printing them.
  10277. if( !includeResults && result.getResultType() != ResultWas::Warning )
  10278. return true;
  10279. // Print the expression if there is one.
  10280. if( result.hasExpression() ) {
  10281. m_xml.startElement( "Expression" )
  10282. .writeAttribute( "success", result.succeeded() )
  10283. .writeAttribute( "type", result.getTestMacroName() );
  10284. writeSourceInfo( result.getSourceInfo() );
  10285. m_xml.scopedElement( "Original" )
  10286. .writeText( result.getExpression() );
  10287. m_xml.scopedElement( "Expanded" )
  10288. .writeText( result.getExpandedExpression() );
  10289. }
  10290. // And... Print a result applicable to each result type.
  10291. switch( result.getResultType() ) {
  10292. case ResultWas::ThrewException:
  10293. m_xml.startElement( "Exception" );
  10294. writeSourceInfo( result.getSourceInfo() );
  10295. m_xml.writeText( result.getMessage() );
  10296. m_xml.endElement();
  10297. break;
  10298. case ResultWas::FatalErrorCondition:
  10299. m_xml.startElement( "FatalErrorCondition" );
  10300. writeSourceInfo( result.getSourceInfo() );
  10301. m_xml.writeText( result.getMessage() );
  10302. m_xml.endElement();
  10303. break;
  10304. case ResultWas::Info:
  10305. m_xml.scopedElement( "Info" )
  10306. .writeText( result.getMessage() );
  10307. break;
  10308. case ResultWas::Warning:
  10309. // Warning will already have been written
  10310. break;
  10311. case ResultWas::ExplicitFailure:
  10312. m_xml.startElement( "Failure" );
  10313. writeSourceInfo( result.getSourceInfo() );
  10314. m_xml.writeText( result.getMessage() );
  10315. m_xml.endElement();
  10316. break;
  10317. default:
  10318. break;
  10319. }
  10320. if( result.hasExpression() )
  10321. m_xml.endElement();
  10322. return true;
  10323. }
  10324. void XmlReporter::sectionEnded( SectionStats const& sectionStats ) {
  10325. StreamingReporterBase::sectionEnded( sectionStats );
  10326. if( --m_sectionDepth > 0 ) {
  10327. XmlWriter::ScopedElement e = m_xml.scopedElement( "OverallResults" );
  10328. e.writeAttribute( "successes", sectionStats.assertions.passed );
  10329. e.writeAttribute( "failures", sectionStats.assertions.failed );
  10330. e.writeAttribute( "expectedFailures", sectionStats.assertions.failedButOk );
  10331. if ( m_config->showDurations() == ShowDurations::Always )
  10332. e.writeAttribute( "durationInSeconds", sectionStats.durationInSeconds );
  10333. m_xml.endElement();
  10334. }
  10335. }
  10336. void XmlReporter::testCaseEnded( TestCaseStats const& testCaseStats ) {
  10337. StreamingReporterBase::testCaseEnded( testCaseStats );
  10338. XmlWriter::ScopedElement e = m_xml.scopedElement( "OverallResult" );
  10339. e.writeAttribute( "success", testCaseStats.totals.assertions.allOk() );
  10340. if ( m_config->showDurations() == ShowDurations::Always )
  10341. e.writeAttribute( "durationInSeconds", m_testCaseTimer.getElapsedSeconds() );
  10342. if( !testCaseStats.stdOut.empty() )
  10343. m_xml.scopedElement( "StdOut" ).writeText( trim( testCaseStats.stdOut ), false );
  10344. if( !testCaseStats.stdErr.empty() )
  10345. m_xml.scopedElement( "StdErr" ).writeText( trim( testCaseStats.stdErr ), false );
  10346. m_xml.endElement();
  10347. }
  10348. void XmlReporter::testGroupEnded( TestGroupStats const& testGroupStats ) {
  10349. StreamingReporterBase::testGroupEnded( testGroupStats );
  10350. // TODO: Check testGroupStats.aborting and act accordingly.
  10351. m_xml.scopedElement( "OverallResults" )
  10352. .writeAttribute( "successes", testGroupStats.totals.assertions.passed )
  10353. .writeAttribute( "failures", testGroupStats.totals.assertions.failed )
  10354. .writeAttribute( "expectedFailures", testGroupStats.totals.assertions.failedButOk );
  10355. m_xml.endElement();
  10356. }
  10357. void XmlReporter::testRunEnded( TestRunStats const& testRunStats ) {
  10358. StreamingReporterBase::testRunEnded( testRunStats );
  10359. m_xml.scopedElement( "OverallResults" )
  10360. .writeAttribute( "successes", testRunStats.totals.assertions.passed )
  10361. .writeAttribute( "failures", testRunStats.totals.assertions.failed )
  10362. .writeAttribute( "expectedFailures", testRunStats.totals.assertions.failedButOk );
  10363. m_xml.endElement();
  10364. }
  10365. CATCH_REGISTER_REPORTER( "xml", XmlReporter )
  10366. } // end namespace Catch
  10367. #if defined(_MSC_VER)
  10368. #pragma warning(pop)
  10369. #endif
  10370. // end catch_reporter_xml.cpp
  10371. namespace Catch {
  10372. LeakDetector leakDetector;
  10373. }
  10374. #ifdef __clang__
  10375. #pragma clang diagnostic pop
  10376. #endif
  10377. // end catch_impl.hpp
  10378. #endif
  10379. #ifdef CATCH_CONFIG_MAIN
  10380. // start catch_default_main.hpp
  10381. #ifndef __OBJC__
  10382. #if defined(CATCH_CONFIG_WCHAR) && defined(WIN32) && defined(_UNICODE) && !defined(DO_NOT_USE_WMAIN)
  10383. // Standard C/C++ Win32 Unicode wmain entry point
  10384. extern "C" int wmain (int argc, wchar_t * argv[], wchar_t * []) {
  10385. #else
  10386. // Standard C/C++ main entry point
  10387. int main (int argc, char * argv[]) {
  10388. #endif
  10389. return Catch::Session().run( argc, argv );
  10390. }
  10391. #else // __OBJC__
  10392. // Objective-C entry point
  10393. int main (int argc, char * const argv[]) {
  10394. #if !CATCH_ARC_ENABLED
  10395. NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
  10396. #endif
  10397. Catch::registerTestMethods();
  10398. int result = Catch::Session().run( argc, (char**)argv );
  10399. #if !CATCH_ARC_ENABLED
  10400. [pool drain];
  10401. #endif
  10402. return result;
  10403. }
  10404. #endif // __OBJC__
  10405. // end catch_default_main.hpp
  10406. #endif
  10407. #if !defined(CATCH_CONFIG_IMPL_ONLY)
  10408. #ifdef CLARA_CONFIG_MAIN_NOT_DEFINED
  10409. # undef CLARA_CONFIG_MAIN
  10410. #endif
  10411. #if !defined(CATCH_CONFIG_DISABLE)
  10412. //////
  10413. // If this config identifier is defined then all CATCH macros are prefixed with CATCH_
  10414. #ifdef CATCH_CONFIG_PREFIX_ALL
  10415. #define CATCH_REQUIRE( ... ) INTERNAL_CATCH_TEST( "CATCH_REQUIRE", Catch::ResultDisposition::Normal, __VA_ARGS__ )
  10416. #define CATCH_REQUIRE_FALSE( ... ) INTERNAL_CATCH_TEST( "CATCH_REQUIRE_FALSE", Catch::ResultDisposition::Normal | Catch::ResultDisposition::FalseTest, __VA_ARGS__ )
  10417. #define CATCH_REQUIRE_THROWS( ... ) INTERNAL_CATCH_THROWS( "CATCH_REQUIRE_THROWS", Catch::ResultDisposition::Normal, "", __VA_ARGS__ )
  10418. #define CATCH_REQUIRE_THROWS_AS( expr, exceptionType ) INTERNAL_CATCH_THROWS_AS( "CATCH_REQUIRE_THROWS_AS", exceptionType, Catch::ResultDisposition::Normal, expr )
  10419. #define CATCH_REQUIRE_THROWS_WITH( expr, matcher ) INTERNAL_CATCH_THROWS_STR_MATCHES( "CATCH_REQUIRE_THROWS_WITH", Catch::ResultDisposition::Normal, matcher, expr )
  10420. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  10421. #define CATCH_REQUIRE_THROWS_MATCHES( expr, exceptionType, matcher ) INTERNAL_CATCH_THROWS_MATCHES( "CATCH_REQUIRE_THROWS_MATCHES", exceptionType, Catch::ResultDisposition::Normal, matcher, expr )
  10422. #endif// CATCH_CONFIG_DISABLE_MATCHERS
  10423. #define CATCH_REQUIRE_NOTHROW( ... ) INTERNAL_CATCH_NO_THROW( "CATCH_REQUIRE_NOTHROW", Catch::ResultDisposition::Normal, __VA_ARGS__ )
  10424. #define CATCH_CHECK( ... ) INTERNAL_CATCH_TEST( "CATCH_CHECK", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  10425. #define CATCH_CHECK_FALSE( ... ) INTERNAL_CATCH_TEST( "CATCH_CHECK_FALSE", Catch::ResultDisposition::ContinueOnFailure | Catch::ResultDisposition::FalseTest, __VA_ARGS__ )
  10426. #define CATCH_CHECKED_IF( ... ) INTERNAL_CATCH_IF( "CATCH_CHECKED_IF", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  10427. #define CATCH_CHECKED_ELSE( ... ) INTERNAL_CATCH_ELSE( "CATCH_CHECKED_ELSE", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  10428. #define CATCH_CHECK_NOFAIL( ... ) INTERNAL_CATCH_TEST( "CATCH_CHECK_NOFAIL", Catch::ResultDisposition::ContinueOnFailure | Catch::ResultDisposition::SuppressFail, __VA_ARGS__ )
  10429. #define CATCH_CHECK_THROWS( ... ) INTERNAL_CATCH_THROWS( "CATCH_CHECK_THROWS", Catch::ResultDisposition::ContinueOnFailure, "", __VA_ARGS__ )
  10430. #define CATCH_CHECK_THROWS_AS( expr, exceptionType ) INTERNAL_CATCH_THROWS_AS( "CATCH_CHECK_THROWS_AS", exceptionType, Catch::ResultDisposition::ContinueOnFailure, expr )
  10431. #define CATCH_CHECK_THROWS_WITH( expr, matcher ) INTERNAL_CATCH_THROWS_STR_MATCHES( "CATCH_CHECK_THROWS_WITH", Catch::ResultDisposition::ContinueOnFailure, matcher, expr )
  10432. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  10433. #define CATCH_CHECK_THROWS_MATCHES( expr, exceptionType, matcher ) INTERNAL_CATCH_THROWS_MATCHES( "CATCH_CHECK_THROWS_MATCHES", exceptionType, Catch::ResultDisposition::ContinueOnFailure, matcher, expr )
  10434. #endif // CATCH_CONFIG_DISABLE_MATCHERS
  10435. #define CATCH_CHECK_NOTHROW( ... ) INTERNAL_CATCH_NO_THROW( "CATCH_CHECK_NOTHROW", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  10436. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  10437. #define CATCH_CHECK_THAT( arg, matcher ) INTERNAL_CHECK_THAT( "CATCH_CHECK_THAT", matcher, Catch::ResultDisposition::ContinueOnFailure, arg )
  10438. #define CATCH_REQUIRE_THAT( arg, matcher ) INTERNAL_CHECK_THAT( "CATCH_REQUIRE_THAT", matcher, Catch::ResultDisposition::Normal, arg )
  10439. #endif // CATCH_CONFIG_DISABLE_MATCHERS
  10440. #define CATCH_INFO( msg ) INTERNAL_CATCH_INFO( "CATCH_INFO", msg )
  10441. #define CATCH_WARN( msg ) INTERNAL_CATCH_MSG( "CATCH_WARN", Catch::ResultWas::Warning, Catch::ResultDisposition::ContinueOnFailure, msg )
  10442. #define CATCH_CAPTURE( msg ) INTERNAL_CATCH_INFO( "CATCH_CAPTURE", #msg " := " << ::Catch::Detail::stringify(msg) )
  10443. #define CATCH_TEST_CASE( ... ) INTERNAL_CATCH_TESTCASE( __VA_ARGS__ )
  10444. #define CATCH_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEST_CASE_METHOD( className, __VA_ARGS__ )
  10445. #define CATCH_METHOD_AS_TEST_CASE( method, ... ) INTERNAL_CATCH_METHOD_AS_TEST_CASE( method, __VA_ARGS__ )
  10446. #define CATCH_REGISTER_TEST_CASE( Function, ... ) INTERNAL_CATCH_REGISTER_TESTCASE( Function, __VA_ARGS__ )
  10447. #define CATCH_SECTION( ... ) INTERNAL_CATCH_SECTION( __VA_ARGS__ )
  10448. #define CATCH_FAIL( ... ) INTERNAL_CATCH_MSG( "CATCH_FAIL", Catch::ResultWas::ExplicitFailure, Catch::ResultDisposition::Normal, __VA_ARGS__ )
  10449. #define CATCH_FAIL_CHECK( ... ) INTERNAL_CATCH_MSG( "CATCH_FAIL_CHECK", Catch::ResultWas::ExplicitFailure, Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  10450. #define CATCH_SUCCEED( ... ) INTERNAL_CATCH_MSG( "CATCH_SUCCEED", Catch::ResultWas::Ok, Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  10451. #define CATCH_ANON_TEST_CASE() INTERNAL_CATCH_TESTCASE()
  10452. // "BDD-style" convenience wrappers
  10453. #define CATCH_SCENARIO( ... ) CATCH_TEST_CASE( "Scenario: " __VA_ARGS__ )
  10454. #define CATCH_SCENARIO_METHOD( className, ... ) INTERNAL_CATCH_TEST_CASE_METHOD( className, "Scenario: " __VA_ARGS__ )
  10455. #define CATCH_GIVEN( desc ) CATCH_SECTION( std::string( "Given: ") + desc )
  10456. #define CATCH_WHEN( desc ) CATCH_SECTION( std::string( " When: ") + desc )
  10457. #define CATCH_AND_WHEN( desc ) CATCH_SECTION( std::string( " And: ") + desc )
  10458. #define CATCH_THEN( desc ) CATCH_SECTION( std::string( " Then: ") + desc )
  10459. #define CATCH_AND_THEN( desc ) CATCH_SECTION( std::string( " And: ") + desc )
  10460. // If CATCH_CONFIG_PREFIX_ALL is not defined then the CATCH_ prefix is not required
  10461. #else
  10462. #define REQUIRE( ... ) INTERNAL_CATCH_TEST( "REQUIRE", Catch::ResultDisposition::Normal, __VA_ARGS__ )
  10463. #define REQUIRE_FALSE( ... ) INTERNAL_CATCH_TEST( "REQUIRE_FALSE", Catch::ResultDisposition::Normal | Catch::ResultDisposition::FalseTest, __VA_ARGS__ )
  10464. #define REQUIRE_THROWS( ... ) INTERNAL_CATCH_THROWS( "REQUIRE_THROWS", Catch::ResultDisposition::Normal, __VA_ARGS__ )
  10465. #define REQUIRE_THROWS_AS( expr, exceptionType ) INTERNAL_CATCH_THROWS_AS( "REQUIRE_THROWS_AS", exceptionType, Catch::ResultDisposition::Normal, expr )
  10466. #define REQUIRE_THROWS_WITH( expr, matcher ) INTERNAL_CATCH_THROWS_STR_MATCHES( "REQUIRE_THROWS_WITH", Catch::ResultDisposition::Normal, matcher, expr )
  10467. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  10468. #define REQUIRE_THROWS_MATCHES( expr, exceptionType, matcher ) INTERNAL_CATCH_THROWS_MATCHES( "REQUIRE_THROWS_MATCHES", exceptionType, Catch::ResultDisposition::Normal, matcher, expr )
  10469. #endif // CATCH_CONFIG_DISABLE_MATCHERS
  10470. #define REQUIRE_NOTHROW( ... ) INTERNAL_CATCH_NO_THROW( "REQUIRE_NOTHROW", Catch::ResultDisposition::Normal, __VA_ARGS__ )
  10471. #define CHECK( ... ) INTERNAL_CATCH_TEST( "CHECK", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  10472. #define CHECK_FALSE( ... ) INTERNAL_CATCH_TEST( "CHECK_FALSE", Catch::ResultDisposition::ContinueOnFailure | Catch::ResultDisposition::FalseTest, __VA_ARGS__ )
  10473. #define CHECKED_IF( ... ) INTERNAL_CATCH_IF( "CHECKED_IF", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  10474. #define CHECKED_ELSE( ... ) INTERNAL_CATCH_ELSE( "CHECKED_ELSE", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  10475. #define CHECK_NOFAIL( ... ) INTERNAL_CATCH_TEST( "CHECK_NOFAIL", Catch::ResultDisposition::ContinueOnFailure | Catch::ResultDisposition::SuppressFail, __VA_ARGS__ )
  10476. #define CHECK_THROWS( ... ) INTERNAL_CATCH_THROWS( "CHECK_THROWS", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  10477. #define CHECK_THROWS_AS( expr, exceptionType ) INTERNAL_CATCH_THROWS_AS( "CHECK_THROWS_AS", exceptionType, Catch::ResultDisposition::ContinueOnFailure, expr )
  10478. #define CHECK_THROWS_WITH( expr, matcher ) INTERNAL_CATCH_THROWS_STR_MATCHES( "CHECK_THROWS_WITH", Catch::ResultDisposition::ContinueOnFailure, matcher, expr )
  10479. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  10480. #define CHECK_THROWS_MATCHES( expr, exceptionType, matcher ) INTERNAL_CATCH_THROWS_MATCHES( "CHECK_THROWS_MATCHES", exceptionType, Catch::ResultDisposition::ContinueOnFailure, matcher, expr )
  10481. #endif // CATCH_CONFIG_DISABLE_MATCHERS
  10482. #define CHECK_NOTHROW( ... ) INTERNAL_CATCH_NO_THROW( "CHECK_NOTHROW", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  10483. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  10484. #define CHECK_THAT( arg, matcher ) INTERNAL_CHECK_THAT( "CHECK_THAT", matcher, Catch::ResultDisposition::ContinueOnFailure, arg )
  10485. #define REQUIRE_THAT( arg, matcher ) INTERNAL_CHECK_THAT( "REQUIRE_THAT", matcher, Catch::ResultDisposition::Normal, arg )
  10486. #endif // CATCH_CONFIG_DISABLE_MATCHERS
  10487. #define INFO( msg ) INTERNAL_CATCH_INFO( "INFO", msg )
  10488. #define WARN( msg ) INTERNAL_CATCH_MSG( "WARN", Catch::ResultWas::Warning, Catch::ResultDisposition::ContinueOnFailure, msg )
  10489. #define CAPTURE( msg ) INTERNAL_CATCH_INFO( "CAPTURE", #msg " := " << ::Catch::Detail::stringify(msg) )
  10490. #define TEST_CASE( ... ) INTERNAL_CATCH_TESTCASE( __VA_ARGS__ )
  10491. #define TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEST_CASE_METHOD( className, __VA_ARGS__ )
  10492. #define METHOD_AS_TEST_CASE( method, ... ) INTERNAL_CATCH_METHOD_AS_TEST_CASE( method, __VA_ARGS__ )
  10493. #define REGISTER_TEST_CASE( Function, ... ) INTERNAL_CATCH_REGISTER_TESTCASE( Function, __VA_ARGS__ )
  10494. #define SECTION( ... ) INTERNAL_CATCH_SECTION( __VA_ARGS__ )
  10495. #define FAIL( ... ) INTERNAL_CATCH_MSG( "FAIL", Catch::ResultWas::ExplicitFailure, Catch::ResultDisposition::Normal, __VA_ARGS__ )
  10496. #define FAIL_CHECK( ... ) INTERNAL_CATCH_MSG( "FAIL_CHECK", Catch::ResultWas::ExplicitFailure, Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  10497. #define SUCCEED( ... ) INTERNAL_CATCH_MSG( "SUCCEED", Catch::ResultWas::Ok, Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  10498. #define ANON_TEST_CASE() INTERNAL_CATCH_TESTCASE()
  10499. #endif
  10500. #define CATCH_TRANSLATE_EXCEPTION( signature ) INTERNAL_CATCH_TRANSLATE_EXCEPTION( signature )
  10501. // "BDD-style" convenience wrappers
  10502. #define SCENARIO( ... ) TEST_CASE( "Scenario: " __VA_ARGS__ )
  10503. #define SCENARIO_METHOD( className, ... ) INTERNAL_CATCH_TEST_CASE_METHOD( className, "Scenario: " __VA_ARGS__ )
  10504. #define GIVEN( desc ) SECTION( std::string(" Given: ") + desc )
  10505. #define WHEN( desc ) SECTION( std::string(" When: ") + desc )
  10506. #define AND_WHEN( desc ) SECTION( std::string("And when: ") + desc )
  10507. #define THEN( desc ) SECTION( std::string(" Then: ") + desc )
  10508. #define AND_THEN( desc ) SECTION( std::string(" And: ") + desc )
  10509. using Catch::Detail::Approx;
  10510. #else
  10511. //////
  10512. // If this config identifier is defined then all CATCH macros are prefixed with CATCH_
  10513. #ifdef CATCH_CONFIG_PREFIX_ALL
  10514. #define CATCH_REQUIRE( ... ) (void)(0)
  10515. #define CATCH_REQUIRE_FALSE( ... ) (void)(0)
  10516. #define CATCH_REQUIRE_THROWS( ... ) (void)(0)
  10517. #define CATCH_REQUIRE_THROWS_AS( expr, exceptionType ) (void)(0)
  10518. #define CATCH_REQUIRE_THROWS_WITH( expr, matcher ) (void)(0)
  10519. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  10520. #define CATCH_REQUIRE_THROWS_MATCHES( expr, exceptionType, matcher ) (void)(0)
  10521. #endif// CATCH_CONFIG_DISABLE_MATCHERS
  10522. #define CATCH_REQUIRE_NOTHROW( ... ) (void)(0)
  10523. #define CATCH_CHECK( ... ) (void)(0)
  10524. #define CATCH_CHECK_FALSE( ... ) (void)(0)
  10525. #define CATCH_CHECKED_IF( ... ) if (__VA_ARGS__)
  10526. #define CATCH_CHECKED_ELSE( ... ) if (!(__VA_ARGS__))
  10527. #define CATCH_CHECK_NOFAIL( ... ) (void)(0)
  10528. #define CATCH_CHECK_THROWS( ... ) (void)(0)
  10529. #define CATCH_CHECK_THROWS_AS( expr, exceptionType ) (void)(0)
  10530. #define CATCH_CHECK_THROWS_WITH( expr, matcher ) (void)(0)
  10531. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  10532. #define CATCH_CHECK_THROWS_MATCHES( expr, exceptionType, matcher ) (void)(0)
  10533. #endif // CATCH_CONFIG_DISABLE_MATCHERS
  10534. #define CATCH_CHECK_NOTHROW( ... ) (void)(0)
  10535. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  10536. #define CATCH_CHECK_THAT( arg, matcher ) (void)(0)
  10537. #define CATCH_REQUIRE_THAT( arg, matcher ) (void)(0)
  10538. #endif // CATCH_CONFIG_DISABLE_MATCHERS
  10539. #define CATCH_INFO( msg ) (void)(0)
  10540. #define CATCH_WARN( msg ) (void)(0)
  10541. #define CATCH_CAPTURE( msg ) (void)(0)
  10542. #define CATCH_TEST_CASE( ... ) INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ))
  10543. #define CATCH_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ))
  10544. #define CATCH_METHOD_AS_TEST_CASE( method, ... )
  10545. #define CATCH_REGISTER_TEST_CASE( Function, ... ) (void)(0)
  10546. #define CATCH_SECTION( ... )
  10547. #define CATCH_FAIL( ... ) (void)(0)
  10548. #define CATCH_FAIL_CHECK( ... ) (void)(0)
  10549. #define CATCH_SUCCEED( ... ) (void)(0)
  10550. #define CATCH_ANON_TEST_CASE() INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ))
  10551. // "BDD-style" convenience wrappers
  10552. #define CATCH_SCENARIO( ... ) INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ))
  10553. #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 )
  10554. #define CATCH_GIVEN( desc )
  10555. #define CATCH_WHEN( desc )
  10556. #define CATCH_AND_WHEN( desc )
  10557. #define CATCH_THEN( desc )
  10558. #define CATCH_AND_THEN( desc )
  10559. // If CATCH_CONFIG_PREFIX_ALL is not defined then the CATCH_ prefix is not required
  10560. #else
  10561. #define REQUIRE( ... ) (void)(0)
  10562. #define REQUIRE_FALSE( ... ) (void)(0)
  10563. #define REQUIRE_THROWS( ... ) (void)(0)
  10564. #define REQUIRE_THROWS_AS( expr, exceptionType ) (void)(0)
  10565. #define REQUIRE_THROWS_WITH( expr, matcher ) (void)(0)
  10566. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  10567. #define REQUIRE_THROWS_MATCHES( expr, exceptionType, matcher ) (void)(0)
  10568. #endif // CATCH_CONFIG_DISABLE_MATCHERS
  10569. #define REQUIRE_NOTHROW( ... ) (void)(0)
  10570. #define CHECK( ... ) (void)(0)
  10571. #define CHECK_FALSE( ... ) (void)(0)
  10572. #define CHECKED_IF( ... ) if (__VA_ARGS__)
  10573. #define CHECKED_ELSE( ... ) if (!(__VA_ARGS__))
  10574. #define CHECK_NOFAIL( ... ) (void)(0)
  10575. #define CHECK_THROWS( ... ) (void)(0)
  10576. #define CHECK_THROWS_AS( expr, exceptionType ) (void)(0)
  10577. #define CHECK_THROWS_WITH( expr, matcher ) (void)(0)
  10578. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  10579. #define CHECK_THROWS_MATCHES( expr, exceptionType, matcher ) (void)(0)
  10580. #endif // CATCH_CONFIG_DISABLE_MATCHERS
  10581. #define CHECK_NOTHROW( ... ) (void)(0)
  10582. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  10583. #define CHECK_THAT( arg, matcher ) (void)(0)
  10584. #define REQUIRE_THAT( arg, matcher ) (void)(0)
  10585. #endif // CATCH_CONFIG_DISABLE_MATCHERS
  10586. #define INFO( msg ) (void)(0)
  10587. #define WARN( msg ) (void)(0)
  10588. #define CAPTURE( msg ) (void)(0)
  10589. #define TEST_CASE( ... ) INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ))
  10590. #define TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ))
  10591. #define METHOD_AS_TEST_CASE( method, ... )
  10592. #define REGISTER_TEST_CASE( Function, ... ) (void)(0)
  10593. #define SECTION( ... )
  10594. #define FAIL( ... ) (void)(0)
  10595. #define FAIL_CHECK( ... ) (void)(0)
  10596. #define SUCCEED( ... ) (void)(0)
  10597. #define ANON_TEST_CASE() INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ))
  10598. #endif
  10599. #define CATCH_TRANSLATE_EXCEPTION( signature ) INTERNAL_CATCH_TRANSLATE_EXCEPTION_NO_REG( INTERNAL_CATCH_UNIQUE_NAME( catch_internal_ExceptionTranslator ), signature )
  10600. // "BDD-style" convenience wrappers
  10601. #define SCENARIO( ... ) INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ) )
  10602. #define SCENARIO_METHOD( className, ... ) INTERNAL_CATCH_TESTCASE_METHOD_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ), className )
  10603. #define GIVEN( desc )
  10604. #define WHEN( desc )
  10605. #define AND_WHEN( desc )
  10606. #define THEN( desc )
  10607. #define AND_THEN( desc )
  10608. using Catch::Detail::Approx;
  10609. #endif
  10610. #endif // ! CATCH_CONFIG_IMPL_ONLY
  10611. // start catch_reenable_warnings.h
  10612. #ifdef __clang__
  10613. # ifdef __ICC // icpc defines the __clang__ macro
  10614. # pragma warning(pop)
  10615. # else
  10616. # pragma clang diagnostic pop
  10617. # endif
  10618. #elif defined __GNUC__
  10619. # pragma GCC diagnostic pop
  10620. #endif
  10621. // end catch_reenable_warnings.h
  10622. // end catch.hpp
  10623. #endif // TWOBLUECUBES_SINGLE_INCLUDE_CATCH_HPP_INCLUDED