Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.

12750 lines
424KB

  1. /*
  2. * Catch v2.1.1
  3. * Generated: 2018-01-26 16:04:07.190063
  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. #ifdef __clang__
  15. # pragma clang system_header
  16. #elif defined __GNUC__
  17. # pragma GCC system_header
  18. #endif
  19. // start catch_suppress_warnings.h
  20. #ifdef __clang__
  21. # ifdef __ICC // icpc defines the __clang__ macro
  22. # pragma warning(push)
  23. # pragma warning(disable: 161 1682)
  24. # else // __ICC
  25. # pragma clang diagnostic ignored "-Wunused-variable"
  26. # pragma clang diagnostic push
  27. # pragma clang diagnostic ignored "-Wpadded"
  28. # pragma clang diagnostic ignored "-Wswitch-enum"
  29. # pragma clang diagnostic ignored "-Wcovered-switch-default"
  30. # endif
  31. #elif defined __GNUC__
  32. # pragma GCC diagnostic ignored "-Wunused-variable"
  33. # pragma GCC diagnostic ignored "-Wparentheses"
  34. # pragma GCC diagnostic push
  35. # pragma GCC diagnostic ignored "-Wpadded"
  36. #endif
  37. // end catch_suppress_warnings.h
  38. #if defined(CATCH_CONFIG_MAIN) || defined(CATCH_CONFIG_RUNNER)
  39. # define CATCH_IMPL
  40. # define CATCH_CONFIG_ALL_PARTS
  41. #endif
  42. // In the impl file, we want to have access to all parts of the headers
  43. // Can also be used to sanely support PCHs
  44. #if defined(CATCH_CONFIG_ALL_PARTS)
  45. # define CATCH_CONFIG_EXTERNAL_INTERFACES
  46. # if defined(CATCH_CONFIG_DISABLE_MATCHERS)
  47. # undef CATCH_CONFIG_DISABLE_MATCHERS
  48. # endif
  49. # define CATCH_CONFIG_ENABLE_CHRONO_STRINGMAKER
  50. #endif
  51. #if !defined(CATCH_CONFIG_IMPL_ONLY)
  52. // start catch_platform.h
  53. #ifdef __APPLE__
  54. # include <TargetConditionals.h>
  55. # if TARGET_OS_OSX == 1
  56. # define CATCH_PLATFORM_MAC
  57. # elif TARGET_OS_IPHONE == 1
  58. # define CATCH_PLATFORM_IPHONE
  59. # endif
  60. #elif defined(linux) || defined(__linux) || defined(__linux__)
  61. # define CATCH_PLATFORM_LINUX
  62. #elif defined(WIN32) || defined(__WIN32__) || defined(_WIN32) || defined(_MSC_VER)
  63. # define CATCH_PLATFORM_WINDOWS
  64. #endif
  65. // end catch_platform.h
  66. #ifdef CATCH_IMPL
  67. # ifndef CLARA_CONFIG_MAIN
  68. # define CLARA_CONFIG_MAIN_NOT_DEFINED
  69. # define CLARA_CONFIG_MAIN
  70. # endif
  71. #endif
  72. // start catch_user_interfaces.h
  73. namespace Catch {
  74. unsigned int rngSeed();
  75. }
  76. // end catch_user_interfaces.h
  77. // start catch_tag_alias_autoregistrar.h
  78. // start catch_common.h
  79. // start catch_compiler_capabilities.h
  80. // Detect a number of compiler features - by compiler
  81. // The following features are defined:
  82. //
  83. // CATCH_CONFIG_COUNTER : is the __COUNTER__ macro supported?
  84. // CATCH_CONFIG_WINDOWS_SEH : is Windows SEH supported?
  85. // CATCH_CONFIG_POSIX_SIGNALS : are POSIX signals supported?
  86. // ****************
  87. // Note to maintainers: if new toggles are added please document them
  88. // in configuration.md, too
  89. // ****************
  90. // In general each macro has a _NO_<feature name> form
  91. // (e.g. CATCH_CONFIG_NO_POSIX_SIGNALS) which disables the feature.
  92. // Many features, at point of detection, define an _INTERNAL_ macro, so they
  93. // can be combined, en-mass, with the _NO_ forms later.
  94. #ifdef __cplusplus
  95. # if __cplusplus >= 201402L
  96. # define CATCH_CPP14_OR_GREATER
  97. # endif
  98. #endif
  99. #ifdef __clang__
  100. # define CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
  101. _Pragma( "clang diagnostic push" ) \
  102. _Pragma( "clang diagnostic ignored \"-Wexit-time-destructors\"" ) \
  103. _Pragma( "clang diagnostic ignored \"-Wglobal-constructors\"")
  104. # define CATCH_INTERNAL_UNSUPPRESS_GLOBALS_WARNINGS \
  105. _Pragma( "clang diagnostic pop" )
  106. # define CATCH_INTERNAL_SUPPRESS_PARENTHESES_WARNINGS \
  107. _Pragma( "clang diagnostic push" ) \
  108. _Pragma( "clang diagnostic ignored \"-Wparentheses\"" )
  109. # define CATCH_INTERNAL_UNSUPPRESS_PARENTHESES_WARNINGS \
  110. _Pragma( "clang diagnostic pop" )
  111. #endif // __clang__
  112. ////////////////////////////////////////////////////////////////////////////////
  113. // We know some environments not to support full POSIX signals
  114. #if defined(__CYGWIN__) || defined(__QNX__)
  115. # if !defined(CATCH_CONFIG_POSIX_SIGNALS)
  116. # define CATCH_INTERNAL_CONFIG_NO_POSIX_SIGNALS
  117. # endif
  118. #endif
  119. #ifdef __OS400__
  120. # define CATCH_INTERNAL_CONFIG_NO_POSIX_SIGNALS
  121. # define CATCH_CONFIG_COLOUR_NONE
  122. #endif
  123. ////////////////////////////////////////////////////////////////////////////////
  124. // Cygwin
  125. #ifdef __CYGWIN__
  126. // Required for some versions of Cygwin to declare gettimeofday
  127. // see: http://stackoverflow.com/questions/36901803/gettimeofday-not-declared-in-this-scope-cygwin
  128. # define _BSD_SOURCE
  129. #endif // __CYGWIN__
  130. ////////////////////////////////////////////////////////////////////////////////
  131. // Visual C++
  132. #ifdef _MSC_VER
  133. // Universal Windows platform does not support SEH
  134. // Or console colours (or console at all...)
  135. # if defined(WINAPI_FAMILY) && (WINAPI_FAMILY == WINAPI_FAMILY_APP)
  136. # define CATCH_CONFIG_COLOUR_NONE
  137. # else
  138. # define CATCH_INTERNAL_CONFIG_WINDOWS_SEH
  139. # endif
  140. #endif // _MSC_VER
  141. ////////////////////////////////////////////////////////////////////////////////
  142. // Use of __COUNTER__ is suppressed during code analysis in
  143. // CLion/AppCode 2017.2.x and former, because __COUNTER__ is not properly
  144. // handled by it.
  145. // Otherwise all supported compilers support COUNTER macro,
  146. // but user still might want to turn it off
  147. #if ( !defined(__JETBRAINS_IDE__) || __JETBRAINS_IDE__ >= 20170300L )
  148. #define CATCH_INTERNAL_CONFIG_COUNTER
  149. #endif
  150. #if defined(CATCH_INTERNAL_CONFIG_COUNTER) && !defined(CATCH_CONFIG_NO_COUNTER) && !defined(CATCH_CONFIG_COUNTER)
  151. # define CATCH_CONFIG_COUNTER
  152. #endif
  153. #if defined(CATCH_INTERNAL_CONFIG_WINDOWS_SEH) && !defined(CATCH_CONFIG_NO_WINDOWS_SEH) && !defined(CATCH_CONFIG_WINDOWS_SEH)
  154. # define CATCH_CONFIG_WINDOWS_SEH
  155. #endif
  156. // This is set by default, because we assume that unix compilers are posix-signal-compatible by default.
  157. #if !defined(CATCH_INTERNAL_CONFIG_NO_POSIX_SIGNALS) && !defined(CATCH_CONFIG_NO_POSIX_SIGNALS) && !defined(CATCH_CONFIG_POSIX_SIGNALS)
  158. # define CATCH_CONFIG_POSIX_SIGNALS
  159. #endif
  160. #if !defined(CATCH_INTERNAL_SUPPRESS_PARENTHESES_WARNINGS)
  161. # define CATCH_INTERNAL_SUPPRESS_PARENTHESES_WARNINGS
  162. # define CATCH_INTERNAL_UNSUPPRESS_PARENTHESES_WARNINGS
  163. #endif
  164. #if !defined(CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS)
  165. # define CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS
  166. # define CATCH_INTERNAL_UNSUPPRESS_GLOBALS_WARNINGS
  167. #endif
  168. // end catch_compiler_capabilities.h
  169. #define INTERNAL_CATCH_UNIQUE_NAME_LINE2( name, line ) name##line
  170. #define INTERNAL_CATCH_UNIQUE_NAME_LINE( name, line ) INTERNAL_CATCH_UNIQUE_NAME_LINE2( name, line )
  171. #ifdef CATCH_CONFIG_COUNTER
  172. # define INTERNAL_CATCH_UNIQUE_NAME( name ) INTERNAL_CATCH_UNIQUE_NAME_LINE( name, __COUNTER__ )
  173. #else
  174. # define INTERNAL_CATCH_UNIQUE_NAME( name ) INTERNAL_CATCH_UNIQUE_NAME_LINE( name, __LINE__ )
  175. #endif
  176. #include <iosfwd>
  177. #include <string>
  178. #include <cstdint>
  179. namespace Catch {
  180. struct CaseSensitive { enum Choice {
  181. Yes,
  182. No
  183. }; };
  184. class NonCopyable {
  185. NonCopyable( NonCopyable const& ) = delete;
  186. NonCopyable( NonCopyable && ) = delete;
  187. NonCopyable& operator = ( NonCopyable const& ) = delete;
  188. NonCopyable& operator = ( NonCopyable && ) = delete;
  189. protected:
  190. NonCopyable();
  191. virtual ~NonCopyable();
  192. };
  193. struct SourceLineInfo {
  194. SourceLineInfo() = delete;
  195. SourceLineInfo( char const* _file, std::size_t _line ) noexcept
  196. : file( _file ),
  197. line( _line )
  198. {}
  199. SourceLineInfo( SourceLineInfo const& other ) = default;
  200. SourceLineInfo( SourceLineInfo && ) = default;
  201. SourceLineInfo& operator = ( SourceLineInfo const& ) = default;
  202. SourceLineInfo& operator = ( SourceLineInfo && ) = default;
  203. bool empty() const noexcept;
  204. bool operator == ( SourceLineInfo const& other ) const noexcept;
  205. bool operator < ( SourceLineInfo const& other ) const noexcept;
  206. char const* file;
  207. std::size_t line;
  208. };
  209. std::ostream& operator << ( std::ostream& os, SourceLineInfo const& info );
  210. // Use this in variadic streaming macros to allow
  211. // >> +StreamEndStop
  212. // as well as
  213. // >> stuff +StreamEndStop
  214. struct StreamEndStop {
  215. std::string operator+() const;
  216. };
  217. template<typename T>
  218. T const& operator + ( T const& value, StreamEndStop ) {
  219. return value;
  220. }
  221. }
  222. #define CATCH_INTERNAL_LINEINFO \
  223. ::Catch::SourceLineInfo( __FILE__, static_cast<std::size_t>( __LINE__ ) )
  224. // end catch_common.h
  225. namespace Catch {
  226. struct RegistrarForTagAliases {
  227. RegistrarForTagAliases( char const* alias, char const* tag, SourceLineInfo const& lineInfo );
  228. };
  229. } // end namespace Catch
  230. #define CATCH_REGISTER_TAG_ALIAS( alias, spec ) \
  231. CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
  232. namespace{ Catch::RegistrarForTagAliases INTERNAL_CATCH_UNIQUE_NAME( AutoRegisterTagAlias )( alias, spec, CATCH_INTERNAL_LINEINFO ); } \
  233. CATCH_INTERNAL_UNSUPPRESS_GLOBALS_WARNINGS
  234. // end catch_tag_alias_autoregistrar.h
  235. // start catch_test_registry.h
  236. // start catch_interfaces_testcase.h
  237. #include <vector>
  238. #include <memory>
  239. namespace Catch {
  240. class TestSpec;
  241. struct ITestInvoker {
  242. virtual void invoke () const = 0;
  243. virtual ~ITestInvoker();
  244. };
  245. using ITestCasePtr = std::shared_ptr<ITestInvoker>;
  246. class TestCase;
  247. struct IConfig;
  248. struct ITestCaseRegistry {
  249. virtual ~ITestCaseRegistry();
  250. virtual std::vector<TestCase> const& getAllTests() const = 0;
  251. virtual std::vector<TestCase> const& getAllTestsSorted( IConfig const& config ) const = 0;
  252. };
  253. bool matchTest( TestCase const& testCase, TestSpec const& testSpec, IConfig const& config );
  254. std::vector<TestCase> filterTests( std::vector<TestCase> const& testCases, TestSpec const& testSpec, IConfig const& config );
  255. std::vector<TestCase> const& getAllTestCasesSorted( IConfig const& config );
  256. }
  257. // end catch_interfaces_testcase.h
  258. // start catch_stringref.h
  259. #include <cstddef>
  260. #include <string>
  261. #include <iosfwd>
  262. namespace Catch {
  263. class StringData;
  264. /// A non-owning string class (similar to the forthcoming std::string_view)
  265. /// Note that, because a StringRef may be a substring of another string,
  266. /// it may not be null terminated. c_str() must return a null terminated
  267. /// string, however, and so the StringRef will internally take ownership
  268. /// (taking a copy), if necessary. In theory this ownership is not externally
  269. /// visible - but it does mean (substring) StringRefs should not be shared between
  270. /// threads.
  271. class StringRef {
  272. public:
  273. using size_type = std::size_t;
  274. private:
  275. friend struct StringRefTestAccess;
  276. char const* m_start;
  277. size_type m_size;
  278. char* m_data = nullptr;
  279. void takeOwnership();
  280. static constexpr char const* const s_empty = "";
  281. public: // construction/ assignment
  282. StringRef() noexcept
  283. : StringRef( s_empty, 0 )
  284. {}
  285. StringRef( StringRef const& other ) noexcept
  286. : m_start( other.m_start ),
  287. m_size( other.m_size )
  288. {}
  289. StringRef( StringRef&& other ) noexcept
  290. : m_start( other.m_start ),
  291. m_size( other.m_size ),
  292. m_data( other.m_data )
  293. {
  294. other.m_data = nullptr;
  295. }
  296. StringRef( char const* rawChars ) noexcept;
  297. StringRef( char const* rawChars, size_type size ) noexcept
  298. : m_start( rawChars ),
  299. m_size( size )
  300. {}
  301. StringRef( std::string const& stdString ) noexcept
  302. : m_start( stdString.c_str() ),
  303. m_size( stdString.size() )
  304. {}
  305. ~StringRef() noexcept {
  306. delete[] m_data;
  307. }
  308. auto operator = ( StringRef const &other ) noexcept -> StringRef& {
  309. delete[] m_data;
  310. m_data = nullptr;
  311. m_start = other.m_start;
  312. m_size = other.m_size;
  313. return *this;
  314. }
  315. operator std::string() const;
  316. void swap( StringRef& other ) noexcept;
  317. public: // operators
  318. auto operator == ( StringRef const& other ) const noexcept -> bool;
  319. auto operator != ( StringRef const& other ) const noexcept -> bool;
  320. auto operator[] ( size_type index ) const noexcept -> char;
  321. public: // named queries
  322. auto empty() const noexcept -> bool {
  323. return m_size == 0;
  324. }
  325. auto size() const noexcept -> size_type {
  326. return m_size;
  327. }
  328. auto numberOfCharacters() const noexcept -> size_type;
  329. auto c_str() const -> char const*;
  330. public: // substrings and searches
  331. auto substr( size_type start, size_type size ) const noexcept -> StringRef;
  332. private: // ownership queries - may not be consistent between calls
  333. auto isOwned() const noexcept -> bool;
  334. auto isSubstring() const noexcept -> bool;
  335. auto data() const noexcept -> char const*;
  336. };
  337. auto operator + ( StringRef const& lhs, StringRef const& rhs ) -> std::string;
  338. auto operator + ( StringRef const& lhs, char const* rhs ) -> std::string;
  339. auto operator + ( char const* lhs, StringRef const& rhs ) -> std::string;
  340. auto operator << ( std::ostream& os, StringRef const& sr ) -> std::ostream&;
  341. inline auto operator "" _sr( char const* rawChars, std::size_t size ) noexcept -> StringRef {
  342. return StringRef( rawChars, size );
  343. }
  344. } // namespace Catch
  345. // end catch_stringref.h
  346. namespace Catch {
  347. template<typename C>
  348. class TestInvokerAsMethod : public ITestInvoker {
  349. void (C::*m_testAsMethod)();
  350. public:
  351. TestInvokerAsMethod( void (C::*testAsMethod)() ) noexcept : m_testAsMethod( testAsMethod ) {}
  352. void invoke() const override {
  353. C obj;
  354. (obj.*m_testAsMethod)();
  355. }
  356. };
  357. auto makeTestInvoker( void(*testAsFunction)() ) noexcept -> ITestInvoker*;
  358. template<typename C>
  359. auto makeTestInvoker( void (C::*testAsMethod)() ) noexcept -> ITestInvoker* {
  360. return new(std::nothrow) TestInvokerAsMethod<C>( testAsMethod );
  361. }
  362. struct NameAndTags {
  363. NameAndTags( StringRef name_ = StringRef(), StringRef tags_ = StringRef() ) noexcept;
  364. StringRef name;
  365. StringRef tags;
  366. };
  367. struct AutoReg : NonCopyable {
  368. AutoReg( ITestInvoker* invoker, SourceLineInfo const& lineInfo, StringRef classOrMethod, NameAndTags const& nameAndTags ) noexcept;
  369. ~AutoReg();
  370. };
  371. } // end namespace Catch
  372. #if defined(CATCH_CONFIG_DISABLE)
  373. #define INTERNAL_CATCH_TESTCASE_NO_REGISTRATION( TestName, ... ) \
  374. static void TestName()
  375. #define INTERNAL_CATCH_TESTCASE_METHOD_NO_REGISTRATION( TestName, ClassName, ... ) \
  376. namespace{ \
  377. struct TestName : ClassName { \
  378. void test(); \
  379. }; \
  380. } \
  381. void TestName::test()
  382. #endif
  383. ///////////////////////////////////////////////////////////////////////////////
  384. #define INTERNAL_CATCH_TESTCASE2( TestName, ... ) \
  385. static void TestName(); \
  386. CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
  387. namespace{ Catch::AutoReg INTERNAL_CATCH_UNIQUE_NAME( autoRegistrar )( Catch::makeTestInvoker( &TestName ), CATCH_INTERNAL_LINEINFO, "", Catch::NameAndTags{ __VA_ARGS__ } ); } /* NOLINT */ \
  388. CATCH_INTERNAL_UNSUPPRESS_GLOBALS_WARNINGS \
  389. static void TestName()
  390. #define INTERNAL_CATCH_TESTCASE( ... ) \
  391. INTERNAL_CATCH_TESTCASE2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ), __VA_ARGS__ )
  392. ///////////////////////////////////////////////////////////////////////////////
  393. #define INTERNAL_CATCH_METHOD_AS_TEST_CASE( QualifiedMethod, ... ) \
  394. CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
  395. namespace{ Catch::AutoReg INTERNAL_CATCH_UNIQUE_NAME( autoRegistrar )( Catch::makeTestInvoker( &QualifiedMethod ), CATCH_INTERNAL_LINEINFO, "&" #QualifiedMethod, Catch::NameAndTags{ __VA_ARGS__ } ); } /* NOLINT */ \
  396. CATCH_INTERNAL_UNSUPPRESS_GLOBALS_WARNINGS
  397. ///////////////////////////////////////////////////////////////////////////////
  398. #define INTERNAL_CATCH_TEST_CASE_METHOD2( TestName, ClassName, ... )\
  399. CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
  400. namespace{ \
  401. struct TestName : ClassName{ \
  402. void test(); \
  403. }; \
  404. Catch::AutoReg INTERNAL_CATCH_UNIQUE_NAME( autoRegistrar ) ( Catch::makeTestInvoker( &TestName::test ), CATCH_INTERNAL_LINEINFO, #ClassName, Catch::NameAndTags{ __VA_ARGS__ } ); /* NOLINT */ \
  405. } \
  406. CATCH_INTERNAL_UNSUPPRESS_GLOBALS_WARNINGS \
  407. void TestName::test()
  408. #define INTERNAL_CATCH_TEST_CASE_METHOD( ClassName, ... ) \
  409. INTERNAL_CATCH_TEST_CASE_METHOD2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ), ClassName, __VA_ARGS__ )
  410. ///////////////////////////////////////////////////////////////////////////////
  411. #define INTERNAL_CATCH_REGISTER_TESTCASE( Function, ... ) \
  412. CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
  413. Catch::AutoReg INTERNAL_CATCH_UNIQUE_NAME( autoRegistrar )( Catch::makeTestInvoker( Function ), CATCH_INTERNAL_LINEINFO, "", Catch::NameAndTags{ __VA_ARGS__ } ); /* NOLINT */ \
  414. CATCH_INTERNAL_UNSUPPRESS_GLOBALS_WARNINGS
  415. // end catch_test_registry.h
  416. // start catch_capture.hpp
  417. // start catch_assertionhandler.h
  418. // start catch_assertioninfo.h
  419. // start catch_result_type.h
  420. namespace Catch {
  421. // ResultWas::OfType enum
  422. struct ResultWas { enum OfType {
  423. Unknown = -1,
  424. Ok = 0,
  425. Info = 1,
  426. Warning = 2,
  427. FailureBit = 0x10,
  428. ExpressionFailed = FailureBit | 1,
  429. ExplicitFailure = FailureBit | 2,
  430. Exception = 0x100 | FailureBit,
  431. ThrewException = Exception | 1,
  432. DidntThrowException = Exception | 2,
  433. FatalErrorCondition = 0x200 | FailureBit
  434. }; };
  435. bool isOk( ResultWas::OfType resultType );
  436. bool isJustInfo( int flags );
  437. // ResultDisposition::Flags enum
  438. struct ResultDisposition { enum Flags {
  439. Normal = 0x01,
  440. ContinueOnFailure = 0x02, // Failures fail test, but execution continues
  441. FalseTest = 0x04, // Prefix expression with !
  442. SuppressFail = 0x08 // Failures are reported but do not fail the test
  443. }; };
  444. ResultDisposition::Flags operator | ( ResultDisposition::Flags lhs, ResultDisposition::Flags rhs );
  445. bool shouldContinueOnFailure( int flags );
  446. inline bool isFalseTest( int flags ) { return ( flags & ResultDisposition::FalseTest ) != 0; }
  447. bool shouldSuppressFailure( int flags );
  448. } // end namespace Catch
  449. // end catch_result_type.h
  450. namespace Catch {
  451. struct AssertionInfo
  452. {
  453. StringRef macroName;
  454. SourceLineInfo lineInfo;
  455. StringRef capturedExpression;
  456. ResultDisposition::Flags resultDisposition;
  457. // We want to delete this constructor but a compiler bug in 4.8 means
  458. // the struct is then treated as non-aggregate
  459. //AssertionInfo() = delete;
  460. };
  461. } // end namespace Catch
  462. // end catch_assertioninfo.h
  463. // start catch_decomposer.h
  464. // start catch_tostring.h
  465. #include <vector>
  466. #include <cstddef>
  467. #include <type_traits>
  468. #include <string>
  469. // start catch_stream.h
  470. #include <iosfwd>
  471. #include <cstddef>
  472. #include <ostream>
  473. namespace Catch {
  474. std::ostream& cout();
  475. std::ostream& cerr();
  476. std::ostream& clog();
  477. class StringRef;
  478. struct IStream {
  479. virtual ~IStream();
  480. virtual std::ostream& stream() const = 0;
  481. };
  482. auto makeStream( StringRef const &filename ) -> IStream const*;
  483. class ReusableStringStream {
  484. std::size_t m_index;
  485. std::ostream* m_oss;
  486. public:
  487. ReusableStringStream();
  488. ~ReusableStringStream();
  489. auto str() const -> std::string;
  490. template<typename T>
  491. auto operator << ( T const& value ) -> ReusableStringStream& {
  492. *m_oss << value;
  493. return *this;
  494. }
  495. auto get() -> std::ostream& { return *m_oss; }
  496. static void cleanup();
  497. };
  498. }
  499. // end catch_stream.h
  500. #ifdef __OBJC__
  501. // start catch_objc_arc.hpp
  502. #import <Foundation/Foundation.h>
  503. #ifdef __has_feature
  504. #define CATCH_ARC_ENABLED __has_feature(objc_arc)
  505. #else
  506. #define CATCH_ARC_ENABLED 0
  507. #endif
  508. void arcSafeRelease( NSObject* obj );
  509. id performOptionalSelector( id obj, SEL sel );
  510. #if !CATCH_ARC_ENABLED
  511. inline void arcSafeRelease( NSObject* obj ) {
  512. [obj release];
  513. }
  514. inline id performOptionalSelector( id obj, SEL sel ) {
  515. if( [obj respondsToSelector: sel] )
  516. return [obj performSelector: sel];
  517. return nil;
  518. }
  519. #define CATCH_UNSAFE_UNRETAINED
  520. #define CATCH_ARC_STRONG
  521. #else
  522. inline void arcSafeRelease( NSObject* ){}
  523. inline id performOptionalSelector( id obj, SEL sel ) {
  524. #ifdef __clang__
  525. #pragma clang diagnostic push
  526. #pragma clang diagnostic ignored "-Warc-performSelector-leaks"
  527. #endif
  528. if( [obj respondsToSelector: sel] )
  529. return [obj performSelector: sel];
  530. #ifdef __clang__
  531. #pragma clang diagnostic pop
  532. #endif
  533. return nil;
  534. }
  535. #define CATCH_UNSAFE_UNRETAINED __unsafe_unretained
  536. #define CATCH_ARC_STRONG __strong
  537. #endif
  538. // end catch_objc_arc.hpp
  539. #endif
  540. #ifdef _MSC_VER
  541. #pragma warning(push)
  542. #pragma warning(disable:4180) // We attempt to stream a function (address) by const&, which MSVC complains about but is harmless
  543. #endif
  544. // We need a dummy global operator<< so we can bring it into Catch namespace later
  545. struct Catch_global_namespace_dummy {};
  546. std::ostream& operator<<(std::ostream&, Catch_global_namespace_dummy);
  547. namespace Catch {
  548. // Bring in operator<< from global namespace into Catch namespace
  549. using ::operator<<;
  550. namespace Detail {
  551. extern const std::string unprintableString;
  552. std::string rawMemoryToString( const void *object, std::size_t size );
  553. template<typename T>
  554. std::string rawMemoryToString( const T& object ) {
  555. return rawMemoryToString( &object, sizeof(object) );
  556. }
  557. template<typename T>
  558. class IsStreamInsertable {
  559. template<typename SS, typename TT>
  560. static auto test(int)
  561. -> decltype(std::declval<SS&>() << std::declval<TT>(), std::true_type());
  562. template<typename, typename>
  563. static auto test(...)->std::false_type;
  564. public:
  565. static const bool value = decltype(test<std::ostream, const T&>(0))::value;
  566. };
  567. template<typename E>
  568. std::string convertUnknownEnumToString( E e );
  569. template<typename T>
  570. typename std::enable_if<!std::is_enum<T>::value, std::string>::type convertUnstreamable( T const& ) {
  571. return Detail::unprintableString;
  572. };
  573. template<typename T>
  574. typename std::enable_if<std::is_enum<T>::value, std::string>::type convertUnstreamable( T const& value ) {
  575. return convertUnknownEnumToString( value );
  576. };
  577. } // namespace Detail
  578. // If we decide for C++14, change these to enable_if_ts
  579. template <typename T, typename = void>
  580. struct StringMaker {
  581. template <typename Fake = T>
  582. static
  583. typename std::enable_if<::Catch::Detail::IsStreamInsertable<Fake>::value, std::string>::type
  584. convert(const Fake& value) {
  585. ReusableStringStream rss;
  586. rss << value;
  587. return rss.str();
  588. }
  589. template <typename Fake = T>
  590. static
  591. typename std::enable_if<!::Catch::Detail::IsStreamInsertable<Fake>::value, std::string>::type
  592. convert( const Fake& value ) {
  593. return Detail::convertUnstreamable( value );
  594. }
  595. };
  596. namespace Detail {
  597. // This function dispatches all stringification requests inside of Catch.
  598. // Should be preferably called fully qualified, like ::Catch::Detail::stringify
  599. template <typename T>
  600. std::string stringify(const T& e) {
  601. return ::Catch::StringMaker<typename std::remove_cv<typename std::remove_reference<T>::type>::type>::convert(e);
  602. }
  603. template<typename E>
  604. std::string convertUnknownEnumToString( E e ) {
  605. return ::Catch::Detail::stringify(static_cast<typename std::underlying_type<E>::type>(e));
  606. }
  607. } // namespace Detail
  608. // Some predefined specializations
  609. template<>
  610. struct StringMaker<std::string> {
  611. static std::string convert(const std::string& str);
  612. };
  613. template<>
  614. struct StringMaker<std::wstring> {
  615. static std::string convert(const std::wstring& wstr);
  616. };
  617. template<>
  618. struct StringMaker<char const *> {
  619. static std::string convert(char const * str);
  620. };
  621. template<>
  622. struct StringMaker<char *> {
  623. static std::string convert(char * str);
  624. };
  625. template<>
  626. struct StringMaker<wchar_t const *> {
  627. static std::string convert(wchar_t const * str);
  628. };
  629. template<>
  630. struct StringMaker<wchar_t *> {
  631. static std::string convert(wchar_t * str);
  632. };
  633. template<int SZ>
  634. struct StringMaker<char[SZ]> {
  635. static std::string convert(const char* str) {
  636. return ::Catch::Detail::stringify(std::string{ str });
  637. }
  638. };
  639. template<int SZ>
  640. struct StringMaker<signed char[SZ]> {
  641. static std::string convert(const char* str) {
  642. return ::Catch::Detail::stringify(std::string{ str });
  643. }
  644. };
  645. template<int SZ>
  646. struct StringMaker<unsigned char[SZ]> {
  647. static std::string convert(const char* str) {
  648. return ::Catch::Detail::stringify(std::string{ str });
  649. }
  650. };
  651. template<>
  652. struct StringMaker<int> {
  653. static std::string convert(int value);
  654. };
  655. template<>
  656. struct StringMaker<long> {
  657. static std::string convert(long value);
  658. };
  659. template<>
  660. struct StringMaker<long long> {
  661. static std::string convert(long long value);
  662. };
  663. template<>
  664. struct StringMaker<unsigned int> {
  665. static std::string convert(unsigned int value);
  666. };
  667. template<>
  668. struct StringMaker<unsigned long> {
  669. static std::string convert(unsigned long value);
  670. };
  671. template<>
  672. struct StringMaker<unsigned long long> {
  673. static std::string convert(unsigned long long value);
  674. };
  675. template<>
  676. struct StringMaker<bool> {
  677. static std::string convert(bool b);
  678. };
  679. template<>
  680. struct StringMaker<char> {
  681. static std::string convert(char c);
  682. };
  683. template<>
  684. struct StringMaker<signed char> {
  685. static std::string convert(signed char c);
  686. };
  687. template<>
  688. struct StringMaker<unsigned char> {
  689. static std::string convert(unsigned char c);
  690. };
  691. template<>
  692. struct StringMaker<std::nullptr_t> {
  693. static std::string convert(std::nullptr_t);
  694. };
  695. template<>
  696. struct StringMaker<float> {
  697. static std::string convert(float value);
  698. };
  699. template<>
  700. struct StringMaker<double> {
  701. static std::string convert(double value);
  702. };
  703. template <typename T>
  704. struct StringMaker<T*> {
  705. template <typename U>
  706. static std::string convert(U* p) {
  707. if (p) {
  708. return ::Catch::Detail::rawMemoryToString(p);
  709. } else {
  710. return "nullptr";
  711. }
  712. }
  713. };
  714. template <typename R, typename C>
  715. struct StringMaker<R C::*> {
  716. static std::string convert(R C::* p) {
  717. if (p) {
  718. return ::Catch::Detail::rawMemoryToString(p);
  719. } else {
  720. return "nullptr";
  721. }
  722. }
  723. };
  724. namespace Detail {
  725. template<typename InputIterator>
  726. std::string rangeToString(InputIterator first, InputIterator last) {
  727. ReusableStringStream rss;
  728. rss << "{ ";
  729. if (first != last) {
  730. rss << ::Catch::Detail::stringify(*first);
  731. for (++first; first != last; ++first)
  732. rss << ", " << ::Catch::Detail::stringify(*first);
  733. }
  734. rss << " }";
  735. return rss.str();
  736. }
  737. }
  738. #ifdef __OBJC__
  739. template<>
  740. struct StringMaker<NSString*> {
  741. static std::string convert(NSString * nsstring) {
  742. if (!nsstring)
  743. return "nil";
  744. return std::string("@") + [nsstring UTF8String];
  745. }
  746. };
  747. template<>
  748. struct StringMaker<NSObject*> {
  749. static std::string convert(NSObject* nsObject) {
  750. return ::Catch::Detail::stringify([nsObject description]);
  751. }
  752. };
  753. namespace Detail {
  754. inline std::string stringify( NSString* nsstring ) {
  755. return StringMaker<NSString*>::convert( nsstring );
  756. }
  757. } // namespace Detail
  758. #endif // __OBJC__
  759. } // namespace Catch
  760. //////////////////////////////////////////////////////
  761. // Separate std-lib types stringification, so it can be selectively enabled
  762. // This means that we do not bring in
  763. #if defined(CATCH_CONFIG_ENABLE_ALL_STRINGMAKERS)
  764. # define CATCH_CONFIG_ENABLE_PAIR_STRINGMAKER
  765. # define CATCH_CONFIG_ENABLE_TUPLE_STRINGMAKER
  766. # define CATCH_CONFIG_ENABLE_CHRONO_STRINGMAKER
  767. #endif
  768. // Separate std::pair specialization
  769. #if defined(CATCH_CONFIG_ENABLE_PAIR_STRINGMAKER)
  770. #include <utility>
  771. namespace Catch {
  772. template<typename T1, typename T2>
  773. struct StringMaker<std::pair<T1, T2> > {
  774. static std::string convert(const std::pair<T1, T2>& pair) {
  775. ReusableStringStream rss;
  776. rss << "{ "
  777. << ::Catch::Detail::stringify(pair.first)
  778. << ", "
  779. << ::Catch::Detail::stringify(pair.second)
  780. << " }";
  781. return rss.str();
  782. }
  783. };
  784. }
  785. #endif // CATCH_CONFIG_ENABLE_PAIR_STRINGMAKER
  786. // Separate std::tuple specialization
  787. #if defined(CATCH_CONFIG_ENABLE_TUPLE_STRINGMAKER)
  788. #include <tuple>
  789. namespace Catch {
  790. namespace Detail {
  791. template<
  792. typename Tuple,
  793. std::size_t N = 0,
  794. bool = (N < std::tuple_size<Tuple>::value)
  795. >
  796. struct TupleElementPrinter {
  797. static void print(const Tuple& tuple, std::ostream& os) {
  798. os << (N ? ", " : " ")
  799. << ::Catch::Detail::stringify(std::get<N>(tuple));
  800. TupleElementPrinter<Tuple, N + 1>::print(tuple, os);
  801. }
  802. };
  803. template<
  804. typename Tuple,
  805. std::size_t N
  806. >
  807. struct TupleElementPrinter<Tuple, N, false> {
  808. static void print(const Tuple&, std::ostream&) {}
  809. };
  810. }
  811. template<typename ...Types>
  812. struct StringMaker<std::tuple<Types...>> {
  813. static std::string convert(const std::tuple<Types...>& tuple) {
  814. ReusableStringStream rss;
  815. rss << '{';
  816. Detail::TupleElementPrinter<std::tuple<Types...>>::print(tuple, rss.get());
  817. rss << " }";
  818. return rss.str();
  819. }
  820. };
  821. }
  822. #endif // CATCH_CONFIG_ENABLE_TUPLE_STRINGMAKER
  823. namespace Catch {
  824. struct not_this_one {}; // Tag type for detecting which begin/ end are being selected
  825. // Import begin/ end from std here so they are considered alongside the fallback (...) overloads in this namespace
  826. using std::begin;
  827. using std::end;
  828. not_this_one begin( ... );
  829. not_this_one end( ... );
  830. template <typename T>
  831. struct is_range {
  832. static const bool value =
  833. !std::is_same<decltype(begin(std::declval<T>())), not_this_one>::value &&
  834. !std::is_same<decltype(end(std::declval<T>())), not_this_one>::value;
  835. };
  836. template<typename Range>
  837. std::string rangeToString( Range const& range ) {
  838. return ::Catch::Detail::rangeToString( begin( range ), end( range ) );
  839. }
  840. // Handle vector<bool> specially
  841. template<typename Allocator>
  842. std::string rangeToString( std::vector<bool, Allocator> const& v ) {
  843. ReusableStringStream rss;
  844. rss << "{ ";
  845. bool first = true;
  846. for( bool b : v ) {
  847. if( first )
  848. first = false;
  849. else
  850. rss << ", ";
  851. rss << ::Catch::Detail::stringify( b );
  852. }
  853. rss << " }";
  854. return rss.str();
  855. }
  856. template<typename R>
  857. struct StringMaker<R, typename std::enable_if<is_range<R>::value && !std::is_array<R>::value>::type> {
  858. static std::string convert( R const& range ) {
  859. return rangeToString( range );
  860. }
  861. };
  862. template <typename T, int SZ>
  863. struct StringMaker<T[SZ]> {
  864. static std::string convert(T const(&arr)[SZ]) {
  865. return rangeToString(arr);
  866. }
  867. };
  868. } // namespace Catch
  869. // Separate std::chrono::duration specialization
  870. #if defined(CATCH_CONFIG_ENABLE_CHRONO_STRINGMAKER)
  871. #include <ctime>
  872. #include <ratio>
  873. #include <chrono>
  874. namespace Catch {
  875. template <class Ratio>
  876. struct ratio_string {
  877. static std::string symbol();
  878. };
  879. template <class Ratio>
  880. std::string ratio_string<Ratio>::symbol() {
  881. Catch::ReusableStringStream rss;
  882. rss << '[' << Ratio::num << '/'
  883. << Ratio::den << ']';
  884. return rss.str();
  885. }
  886. template <>
  887. struct ratio_string<std::atto> {
  888. static std::string symbol();
  889. };
  890. template <>
  891. struct ratio_string<std::femto> {
  892. static std::string symbol();
  893. };
  894. template <>
  895. struct ratio_string<std::pico> {
  896. static std::string symbol();
  897. };
  898. template <>
  899. struct ratio_string<std::nano> {
  900. static std::string symbol();
  901. };
  902. template <>
  903. struct ratio_string<std::micro> {
  904. static std::string symbol();
  905. };
  906. template <>
  907. struct ratio_string<std::milli> {
  908. static std::string symbol();
  909. };
  910. ////////////
  911. // std::chrono::duration specializations
  912. template<typename Value, typename Ratio>
  913. struct StringMaker<std::chrono::duration<Value, Ratio>> {
  914. static std::string convert(std::chrono::duration<Value, Ratio> const& duration) {
  915. ReusableStringStream rss;
  916. rss << duration.count() << ' ' << ratio_string<Ratio>::symbol() << 's';
  917. return rss.str();
  918. }
  919. };
  920. template<typename Value>
  921. struct StringMaker<std::chrono::duration<Value, std::ratio<1>>> {
  922. static std::string convert(std::chrono::duration<Value, std::ratio<1>> const& duration) {
  923. ReusableStringStream rss;
  924. rss << duration.count() << " s";
  925. return rss.str();
  926. }
  927. };
  928. template<typename Value>
  929. struct StringMaker<std::chrono::duration<Value, std::ratio<60>>> {
  930. static std::string convert(std::chrono::duration<Value, std::ratio<60>> const& duration) {
  931. ReusableStringStream rss;
  932. rss << duration.count() << " m";
  933. return rss.str();
  934. }
  935. };
  936. template<typename Value>
  937. struct StringMaker<std::chrono::duration<Value, std::ratio<3600>>> {
  938. static std::string convert(std::chrono::duration<Value, std::ratio<3600>> const& duration) {
  939. ReusableStringStream rss;
  940. rss << duration.count() << " h";
  941. return rss.str();
  942. }
  943. };
  944. ////////////
  945. // std::chrono::time_point specialization
  946. // Generic time_point cannot be specialized, only std::chrono::time_point<system_clock>
  947. template<typename Clock, typename Duration>
  948. struct StringMaker<std::chrono::time_point<Clock, Duration>> {
  949. static std::string convert(std::chrono::time_point<Clock, Duration> const& time_point) {
  950. return ::Catch::Detail::stringify(time_point.time_since_epoch()) + " since epoch";
  951. }
  952. };
  953. // std::chrono::time_point<system_clock> specialization
  954. template<typename Duration>
  955. struct StringMaker<std::chrono::time_point<std::chrono::system_clock, Duration>> {
  956. static std::string convert(std::chrono::time_point<std::chrono::system_clock, Duration> const& time_point) {
  957. auto converted = std::chrono::system_clock::to_time_t(time_point);
  958. #ifdef _MSC_VER
  959. std::tm timeInfo = {};
  960. gmtime_s(&timeInfo, &converted);
  961. #else
  962. std::tm* timeInfo = std::gmtime(&converted);
  963. #endif
  964. auto const timeStampSize = sizeof("2017-01-16T17:06:45Z");
  965. char timeStamp[timeStampSize];
  966. const char * const fmt = "%Y-%m-%dT%H:%M:%SZ";
  967. #ifdef _MSC_VER
  968. std::strftime(timeStamp, timeStampSize, fmt, &timeInfo);
  969. #else
  970. std::strftime(timeStamp, timeStampSize, fmt, timeInfo);
  971. #endif
  972. return std::string(timeStamp);
  973. }
  974. };
  975. }
  976. #endif // CATCH_CONFIG_ENABLE_CHRONO_STRINGMAKER
  977. #ifdef _MSC_VER
  978. #pragma warning(pop)
  979. #endif
  980. // end catch_tostring.h
  981. #include <iosfwd>
  982. #ifdef _MSC_VER
  983. #pragma warning(push)
  984. #pragma warning(disable:4389) // '==' : signed/unsigned mismatch
  985. #pragma warning(disable:4018) // more "signed/unsigned mismatch"
  986. #pragma warning(disable:4312) // Converting int to T* using reinterpret_cast (issue on x64 platform)
  987. #pragma warning(disable:4180) // qualifier applied to function type has no meaning
  988. #endif
  989. namespace Catch {
  990. struct ITransientExpression {
  991. auto isBinaryExpression() const -> bool { return m_isBinaryExpression; }
  992. auto getResult() const -> bool { return m_result; }
  993. virtual void streamReconstructedExpression( std::ostream &os ) const = 0;
  994. ITransientExpression( bool isBinaryExpression, bool result )
  995. : m_isBinaryExpression( isBinaryExpression ),
  996. m_result( result )
  997. {}
  998. // We don't actually need a virtual destructor, but many static analysers
  999. // complain if it's not here :-(
  1000. virtual ~ITransientExpression();
  1001. bool m_isBinaryExpression;
  1002. bool m_result;
  1003. };
  1004. void formatReconstructedExpression( std::ostream &os, std::string const& lhs, StringRef op, std::string const& rhs );
  1005. template<typename LhsT, typename RhsT>
  1006. class BinaryExpr : public ITransientExpression {
  1007. LhsT m_lhs;
  1008. StringRef m_op;
  1009. RhsT m_rhs;
  1010. void streamReconstructedExpression( std::ostream &os ) const override {
  1011. formatReconstructedExpression
  1012. ( os, Catch::Detail::stringify( m_lhs ), m_op, Catch::Detail::stringify( m_rhs ) );
  1013. }
  1014. public:
  1015. BinaryExpr( bool comparisonResult, LhsT lhs, StringRef op, RhsT rhs )
  1016. : ITransientExpression{ true, comparisonResult },
  1017. m_lhs( lhs ),
  1018. m_op( op ),
  1019. m_rhs( rhs )
  1020. {}
  1021. };
  1022. template<typename LhsT>
  1023. class UnaryExpr : public ITransientExpression {
  1024. LhsT m_lhs;
  1025. void streamReconstructedExpression( std::ostream &os ) const override {
  1026. os << Catch::Detail::stringify( m_lhs );
  1027. }
  1028. public:
  1029. explicit UnaryExpr( LhsT lhs )
  1030. : ITransientExpression{ false, lhs ? true : false },
  1031. m_lhs( lhs )
  1032. {}
  1033. };
  1034. // Specialised comparison functions to handle equality comparisons between ints and pointers (NULL deduces as an int)
  1035. template<typename LhsT, typename RhsT>
  1036. auto compareEqual( LhsT const& lhs, RhsT const& rhs ) -> bool { return static_cast<bool>(lhs == rhs); };
  1037. template<typename T>
  1038. auto compareEqual( T* const& lhs, int rhs ) -> bool { return lhs == reinterpret_cast<void const*>( rhs ); }
  1039. template<typename T>
  1040. auto compareEqual( T* const& lhs, long rhs ) -> bool { return lhs == reinterpret_cast<void const*>( rhs ); }
  1041. template<typename T>
  1042. auto compareEqual( int lhs, T* const& rhs ) -> bool { return reinterpret_cast<void const*>( lhs ) == rhs; }
  1043. template<typename T>
  1044. auto compareEqual( long lhs, T* const& rhs ) -> bool { return reinterpret_cast<void const*>( lhs ) == rhs; }
  1045. template<typename LhsT, typename RhsT>
  1046. auto compareNotEqual( LhsT const& lhs, RhsT&& rhs ) -> bool { return static_cast<bool>(lhs != rhs); };
  1047. template<typename T>
  1048. auto compareNotEqual( T* const& lhs, int rhs ) -> bool { return lhs != reinterpret_cast<void const*>( rhs ); }
  1049. template<typename T>
  1050. auto compareNotEqual( T* const& lhs, long rhs ) -> bool { return lhs != reinterpret_cast<void const*>( rhs ); }
  1051. template<typename T>
  1052. auto compareNotEqual( int lhs, T* const& rhs ) -> bool { return reinterpret_cast<void const*>( lhs ) != rhs; }
  1053. template<typename T>
  1054. auto compareNotEqual( long lhs, T* const& rhs ) -> bool { return reinterpret_cast<void const*>( lhs ) != rhs; }
  1055. template<typename LhsT>
  1056. class ExprLhs {
  1057. LhsT m_lhs;
  1058. public:
  1059. explicit ExprLhs( LhsT lhs ) : m_lhs( lhs ) {}
  1060. template<typename RhsT>
  1061. auto operator == ( RhsT const& rhs ) -> BinaryExpr<LhsT, RhsT const&> const {
  1062. return { compareEqual( m_lhs, rhs ), m_lhs, "==", rhs };
  1063. }
  1064. auto operator == ( bool rhs ) -> BinaryExpr<LhsT, bool> const {
  1065. return { m_lhs == rhs, m_lhs, "==", rhs };
  1066. }
  1067. template<typename RhsT>
  1068. auto operator != ( RhsT const& rhs ) -> BinaryExpr<LhsT, RhsT const&> const {
  1069. return { compareNotEqual( m_lhs, rhs ), m_lhs, "!=", rhs };
  1070. }
  1071. auto operator != ( bool rhs ) -> BinaryExpr<LhsT, bool> const {
  1072. return { m_lhs != rhs, m_lhs, "!=", rhs };
  1073. }
  1074. template<typename RhsT>
  1075. auto operator > ( RhsT const& rhs ) -> BinaryExpr<LhsT, RhsT const&> const {
  1076. return { static_cast<bool>(m_lhs > rhs), m_lhs, ">", rhs };
  1077. }
  1078. template<typename RhsT>
  1079. auto operator < ( RhsT const& rhs ) -> BinaryExpr<LhsT, RhsT const&> const {
  1080. return { static_cast<bool>(m_lhs < rhs), m_lhs, "<", rhs };
  1081. }
  1082. template<typename RhsT>
  1083. auto operator >= ( RhsT const& rhs ) -> BinaryExpr<LhsT, RhsT const&> const {
  1084. return { static_cast<bool>(m_lhs >= rhs), m_lhs, ">=", rhs };
  1085. }
  1086. template<typename RhsT>
  1087. auto operator <= ( RhsT const& rhs ) -> BinaryExpr<LhsT, RhsT const&> const {
  1088. return { static_cast<bool>(m_lhs <= rhs), m_lhs, "<=", rhs };
  1089. }
  1090. auto makeUnaryExpr() const -> UnaryExpr<LhsT> {
  1091. return UnaryExpr<LhsT>{ m_lhs };
  1092. }
  1093. };
  1094. void handleExpression( ITransientExpression const& expr );
  1095. template<typename T>
  1096. void handleExpression( ExprLhs<T> const& expr ) {
  1097. handleExpression( expr.makeUnaryExpr() );
  1098. }
  1099. struct Decomposer {
  1100. template<typename T>
  1101. auto operator <= ( T const& lhs ) -> ExprLhs<T const&> {
  1102. return ExprLhs<T const&>{ lhs };
  1103. }
  1104. auto operator <=( bool value ) -> ExprLhs<bool> {
  1105. return ExprLhs<bool>{ value };
  1106. }
  1107. };
  1108. } // end namespace Catch
  1109. #ifdef _MSC_VER
  1110. #pragma warning(pop)
  1111. #endif
  1112. // end catch_decomposer.h
  1113. // start catch_interfaces_capture.h
  1114. #include <string>
  1115. namespace Catch {
  1116. class AssertionResult;
  1117. struct AssertionInfo;
  1118. struct SectionInfo;
  1119. struct SectionEndInfo;
  1120. struct MessageInfo;
  1121. struct Counts;
  1122. struct BenchmarkInfo;
  1123. struct BenchmarkStats;
  1124. struct AssertionReaction;
  1125. struct ITransientExpression;
  1126. struct IResultCapture {
  1127. virtual ~IResultCapture();
  1128. virtual bool sectionStarted( SectionInfo const& sectionInfo,
  1129. Counts& assertions ) = 0;
  1130. virtual void sectionEnded( SectionEndInfo const& endInfo ) = 0;
  1131. virtual void sectionEndedEarly( SectionEndInfo const& endInfo ) = 0;
  1132. virtual void benchmarkStarting( BenchmarkInfo const& info ) = 0;
  1133. virtual void benchmarkEnded( BenchmarkStats const& stats ) = 0;
  1134. virtual void pushScopedMessage( MessageInfo const& message ) = 0;
  1135. virtual void popScopedMessage( MessageInfo const& message ) = 0;
  1136. virtual void handleFatalErrorCondition( StringRef message ) = 0;
  1137. virtual void handleExpr
  1138. ( AssertionInfo const& info,
  1139. ITransientExpression const& expr,
  1140. AssertionReaction& reaction ) = 0;
  1141. virtual void handleMessage
  1142. ( AssertionInfo const& info,
  1143. ResultWas::OfType resultType,
  1144. StringRef const& message,
  1145. AssertionReaction& reaction ) = 0;
  1146. virtual void handleUnexpectedExceptionNotThrown
  1147. ( AssertionInfo const& info,
  1148. AssertionReaction& reaction ) = 0;
  1149. virtual void handleUnexpectedInflightException
  1150. ( AssertionInfo const& info,
  1151. std::string const& message,
  1152. AssertionReaction& reaction ) = 0;
  1153. virtual void handleIncomplete
  1154. ( AssertionInfo const& info ) = 0;
  1155. virtual void handleNonExpr
  1156. ( AssertionInfo const &info,
  1157. ResultWas::OfType resultType,
  1158. AssertionReaction &reaction ) = 0;
  1159. virtual bool lastAssertionPassed() = 0;
  1160. virtual void assertionPassed() = 0;
  1161. // Deprecated, do not use:
  1162. virtual std::string getCurrentTestName() const = 0;
  1163. virtual const AssertionResult* getLastResult() const = 0;
  1164. virtual void exceptionEarlyReported() = 0;
  1165. };
  1166. IResultCapture& getResultCapture();
  1167. }
  1168. // end catch_interfaces_capture.h
  1169. namespace Catch {
  1170. struct TestFailureException{};
  1171. struct AssertionResultData;
  1172. struct IResultCapture;
  1173. class RunContext;
  1174. class LazyExpression {
  1175. friend class AssertionHandler;
  1176. friend struct AssertionStats;
  1177. friend class RunContext;
  1178. ITransientExpression const* m_transientExpression = nullptr;
  1179. bool m_isNegated;
  1180. public:
  1181. LazyExpression( bool isNegated );
  1182. LazyExpression( LazyExpression const& other );
  1183. LazyExpression& operator = ( LazyExpression const& ) = delete;
  1184. explicit operator bool() const;
  1185. friend auto operator << ( std::ostream& os, LazyExpression const& lazyExpr ) -> std::ostream&;
  1186. };
  1187. struct AssertionReaction {
  1188. bool shouldDebugBreak = false;
  1189. bool shouldThrow = false;
  1190. };
  1191. class AssertionHandler {
  1192. AssertionInfo m_assertionInfo;
  1193. AssertionReaction m_reaction;
  1194. bool m_completed = false;
  1195. IResultCapture& m_resultCapture;
  1196. public:
  1197. AssertionHandler
  1198. ( StringRef macroName,
  1199. SourceLineInfo const& lineInfo,
  1200. StringRef capturedExpression,
  1201. ResultDisposition::Flags resultDisposition );
  1202. ~AssertionHandler() {
  1203. if ( !m_completed ) {
  1204. m_resultCapture.handleIncomplete( m_assertionInfo );
  1205. }
  1206. }
  1207. template<typename T>
  1208. void handleExpr( ExprLhs<T> const& expr ) {
  1209. handleExpr( expr.makeUnaryExpr() );
  1210. }
  1211. void handleExpr( ITransientExpression const& expr );
  1212. void handleMessage(ResultWas::OfType resultType, StringRef const& message);
  1213. void handleExceptionThrownAsExpected();
  1214. void handleUnexpectedExceptionNotThrown();
  1215. void handleExceptionNotThrownAsExpected();
  1216. void handleThrowingCallSkipped();
  1217. void handleUnexpectedInflightException();
  1218. void complete();
  1219. void setCompleted();
  1220. // query
  1221. auto allowThrows() const -> bool;
  1222. };
  1223. void handleExceptionMatchExpr( AssertionHandler& handler, std::string const& str, StringRef matcherString );
  1224. } // namespace Catch
  1225. // end catch_assertionhandler.h
  1226. // start catch_message.h
  1227. #include <string>
  1228. namespace Catch {
  1229. struct MessageInfo {
  1230. MessageInfo( std::string const& _macroName,
  1231. SourceLineInfo const& _lineInfo,
  1232. ResultWas::OfType _type );
  1233. std::string macroName;
  1234. std::string message;
  1235. SourceLineInfo lineInfo;
  1236. ResultWas::OfType type;
  1237. unsigned int sequence;
  1238. bool operator == ( MessageInfo const& other ) const;
  1239. bool operator < ( MessageInfo const& other ) const;
  1240. private:
  1241. static unsigned int globalCount;
  1242. };
  1243. struct MessageStream {
  1244. template<typename T>
  1245. MessageStream& operator << ( T const& value ) {
  1246. m_stream << value;
  1247. return *this;
  1248. }
  1249. ReusableStringStream m_stream;
  1250. };
  1251. struct MessageBuilder : MessageStream {
  1252. MessageBuilder( std::string const& macroName,
  1253. SourceLineInfo const& lineInfo,
  1254. ResultWas::OfType type );
  1255. template<typename T>
  1256. MessageBuilder& operator << ( T const& value ) {
  1257. m_stream << value;
  1258. return *this;
  1259. }
  1260. MessageInfo m_info;
  1261. };
  1262. class ScopedMessage {
  1263. public:
  1264. explicit ScopedMessage( MessageBuilder const& builder );
  1265. ~ScopedMessage();
  1266. MessageInfo m_info;
  1267. };
  1268. } // end namespace Catch
  1269. // end catch_message.h
  1270. #if !defined(CATCH_CONFIG_DISABLE)
  1271. #if !defined(CATCH_CONFIG_DISABLE_STRINGIFICATION)
  1272. #define CATCH_INTERNAL_STRINGIFY(...) #__VA_ARGS__
  1273. #else
  1274. #define CATCH_INTERNAL_STRINGIFY(...) "Disabled by CATCH_CONFIG_DISABLE_STRINGIFICATION"
  1275. #endif
  1276. #if defined(CATCH_CONFIG_FAST_COMPILE)
  1277. ///////////////////////////////////////////////////////////////////////////////
  1278. // Another way to speed-up compilation is to omit local try-catch for REQUIRE*
  1279. // macros.
  1280. #define INTERNAL_CATCH_TRY
  1281. #define INTERNAL_CATCH_CATCH( capturer )
  1282. #else // CATCH_CONFIG_FAST_COMPILE
  1283. #define INTERNAL_CATCH_TRY try
  1284. #define INTERNAL_CATCH_CATCH( handler ) catch(...) { handler.handleUnexpectedInflightException(); }
  1285. #endif
  1286. #define INTERNAL_CATCH_REACT( handler ) handler.complete();
  1287. ///////////////////////////////////////////////////////////////////////////////
  1288. #define INTERNAL_CATCH_TEST( macroName, resultDisposition, ... ) \
  1289. do { \
  1290. Catch::AssertionHandler catchAssertionHandler( macroName, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(__VA_ARGS__), resultDisposition ); \
  1291. INTERNAL_CATCH_TRY { \
  1292. CATCH_INTERNAL_SUPPRESS_PARENTHESES_WARNINGS \
  1293. catchAssertionHandler.handleExpr( Catch::Decomposer() <= __VA_ARGS__ ); \
  1294. CATCH_INTERNAL_UNSUPPRESS_PARENTHESES_WARNINGS \
  1295. } INTERNAL_CATCH_CATCH( catchAssertionHandler ) \
  1296. INTERNAL_CATCH_REACT( catchAssertionHandler ) \
  1297. } 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
  1298. // The double negation silences MSVC's C4800 warning, the static_cast forces short-circuit evaluation if the type has overloaded &&.
  1299. ///////////////////////////////////////////////////////////////////////////////
  1300. #define INTERNAL_CATCH_IF( macroName, resultDisposition, ... ) \
  1301. INTERNAL_CATCH_TEST( macroName, resultDisposition, __VA_ARGS__ ); \
  1302. if( Catch::getResultCapture().lastAssertionPassed() )
  1303. ///////////////////////////////////////////////////////////////////////////////
  1304. #define INTERNAL_CATCH_ELSE( macroName, resultDisposition, ... ) \
  1305. INTERNAL_CATCH_TEST( macroName, resultDisposition, __VA_ARGS__ ); \
  1306. if( !Catch::getResultCapture().lastAssertionPassed() )
  1307. ///////////////////////////////////////////////////////////////////////////////
  1308. #define INTERNAL_CATCH_NO_THROW( macroName, resultDisposition, ... ) \
  1309. do { \
  1310. Catch::AssertionHandler catchAssertionHandler( macroName, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(__VA_ARGS__), resultDisposition ); \
  1311. try { \
  1312. static_cast<void>(__VA_ARGS__); \
  1313. catchAssertionHandler.handleExceptionNotThrownAsExpected(); \
  1314. } \
  1315. catch( ... ) { \
  1316. catchAssertionHandler.handleUnexpectedInflightException(); \
  1317. } \
  1318. INTERNAL_CATCH_REACT( catchAssertionHandler ) \
  1319. } while( false )
  1320. ///////////////////////////////////////////////////////////////////////////////
  1321. #define INTERNAL_CATCH_THROWS( macroName, resultDisposition, ... ) \
  1322. do { \
  1323. Catch::AssertionHandler catchAssertionHandler( macroName, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(__VA_ARGS__), resultDisposition); \
  1324. if( catchAssertionHandler.allowThrows() ) \
  1325. try { \
  1326. static_cast<void>(__VA_ARGS__); \
  1327. catchAssertionHandler.handleUnexpectedExceptionNotThrown(); \
  1328. } \
  1329. catch( ... ) { \
  1330. catchAssertionHandler.handleExceptionThrownAsExpected(); \
  1331. } \
  1332. else \
  1333. catchAssertionHandler.handleThrowingCallSkipped(); \
  1334. INTERNAL_CATCH_REACT( catchAssertionHandler ) \
  1335. } while( false )
  1336. ///////////////////////////////////////////////////////////////////////////////
  1337. #define INTERNAL_CATCH_THROWS_AS( macroName, exceptionType, resultDisposition, expr ) \
  1338. do { \
  1339. Catch::AssertionHandler catchAssertionHandler( macroName, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(expr) ", " CATCH_INTERNAL_STRINGIFY(exceptionType), resultDisposition ); \
  1340. if( catchAssertionHandler.allowThrows() ) \
  1341. try { \
  1342. static_cast<void>(expr); \
  1343. catchAssertionHandler.handleUnexpectedExceptionNotThrown(); \
  1344. } \
  1345. catch( exceptionType const& ) { \
  1346. catchAssertionHandler.handleExceptionThrownAsExpected(); \
  1347. } \
  1348. catch( ... ) { \
  1349. catchAssertionHandler.handleUnexpectedInflightException(); \
  1350. } \
  1351. else \
  1352. catchAssertionHandler.handleThrowingCallSkipped(); \
  1353. INTERNAL_CATCH_REACT( catchAssertionHandler ) \
  1354. } while( false )
  1355. ///////////////////////////////////////////////////////////////////////////////
  1356. #define INTERNAL_CATCH_MSG( macroName, messageType, resultDisposition, ... ) \
  1357. do { \
  1358. Catch::AssertionHandler catchAssertionHandler( macroName, CATCH_INTERNAL_LINEINFO, "", resultDisposition ); \
  1359. catchAssertionHandler.handleMessage( messageType, ( Catch::MessageStream() << __VA_ARGS__ + ::Catch::StreamEndStop() ).m_stream.str() ); \
  1360. INTERNAL_CATCH_REACT( catchAssertionHandler ) \
  1361. } while( false )
  1362. ///////////////////////////////////////////////////////////////////////////////
  1363. #define INTERNAL_CATCH_INFO( macroName, log ) \
  1364. Catch::ScopedMessage INTERNAL_CATCH_UNIQUE_NAME( scopedMessage )( Catch::MessageBuilder( macroName, CATCH_INTERNAL_LINEINFO, Catch::ResultWas::Info ) << log );
  1365. ///////////////////////////////////////////////////////////////////////////////
  1366. // Although this is matcher-based, it can be used with just a string
  1367. #define INTERNAL_CATCH_THROWS_STR_MATCHES( macroName, resultDisposition, matcher, ... ) \
  1368. do { \
  1369. Catch::AssertionHandler catchAssertionHandler( macroName, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(__VA_ARGS__) ", " CATCH_INTERNAL_STRINGIFY(matcher), resultDisposition ); \
  1370. if( catchAssertionHandler.allowThrows() ) \
  1371. try { \
  1372. static_cast<void>(__VA_ARGS__); \
  1373. catchAssertionHandler.handleUnexpectedExceptionNotThrown(); \
  1374. } \
  1375. catch( ... ) { \
  1376. Catch::handleExceptionMatchExpr( catchAssertionHandler, matcher, #matcher ); \
  1377. } \
  1378. else \
  1379. catchAssertionHandler.handleThrowingCallSkipped(); \
  1380. INTERNAL_CATCH_REACT( catchAssertionHandler ) \
  1381. } while( false )
  1382. #endif // CATCH_CONFIG_DISABLE
  1383. // end catch_capture.hpp
  1384. // start catch_section.h
  1385. // start catch_section_info.h
  1386. // start catch_totals.h
  1387. #include <cstddef>
  1388. namespace Catch {
  1389. struct Counts {
  1390. Counts operator - ( Counts const& other ) const;
  1391. Counts& operator += ( Counts const& other );
  1392. std::size_t total() const;
  1393. bool allPassed() const;
  1394. bool allOk() const;
  1395. std::size_t passed = 0;
  1396. std::size_t failed = 0;
  1397. std::size_t failedButOk = 0;
  1398. };
  1399. struct Totals {
  1400. Totals operator - ( Totals const& other ) const;
  1401. Totals& operator += ( Totals const& other );
  1402. Totals delta( Totals const& prevTotals ) const;
  1403. Counts assertions;
  1404. Counts testCases;
  1405. };
  1406. }
  1407. // end catch_totals.h
  1408. #include <string>
  1409. namespace Catch {
  1410. struct SectionInfo {
  1411. SectionInfo
  1412. ( SourceLineInfo const& _lineInfo,
  1413. std::string const& _name,
  1414. std::string const& _description = std::string() );
  1415. std::string name;
  1416. std::string description;
  1417. SourceLineInfo lineInfo;
  1418. };
  1419. struct SectionEndInfo {
  1420. SectionEndInfo( SectionInfo const& _sectionInfo, Counts const& _prevAssertions, double _durationInSeconds );
  1421. SectionInfo sectionInfo;
  1422. Counts prevAssertions;
  1423. double durationInSeconds;
  1424. };
  1425. } // end namespace Catch
  1426. // end catch_section_info.h
  1427. // start catch_timer.h
  1428. #include <cstdint>
  1429. namespace Catch {
  1430. auto getCurrentNanosecondsSinceEpoch() -> uint64_t;
  1431. auto getEstimatedClockResolution() -> uint64_t;
  1432. class Timer {
  1433. uint64_t m_nanoseconds = 0;
  1434. public:
  1435. void start();
  1436. auto getElapsedNanoseconds() const -> uint64_t;
  1437. auto getElapsedMicroseconds() const -> uint64_t;
  1438. auto getElapsedMilliseconds() const -> unsigned int;
  1439. auto getElapsedSeconds() const -> double;
  1440. };
  1441. } // namespace Catch
  1442. // end catch_timer.h
  1443. #include <string>
  1444. namespace Catch {
  1445. class Section : NonCopyable {
  1446. public:
  1447. Section( SectionInfo const& info );
  1448. ~Section();
  1449. // This indicates whether the section should be executed or not
  1450. explicit operator bool() const;
  1451. private:
  1452. SectionInfo m_info;
  1453. std::string m_name;
  1454. Counts m_assertions;
  1455. bool m_sectionIncluded;
  1456. Timer m_timer;
  1457. };
  1458. } // end namespace Catch
  1459. #define INTERNAL_CATCH_SECTION( ... ) \
  1460. if( Catch::Section const& INTERNAL_CATCH_UNIQUE_NAME( catch_internal_Section ) = Catch::SectionInfo( CATCH_INTERNAL_LINEINFO, __VA_ARGS__ ) )
  1461. // end catch_section.h
  1462. // start catch_benchmark.h
  1463. #include <cstdint>
  1464. #include <string>
  1465. namespace Catch {
  1466. class BenchmarkLooper {
  1467. std::string m_name;
  1468. std::size_t m_count = 0;
  1469. std::size_t m_iterationsToRun = 1;
  1470. uint64_t m_resolution;
  1471. Timer m_timer;
  1472. static auto getResolution() -> uint64_t;
  1473. public:
  1474. // Keep most of this inline as it's on the code path that is being timed
  1475. BenchmarkLooper( StringRef name )
  1476. : m_name( name ),
  1477. m_resolution( getResolution() )
  1478. {
  1479. reportStart();
  1480. m_timer.start();
  1481. }
  1482. explicit operator bool() {
  1483. if( m_count < m_iterationsToRun )
  1484. return true;
  1485. return needsMoreIterations();
  1486. }
  1487. void increment() {
  1488. ++m_count;
  1489. }
  1490. void reportStart();
  1491. auto needsMoreIterations() -> bool;
  1492. };
  1493. } // end namespace Catch
  1494. #define BENCHMARK( name ) \
  1495. for( Catch::BenchmarkLooper looper( name ); looper; looper.increment() )
  1496. // end catch_benchmark.h
  1497. // start catch_interfaces_exception.h
  1498. // start catch_interfaces_registry_hub.h
  1499. #include <string>
  1500. #include <memory>
  1501. namespace Catch {
  1502. class TestCase;
  1503. struct ITestCaseRegistry;
  1504. struct IExceptionTranslatorRegistry;
  1505. struct IExceptionTranslator;
  1506. struct IReporterRegistry;
  1507. struct IReporterFactory;
  1508. struct ITagAliasRegistry;
  1509. class StartupExceptionRegistry;
  1510. using IReporterFactoryPtr = std::shared_ptr<IReporterFactory>;
  1511. struct IRegistryHub {
  1512. virtual ~IRegistryHub();
  1513. virtual IReporterRegistry const& getReporterRegistry() const = 0;
  1514. virtual ITestCaseRegistry const& getTestCaseRegistry() const = 0;
  1515. virtual ITagAliasRegistry const& getTagAliasRegistry() const = 0;
  1516. virtual IExceptionTranslatorRegistry& getExceptionTranslatorRegistry() = 0;
  1517. virtual StartupExceptionRegistry const& getStartupExceptionRegistry() const = 0;
  1518. };
  1519. struct IMutableRegistryHub {
  1520. virtual ~IMutableRegistryHub();
  1521. virtual void registerReporter( std::string const& name, IReporterFactoryPtr const& factory ) = 0;
  1522. virtual void registerListener( IReporterFactoryPtr const& factory ) = 0;
  1523. virtual void registerTest( TestCase const& testInfo ) = 0;
  1524. virtual void registerTranslator( const IExceptionTranslator* translator ) = 0;
  1525. virtual void registerTagAlias( std::string const& alias, std::string const& tag, SourceLineInfo const& lineInfo ) = 0;
  1526. virtual void registerStartupException() noexcept = 0;
  1527. };
  1528. IRegistryHub& getRegistryHub();
  1529. IMutableRegistryHub& getMutableRegistryHub();
  1530. void cleanUp();
  1531. std::string translateActiveException();
  1532. }
  1533. // end catch_interfaces_registry_hub.h
  1534. #if defined(CATCH_CONFIG_DISABLE)
  1535. #define INTERNAL_CATCH_TRANSLATE_EXCEPTION_NO_REG( translatorName, signature) \
  1536. static std::string translatorName( signature )
  1537. #endif
  1538. #include <exception>
  1539. #include <string>
  1540. #include <vector>
  1541. namespace Catch {
  1542. using exceptionTranslateFunction = std::string(*)();
  1543. struct IExceptionTranslator;
  1544. using ExceptionTranslators = std::vector<std::unique_ptr<IExceptionTranslator const>>;
  1545. struct IExceptionTranslator {
  1546. virtual ~IExceptionTranslator();
  1547. virtual std::string translate( ExceptionTranslators::const_iterator it, ExceptionTranslators::const_iterator itEnd ) const = 0;
  1548. };
  1549. struct IExceptionTranslatorRegistry {
  1550. virtual ~IExceptionTranslatorRegistry();
  1551. virtual std::string translateActiveException() const = 0;
  1552. };
  1553. class ExceptionTranslatorRegistrar {
  1554. template<typename T>
  1555. class ExceptionTranslator : public IExceptionTranslator {
  1556. public:
  1557. ExceptionTranslator( std::string(*translateFunction)( T& ) )
  1558. : m_translateFunction( translateFunction )
  1559. {}
  1560. std::string translate( ExceptionTranslators::const_iterator it, ExceptionTranslators::const_iterator itEnd ) const override {
  1561. try {
  1562. if( it == itEnd )
  1563. std::rethrow_exception(std::current_exception());
  1564. else
  1565. return (*it)->translate( it+1, itEnd );
  1566. }
  1567. catch( T& ex ) {
  1568. return m_translateFunction( ex );
  1569. }
  1570. }
  1571. protected:
  1572. std::string(*m_translateFunction)( T& );
  1573. };
  1574. public:
  1575. template<typename T>
  1576. ExceptionTranslatorRegistrar( std::string(*translateFunction)( T& ) ) {
  1577. getMutableRegistryHub().registerTranslator
  1578. ( new ExceptionTranslator<T>( translateFunction ) );
  1579. }
  1580. };
  1581. }
  1582. ///////////////////////////////////////////////////////////////////////////////
  1583. #define INTERNAL_CATCH_TRANSLATE_EXCEPTION2( translatorName, signature ) \
  1584. static std::string translatorName( signature ); \
  1585. CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
  1586. namespace{ Catch::ExceptionTranslatorRegistrar INTERNAL_CATCH_UNIQUE_NAME( catch_internal_ExceptionRegistrar )( &translatorName ); } \
  1587. CATCH_INTERNAL_UNSUPPRESS_GLOBALS_WARNINGS \
  1588. static std::string translatorName( signature )
  1589. #define INTERNAL_CATCH_TRANSLATE_EXCEPTION( signature ) INTERNAL_CATCH_TRANSLATE_EXCEPTION2( INTERNAL_CATCH_UNIQUE_NAME( catch_internal_ExceptionTranslator ), signature )
  1590. // end catch_interfaces_exception.h
  1591. // start catch_approx.h
  1592. #include <type_traits>
  1593. #include <stdexcept>
  1594. namespace Catch {
  1595. namespace Detail {
  1596. class Approx {
  1597. private:
  1598. bool equalityComparisonImpl(double other) const;
  1599. public:
  1600. explicit Approx ( double value );
  1601. static Approx custom();
  1602. template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
  1603. Approx operator()( T const& value ) {
  1604. Approx approx( static_cast<double>(value) );
  1605. approx.epsilon( m_epsilon );
  1606. approx.margin( m_margin );
  1607. approx.scale( m_scale );
  1608. return approx;
  1609. }
  1610. template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
  1611. explicit Approx( T const& value ): Approx(static_cast<double>(value))
  1612. {}
  1613. template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
  1614. friend bool operator == ( const T& lhs, Approx const& rhs ) {
  1615. auto lhs_v = static_cast<double>(lhs);
  1616. return rhs.equalityComparisonImpl(lhs_v);
  1617. }
  1618. template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
  1619. friend bool operator == ( Approx const& lhs, const T& rhs ) {
  1620. return operator==( rhs, lhs );
  1621. }
  1622. template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
  1623. friend bool operator != ( T const& lhs, Approx const& rhs ) {
  1624. return !operator==( lhs, rhs );
  1625. }
  1626. template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
  1627. friend bool operator != ( Approx const& lhs, T const& rhs ) {
  1628. return !operator==( rhs, lhs );
  1629. }
  1630. template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
  1631. friend bool operator <= ( T const& lhs, Approx const& rhs ) {
  1632. return static_cast<double>(lhs) < rhs.m_value || lhs == rhs;
  1633. }
  1634. template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
  1635. friend bool operator <= ( Approx const& lhs, T const& rhs ) {
  1636. return lhs.m_value < static_cast<double>(rhs) || lhs == rhs;
  1637. }
  1638. template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
  1639. friend bool operator >= ( T const& lhs, Approx const& rhs ) {
  1640. return static_cast<double>(lhs) > rhs.m_value || lhs == rhs;
  1641. }
  1642. template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
  1643. friend bool operator >= ( Approx const& lhs, T const& rhs ) {
  1644. return lhs.m_value > static_cast<double>(rhs) || lhs == rhs;
  1645. }
  1646. template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
  1647. Approx& epsilon( T const& newEpsilon ) {
  1648. double epsilonAsDouble = static_cast<double>(newEpsilon);
  1649. if( epsilonAsDouble < 0 || epsilonAsDouble > 1.0 ) {
  1650. throw std::domain_error
  1651. ( "Invalid Approx::epsilon: " +
  1652. Catch::Detail::stringify( epsilonAsDouble ) +
  1653. ", Approx::epsilon has to be between 0 and 1" );
  1654. }
  1655. m_epsilon = epsilonAsDouble;
  1656. return *this;
  1657. }
  1658. template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
  1659. Approx& margin( T const& newMargin ) {
  1660. double marginAsDouble = static_cast<double>(newMargin);
  1661. if( marginAsDouble < 0 ) {
  1662. throw std::domain_error
  1663. ( "Invalid Approx::margin: " +
  1664. Catch::Detail::stringify( marginAsDouble ) +
  1665. ", Approx::Margin has to be non-negative." );
  1666. }
  1667. m_margin = marginAsDouble;
  1668. return *this;
  1669. }
  1670. template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
  1671. Approx& scale( T const& newScale ) {
  1672. m_scale = static_cast<double>(newScale);
  1673. return *this;
  1674. }
  1675. std::string toString() const;
  1676. private:
  1677. double m_epsilon;
  1678. double m_margin;
  1679. double m_scale;
  1680. double m_value;
  1681. };
  1682. }
  1683. template<>
  1684. struct StringMaker<Catch::Detail::Approx> {
  1685. static std::string convert(Catch::Detail::Approx const& value);
  1686. };
  1687. } // end namespace Catch
  1688. // end catch_approx.h
  1689. // start catch_string_manip.h
  1690. #include <string>
  1691. #include <iosfwd>
  1692. namespace Catch {
  1693. bool startsWith( std::string const& s, std::string const& prefix );
  1694. bool startsWith( std::string const& s, char prefix );
  1695. bool endsWith( std::string const& s, std::string const& suffix );
  1696. bool endsWith( std::string const& s, char suffix );
  1697. bool contains( std::string const& s, std::string const& infix );
  1698. void toLowerInPlace( std::string& s );
  1699. std::string toLower( std::string const& s );
  1700. std::string trim( std::string const& str );
  1701. bool replaceInPlace( std::string& str, std::string const& replaceThis, std::string const& withThis );
  1702. struct pluralise {
  1703. pluralise( std::size_t count, std::string const& label );
  1704. friend std::ostream& operator << ( std::ostream& os, pluralise const& pluraliser );
  1705. std::size_t m_count;
  1706. std::string m_label;
  1707. };
  1708. }
  1709. // end catch_string_manip.h
  1710. #ifndef CATCH_CONFIG_DISABLE_MATCHERS
  1711. // start catch_capture_matchers.h
  1712. // start catch_matchers.h
  1713. #include <string>
  1714. #include <vector>
  1715. namespace Catch {
  1716. namespace Matchers {
  1717. namespace Impl {
  1718. template<typename ArgT> struct MatchAllOf;
  1719. template<typename ArgT> struct MatchAnyOf;
  1720. template<typename ArgT> struct MatchNotOf;
  1721. class MatcherUntypedBase {
  1722. public:
  1723. MatcherUntypedBase() = default;
  1724. MatcherUntypedBase ( MatcherUntypedBase const& ) = default;
  1725. MatcherUntypedBase& operator = ( MatcherUntypedBase const& ) = delete;
  1726. std::string toString() const;
  1727. protected:
  1728. virtual ~MatcherUntypedBase();
  1729. virtual std::string describe() const = 0;
  1730. mutable std::string m_cachedToString;
  1731. };
  1732. template<typename ObjectT>
  1733. struct MatcherMethod {
  1734. virtual bool match( ObjectT const& arg ) const = 0;
  1735. };
  1736. template<typename PtrT>
  1737. struct MatcherMethod<PtrT*> {
  1738. virtual bool match( PtrT* arg ) const = 0;
  1739. };
  1740. template<typename T>
  1741. struct MatcherBase : MatcherUntypedBase, MatcherMethod<T> {
  1742. MatchAllOf<T> operator && ( MatcherBase const& other ) const;
  1743. MatchAnyOf<T> operator || ( MatcherBase const& other ) const;
  1744. MatchNotOf<T> operator ! () const;
  1745. };
  1746. template<typename ArgT>
  1747. struct MatchAllOf : MatcherBase<ArgT> {
  1748. bool match( ArgT const& arg ) const override {
  1749. for( auto matcher : m_matchers ) {
  1750. if (!matcher->match(arg))
  1751. return false;
  1752. }
  1753. return true;
  1754. }
  1755. std::string describe() const override {
  1756. std::string description;
  1757. description.reserve( 4 + m_matchers.size()*32 );
  1758. description += "( ";
  1759. bool first = true;
  1760. for( auto matcher : m_matchers ) {
  1761. if( first )
  1762. first = false;
  1763. else
  1764. description += " and ";
  1765. description += matcher->toString();
  1766. }
  1767. description += " )";
  1768. return description;
  1769. }
  1770. MatchAllOf<ArgT>& operator && ( MatcherBase<ArgT> const& other ) {
  1771. m_matchers.push_back( &other );
  1772. return *this;
  1773. }
  1774. std::vector<MatcherBase<ArgT> const*> m_matchers;
  1775. };
  1776. template<typename ArgT>
  1777. struct MatchAnyOf : MatcherBase<ArgT> {
  1778. bool match( ArgT const& arg ) const override {
  1779. for( auto matcher : m_matchers ) {
  1780. if (matcher->match(arg))
  1781. return true;
  1782. }
  1783. return false;
  1784. }
  1785. std::string describe() const override {
  1786. std::string description;
  1787. description.reserve( 4 + m_matchers.size()*32 );
  1788. description += "( ";
  1789. bool first = true;
  1790. for( auto matcher : m_matchers ) {
  1791. if( first )
  1792. first = false;
  1793. else
  1794. description += " or ";
  1795. description += matcher->toString();
  1796. }
  1797. description += " )";
  1798. return description;
  1799. }
  1800. MatchAnyOf<ArgT>& operator || ( MatcherBase<ArgT> const& other ) {
  1801. m_matchers.push_back( &other );
  1802. return *this;
  1803. }
  1804. std::vector<MatcherBase<ArgT> const*> m_matchers;
  1805. };
  1806. template<typename ArgT>
  1807. struct MatchNotOf : MatcherBase<ArgT> {
  1808. MatchNotOf( MatcherBase<ArgT> const& underlyingMatcher ) : m_underlyingMatcher( underlyingMatcher ) {}
  1809. bool match( ArgT const& arg ) const override {
  1810. return !m_underlyingMatcher.match( arg );
  1811. }
  1812. std::string describe() const override {
  1813. return "not " + m_underlyingMatcher.toString();
  1814. }
  1815. MatcherBase<ArgT> const& m_underlyingMatcher;
  1816. };
  1817. template<typename T>
  1818. MatchAllOf<T> MatcherBase<T>::operator && ( MatcherBase const& other ) const {
  1819. return MatchAllOf<T>() && *this && other;
  1820. }
  1821. template<typename T>
  1822. MatchAnyOf<T> MatcherBase<T>::operator || ( MatcherBase const& other ) const {
  1823. return MatchAnyOf<T>() || *this || other;
  1824. }
  1825. template<typename T>
  1826. MatchNotOf<T> MatcherBase<T>::operator ! () const {
  1827. return MatchNotOf<T>( *this );
  1828. }
  1829. } // namespace Impl
  1830. } // namespace Matchers
  1831. using namespace Matchers;
  1832. using Matchers::Impl::MatcherBase;
  1833. } // namespace Catch
  1834. // end catch_matchers.h
  1835. // start catch_matchers_floating.h
  1836. #include <type_traits>
  1837. #include <cmath>
  1838. namespace Catch {
  1839. namespace Matchers {
  1840. namespace Floating {
  1841. enum class FloatingPointKind : uint8_t;
  1842. struct WithinAbsMatcher : MatcherBase<double> {
  1843. WithinAbsMatcher(double target, double margin);
  1844. bool match(double const& matchee) const override;
  1845. std::string describe() const override;
  1846. private:
  1847. double m_target;
  1848. double m_margin;
  1849. };
  1850. struct WithinUlpsMatcher : MatcherBase<double> {
  1851. WithinUlpsMatcher(double target, int ulps, FloatingPointKind baseType);
  1852. bool match(double const& matchee) const override;
  1853. std::string describe() const override;
  1854. private:
  1855. double m_target;
  1856. int m_ulps;
  1857. FloatingPointKind m_type;
  1858. };
  1859. } // namespace Floating
  1860. // The following functions create the actual matcher objects.
  1861. // This allows the types to be inferred
  1862. Floating::WithinUlpsMatcher WithinULP(double target, int maxUlpDiff);
  1863. Floating::WithinUlpsMatcher WithinULP(float target, int maxUlpDiff);
  1864. Floating::WithinAbsMatcher WithinAbs(double target, double margin);
  1865. } // namespace Matchers
  1866. } // namespace Catch
  1867. // end catch_matchers_floating.h
  1868. // start catch_matchers_string.h
  1869. #include <string>
  1870. namespace Catch {
  1871. namespace Matchers {
  1872. namespace StdString {
  1873. struct CasedString
  1874. {
  1875. CasedString( std::string const& str, CaseSensitive::Choice caseSensitivity );
  1876. std::string adjustString( std::string const& str ) const;
  1877. std::string caseSensitivitySuffix() const;
  1878. CaseSensitive::Choice m_caseSensitivity;
  1879. std::string m_str;
  1880. };
  1881. struct StringMatcherBase : MatcherBase<std::string> {
  1882. StringMatcherBase( std::string const& operation, CasedString const& comparator );
  1883. std::string describe() const override;
  1884. CasedString m_comparator;
  1885. std::string m_operation;
  1886. };
  1887. struct EqualsMatcher : StringMatcherBase {
  1888. EqualsMatcher( CasedString const& comparator );
  1889. bool match( std::string const& source ) const override;
  1890. };
  1891. struct ContainsMatcher : StringMatcherBase {
  1892. ContainsMatcher( CasedString const& comparator );
  1893. bool match( std::string const& source ) const override;
  1894. };
  1895. struct StartsWithMatcher : StringMatcherBase {
  1896. StartsWithMatcher( CasedString const& comparator );
  1897. bool match( std::string const& source ) const override;
  1898. };
  1899. struct EndsWithMatcher : StringMatcherBase {
  1900. EndsWithMatcher( CasedString const& comparator );
  1901. bool match( std::string const& source ) const override;
  1902. };
  1903. struct RegexMatcher : MatcherBase<std::string> {
  1904. RegexMatcher( std::string regex, CaseSensitive::Choice caseSensitivity );
  1905. bool match( std::string const& matchee ) const override;
  1906. std::string describe() const override;
  1907. private:
  1908. std::string m_regex;
  1909. CaseSensitive::Choice m_caseSensitivity;
  1910. };
  1911. } // namespace StdString
  1912. // The following functions create the actual matcher objects.
  1913. // This allows the types to be inferred
  1914. StdString::EqualsMatcher Equals( std::string const& str, CaseSensitive::Choice caseSensitivity = CaseSensitive::Yes );
  1915. StdString::ContainsMatcher Contains( std::string const& str, CaseSensitive::Choice caseSensitivity = CaseSensitive::Yes );
  1916. StdString::EndsWithMatcher EndsWith( std::string const& str, CaseSensitive::Choice caseSensitivity = CaseSensitive::Yes );
  1917. StdString::StartsWithMatcher StartsWith( std::string const& str, CaseSensitive::Choice caseSensitivity = CaseSensitive::Yes );
  1918. StdString::RegexMatcher Matches( std::string const& regex, CaseSensitive::Choice caseSensitivity = CaseSensitive::Yes );
  1919. } // namespace Matchers
  1920. } // namespace Catch
  1921. // end catch_matchers_string.h
  1922. // start catch_matchers_vector.h
  1923. #include <algorithm>
  1924. namespace Catch {
  1925. namespace Matchers {
  1926. namespace Vector {
  1927. namespace Detail {
  1928. template <typename InputIterator, typename T>
  1929. size_t count(InputIterator first, InputIterator last, T const& item) {
  1930. size_t cnt = 0;
  1931. for (; first != last; ++first) {
  1932. if (*first == item) {
  1933. ++cnt;
  1934. }
  1935. }
  1936. return cnt;
  1937. }
  1938. template <typename InputIterator, typename T>
  1939. bool contains(InputIterator first, InputIterator last, T const& item) {
  1940. for (; first != last; ++first) {
  1941. if (*first == item) {
  1942. return true;
  1943. }
  1944. }
  1945. return false;
  1946. }
  1947. }
  1948. template<typename T>
  1949. struct ContainsElementMatcher : MatcherBase<std::vector<T>> {
  1950. ContainsElementMatcher(T const &comparator) : m_comparator( comparator) {}
  1951. bool match(std::vector<T> const &v) const override {
  1952. for (auto const& el : v) {
  1953. if (el == m_comparator) {
  1954. return true;
  1955. }
  1956. }
  1957. return false;
  1958. }
  1959. std::string describe() const override {
  1960. return "Contains: " + ::Catch::Detail::stringify( m_comparator );
  1961. }
  1962. T const& m_comparator;
  1963. };
  1964. template<typename T>
  1965. struct ContainsMatcher : MatcherBase<std::vector<T>> {
  1966. ContainsMatcher(std::vector<T> const &comparator) : m_comparator( comparator ) {}
  1967. bool match(std::vector<T> const &v) const override {
  1968. // !TBD: see note in EqualsMatcher
  1969. if (m_comparator.size() > v.size())
  1970. return false;
  1971. for (auto const& comparator : m_comparator) {
  1972. auto present = false;
  1973. for (const auto& el : v) {
  1974. if (el == comparator) {
  1975. present = true;
  1976. break;
  1977. }
  1978. }
  1979. if (!present) {
  1980. return false;
  1981. }
  1982. }
  1983. return true;
  1984. }
  1985. std::string describe() const override {
  1986. return "Contains: " + ::Catch::Detail::stringify( m_comparator );
  1987. }
  1988. std::vector<T> const& m_comparator;
  1989. };
  1990. template<typename T>
  1991. struct EqualsMatcher : MatcherBase<std::vector<T>> {
  1992. EqualsMatcher(std::vector<T> const &comparator) : m_comparator( comparator ) {}
  1993. bool match(std::vector<T> const &v) const override {
  1994. // !TBD: This currently works if all elements can be compared using !=
  1995. // - a more general approach would be via a compare template that defaults
  1996. // to using !=. but could be specialised for, e.g. std::vector<T> etc
  1997. // - then just call that directly
  1998. if (m_comparator.size() != v.size())
  1999. return false;
  2000. for (std::size_t i = 0; i < v.size(); ++i)
  2001. if (m_comparator[i] != v[i])
  2002. return false;
  2003. return true;
  2004. }
  2005. std::string describe() const override {
  2006. return "Equals: " + ::Catch::Detail::stringify( m_comparator );
  2007. }
  2008. std::vector<T> const& m_comparator;
  2009. };
  2010. template<typename T>
  2011. struct UnorderedEqualsMatcher : MatcherBase<std::vector<T>> {
  2012. UnorderedEqualsMatcher(std::vector<T> const& target) : m_target(target) {}
  2013. bool match(std::vector<T> const& vec) const override {
  2014. // Note: This is a reimplementation of std::is_permutation,
  2015. // because I don't want to include <algorithm> inside the common path
  2016. if (m_target.size() != vec.size()) {
  2017. return false;
  2018. }
  2019. auto lfirst = m_target.begin(), llast = m_target.end();
  2020. auto rfirst = vec.begin(), rlast = vec.end();
  2021. // Cut common prefix to optimize checking of permuted parts
  2022. while (lfirst != llast && *lfirst != *rfirst) {
  2023. ++lfirst; ++rfirst;
  2024. }
  2025. if (lfirst == llast) {
  2026. return true;
  2027. }
  2028. for (auto mid = lfirst; mid != llast; ++mid) {
  2029. // Skip already counted items
  2030. if (Detail::contains(lfirst, mid, *mid)) {
  2031. continue;
  2032. }
  2033. size_t num_vec = Detail::count(rfirst, rlast, *mid);
  2034. if (num_vec == 0 || Detail::count(lfirst, llast, *mid) != num_vec) {
  2035. return false;
  2036. }
  2037. }
  2038. return true;
  2039. }
  2040. std::string describe() const override {
  2041. return "UnorderedEquals: " + ::Catch::Detail::stringify(m_target);
  2042. }
  2043. private:
  2044. std::vector<T> const& m_target;
  2045. };
  2046. } // namespace Vector
  2047. // The following functions create the actual matcher objects.
  2048. // This allows the types to be inferred
  2049. template<typename T>
  2050. Vector::ContainsMatcher<T> Contains( std::vector<T> const& comparator ) {
  2051. return Vector::ContainsMatcher<T>( comparator );
  2052. }
  2053. template<typename T>
  2054. Vector::ContainsElementMatcher<T> VectorContains( T const& comparator ) {
  2055. return Vector::ContainsElementMatcher<T>( comparator );
  2056. }
  2057. template<typename T>
  2058. Vector::EqualsMatcher<T> Equals( std::vector<T> const& comparator ) {
  2059. return Vector::EqualsMatcher<T>( comparator );
  2060. }
  2061. template<typename T>
  2062. Vector::UnorderedEqualsMatcher<T> UnorderedEquals(std::vector<T> const& target) {
  2063. return Vector::UnorderedEqualsMatcher<T>(target);
  2064. }
  2065. } // namespace Matchers
  2066. } // namespace Catch
  2067. // end catch_matchers_vector.h
  2068. namespace Catch {
  2069. template<typename ArgT, typename MatcherT>
  2070. class MatchExpr : public ITransientExpression {
  2071. ArgT const& m_arg;
  2072. MatcherT m_matcher;
  2073. StringRef m_matcherString;
  2074. public:
  2075. MatchExpr( ArgT const& arg, MatcherT const& matcher, StringRef matcherString )
  2076. : ITransientExpression{ true, matcher.match( arg ) },
  2077. m_arg( arg ),
  2078. m_matcher( matcher ),
  2079. m_matcherString( matcherString )
  2080. {}
  2081. void streamReconstructedExpression( std::ostream &os ) const override {
  2082. auto matcherAsString = m_matcher.toString();
  2083. os << Catch::Detail::stringify( m_arg ) << ' ';
  2084. if( matcherAsString == Detail::unprintableString )
  2085. os << m_matcherString;
  2086. else
  2087. os << matcherAsString;
  2088. }
  2089. };
  2090. using StringMatcher = Matchers::Impl::MatcherBase<std::string>;
  2091. void handleExceptionMatchExpr( AssertionHandler& handler, StringMatcher const& matcher, StringRef matcherString );
  2092. template<typename ArgT, typename MatcherT>
  2093. auto makeMatchExpr( ArgT const& arg, MatcherT const& matcher, StringRef matcherString ) -> MatchExpr<ArgT, MatcherT> {
  2094. return MatchExpr<ArgT, MatcherT>( arg, matcher, matcherString );
  2095. }
  2096. } // namespace Catch
  2097. ///////////////////////////////////////////////////////////////////////////////
  2098. #define INTERNAL_CHECK_THAT( macroName, matcher, resultDisposition, arg ) \
  2099. do { \
  2100. Catch::AssertionHandler catchAssertionHandler( macroName, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(arg) ", " CATCH_INTERNAL_STRINGIFY(matcher), resultDisposition ); \
  2101. INTERNAL_CATCH_TRY { \
  2102. catchAssertionHandler.handleExpr( Catch::makeMatchExpr( arg, matcher, #matcher ) ); \
  2103. } INTERNAL_CATCH_CATCH( catchAssertionHandler ) \
  2104. INTERNAL_CATCH_REACT( catchAssertionHandler ) \
  2105. } while( false )
  2106. ///////////////////////////////////////////////////////////////////////////////
  2107. #define INTERNAL_CATCH_THROWS_MATCHES( macroName, exceptionType, resultDisposition, matcher, ... ) \
  2108. do { \
  2109. Catch::AssertionHandler catchAssertionHandler( macroName, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(__VA_ARGS__) ", " CATCH_INTERNAL_STRINGIFY(exceptionType) ", " CATCH_INTERNAL_STRINGIFY(matcher), resultDisposition ); \
  2110. if( catchAssertionHandler.allowThrows() ) \
  2111. try { \
  2112. static_cast<void>(__VA_ARGS__ ); \
  2113. catchAssertionHandler.handleUnexpectedExceptionNotThrown(); \
  2114. } \
  2115. catch( exceptionType const& ex ) { \
  2116. catchAssertionHandler.handleExpr( Catch::makeMatchExpr( ex, matcher, #matcher ) ); \
  2117. } \
  2118. catch( ... ) { \
  2119. catchAssertionHandler.handleUnexpectedInflightException(); \
  2120. } \
  2121. else \
  2122. catchAssertionHandler.handleThrowingCallSkipped(); \
  2123. INTERNAL_CATCH_REACT( catchAssertionHandler ) \
  2124. } while( false )
  2125. // end catch_capture_matchers.h
  2126. #endif
  2127. // These files are included here so the single_include script doesn't put them
  2128. // in the conditionally compiled sections
  2129. // start catch_test_case_info.h
  2130. #include <string>
  2131. #include <vector>
  2132. #include <memory>
  2133. #ifdef __clang__
  2134. #pragma clang diagnostic push
  2135. #pragma clang diagnostic ignored "-Wpadded"
  2136. #endif
  2137. namespace Catch {
  2138. struct ITestInvoker;
  2139. struct TestCaseInfo {
  2140. enum SpecialProperties{
  2141. None = 0,
  2142. IsHidden = 1 << 1,
  2143. ShouldFail = 1 << 2,
  2144. MayFail = 1 << 3,
  2145. Throws = 1 << 4,
  2146. NonPortable = 1 << 5,
  2147. Benchmark = 1 << 6
  2148. };
  2149. TestCaseInfo( std::string const& _name,
  2150. std::string const& _className,
  2151. std::string const& _description,
  2152. std::vector<std::string> const& _tags,
  2153. SourceLineInfo const& _lineInfo );
  2154. friend void setTags( TestCaseInfo& testCaseInfo, std::vector<std::string> tags );
  2155. bool isHidden() const;
  2156. bool throws() const;
  2157. bool okToFail() const;
  2158. bool expectedToFail() const;
  2159. std::string tagsAsString() const;
  2160. std::string name;
  2161. std::string className;
  2162. std::string description;
  2163. std::vector<std::string> tags;
  2164. std::vector<std::string> lcaseTags;
  2165. SourceLineInfo lineInfo;
  2166. SpecialProperties properties;
  2167. };
  2168. class TestCase : public TestCaseInfo {
  2169. public:
  2170. TestCase( ITestInvoker* testCase, TestCaseInfo const& info );
  2171. TestCase withName( std::string const& _newName ) const;
  2172. void invoke() const;
  2173. TestCaseInfo const& getTestCaseInfo() const;
  2174. bool operator == ( TestCase const& other ) const;
  2175. bool operator < ( TestCase const& other ) const;
  2176. private:
  2177. std::shared_ptr<ITestInvoker> test;
  2178. };
  2179. TestCase makeTestCase( ITestInvoker* testCase,
  2180. std::string const& className,
  2181. std::string const& name,
  2182. std::string const& description,
  2183. SourceLineInfo const& lineInfo );
  2184. }
  2185. #ifdef __clang__
  2186. #pragma clang diagnostic pop
  2187. #endif
  2188. // end catch_test_case_info.h
  2189. // start catch_interfaces_runner.h
  2190. namespace Catch {
  2191. struct IRunner {
  2192. virtual ~IRunner();
  2193. virtual bool aborting() const = 0;
  2194. };
  2195. }
  2196. // end catch_interfaces_runner.h
  2197. #ifdef __OBJC__
  2198. // start catch_objc.hpp
  2199. #import <objc/runtime.h>
  2200. #include <string>
  2201. // NB. Any general catch headers included here must be included
  2202. // in catch.hpp first to make sure they are included by the single
  2203. // header for non obj-usage
  2204. ///////////////////////////////////////////////////////////////////////////////
  2205. // This protocol is really only here for (self) documenting purposes, since
  2206. // all its methods are optional.
  2207. @protocol OcFixture
  2208. @optional
  2209. -(void) setUp;
  2210. -(void) tearDown;
  2211. @end
  2212. namespace Catch {
  2213. class OcMethod : public ITestInvoker {
  2214. public:
  2215. OcMethod( Class cls, SEL sel ) : m_cls( cls ), m_sel( sel ) {}
  2216. virtual void invoke() const {
  2217. id obj = [[m_cls alloc] init];
  2218. performOptionalSelector( obj, @selector(setUp) );
  2219. performOptionalSelector( obj, m_sel );
  2220. performOptionalSelector( obj, @selector(tearDown) );
  2221. arcSafeRelease( obj );
  2222. }
  2223. private:
  2224. virtual ~OcMethod() {}
  2225. Class m_cls;
  2226. SEL m_sel;
  2227. };
  2228. namespace Detail{
  2229. inline std::string getAnnotation( Class cls,
  2230. std::string const& annotationName,
  2231. std::string const& testCaseName ) {
  2232. NSString* selStr = [[NSString alloc] initWithFormat:@"Catch_%s_%s", annotationName.c_str(), testCaseName.c_str()];
  2233. SEL sel = NSSelectorFromString( selStr );
  2234. arcSafeRelease( selStr );
  2235. id value = performOptionalSelector( cls, sel );
  2236. if( value )
  2237. return [(NSString*)value UTF8String];
  2238. return "";
  2239. }
  2240. }
  2241. inline std::size_t registerTestMethods() {
  2242. std::size_t noTestMethods = 0;
  2243. int noClasses = objc_getClassList( nullptr, 0 );
  2244. Class* classes = (CATCH_UNSAFE_UNRETAINED Class *)malloc( sizeof(Class) * noClasses);
  2245. objc_getClassList( classes, noClasses );
  2246. for( int c = 0; c < noClasses; c++ ) {
  2247. Class cls = classes[c];
  2248. {
  2249. u_int count;
  2250. Method* methods = class_copyMethodList( cls, &count );
  2251. for( u_int m = 0; m < count ; m++ ) {
  2252. SEL selector = method_getName(methods[m]);
  2253. std::string methodName = sel_getName(selector);
  2254. if( startsWith( methodName, "Catch_TestCase_" ) ) {
  2255. std::string testCaseName = methodName.substr( 15 );
  2256. std::string name = Detail::getAnnotation( cls, "Name", testCaseName );
  2257. std::string desc = Detail::getAnnotation( cls, "Description", testCaseName );
  2258. const char* className = class_getName( cls );
  2259. getMutableRegistryHub().registerTest( makeTestCase( new OcMethod( cls, selector ), className, name.c_str(), desc.c_str(), SourceLineInfo("",0) ) );
  2260. noTestMethods++;
  2261. }
  2262. }
  2263. free(methods);
  2264. }
  2265. }
  2266. return noTestMethods;
  2267. }
  2268. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  2269. namespace Matchers {
  2270. namespace Impl {
  2271. namespace NSStringMatchers {
  2272. struct StringHolder : MatcherBase<NSString*>{
  2273. StringHolder( NSString* substr ) : m_substr( [substr copy] ){}
  2274. StringHolder( StringHolder const& other ) : m_substr( [other.m_substr copy] ){}
  2275. StringHolder() {
  2276. arcSafeRelease( m_substr );
  2277. }
  2278. bool match( NSString* arg ) const override {
  2279. return false;
  2280. }
  2281. NSString* CATCH_ARC_STRONG m_substr;
  2282. };
  2283. struct Equals : StringHolder {
  2284. Equals( NSString* substr ) : StringHolder( substr ){}
  2285. bool match( NSString* str ) const override {
  2286. return (str != nil || m_substr == nil ) &&
  2287. [str isEqualToString:m_substr];
  2288. }
  2289. std::string describe() const override {
  2290. return "equals string: " + Catch::Detail::stringify( m_substr );
  2291. }
  2292. };
  2293. struct Contains : StringHolder {
  2294. Contains( NSString* substr ) : StringHolder( substr ){}
  2295. bool match( NSString* str ) const {
  2296. return (str != nil || m_substr == nil ) &&
  2297. [str rangeOfString:m_substr].location != NSNotFound;
  2298. }
  2299. std::string describe() const override {
  2300. return "contains string: " + Catch::Detail::stringify( m_substr );
  2301. }
  2302. };
  2303. struct StartsWith : StringHolder {
  2304. StartsWith( NSString* substr ) : StringHolder( substr ){}
  2305. bool match( NSString* str ) const override {
  2306. return (str != nil || m_substr == nil ) &&
  2307. [str rangeOfString:m_substr].location == 0;
  2308. }
  2309. std::string describe() const override {
  2310. return "starts with: " + Catch::Detail::stringify( m_substr );
  2311. }
  2312. };
  2313. struct EndsWith : StringHolder {
  2314. EndsWith( NSString* substr ) : StringHolder( substr ){}
  2315. bool match( NSString* str ) const override {
  2316. return (str != nil || m_substr == nil ) &&
  2317. [str rangeOfString:m_substr].location == [str length] - [m_substr length];
  2318. }
  2319. std::string describe() const override {
  2320. return "ends with: " + Catch::Detail::stringify( m_substr );
  2321. }
  2322. };
  2323. } // namespace NSStringMatchers
  2324. } // namespace Impl
  2325. inline Impl::NSStringMatchers::Equals
  2326. Equals( NSString* substr ){ return Impl::NSStringMatchers::Equals( substr ); }
  2327. inline Impl::NSStringMatchers::Contains
  2328. Contains( NSString* substr ){ return Impl::NSStringMatchers::Contains( substr ); }
  2329. inline Impl::NSStringMatchers::StartsWith
  2330. StartsWith( NSString* substr ){ return Impl::NSStringMatchers::StartsWith( substr ); }
  2331. inline Impl::NSStringMatchers::EndsWith
  2332. EndsWith( NSString* substr ){ return Impl::NSStringMatchers::EndsWith( substr ); }
  2333. } // namespace Matchers
  2334. using namespace Matchers;
  2335. #endif // CATCH_CONFIG_DISABLE_MATCHERS
  2336. } // namespace Catch
  2337. ///////////////////////////////////////////////////////////////////////////////
  2338. #define OC_MAKE_UNIQUE_NAME( root, uniqueSuffix ) root##uniqueSuffix
  2339. #define OC_TEST_CASE2( name, desc, uniqueSuffix ) \
  2340. +(NSString*) OC_MAKE_UNIQUE_NAME( Catch_Name_test_, uniqueSuffix ) \
  2341. { \
  2342. return @ name; \
  2343. } \
  2344. +(NSString*) OC_MAKE_UNIQUE_NAME( Catch_Description_test_, uniqueSuffix ) \
  2345. { \
  2346. return @ desc; \
  2347. } \
  2348. -(void) OC_MAKE_UNIQUE_NAME( Catch_TestCase_test_, uniqueSuffix )
  2349. #define OC_TEST_CASE( name, desc ) OC_TEST_CASE2( name, desc, __LINE__ )
  2350. // end catch_objc.hpp
  2351. #endif
  2352. #ifdef CATCH_CONFIG_EXTERNAL_INTERFACES
  2353. // start catch_external_interfaces.h
  2354. // start catch_reporter_bases.hpp
  2355. // start catch_interfaces_reporter.h
  2356. // start catch_config.hpp
  2357. // start catch_test_spec_parser.h
  2358. #ifdef __clang__
  2359. #pragma clang diagnostic push
  2360. #pragma clang diagnostic ignored "-Wpadded"
  2361. #endif
  2362. // start catch_test_spec.h
  2363. #ifdef __clang__
  2364. #pragma clang diagnostic push
  2365. #pragma clang diagnostic ignored "-Wpadded"
  2366. #endif
  2367. // start catch_wildcard_pattern.h
  2368. namespace Catch
  2369. {
  2370. class WildcardPattern {
  2371. enum WildcardPosition {
  2372. NoWildcard = 0,
  2373. WildcardAtStart = 1,
  2374. WildcardAtEnd = 2,
  2375. WildcardAtBothEnds = WildcardAtStart | WildcardAtEnd
  2376. };
  2377. public:
  2378. WildcardPattern( std::string const& pattern, CaseSensitive::Choice caseSensitivity );
  2379. virtual ~WildcardPattern() = default;
  2380. virtual bool matches( std::string const& str ) const;
  2381. private:
  2382. std::string adjustCase( std::string const& str ) const;
  2383. CaseSensitive::Choice m_caseSensitivity;
  2384. WildcardPosition m_wildcard = NoWildcard;
  2385. std::string m_pattern;
  2386. };
  2387. }
  2388. // end catch_wildcard_pattern.h
  2389. #include <string>
  2390. #include <vector>
  2391. #include <memory>
  2392. namespace Catch {
  2393. class TestSpec {
  2394. struct Pattern {
  2395. virtual ~Pattern();
  2396. virtual bool matches( TestCaseInfo const& testCase ) const = 0;
  2397. };
  2398. using PatternPtr = std::shared_ptr<Pattern>;
  2399. class NamePattern : public Pattern {
  2400. public:
  2401. NamePattern( std::string const& name );
  2402. virtual ~NamePattern();
  2403. virtual bool matches( TestCaseInfo const& testCase ) const override;
  2404. private:
  2405. WildcardPattern m_wildcardPattern;
  2406. };
  2407. class TagPattern : public Pattern {
  2408. public:
  2409. TagPattern( std::string const& tag );
  2410. virtual ~TagPattern();
  2411. virtual bool matches( TestCaseInfo const& testCase ) const override;
  2412. private:
  2413. std::string m_tag;
  2414. };
  2415. class ExcludedPattern : public Pattern {
  2416. public:
  2417. ExcludedPattern( PatternPtr const& underlyingPattern );
  2418. virtual ~ExcludedPattern();
  2419. virtual bool matches( TestCaseInfo const& testCase ) const override;
  2420. private:
  2421. PatternPtr m_underlyingPattern;
  2422. };
  2423. struct Filter {
  2424. std::vector<PatternPtr> m_patterns;
  2425. bool matches( TestCaseInfo const& testCase ) const;
  2426. };
  2427. public:
  2428. bool hasFilters() const;
  2429. bool matches( TestCaseInfo const& testCase ) const;
  2430. private:
  2431. std::vector<Filter> m_filters;
  2432. friend class TestSpecParser;
  2433. };
  2434. }
  2435. #ifdef __clang__
  2436. #pragma clang diagnostic pop
  2437. #endif
  2438. // end catch_test_spec.h
  2439. // start catch_interfaces_tag_alias_registry.h
  2440. #include <string>
  2441. namespace Catch {
  2442. struct TagAlias;
  2443. struct ITagAliasRegistry {
  2444. virtual ~ITagAliasRegistry();
  2445. // Nullptr if not present
  2446. virtual TagAlias const* find( std::string const& alias ) const = 0;
  2447. virtual std::string expandAliases( std::string const& unexpandedTestSpec ) const = 0;
  2448. static ITagAliasRegistry const& get();
  2449. };
  2450. } // end namespace Catch
  2451. // end catch_interfaces_tag_alias_registry.h
  2452. namespace Catch {
  2453. class TestSpecParser {
  2454. enum Mode{ None, Name, QuotedName, Tag, EscapedName };
  2455. Mode m_mode = None;
  2456. bool m_exclusion = false;
  2457. std::size_t m_start = std::string::npos, m_pos = 0;
  2458. std::string m_arg;
  2459. std::vector<std::size_t> m_escapeChars;
  2460. TestSpec::Filter m_currentFilter;
  2461. TestSpec m_testSpec;
  2462. ITagAliasRegistry const* m_tagAliases = nullptr;
  2463. public:
  2464. TestSpecParser( ITagAliasRegistry const& tagAliases );
  2465. TestSpecParser& parse( std::string const& arg );
  2466. TestSpec testSpec();
  2467. private:
  2468. void visitChar( char c );
  2469. void startNewMode( Mode mode, std::size_t start );
  2470. void escape();
  2471. std::string subString() const;
  2472. template<typename T>
  2473. void addPattern() {
  2474. std::string token = subString();
  2475. for( std::size_t i = 0; i < m_escapeChars.size(); ++i )
  2476. token = token.substr( 0, m_escapeChars[i]-m_start-i ) + token.substr( m_escapeChars[i]-m_start-i+1 );
  2477. m_escapeChars.clear();
  2478. if( startsWith( token, "exclude:" ) ) {
  2479. m_exclusion = true;
  2480. token = token.substr( 8 );
  2481. }
  2482. if( !token.empty() ) {
  2483. TestSpec::PatternPtr pattern = std::make_shared<T>( token );
  2484. if( m_exclusion )
  2485. pattern = std::make_shared<TestSpec::ExcludedPattern>( pattern );
  2486. m_currentFilter.m_patterns.push_back( pattern );
  2487. }
  2488. m_exclusion = false;
  2489. m_mode = None;
  2490. }
  2491. void addFilter();
  2492. };
  2493. TestSpec parseTestSpec( std::string const& arg );
  2494. } // namespace Catch
  2495. #ifdef __clang__
  2496. #pragma clang diagnostic pop
  2497. #endif
  2498. // end catch_test_spec_parser.h
  2499. // start catch_interfaces_config.h
  2500. #include <iosfwd>
  2501. #include <string>
  2502. #include <vector>
  2503. #include <memory>
  2504. namespace Catch {
  2505. enum class Verbosity {
  2506. Quiet = 0,
  2507. Normal,
  2508. High
  2509. };
  2510. struct WarnAbout { enum What {
  2511. Nothing = 0x00,
  2512. NoAssertions = 0x01
  2513. }; };
  2514. struct ShowDurations { enum OrNot {
  2515. DefaultForReporter,
  2516. Always,
  2517. Never
  2518. }; };
  2519. struct RunTests { enum InWhatOrder {
  2520. InDeclarationOrder,
  2521. InLexicographicalOrder,
  2522. InRandomOrder
  2523. }; };
  2524. struct UseColour { enum YesOrNo {
  2525. Auto,
  2526. Yes,
  2527. No
  2528. }; };
  2529. struct WaitForKeypress { enum When {
  2530. Never,
  2531. BeforeStart = 1,
  2532. BeforeExit = 2,
  2533. BeforeStartAndExit = BeforeStart | BeforeExit
  2534. }; };
  2535. class TestSpec;
  2536. struct IConfig : NonCopyable {
  2537. virtual ~IConfig();
  2538. virtual bool allowThrows() const = 0;
  2539. virtual std::ostream& stream() const = 0;
  2540. virtual std::string name() const = 0;
  2541. virtual bool includeSuccessfulResults() const = 0;
  2542. virtual bool shouldDebugBreak() const = 0;
  2543. virtual bool warnAboutMissingAssertions() const = 0;
  2544. virtual int abortAfter() const = 0;
  2545. virtual bool showInvisibles() const = 0;
  2546. virtual ShowDurations::OrNot showDurations() const = 0;
  2547. virtual TestSpec const& testSpec() const = 0;
  2548. virtual RunTests::InWhatOrder runOrder() const = 0;
  2549. virtual unsigned int rngSeed() const = 0;
  2550. virtual int benchmarkResolutionMultiple() const = 0;
  2551. virtual UseColour::YesOrNo useColour() const = 0;
  2552. virtual std::vector<std::string> const& getSectionsToRun() const = 0;
  2553. virtual Verbosity verbosity() const = 0;
  2554. };
  2555. using IConfigPtr = std::shared_ptr<IConfig const>;
  2556. }
  2557. // end catch_interfaces_config.h
  2558. // Libstdc++ doesn't like incomplete classes for unique_ptr
  2559. #include <memory>
  2560. #include <vector>
  2561. #include <string>
  2562. #ifndef CATCH_CONFIG_CONSOLE_WIDTH
  2563. #define CATCH_CONFIG_CONSOLE_WIDTH 80
  2564. #endif
  2565. namespace Catch {
  2566. struct IStream;
  2567. struct ConfigData {
  2568. bool listTests = false;
  2569. bool listTags = false;
  2570. bool listReporters = false;
  2571. bool listTestNamesOnly = false;
  2572. bool showSuccessfulTests = false;
  2573. bool shouldDebugBreak = false;
  2574. bool noThrow = false;
  2575. bool showHelp = false;
  2576. bool showInvisibles = false;
  2577. bool filenamesAsTags = false;
  2578. bool libIdentify = false;
  2579. int abortAfter = -1;
  2580. unsigned int rngSeed = 0;
  2581. int benchmarkResolutionMultiple = 100;
  2582. Verbosity verbosity = Verbosity::Normal;
  2583. WarnAbout::What warnings = WarnAbout::Nothing;
  2584. ShowDurations::OrNot showDurations = ShowDurations::DefaultForReporter;
  2585. RunTests::InWhatOrder runOrder = RunTests::InDeclarationOrder;
  2586. UseColour::YesOrNo useColour = UseColour::Auto;
  2587. WaitForKeypress::When waitForKeypress = WaitForKeypress::Never;
  2588. std::string outputFilename;
  2589. std::string name;
  2590. std::string processName;
  2591. std::vector<std::string> reporterNames;
  2592. std::vector<std::string> testsOrTags;
  2593. std::vector<std::string> sectionsToRun;
  2594. };
  2595. class Config : public IConfig {
  2596. public:
  2597. Config() = default;
  2598. Config( ConfigData const& data );
  2599. virtual ~Config() = default;
  2600. std::string const& getFilename() const;
  2601. bool listTests() const;
  2602. bool listTestNamesOnly() const;
  2603. bool listTags() const;
  2604. bool listReporters() const;
  2605. std::string getProcessName() const;
  2606. std::vector<std::string> const& getReporterNames() const;
  2607. std::vector<std::string> const& getSectionsToRun() const override;
  2608. virtual TestSpec const& testSpec() const override;
  2609. bool showHelp() const;
  2610. // IConfig interface
  2611. bool allowThrows() const override;
  2612. std::ostream& stream() const override;
  2613. std::string name() const override;
  2614. bool includeSuccessfulResults() const override;
  2615. bool warnAboutMissingAssertions() const override;
  2616. ShowDurations::OrNot showDurations() const override;
  2617. RunTests::InWhatOrder runOrder() const override;
  2618. unsigned int rngSeed() const override;
  2619. int benchmarkResolutionMultiple() const override;
  2620. UseColour::YesOrNo useColour() const override;
  2621. bool shouldDebugBreak() const override;
  2622. int abortAfter() const override;
  2623. bool showInvisibles() const override;
  2624. Verbosity verbosity() const override;
  2625. private:
  2626. IStream const* openStream();
  2627. ConfigData m_data;
  2628. std::unique_ptr<IStream const> m_stream;
  2629. TestSpec m_testSpec;
  2630. };
  2631. } // end namespace Catch
  2632. // end catch_config.hpp
  2633. // start catch_assertionresult.h
  2634. #include <string>
  2635. namespace Catch {
  2636. struct AssertionResultData
  2637. {
  2638. AssertionResultData() = delete;
  2639. AssertionResultData( ResultWas::OfType _resultType, LazyExpression const& _lazyExpression );
  2640. std::string message;
  2641. mutable std::string reconstructedExpression;
  2642. LazyExpression lazyExpression;
  2643. ResultWas::OfType resultType;
  2644. std::string reconstructExpression() const;
  2645. };
  2646. class AssertionResult {
  2647. public:
  2648. AssertionResult() = delete;
  2649. AssertionResult( AssertionInfo const& info, AssertionResultData const& data );
  2650. bool isOk() const;
  2651. bool succeeded() const;
  2652. ResultWas::OfType getResultType() const;
  2653. bool hasExpression() const;
  2654. bool hasMessage() const;
  2655. std::string getExpression() const;
  2656. std::string getExpressionInMacro() const;
  2657. bool hasExpandedExpression() const;
  2658. std::string getExpandedExpression() const;
  2659. std::string getMessage() const;
  2660. SourceLineInfo getSourceInfo() const;
  2661. StringRef getTestMacroName() const;
  2662. //protected:
  2663. AssertionInfo m_info;
  2664. AssertionResultData m_resultData;
  2665. };
  2666. } // end namespace Catch
  2667. // end catch_assertionresult.h
  2668. // start catch_option.hpp
  2669. namespace Catch {
  2670. // An optional type
  2671. template<typename T>
  2672. class Option {
  2673. public:
  2674. Option() : nullableValue( nullptr ) {}
  2675. Option( T const& _value )
  2676. : nullableValue( new( storage ) T( _value ) )
  2677. {}
  2678. Option( Option const& _other )
  2679. : nullableValue( _other ? new( storage ) T( *_other ) : nullptr )
  2680. {}
  2681. ~Option() {
  2682. reset();
  2683. }
  2684. Option& operator= ( Option const& _other ) {
  2685. if( &_other != this ) {
  2686. reset();
  2687. if( _other )
  2688. nullableValue = new( storage ) T( *_other );
  2689. }
  2690. return *this;
  2691. }
  2692. Option& operator = ( T const& _value ) {
  2693. reset();
  2694. nullableValue = new( storage ) T( _value );
  2695. return *this;
  2696. }
  2697. void reset() {
  2698. if( nullableValue )
  2699. nullableValue->~T();
  2700. nullableValue = nullptr;
  2701. }
  2702. T& operator*() { return *nullableValue; }
  2703. T const& operator*() const { return *nullableValue; }
  2704. T* operator->() { return nullableValue; }
  2705. const T* operator->() const { return nullableValue; }
  2706. T valueOr( T const& defaultValue ) const {
  2707. return nullableValue ? *nullableValue : defaultValue;
  2708. }
  2709. bool some() const { return nullableValue != nullptr; }
  2710. bool none() const { return nullableValue == nullptr; }
  2711. bool operator !() const { return nullableValue == nullptr; }
  2712. explicit operator bool() const {
  2713. return some();
  2714. }
  2715. private:
  2716. T *nullableValue;
  2717. alignas(alignof(T)) char storage[sizeof(T)];
  2718. };
  2719. } // end namespace Catch
  2720. // end catch_option.hpp
  2721. #include <string>
  2722. #include <iosfwd>
  2723. #include <map>
  2724. #include <set>
  2725. #include <memory>
  2726. namespace Catch {
  2727. struct ReporterConfig {
  2728. explicit ReporterConfig( IConfigPtr const& _fullConfig );
  2729. ReporterConfig( IConfigPtr const& _fullConfig, std::ostream& _stream );
  2730. std::ostream& stream() const;
  2731. IConfigPtr fullConfig() const;
  2732. private:
  2733. std::ostream* m_stream;
  2734. IConfigPtr m_fullConfig;
  2735. };
  2736. struct ReporterPreferences {
  2737. bool shouldRedirectStdOut = false;
  2738. };
  2739. template<typename T>
  2740. struct LazyStat : Option<T> {
  2741. LazyStat& operator=( T const& _value ) {
  2742. Option<T>::operator=( _value );
  2743. used = false;
  2744. return *this;
  2745. }
  2746. void reset() {
  2747. Option<T>::reset();
  2748. used = false;
  2749. }
  2750. bool used = false;
  2751. };
  2752. struct TestRunInfo {
  2753. TestRunInfo( std::string const& _name );
  2754. std::string name;
  2755. };
  2756. struct GroupInfo {
  2757. GroupInfo( std::string const& _name,
  2758. std::size_t _groupIndex,
  2759. std::size_t _groupsCount );
  2760. std::string name;
  2761. std::size_t groupIndex;
  2762. std::size_t groupsCounts;
  2763. };
  2764. struct AssertionStats {
  2765. AssertionStats( AssertionResult const& _assertionResult,
  2766. std::vector<MessageInfo> const& _infoMessages,
  2767. Totals const& _totals );
  2768. AssertionStats( AssertionStats const& ) = default;
  2769. AssertionStats( AssertionStats && ) = default;
  2770. AssertionStats& operator = ( AssertionStats const& ) = default;
  2771. AssertionStats& operator = ( AssertionStats && ) = default;
  2772. virtual ~AssertionStats();
  2773. AssertionResult assertionResult;
  2774. std::vector<MessageInfo> infoMessages;
  2775. Totals totals;
  2776. };
  2777. struct SectionStats {
  2778. SectionStats( SectionInfo const& _sectionInfo,
  2779. Counts const& _assertions,
  2780. double _durationInSeconds,
  2781. bool _missingAssertions );
  2782. SectionStats( SectionStats const& ) = default;
  2783. SectionStats( SectionStats && ) = default;
  2784. SectionStats& operator = ( SectionStats const& ) = default;
  2785. SectionStats& operator = ( SectionStats && ) = default;
  2786. virtual ~SectionStats();
  2787. SectionInfo sectionInfo;
  2788. Counts assertions;
  2789. double durationInSeconds;
  2790. bool missingAssertions;
  2791. };
  2792. struct TestCaseStats {
  2793. TestCaseStats( TestCaseInfo const& _testInfo,
  2794. Totals const& _totals,
  2795. std::string const& _stdOut,
  2796. std::string const& _stdErr,
  2797. bool _aborting );
  2798. TestCaseStats( TestCaseStats const& ) = default;
  2799. TestCaseStats( TestCaseStats && ) = default;
  2800. TestCaseStats& operator = ( TestCaseStats const& ) = default;
  2801. TestCaseStats& operator = ( TestCaseStats && ) = default;
  2802. virtual ~TestCaseStats();
  2803. TestCaseInfo testInfo;
  2804. Totals totals;
  2805. std::string stdOut;
  2806. std::string stdErr;
  2807. bool aborting;
  2808. };
  2809. struct TestGroupStats {
  2810. TestGroupStats( GroupInfo const& _groupInfo,
  2811. Totals const& _totals,
  2812. bool _aborting );
  2813. TestGroupStats( GroupInfo const& _groupInfo );
  2814. TestGroupStats( TestGroupStats const& ) = default;
  2815. TestGroupStats( TestGroupStats && ) = default;
  2816. TestGroupStats& operator = ( TestGroupStats const& ) = default;
  2817. TestGroupStats& operator = ( TestGroupStats && ) = default;
  2818. virtual ~TestGroupStats();
  2819. GroupInfo groupInfo;
  2820. Totals totals;
  2821. bool aborting;
  2822. };
  2823. struct TestRunStats {
  2824. TestRunStats( TestRunInfo const& _runInfo,
  2825. Totals const& _totals,
  2826. bool _aborting );
  2827. TestRunStats( TestRunStats const& ) = default;
  2828. TestRunStats( TestRunStats && ) = default;
  2829. TestRunStats& operator = ( TestRunStats const& ) = default;
  2830. TestRunStats& operator = ( TestRunStats && ) = default;
  2831. virtual ~TestRunStats();
  2832. TestRunInfo runInfo;
  2833. Totals totals;
  2834. bool aborting;
  2835. };
  2836. struct BenchmarkInfo {
  2837. std::string name;
  2838. };
  2839. struct BenchmarkStats {
  2840. BenchmarkInfo info;
  2841. std::size_t iterations;
  2842. uint64_t elapsedTimeInNanoseconds;
  2843. };
  2844. struct IStreamingReporter {
  2845. virtual ~IStreamingReporter() = default;
  2846. // Implementing class must also provide the following static methods:
  2847. // static std::string getDescription();
  2848. // static std::set<Verbosity> getSupportedVerbosities()
  2849. virtual ReporterPreferences getPreferences() const = 0;
  2850. virtual void noMatchingTestCases( std::string const& spec ) = 0;
  2851. virtual void testRunStarting( TestRunInfo const& testRunInfo ) = 0;
  2852. virtual void testGroupStarting( GroupInfo const& groupInfo ) = 0;
  2853. virtual void testCaseStarting( TestCaseInfo const& testInfo ) = 0;
  2854. virtual void sectionStarting( SectionInfo const& sectionInfo ) = 0;
  2855. // *** experimental ***
  2856. virtual void benchmarkStarting( BenchmarkInfo const& ) {}
  2857. virtual void assertionStarting( AssertionInfo const& assertionInfo ) = 0;
  2858. // The return value indicates if the messages buffer should be cleared:
  2859. virtual bool assertionEnded( AssertionStats const& assertionStats ) = 0;
  2860. // *** experimental ***
  2861. virtual void benchmarkEnded( BenchmarkStats const& ) {}
  2862. virtual void sectionEnded( SectionStats const& sectionStats ) = 0;
  2863. virtual void testCaseEnded( TestCaseStats const& testCaseStats ) = 0;
  2864. virtual void testGroupEnded( TestGroupStats const& testGroupStats ) = 0;
  2865. virtual void testRunEnded( TestRunStats const& testRunStats ) = 0;
  2866. virtual void skipTest( TestCaseInfo const& testInfo ) = 0;
  2867. // Default empty implementation provided
  2868. virtual void fatalErrorEncountered( StringRef name );
  2869. virtual bool isMulti() const;
  2870. };
  2871. using IStreamingReporterPtr = std::unique_ptr<IStreamingReporter>;
  2872. struct IReporterFactory {
  2873. virtual ~IReporterFactory();
  2874. virtual IStreamingReporterPtr create( ReporterConfig const& config ) const = 0;
  2875. virtual std::string getDescription() const = 0;
  2876. };
  2877. using IReporterFactoryPtr = std::shared_ptr<IReporterFactory>;
  2878. struct IReporterRegistry {
  2879. using FactoryMap = std::map<std::string, IReporterFactoryPtr>;
  2880. using Listeners = std::vector<IReporterFactoryPtr>;
  2881. virtual ~IReporterRegistry();
  2882. virtual IStreamingReporterPtr create( std::string const& name, IConfigPtr const& config ) const = 0;
  2883. virtual FactoryMap const& getFactories() const = 0;
  2884. virtual Listeners const& getListeners() const = 0;
  2885. };
  2886. void addReporter( IStreamingReporterPtr& existingReporter, IStreamingReporterPtr&& additionalReporter );
  2887. } // end namespace Catch
  2888. // end catch_interfaces_reporter.h
  2889. #include <algorithm>
  2890. #include <cstring>
  2891. #include <cfloat>
  2892. #include <cstdio>
  2893. #include <assert.h>
  2894. #include <memory>
  2895. #include <ostream>
  2896. namespace Catch {
  2897. void prepareExpandedExpression(AssertionResult& result);
  2898. // Returns double formatted as %.3f (format expected on output)
  2899. std::string getFormattedDuration( double duration );
  2900. template<typename DerivedT>
  2901. struct StreamingReporterBase : IStreamingReporter {
  2902. StreamingReporterBase( ReporterConfig const& _config )
  2903. : m_config( _config.fullConfig() ),
  2904. stream( _config.stream() )
  2905. {
  2906. m_reporterPrefs.shouldRedirectStdOut = false;
  2907. if( !DerivedT::getSupportedVerbosities().count( m_config->verbosity() ) )
  2908. throw std::domain_error( "Verbosity level not supported by this reporter" );
  2909. }
  2910. ReporterPreferences getPreferences() const override {
  2911. return m_reporterPrefs;
  2912. }
  2913. static std::set<Verbosity> getSupportedVerbosities() {
  2914. return { Verbosity::Normal };
  2915. }
  2916. ~StreamingReporterBase() override = default;
  2917. void noMatchingTestCases(std::string const&) override {}
  2918. void testRunStarting(TestRunInfo const& _testRunInfo) override {
  2919. currentTestRunInfo = _testRunInfo;
  2920. }
  2921. void testGroupStarting(GroupInfo const& _groupInfo) override {
  2922. currentGroupInfo = _groupInfo;
  2923. }
  2924. void testCaseStarting(TestCaseInfo const& _testInfo) override {
  2925. currentTestCaseInfo = _testInfo;
  2926. }
  2927. void sectionStarting(SectionInfo const& _sectionInfo) override {
  2928. m_sectionStack.push_back(_sectionInfo);
  2929. }
  2930. void sectionEnded(SectionStats const& /* _sectionStats */) override {
  2931. m_sectionStack.pop_back();
  2932. }
  2933. void testCaseEnded(TestCaseStats const& /* _testCaseStats */) override {
  2934. currentTestCaseInfo.reset();
  2935. }
  2936. void testGroupEnded(TestGroupStats const& /* _testGroupStats */) override {
  2937. currentGroupInfo.reset();
  2938. }
  2939. void testRunEnded(TestRunStats const& /* _testRunStats */) override {
  2940. currentTestCaseInfo.reset();
  2941. currentGroupInfo.reset();
  2942. currentTestRunInfo.reset();
  2943. }
  2944. void skipTest(TestCaseInfo const&) override {
  2945. // Don't do anything with this by default.
  2946. // It can optionally be overridden in the derived class.
  2947. }
  2948. IConfigPtr m_config;
  2949. std::ostream& stream;
  2950. LazyStat<TestRunInfo> currentTestRunInfo;
  2951. LazyStat<GroupInfo> currentGroupInfo;
  2952. LazyStat<TestCaseInfo> currentTestCaseInfo;
  2953. std::vector<SectionInfo> m_sectionStack;
  2954. ReporterPreferences m_reporterPrefs;
  2955. };
  2956. template<typename DerivedT>
  2957. struct CumulativeReporterBase : IStreamingReporter {
  2958. template<typename T, typename ChildNodeT>
  2959. struct Node {
  2960. explicit Node( T const& _value ) : value( _value ) {}
  2961. virtual ~Node() {}
  2962. using ChildNodes = std::vector<std::shared_ptr<ChildNodeT>>;
  2963. T value;
  2964. ChildNodes children;
  2965. };
  2966. struct SectionNode {
  2967. explicit SectionNode(SectionStats const& _stats) : stats(_stats) {}
  2968. virtual ~SectionNode() = default;
  2969. bool operator == (SectionNode const& other) const {
  2970. return stats.sectionInfo.lineInfo == other.stats.sectionInfo.lineInfo;
  2971. }
  2972. bool operator == (std::shared_ptr<SectionNode> const& other) const {
  2973. return operator==(*other);
  2974. }
  2975. SectionStats stats;
  2976. using ChildSections = std::vector<std::shared_ptr<SectionNode>>;
  2977. using Assertions = std::vector<AssertionStats>;
  2978. ChildSections childSections;
  2979. Assertions assertions;
  2980. std::string stdOut;
  2981. std::string stdErr;
  2982. };
  2983. struct BySectionInfo {
  2984. BySectionInfo( SectionInfo const& other ) : m_other( other ) {}
  2985. BySectionInfo( BySectionInfo const& other ) : m_other( other.m_other ) {}
  2986. bool operator() (std::shared_ptr<SectionNode> const& node) const {
  2987. return ((node->stats.sectionInfo.name == m_other.name) &&
  2988. (node->stats.sectionInfo.lineInfo == m_other.lineInfo));
  2989. }
  2990. void operator=(BySectionInfo const&) = delete;
  2991. private:
  2992. SectionInfo const& m_other;
  2993. };
  2994. using TestCaseNode = Node<TestCaseStats, SectionNode>;
  2995. using TestGroupNode = Node<TestGroupStats, TestCaseNode>;
  2996. using TestRunNode = Node<TestRunStats, TestGroupNode>;
  2997. CumulativeReporterBase( ReporterConfig const& _config )
  2998. : m_config( _config.fullConfig() ),
  2999. stream( _config.stream() )
  3000. {
  3001. m_reporterPrefs.shouldRedirectStdOut = false;
  3002. if( !DerivedT::getSupportedVerbosities().count( m_config->verbosity() ) )
  3003. throw std::domain_error( "Verbosity level not supported by this reporter" );
  3004. }
  3005. ~CumulativeReporterBase() override = default;
  3006. ReporterPreferences getPreferences() const override {
  3007. return m_reporterPrefs;
  3008. }
  3009. static std::set<Verbosity> getSupportedVerbosities() {
  3010. return { Verbosity::Normal };
  3011. }
  3012. void testRunStarting( TestRunInfo const& ) override {}
  3013. void testGroupStarting( GroupInfo const& ) override {}
  3014. void testCaseStarting( TestCaseInfo const& ) override {}
  3015. void sectionStarting( SectionInfo const& sectionInfo ) override {
  3016. SectionStats incompleteStats( sectionInfo, Counts(), 0, false );
  3017. std::shared_ptr<SectionNode> node;
  3018. if( m_sectionStack.empty() ) {
  3019. if( !m_rootSection )
  3020. m_rootSection = std::make_shared<SectionNode>( incompleteStats );
  3021. node = m_rootSection;
  3022. }
  3023. else {
  3024. SectionNode& parentNode = *m_sectionStack.back();
  3025. auto it =
  3026. std::find_if( parentNode.childSections.begin(),
  3027. parentNode.childSections.end(),
  3028. BySectionInfo( sectionInfo ) );
  3029. if( it == parentNode.childSections.end() ) {
  3030. node = std::make_shared<SectionNode>( incompleteStats );
  3031. parentNode.childSections.push_back( node );
  3032. }
  3033. else
  3034. node = *it;
  3035. }
  3036. m_sectionStack.push_back( node );
  3037. m_deepestSection = std::move(node);
  3038. }
  3039. void assertionStarting(AssertionInfo const&) override {}
  3040. bool assertionEnded(AssertionStats const& assertionStats) override {
  3041. assert(!m_sectionStack.empty());
  3042. // AssertionResult holds a pointer to a temporary DecomposedExpression,
  3043. // which getExpandedExpression() calls to build the expression string.
  3044. // Our section stack copy of the assertionResult will likely outlive the
  3045. // temporary, so it must be expanded or discarded now to avoid calling
  3046. // a destroyed object later.
  3047. prepareExpandedExpression(const_cast<AssertionResult&>( assertionStats.assertionResult ) );
  3048. SectionNode& sectionNode = *m_sectionStack.back();
  3049. sectionNode.assertions.push_back(assertionStats);
  3050. return true;
  3051. }
  3052. void sectionEnded(SectionStats const& sectionStats) override {
  3053. assert(!m_sectionStack.empty());
  3054. SectionNode& node = *m_sectionStack.back();
  3055. node.stats = sectionStats;
  3056. m_sectionStack.pop_back();
  3057. }
  3058. void testCaseEnded(TestCaseStats const& testCaseStats) override {
  3059. auto node = std::make_shared<TestCaseNode>(testCaseStats);
  3060. assert(m_sectionStack.size() == 0);
  3061. node->children.push_back(m_rootSection);
  3062. m_testCases.push_back(node);
  3063. m_rootSection.reset();
  3064. assert(m_deepestSection);
  3065. m_deepestSection->stdOut = testCaseStats.stdOut;
  3066. m_deepestSection->stdErr = testCaseStats.stdErr;
  3067. }
  3068. void testGroupEnded(TestGroupStats const& testGroupStats) override {
  3069. auto node = std::make_shared<TestGroupNode>(testGroupStats);
  3070. node->children.swap(m_testCases);
  3071. m_testGroups.push_back(node);
  3072. }
  3073. void testRunEnded(TestRunStats const& testRunStats) override {
  3074. auto node = std::make_shared<TestRunNode>(testRunStats);
  3075. node->children.swap(m_testGroups);
  3076. m_testRuns.push_back(node);
  3077. testRunEndedCumulative();
  3078. }
  3079. virtual void testRunEndedCumulative() = 0;
  3080. void skipTest(TestCaseInfo const&) override {}
  3081. IConfigPtr m_config;
  3082. std::ostream& stream;
  3083. std::vector<AssertionStats> m_assertions;
  3084. std::vector<std::vector<std::shared_ptr<SectionNode>>> m_sections;
  3085. std::vector<std::shared_ptr<TestCaseNode>> m_testCases;
  3086. std::vector<std::shared_ptr<TestGroupNode>> m_testGroups;
  3087. std::vector<std::shared_ptr<TestRunNode>> m_testRuns;
  3088. std::shared_ptr<SectionNode> m_rootSection;
  3089. std::shared_ptr<SectionNode> m_deepestSection;
  3090. std::vector<std::shared_ptr<SectionNode>> m_sectionStack;
  3091. ReporterPreferences m_reporterPrefs;
  3092. };
  3093. template<char C>
  3094. char const* getLineOfChars() {
  3095. static char line[CATCH_CONFIG_CONSOLE_WIDTH] = {0};
  3096. if( !*line ) {
  3097. std::memset( line, C, CATCH_CONFIG_CONSOLE_WIDTH-1 );
  3098. line[CATCH_CONFIG_CONSOLE_WIDTH-1] = 0;
  3099. }
  3100. return line;
  3101. }
  3102. struct TestEventListenerBase : StreamingReporterBase<TestEventListenerBase> {
  3103. TestEventListenerBase( ReporterConfig const& _config );
  3104. void assertionStarting(AssertionInfo const&) override;
  3105. bool assertionEnded(AssertionStats const&) override;
  3106. };
  3107. } // end namespace Catch
  3108. // end catch_reporter_bases.hpp
  3109. // start catch_console_colour.h
  3110. namespace Catch {
  3111. struct Colour {
  3112. enum Code {
  3113. None = 0,
  3114. White,
  3115. Red,
  3116. Green,
  3117. Blue,
  3118. Cyan,
  3119. Yellow,
  3120. Grey,
  3121. Bright = 0x10,
  3122. BrightRed = Bright | Red,
  3123. BrightGreen = Bright | Green,
  3124. LightGrey = Bright | Grey,
  3125. BrightWhite = Bright | White,
  3126. // By intention
  3127. FileName = LightGrey,
  3128. Warning = Yellow,
  3129. ResultError = BrightRed,
  3130. ResultSuccess = BrightGreen,
  3131. ResultExpectedFailure = Warning,
  3132. Error = BrightRed,
  3133. Success = Green,
  3134. OriginalExpression = Cyan,
  3135. ReconstructedExpression = Yellow,
  3136. SecondaryText = LightGrey,
  3137. Headers = White
  3138. };
  3139. // Use constructed object for RAII guard
  3140. Colour( Code _colourCode );
  3141. Colour( Colour&& other ) noexcept;
  3142. Colour& operator=( Colour&& other ) noexcept;
  3143. ~Colour();
  3144. // Use static method for one-shot changes
  3145. static void use( Code _colourCode );
  3146. private:
  3147. bool m_moved = false;
  3148. };
  3149. std::ostream& operator << ( std::ostream& os, Colour const& );
  3150. } // end namespace Catch
  3151. // end catch_console_colour.h
  3152. // start catch_reporter_registrars.hpp
  3153. namespace Catch {
  3154. template<typename T>
  3155. class ReporterRegistrar {
  3156. class ReporterFactory : public IReporterFactory {
  3157. virtual IStreamingReporterPtr create( ReporterConfig const& config ) const override {
  3158. return std::unique_ptr<T>( new T( config ) );
  3159. }
  3160. virtual std::string getDescription() const override {
  3161. return T::getDescription();
  3162. }
  3163. };
  3164. public:
  3165. explicit ReporterRegistrar( std::string const& name ) {
  3166. getMutableRegistryHub().registerReporter( name, std::make_shared<ReporterFactory>() );
  3167. }
  3168. };
  3169. template<typename T>
  3170. class ListenerRegistrar {
  3171. class ListenerFactory : public IReporterFactory {
  3172. virtual IStreamingReporterPtr create( ReporterConfig const& config ) const override {
  3173. return std::unique_ptr<T>( new T( config ) );
  3174. }
  3175. virtual std::string getDescription() const override {
  3176. return std::string();
  3177. }
  3178. };
  3179. public:
  3180. ListenerRegistrar() {
  3181. getMutableRegistryHub().registerListener( std::make_shared<ListenerFactory>() );
  3182. }
  3183. };
  3184. }
  3185. #if !defined(CATCH_CONFIG_DISABLE)
  3186. #define CATCH_REGISTER_REPORTER( name, reporterType ) \
  3187. CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
  3188. namespace{ Catch::ReporterRegistrar<reporterType> catch_internal_RegistrarFor##reporterType( name ); } \
  3189. CATCH_INTERNAL_UNSUPPRESS_GLOBALS_WARNINGS
  3190. #define CATCH_REGISTER_LISTENER( listenerType ) \
  3191. CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
  3192. namespace{ Catch::ListenerRegistrar<listenerType> catch_internal_RegistrarFor##listenerType; } \
  3193. CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS
  3194. #else // CATCH_CONFIG_DISABLE
  3195. #define CATCH_REGISTER_REPORTER(name, reporterType)
  3196. #define CATCH_REGISTER_LISTENER(listenerType)
  3197. #endif // CATCH_CONFIG_DISABLE
  3198. // end catch_reporter_registrars.hpp
  3199. // Allow users to base their work off existing reporters
  3200. // start catch_reporter_compact.h
  3201. namespace Catch {
  3202. struct CompactReporter : StreamingReporterBase<CompactReporter> {
  3203. using StreamingReporterBase::StreamingReporterBase;
  3204. ~CompactReporter() override;
  3205. static std::string getDescription();
  3206. ReporterPreferences getPreferences() const override;
  3207. void noMatchingTestCases(std::string const& spec) override;
  3208. void assertionStarting(AssertionInfo const&) override;
  3209. bool assertionEnded(AssertionStats const& _assertionStats) override;
  3210. void sectionEnded(SectionStats const& _sectionStats) override;
  3211. void testRunEnded(TestRunStats const& _testRunStats) override;
  3212. };
  3213. } // end namespace Catch
  3214. // end catch_reporter_compact.h
  3215. // start catch_reporter_console.h
  3216. #if defined(_MSC_VER)
  3217. #pragma warning(push)
  3218. #pragma warning(disable:4061) // Not all labels are EXPLICITLY handled in switch
  3219. // Note that 4062 (not all labels are handled
  3220. // and default is missing) is enabled
  3221. #endif
  3222. namespace Catch {
  3223. // Fwd decls
  3224. struct SummaryColumn;
  3225. class TablePrinter;
  3226. struct ConsoleReporter : StreamingReporterBase<ConsoleReporter> {
  3227. std::unique_ptr<TablePrinter> m_tablePrinter;
  3228. ConsoleReporter(ReporterConfig const& config);
  3229. ~ConsoleReporter() override;
  3230. static std::string getDescription();
  3231. void noMatchingTestCases(std::string const& spec) override;
  3232. void assertionStarting(AssertionInfo const&) override;
  3233. bool assertionEnded(AssertionStats const& _assertionStats) override;
  3234. void sectionStarting(SectionInfo const& _sectionInfo) override;
  3235. void sectionEnded(SectionStats const& _sectionStats) override;
  3236. void benchmarkStarting(BenchmarkInfo const& info) override;
  3237. void benchmarkEnded(BenchmarkStats const& stats) override;
  3238. void testCaseEnded(TestCaseStats const& _testCaseStats) override;
  3239. void testGroupEnded(TestGroupStats const& _testGroupStats) override;
  3240. void testRunEnded(TestRunStats const& _testRunStats) override;
  3241. private:
  3242. void lazyPrint();
  3243. void lazyPrintWithoutClosingBenchmarkTable();
  3244. void lazyPrintRunInfo();
  3245. void lazyPrintGroupInfo();
  3246. void printTestCaseAndSectionHeader();
  3247. void printClosedHeader(std::string const& _name);
  3248. void printOpenHeader(std::string const& _name);
  3249. // if string has a : in first line will set indent to follow it on
  3250. // subsequent lines
  3251. void printHeaderString(std::string const& _string, std::size_t indent = 0);
  3252. void printTotals(Totals const& totals);
  3253. void printSummaryRow(std::string const& label, std::vector<SummaryColumn> const& cols, std::size_t row);
  3254. void printTotalsDivider(Totals const& totals);
  3255. void printSummaryDivider();
  3256. private:
  3257. bool m_headerPrinted = false;
  3258. };
  3259. } // end namespace Catch
  3260. #if defined(_MSC_VER)
  3261. #pragma warning(pop)
  3262. #endif
  3263. // end catch_reporter_console.h
  3264. // start catch_reporter_junit.h
  3265. // start catch_xmlwriter.h
  3266. #include <vector>
  3267. namespace Catch {
  3268. class XmlEncode {
  3269. public:
  3270. enum ForWhat { ForTextNodes, ForAttributes };
  3271. XmlEncode( std::string const& str, ForWhat forWhat = ForTextNodes );
  3272. void encodeTo( std::ostream& os ) const;
  3273. friend std::ostream& operator << ( std::ostream& os, XmlEncode const& xmlEncode );
  3274. private:
  3275. std::string m_str;
  3276. ForWhat m_forWhat;
  3277. };
  3278. class XmlWriter {
  3279. public:
  3280. class ScopedElement {
  3281. public:
  3282. ScopedElement( XmlWriter* writer );
  3283. ScopedElement( ScopedElement&& other ) noexcept;
  3284. ScopedElement& operator=( ScopedElement&& other ) noexcept;
  3285. ~ScopedElement();
  3286. ScopedElement& writeText( std::string const& text, bool indent = true );
  3287. template<typename T>
  3288. ScopedElement& writeAttribute( std::string const& name, T const& attribute ) {
  3289. m_writer->writeAttribute( name, attribute );
  3290. return *this;
  3291. }
  3292. private:
  3293. mutable XmlWriter* m_writer = nullptr;
  3294. };
  3295. XmlWriter( std::ostream& os = Catch::cout() );
  3296. ~XmlWriter();
  3297. XmlWriter( XmlWriter const& ) = delete;
  3298. XmlWriter& operator=( XmlWriter const& ) = delete;
  3299. XmlWriter& startElement( std::string const& name );
  3300. ScopedElement scopedElement( std::string const& name );
  3301. XmlWriter& endElement();
  3302. XmlWriter& writeAttribute( std::string const& name, std::string const& attribute );
  3303. XmlWriter& writeAttribute( std::string const& name, bool attribute );
  3304. template<typename T>
  3305. XmlWriter& writeAttribute( std::string const& name, T const& attribute ) {
  3306. ReusableStringStream rss;
  3307. rss << attribute;
  3308. return writeAttribute( name, rss.str() );
  3309. }
  3310. XmlWriter& writeText( std::string const& text, bool indent = true );
  3311. XmlWriter& writeComment( std::string const& text );
  3312. void writeStylesheetRef( std::string const& url );
  3313. XmlWriter& writeBlankLine();
  3314. void ensureTagClosed();
  3315. private:
  3316. void writeDeclaration();
  3317. void newlineIfNecessary();
  3318. bool m_tagIsOpen = false;
  3319. bool m_needsNewline = false;
  3320. std::vector<std::string> m_tags;
  3321. std::string m_indent;
  3322. std::ostream& m_os;
  3323. };
  3324. }
  3325. // end catch_xmlwriter.h
  3326. namespace Catch {
  3327. class JunitReporter : public CumulativeReporterBase<JunitReporter> {
  3328. public:
  3329. JunitReporter(ReporterConfig const& _config);
  3330. ~JunitReporter() override;
  3331. static std::string getDescription();
  3332. void noMatchingTestCases(std::string const& /*spec*/) override;
  3333. void testRunStarting(TestRunInfo const& runInfo) override;
  3334. void testGroupStarting(GroupInfo const& groupInfo) override;
  3335. void testCaseStarting(TestCaseInfo const& testCaseInfo) override;
  3336. bool assertionEnded(AssertionStats const& assertionStats) override;
  3337. void testCaseEnded(TestCaseStats const& testCaseStats) override;
  3338. void testGroupEnded(TestGroupStats const& testGroupStats) override;
  3339. void testRunEndedCumulative() override;
  3340. void writeGroup(TestGroupNode const& groupNode, double suiteTime);
  3341. void writeTestCase(TestCaseNode const& testCaseNode);
  3342. void writeSection(std::string const& className,
  3343. std::string const& rootName,
  3344. SectionNode const& sectionNode);
  3345. void writeAssertions(SectionNode const& sectionNode);
  3346. void writeAssertion(AssertionStats const& stats);
  3347. XmlWriter xml;
  3348. Timer suiteTimer;
  3349. std::string stdOutForSuite;
  3350. std::string stdErrForSuite;
  3351. unsigned int unexpectedExceptions = 0;
  3352. bool m_okToFail = false;
  3353. };
  3354. } // end namespace Catch
  3355. // end catch_reporter_junit.h
  3356. // start catch_reporter_xml.h
  3357. namespace Catch {
  3358. class XmlReporter : public StreamingReporterBase<XmlReporter> {
  3359. public:
  3360. XmlReporter(ReporterConfig const& _config);
  3361. ~XmlReporter() override;
  3362. static std::string getDescription();
  3363. virtual std::string getStylesheetRef() const;
  3364. void writeSourceInfo(SourceLineInfo const& sourceInfo);
  3365. public: // StreamingReporterBase
  3366. void noMatchingTestCases(std::string const& s) override;
  3367. void testRunStarting(TestRunInfo const& testInfo) override;
  3368. void testGroupStarting(GroupInfo const& groupInfo) override;
  3369. void testCaseStarting(TestCaseInfo const& testInfo) override;
  3370. void sectionStarting(SectionInfo const& sectionInfo) override;
  3371. void assertionStarting(AssertionInfo const&) override;
  3372. bool assertionEnded(AssertionStats const& assertionStats) override;
  3373. void sectionEnded(SectionStats const& sectionStats) override;
  3374. void testCaseEnded(TestCaseStats const& testCaseStats) override;
  3375. void testGroupEnded(TestGroupStats const& testGroupStats) override;
  3376. void testRunEnded(TestRunStats const& testRunStats) override;
  3377. private:
  3378. Timer m_testCaseTimer;
  3379. XmlWriter m_xml;
  3380. int m_sectionDepth = 0;
  3381. };
  3382. } // end namespace Catch
  3383. // end catch_reporter_xml.h
  3384. // end catch_external_interfaces.h
  3385. #endif
  3386. #endif // ! CATCH_CONFIG_IMPL_ONLY
  3387. #ifdef CATCH_IMPL
  3388. // start catch_impl.hpp
  3389. #ifdef __clang__
  3390. #pragma clang diagnostic push
  3391. #pragma clang diagnostic ignored "-Wweak-vtables"
  3392. #endif
  3393. // Keep these here for external reporters
  3394. // start catch_test_case_tracker.h
  3395. #include <string>
  3396. #include <vector>
  3397. #include <memory>
  3398. namespace Catch {
  3399. namespace TestCaseTracking {
  3400. struct NameAndLocation {
  3401. std::string name;
  3402. SourceLineInfo location;
  3403. NameAndLocation( std::string const& _name, SourceLineInfo const& _location );
  3404. };
  3405. struct ITracker;
  3406. using ITrackerPtr = std::shared_ptr<ITracker>;
  3407. struct ITracker {
  3408. virtual ~ITracker();
  3409. // static queries
  3410. virtual NameAndLocation const& nameAndLocation() const = 0;
  3411. // dynamic queries
  3412. virtual bool isComplete() const = 0; // Successfully completed or failed
  3413. virtual bool isSuccessfullyCompleted() const = 0;
  3414. virtual bool isOpen() const = 0; // Started but not complete
  3415. virtual bool hasChildren() const = 0;
  3416. virtual ITracker& parent() = 0;
  3417. // actions
  3418. virtual void close() = 0; // Successfully complete
  3419. virtual void fail() = 0;
  3420. virtual void markAsNeedingAnotherRun() = 0;
  3421. virtual void addChild( ITrackerPtr const& child ) = 0;
  3422. virtual ITrackerPtr findChild( NameAndLocation const& nameAndLocation ) = 0;
  3423. virtual void openChild() = 0;
  3424. // Debug/ checking
  3425. virtual bool isSectionTracker() const = 0;
  3426. virtual bool isIndexTracker() const = 0;
  3427. };
  3428. class TrackerContext {
  3429. enum RunState {
  3430. NotStarted,
  3431. Executing,
  3432. CompletedCycle
  3433. };
  3434. ITrackerPtr m_rootTracker;
  3435. ITracker* m_currentTracker = nullptr;
  3436. RunState m_runState = NotStarted;
  3437. public:
  3438. static TrackerContext& instance();
  3439. ITracker& startRun();
  3440. void endRun();
  3441. void startCycle();
  3442. void completeCycle();
  3443. bool completedCycle() const;
  3444. ITracker& currentTracker();
  3445. void setCurrentTracker( ITracker* tracker );
  3446. };
  3447. class TrackerBase : public ITracker {
  3448. protected:
  3449. enum CycleState {
  3450. NotStarted,
  3451. Executing,
  3452. ExecutingChildren,
  3453. NeedsAnotherRun,
  3454. CompletedSuccessfully,
  3455. Failed
  3456. };
  3457. class TrackerHasName {
  3458. NameAndLocation m_nameAndLocation;
  3459. public:
  3460. TrackerHasName( NameAndLocation const& nameAndLocation );
  3461. bool operator ()( ITrackerPtr const& tracker ) const;
  3462. };
  3463. using Children = std::vector<ITrackerPtr>;
  3464. NameAndLocation m_nameAndLocation;
  3465. TrackerContext& m_ctx;
  3466. ITracker* m_parent;
  3467. Children m_children;
  3468. CycleState m_runState = NotStarted;
  3469. public:
  3470. TrackerBase( NameAndLocation const& nameAndLocation, TrackerContext& ctx, ITracker* parent );
  3471. NameAndLocation const& nameAndLocation() const override;
  3472. bool isComplete() const override;
  3473. bool isSuccessfullyCompleted() const override;
  3474. bool isOpen() const override;
  3475. bool hasChildren() const override;
  3476. void addChild( ITrackerPtr const& child ) override;
  3477. ITrackerPtr findChild( NameAndLocation const& nameAndLocation ) override;
  3478. ITracker& parent() override;
  3479. void openChild() override;
  3480. bool isSectionTracker() const override;
  3481. bool isIndexTracker() const override;
  3482. void open();
  3483. void close() override;
  3484. void fail() override;
  3485. void markAsNeedingAnotherRun() override;
  3486. private:
  3487. void moveToParent();
  3488. void moveToThis();
  3489. };
  3490. class SectionTracker : public TrackerBase {
  3491. std::vector<std::string> m_filters;
  3492. public:
  3493. SectionTracker( NameAndLocation const& nameAndLocation, TrackerContext& ctx, ITracker* parent );
  3494. bool isSectionTracker() const override;
  3495. static SectionTracker& acquire( TrackerContext& ctx, NameAndLocation const& nameAndLocation );
  3496. void tryOpen();
  3497. void addInitialFilters( std::vector<std::string> const& filters );
  3498. void addNextFilters( std::vector<std::string> const& filters );
  3499. };
  3500. class IndexTracker : public TrackerBase {
  3501. int m_size;
  3502. int m_index = -1;
  3503. public:
  3504. IndexTracker( NameAndLocation const& nameAndLocation, TrackerContext& ctx, ITracker* parent, int size );
  3505. bool isIndexTracker() const override;
  3506. void close() override;
  3507. static IndexTracker& acquire( TrackerContext& ctx, NameAndLocation const& nameAndLocation, int size );
  3508. int index() const;
  3509. void moveNext();
  3510. };
  3511. } // namespace TestCaseTracking
  3512. using TestCaseTracking::ITracker;
  3513. using TestCaseTracking::TrackerContext;
  3514. using TestCaseTracking::SectionTracker;
  3515. using TestCaseTracking::IndexTracker;
  3516. } // namespace Catch
  3517. // end catch_test_case_tracker.h
  3518. // start catch_leak_detector.h
  3519. namespace Catch {
  3520. struct LeakDetector {
  3521. LeakDetector();
  3522. };
  3523. }
  3524. // end catch_leak_detector.h
  3525. // Cpp files will be included in the single-header file here
  3526. // start catch_approx.cpp
  3527. #include <cmath>
  3528. #include <limits>
  3529. namespace {
  3530. // Performs equivalent check of std::fabs(lhs - rhs) <= margin
  3531. // But without the subtraction to allow for INFINITY in comparison
  3532. bool marginComparison(double lhs, double rhs, double margin) {
  3533. return (lhs + margin >= rhs) && (rhs + margin >= lhs);
  3534. }
  3535. }
  3536. namespace Catch {
  3537. namespace Detail {
  3538. Approx::Approx ( double value )
  3539. : m_epsilon( std::numeric_limits<float>::epsilon()*100 ),
  3540. m_margin( 0.0 ),
  3541. m_scale( 0.0 ),
  3542. m_value( value )
  3543. {}
  3544. Approx Approx::custom() {
  3545. return Approx( 0 );
  3546. }
  3547. std::string Approx::toString() const {
  3548. ReusableStringStream rss;
  3549. rss << "Approx( " << ::Catch::Detail::stringify( m_value ) << " )";
  3550. return rss.str();
  3551. }
  3552. bool Approx::equalityComparisonImpl(const double other) const {
  3553. // First try with fixed margin, then compute margin based on epsilon, scale and Approx's value
  3554. // Thanks to Richard Harris for his help refining the scaled margin value
  3555. return marginComparison(m_value, other, m_margin) || marginComparison(m_value, other, m_epsilon * (m_scale + std::fabs(m_value)));
  3556. }
  3557. } // end namespace Detail
  3558. std::string StringMaker<Catch::Detail::Approx>::convert(Catch::Detail::Approx const& value) {
  3559. return value.toString();
  3560. }
  3561. } // end namespace Catch
  3562. // end catch_approx.cpp
  3563. // start catch_assertionhandler.cpp
  3564. // start catch_context.h
  3565. #include <memory>
  3566. namespace Catch {
  3567. struct IResultCapture;
  3568. struct IRunner;
  3569. struct IConfig;
  3570. struct IMutableContext;
  3571. using IConfigPtr = std::shared_ptr<IConfig const>;
  3572. struct IContext
  3573. {
  3574. virtual ~IContext();
  3575. virtual IResultCapture* getResultCapture() = 0;
  3576. virtual IRunner* getRunner() = 0;
  3577. virtual IConfigPtr const& getConfig() const = 0;
  3578. };
  3579. struct IMutableContext : IContext
  3580. {
  3581. virtual ~IMutableContext();
  3582. virtual void setResultCapture( IResultCapture* resultCapture ) = 0;
  3583. virtual void setRunner( IRunner* runner ) = 0;
  3584. virtual void setConfig( IConfigPtr const& config ) = 0;
  3585. private:
  3586. static IMutableContext *currentContext;
  3587. friend IMutableContext& getCurrentMutableContext();
  3588. friend void cleanUpContext();
  3589. static void createContext();
  3590. };
  3591. inline IMutableContext& getCurrentMutableContext()
  3592. {
  3593. if( !IMutableContext::currentContext )
  3594. IMutableContext::createContext();
  3595. return *IMutableContext::currentContext;
  3596. }
  3597. inline IContext& getCurrentContext()
  3598. {
  3599. return getCurrentMutableContext();
  3600. }
  3601. void cleanUpContext();
  3602. }
  3603. // end catch_context.h
  3604. // start catch_debugger.h
  3605. namespace Catch {
  3606. bool isDebuggerActive();
  3607. }
  3608. #ifdef CATCH_PLATFORM_MAC
  3609. #define CATCH_TRAP() __asm__("int $3\n" : : ) /* NOLINT */
  3610. #elif defined(CATCH_PLATFORM_LINUX)
  3611. // If we can use inline assembler, do it because this allows us to break
  3612. // directly at the location of the failing check instead of breaking inside
  3613. // raise() called from it, i.e. one stack frame below.
  3614. #if defined(__GNUC__) && (defined(__i386) || defined(__x86_64))
  3615. #define CATCH_TRAP() asm volatile ("int $3") /* NOLINT */
  3616. #else // Fall back to the generic way.
  3617. #include <signal.h>
  3618. #define CATCH_TRAP() raise(SIGTRAP)
  3619. #endif
  3620. #elif defined(_MSC_VER)
  3621. #define CATCH_TRAP() __debugbreak()
  3622. #elif defined(__MINGW32__)
  3623. extern "C" __declspec(dllimport) void __stdcall DebugBreak();
  3624. #define CATCH_TRAP() DebugBreak()
  3625. #endif
  3626. #ifdef CATCH_TRAP
  3627. #define CATCH_BREAK_INTO_DEBUGGER() if( Catch::isDebuggerActive() ) { CATCH_TRAP(); }
  3628. #else
  3629. #define CATCH_BREAK_INTO_DEBUGGER() (void)0, 0
  3630. #endif
  3631. // end catch_debugger.h
  3632. // start catch_run_context.h
  3633. // start catch_fatal_condition.h
  3634. #include <string>
  3635. #if defined ( CATCH_PLATFORM_WINDOWS ) /////////////////////////////////////////
  3636. // start catch_windows_h_proxy.h
  3637. #if defined(CATCH_PLATFORM_WINDOWS)
  3638. #if !defined(NOMINMAX) && !defined(CATCH_CONFIG_NO_NOMINMAX)
  3639. # define CATCH_DEFINED_NOMINMAX
  3640. # define NOMINMAX
  3641. #endif
  3642. #if !defined(WIN32_LEAN_AND_MEAN) && !defined(CATCH_CONFIG_NO_WIN32_LEAN_AND_MEAN)
  3643. # define CATCH_DEFINED_WIN32_LEAN_AND_MEAN
  3644. # define WIN32_LEAN_AND_MEAN
  3645. #endif
  3646. #ifdef __AFXDLL
  3647. #include <AfxWin.h>
  3648. #else
  3649. #include <windows.h>
  3650. #endif
  3651. #ifdef CATCH_DEFINED_NOMINMAX
  3652. # undef NOMINMAX
  3653. #endif
  3654. #ifdef CATCH_DEFINED_WIN32_LEAN_AND_MEAN
  3655. # undef WIN32_LEAN_AND_MEAN
  3656. #endif
  3657. #endif // defined(CATCH_PLATFORM_WINDOWS)
  3658. // end catch_windows_h_proxy.h
  3659. # if !defined ( CATCH_CONFIG_WINDOWS_SEH )
  3660. namespace Catch {
  3661. struct FatalConditionHandler {
  3662. void reset();
  3663. };
  3664. }
  3665. # else // CATCH_CONFIG_WINDOWS_SEH is defined
  3666. namespace Catch {
  3667. struct FatalConditionHandler {
  3668. static LONG CALLBACK handleVectoredException(PEXCEPTION_POINTERS ExceptionInfo);
  3669. FatalConditionHandler();
  3670. static void reset();
  3671. ~FatalConditionHandler();
  3672. private:
  3673. static bool isSet;
  3674. static ULONG guaranteeSize;
  3675. static PVOID exceptionHandlerHandle;
  3676. };
  3677. } // namespace Catch
  3678. # endif // CATCH_CONFIG_WINDOWS_SEH
  3679. #else // Not Windows - assumed to be POSIX compatible //////////////////////////
  3680. # if !defined(CATCH_CONFIG_POSIX_SIGNALS)
  3681. namespace Catch {
  3682. struct FatalConditionHandler {
  3683. void reset();
  3684. };
  3685. }
  3686. # else // CATCH_CONFIG_POSIX_SIGNALS is defined
  3687. #include <signal.h>
  3688. namespace Catch {
  3689. struct FatalConditionHandler {
  3690. static bool isSet;
  3691. static struct sigaction oldSigActions[];// [sizeof(signalDefs) / sizeof(SignalDefs)];
  3692. static stack_t oldSigStack;
  3693. static char altStackMem[];
  3694. static void handleSignal( int sig );
  3695. FatalConditionHandler();
  3696. ~FatalConditionHandler();
  3697. static void reset();
  3698. };
  3699. } // namespace Catch
  3700. # endif // CATCH_CONFIG_POSIX_SIGNALS
  3701. #endif // not Windows
  3702. // end catch_fatal_condition.h
  3703. #include <string>
  3704. namespace Catch {
  3705. struct IMutableContext;
  3706. ///////////////////////////////////////////////////////////////////////////
  3707. class RunContext : public IResultCapture, public IRunner {
  3708. public:
  3709. RunContext( RunContext const& ) = delete;
  3710. RunContext& operator =( RunContext const& ) = delete;
  3711. explicit RunContext( IConfigPtr const& _config, IStreamingReporterPtr&& reporter );
  3712. ~RunContext() override;
  3713. void testGroupStarting( std::string const& testSpec, std::size_t groupIndex, std::size_t groupsCount );
  3714. void testGroupEnded( std::string const& testSpec, Totals const& totals, std::size_t groupIndex, std::size_t groupsCount );
  3715. Totals runTest(TestCase const& testCase);
  3716. IConfigPtr config() const;
  3717. IStreamingReporter& reporter() const;
  3718. public: // IResultCapture
  3719. // Assertion handlers
  3720. void handleExpr
  3721. ( AssertionInfo const& info,
  3722. ITransientExpression const& expr,
  3723. AssertionReaction& reaction ) override;
  3724. void handleMessage
  3725. ( AssertionInfo const& info,
  3726. ResultWas::OfType resultType,
  3727. StringRef const& message,
  3728. AssertionReaction& reaction ) override;
  3729. void handleUnexpectedExceptionNotThrown
  3730. ( AssertionInfo const& info,
  3731. AssertionReaction& reaction ) override;
  3732. void handleUnexpectedInflightException
  3733. ( AssertionInfo const& info,
  3734. std::string const& message,
  3735. AssertionReaction& reaction ) override;
  3736. void handleIncomplete
  3737. ( AssertionInfo const& info ) override;
  3738. void handleNonExpr
  3739. ( AssertionInfo const &info,
  3740. ResultWas::OfType resultType,
  3741. AssertionReaction &reaction ) override;
  3742. bool sectionStarted( SectionInfo const& sectionInfo, Counts& assertions ) override;
  3743. void sectionEnded( SectionEndInfo const& endInfo ) override;
  3744. void sectionEndedEarly( SectionEndInfo const& endInfo ) override;
  3745. void benchmarkStarting( BenchmarkInfo const& info ) override;
  3746. void benchmarkEnded( BenchmarkStats const& stats ) override;
  3747. void pushScopedMessage( MessageInfo const& message ) override;
  3748. void popScopedMessage( MessageInfo const& message ) override;
  3749. std::string getCurrentTestName() const override;
  3750. const AssertionResult* getLastResult() const override;
  3751. void exceptionEarlyReported() override;
  3752. void handleFatalErrorCondition( StringRef message ) override;
  3753. bool lastAssertionPassed() override;
  3754. void assertionPassed() override;
  3755. public:
  3756. // !TBD We need to do this another way!
  3757. bool aborting() const override;
  3758. private:
  3759. void runCurrentTest( std::string& redirectedCout, std::string& redirectedCerr );
  3760. void invokeActiveTestCase();
  3761. void resetAssertionInfo();
  3762. bool testForMissingAssertions( Counts& assertions );
  3763. void assertionEnded( AssertionResult const& result );
  3764. void reportExpr
  3765. ( AssertionInfo const &info,
  3766. ResultWas::OfType resultType,
  3767. ITransientExpression const *expr,
  3768. bool negated );
  3769. void populateReaction( AssertionReaction& reaction );
  3770. private:
  3771. void handleUnfinishedSections();
  3772. TestRunInfo m_runInfo;
  3773. IMutableContext& m_context;
  3774. TestCase const* m_activeTestCase = nullptr;
  3775. ITracker* m_testCaseTracker;
  3776. Option<AssertionResult> m_lastResult;
  3777. IConfigPtr m_config;
  3778. Totals m_totals;
  3779. IStreamingReporterPtr m_reporter;
  3780. std::vector<MessageInfo> m_messages;
  3781. AssertionInfo m_lastAssertionInfo;
  3782. std::vector<SectionEndInfo> m_unfinishedSections;
  3783. std::vector<ITracker*> m_activeSections;
  3784. TrackerContext m_trackerContext;
  3785. bool m_lastAssertionPassed = false;
  3786. bool m_shouldReportUnexpected = true;
  3787. bool m_includeSuccessfulResults;
  3788. };
  3789. } // end namespace Catch
  3790. // end catch_run_context.h
  3791. namespace Catch {
  3792. auto operator <<( std::ostream& os, ITransientExpression const& expr ) -> std::ostream& {
  3793. expr.streamReconstructedExpression( os );
  3794. return os;
  3795. }
  3796. LazyExpression::LazyExpression( bool isNegated )
  3797. : m_isNegated( isNegated )
  3798. {}
  3799. LazyExpression::LazyExpression( LazyExpression const& other ) : m_isNegated( other.m_isNegated ) {}
  3800. LazyExpression::operator bool() const {
  3801. return m_transientExpression != nullptr;
  3802. }
  3803. auto operator << ( std::ostream& os, LazyExpression const& lazyExpr ) -> std::ostream& {
  3804. if( lazyExpr.m_isNegated )
  3805. os << "!";
  3806. if( lazyExpr ) {
  3807. if( lazyExpr.m_isNegated && lazyExpr.m_transientExpression->isBinaryExpression() )
  3808. os << "(" << *lazyExpr.m_transientExpression << ")";
  3809. else
  3810. os << *lazyExpr.m_transientExpression;
  3811. }
  3812. else {
  3813. os << "{** error - unchecked empty expression requested **}";
  3814. }
  3815. return os;
  3816. }
  3817. AssertionHandler::AssertionHandler
  3818. ( StringRef macroName,
  3819. SourceLineInfo const& lineInfo,
  3820. StringRef capturedExpression,
  3821. ResultDisposition::Flags resultDisposition )
  3822. : m_assertionInfo{ macroName, lineInfo, capturedExpression, resultDisposition },
  3823. m_resultCapture( getResultCapture() )
  3824. {}
  3825. void AssertionHandler::handleExpr( ITransientExpression const& expr ) {
  3826. m_resultCapture.handleExpr( m_assertionInfo, expr, m_reaction );
  3827. }
  3828. void AssertionHandler::handleMessage(ResultWas::OfType resultType, StringRef const& message) {
  3829. m_resultCapture.handleMessage( m_assertionInfo, resultType, message, m_reaction );
  3830. }
  3831. auto AssertionHandler::allowThrows() const -> bool {
  3832. return getCurrentContext().getConfig()->allowThrows();
  3833. }
  3834. void AssertionHandler::complete() {
  3835. setCompleted();
  3836. if( m_reaction.shouldDebugBreak ) {
  3837. // If you find your debugger stopping you here then go one level up on the
  3838. // call-stack for the code that caused it (typically a failed assertion)
  3839. // (To go back to the test and change execution, jump over the throw, next)
  3840. CATCH_BREAK_INTO_DEBUGGER();
  3841. }
  3842. if( m_reaction.shouldThrow )
  3843. throw Catch::TestFailureException();
  3844. }
  3845. void AssertionHandler::setCompleted() {
  3846. m_completed = true;
  3847. }
  3848. void AssertionHandler::handleUnexpectedInflightException() {
  3849. m_resultCapture.handleUnexpectedInflightException( m_assertionInfo, Catch::translateActiveException(), m_reaction );
  3850. }
  3851. void AssertionHandler::handleExceptionThrownAsExpected() {
  3852. m_resultCapture.handleNonExpr(m_assertionInfo, ResultWas::Ok, m_reaction);
  3853. }
  3854. void AssertionHandler::handleExceptionNotThrownAsExpected() {
  3855. m_resultCapture.handleNonExpr(m_assertionInfo, ResultWas::Ok, m_reaction);
  3856. }
  3857. void AssertionHandler::handleUnexpectedExceptionNotThrown() {
  3858. m_resultCapture.handleUnexpectedExceptionNotThrown( m_assertionInfo, m_reaction );
  3859. }
  3860. void AssertionHandler::handleThrowingCallSkipped() {
  3861. m_resultCapture.handleNonExpr(m_assertionInfo, ResultWas::Ok, m_reaction);
  3862. }
  3863. // This is the overload that takes a string and infers the Equals matcher from it
  3864. // The more general overload, that takes any string matcher, is in catch_capture_matchers.cpp
  3865. void handleExceptionMatchExpr( AssertionHandler& handler, std::string const& str, StringRef matcherString ) {
  3866. handleExceptionMatchExpr( handler, Matchers::Equals( str ), matcherString );
  3867. }
  3868. } // namespace Catch
  3869. // end catch_assertionhandler.cpp
  3870. // start catch_assertionresult.cpp
  3871. namespace Catch {
  3872. AssertionResultData::AssertionResultData(ResultWas::OfType _resultType, LazyExpression const & _lazyExpression):
  3873. lazyExpression(_lazyExpression),
  3874. resultType(_resultType) {}
  3875. std::string AssertionResultData::reconstructExpression() const {
  3876. if( reconstructedExpression.empty() ) {
  3877. if( lazyExpression ) {
  3878. ReusableStringStream rss;
  3879. rss << lazyExpression;
  3880. reconstructedExpression = rss.str();
  3881. }
  3882. }
  3883. return reconstructedExpression;
  3884. }
  3885. AssertionResult::AssertionResult( AssertionInfo const& info, AssertionResultData const& data )
  3886. : m_info( info ),
  3887. m_resultData( data )
  3888. {}
  3889. // Result was a success
  3890. bool AssertionResult::succeeded() const {
  3891. return Catch::isOk( m_resultData.resultType );
  3892. }
  3893. // Result was a success, or failure is suppressed
  3894. bool AssertionResult::isOk() const {
  3895. return Catch::isOk( m_resultData.resultType ) || shouldSuppressFailure( m_info.resultDisposition );
  3896. }
  3897. ResultWas::OfType AssertionResult::getResultType() const {
  3898. return m_resultData.resultType;
  3899. }
  3900. bool AssertionResult::hasExpression() const {
  3901. return m_info.capturedExpression[0] != 0;
  3902. }
  3903. bool AssertionResult::hasMessage() const {
  3904. return !m_resultData.message.empty();
  3905. }
  3906. std::string AssertionResult::getExpression() const {
  3907. if( isFalseTest( m_info.resultDisposition ) )
  3908. return "!(" + m_info.capturedExpression + ")";
  3909. else
  3910. return m_info.capturedExpression;
  3911. }
  3912. std::string AssertionResult::getExpressionInMacro() const {
  3913. std::string expr;
  3914. if( m_info.macroName[0] == 0 )
  3915. expr = m_info.capturedExpression;
  3916. else {
  3917. expr.reserve( m_info.macroName.size() + m_info.capturedExpression.size() + 4 );
  3918. expr += m_info.macroName.c_str();
  3919. expr += "( ";
  3920. expr += m_info.capturedExpression.c_str();
  3921. expr += " )";
  3922. }
  3923. return expr;
  3924. }
  3925. bool AssertionResult::hasExpandedExpression() const {
  3926. return hasExpression() && getExpandedExpression() != getExpression();
  3927. }
  3928. std::string AssertionResult::getExpandedExpression() const {
  3929. std::string expr = m_resultData.reconstructExpression();
  3930. return expr.empty()
  3931. ? getExpression()
  3932. : expr;
  3933. }
  3934. std::string AssertionResult::getMessage() const {
  3935. return m_resultData.message;
  3936. }
  3937. SourceLineInfo AssertionResult::getSourceInfo() const {
  3938. return m_info.lineInfo;
  3939. }
  3940. StringRef AssertionResult::getTestMacroName() const {
  3941. return m_info.macroName;
  3942. }
  3943. } // end namespace Catch
  3944. // end catch_assertionresult.cpp
  3945. // start catch_benchmark.cpp
  3946. namespace Catch {
  3947. auto BenchmarkLooper::getResolution() -> uint64_t {
  3948. return getEstimatedClockResolution() * getCurrentContext().getConfig()->benchmarkResolutionMultiple();
  3949. }
  3950. void BenchmarkLooper::reportStart() {
  3951. getResultCapture().benchmarkStarting( { m_name } );
  3952. }
  3953. auto BenchmarkLooper::needsMoreIterations() -> bool {
  3954. auto elapsed = m_timer.getElapsedNanoseconds();
  3955. // Exponentially increasing iterations until we're confident in our timer resolution
  3956. if( elapsed < m_resolution ) {
  3957. m_iterationsToRun *= 10;
  3958. return true;
  3959. }
  3960. getResultCapture().benchmarkEnded( { { m_name }, m_count, elapsed } );
  3961. return false;
  3962. }
  3963. } // end namespace Catch
  3964. // end catch_benchmark.cpp
  3965. // start catch_capture_matchers.cpp
  3966. namespace Catch {
  3967. using StringMatcher = Matchers::Impl::MatcherBase<std::string>;
  3968. // This is the general overload that takes a any string matcher
  3969. // There is another overload, in catch_assertinhandler.h/.cpp, that only takes a string and infers
  3970. // the Equals matcher (so the header does not mention matchers)
  3971. void handleExceptionMatchExpr( AssertionHandler& handler, StringMatcher const& matcher, StringRef matcherString ) {
  3972. std::string exceptionMessage = Catch::translateActiveException();
  3973. MatchExpr<std::string, StringMatcher const&> expr( exceptionMessage, matcher, matcherString );
  3974. handler.handleExpr( expr );
  3975. }
  3976. } // namespace Catch
  3977. // end catch_capture_matchers.cpp
  3978. // start catch_commandline.cpp
  3979. // start catch_commandline.h
  3980. // start catch_clara.h
  3981. // Use Catch's value for console width (store Clara's off to the side, if present)
  3982. #ifdef CLARA_CONFIG_CONSOLE_WIDTH
  3983. #define CATCH_TEMP_CLARA_CONFIG_CONSOLE_WIDTH CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH
  3984. #undef CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH
  3985. #endif
  3986. #define CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH CATCH_CONFIG_CONSOLE_WIDTH-1
  3987. #ifdef __clang__
  3988. #pragma clang diagnostic push
  3989. #pragma clang diagnostic ignored "-Wweak-vtables"
  3990. #pragma clang diagnostic ignored "-Wexit-time-destructors"
  3991. #pragma clang diagnostic ignored "-Wshadow"
  3992. #endif
  3993. // start clara.hpp
  3994. // Copyright 2017 Two Blue Cubes Ltd. All rights reserved.
  3995. //
  3996. // Distributed under the Boost Software License, Version 1.0. (See accompanying
  3997. // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
  3998. //
  3999. // See https://github.com/philsquared/Clara for more details
  4000. // Clara v1.1.1
  4001. #ifndef CATCH_CLARA_CONFIG_CONSOLE_WIDTH
  4002. #define CATCH_CLARA_CONFIG_CONSOLE_WIDTH 80
  4003. #endif
  4004. #ifndef CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH
  4005. #define CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH CATCH_CLARA_CONFIG_CONSOLE_WIDTH
  4006. #endif
  4007. // ----------- #included from clara_textflow.hpp -----------
  4008. // TextFlowCpp
  4009. //
  4010. // A single-header library for wrapping and laying out basic text, by Phil Nash
  4011. //
  4012. // This work is licensed under the BSD 2-Clause license.
  4013. // See the accompanying LICENSE file, or the one at https://opensource.org/licenses/BSD-2-Clause
  4014. //
  4015. // This project is hosted at https://github.com/philsquared/textflowcpp
  4016. #include <cassert>
  4017. #include <ostream>
  4018. #include <sstream>
  4019. #include <vector>
  4020. #ifndef CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH
  4021. #define CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH 80
  4022. #endif
  4023. namespace Catch { namespace clara { namespace TextFlow {
  4024. inline auto isWhitespace( char c ) -> bool {
  4025. static std::string chars = " \t\n\r";
  4026. return chars.find( c ) != std::string::npos;
  4027. }
  4028. inline auto isBreakableBefore( char c ) -> bool {
  4029. static std::string chars = "[({<|";
  4030. return chars.find( c ) != std::string::npos;
  4031. }
  4032. inline auto isBreakableAfter( char c ) -> bool {
  4033. static std::string chars = "])}>.,:;*+-=&/\\";
  4034. return chars.find( c ) != std::string::npos;
  4035. }
  4036. class Columns;
  4037. class Column {
  4038. std::vector<std::string> m_strings;
  4039. size_t m_width = CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH;
  4040. size_t m_indent = 0;
  4041. size_t m_initialIndent = std::string::npos;
  4042. public:
  4043. class iterator {
  4044. friend Column;
  4045. Column const& m_column;
  4046. size_t m_stringIndex = 0;
  4047. size_t m_pos = 0;
  4048. size_t m_len = 0;
  4049. size_t m_end = 0;
  4050. bool m_suffix = false;
  4051. iterator( Column const& column, size_t stringIndex )
  4052. : m_column( column ),
  4053. m_stringIndex( stringIndex )
  4054. {}
  4055. auto line() const -> std::string const& { return m_column.m_strings[m_stringIndex]; }
  4056. auto isBoundary( size_t at ) const -> bool {
  4057. assert( at > 0 );
  4058. assert( at <= line().size() );
  4059. return at == line().size() ||
  4060. ( isWhitespace( line()[at] ) && !isWhitespace( line()[at-1] ) ) ||
  4061. isBreakableBefore( line()[at] ) ||
  4062. isBreakableAfter( line()[at-1] );
  4063. }
  4064. void calcLength() {
  4065. assert( m_stringIndex < m_column.m_strings.size() );
  4066. m_suffix = false;
  4067. auto width = m_column.m_width-indent();
  4068. m_end = m_pos;
  4069. while( m_end < line().size() && line()[m_end] != '\n' )
  4070. ++m_end;
  4071. if( m_end < m_pos + width ) {
  4072. m_len = m_end - m_pos;
  4073. }
  4074. else {
  4075. size_t len = width;
  4076. while (len > 0 && !isBoundary(m_pos + len))
  4077. --len;
  4078. while (len > 0 && isWhitespace( line()[m_pos + len - 1] ))
  4079. --len;
  4080. if (len > 0) {
  4081. m_len = len;
  4082. } else {
  4083. m_suffix = true;
  4084. m_len = width - 1;
  4085. }
  4086. }
  4087. }
  4088. auto indent() const -> size_t {
  4089. auto initial = m_pos == 0 && m_stringIndex == 0 ? m_column.m_initialIndent : std::string::npos;
  4090. return initial == std::string::npos ? m_column.m_indent : initial;
  4091. }
  4092. auto addIndentAndSuffix(std::string const &plain) const -> std::string {
  4093. return std::string( indent(), ' ' ) + (m_suffix ? plain + "-" : plain);
  4094. }
  4095. public:
  4096. explicit iterator( Column const& column ) : m_column( column ) {
  4097. assert( m_column.m_width > m_column.m_indent );
  4098. assert( m_column.m_initialIndent == std::string::npos || m_column.m_width > m_column.m_initialIndent );
  4099. calcLength();
  4100. if( m_len == 0 )
  4101. m_stringIndex++; // Empty string
  4102. }
  4103. auto operator *() const -> std::string {
  4104. assert( m_stringIndex < m_column.m_strings.size() );
  4105. assert( m_pos <= m_end );
  4106. if( m_pos + m_column.m_width < m_end )
  4107. return addIndentAndSuffix(line().substr(m_pos, m_len));
  4108. else
  4109. return addIndentAndSuffix(line().substr(m_pos, m_end - m_pos));
  4110. }
  4111. auto operator ++() -> iterator& {
  4112. m_pos += m_len;
  4113. if( m_pos < line().size() && line()[m_pos] == '\n' )
  4114. m_pos += 1;
  4115. else
  4116. while( m_pos < line().size() && isWhitespace( line()[m_pos] ) )
  4117. ++m_pos;
  4118. if( m_pos == line().size() ) {
  4119. m_pos = 0;
  4120. ++m_stringIndex;
  4121. }
  4122. if( m_stringIndex < m_column.m_strings.size() )
  4123. calcLength();
  4124. return *this;
  4125. }
  4126. auto operator ++(int) -> iterator {
  4127. iterator prev( *this );
  4128. operator++();
  4129. return prev;
  4130. }
  4131. auto operator ==( iterator const& other ) const -> bool {
  4132. return
  4133. m_pos == other.m_pos &&
  4134. m_stringIndex == other.m_stringIndex &&
  4135. &m_column == &other.m_column;
  4136. }
  4137. auto operator !=( iterator const& other ) const -> bool {
  4138. return !operator==( other );
  4139. }
  4140. };
  4141. using const_iterator = iterator;
  4142. explicit Column( std::string const& text ) { m_strings.push_back( text ); }
  4143. auto width( size_t newWidth ) -> Column& {
  4144. assert( newWidth > 0 );
  4145. m_width = newWidth;
  4146. return *this;
  4147. }
  4148. auto indent( size_t newIndent ) -> Column& {
  4149. m_indent = newIndent;
  4150. return *this;
  4151. }
  4152. auto initialIndent( size_t newIndent ) -> Column& {
  4153. m_initialIndent = newIndent;
  4154. return *this;
  4155. }
  4156. auto width() const -> size_t { return m_width; }
  4157. auto begin() const -> iterator { return iterator( *this ); }
  4158. auto end() const -> iterator { return { *this, m_strings.size() }; }
  4159. inline friend std::ostream& operator << ( std::ostream& os, Column const& col ) {
  4160. bool first = true;
  4161. for( auto line : col ) {
  4162. if( first )
  4163. first = false;
  4164. else
  4165. os << "\n";
  4166. os << line;
  4167. }
  4168. return os;
  4169. }
  4170. auto operator + ( Column const& other ) -> Columns;
  4171. auto toString() const -> std::string {
  4172. std::ostringstream oss;
  4173. oss << *this;
  4174. return oss.str();
  4175. }
  4176. };
  4177. class Spacer : public Column {
  4178. public:
  4179. explicit Spacer( size_t spaceWidth ) : Column( "" ) {
  4180. width( spaceWidth );
  4181. }
  4182. };
  4183. class Columns {
  4184. std::vector<Column> m_columns;
  4185. public:
  4186. class iterator {
  4187. friend Columns;
  4188. struct EndTag {};
  4189. std::vector<Column> const& m_columns;
  4190. std::vector<Column::iterator> m_iterators;
  4191. size_t m_activeIterators;
  4192. iterator( Columns const& columns, EndTag )
  4193. : m_columns( columns.m_columns ),
  4194. m_activeIterators( 0 )
  4195. {
  4196. m_iterators.reserve( m_columns.size() );
  4197. for( auto const& col : m_columns )
  4198. m_iterators.push_back( col.end() );
  4199. }
  4200. public:
  4201. explicit iterator( Columns const& columns )
  4202. : m_columns( columns.m_columns ),
  4203. m_activeIterators( m_columns.size() )
  4204. {
  4205. m_iterators.reserve( m_columns.size() );
  4206. for( auto const& col : m_columns )
  4207. m_iterators.push_back( col.begin() );
  4208. }
  4209. auto operator ==( iterator const& other ) const -> bool {
  4210. return m_iterators == other.m_iterators;
  4211. }
  4212. auto operator !=( iterator const& other ) const -> bool {
  4213. return m_iterators != other.m_iterators;
  4214. }
  4215. auto operator *() const -> std::string {
  4216. std::string row, padding;
  4217. for( size_t i = 0; i < m_columns.size(); ++i ) {
  4218. auto width = m_columns[i].width();
  4219. if( m_iterators[i] != m_columns[i].end() ) {
  4220. std::string col = *m_iterators[i];
  4221. row += padding + col;
  4222. if( col.size() < width )
  4223. padding = std::string( width - col.size(), ' ' );
  4224. else
  4225. padding = "";
  4226. }
  4227. else {
  4228. padding += std::string( width, ' ' );
  4229. }
  4230. }
  4231. return row;
  4232. }
  4233. auto operator ++() -> iterator& {
  4234. for( size_t i = 0; i < m_columns.size(); ++i ) {
  4235. if (m_iterators[i] != m_columns[i].end())
  4236. ++m_iterators[i];
  4237. }
  4238. return *this;
  4239. }
  4240. auto operator ++(int) -> iterator {
  4241. iterator prev( *this );
  4242. operator++();
  4243. return prev;
  4244. }
  4245. };
  4246. using const_iterator = iterator;
  4247. auto begin() const -> iterator { return iterator( *this ); }
  4248. auto end() const -> iterator { return { *this, iterator::EndTag() }; }
  4249. auto operator += ( Column const& col ) -> Columns& {
  4250. m_columns.push_back( col );
  4251. return *this;
  4252. }
  4253. auto operator + ( Column const& col ) -> Columns {
  4254. Columns combined = *this;
  4255. combined += col;
  4256. return combined;
  4257. }
  4258. inline friend std::ostream& operator << ( std::ostream& os, Columns const& cols ) {
  4259. bool first = true;
  4260. for( auto line : cols ) {
  4261. if( first )
  4262. first = false;
  4263. else
  4264. os << "\n";
  4265. os << line;
  4266. }
  4267. return os;
  4268. }
  4269. auto toString() const -> std::string {
  4270. std::ostringstream oss;
  4271. oss << *this;
  4272. return oss.str();
  4273. }
  4274. };
  4275. inline auto Column::operator + ( Column const& other ) -> Columns {
  4276. Columns cols;
  4277. cols += *this;
  4278. cols += other;
  4279. return cols;
  4280. }
  4281. }}} // namespace Catch::clara::TextFlow
  4282. // ----------- end of #include from clara_textflow.hpp -----------
  4283. // ........... back in clara.hpp
  4284. #include <memory>
  4285. #include <set>
  4286. #include <algorithm>
  4287. #if !defined(CATCH_PLATFORM_WINDOWS) && ( defined(WIN32) || defined(__WIN32__) || defined(_WIN32) || defined(_MSC_VER) )
  4288. #define CATCH_PLATFORM_WINDOWS
  4289. #endif
  4290. namespace Catch { namespace clara {
  4291. namespace detail {
  4292. // Traits for extracting arg and return type of lambdas (for single argument lambdas)
  4293. template<typename L>
  4294. struct UnaryLambdaTraits : UnaryLambdaTraits<decltype( &L::operator() )> {};
  4295. template<typename ClassT, typename ReturnT, typename... Args>
  4296. struct UnaryLambdaTraits<ReturnT( ClassT::* )( Args... ) const> {
  4297. static const bool isValid = false;
  4298. };
  4299. template<typename ClassT, typename ReturnT, typename ArgT>
  4300. struct UnaryLambdaTraits<ReturnT( ClassT::* )( ArgT ) const> {
  4301. static const bool isValid = true;
  4302. using ArgType = typename std::remove_const<typename std::remove_reference<ArgT>::type>::type;
  4303. using ReturnType = ReturnT;
  4304. };
  4305. class TokenStream;
  4306. // Transport for raw args (copied from main args, or supplied via init list for testing)
  4307. class Args {
  4308. friend TokenStream;
  4309. std::string m_exeName;
  4310. std::vector<std::string> m_args;
  4311. public:
  4312. Args( int argc, char *argv[] ) {
  4313. m_exeName = argv[0];
  4314. for( int i = 1; i < argc; ++i )
  4315. m_args.push_back( argv[i] );
  4316. }
  4317. Args( std::initializer_list<std::string> args )
  4318. : m_exeName( *args.begin() ),
  4319. m_args( args.begin()+1, args.end() )
  4320. {}
  4321. auto exeName() const -> std::string {
  4322. return m_exeName;
  4323. }
  4324. };
  4325. // Wraps a token coming from a token stream. These may not directly correspond to strings as a single string
  4326. // may encode an option + its argument if the : or = form is used
  4327. enum class TokenType {
  4328. Option, Argument
  4329. };
  4330. struct Token {
  4331. TokenType type;
  4332. std::string token;
  4333. };
  4334. inline auto isOptPrefix( char c ) -> bool {
  4335. return c == '-'
  4336. #ifdef CATCH_PLATFORM_WINDOWS
  4337. || c == '/'
  4338. #endif
  4339. ;
  4340. }
  4341. // Abstracts iterators into args as a stream of tokens, with option arguments uniformly handled
  4342. class TokenStream {
  4343. using Iterator = std::vector<std::string>::const_iterator;
  4344. Iterator it;
  4345. Iterator itEnd;
  4346. std::vector<Token> m_tokenBuffer;
  4347. void loadBuffer() {
  4348. m_tokenBuffer.resize( 0 );
  4349. // Skip any empty strings
  4350. while( it != itEnd && it->empty() )
  4351. ++it;
  4352. if( it != itEnd ) {
  4353. auto const &next = *it;
  4354. if( isOptPrefix( next[0] ) ) {
  4355. auto delimiterPos = next.find_first_of( " :=" );
  4356. if( delimiterPos != std::string::npos ) {
  4357. m_tokenBuffer.push_back( { TokenType::Option, next.substr( 0, delimiterPos ) } );
  4358. m_tokenBuffer.push_back( { TokenType::Argument, next.substr( delimiterPos + 1 ) } );
  4359. } else {
  4360. if( next[1] != '-' && next.size() > 2 ) {
  4361. std::string opt = "- ";
  4362. for( size_t i = 1; i < next.size(); ++i ) {
  4363. opt[1] = next[i];
  4364. m_tokenBuffer.push_back( { TokenType::Option, opt } );
  4365. }
  4366. } else {
  4367. m_tokenBuffer.push_back( { TokenType::Option, next } );
  4368. }
  4369. }
  4370. } else {
  4371. m_tokenBuffer.push_back( { TokenType::Argument, next } );
  4372. }
  4373. }
  4374. }
  4375. public:
  4376. explicit TokenStream( Args const &args ) : TokenStream( args.m_args.begin(), args.m_args.end() ) {}
  4377. TokenStream( Iterator it, Iterator itEnd ) : it( it ), itEnd( itEnd ) {
  4378. loadBuffer();
  4379. }
  4380. explicit operator bool() const {
  4381. return !m_tokenBuffer.empty() || it != itEnd;
  4382. }
  4383. auto count() const -> size_t { return m_tokenBuffer.size() + (itEnd - it); }
  4384. auto operator*() const -> Token {
  4385. assert( !m_tokenBuffer.empty() );
  4386. return m_tokenBuffer.front();
  4387. }
  4388. auto operator->() const -> Token const * {
  4389. assert( !m_tokenBuffer.empty() );
  4390. return &m_tokenBuffer.front();
  4391. }
  4392. auto operator++() -> TokenStream & {
  4393. if( m_tokenBuffer.size() >= 2 ) {
  4394. m_tokenBuffer.erase( m_tokenBuffer.begin() );
  4395. } else {
  4396. if( it != itEnd )
  4397. ++it;
  4398. loadBuffer();
  4399. }
  4400. return *this;
  4401. }
  4402. };
  4403. class ResultBase {
  4404. public:
  4405. enum Type {
  4406. Ok, LogicError, RuntimeError
  4407. };
  4408. protected:
  4409. ResultBase( Type type ) : m_type( type ) {}
  4410. virtual ~ResultBase() = default;
  4411. virtual void enforceOk() const = 0;
  4412. Type m_type;
  4413. };
  4414. template<typename T>
  4415. class ResultValueBase : public ResultBase {
  4416. public:
  4417. auto value() const -> T const & {
  4418. enforceOk();
  4419. return m_value;
  4420. }
  4421. protected:
  4422. ResultValueBase( Type type ) : ResultBase( type ) {}
  4423. ResultValueBase( ResultValueBase const &other ) : ResultBase( other ) {
  4424. if( m_type == ResultBase::Ok )
  4425. new( &m_value ) T( other.m_value );
  4426. }
  4427. ResultValueBase( Type, T const &value ) : ResultBase( Ok ) {
  4428. new( &m_value ) T( value );
  4429. }
  4430. auto operator=( ResultValueBase const &other ) -> ResultValueBase & {
  4431. if( m_type == ResultBase::Ok )
  4432. m_value.~T();
  4433. ResultBase::operator=(other);
  4434. if( m_type == ResultBase::Ok )
  4435. new( &m_value ) T( other.m_value );
  4436. return *this;
  4437. }
  4438. ~ResultValueBase() override {
  4439. if( m_type == Ok )
  4440. m_value.~T();
  4441. }
  4442. union {
  4443. T m_value;
  4444. };
  4445. };
  4446. template<>
  4447. class ResultValueBase<void> : public ResultBase {
  4448. protected:
  4449. using ResultBase::ResultBase;
  4450. };
  4451. template<typename T = void>
  4452. class BasicResult : public ResultValueBase<T> {
  4453. public:
  4454. template<typename U>
  4455. explicit BasicResult( BasicResult<U> const &other )
  4456. : ResultValueBase<T>( other.type() ),
  4457. m_errorMessage( other.errorMessage() )
  4458. {
  4459. assert( type() != ResultBase::Ok );
  4460. }
  4461. template<typename U>
  4462. static auto ok( U const &value ) -> BasicResult { return { ResultBase::Ok, value }; }
  4463. static auto ok() -> BasicResult { return { ResultBase::Ok }; }
  4464. static auto logicError( std::string const &message ) -> BasicResult { return { ResultBase::LogicError, message }; }
  4465. static auto runtimeError( std::string const &message ) -> BasicResult { return { ResultBase::RuntimeError, message }; }
  4466. explicit operator bool() const { return m_type == ResultBase::Ok; }
  4467. auto type() const -> ResultBase::Type { return m_type; }
  4468. auto errorMessage() const -> std::string { return m_errorMessage; }
  4469. protected:
  4470. void enforceOk() const override {
  4471. // !TBD: If no exceptions, std::terminate here or something
  4472. switch( m_type ) {
  4473. case ResultBase::LogicError:
  4474. throw std::logic_error( m_errorMessage );
  4475. case ResultBase::RuntimeError:
  4476. throw std::runtime_error( m_errorMessage );
  4477. case ResultBase::Ok:
  4478. break;
  4479. }
  4480. }
  4481. std::string m_errorMessage; // Only populated if resultType is an error
  4482. BasicResult( ResultBase::Type type, std::string const &message )
  4483. : ResultValueBase<T>(type),
  4484. m_errorMessage(message)
  4485. {
  4486. assert( m_type != ResultBase::Ok );
  4487. }
  4488. using ResultValueBase<T>::ResultValueBase;
  4489. using ResultBase::m_type;
  4490. };
  4491. enum class ParseResultType {
  4492. Matched, NoMatch, ShortCircuitAll, ShortCircuitSame
  4493. };
  4494. class ParseState {
  4495. public:
  4496. ParseState( ParseResultType type, TokenStream const &remainingTokens )
  4497. : m_type(type),
  4498. m_remainingTokens( remainingTokens )
  4499. {}
  4500. auto type() const -> ParseResultType { return m_type; }
  4501. auto remainingTokens() const -> TokenStream { return m_remainingTokens; }
  4502. private:
  4503. ParseResultType m_type;
  4504. TokenStream m_remainingTokens;
  4505. };
  4506. using Result = BasicResult<void>;
  4507. using ParserResult = BasicResult<ParseResultType>;
  4508. using InternalParseResult = BasicResult<ParseState>;
  4509. struct HelpColumns {
  4510. std::string left;
  4511. std::string right;
  4512. };
  4513. template<typename T>
  4514. inline auto convertInto( std::string const &source, T& target ) -> ParserResult {
  4515. std::stringstream ss;
  4516. ss << source;
  4517. ss >> target;
  4518. if( ss.fail() )
  4519. return ParserResult::runtimeError( "Unable to convert '" + source + "' to destination type" );
  4520. else
  4521. return ParserResult::ok( ParseResultType::Matched );
  4522. }
  4523. inline auto convertInto( std::string const &source, std::string& target ) -> ParserResult {
  4524. target = source;
  4525. return ParserResult::ok( ParseResultType::Matched );
  4526. }
  4527. inline auto convertInto( std::string const &source, bool &target ) -> ParserResult {
  4528. std::string srcLC = source;
  4529. std::transform( srcLC.begin(), srcLC.end(), srcLC.begin(), []( char c ) { return static_cast<char>( ::tolower(c) ); } );
  4530. if (srcLC == "y" || srcLC == "1" || srcLC == "true" || srcLC == "yes" || srcLC == "on")
  4531. target = true;
  4532. else if (srcLC == "n" || srcLC == "0" || srcLC == "false" || srcLC == "no" || srcLC == "off")
  4533. target = false;
  4534. else
  4535. return ParserResult::runtimeError( "Expected a boolean value but did not recognise: '" + source + "'" );
  4536. return ParserResult::ok( ParseResultType::Matched );
  4537. }
  4538. struct NonCopyable {
  4539. NonCopyable() = default;
  4540. NonCopyable( NonCopyable const & ) = delete;
  4541. NonCopyable( NonCopyable && ) = delete;
  4542. NonCopyable &operator=( NonCopyable const & ) = delete;
  4543. NonCopyable &operator=( NonCopyable && ) = delete;
  4544. };
  4545. struct BoundRef : NonCopyable {
  4546. virtual ~BoundRef() = default;
  4547. virtual auto isContainer() const -> bool { return false; }
  4548. };
  4549. struct BoundValueRefBase : BoundRef {
  4550. virtual auto setValue( std::string const &arg ) -> ParserResult = 0;
  4551. };
  4552. struct BoundFlagRefBase : BoundRef {
  4553. virtual auto setFlag( bool flag ) -> ParserResult = 0;
  4554. };
  4555. template<typename T>
  4556. struct BoundValueRef : BoundValueRefBase {
  4557. T &m_ref;
  4558. explicit BoundValueRef( T &ref ) : m_ref( ref ) {}
  4559. auto setValue( std::string const &arg ) -> ParserResult override {
  4560. return convertInto( arg, m_ref );
  4561. }
  4562. };
  4563. template<typename T>
  4564. struct BoundValueRef<std::vector<T>> : BoundValueRefBase {
  4565. std::vector<T> &m_ref;
  4566. explicit BoundValueRef( std::vector<T> &ref ) : m_ref( ref ) {}
  4567. auto isContainer() const -> bool override { return true; }
  4568. auto setValue( std::string const &arg ) -> ParserResult override {
  4569. T temp;
  4570. auto result = convertInto( arg, temp );
  4571. if( result )
  4572. m_ref.push_back( temp );
  4573. return result;
  4574. }
  4575. };
  4576. struct BoundFlagRef : BoundFlagRefBase {
  4577. bool &m_ref;
  4578. explicit BoundFlagRef( bool &ref ) : m_ref( ref ) {}
  4579. auto setFlag( bool flag ) -> ParserResult override {
  4580. m_ref = flag;
  4581. return ParserResult::ok( ParseResultType::Matched );
  4582. }
  4583. };
  4584. template<typename ReturnType>
  4585. struct LambdaInvoker {
  4586. static_assert( std::is_same<ReturnType, ParserResult>::value, "Lambda must return void or clara::ParserResult" );
  4587. template<typename L, typename ArgType>
  4588. static auto invoke( L const &lambda, ArgType const &arg ) -> ParserResult {
  4589. return lambda( arg );
  4590. }
  4591. };
  4592. template<>
  4593. struct LambdaInvoker<void> {
  4594. template<typename L, typename ArgType>
  4595. static auto invoke( L const &lambda, ArgType const &arg ) -> ParserResult {
  4596. lambda( arg );
  4597. return ParserResult::ok( ParseResultType::Matched );
  4598. }
  4599. };
  4600. template<typename ArgType, typename L>
  4601. inline auto invokeLambda( L const &lambda, std::string const &arg ) -> ParserResult {
  4602. ArgType temp{};
  4603. auto result = convertInto( arg, temp );
  4604. return !result
  4605. ? result
  4606. : LambdaInvoker<typename UnaryLambdaTraits<L>::ReturnType>::invoke( lambda, temp );
  4607. }
  4608. template<typename L>
  4609. struct BoundLambda : BoundValueRefBase {
  4610. L m_lambda;
  4611. static_assert( UnaryLambdaTraits<L>::isValid, "Supplied lambda must take exactly one argument" );
  4612. explicit BoundLambda( L const &lambda ) : m_lambda( lambda ) {}
  4613. auto setValue( std::string const &arg ) -> ParserResult override {
  4614. return invokeLambda<typename UnaryLambdaTraits<L>::ArgType>( m_lambda, arg );
  4615. }
  4616. };
  4617. template<typename L>
  4618. struct BoundFlagLambda : BoundFlagRefBase {
  4619. L m_lambda;
  4620. static_assert( UnaryLambdaTraits<L>::isValid, "Supplied lambda must take exactly one argument" );
  4621. static_assert( std::is_same<typename UnaryLambdaTraits<L>::ArgType, bool>::value, "flags must be boolean" );
  4622. explicit BoundFlagLambda( L const &lambda ) : m_lambda( lambda ) {}
  4623. auto setFlag( bool flag ) -> ParserResult override {
  4624. return LambdaInvoker<typename UnaryLambdaTraits<L>::ReturnType>::invoke( m_lambda, flag );
  4625. }
  4626. };
  4627. enum class Optionality { Optional, Required };
  4628. struct Parser;
  4629. class ParserBase {
  4630. public:
  4631. virtual ~ParserBase() = default;
  4632. virtual auto validate() const -> Result { return Result::ok(); }
  4633. virtual auto parse( std::string const& exeName, TokenStream const &tokens) const -> InternalParseResult = 0;
  4634. virtual auto cardinality() const -> size_t { return 1; }
  4635. auto parse( Args const &args ) const -> InternalParseResult {
  4636. return parse( args.exeName(), TokenStream( args ) );
  4637. }
  4638. };
  4639. template<typename DerivedT>
  4640. class ComposableParserImpl : public ParserBase {
  4641. public:
  4642. template<typename T>
  4643. auto operator|( T const &other ) const -> Parser;
  4644. template<typename T>
  4645. auto operator+( T const &other ) const -> Parser;
  4646. };
  4647. // Common code and state for Args and Opts
  4648. template<typename DerivedT>
  4649. class ParserRefImpl : public ComposableParserImpl<DerivedT> {
  4650. protected:
  4651. Optionality m_optionality = Optionality::Optional;
  4652. std::shared_ptr<BoundRef> m_ref;
  4653. std::string m_hint;
  4654. std::string m_description;
  4655. explicit ParserRefImpl( std::shared_ptr<BoundRef> const &ref ) : m_ref( ref ) {}
  4656. public:
  4657. template<typename T>
  4658. ParserRefImpl( T &ref, std::string const &hint )
  4659. : m_ref( std::make_shared<BoundValueRef<T>>( ref ) ),
  4660. m_hint( hint )
  4661. {}
  4662. template<typename LambdaT>
  4663. ParserRefImpl( LambdaT const &ref, std::string const &hint )
  4664. : m_ref( std::make_shared<BoundLambda<LambdaT>>( ref ) ),
  4665. m_hint(hint)
  4666. {}
  4667. auto operator()( std::string const &description ) -> DerivedT & {
  4668. m_description = description;
  4669. return static_cast<DerivedT &>( *this );
  4670. }
  4671. auto optional() -> DerivedT & {
  4672. m_optionality = Optionality::Optional;
  4673. return static_cast<DerivedT &>( *this );
  4674. };
  4675. auto required() -> DerivedT & {
  4676. m_optionality = Optionality::Required;
  4677. return static_cast<DerivedT &>( *this );
  4678. };
  4679. auto isOptional() const -> bool {
  4680. return m_optionality == Optionality::Optional;
  4681. }
  4682. auto cardinality() const -> size_t override {
  4683. if( m_ref->isContainer() )
  4684. return 0;
  4685. else
  4686. return 1;
  4687. }
  4688. auto hint() const -> std::string { return m_hint; }
  4689. };
  4690. class ExeName : public ComposableParserImpl<ExeName> {
  4691. std::shared_ptr<std::string> m_name;
  4692. std::shared_ptr<BoundValueRefBase> m_ref;
  4693. template<typename LambdaT>
  4694. static auto makeRef(LambdaT const &lambda) -> std::shared_ptr<BoundValueRefBase> {
  4695. return std::make_shared<BoundLambda<LambdaT>>( lambda) ;
  4696. }
  4697. public:
  4698. ExeName() : m_name( std::make_shared<std::string>( "<executable>" ) ) {}
  4699. explicit ExeName( std::string &ref ) : ExeName() {
  4700. m_ref = std::make_shared<BoundValueRef<std::string>>( ref );
  4701. }
  4702. template<typename LambdaT>
  4703. explicit ExeName( LambdaT const& lambda ) : ExeName() {
  4704. m_ref = std::make_shared<BoundLambda<LambdaT>>( lambda );
  4705. }
  4706. // The exe name is not parsed out of the normal tokens, but is handled specially
  4707. auto parse( std::string const&, TokenStream const &tokens ) const -> InternalParseResult override {
  4708. return InternalParseResult::ok( ParseState( ParseResultType::NoMatch, tokens ) );
  4709. }
  4710. auto name() const -> std::string { return *m_name; }
  4711. auto set( std::string const& newName ) -> ParserResult {
  4712. auto lastSlash = newName.find_last_of( "\\/" );
  4713. auto filename = ( lastSlash == std::string::npos )
  4714. ? newName
  4715. : newName.substr( lastSlash+1 );
  4716. *m_name = filename;
  4717. if( m_ref )
  4718. return m_ref->setValue( filename );
  4719. else
  4720. return ParserResult::ok( ParseResultType::Matched );
  4721. }
  4722. };
  4723. class Arg : public ParserRefImpl<Arg> {
  4724. public:
  4725. using ParserRefImpl::ParserRefImpl;
  4726. auto parse( std::string const &, TokenStream const &tokens ) const -> InternalParseResult override {
  4727. auto validationResult = validate();
  4728. if( !validationResult )
  4729. return InternalParseResult( validationResult );
  4730. auto remainingTokens = tokens;
  4731. auto const &token = *remainingTokens;
  4732. if( token.type != TokenType::Argument )
  4733. return InternalParseResult::ok( ParseState( ParseResultType::NoMatch, remainingTokens ) );
  4734. assert( dynamic_cast<detail::BoundValueRefBase*>( m_ref.get() ) );
  4735. auto valueRef = static_cast<detail::BoundValueRefBase*>( m_ref.get() );
  4736. auto result = valueRef->setValue( remainingTokens->token );
  4737. if( !result )
  4738. return InternalParseResult( result );
  4739. else
  4740. return InternalParseResult::ok( ParseState( ParseResultType::Matched, ++remainingTokens ) );
  4741. }
  4742. };
  4743. inline auto normaliseOpt( std::string const &optName ) -> std::string {
  4744. #ifdef CATCH_PLATFORM_WINDOWS
  4745. if( optName[0] == '/' )
  4746. return "-" + optName.substr( 1 );
  4747. else
  4748. #endif
  4749. return optName;
  4750. }
  4751. class Opt : public ParserRefImpl<Opt> {
  4752. protected:
  4753. std::vector<std::string> m_optNames;
  4754. public:
  4755. template<typename LambdaT>
  4756. explicit Opt( LambdaT const &ref ) : ParserRefImpl( std::make_shared<BoundFlagLambda<LambdaT>>( ref ) ) {}
  4757. explicit Opt( bool &ref ) : ParserRefImpl( std::make_shared<BoundFlagRef>( ref ) ) {}
  4758. template<typename LambdaT>
  4759. Opt( LambdaT const &ref, std::string const &hint ) : ParserRefImpl( ref, hint ) {}
  4760. template<typename T>
  4761. Opt( T &ref, std::string const &hint ) : ParserRefImpl( ref, hint ) {}
  4762. auto operator[]( std::string const &optName ) -> Opt & {
  4763. m_optNames.push_back( optName );
  4764. return *this;
  4765. }
  4766. auto getHelpColumns() const -> std::vector<HelpColumns> {
  4767. std::ostringstream oss;
  4768. bool first = true;
  4769. for( auto const &opt : m_optNames ) {
  4770. if (first)
  4771. first = false;
  4772. else
  4773. oss << ", ";
  4774. oss << opt;
  4775. }
  4776. if( !m_hint.empty() )
  4777. oss << " <" << m_hint << ">";
  4778. return { { oss.str(), m_description } };
  4779. }
  4780. auto isMatch( std::string const &optToken ) const -> bool {
  4781. auto normalisedToken = normaliseOpt( optToken );
  4782. for( auto const &name : m_optNames ) {
  4783. if( normaliseOpt( name ) == normalisedToken )
  4784. return true;
  4785. }
  4786. return false;
  4787. }
  4788. using ParserBase::parse;
  4789. auto parse( std::string const&, TokenStream const &tokens ) const -> InternalParseResult override {
  4790. auto validationResult = validate();
  4791. if( !validationResult )
  4792. return InternalParseResult( validationResult );
  4793. auto remainingTokens = tokens;
  4794. if( remainingTokens && remainingTokens->type == TokenType::Option ) {
  4795. auto const &token = *remainingTokens;
  4796. if( isMatch(token.token ) ) {
  4797. if( auto flagRef = dynamic_cast<detail::BoundFlagRefBase*>( m_ref.get() ) ) {
  4798. auto result = flagRef->setFlag( true );
  4799. if( !result )
  4800. return InternalParseResult( result );
  4801. if( result.value() == ParseResultType::ShortCircuitAll )
  4802. return InternalParseResult::ok( ParseState( result.value(), remainingTokens ) );
  4803. } else {
  4804. assert( dynamic_cast<detail::BoundValueRefBase*>( m_ref.get() ) );
  4805. auto valueRef = static_cast<detail::BoundValueRefBase*>( m_ref.get() );
  4806. ++remainingTokens;
  4807. if( !remainingTokens )
  4808. return InternalParseResult::runtimeError( "Expected argument following " + token.token );
  4809. auto const &argToken = *remainingTokens;
  4810. if( argToken.type != TokenType::Argument )
  4811. return InternalParseResult::runtimeError( "Expected argument following " + token.token );
  4812. auto result = valueRef->setValue( argToken.token );
  4813. if( !result )
  4814. return InternalParseResult( result );
  4815. if( result.value() == ParseResultType::ShortCircuitAll )
  4816. return InternalParseResult::ok( ParseState( result.value(), remainingTokens ) );
  4817. }
  4818. return InternalParseResult::ok( ParseState( ParseResultType::Matched, ++remainingTokens ) );
  4819. }
  4820. }
  4821. return InternalParseResult::ok( ParseState( ParseResultType::NoMatch, remainingTokens ) );
  4822. }
  4823. auto validate() const -> Result override {
  4824. if( m_optNames.empty() )
  4825. return Result::logicError( "No options supplied to Opt" );
  4826. for( auto const &name : m_optNames ) {
  4827. if( name.empty() )
  4828. return Result::logicError( "Option name cannot be empty" );
  4829. #ifdef CATCH_PLATFORM_WINDOWS
  4830. if( name[0] != '-' && name[0] != '/' )
  4831. return Result::logicError( "Option name must begin with '-' or '/'" );
  4832. #else
  4833. if( name[0] != '-' )
  4834. return Result::logicError( "Option name must begin with '-'" );
  4835. #endif
  4836. }
  4837. return ParserRefImpl::validate();
  4838. }
  4839. };
  4840. struct Help : Opt {
  4841. Help( bool &showHelpFlag )
  4842. : Opt([&]( bool flag ) {
  4843. showHelpFlag = flag;
  4844. return ParserResult::ok( ParseResultType::ShortCircuitAll );
  4845. })
  4846. {
  4847. static_cast<Opt &>( *this )
  4848. ("display usage information")
  4849. ["-?"]["-h"]["--help"]
  4850. .optional();
  4851. }
  4852. };
  4853. struct Parser : ParserBase {
  4854. mutable ExeName m_exeName;
  4855. std::vector<Opt> m_options;
  4856. std::vector<Arg> m_args;
  4857. auto operator|=( ExeName const &exeName ) -> Parser & {
  4858. m_exeName = exeName;
  4859. return *this;
  4860. }
  4861. auto operator|=( Arg const &arg ) -> Parser & {
  4862. m_args.push_back(arg);
  4863. return *this;
  4864. }
  4865. auto operator|=( Opt const &opt ) -> Parser & {
  4866. m_options.push_back(opt);
  4867. return *this;
  4868. }
  4869. auto operator|=( Parser const &other ) -> Parser & {
  4870. m_options.insert(m_options.end(), other.m_options.begin(), other.m_options.end());
  4871. m_args.insert(m_args.end(), other.m_args.begin(), other.m_args.end());
  4872. return *this;
  4873. }
  4874. template<typename T>
  4875. auto operator|( T const &other ) const -> Parser {
  4876. return Parser( *this ) |= other;
  4877. }
  4878. // Forward deprecated interface with '+' instead of '|'
  4879. template<typename T>
  4880. auto operator+=( T const &other ) -> Parser & { return operator|=( other ); }
  4881. template<typename T>
  4882. auto operator+( T const &other ) const -> Parser { return operator|( other ); }
  4883. auto getHelpColumns() const -> std::vector<HelpColumns> {
  4884. std::vector<HelpColumns> cols;
  4885. for (auto const &o : m_options) {
  4886. auto childCols = o.getHelpColumns();
  4887. cols.insert( cols.end(), childCols.begin(), childCols.end() );
  4888. }
  4889. return cols;
  4890. }
  4891. void writeToStream( std::ostream &os ) const {
  4892. if (!m_exeName.name().empty()) {
  4893. os << "usage:\n" << " " << m_exeName.name() << " ";
  4894. bool required = true, first = true;
  4895. for( auto const &arg : m_args ) {
  4896. if (first)
  4897. first = false;
  4898. else
  4899. os << " ";
  4900. if( arg.isOptional() && required ) {
  4901. os << "[";
  4902. required = false;
  4903. }
  4904. os << "<" << arg.hint() << ">";
  4905. if( arg.cardinality() == 0 )
  4906. os << " ... ";
  4907. }
  4908. if( !required )
  4909. os << "]";
  4910. if( !m_options.empty() )
  4911. os << " options";
  4912. os << "\n\nwhere options are:" << std::endl;
  4913. }
  4914. auto rows = getHelpColumns();
  4915. size_t consoleWidth = CATCH_CLARA_CONFIG_CONSOLE_WIDTH;
  4916. size_t optWidth = 0;
  4917. for( auto const &cols : rows )
  4918. optWidth = (std::max)(optWidth, cols.left.size() + 2);
  4919. optWidth = (std::min)(optWidth, consoleWidth/2);
  4920. for( auto const &cols : rows ) {
  4921. auto row =
  4922. TextFlow::Column( cols.left ).width( optWidth ).indent( 2 ) +
  4923. TextFlow::Spacer(4) +
  4924. TextFlow::Column( cols.right ).width( consoleWidth - 7 - optWidth );
  4925. os << row << std::endl;
  4926. }
  4927. }
  4928. friend auto operator<<( std::ostream &os, Parser const &parser ) -> std::ostream& {
  4929. parser.writeToStream( os );
  4930. return os;
  4931. }
  4932. auto validate() const -> Result override {
  4933. for( auto const &opt : m_options ) {
  4934. auto result = opt.validate();
  4935. if( !result )
  4936. return result;
  4937. }
  4938. for( auto const &arg : m_args ) {
  4939. auto result = arg.validate();
  4940. if( !result )
  4941. return result;
  4942. }
  4943. return Result::ok();
  4944. }
  4945. using ParserBase::parse;
  4946. auto parse( std::string const& exeName, TokenStream const &tokens ) const -> InternalParseResult override {
  4947. struct ParserInfo {
  4948. ParserBase const* parser = nullptr;
  4949. size_t count = 0;
  4950. };
  4951. const size_t totalParsers = m_options.size() + m_args.size();
  4952. assert( totalParsers < 512 );
  4953. // ParserInfo parseInfos[totalParsers]; // <-- this is what we really want to do
  4954. ParserInfo parseInfos[512];
  4955. {
  4956. size_t i = 0;
  4957. for (auto const &opt : m_options) parseInfos[i++].parser = &opt;
  4958. for (auto const &arg : m_args) parseInfos[i++].parser = &arg;
  4959. }
  4960. m_exeName.set( exeName );
  4961. auto result = InternalParseResult::ok( ParseState( ParseResultType::NoMatch, tokens ) );
  4962. while( result.value().remainingTokens() ) {
  4963. bool tokenParsed = false;
  4964. for( size_t i = 0; i < totalParsers; ++i ) {
  4965. auto& parseInfo = parseInfos[i];
  4966. if( parseInfo.parser->cardinality() == 0 || parseInfo.count < parseInfo.parser->cardinality() ) {
  4967. result = parseInfo.parser->parse(exeName, result.value().remainingTokens());
  4968. if (!result)
  4969. return result;
  4970. if (result.value().type() != ParseResultType::NoMatch) {
  4971. tokenParsed = true;
  4972. ++parseInfo.count;
  4973. break;
  4974. }
  4975. }
  4976. }
  4977. if( result.value().type() == ParseResultType::ShortCircuitAll )
  4978. return result;
  4979. if( !tokenParsed )
  4980. return InternalParseResult::runtimeError( "Unrecognised token: " + result.value().remainingTokens()->token );
  4981. }
  4982. // !TBD Check missing required options
  4983. return result;
  4984. }
  4985. };
  4986. template<typename DerivedT>
  4987. template<typename T>
  4988. auto ComposableParserImpl<DerivedT>::operator|( T const &other ) const -> Parser {
  4989. return Parser() | static_cast<DerivedT const &>( *this ) | other;
  4990. }
  4991. } // namespace detail
  4992. // A Combined parser
  4993. using detail::Parser;
  4994. // A parser for options
  4995. using detail::Opt;
  4996. // A parser for arguments
  4997. using detail::Arg;
  4998. // Wrapper for argc, argv from main()
  4999. using detail::Args;
  5000. // Specifies the name of the executable
  5001. using detail::ExeName;
  5002. // Convenience wrapper for option parser that specifies the help option
  5003. using detail::Help;
  5004. // enum of result types from a parse
  5005. using detail::ParseResultType;
  5006. // Result type for parser operation
  5007. using detail::ParserResult;
  5008. }} // namespace Catch::clara
  5009. // end clara.hpp
  5010. #ifdef __clang__
  5011. #pragma clang diagnostic pop
  5012. #endif
  5013. // Restore Clara's value for console width, if present
  5014. #ifdef CATCH_TEMP_CLARA_CONFIG_CONSOLE_WIDTH
  5015. #define CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH CATCH_TEMP_CLARA_CONFIG_CONSOLE_WIDTH
  5016. #undef CATCH_TEMP_CLARA_CONFIG_CONSOLE_WIDTH
  5017. #endif
  5018. // end catch_clara.h
  5019. namespace Catch {
  5020. clara::Parser makeCommandLineParser( ConfigData& config );
  5021. } // end namespace Catch
  5022. // end catch_commandline.h
  5023. #include <fstream>
  5024. #include <ctime>
  5025. namespace Catch {
  5026. clara::Parser makeCommandLineParser( ConfigData& config ) {
  5027. using namespace clara;
  5028. auto const setWarning = [&]( std::string const& warning ) {
  5029. if( warning != "NoAssertions" )
  5030. return ParserResult::runtimeError( "Unrecognised warning: '" + warning + "'" );
  5031. config.warnings = static_cast<WarnAbout::What>( config.warnings | WarnAbout::NoAssertions );
  5032. return ParserResult::ok( ParseResultType::Matched );
  5033. };
  5034. auto const loadTestNamesFromFile = [&]( std::string const& filename ) {
  5035. std::ifstream f( filename.c_str() );
  5036. if( !f.is_open() )
  5037. return ParserResult::runtimeError( "Unable to load input file: '" + filename + "'" );
  5038. std::string line;
  5039. while( std::getline( f, line ) ) {
  5040. line = trim(line);
  5041. if( !line.empty() && !startsWith( line, '#' ) ) {
  5042. if( !startsWith( line, '"' ) )
  5043. line = '"' + line + '"';
  5044. config.testsOrTags.push_back( line + ',' );
  5045. }
  5046. }
  5047. return ParserResult::ok( ParseResultType::Matched );
  5048. };
  5049. auto const setTestOrder = [&]( std::string const& order ) {
  5050. if( startsWith( "declared", order ) )
  5051. config.runOrder = RunTests::InDeclarationOrder;
  5052. else if( startsWith( "lexical", order ) )
  5053. config.runOrder = RunTests::InLexicographicalOrder;
  5054. else if( startsWith( "random", order ) )
  5055. config.runOrder = RunTests::InRandomOrder;
  5056. else
  5057. return clara::ParserResult::runtimeError( "Unrecognised ordering: '" + order + "'" );
  5058. return ParserResult::ok( ParseResultType::Matched );
  5059. };
  5060. auto const setRngSeed = [&]( std::string const& seed ) {
  5061. if( seed != "time" )
  5062. return clara::detail::convertInto( seed, config.rngSeed );
  5063. config.rngSeed = static_cast<unsigned int>( std::time(nullptr) );
  5064. return ParserResult::ok( ParseResultType::Matched );
  5065. };
  5066. auto const setColourUsage = [&]( std::string const& useColour ) {
  5067. auto mode = toLower( useColour );
  5068. if( mode == "yes" )
  5069. config.useColour = UseColour::Yes;
  5070. else if( mode == "no" )
  5071. config.useColour = UseColour::No;
  5072. else if( mode == "auto" )
  5073. config.useColour = UseColour::Auto;
  5074. else
  5075. return ParserResult::runtimeError( "colour mode must be one of: auto, yes or no. '" + useColour + "' not recognised" );
  5076. return ParserResult::ok( ParseResultType::Matched );
  5077. };
  5078. auto const setWaitForKeypress = [&]( std::string const& keypress ) {
  5079. auto keypressLc = toLower( keypress );
  5080. if( keypressLc == "start" )
  5081. config.waitForKeypress = WaitForKeypress::BeforeStart;
  5082. else if( keypressLc == "exit" )
  5083. config.waitForKeypress = WaitForKeypress::BeforeExit;
  5084. else if( keypressLc == "both" )
  5085. config.waitForKeypress = WaitForKeypress::BeforeStartAndExit;
  5086. else
  5087. return ParserResult::runtimeError( "keypress argument must be one of: start, exit or both. '" + keypress + "' not recognised" );
  5088. return ParserResult::ok( ParseResultType::Matched );
  5089. };
  5090. auto const setVerbosity = [&]( std::string const& verbosity ) {
  5091. auto lcVerbosity = toLower( verbosity );
  5092. if( lcVerbosity == "quiet" )
  5093. config.verbosity = Verbosity::Quiet;
  5094. else if( lcVerbosity == "normal" )
  5095. config.verbosity = Verbosity::Normal;
  5096. else if( lcVerbosity == "high" )
  5097. config.verbosity = Verbosity::High;
  5098. else
  5099. return ParserResult::runtimeError( "Unrecognised verbosity, '" + verbosity + "'" );
  5100. return ParserResult::ok( ParseResultType::Matched );
  5101. };
  5102. auto cli
  5103. = ExeName( config.processName )
  5104. | Help( config.showHelp )
  5105. | Opt( config.listTests )
  5106. ["-l"]["--list-tests"]
  5107. ( "list all/matching test cases" )
  5108. | Opt( config.listTags )
  5109. ["-t"]["--list-tags"]
  5110. ( "list all/matching tags" )
  5111. | Opt( config.showSuccessfulTests )
  5112. ["-s"]["--success"]
  5113. ( "include successful tests in output" )
  5114. | Opt( config.shouldDebugBreak )
  5115. ["-b"]["--break"]
  5116. ( "break into debugger on failure" )
  5117. | Opt( config.noThrow )
  5118. ["-e"]["--nothrow"]
  5119. ( "skip exception tests" )
  5120. | Opt( config.showInvisibles )
  5121. ["-i"]["--invisibles"]
  5122. ( "show invisibles (tabs, newlines)" )
  5123. | Opt( config.outputFilename, "filename" )
  5124. ["-o"]["--out"]
  5125. ( "output filename" )
  5126. | Opt( config.reporterNames, "name" )
  5127. ["-r"]["--reporter"]
  5128. ( "reporter to use (defaults to console)" )
  5129. | Opt( config.name, "name" )
  5130. ["-n"]["--name"]
  5131. ( "suite name" )
  5132. | Opt( [&]( bool ){ config.abortAfter = 1; } )
  5133. ["-a"]["--abort"]
  5134. ( "abort at first failure" )
  5135. | Opt( [&]( int x ){ config.abortAfter = x; }, "no. failures" )
  5136. ["-x"]["--abortx"]
  5137. ( "abort after x failures" )
  5138. | Opt( setWarning, "warning name" )
  5139. ["-w"]["--warn"]
  5140. ( "enable warnings" )
  5141. | Opt( [&]( bool flag ) { config.showDurations = flag ? ShowDurations::Always : ShowDurations::Never; }, "yes|no" )
  5142. ["-d"]["--durations"]
  5143. ( "show test durations" )
  5144. | Opt( loadTestNamesFromFile, "filename" )
  5145. ["-f"]["--input-file"]
  5146. ( "load test names to run from a file" )
  5147. | Opt( config.filenamesAsTags )
  5148. ["-#"]["--filenames-as-tags"]
  5149. ( "adds a tag for the filename" )
  5150. | Opt( config.sectionsToRun, "section name" )
  5151. ["-c"]["--section"]
  5152. ( "specify section to run" )
  5153. | Opt( setVerbosity, "quiet|normal|high" )
  5154. ["-v"]["--verbosity"]
  5155. ( "set output verbosity" )
  5156. | Opt( config.listTestNamesOnly )
  5157. ["--list-test-names-only"]
  5158. ( "list all/matching test cases names only" )
  5159. | Opt( config.listReporters )
  5160. ["--list-reporters"]
  5161. ( "list all reporters" )
  5162. | Opt( setTestOrder, "decl|lex|rand" )
  5163. ["--order"]
  5164. ( "test case order (defaults to decl)" )
  5165. | Opt( setRngSeed, "'time'|number" )
  5166. ["--rng-seed"]
  5167. ( "set a specific seed for random numbers" )
  5168. | Opt( setColourUsage, "yes|no" )
  5169. ["--use-colour"]
  5170. ( "should output be colourised" )
  5171. | Opt( config.libIdentify )
  5172. ["--libidentify"]
  5173. ( "report name and version according to libidentify standard" )
  5174. | Opt( setWaitForKeypress, "start|exit|both" )
  5175. ["--wait-for-keypress"]
  5176. ( "waits for a keypress before exiting" )
  5177. | Opt( config.benchmarkResolutionMultiple, "multiplier" )
  5178. ["--benchmark-resolution-multiple"]
  5179. ( "multiple of clock resolution to run benchmarks" )
  5180. | Arg( config.testsOrTags, "test name|pattern|tags" )
  5181. ( "which test or tests to use" );
  5182. return cli;
  5183. }
  5184. } // end namespace Catch
  5185. // end catch_commandline.cpp
  5186. // start catch_common.cpp
  5187. #include <cstring>
  5188. #include <ostream>
  5189. namespace Catch {
  5190. bool SourceLineInfo::empty() const noexcept {
  5191. return file[0] == '\0';
  5192. }
  5193. bool SourceLineInfo::operator == ( SourceLineInfo const& other ) const noexcept {
  5194. return line == other.line && (file == other.file || std::strcmp(file, other.file) == 0);
  5195. }
  5196. bool SourceLineInfo::operator < ( SourceLineInfo const& other ) const noexcept {
  5197. return line < other.line || ( line == other.line && (std::strcmp(file, other.file) < 0));
  5198. }
  5199. std::ostream& operator << ( std::ostream& os, SourceLineInfo const& info ) {
  5200. #ifndef __GNUG__
  5201. os << info.file << '(' << info.line << ')';
  5202. #else
  5203. os << info.file << ':' << info.line;
  5204. #endif
  5205. return os;
  5206. }
  5207. std::string StreamEndStop::operator+() const {
  5208. return std::string();
  5209. }
  5210. NonCopyable::NonCopyable() = default;
  5211. NonCopyable::~NonCopyable() = default;
  5212. }
  5213. // end catch_common.cpp
  5214. // start catch_config.cpp
  5215. // start catch_enforce.h
  5216. #include <stdexcept>
  5217. #include <iosfwd>
  5218. #define CATCH_PREPARE_EXCEPTION( type, msg ) \
  5219. type( static_cast<std::ostringstream&&>( Catch::ReusableStringStream().get() << msg ).str() )
  5220. #define CATCH_INTERNAL_ERROR( msg ) \
  5221. throw CATCH_PREPARE_EXCEPTION( std::logic_error, CATCH_INTERNAL_LINEINFO << ": Internal Catch error: " << msg);
  5222. #define CATCH_ERROR( msg ) \
  5223. throw CATCH_PREPARE_EXCEPTION( std::domain_error, msg )
  5224. #define CATCH_ENFORCE( condition, msg ) \
  5225. do{ if( !(condition) ) CATCH_ERROR( msg ); } while(false)
  5226. // end catch_enforce.h
  5227. namespace Catch {
  5228. Config::Config( ConfigData const& data )
  5229. : m_data( data ),
  5230. m_stream( openStream() )
  5231. {
  5232. if( !data.testsOrTags.empty() ) {
  5233. TestSpecParser parser( ITagAliasRegistry::get() );
  5234. for( auto const& testOrTags : data.testsOrTags )
  5235. parser.parse( testOrTags );
  5236. m_testSpec = parser.testSpec();
  5237. }
  5238. }
  5239. std::string const& Config::getFilename() const {
  5240. return m_data.outputFilename ;
  5241. }
  5242. bool Config::listTests() const { return m_data.listTests; }
  5243. bool Config::listTestNamesOnly() const { return m_data.listTestNamesOnly; }
  5244. bool Config::listTags() const { return m_data.listTags; }
  5245. bool Config::listReporters() const { return m_data.listReporters; }
  5246. std::string Config::getProcessName() const { return m_data.processName; }
  5247. std::vector<std::string> const& Config::getReporterNames() const { return m_data.reporterNames; }
  5248. std::vector<std::string> const& Config::getSectionsToRun() const { return m_data.sectionsToRun; }
  5249. TestSpec const& Config::testSpec() const { return m_testSpec; }
  5250. bool Config::showHelp() const { return m_data.showHelp; }
  5251. // IConfig interface
  5252. bool Config::allowThrows() const { return !m_data.noThrow; }
  5253. std::ostream& Config::stream() const { return m_stream->stream(); }
  5254. std::string Config::name() const { return m_data.name.empty() ? m_data.processName : m_data.name; }
  5255. bool Config::includeSuccessfulResults() const { return m_data.showSuccessfulTests; }
  5256. bool Config::warnAboutMissingAssertions() const { return m_data.warnings & WarnAbout::NoAssertions; }
  5257. ShowDurations::OrNot Config::showDurations() const { return m_data.showDurations; }
  5258. RunTests::InWhatOrder Config::runOrder() const { return m_data.runOrder; }
  5259. unsigned int Config::rngSeed() const { return m_data.rngSeed; }
  5260. int Config::benchmarkResolutionMultiple() const { return m_data.benchmarkResolutionMultiple; }
  5261. UseColour::YesOrNo Config::useColour() const { return m_data.useColour; }
  5262. bool Config::shouldDebugBreak() const { return m_data.shouldDebugBreak; }
  5263. int Config::abortAfter() const { return m_data.abortAfter; }
  5264. bool Config::showInvisibles() const { return m_data.showInvisibles; }
  5265. Verbosity Config::verbosity() const { return m_data.verbosity; }
  5266. IStream const* Config::openStream() {
  5267. return Catch::makeStream(m_data.outputFilename);
  5268. }
  5269. } // end namespace Catch
  5270. // end catch_config.cpp
  5271. // start catch_console_colour.cpp
  5272. #if defined(__clang__)
  5273. # pragma clang diagnostic push
  5274. # pragma clang diagnostic ignored "-Wexit-time-destructors"
  5275. #endif
  5276. // start catch_errno_guard.h
  5277. namespace Catch {
  5278. class ErrnoGuard {
  5279. public:
  5280. ErrnoGuard();
  5281. ~ErrnoGuard();
  5282. private:
  5283. int m_oldErrno;
  5284. };
  5285. }
  5286. // end catch_errno_guard.h
  5287. #include <sstream>
  5288. namespace Catch {
  5289. namespace {
  5290. struct IColourImpl {
  5291. virtual ~IColourImpl() = default;
  5292. virtual void use( Colour::Code _colourCode ) = 0;
  5293. };
  5294. struct NoColourImpl : IColourImpl {
  5295. void use( Colour::Code ) {}
  5296. static IColourImpl* instance() {
  5297. static NoColourImpl s_instance;
  5298. return &s_instance;
  5299. }
  5300. };
  5301. } // anon namespace
  5302. } // namespace Catch
  5303. #if !defined( CATCH_CONFIG_COLOUR_NONE ) && !defined( CATCH_CONFIG_COLOUR_WINDOWS ) && !defined( CATCH_CONFIG_COLOUR_ANSI )
  5304. # ifdef CATCH_PLATFORM_WINDOWS
  5305. # define CATCH_CONFIG_COLOUR_WINDOWS
  5306. # else
  5307. # define CATCH_CONFIG_COLOUR_ANSI
  5308. # endif
  5309. #endif
  5310. #if defined ( CATCH_CONFIG_COLOUR_WINDOWS ) /////////////////////////////////////////
  5311. namespace Catch {
  5312. namespace {
  5313. class Win32ColourImpl : public IColourImpl {
  5314. public:
  5315. Win32ColourImpl() : stdoutHandle( GetStdHandle(STD_OUTPUT_HANDLE) )
  5316. {
  5317. CONSOLE_SCREEN_BUFFER_INFO csbiInfo;
  5318. GetConsoleScreenBufferInfo( stdoutHandle, &csbiInfo );
  5319. originalForegroundAttributes = csbiInfo.wAttributes & ~( BACKGROUND_GREEN | BACKGROUND_RED | BACKGROUND_BLUE | BACKGROUND_INTENSITY );
  5320. originalBackgroundAttributes = csbiInfo.wAttributes & ~( FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_BLUE | FOREGROUND_INTENSITY );
  5321. }
  5322. virtual void use( Colour::Code _colourCode ) override {
  5323. switch( _colourCode ) {
  5324. case Colour::None: return setTextAttribute( originalForegroundAttributes );
  5325. case Colour::White: return setTextAttribute( FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_BLUE );
  5326. case Colour::Red: return setTextAttribute( FOREGROUND_RED );
  5327. case Colour::Green: return setTextAttribute( FOREGROUND_GREEN );
  5328. case Colour::Blue: return setTextAttribute( FOREGROUND_BLUE );
  5329. case Colour::Cyan: return setTextAttribute( FOREGROUND_BLUE | FOREGROUND_GREEN );
  5330. case Colour::Yellow: return setTextAttribute( FOREGROUND_RED | FOREGROUND_GREEN );
  5331. case Colour::Grey: return setTextAttribute( 0 );
  5332. case Colour::LightGrey: return setTextAttribute( FOREGROUND_INTENSITY );
  5333. case Colour::BrightRed: return setTextAttribute( FOREGROUND_INTENSITY | FOREGROUND_RED );
  5334. case Colour::BrightGreen: return setTextAttribute( FOREGROUND_INTENSITY | FOREGROUND_GREEN );
  5335. case Colour::BrightWhite: return setTextAttribute( FOREGROUND_INTENSITY | FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_BLUE );
  5336. case Colour::Bright: CATCH_INTERNAL_ERROR( "not a colour" );
  5337. }
  5338. }
  5339. private:
  5340. void setTextAttribute( WORD _textAttribute ) {
  5341. SetConsoleTextAttribute( stdoutHandle, _textAttribute | originalBackgroundAttributes );
  5342. }
  5343. HANDLE stdoutHandle;
  5344. WORD originalForegroundAttributes;
  5345. WORD originalBackgroundAttributes;
  5346. };
  5347. IColourImpl* platformColourInstance() {
  5348. static Win32ColourImpl s_instance;
  5349. IConfigPtr config = getCurrentContext().getConfig();
  5350. UseColour::YesOrNo colourMode = config
  5351. ? config->useColour()
  5352. : UseColour::Auto;
  5353. if( colourMode == UseColour::Auto )
  5354. colourMode = UseColour::Yes;
  5355. return colourMode == UseColour::Yes
  5356. ? &s_instance
  5357. : NoColourImpl::instance();
  5358. }
  5359. } // end anon namespace
  5360. } // end namespace Catch
  5361. #elif defined( CATCH_CONFIG_COLOUR_ANSI ) //////////////////////////////////////
  5362. #include <unistd.h>
  5363. namespace Catch {
  5364. namespace {
  5365. // use POSIX/ ANSI console terminal codes
  5366. // Thanks to Adam Strzelecki for original contribution
  5367. // (http://github.com/nanoant)
  5368. // https://github.com/philsquared/Catch/pull/131
  5369. class PosixColourImpl : public IColourImpl {
  5370. public:
  5371. virtual void use( Colour::Code _colourCode ) override {
  5372. switch( _colourCode ) {
  5373. case Colour::None:
  5374. case Colour::White: return setColour( "[0m" );
  5375. case Colour::Red: return setColour( "[0;31m" );
  5376. case Colour::Green: return setColour( "[0;32m" );
  5377. case Colour::Blue: return setColour( "[0;34m" );
  5378. case Colour::Cyan: return setColour( "[0;36m" );
  5379. case Colour::Yellow: return setColour( "[0;33m" );
  5380. case Colour::Grey: return setColour( "[1;30m" );
  5381. case Colour::LightGrey: return setColour( "[0;37m" );
  5382. case Colour::BrightRed: return setColour( "[1;31m" );
  5383. case Colour::BrightGreen: return setColour( "[1;32m" );
  5384. case Colour::BrightWhite: return setColour( "[1;37m" );
  5385. case Colour::Bright: CATCH_INTERNAL_ERROR( "not a colour" );
  5386. }
  5387. }
  5388. static IColourImpl* instance() {
  5389. static PosixColourImpl s_instance;
  5390. return &s_instance;
  5391. }
  5392. private:
  5393. void setColour( const char* _escapeCode ) {
  5394. Catch::cout() << '\033' << _escapeCode;
  5395. }
  5396. };
  5397. bool useColourOnPlatform() {
  5398. return
  5399. #ifdef CATCH_PLATFORM_MAC
  5400. !isDebuggerActive() &&
  5401. #endif
  5402. isatty(STDOUT_FILENO);
  5403. }
  5404. IColourImpl* platformColourInstance() {
  5405. ErrnoGuard guard;
  5406. IConfigPtr config = getCurrentContext().getConfig();
  5407. UseColour::YesOrNo colourMode = config
  5408. ? config->useColour()
  5409. : UseColour::Auto;
  5410. if( colourMode == UseColour::Auto )
  5411. colourMode = useColourOnPlatform()
  5412. ? UseColour::Yes
  5413. : UseColour::No;
  5414. return colourMode == UseColour::Yes
  5415. ? PosixColourImpl::instance()
  5416. : NoColourImpl::instance();
  5417. }
  5418. } // end anon namespace
  5419. } // end namespace Catch
  5420. #else // not Windows or ANSI ///////////////////////////////////////////////
  5421. namespace Catch {
  5422. static IColourImpl* platformColourInstance() { return NoColourImpl::instance(); }
  5423. } // end namespace Catch
  5424. #endif // Windows/ ANSI/ None
  5425. namespace Catch {
  5426. Colour::Colour( Code _colourCode ) { use( _colourCode ); }
  5427. Colour::Colour( Colour&& rhs ) noexcept {
  5428. m_moved = rhs.m_moved;
  5429. rhs.m_moved = true;
  5430. }
  5431. Colour& Colour::operator=( Colour&& rhs ) noexcept {
  5432. m_moved = rhs.m_moved;
  5433. rhs.m_moved = true;
  5434. return *this;
  5435. }
  5436. Colour::~Colour(){ if( !m_moved ) use( None ); }
  5437. void Colour::use( Code _colourCode ) {
  5438. static IColourImpl* impl = platformColourInstance();
  5439. impl->use( _colourCode );
  5440. }
  5441. std::ostream& operator << ( std::ostream& os, Colour const& ) {
  5442. return os;
  5443. }
  5444. } // end namespace Catch
  5445. #if defined(__clang__)
  5446. # pragma clang diagnostic pop
  5447. #endif
  5448. // end catch_console_colour.cpp
  5449. // start catch_context.cpp
  5450. namespace Catch {
  5451. class Context : public IMutableContext, NonCopyable {
  5452. public: // IContext
  5453. virtual IResultCapture* getResultCapture() override {
  5454. return m_resultCapture;
  5455. }
  5456. virtual IRunner* getRunner() override {
  5457. return m_runner;
  5458. }
  5459. virtual IConfigPtr const& getConfig() const override {
  5460. return m_config;
  5461. }
  5462. virtual ~Context() override;
  5463. public: // IMutableContext
  5464. virtual void setResultCapture( IResultCapture* resultCapture ) override {
  5465. m_resultCapture = resultCapture;
  5466. }
  5467. virtual void setRunner( IRunner* runner ) override {
  5468. m_runner = runner;
  5469. }
  5470. virtual void setConfig( IConfigPtr const& config ) override {
  5471. m_config = config;
  5472. }
  5473. friend IMutableContext& getCurrentMutableContext();
  5474. private:
  5475. IConfigPtr m_config;
  5476. IRunner* m_runner = nullptr;
  5477. IResultCapture* m_resultCapture = nullptr;
  5478. };
  5479. IMutableContext *IMutableContext::currentContext = nullptr;
  5480. void IMutableContext::createContext()
  5481. {
  5482. currentContext = new Context();
  5483. }
  5484. void cleanUpContext() {
  5485. delete IMutableContext::currentContext;
  5486. IMutableContext::currentContext = nullptr;
  5487. }
  5488. IContext::~IContext() = default;
  5489. IMutableContext::~IMutableContext() = default;
  5490. Context::~Context() = default;
  5491. }
  5492. // end catch_context.cpp
  5493. // start catch_debug_console.cpp
  5494. // start catch_debug_console.h
  5495. #include <string>
  5496. namespace Catch {
  5497. void writeToDebugConsole( std::string const& text );
  5498. }
  5499. // end catch_debug_console.h
  5500. #ifdef CATCH_PLATFORM_WINDOWS
  5501. namespace Catch {
  5502. void writeToDebugConsole( std::string const& text ) {
  5503. ::OutputDebugStringA( text.c_str() );
  5504. }
  5505. }
  5506. #else
  5507. namespace Catch {
  5508. void writeToDebugConsole( std::string const& text ) {
  5509. // !TBD: Need a version for Mac/ XCode and other IDEs
  5510. Catch::cout() << text;
  5511. }
  5512. }
  5513. #endif // Platform
  5514. // end catch_debug_console.cpp
  5515. // start catch_debugger.cpp
  5516. #ifdef CATCH_PLATFORM_MAC
  5517. # include <assert.h>
  5518. # include <stdbool.h>
  5519. # include <sys/types.h>
  5520. # include <unistd.h>
  5521. # include <sys/sysctl.h>
  5522. # include <cstddef>
  5523. # include <ostream>
  5524. namespace Catch {
  5525. // The following function is taken directly from the following technical note:
  5526. // http://developer.apple.com/library/mac/#qa/qa2004/qa1361.html
  5527. // Returns true if the current process is being debugged (either
  5528. // running under the debugger or has a debugger attached post facto).
  5529. bool isDebuggerActive(){
  5530. int mib[4];
  5531. struct kinfo_proc info;
  5532. std::size_t size;
  5533. // Initialize the flags so that, if sysctl fails for some bizarre
  5534. // reason, we get a predictable result.
  5535. info.kp_proc.p_flag = 0;
  5536. // Initialize mib, which tells sysctl the info we want, in this case
  5537. // we're looking for information about a specific process ID.
  5538. mib[0] = CTL_KERN;
  5539. mib[1] = KERN_PROC;
  5540. mib[2] = KERN_PROC_PID;
  5541. mib[3] = getpid();
  5542. // Call sysctl.
  5543. size = sizeof(info);
  5544. if( sysctl(mib, sizeof(mib) / sizeof(*mib), &info, &size, nullptr, 0) != 0 ) {
  5545. Catch::cerr() << "\n** Call to sysctl failed - unable to determine if debugger is active **\n" << std::endl;
  5546. return false;
  5547. }
  5548. // We're being debugged if the P_TRACED flag is set.
  5549. return ( (info.kp_proc.p_flag & P_TRACED) != 0 );
  5550. }
  5551. } // namespace Catch
  5552. #elif defined(CATCH_PLATFORM_LINUX)
  5553. #include <fstream>
  5554. #include <string>
  5555. namespace Catch{
  5556. // The standard POSIX way of detecting a debugger is to attempt to
  5557. // ptrace() the process, but this needs to be done from a child and not
  5558. // this process itself to still allow attaching to this process later
  5559. // if wanted, so is rather heavy. Under Linux we have the PID of the
  5560. // "debugger" (which doesn't need to be gdb, of course, it could also
  5561. // be strace, for example) in /proc/$PID/status, so just get it from
  5562. // there instead.
  5563. bool isDebuggerActive(){
  5564. // Libstdc++ has a bug, where std::ifstream sets errno to 0
  5565. // This way our users can properly assert over errno values
  5566. ErrnoGuard guard;
  5567. std::ifstream in("/proc/self/status");
  5568. for( std::string line; std::getline(in, line); ) {
  5569. static const int PREFIX_LEN = 11;
  5570. if( line.compare(0, PREFIX_LEN, "TracerPid:\t") == 0 ) {
  5571. // We're traced if the PID is not 0 and no other PID starts
  5572. // with 0 digit, so it's enough to check for just a single
  5573. // character.
  5574. return line.length() > PREFIX_LEN && line[PREFIX_LEN] != '0';
  5575. }
  5576. }
  5577. return false;
  5578. }
  5579. } // namespace Catch
  5580. #elif defined(_MSC_VER)
  5581. extern "C" __declspec(dllimport) int __stdcall IsDebuggerPresent();
  5582. namespace Catch {
  5583. bool isDebuggerActive() {
  5584. return IsDebuggerPresent() != 0;
  5585. }
  5586. }
  5587. #elif defined(__MINGW32__)
  5588. extern "C" __declspec(dllimport) int __stdcall IsDebuggerPresent();
  5589. namespace Catch {
  5590. bool isDebuggerActive() {
  5591. return IsDebuggerPresent() != 0;
  5592. }
  5593. }
  5594. #else
  5595. namespace Catch {
  5596. bool isDebuggerActive() { return false; }
  5597. }
  5598. #endif // Platform
  5599. // end catch_debugger.cpp
  5600. // start catch_decomposer.cpp
  5601. namespace Catch {
  5602. ITransientExpression::~ITransientExpression() = default;
  5603. void formatReconstructedExpression( std::ostream &os, std::string const& lhs, StringRef op, std::string const& rhs ) {
  5604. if( lhs.size() + rhs.size() < 40 &&
  5605. lhs.find('\n') == std::string::npos &&
  5606. rhs.find('\n') == std::string::npos )
  5607. os << lhs << " " << op << " " << rhs;
  5608. else
  5609. os << lhs << "\n" << op << "\n" << rhs;
  5610. }
  5611. }
  5612. // end catch_decomposer.cpp
  5613. // start catch_errno_guard.cpp
  5614. #include <cerrno>
  5615. namespace Catch {
  5616. ErrnoGuard::ErrnoGuard():m_oldErrno(errno){}
  5617. ErrnoGuard::~ErrnoGuard() { errno = m_oldErrno; }
  5618. }
  5619. // end catch_errno_guard.cpp
  5620. // start catch_exception_translator_registry.cpp
  5621. // start catch_exception_translator_registry.h
  5622. #include <vector>
  5623. #include <string>
  5624. #include <memory>
  5625. namespace Catch {
  5626. class ExceptionTranslatorRegistry : public IExceptionTranslatorRegistry {
  5627. public:
  5628. ~ExceptionTranslatorRegistry();
  5629. virtual void registerTranslator( const IExceptionTranslator* translator );
  5630. virtual std::string translateActiveException() const override;
  5631. std::string tryTranslators() const;
  5632. private:
  5633. std::vector<std::unique_ptr<IExceptionTranslator const>> m_translators;
  5634. };
  5635. }
  5636. // end catch_exception_translator_registry.h
  5637. #ifdef __OBJC__
  5638. #import "Foundation/Foundation.h"
  5639. #endif
  5640. namespace Catch {
  5641. ExceptionTranslatorRegistry::~ExceptionTranslatorRegistry() {
  5642. }
  5643. void ExceptionTranslatorRegistry::registerTranslator( const IExceptionTranslator* translator ) {
  5644. m_translators.push_back( std::unique_ptr<const IExceptionTranslator>( translator ) );
  5645. }
  5646. std::string ExceptionTranslatorRegistry::translateActiveException() const {
  5647. try {
  5648. #ifdef __OBJC__
  5649. // In Objective-C try objective-c exceptions first
  5650. @try {
  5651. return tryTranslators();
  5652. }
  5653. @catch (NSException *exception) {
  5654. return Catch::Detail::stringify( [exception description] );
  5655. }
  5656. #else
  5657. // Compiling a mixed mode project with MSVC means that CLR
  5658. // exceptions will be caught in (...) as well. However, these
  5659. // do not fill-in std::current_exception and thus lead to crash
  5660. // when attempting rethrow.
  5661. // /EHa switch also causes structured exceptions to be caught
  5662. // here, but they fill-in current_exception properly, so
  5663. // at worst the output should be a little weird, instead of
  5664. // causing a crash.
  5665. if (std::current_exception() == nullptr) {
  5666. return "Non C++ exception. Possibly a CLR exception.";
  5667. }
  5668. return tryTranslators();
  5669. #endif
  5670. }
  5671. catch( TestFailureException& ) {
  5672. std::rethrow_exception(std::current_exception());
  5673. }
  5674. catch( std::exception& ex ) {
  5675. return ex.what();
  5676. }
  5677. catch( std::string& msg ) {
  5678. return msg;
  5679. }
  5680. catch( const char* msg ) {
  5681. return msg;
  5682. }
  5683. catch(...) {
  5684. return "Unknown exception";
  5685. }
  5686. }
  5687. std::string ExceptionTranslatorRegistry::tryTranslators() const {
  5688. if( m_translators.empty() )
  5689. std::rethrow_exception(std::current_exception());
  5690. else
  5691. return m_translators[0]->translate( m_translators.begin()+1, m_translators.end() );
  5692. }
  5693. }
  5694. // end catch_exception_translator_registry.cpp
  5695. // start catch_fatal_condition.cpp
  5696. #if defined(__GNUC__)
  5697. # pragma GCC diagnostic push
  5698. # pragma GCC diagnostic ignored "-Wmissing-field-initializers"
  5699. #endif
  5700. namespace {
  5701. // Report the error condition
  5702. void reportFatal( char const * const message ) {
  5703. Catch::getCurrentContext().getResultCapture()->handleFatalErrorCondition( message );
  5704. }
  5705. }
  5706. #if defined ( CATCH_PLATFORM_WINDOWS ) /////////////////////////////////////////
  5707. # if !defined ( CATCH_CONFIG_WINDOWS_SEH )
  5708. namespace Catch {
  5709. void FatalConditionHandler::reset() {}
  5710. }
  5711. # else // CATCH_CONFIG_WINDOWS_SEH is defined
  5712. namespace Catch {
  5713. struct SignalDefs { DWORD id; const char* name; };
  5714. // There is no 1-1 mapping between signals and windows exceptions.
  5715. // Windows can easily distinguish between SO and SigSegV,
  5716. // but SigInt, SigTerm, etc are handled differently.
  5717. static SignalDefs signalDefs[] = {
  5718. { EXCEPTION_ILLEGAL_INSTRUCTION, "SIGILL - Illegal instruction signal" },
  5719. { EXCEPTION_STACK_OVERFLOW, "SIGSEGV - Stack overflow" },
  5720. { EXCEPTION_ACCESS_VIOLATION, "SIGSEGV - Segmentation violation signal" },
  5721. { EXCEPTION_INT_DIVIDE_BY_ZERO, "Divide by zero error" },
  5722. };
  5723. LONG CALLBACK FatalConditionHandler::handleVectoredException(PEXCEPTION_POINTERS ExceptionInfo) {
  5724. for (auto const& def : signalDefs) {
  5725. if (ExceptionInfo->ExceptionRecord->ExceptionCode == def.id) {
  5726. reportFatal(def.name);
  5727. }
  5728. }
  5729. // If its not an exception we care about, pass it along.
  5730. // This stops us from eating debugger breaks etc.
  5731. return EXCEPTION_CONTINUE_SEARCH;
  5732. }
  5733. FatalConditionHandler::FatalConditionHandler() {
  5734. isSet = true;
  5735. // 32k seems enough for Catch to handle stack overflow,
  5736. // but the value was found experimentally, so there is no strong guarantee
  5737. guaranteeSize = 32 * 1024;
  5738. exceptionHandlerHandle = nullptr;
  5739. // Register as first handler in current chain
  5740. exceptionHandlerHandle = AddVectoredExceptionHandler(1, handleVectoredException);
  5741. // Pass in guarantee size to be filled
  5742. SetThreadStackGuarantee(&guaranteeSize);
  5743. }
  5744. void FatalConditionHandler::reset() {
  5745. if (isSet) {
  5746. // Unregister handler and restore the old guarantee
  5747. RemoveVectoredExceptionHandler(exceptionHandlerHandle);
  5748. SetThreadStackGuarantee(&guaranteeSize);
  5749. exceptionHandlerHandle = nullptr;
  5750. isSet = false;
  5751. }
  5752. }
  5753. FatalConditionHandler::~FatalConditionHandler() {
  5754. reset();
  5755. }
  5756. bool FatalConditionHandler::isSet = false;
  5757. ULONG FatalConditionHandler::guaranteeSize = 0;
  5758. PVOID FatalConditionHandler::exceptionHandlerHandle = nullptr;
  5759. } // namespace Catch
  5760. # endif // CATCH_CONFIG_WINDOWS_SEH
  5761. #else // Not Windows - assumed to be POSIX compatible //////////////////////////
  5762. # if !defined(CATCH_CONFIG_POSIX_SIGNALS)
  5763. namespace Catch {
  5764. void FatalConditionHandler::reset() {}
  5765. }
  5766. # else // CATCH_CONFIG_POSIX_SIGNALS is defined
  5767. #include <signal.h>
  5768. namespace Catch {
  5769. struct SignalDefs {
  5770. int id;
  5771. const char* name;
  5772. };
  5773. static SignalDefs signalDefs[] = {
  5774. { SIGINT, "SIGINT - Terminal interrupt signal" },
  5775. { SIGILL, "SIGILL - Illegal instruction signal" },
  5776. { SIGFPE, "SIGFPE - Floating point error signal" },
  5777. { SIGSEGV, "SIGSEGV - Segmentation violation signal" },
  5778. { SIGTERM, "SIGTERM - Termination request signal" },
  5779. { SIGABRT, "SIGABRT - Abort (abnormal termination) signal" }
  5780. };
  5781. void FatalConditionHandler::handleSignal( int sig ) {
  5782. char const * name = "<unknown signal>";
  5783. for (auto const& def : signalDefs) {
  5784. if (sig == def.id) {
  5785. name = def.name;
  5786. break;
  5787. }
  5788. }
  5789. reset();
  5790. reportFatal(name);
  5791. raise( sig );
  5792. }
  5793. FatalConditionHandler::FatalConditionHandler() {
  5794. isSet = true;
  5795. stack_t sigStack;
  5796. sigStack.ss_sp = altStackMem;
  5797. sigStack.ss_size = SIGSTKSZ;
  5798. sigStack.ss_flags = 0;
  5799. sigaltstack(&sigStack, &oldSigStack);
  5800. struct sigaction sa = { };
  5801. sa.sa_handler = handleSignal;
  5802. sa.sa_flags = SA_ONSTACK;
  5803. for (std::size_t i = 0; i < sizeof(signalDefs)/sizeof(SignalDefs); ++i) {
  5804. sigaction(signalDefs[i].id, &sa, &oldSigActions[i]);
  5805. }
  5806. }
  5807. FatalConditionHandler::~FatalConditionHandler() {
  5808. reset();
  5809. }
  5810. void FatalConditionHandler::reset() {
  5811. if( isSet ) {
  5812. // Set signals back to previous values -- hopefully nobody overwrote them in the meantime
  5813. for( std::size_t i = 0; i < sizeof(signalDefs)/sizeof(SignalDefs); ++i ) {
  5814. sigaction(signalDefs[i].id, &oldSigActions[i], nullptr);
  5815. }
  5816. // Return the old stack
  5817. sigaltstack(&oldSigStack, nullptr);
  5818. isSet = false;
  5819. }
  5820. }
  5821. bool FatalConditionHandler::isSet = false;
  5822. struct sigaction FatalConditionHandler::oldSigActions[sizeof(signalDefs)/sizeof(SignalDefs)] = {};
  5823. stack_t FatalConditionHandler::oldSigStack = {};
  5824. char FatalConditionHandler::altStackMem[SIGSTKSZ] = {};
  5825. } // namespace Catch
  5826. # endif // CATCH_CONFIG_POSIX_SIGNALS
  5827. #endif // not Windows
  5828. #if defined(__GNUC__)
  5829. # pragma GCC diagnostic pop
  5830. #endif
  5831. // end catch_fatal_condition.cpp
  5832. // start catch_interfaces_capture.cpp
  5833. namespace Catch {
  5834. IResultCapture::~IResultCapture() = default;
  5835. }
  5836. // end catch_interfaces_capture.cpp
  5837. // start catch_interfaces_config.cpp
  5838. namespace Catch {
  5839. IConfig::~IConfig() = default;
  5840. }
  5841. // end catch_interfaces_config.cpp
  5842. // start catch_interfaces_exception.cpp
  5843. namespace Catch {
  5844. IExceptionTranslator::~IExceptionTranslator() = default;
  5845. IExceptionTranslatorRegistry::~IExceptionTranslatorRegistry() = default;
  5846. }
  5847. // end catch_interfaces_exception.cpp
  5848. // start catch_interfaces_registry_hub.cpp
  5849. namespace Catch {
  5850. IRegistryHub::~IRegistryHub() = default;
  5851. IMutableRegistryHub::~IMutableRegistryHub() = default;
  5852. }
  5853. // end catch_interfaces_registry_hub.cpp
  5854. // start catch_interfaces_reporter.cpp
  5855. // start catch_reporter_multi.h
  5856. namespace Catch {
  5857. class MultipleReporters : public IStreamingReporter {
  5858. using Reporters = std::vector<IStreamingReporterPtr>;
  5859. Reporters m_reporters;
  5860. public:
  5861. void add( IStreamingReporterPtr&& reporter );
  5862. public: // IStreamingReporter
  5863. ReporterPreferences getPreferences() const override;
  5864. void noMatchingTestCases( std::string const& spec ) override;
  5865. static std::set<Verbosity> getSupportedVerbosities();
  5866. void benchmarkStarting( BenchmarkInfo const& benchmarkInfo ) override;
  5867. void benchmarkEnded( BenchmarkStats const& benchmarkStats ) override;
  5868. void testRunStarting( TestRunInfo const& testRunInfo ) override;
  5869. void testGroupStarting( GroupInfo const& groupInfo ) override;
  5870. void testCaseStarting( TestCaseInfo const& testInfo ) override;
  5871. void sectionStarting( SectionInfo const& sectionInfo ) override;
  5872. void assertionStarting( AssertionInfo const& assertionInfo ) override;
  5873. // The return value indicates if the messages buffer should be cleared:
  5874. bool assertionEnded( AssertionStats const& assertionStats ) override;
  5875. void sectionEnded( SectionStats const& sectionStats ) override;
  5876. void testCaseEnded( TestCaseStats const& testCaseStats ) override;
  5877. void testGroupEnded( TestGroupStats const& testGroupStats ) override;
  5878. void testRunEnded( TestRunStats const& testRunStats ) override;
  5879. void skipTest( TestCaseInfo const& testInfo ) override;
  5880. bool isMulti() const override;
  5881. };
  5882. } // end namespace Catch
  5883. // end catch_reporter_multi.h
  5884. namespace Catch {
  5885. ReporterConfig::ReporterConfig( IConfigPtr const& _fullConfig )
  5886. : m_stream( &_fullConfig->stream() ), m_fullConfig( _fullConfig ) {}
  5887. ReporterConfig::ReporterConfig( IConfigPtr const& _fullConfig, std::ostream& _stream )
  5888. : m_stream( &_stream ), m_fullConfig( _fullConfig ) {}
  5889. std::ostream& ReporterConfig::stream() const { return *m_stream; }
  5890. IConfigPtr ReporterConfig::fullConfig() const { return m_fullConfig; }
  5891. TestRunInfo::TestRunInfo( std::string const& _name ) : name( _name ) {}
  5892. GroupInfo::GroupInfo( std::string const& _name,
  5893. std::size_t _groupIndex,
  5894. std::size_t _groupsCount )
  5895. : name( _name ),
  5896. groupIndex( _groupIndex ),
  5897. groupsCounts( _groupsCount )
  5898. {}
  5899. AssertionStats::AssertionStats( AssertionResult const& _assertionResult,
  5900. std::vector<MessageInfo> const& _infoMessages,
  5901. Totals const& _totals )
  5902. : assertionResult( _assertionResult ),
  5903. infoMessages( _infoMessages ),
  5904. totals( _totals )
  5905. {
  5906. assertionResult.m_resultData.lazyExpression.m_transientExpression = _assertionResult.m_resultData.lazyExpression.m_transientExpression;
  5907. if( assertionResult.hasMessage() ) {
  5908. // Copy message into messages list.
  5909. // !TBD This should have been done earlier, somewhere
  5910. MessageBuilder builder( assertionResult.getTestMacroName(), assertionResult.getSourceInfo(), assertionResult.getResultType() );
  5911. builder << assertionResult.getMessage();
  5912. builder.m_info.message = builder.m_stream.str();
  5913. infoMessages.push_back( builder.m_info );
  5914. }
  5915. }
  5916. AssertionStats::~AssertionStats() = default;
  5917. SectionStats::SectionStats( SectionInfo const& _sectionInfo,
  5918. Counts const& _assertions,
  5919. double _durationInSeconds,
  5920. bool _missingAssertions )
  5921. : sectionInfo( _sectionInfo ),
  5922. assertions( _assertions ),
  5923. durationInSeconds( _durationInSeconds ),
  5924. missingAssertions( _missingAssertions )
  5925. {}
  5926. SectionStats::~SectionStats() = default;
  5927. TestCaseStats::TestCaseStats( TestCaseInfo const& _testInfo,
  5928. Totals const& _totals,
  5929. std::string const& _stdOut,
  5930. std::string const& _stdErr,
  5931. bool _aborting )
  5932. : testInfo( _testInfo ),
  5933. totals( _totals ),
  5934. stdOut( _stdOut ),
  5935. stdErr( _stdErr ),
  5936. aborting( _aborting )
  5937. {}
  5938. TestCaseStats::~TestCaseStats() = default;
  5939. TestGroupStats::TestGroupStats( GroupInfo const& _groupInfo,
  5940. Totals const& _totals,
  5941. bool _aborting )
  5942. : groupInfo( _groupInfo ),
  5943. totals( _totals ),
  5944. aborting( _aborting )
  5945. {}
  5946. TestGroupStats::TestGroupStats( GroupInfo const& _groupInfo )
  5947. : groupInfo( _groupInfo ),
  5948. aborting( false )
  5949. {}
  5950. TestGroupStats::~TestGroupStats() = default;
  5951. TestRunStats::TestRunStats( TestRunInfo const& _runInfo,
  5952. Totals const& _totals,
  5953. bool _aborting )
  5954. : runInfo( _runInfo ),
  5955. totals( _totals ),
  5956. aborting( _aborting )
  5957. {}
  5958. TestRunStats::~TestRunStats() = default;
  5959. void IStreamingReporter::fatalErrorEncountered( StringRef ) {}
  5960. bool IStreamingReporter::isMulti() const { return false; }
  5961. IReporterFactory::~IReporterFactory() = default;
  5962. IReporterRegistry::~IReporterRegistry() = default;
  5963. void addReporter( IStreamingReporterPtr& existingReporter, IStreamingReporterPtr&& additionalReporter ) {
  5964. if( !existingReporter ) {
  5965. existingReporter = std::move( additionalReporter );
  5966. return;
  5967. }
  5968. MultipleReporters* multi = nullptr;
  5969. if( existingReporter->isMulti() ) {
  5970. multi = static_cast<MultipleReporters*>( existingReporter.get() );
  5971. }
  5972. else {
  5973. auto newMulti = std::unique_ptr<MultipleReporters>( new MultipleReporters );
  5974. newMulti->add( std::move( existingReporter ) );
  5975. multi = newMulti.get();
  5976. existingReporter = std::move( newMulti );
  5977. }
  5978. multi->add( std::move( additionalReporter ) );
  5979. }
  5980. } // end namespace Catch
  5981. // end catch_interfaces_reporter.cpp
  5982. // start catch_interfaces_runner.cpp
  5983. namespace Catch {
  5984. IRunner::~IRunner() = default;
  5985. }
  5986. // end catch_interfaces_runner.cpp
  5987. // start catch_interfaces_testcase.cpp
  5988. namespace Catch {
  5989. ITestInvoker::~ITestInvoker() = default;
  5990. ITestCaseRegistry::~ITestCaseRegistry() = default;
  5991. }
  5992. // end catch_interfaces_testcase.cpp
  5993. // start catch_leak_detector.cpp
  5994. #ifdef CATCH_CONFIG_WINDOWS_CRTDBG
  5995. #include <crtdbg.h>
  5996. namespace Catch {
  5997. LeakDetector::LeakDetector() {
  5998. int flag = _CrtSetDbgFlag(_CRTDBG_REPORT_FLAG);
  5999. flag |= _CRTDBG_LEAK_CHECK_DF;
  6000. flag |= _CRTDBG_ALLOC_MEM_DF;
  6001. _CrtSetDbgFlag(flag);
  6002. _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE | _CRTDBG_MODE_DEBUG);
  6003. _CrtSetReportFile(_CRT_WARN, _CRTDBG_FILE_STDERR);
  6004. // Change this to leaking allocation's number to break there
  6005. _CrtSetBreakAlloc(-1);
  6006. }
  6007. }
  6008. #else
  6009. Catch::LeakDetector::LeakDetector() {}
  6010. #endif
  6011. // end catch_leak_detector.cpp
  6012. // start catch_list.cpp
  6013. // start catch_list.h
  6014. #include <set>
  6015. namespace Catch {
  6016. std::size_t listTests( Config const& config );
  6017. std::size_t listTestsNamesOnly( Config const& config );
  6018. struct TagInfo {
  6019. void add( std::string const& spelling );
  6020. std::string all() const;
  6021. std::set<std::string> spellings;
  6022. std::size_t count = 0;
  6023. };
  6024. std::size_t listTags( Config const& config );
  6025. std::size_t listReporters( Config const& /*config*/ );
  6026. Option<std::size_t> list( Config const& config );
  6027. } // end namespace Catch
  6028. // end catch_list.h
  6029. // start catch_text.h
  6030. namespace Catch {
  6031. using namespace clara::TextFlow;
  6032. }
  6033. // end catch_text.h
  6034. #include <limits>
  6035. #include <algorithm>
  6036. #include <iomanip>
  6037. namespace Catch {
  6038. std::size_t listTests( Config const& config ) {
  6039. TestSpec testSpec = config.testSpec();
  6040. if( config.testSpec().hasFilters() )
  6041. Catch::cout() << "Matching test cases:\n";
  6042. else {
  6043. Catch::cout() << "All available test cases:\n";
  6044. testSpec = TestSpecParser( ITagAliasRegistry::get() ).parse( "*" ).testSpec();
  6045. }
  6046. auto matchedTestCases = filterTests( getAllTestCasesSorted( config ), testSpec, config );
  6047. for( auto const& testCaseInfo : matchedTestCases ) {
  6048. Colour::Code colour = testCaseInfo.isHidden()
  6049. ? Colour::SecondaryText
  6050. : Colour::None;
  6051. Colour colourGuard( colour );
  6052. Catch::cout() << Column( testCaseInfo.name ).initialIndent( 2 ).indent( 4 ) << "\n";
  6053. if( config.verbosity() >= Verbosity::High ) {
  6054. Catch::cout() << Column( Catch::Detail::stringify( testCaseInfo.lineInfo ) ).indent(4) << std::endl;
  6055. std::string description = testCaseInfo.description;
  6056. if( description.empty() )
  6057. description = "(NO DESCRIPTION)";
  6058. Catch::cout() << Column( description ).indent(4) << std::endl;
  6059. }
  6060. if( !testCaseInfo.tags.empty() )
  6061. Catch::cout() << Column( testCaseInfo.tagsAsString() ).indent( 6 ) << "\n";
  6062. }
  6063. if( !config.testSpec().hasFilters() )
  6064. Catch::cout() << pluralise( matchedTestCases.size(), "test case" ) << '\n' << std::endl;
  6065. else
  6066. Catch::cout() << pluralise( matchedTestCases.size(), "matching test case" ) << '\n' << std::endl;
  6067. return matchedTestCases.size();
  6068. }
  6069. std::size_t listTestsNamesOnly( Config const& config ) {
  6070. TestSpec testSpec = config.testSpec();
  6071. if( !config.testSpec().hasFilters() )
  6072. testSpec = TestSpecParser( ITagAliasRegistry::get() ).parse( "*" ).testSpec();
  6073. std::size_t matchedTests = 0;
  6074. std::vector<TestCase> matchedTestCases = filterTests( getAllTestCasesSorted( config ), testSpec, config );
  6075. for( auto const& testCaseInfo : matchedTestCases ) {
  6076. matchedTests++;
  6077. if( startsWith( testCaseInfo.name, '#' ) )
  6078. Catch::cout() << '"' << testCaseInfo.name << '"';
  6079. else
  6080. Catch::cout() << testCaseInfo.name;
  6081. if ( config.verbosity() >= Verbosity::High )
  6082. Catch::cout() << "\t@" << testCaseInfo.lineInfo;
  6083. Catch::cout() << std::endl;
  6084. }
  6085. return matchedTests;
  6086. }
  6087. void TagInfo::add( std::string const& spelling ) {
  6088. ++count;
  6089. spellings.insert( spelling );
  6090. }
  6091. std::string TagInfo::all() const {
  6092. std::string out;
  6093. for( auto const& spelling : spellings )
  6094. out += "[" + spelling + "]";
  6095. return out;
  6096. }
  6097. std::size_t listTags( Config const& config ) {
  6098. TestSpec testSpec = config.testSpec();
  6099. if( config.testSpec().hasFilters() )
  6100. Catch::cout() << "Tags for matching test cases:\n";
  6101. else {
  6102. Catch::cout() << "All available tags:\n";
  6103. testSpec = TestSpecParser( ITagAliasRegistry::get() ).parse( "*" ).testSpec();
  6104. }
  6105. std::map<std::string, TagInfo> tagCounts;
  6106. std::vector<TestCase> matchedTestCases = filterTests( getAllTestCasesSorted( config ), testSpec, config );
  6107. for( auto const& testCase : matchedTestCases ) {
  6108. for( auto const& tagName : testCase.getTestCaseInfo().tags ) {
  6109. std::string lcaseTagName = toLower( tagName );
  6110. auto countIt = tagCounts.find( lcaseTagName );
  6111. if( countIt == tagCounts.end() )
  6112. countIt = tagCounts.insert( std::make_pair( lcaseTagName, TagInfo() ) ).first;
  6113. countIt->second.add( tagName );
  6114. }
  6115. }
  6116. for( auto const& tagCount : tagCounts ) {
  6117. ReusableStringStream rss;
  6118. rss << " " << std::setw(2) << tagCount.second.count << " ";
  6119. auto str = rss.str();
  6120. auto wrapper = Column( tagCount.second.all() )
  6121. .initialIndent( 0 )
  6122. .indent( str.size() )
  6123. .width( CATCH_CONFIG_CONSOLE_WIDTH-10 );
  6124. Catch::cout() << str << wrapper << '\n';
  6125. }
  6126. Catch::cout() << pluralise( tagCounts.size(), "tag" ) << '\n' << std::endl;
  6127. return tagCounts.size();
  6128. }
  6129. std::size_t listReporters( Config const& /*config*/ ) {
  6130. Catch::cout() << "Available reporters:\n";
  6131. IReporterRegistry::FactoryMap const& factories = getRegistryHub().getReporterRegistry().getFactories();
  6132. std::size_t maxNameLen = 0;
  6133. for( auto const& factoryKvp : factories )
  6134. maxNameLen = (std::max)( maxNameLen, factoryKvp.first.size() );
  6135. for( auto const& factoryKvp : factories ) {
  6136. Catch::cout()
  6137. << Column( factoryKvp.first + ":" )
  6138. .indent(2)
  6139. .width( 5+maxNameLen )
  6140. + Column( factoryKvp.second->getDescription() )
  6141. .initialIndent(0)
  6142. .indent(2)
  6143. .width( CATCH_CONFIG_CONSOLE_WIDTH - maxNameLen-8 )
  6144. << "\n";
  6145. }
  6146. Catch::cout() << std::endl;
  6147. return factories.size();
  6148. }
  6149. Option<std::size_t> list( Config const& config ) {
  6150. Option<std::size_t> listedCount;
  6151. if( config.listTests() )
  6152. listedCount = listedCount.valueOr(0) + listTests( config );
  6153. if( config.listTestNamesOnly() )
  6154. listedCount = listedCount.valueOr(0) + listTestsNamesOnly( config );
  6155. if( config.listTags() )
  6156. listedCount = listedCount.valueOr(0) + listTags( config );
  6157. if( config.listReporters() )
  6158. listedCount = listedCount.valueOr(0) + listReporters( config );
  6159. return listedCount;
  6160. }
  6161. } // end namespace Catch
  6162. // end catch_list.cpp
  6163. // start catch_matchers.cpp
  6164. namespace Catch {
  6165. namespace Matchers {
  6166. namespace Impl {
  6167. std::string MatcherUntypedBase::toString() const {
  6168. if( m_cachedToString.empty() )
  6169. m_cachedToString = describe();
  6170. return m_cachedToString;
  6171. }
  6172. MatcherUntypedBase::~MatcherUntypedBase() = default;
  6173. } // namespace Impl
  6174. } // namespace Matchers
  6175. using namespace Matchers;
  6176. using Matchers::Impl::MatcherBase;
  6177. } // namespace Catch
  6178. // end catch_matchers.cpp
  6179. // start catch_matchers_floating.cpp
  6180. #include <cstdlib>
  6181. #include <cstdint>
  6182. #include <cstring>
  6183. #include <stdexcept>
  6184. namespace Catch {
  6185. namespace Matchers {
  6186. namespace Floating {
  6187. enum class FloatingPointKind : uint8_t {
  6188. Float,
  6189. Double
  6190. };
  6191. }
  6192. }
  6193. }
  6194. namespace {
  6195. template <typename T>
  6196. struct Converter;
  6197. template <>
  6198. struct Converter<float> {
  6199. static_assert(sizeof(float) == sizeof(int32_t), "Important ULP matcher assumption violated");
  6200. Converter(float f) {
  6201. std::memcpy(&i, &f, sizeof(f));
  6202. }
  6203. int32_t i;
  6204. };
  6205. template <>
  6206. struct Converter<double> {
  6207. static_assert(sizeof(double) == sizeof(int64_t), "Important ULP matcher assumption violated");
  6208. Converter(double d) {
  6209. std::memcpy(&i, &d, sizeof(d));
  6210. }
  6211. int64_t i;
  6212. };
  6213. template <typename T>
  6214. auto convert(T t) -> Converter<T> {
  6215. return Converter<T>(t);
  6216. }
  6217. template <typename FP>
  6218. bool almostEqualUlps(FP lhs, FP rhs, int maxUlpDiff) {
  6219. // Comparison with NaN should always be false.
  6220. // This way we can rule it out before getting into the ugly details
  6221. if (std::isnan(lhs) || std::isnan(rhs)) {
  6222. return false;
  6223. }
  6224. auto lc = convert(lhs);
  6225. auto rc = convert(rhs);
  6226. if ((lc.i < 0) != (rc.i < 0)) {
  6227. // Potentially we can have +0 and -0
  6228. return lhs == rhs;
  6229. }
  6230. auto ulpDiff = std::abs(lc.i - rc.i);
  6231. return ulpDiff <= maxUlpDiff;
  6232. }
  6233. }
  6234. namespace Catch {
  6235. namespace Matchers {
  6236. namespace Floating {
  6237. WithinAbsMatcher::WithinAbsMatcher(double target, double margin)
  6238. :m_target{ target }, m_margin{ margin } {
  6239. if (m_margin < 0) {
  6240. throw std::domain_error("Allowed margin difference has to be >= 0");
  6241. }
  6242. }
  6243. // Performs equivalent check of std::fabs(lhs - rhs) <= margin
  6244. // But without the subtraction to allow for INFINITY in comparison
  6245. bool WithinAbsMatcher::match(double const& matchee) const {
  6246. return (matchee + m_margin >= m_target) && (m_target + m_margin >= m_margin);
  6247. }
  6248. std::string WithinAbsMatcher::describe() const {
  6249. return "is within " + ::Catch::Detail::stringify(m_margin) + " of " + ::Catch::Detail::stringify(m_target);
  6250. }
  6251. WithinUlpsMatcher::WithinUlpsMatcher(double target, int ulps, FloatingPointKind baseType)
  6252. :m_target{ target }, m_ulps{ ulps }, m_type{ baseType } {
  6253. if (m_ulps < 0) {
  6254. throw std::domain_error("Allowed ulp difference has to be >= 0");
  6255. }
  6256. }
  6257. bool WithinUlpsMatcher::match(double const& matchee) const {
  6258. switch (m_type) {
  6259. case FloatingPointKind::Float:
  6260. return almostEqualUlps<float>(static_cast<float>(matchee), static_cast<float>(m_target), m_ulps);
  6261. case FloatingPointKind::Double:
  6262. return almostEqualUlps<double>(matchee, m_target, m_ulps);
  6263. default:
  6264. throw std::domain_error("Unknown FloatingPointKind value");
  6265. }
  6266. }
  6267. std::string WithinUlpsMatcher::describe() const {
  6268. return "is within " + std::to_string(m_ulps) + " ULPs of " + ::Catch::Detail::stringify(m_target) + ((m_type == FloatingPointKind::Float)? "f" : "");
  6269. }
  6270. }// namespace Floating
  6271. Floating::WithinUlpsMatcher WithinULP(double target, int maxUlpDiff) {
  6272. return Floating::WithinUlpsMatcher(target, maxUlpDiff, Floating::FloatingPointKind::Double);
  6273. }
  6274. Floating::WithinUlpsMatcher WithinULP(float target, int maxUlpDiff) {
  6275. return Floating::WithinUlpsMatcher(target, maxUlpDiff, Floating::FloatingPointKind::Float);
  6276. }
  6277. Floating::WithinAbsMatcher WithinAbs(double target, double margin) {
  6278. return Floating::WithinAbsMatcher(target, margin);
  6279. }
  6280. } // namespace Matchers
  6281. } // namespace Catch
  6282. // end catch_matchers_floating.cpp
  6283. // start catch_matchers_string.cpp
  6284. #include <regex>
  6285. namespace Catch {
  6286. namespace Matchers {
  6287. namespace StdString {
  6288. CasedString::CasedString( std::string const& str, CaseSensitive::Choice caseSensitivity )
  6289. : m_caseSensitivity( caseSensitivity ),
  6290. m_str( adjustString( str ) )
  6291. {}
  6292. std::string CasedString::adjustString( std::string const& str ) const {
  6293. return m_caseSensitivity == CaseSensitive::No
  6294. ? toLower( str )
  6295. : str;
  6296. }
  6297. std::string CasedString::caseSensitivitySuffix() const {
  6298. return m_caseSensitivity == CaseSensitive::No
  6299. ? " (case insensitive)"
  6300. : std::string();
  6301. }
  6302. StringMatcherBase::StringMatcherBase( std::string const& operation, CasedString const& comparator )
  6303. : m_comparator( comparator ),
  6304. m_operation( operation ) {
  6305. }
  6306. std::string StringMatcherBase::describe() const {
  6307. std::string description;
  6308. description.reserve(5 + m_operation.size() + m_comparator.m_str.size() +
  6309. m_comparator.caseSensitivitySuffix().size());
  6310. description += m_operation;
  6311. description += ": \"";
  6312. description += m_comparator.m_str;
  6313. description += "\"";
  6314. description += m_comparator.caseSensitivitySuffix();
  6315. return description;
  6316. }
  6317. EqualsMatcher::EqualsMatcher( CasedString const& comparator ) : StringMatcherBase( "equals", comparator ) {}
  6318. bool EqualsMatcher::match( std::string const& source ) const {
  6319. return m_comparator.adjustString( source ) == m_comparator.m_str;
  6320. }
  6321. ContainsMatcher::ContainsMatcher( CasedString const& comparator ) : StringMatcherBase( "contains", comparator ) {}
  6322. bool ContainsMatcher::match( std::string const& source ) const {
  6323. return contains( m_comparator.adjustString( source ), m_comparator.m_str );
  6324. }
  6325. StartsWithMatcher::StartsWithMatcher( CasedString const& comparator ) : StringMatcherBase( "starts with", comparator ) {}
  6326. bool StartsWithMatcher::match( std::string const& source ) const {
  6327. return startsWith( m_comparator.adjustString( source ), m_comparator.m_str );
  6328. }
  6329. EndsWithMatcher::EndsWithMatcher( CasedString const& comparator ) : StringMatcherBase( "ends with", comparator ) {}
  6330. bool EndsWithMatcher::match( std::string const& source ) const {
  6331. return endsWith( m_comparator.adjustString( source ), m_comparator.m_str );
  6332. }
  6333. RegexMatcher::RegexMatcher(std::string regex, CaseSensitive::Choice caseSensitivity): m_regex(std::move(regex)), m_caseSensitivity(caseSensitivity) {}
  6334. bool RegexMatcher::match(std::string const& matchee) const {
  6335. auto flags = std::regex::ECMAScript; // ECMAScript is the default syntax option anyway
  6336. if (m_caseSensitivity == CaseSensitive::Choice::No) {
  6337. flags |= std::regex::icase;
  6338. }
  6339. auto reg = std::regex(m_regex, flags);
  6340. return std::regex_match(matchee, reg);
  6341. }
  6342. std::string RegexMatcher::describe() const {
  6343. return "matches " + ::Catch::Detail::stringify(m_regex) + ((m_caseSensitivity == CaseSensitive::Choice::Yes)? " case sensitively" : " case insensitively");
  6344. }
  6345. } // namespace StdString
  6346. StdString::EqualsMatcher Equals( std::string const& str, CaseSensitive::Choice caseSensitivity ) {
  6347. return StdString::EqualsMatcher( StdString::CasedString( str, caseSensitivity) );
  6348. }
  6349. StdString::ContainsMatcher Contains( std::string const& str, CaseSensitive::Choice caseSensitivity ) {
  6350. return StdString::ContainsMatcher( StdString::CasedString( str, caseSensitivity) );
  6351. }
  6352. StdString::EndsWithMatcher EndsWith( std::string const& str, CaseSensitive::Choice caseSensitivity ) {
  6353. return StdString::EndsWithMatcher( StdString::CasedString( str, caseSensitivity) );
  6354. }
  6355. StdString::StartsWithMatcher StartsWith( std::string const& str, CaseSensitive::Choice caseSensitivity ) {
  6356. return StdString::StartsWithMatcher( StdString::CasedString( str, caseSensitivity) );
  6357. }
  6358. StdString::RegexMatcher Matches(std::string const& regex, CaseSensitive::Choice caseSensitivity) {
  6359. return StdString::RegexMatcher(regex, caseSensitivity);
  6360. }
  6361. } // namespace Matchers
  6362. } // namespace Catch
  6363. // end catch_matchers_string.cpp
  6364. // start catch_message.cpp
  6365. namespace Catch {
  6366. MessageInfo::MessageInfo( std::string const& _macroName,
  6367. SourceLineInfo const& _lineInfo,
  6368. ResultWas::OfType _type )
  6369. : macroName( _macroName ),
  6370. lineInfo( _lineInfo ),
  6371. type( _type ),
  6372. sequence( ++globalCount )
  6373. {}
  6374. bool MessageInfo::operator==( MessageInfo const& other ) const {
  6375. return sequence == other.sequence;
  6376. }
  6377. bool MessageInfo::operator<( MessageInfo const& other ) const {
  6378. return sequence < other.sequence;
  6379. }
  6380. // This may need protecting if threading support is added
  6381. unsigned int MessageInfo::globalCount = 0;
  6382. ////////////////////////////////////////////////////////////////////////////
  6383. Catch::MessageBuilder::MessageBuilder( std::string const& macroName,
  6384. SourceLineInfo const& lineInfo,
  6385. ResultWas::OfType type )
  6386. :m_info(macroName, lineInfo, type) {}
  6387. ////////////////////////////////////////////////////////////////////////////
  6388. ScopedMessage::ScopedMessage( MessageBuilder const& builder )
  6389. : m_info( builder.m_info )
  6390. {
  6391. m_info.message = builder.m_stream.str();
  6392. getResultCapture().pushScopedMessage( m_info );
  6393. }
  6394. #if defined(_MSC_VER)
  6395. #pragma warning(push)
  6396. #pragma warning(disable:4996) // std::uncaught_exception is deprecated in C++17
  6397. #endif
  6398. ScopedMessage::~ScopedMessage() {
  6399. if ( !std::uncaught_exception() ){
  6400. getResultCapture().popScopedMessage(m_info);
  6401. }
  6402. }
  6403. #if defined(_MSC_VER)
  6404. #pragma warning(pop)
  6405. #endif
  6406. } // end namespace Catch
  6407. // end catch_message.cpp
  6408. // start catch_random_number_generator.cpp
  6409. // start catch_random_number_generator.h
  6410. #include <algorithm>
  6411. namespace Catch {
  6412. struct IConfig;
  6413. void seedRng( IConfig const& config );
  6414. unsigned int rngSeed();
  6415. struct RandomNumberGenerator {
  6416. using result_type = unsigned int;
  6417. static constexpr result_type (min)() { return 0; }
  6418. static constexpr result_type (max)() { return 1000000; }
  6419. result_type operator()( result_type n ) const;
  6420. result_type operator()() const;
  6421. template<typename V>
  6422. static void shuffle( V& vector ) {
  6423. RandomNumberGenerator rng;
  6424. std::shuffle( vector.begin(), vector.end(), rng );
  6425. }
  6426. };
  6427. }
  6428. // end catch_random_number_generator.h
  6429. #include <cstdlib>
  6430. namespace Catch {
  6431. void seedRng( IConfig const& config ) {
  6432. if( config.rngSeed() != 0 )
  6433. std::srand( config.rngSeed() );
  6434. }
  6435. unsigned int rngSeed() {
  6436. return getCurrentContext().getConfig()->rngSeed();
  6437. }
  6438. RandomNumberGenerator::result_type RandomNumberGenerator::operator()( result_type n ) const {
  6439. return std::rand() % n;
  6440. }
  6441. RandomNumberGenerator::result_type RandomNumberGenerator::operator()() const {
  6442. return std::rand() % (max)();
  6443. }
  6444. }
  6445. // end catch_random_number_generator.cpp
  6446. // start catch_registry_hub.cpp
  6447. // start catch_test_case_registry_impl.h
  6448. #include <vector>
  6449. #include <set>
  6450. #include <algorithm>
  6451. #include <ios>
  6452. namespace Catch {
  6453. class TestCase;
  6454. struct IConfig;
  6455. std::vector<TestCase> sortTests( IConfig const& config, std::vector<TestCase> const& unsortedTestCases );
  6456. bool matchTest( TestCase const& testCase, TestSpec const& testSpec, IConfig const& config );
  6457. void enforceNoDuplicateTestCases( std::vector<TestCase> const& functions );
  6458. std::vector<TestCase> filterTests( std::vector<TestCase> const& testCases, TestSpec const& testSpec, IConfig const& config );
  6459. std::vector<TestCase> const& getAllTestCasesSorted( IConfig const& config );
  6460. class TestRegistry : public ITestCaseRegistry {
  6461. public:
  6462. virtual ~TestRegistry() = default;
  6463. virtual void registerTest( TestCase const& testCase );
  6464. std::vector<TestCase> const& getAllTests() const override;
  6465. std::vector<TestCase> const& getAllTestsSorted( IConfig const& config ) const override;
  6466. private:
  6467. std::vector<TestCase> m_functions;
  6468. mutable RunTests::InWhatOrder m_currentSortOrder = RunTests::InDeclarationOrder;
  6469. mutable std::vector<TestCase> m_sortedFunctions;
  6470. std::size_t m_unnamedCount = 0;
  6471. std::ios_base::Init m_ostreamInit; // Forces cout/ cerr to be initialised
  6472. };
  6473. ///////////////////////////////////////////////////////////////////////////
  6474. class TestInvokerAsFunction : public ITestInvoker {
  6475. void(*m_testAsFunction)();
  6476. public:
  6477. TestInvokerAsFunction( void(*testAsFunction)() ) noexcept;
  6478. void invoke() const override;
  6479. };
  6480. std::string extractClassName( std::string const& classOrQualifiedMethodName );
  6481. ///////////////////////////////////////////////////////////////////////////
  6482. } // end namespace Catch
  6483. // end catch_test_case_registry_impl.h
  6484. // start catch_reporter_registry.h
  6485. #include <map>
  6486. namespace Catch {
  6487. class ReporterRegistry : public IReporterRegistry {
  6488. public:
  6489. ~ReporterRegistry() override;
  6490. IStreamingReporterPtr create( std::string const& name, IConfigPtr const& config ) const override;
  6491. void registerReporter( std::string const& name, IReporterFactoryPtr const& factory );
  6492. void registerListener( IReporterFactoryPtr const& factory );
  6493. FactoryMap const& getFactories() const override;
  6494. Listeners const& getListeners() const override;
  6495. private:
  6496. FactoryMap m_factories;
  6497. Listeners m_listeners;
  6498. };
  6499. }
  6500. // end catch_reporter_registry.h
  6501. // start catch_tag_alias_registry.h
  6502. // start catch_tag_alias.h
  6503. #include <string>
  6504. namespace Catch {
  6505. struct TagAlias {
  6506. TagAlias(std::string const& _tag, SourceLineInfo _lineInfo);
  6507. std::string tag;
  6508. SourceLineInfo lineInfo;
  6509. };
  6510. } // end namespace Catch
  6511. // end catch_tag_alias.h
  6512. #include <map>
  6513. namespace Catch {
  6514. class TagAliasRegistry : public ITagAliasRegistry {
  6515. public:
  6516. ~TagAliasRegistry() override;
  6517. TagAlias const* find( std::string const& alias ) const override;
  6518. std::string expandAliases( std::string const& unexpandedTestSpec ) const override;
  6519. void add( std::string const& alias, std::string const& tag, SourceLineInfo const& lineInfo );
  6520. private:
  6521. std::map<std::string, TagAlias> m_registry;
  6522. };
  6523. } // end namespace Catch
  6524. // end catch_tag_alias_registry.h
  6525. // start catch_startup_exception_registry.h
  6526. #include <vector>
  6527. #include <exception>
  6528. namespace Catch {
  6529. class StartupExceptionRegistry {
  6530. public:
  6531. void add(std::exception_ptr const& exception) noexcept;
  6532. std::vector<std::exception_ptr> const& getExceptions() const noexcept;
  6533. private:
  6534. std::vector<std::exception_ptr> m_exceptions;
  6535. };
  6536. } // end namespace Catch
  6537. // end catch_startup_exception_registry.h
  6538. namespace Catch {
  6539. namespace {
  6540. class RegistryHub : public IRegistryHub, public IMutableRegistryHub,
  6541. private NonCopyable {
  6542. public: // IRegistryHub
  6543. RegistryHub() = default;
  6544. IReporterRegistry const& getReporterRegistry() const override {
  6545. return m_reporterRegistry;
  6546. }
  6547. ITestCaseRegistry const& getTestCaseRegistry() const override {
  6548. return m_testCaseRegistry;
  6549. }
  6550. IExceptionTranslatorRegistry& getExceptionTranslatorRegistry() override {
  6551. return m_exceptionTranslatorRegistry;
  6552. }
  6553. ITagAliasRegistry const& getTagAliasRegistry() const override {
  6554. return m_tagAliasRegistry;
  6555. }
  6556. StartupExceptionRegistry const& getStartupExceptionRegistry() const override {
  6557. return m_exceptionRegistry;
  6558. }
  6559. public: // IMutableRegistryHub
  6560. void registerReporter( std::string const& name, IReporterFactoryPtr const& factory ) override {
  6561. m_reporterRegistry.registerReporter( name, factory );
  6562. }
  6563. void registerListener( IReporterFactoryPtr const& factory ) override {
  6564. m_reporterRegistry.registerListener( factory );
  6565. }
  6566. void registerTest( TestCase const& testInfo ) override {
  6567. m_testCaseRegistry.registerTest( testInfo );
  6568. }
  6569. void registerTranslator( const IExceptionTranslator* translator ) override {
  6570. m_exceptionTranslatorRegistry.registerTranslator( translator );
  6571. }
  6572. void registerTagAlias( std::string const& alias, std::string const& tag, SourceLineInfo const& lineInfo ) override {
  6573. m_tagAliasRegistry.add( alias, tag, lineInfo );
  6574. }
  6575. void registerStartupException() noexcept override {
  6576. m_exceptionRegistry.add(std::current_exception());
  6577. }
  6578. private:
  6579. TestRegistry m_testCaseRegistry;
  6580. ReporterRegistry m_reporterRegistry;
  6581. ExceptionTranslatorRegistry m_exceptionTranslatorRegistry;
  6582. TagAliasRegistry m_tagAliasRegistry;
  6583. StartupExceptionRegistry m_exceptionRegistry;
  6584. };
  6585. // Single, global, instance
  6586. RegistryHub*& getTheRegistryHub() {
  6587. static RegistryHub* theRegistryHub = nullptr;
  6588. if( !theRegistryHub )
  6589. theRegistryHub = new RegistryHub();
  6590. return theRegistryHub;
  6591. }
  6592. }
  6593. IRegistryHub& getRegistryHub() {
  6594. return *getTheRegistryHub();
  6595. }
  6596. IMutableRegistryHub& getMutableRegistryHub() {
  6597. return *getTheRegistryHub();
  6598. }
  6599. void cleanUp() {
  6600. delete getTheRegistryHub();
  6601. getTheRegistryHub() = nullptr;
  6602. cleanUpContext();
  6603. ReusableStringStream::cleanup();
  6604. }
  6605. std::string translateActiveException() {
  6606. return getRegistryHub().getExceptionTranslatorRegistry().translateActiveException();
  6607. }
  6608. } // end namespace Catch
  6609. // end catch_registry_hub.cpp
  6610. // start catch_reporter_registry.cpp
  6611. namespace Catch {
  6612. ReporterRegistry::~ReporterRegistry() = default;
  6613. IStreamingReporterPtr ReporterRegistry::create( std::string const& name, IConfigPtr const& config ) const {
  6614. auto it = m_factories.find( name );
  6615. if( it == m_factories.end() )
  6616. return nullptr;
  6617. return it->second->create( ReporterConfig( config ) );
  6618. }
  6619. void ReporterRegistry::registerReporter( std::string const& name, IReporterFactoryPtr const& factory ) {
  6620. m_factories.emplace(name, factory);
  6621. }
  6622. void ReporterRegistry::registerListener( IReporterFactoryPtr const& factory ) {
  6623. m_listeners.push_back( factory );
  6624. }
  6625. IReporterRegistry::FactoryMap const& ReporterRegistry::getFactories() const {
  6626. return m_factories;
  6627. }
  6628. IReporterRegistry::Listeners const& ReporterRegistry::getListeners() const {
  6629. return m_listeners;
  6630. }
  6631. }
  6632. // end catch_reporter_registry.cpp
  6633. // start catch_result_type.cpp
  6634. namespace Catch {
  6635. bool isOk( ResultWas::OfType resultType ) {
  6636. return ( resultType & ResultWas::FailureBit ) == 0;
  6637. }
  6638. bool isJustInfo( int flags ) {
  6639. return flags == ResultWas::Info;
  6640. }
  6641. ResultDisposition::Flags operator | ( ResultDisposition::Flags lhs, ResultDisposition::Flags rhs ) {
  6642. return static_cast<ResultDisposition::Flags>( static_cast<int>( lhs ) | static_cast<int>( rhs ) );
  6643. }
  6644. bool shouldContinueOnFailure( int flags ) { return ( flags & ResultDisposition::ContinueOnFailure ) != 0; }
  6645. bool shouldSuppressFailure( int flags ) { return ( flags & ResultDisposition::SuppressFail ) != 0; }
  6646. } // end namespace Catch
  6647. // end catch_result_type.cpp
  6648. // start catch_run_context.cpp
  6649. #include <cassert>
  6650. #include <algorithm>
  6651. #include <sstream>
  6652. namespace Catch {
  6653. class RedirectedStream {
  6654. std::ostream& m_originalStream;
  6655. std::ostream& m_redirectionStream;
  6656. std::streambuf* m_prevBuf;
  6657. public:
  6658. RedirectedStream( std::ostream& originalStream, std::ostream& redirectionStream )
  6659. : m_originalStream( originalStream ),
  6660. m_redirectionStream( redirectionStream ),
  6661. m_prevBuf( m_originalStream.rdbuf() )
  6662. {
  6663. m_originalStream.rdbuf( m_redirectionStream.rdbuf() );
  6664. }
  6665. ~RedirectedStream() {
  6666. m_originalStream.rdbuf( m_prevBuf );
  6667. }
  6668. };
  6669. class RedirectedStdOut {
  6670. ReusableStringStream m_rss;
  6671. RedirectedStream m_cout;
  6672. public:
  6673. RedirectedStdOut() : m_cout( Catch::cout(), m_rss.get() ) {}
  6674. auto str() const -> std::string { return m_rss.str(); }
  6675. };
  6676. // StdErr has two constituent streams in C++, std::cerr and std::clog
  6677. // This means that we need to redirect 2 streams into 1 to keep proper
  6678. // order of writes
  6679. class RedirectedStdErr {
  6680. ReusableStringStream m_rss;
  6681. RedirectedStream m_cerr;
  6682. RedirectedStream m_clog;
  6683. public:
  6684. RedirectedStdErr()
  6685. : m_cerr( Catch::cerr(), m_rss.get() ),
  6686. m_clog( Catch::clog(), m_rss.get() )
  6687. {}
  6688. auto str() const -> std::string { return m_rss.str(); }
  6689. };
  6690. RunContext::RunContext(IConfigPtr const& _config, IStreamingReporterPtr&& reporter)
  6691. : m_runInfo(_config->name()),
  6692. m_context(getCurrentMutableContext()),
  6693. m_config(_config),
  6694. m_reporter(std::move(reporter)),
  6695. m_lastAssertionInfo{ "", SourceLineInfo("",0), "", ResultDisposition::Normal },
  6696. m_includeSuccessfulResults( m_config->includeSuccessfulResults() )
  6697. {
  6698. m_context.setRunner(this);
  6699. m_context.setConfig(m_config);
  6700. m_context.setResultCapture(this);
  6701. m_reporter->testRunStarting(m_runInfo);
  6702. }
  6703. RunContext::~RunContext() {
  6704. m_reporter->testRunEnded(TestRunStats(m_runInfo, m_totals, aborting()));
  6705. }
  6706. void RunContext::testGroupStarting(std::string const& testSpec, std::size_t groupIndex, std::size_t groupsCount) {
  6707. m_reporter->testGroupStarting(GroupInfo(testSpec, groupIndex, groupsCount));
  6708. }
  6709. void RunContext::testGroupEnded(std::string const& testSpec, Totals const& totals, std::size_t groupIndex, std::size_t groupsCount) {
  6710. m_reporter->testGroupEnded(TestGroupStats(GroupInfo(testSpec, groupIndex, groupsCount), totals, aborting()));
  6711. }
  6712. Totals RunContext::runTest(TestCase const& testCase) {
  6713. Totals prevTotals = m_totals;
  6714. std::string redirectedCout;
  6715. std::string redirectedCerr;
  6716. TestCaseInfo testInfo = testCase.getTestCaseInfo();
  6717. m_reporter->testCaseStarting(testInfo);
  6718. m_activeTestCase = &testCase;
  6719. ITracker& rootTracker = m_trackerContext.startRun();
  6720. assert(rootTracker.isSectionTracker());
  6721. static_cast<SectionTracker&>(rootTracker).addInitialFilters(m_config->getSectionsToRun());
  6722. do {
  6723. m_trackerContext.startCycle();
  6724. m_testCaseTracker = &SectionTracker::acquire(m_trackerContext, TestCaseTracking::NameAndLocation(testInfo.name, testInfo.lineInfo));
  6725. runCurrentTest(redirectedCout, redirectedCerr);
  6726. } while (!m_testCaseTracker->isSuccessfullyCompleted() && !aborting());
  6727. Totals deltaTotals = m_totals.delta(prevTotals);
  6728. if (testInfo.expectedToFail() && deltaTotals.testCases.passed > 0) {
  6729. deltaTotals.assertions.failed++;
  6730. deltaTotals.testCases.passed--;
  6731. deltaTotals.testCases.failed++;
  6732. }
  6733. m_totals.testCases += deltaTotals.testCases;
  6734. m_reporter->testCaseEnded(TestCaseStats(testInfo,
  6735. deltaTotals,
  6736. redirectedCout,
  6737. redirectedCerr,
  6738. aborting()));
  6739. m_activeTestCase = nullptr;
  6740. m_testCaseTracker = nullptr;
  6741. return deltaTotals;
  6742. }
  6743. IConfigPtr RunContext::config() const {
  6744. return m_config;
  6745. }
  6746. IStreamingReporter& RunContext::reporter() const {
  6747. return *m_reporter;
  6748. }
  6749. void RunContext::assertionEnded(AssertionResult const & result) {
  6750. if (result.getResultType() == ResultWas::Ok) {
  6751. m_totals.assertions.passed++;
  6752. m_lastAssertionPassed = true;
  6753. } else if (!result.isOk()) {
  6754. m_lastAssertionPassed = false;
  6755. if( m_activeTestCase->getTestCaseInfo().okToFail() )
  6756. m_totals.assertions.failedButOk++;
  6757. else
  6758. m_totals.assertions.failed++;
  6759. }
  6760. else {
  6761. m_lastAssertionPassed = true;
  6762. }
  6763. // We have no use for the return value (whether messages should be cleared), because messages were made scoped
  6764. // and should be let to clear themselves out.
  6765. static_cast<void>(m_reporter->assertionEnded(AssertionStats(result, m_messages, m_totals)));
  6766. // Reset working state
  6767. resetAssertionInfo();
  6768. m_lastResult = result;
  6769. }
  6770. void RunContext::resetAssertionInfo() {
  6771. m_lastAssertionInfo.macroName = StringRef();
  6772. m_lastAssertionInfo.capturedExpression = "{Unknown expression after the reported line}"_sr;
  6773. }
  6774. bool RunContext::sectionStarted(SectionInfo const & sectionInfo, Counts & assertions) {
  6775. ITracker& sectionTracker = SectionTracker::acquire(m_trackerContext, TestCaseTracking::NameAndLocation(sectionInfo.name, sectionInfo.lineInfo));
  6776. if (!sectionTracker.isOpen())
  6777. return false;
  6778. m_activeSections.push_back(&sectionTracker);
  6779. m_lastAssertionInfo.lineInfo = sectionInfo.lineInfo;
  6780. m_reporter->sectionStarting(sectionInfo);
  6781. assertions = m_totals.assertions;
  6782. return true;
  6783. }
  6784. bool RunContext::testForMissingAssertions(Counts& assertions) {
  6785. if (assertions.total() != 0)
  6786. return false;
  6787. if (!m_config->warnAboutMissingAssertions())
  6788. return false;
  6789. if (m_trackerContext.currentTracker().hasChildren())
  6790. return false;
  6791. m_totals.assertions.failed++;
  6792. assertions.failed++;
  6793. return true;
  6794. }
  6795. void RunContext::sectionEnded(SectionEndInfo const & endInfo) {
  6796. Counts assertions = m_totals.assertions - endInfo.prevAssertions;
  6797. bool missingAssertions = testForMissingAssertions(assertions);
  6798. if (!m_activeSections.empty()) {
  6799. m_activeSections.back()->close();
  6800. m_activeSections.pop_back();
  6801. }
  6802. m_reporter->sectionEnded(SectionStats(endInfo.sectionInfo, assertions, endInfo.durationInSeconds, missingAssertions));
  6803. m_messages.clear();
  6804. }
  6805. void RunContext::sectionEndedEarly(SectionEndInfo const & endInfo) {
  6806. if (m_unfinishedSections.empty())
  6807. m_activeSections.back()->fail();
  6808. else
  6809. m_activeSections.back()->close();
  6810. m_activeSections.pop_back();
  6811. m_unfinishedSections.push_back(endInfo);
  6812. }
  6813. void RunContext::benchmarkStarting( BenchmarkInfo const& info ) {
  6814. m_reporter->benchmarkStarting( info );
  6815. }
  6816. void RunContext::benchmarkEnded( BenchmarkStats const& stats ) {
  6817. m_reporter->benchmarkEnded( stats );
  6818. }
  6819. void RunContext::pushScopedMessage(MessageInfo const & message) {
  6820. m_messages.push_back(message);
  6821. }
  6822. void RunContext::popScopedMessage(MessageInfo const & message) {
  6823. m_messages.erase(std::remove(m_messages.begin(), m_messages.end(), message), m_messages.end());
  6824. }
  6825. std::string RunContext::getCurrentTestName() const {
  6826. return m_activeTestCase
  6827. ? m_activeTestCase->getTestCaseInfo().name
  6828. : std::string();
  6829. }
  6830. const AssertionResult * RunContext::getLastResult() const {
  6831. return &(*m_lastResult);
  6832. }
  6833. void RunContext::exceptionEarlyReported() {
  6834. m_shouldReportUnexpected = false;
  6835. }
  6836. void RunContext::handleFatalErrorCondition( StringRef message ) {
  6837. // First notify reporter that bad things happened
  6838. m_reporter->fatalErrorEncountered(message);
  6839. // Don't rebuild the result -- the stringification itself can cause more fatal errors
  6840. // Instead, fake a result data.
  6841. AssertionResultData tempResult( ResultWas::FatalErrorCondition, { false } );
  6842. tempResult.message = message;
  6843. AssertionResult result(m_lastAssertionInfo, tempResult);
  6844. assertionEnded(result);
  6845. handleUnfinishedSections();
  6846. // Recreate section for test case (as we will lose the one that was in scope)
  6847. auto const& testCaseInfo = m_activeTestCase->getTestCaseInfo();
  6848. SectionInfo testCaseSection(testCaseInfo.lineInfo, testCaseInfo.name, testCaseInfo.description);
  6849. Counts assertions;
  6850. assertions.failed = 1;
  6851. SectionStats testCaseSectionStats(testCaseSection, assertions, 0, false);
  6852. m_reporter->sectionEnded(testCaseSectionStats);
  6853. auto const& testInfo = m_activeTestCase->getTestCaseInfo();
  6854. Totals deltaTotals;
  6855. deltaTotals.testCases.failed = 1;
  6856. deltaTotals.assertions.failed = 1;
  6857. m_reporter->testCaseEnded(TestCaseStats(testInfo,
  6858. deltaTotals,
  6859. std::string(),
  6860. std::string(),
  6861. false));
  6862. m_totals.testCases.failed++;
  6863. testGroupEnded(std::string(), m_totals, 1, 1);
  6864. m_reporter->testRunEnded(TestRunStats(m_runInfo, m_totals, false));
  6865. }
  6866. bool RunContext::lastAssertionPassed() {
  6867. return m_lastAssertionPassed;
  6868. }
  6869. void RunContext::assertionPassed() {
  6870. m_lastAssertionPassed = true;
  6871. ++m_totals.assertions.passed;
  6872. resetAssertionInfo();
  6873. }
  6874. bool RunContext::aborting() const {
  6875. return m_totals.assertions.failed == static_cast<std::size_t>(m_config->abortAfter());
  6876. }
  6877. void RunContext::runCurrentTest(std::string & redirectedCout, std::string & redirectedCerr) {
  6878. auto const& testCaseInfo = m_activeTestCase->getTestCaseInfo();
  6879. SectionInfo testCaseSection(testCaseInfo.lineInfo, testCaseInfo.name, testCaseInfo.description);
  6880. m_reporter->sectionStarting(testCaseSection);
  6881. Counts prevAssertions = m_totals.assertions;
  6882. double duration = 0;
  6883. m_shouldReportUnexpected = true;
  6884. m_lastAssertionInfo = { "TEST_CASE", testCaseInfo.lineInfo, "", ResultDisposition::Normal };
  6885. seedRng(*m_config);
  6886. Timer timer;
  6887. try {
  6888. if (m_reporter->getPreferences().shouldRedirectStdOut) {
  6889. RedirectedStdOut redirectedStdOut;
  6890. RedirectedStdErr redirectedStdErr;
  6891. timer.start();
  6892. invokeActiveTestCase();
  6893. redirectedCout += redirectedStdOut.str();
  6894. redirectedCerr += redirectedStdErr.str();
  6895. } else {
  6896. timer.start();
  6897. invokeActiveTestCase();
  6898. }
  6899. duration = timer.getElapsedSeconds();
  6900. } catch (TestFailureException&) {
  6901. // This just means the test was aborted due to failure
  6902. } catch (...) {
  6903. // Under CATCH_CONFIG_FAST_COMPILE, unexpected exceptions under REQUIRE assertions
  6904. // are reported without translation at the point of origin.
  6905. if( m_shouldReportUnexpected ) {
  6906. AssertionReaction dummyReaction;
  6907. handleUnexpectedInflightException( m_lastAssertionInfo, translateActiveException(), dummyReaction );
  6908. }
  6909. }
  6910. m_testCaseTracker->close();
  6911. handleUnfinishedSections();
  6912. m_messages.clear();
  6913. Counts assertions = m_totals.assertions - prevAssertions;
  6914. bool missingAssertions = testForMissingAssertions(assertions);
  6915. SectionStats testCaseSectionStats(testCaseSection, assertions, duration, missingAssertions);
  6916. m_reporter->sectionEnded(testCaseSectionStats);
  6917. }
  6918. void RunContext::invokeActiveTestCase() {
  6919. FatalConditionHandler fatalConditionHandler; // Handle signals
  6920. m_activeTestCase->invoke();
  6921. fatalConditionHandler.reset();
  6922. }
  6923. void RunContext::handleUnfinishedSections() {
  6924. // If sections ended prematurely due to an exception we stored their
  6925. // infos here so we can tear them down outside the unwind process.
  6926. for (auto it = m_unfinishedSections.rbegin(),
  6927. itEnd = m_unfinishedSections.rend();
  6928. it != itEnd;
  6929. ++it)
  6930. sectionEnded(*it);
  6931. m_unfinishedSections.clear();
  6932. }
  6933. void RunContext::handleExpr(
  6934. AssertionInfo const& info,
  6935. ITransientExpression const& expr,
  6936. AssertionReaction& reaction
  6937. ) {
  6938. m_reporter->assertionStarting( info );
  6939. bool negated = isFalseTest( info.resultDisposition );
  6940. bool result = expr.getResult() != negated;
  6941. if( result ) {
  6942. if (!m_includeSuccessfulResults) {
  6943. assertionPassed();
  6944. }
  6945. else {
  6946. reportExpr(info, ResultWas::Ok, &expr, negated);
  6947. }
  6948. }
  6949. else {
  6950. reportExpr(info, ResultWas::ExpressionFailed, &expr, negated );
  6951. populateReaction( reaction );
  6952. }
  6953. }
  6954. void RunContext::reportExpr(
  6955. AssertionInfo const &info,
  6956. ResultWas::OfType resultType,
  6957. ITransientExpression const *expr,
  6958. bool negated ) {
  6959. m_lastAssertionInfo = info;
  6960. AssertionResultData data( resultType, LazyExpression( negated ) );
  6961. AssertionResult assertionResult{ info, data };
  6962. assertionResult.m_resultData.lazyExpression.m_transientExpression = expr;
  6963. assertionEnded( assertionResult );
  6964. }
  6965. void RunContext::handleMessage(
  6966. AssertionInfo const& info,
  6967. ResultWas::OfType resultType,
  6968. StringRef const& message,
  6969. AssertionReaction& reaction
  6970. ) {
  6971. m_reporter->assertionStarting( info );
  6972. m_lastAssertionInfo = info;
  6973. AssertionResultData data( resultType, LazyExpression( false ) );
  6974. data.message = message;
  6975. AssertionResult assertionResult{ m_lastAssertionInfo, data };
  6976. assertionEnded( assertionResult );
  6977. if( !assertionResult.isOk() )
  6978. populateReaction( reaction );
  6979. }
  6980. void RunContext::handleUnexpectedExceptionNotThrown(
  6981. AssertionInfo const& info,
  6982. AssertionReaction& reaction
  6983. ) {
  6984. handleNonExpr(info, Catch::ResultWas::DidntThrowException, reaction);
  6985. }
  6986. void RunContext::handleUnexpectedInflightException(
  6987. AssertionInfo const& info,
  6988. std::string const& message,
  6989. AssertionReaction& reaction
  6990. ) {
  6991. m_lastAssertionInfo = info;
  6992. AssertionResultData data( ResultWas::ThrewException, LazyExpression( false ) );
  6993. data.message = message;
  6994. AssertionResult assertionResult{ info, data };
  6995. assertionEnded( assertionResult );
  6996. populateReaction( reaction );
  6997. }
  6998. void RunContext::populateReaction( AssertionReaction& reaction ) {
  6999. reaction.shouldDebugBreak = m_config->shouldDebugBreak();
  7000. reaction.shouldThrow = aborting() || (m_lastAssertionInfo.resultDisposition & ResultDisposition::Normal);
  7001. }
  7002. void RunContext::handleIncomplete(
  7003. AssertionInfo const& info
  7004. ) {
  7005. m_lastAssertionInfo = info;
  7006. AssertionResultData data( ResultWas::ThrewException, LazyExpression( false ) );
  7007. data.message = "Exception translation was disabled by CATCH_CONFIG_FAST_COMPILE";
  7008. AssertionResult assertionResult{ info, data };
  7009. assertionEnded( assertionResult );
  7010. }
  7011. void RunContext::handleNonExpr(
  7012. AssertionInfo const &info,
  7013. ResultWas::OfType resultType,
  7014. AssertionReaction &reaction
  7015. ) {
  7016. m_lastAssertionInfo = info;
  7017. AssertionResultData data( resultType, LazyExpression( false ) );
  7018. AssertionResult assertionResult{ info, data };
  7019. assertionEnded( assertionResult );
  7020. if( !assertionResult.isOk() )
  7021. populateReaction( reaction );
  7022. }
  7023. IResultCapture& getResultCapture() {
  7024. if (auto* capture = getCurrentContext().getResultCapture())
  7025. return *capture;
  7026. else
  7027. CATCH_INTERNAL_ERROR("No result capture instance");
  7028. }
  7029. }
  7030. // end catch_run_context.cpp
  7031. // start catch_section.cpp
  7032. namespace Catch {
  7033. Section::Section( SectionInfo const& info )
  7034. : m_info( info ),
  7035. m_sectionIncluded( getResultCapture().sectionStarted( m_info, m_assertions ) )
  7036. {
  7037. m_timer.start();
  7038. }
  7039. #if defined(_MSC_VER)
  7040. #pragma warning(push)
  7041. #pragma warning(disable:4996) // std::uncaught_exception is deprecated in C++17
  7042. #endif
  7043. Section::~Section() {
  7044. if( m_sectionIncluded ) {
  7045. SectionEndInfo endInfo( m_info, m_assertions, m_timer.getElapsedSeconds() );
  7046. if( std::uncaught_exception() )
  7047. getResultCapture().sectionEndedEarly( endInfo );
  7048. else
  7049. getResultCapture().sectionEnded( endInfo );
  7050. }
  7051. }
  7052. #if defined(_MSC_VER)
  7053. #pragma warning(pop)
  7054. #endif
  7055. // This indicates whether the section should be executed or not
  7056. Section::operator bool() const {
  7057. return m_sectionIncluded;
  7058. }
  7059. } // end namespace Catch
  7060. // end catch_section.cpp
  7061. // start catch_section_info.cpp
  7062. namespace Catch {
  7063. SectionInfo::SectionInfo
  7064. ( SourceLineInfo const& _lineInfo,
  7065. std::string const& _name,
  7066. std::string const& _description )
  7067. : name( _name ),
  7068. description( _description ),
  7069. lineInfo( _lineInfo )
  7070. {}
  7071. SectionEndInfo::SectionEndInfo( SectionInfo const& _sectionInfo, Counts const& _prevAssertions, double _durationInSeconds )
  7072. : sectionInfo( _sectionInfo ), prevAssertions( _prevAssertions ), durationInSeconds( _durationInSeconds )
  7073. {}
  7074. } // end namespace Catch
  7075. // end catch_section_info.cpp
  7076. // start catch_session.cpp
  7077. // start catch_session.h
  7078. #include <memory>
  7079. namespace Catch {
  7080. class Session : NonCopyable {
  7081. public:
  7082. Session();
  7083. ~Session() override;
  7084. void showHelp() const;
  7085. void libIdentify();
  7086. int applyCommandLine( int argc, char* argv[] );
  7087. void useConfigData( ConfigData const& configData );
  7088. int run( int argc, char* argv[] );
  7089. #if defined(WIN32) && defined(UNICODE)
  7090. int run( int argc, wchar_t* const argv[] );
  7091. #endif
  7092. int run();
  7093. clara::Parser const& cli() const;
  7094. void cli( clara::Parser const& newParser );
  7095. ConfigData& configData();
  7096. Config& config();
  7097. private:
  7098. int runInternal();
  7099. clara::Parser m_cli;
  7100. ConfigData m_configData;
  7101. std::shared_ptr<Config> m_config;
  7102. bool m_startupExceptions = false;
  7103. };
  7104. } // end namespace Catch
  7105. // end catch_session.h
  7106. // start catch_version.h
  7107. #include <iosfwd>
  7108. namespace Catch {
  7109. // Versioning information
  7110. struct Version {
  7111. Version( Version const& ) = delete;
  7112. Version& operator=( Version const& ) = delete;
  7113. Version( unsigned int _majorVersion,
  7114. unsigned int _minorVersion,
  7115. unsigned int _patchNumber,
  7116. char const * const _branchName,
  7117. unsigned int _buildNumber );
  7118. unsigned int const majorVersion;
  7119. unsigned int const minorVersion;
  7120. unsigned int const patchNumber;
  7121. // buildNumber is only used if branchName is not null
  7122. char const * const branchName;
  7123. unsigned int const buildNumber;
  7124. friend std::ostream& operator << ( std::ostream& os, Version const& version );
  7125. };
  7126. Version const& libraryVersion();
  7127. }
  7128. // end catch_version.h
  7129. #include <cstdlib>
  7130. #include <iomanip>
  7131. namespace Catch {
  7132. namespace {
  7133. const int MaxExitCode = 255;
  7134. IStreamingReporterPtr createReporter(std::string const& reporterName, IConfigPtr const& config) {
  7135. auto reporter = Catch::getRegistryHub().getReporterRegistry().create(reporterName, config);
  7136. CATCH_ENFORCE(reporter, "No reporter registered with name: '" << reporterName << "'");
  7137. return reporter;
  7138. }
  7139. #ifndef CATCH_CONFIG_DEFAULT_REPORTER
  7140. #define CATCH_CONFIG_DEFAULT_REPORTER "console"
  7141. #endif
  7142. IStreamingReporterPtr makeReporter(std::shared_ptr<Config> const& config) {
  7143. auto const& reporterNames = config->getReporterNames();
  7144. if (reporterNames.empty())
  7145. return createReporter(CATCH_CONFIG_DEFAULT_REPORTER, config);
  7146. IStreamingReporterPtr reporter;
  7147. for (auto const& name : reporterNames)
  7148. addReporter(reporter, createReporter(name, config));
  7149. return reporter;
  7150. }
  7151. #undef CATCH_CONFIG_DEFAULT_REPORTER
  7152. void addListeners(IStreamingReporterPtr& reporters, IConfigPtr const& config) {
  7153. auto const& listeners = Catch::getRegistryHub().getReporterRegistry().getListeners();
  7154. for (auto const& listener : listeners)
  7155. addReporter(reporters, listener->create(Catch::ReporterConfig(config)));
  7156. }
  7157. Catch::Totals runTests(std::shared_ptr<Config> const& config) {
  7158. IStreamingReporterPtr reporter = makeReporter(config);
  7159. addListeners(reporter, config);
  7160. RunContext context(config, std::move(reporter));
  7161. Totals totals;
  7162. context.testGroupStarting(config->name(), 1, 1);
  7163. TestSpec testSpec = config->testSpec();
  7164. if (!testSpec.hasFilters())
  7165. testSpec = TestSpecParser(ITagAliasRegistry::get()).parse("~[.]").testSpec(); // All not hidden tests
  7166. auto const& allTestCases = getAllTestCasesSorted(*config);
  7167. for (auto const& testCase : allTestCases) {
  7168. if (!context.aborting() && matchTest(testCase, testSpec, *config))
  7169. totals += context.runTest(testCase);
  7170. else
  7171. context.reporter().skipTest(testCase);
  7172. }
  7173. context.testGroupEnded(config->name(), totals, 1, 1);
  7174. return totals;
  7175. }
  7176. void applyFilenamesAsTags(Catch::IConfig const& config) {
  7177. auto& tests = const_cast<std::vector<TestCase>&>(getAllTestCasesSorted(config));
  7178. for (auto& testCase : tests) {
  7179. auto tags = testCase.tags;
  7180. std::string filename = testCase.lineInfo.file;
  7181. auto lastSlash = filename.find_last_of("\\/");
  7182. if (lastSlash != std::string::npos) {
  7183. filename.erase(0, lastSlash);
  7184. filename[0] = '#';
  7185. }
  7186. auto lastDot = filename.find_last_of('.');
  7187. if (lastDot != std::string::npos) {
  7188. filename.erase(lastDot);
  7189. }
  7190. tags.push_back(std::move(filename));
  7191. setTags(testCase, tags);
  7192. }
  7193. }
  7194. } // anon namespace
  7195. Session::Session() {
  7196. static bool alreadyInstantiated = false;
  7197. if( alreadyInstantiated ) {
  7198. try { CATCH_INTERNAL_ERROR( "Only one instance of Catch::Session can ever be used" ); }
  7199. catch(...) { getMutableRegistryHub().registerStartupException(); }
  7200. }
  7201. const auto& exceptions = getRegistryHub().getStartupExceptionRegistry().getExceptions();
  7202. if ( !exceptions.empty() ) {
  7203. m_startupExceptions = true;
  7204. Colour colourGuard( Colour::Red );
  7205. Catch::cerr() << "Errors occured during startup!" << '\n';
  7206. // iterate over all exceptions and notify user
  7207. for ( const auto& ex_ptr : exceptions ) {
  7208. try {
  7209. std::rethrow_exception(ex_ptr);
  7210. } catch ( std::exception const& ex ) {
  7211. Catch::cerr() << Column( ex.what() ).indent(2) << '\n';
  7212. }
  7213. }
  7214. }
  7215. alreadyInstantiated = true;
  7216. m_cli = makeCommandLineParser( m_configData );
  7217. }
  7218. Session::~Session() {
  7219. Catch::cleanUp();
  7220. }
  7221. void Session::showHelp() const {
  7222. Catch::cout()
  7223. << "\nCatch v" << libraryVersion() << "\n"
  7224. << m_cli << std::endl
  7225. << "For more detailed usage please see the project docs\n" << std::endl;
  7226. }
  7227. void Session::libIdentify() {
  7228. Catch::cout()
  7229. << std::left << std::setw(16) << "description: " << "A Catch test executable\n"
  7230. << std::left << std::setw(16) << "category: " << "testframework\n"
  7231. << std::left << std::setw(16) << "framework: " << "Catch Test\n"
  7232. << std::left << std::setw(16) << "version: " << libraryVersion() << std::endl;
  7233. }
  7234. int Session::applyCommandLine( int argc, char* argv[] ) {
  7235. if( m_startupExceptions )
  7236. return 1;
  7237. auto result = m_cli.parse( clara::Args( argc, argv ) );
  7238. if( !result ) {
  7239. Catch::cerr()
  7240. << Colour( Colour::Red )
  7241. << "\nError(s) in input:\n"
  7242. << Column( result.errorMessage() ).indent( 2 )
  7243. << "\n\n";
  7244. Catch::cerr() << "Run with -? for usage\n" << std::endl;
  7245. return MaxExitCode;
  7246. }
  7247. if( m_configData.showHelp )
  7248. showHelp();
  7249. if( m_configData.libIdentify )
  7250. libIdentify();
  7251. m_config.reset();
  7252. return 0;
  7253. }
  7254. void Session::useConfigData( ConfigData const& configData ) {
  7255. m_configData = configData;
  7256. m_config.reset();
  7257. }
  7258. int Session::run( int argc, char* argv[] ) {
  7259. if( m_startupExceptions )
  7260. return 1;
  7261. int returnCode = applyCommandLine( argc, argv );
  7262. if( returnCode == 0 )
  7263. returnCode = run();
  7264. return returnCode;
  7265. }
  7266. #if defined(WIN32) && defined(UNICODE)
  7267. int Session::run( int argc, wchar_t* const argv[] ) {
  7268. char **utf8Argv = new char *[ argc ];
  7269. for ( int i = 0; i < argc; ++i ) {
  7270. int bufSize = WideCharToMultiByte( CP_UTF8, 0, argv[i], -1, NULL, 0, NULL, NULL );
  7271. utf8Argv[ i ] = new char[ bufSize ];
  7272. WideCharToMultiByte( CP_UTF8, 0, argv[i], -1, utf8Argv[i], bufSize, NULL, NULL );
  7273. }
  7274. int returnCode = run( argc, utf8Argv );
  7275. for ( int i = 0; i < argc; ++i )
  7276. delete [] utf8Argv[ i ];
  7277. delete [] utf8Argv;
  7278. return returnCode;
  7279. }
  7280. #endif
  7281. int Session::run() {
  7282. if( ( m_configData.waitForKeypress & WaitForKeypress::BeforeStart ) != 0 ) {
  7283. Catch::cout() << "...waiting for enter/ return before starting" << std::endl;
  7284. static_cast<void>(std::getchar());
  7285. }
  7286. int exitCode = runInternal();
  7287. if( ( m_configData.waitForKeypress & WaitForKeypress::BeforeExit ) != 0 ) {
  7288. Catch::cout() << "...waiting for enter/ return before exiting, with code: " << exitCode << std::endl;
  7289. static_cast<void>(std::getchar());
  7290. }
  7291. return exitCode;
  7292. }
  7293. clara::Parser const& Session::cli() const {
  7294. return m_cli;
  7295. }
  7296. void Session::cli( clara::Parser const& newParser ) {
  7297. m_cli = newParser;
  7298. }
  7299. ConfigData& Session::configData() {
  7300. return m_configData;
  7301. }
  7302. Config& Session::config() {
  7303. if( !m_config )
  7304. m_config = std::make_shared<Config>( m_configData );
  7305. return *m_config;
  7306. }
  7307. int Session::runInternal() {
  7308. if( m_startupExceptions )
  7309. return 1;
  7310. if( m_configData.showHelp || m_configData.libIdentify )
  7311. return 0;
  7312. try
  7313. {
  7314. config(); // Force config to be constructed
  7315. seedRng( *m_config );
  7316. if( m_configData.filenamesAsTags )
  7317. applyFilenamesAsTags( *m_config );
  7318. // Handle list request
  7319. if( Option<std::size_t> listed = list( config() ) )
  7320. return static_cast<int>( *listed );
  7321. // Note that on unices only the lower 8 bits are usually used, clamping
  7322. // the return value to 255 prevents false negative when some multiple
  7323. // of 256 tests has failed
  7324. return (std::min)( MaxExitCode, static_cast<int>( runTests( m_config ).assertions.failed ) );
  7325. }
  7326. catch( std::exception& ex ) {
  7327. Catch::cerr() << ex.what() << std::endl;
  7328. return MaxExitCode;
  7329. }
  7330. }
  7331. } // end namespace Catch
  7332. // end catch_session.cpp
  7333. // start catch_startup_exception_registry.cpp
  7334. namespace Catch {
  7335. void StartupExceptionRegistry::add( std::exception_ptr const& exception ) noexcept {
  7336. try {
  7337. m_exceptions.push_back(exception);
  7338. }
  7339. catch(...) {
  7340. // If we run out of memory during start-up there's really not a lot more we can do about it
  7341. std::terminate();
  7342. }
  7343. }
  7344. std::vector<std::exception_ptr> const& StartupExceptionRegistry::getExceptions() const noexcept {
  7345. return m_exceptions;
  7346. }
  7347. } // end namespace Catch
  7348. // end catch_startup_exception_registry.cpp
  7349. // start catch_stream.cpp
  7350. #include <cstdio>
  7351. #include <iostream>
  7352. #include <fstream>
  7353. #include <sstream>
  7354. #include <vector>
  7355. #include <memory>
  7356. #if defined(__clang__)
  7357. # pragma clang diagnostic push
  7358. # pragma clang diagnostic ignored "-Wexit-time-destructors"
  7359. #endif
  7360. namespace Catch {
  7361. Catch::IStream::~IStream() = default;
  7362. namespace detail { namespace {
  7363. template<typename WriterF, std::size_t bufferSize=256>
  7364. class StreamBufImpl : public std::streambuf {
  7365. char data[bufferSize];
  7366. WriterF m_writer;
  7367. public:
  7368. StreamBufImpl() {
  7369. setp( data, data + sizeof(data) );
  7370. }
  7371. ~StreamBufImpl() noexcept {
  7372. StreamBufImpl::sync();
  7373. }
  7374. private:
  7375. int overflow( int c ) override {
  7376. sync();
  7377. if( c != EOF ) {
  7378. if( pbase() == epptr() )
  7379. m_writer( std::string( 1, static_cast<char>( c ) ) );
  7380. else
  7381. sputc( static_cast<char>( c ) );
  7382. }
  7383. return 0;
  7384. }
  7385. int sync() override {
  7386. if( pbase() != pptr() ) {
  7387. m_writer( std::string( pbase(), static_cast<std::string::size_type>( pptr() - pbase() ) ) );
  7388. setp( pbase(), epptr() );
  7389. }
  7390. return 0;
  7391. }
  7392. };
  7393. ///////////////////////////////////////////////////////////////////////////
  7394. struct OutputDebugWriter {
  7395. void operator()( std::string const&str ) {
  7396. writeToDebugConsole( str );
  7397. }
  7398. };
  7399. ///////////////////////////////////////////////////////////////////////////
  7400. class FileStream : public IStream {
  7401. mutable std::ofstream m_ofs;
  7402. public:
  7403. FileStream( StringRef filename ) {
  7404. m_ofs.open( filename.c_str() );
  7405. CATCH_ENFORCE( !m_ofs.fail(), "Unable to open file: '" << filename << "'" );
  7406. }
  7407. ~FileStream() override = default;
  7408. public: // IStream
  7409. std::ostream& stream() const override {
  7410. return m_ofs;
  7411. }
  7412. };
  7413. ///////////////////////////////////////////////////////////////////////////
  7414. class CoutStream : public IStream {
  7415. mutable std::ostream m_os;
  7416. public:
  7417. // Store the streambuf from cout up-front because
  7418. // cout may get redirected when running tests
  7419. CoutStream() : m_os( Catch::cout().rdbuf() ) {}
  7420. ~CoutStream() override = default;
  7421. public: // IStream
  7422. std::ostream& stream() const override { return m_os; }
  7423. };
  7424. ///////////////////////////////////////////////////////////////////////////
  7425. class DebugOutStream : public IStream {
  7426. std::unique_ptr<StreamBufImpl<OutputDebugWriter>> m_streamBuf;
  7427. mutable std::ostream m_os;
  7428. public:
  7429. DebugOutStream()
  7430. : m_streamBuf( new StreamBufImpl<OutputDebugWriter>() ),
  7431. m_os( m_streamBuf.get() )
  7432. {}
  7433. ~DebugOutStream() override = default;
  7434. public: // IStream
  7435. std::ostream& stream() const override { return m_os; }
  7436. };
  7437. }} // namespace anon::detail
  7438. ///////////////////////////////////////////////////////////////////////////
  7439. auto makeStream( StringRef const &filename ) -> IStream const* {
  7440. if( filename.empty() )
  7441. return new detail::CoutStream();
  7442. else if( filename[0] == '%' ) {
  7443. if( filename == "%debug" )
  7444. return new detail::DebugOutStream();
  7445. else
  7446. CATCH_ERROR( "Unrecognised stream: '" << filename << "'" );
  7447. }
  7448. else
  7449. return new detail::FileStream( filename );
  7450. }
  7451. // This class encapsulates the idea of a pool of ostringstreams that can be reused.
  7452. struct StringStreams {
  7453. std::vector<std::unique_ptr<std::ostringstream>> m_streams;
  7454. std::vector<std::size_t> m_unused;
  7455. std::ostringstream m_referenceStream; // Used for copy state/ flags from
  7456. static StringStreams* s_instance;
  7457. auto add() -> std::size_t {
  7458. if( m_unused.empty() ) {
  7459. m_streams.push_back( std::unique_ptr<std::ostringstream>( new std::ostringstream ) );
  7460. return m_streams.size()-1;
  7461. }
  7462. else {
  7463. auto index = m_unused.back();
  7464. m_unused.pop_back();
  7465. return index;
  7466. }
  7467. }
  7468. void release( std::size_t index ) {
  7469. m_streams[index]->copyfmt( m_referenceStream ); // Restore initial flags and other state
  7470. m_unused.push_back(index);
  7471. }
  7472. // !TBD: put in TLS
  7473. static auto instance() -> StringStreams& {
  7474. if( !s_instance )
  7475. s_instance = new StringStreams();
  7476. return *s_instance;
  7477. }
  7478. static void cleanup() {
  7479. delete s_instance;
  7480. s_instance = nullptr;
  7481. }
  7482. };
  7483. StringStreams* StringStreams::s_instance = nullptr;
  7484. void ReusableStringStream::cleanup() {
  7485. StringStreams::cleanup();
  7486. }
  7487. ReusableStringStream::ReusableStringStream()
  7488. : m_index( StringStreams::instance().add() ),
  7489. m_oss( StringStreams::instance().m_streams[m_index].get() )
  7490. {}
  7491. ReusableStringStream::~ReusableStringStream() {
  7492. static_cast<std::ostringstream*>( m_oss )->str("");
  7493. m_oss->clear();
  7494. StringStreams::instance().release( m_index );
  7495. }
  7496. auto ReusableStringStream::str() const -> std::string {
  7497. return static_cast<std::ostringstream*>( m_oss )->str();
  7498. }
  7499. ///////////////////////////////////////////////////////////////////////////
  7500. #ifndef CATCH_CONFIG_NOSTDOUT // If you #define this you must implement these functions
  7501. std::ostream& cout() { return std::cout; }
  7502. std::ostream& cerr() { return std::cerr; }
  7503. std::ostream& clog() { return std::clog; }
  7504. #endif
  7505. }
  7506. #if defined(__clang__)
  7507. # pragma clang diagnostic pop
  7508. #endif
  7509. // end catch_stream.cpp
  7510. // start catch_string_manip.cpp
  7511. #include <algorithm>
  7512. #include <ostream>
  7513. #include <cstring>
  7514. #include <cctype>
  7515. namespace Catch {
  7516. bool startsWith( std::string const& s, std::string const& prefix ) {
  7517. return s.size() >= prefix.size() && std::equal(prefix.begin(), prefix.end(), s.begin());
  7518. }
  7519. bool startsWith( std::string const& s, char prefix ) {
  7520. return !s.empty() && s[0] == prefix;
  7521. }
  7522. bool endsWith( std::string const& s, std::string const& suffix ) {
  7523. return s.size() >= suffix.size() && std::equal(suffix.rbegin(), suffix.rend(), s.rbegin());
  7524. }
  7525. bool endsWith( std::string const& s, char suffix ) {
  7526. return !s.empty() && s[s.size()-1] == suffix;
  7527. }
  7528. bool contains( std::string const& s, std::string const& infix ) {
  7529. return s.find( infix ) != std::string::npos;
  7530. }
  7531. char toLowerCh(char c) {
  7532. return static_cast<char>( std::tolower( c ) );
  7533. }
  7534. void toLowerInPlace( std::string& s ) {
  7535. std::transform( s.begin(), s.end(), s.begin(), toLowerCh );
  7536. }
  7537. std::string toLower( std::string const& s ) {
  7538. std::string lc = s;
  7539. toLowerInPlace( lc );
  7540. return lc;
  7541. }
  7542. std::string trim( std::string const& str ) {
  7543. static char const* whitespaceChars = "\n\r\t ";
  7544. std::string::size_type start = str.find_first_not_of( whitespaceChars );
  7545. std::string::size_type end = str.find_last_not_of( whitespaceChars );
  7546. return start != std::string::npos ? str.substr( start, 1+end-start ) : std::string();
  7547. }
  7548. bool replaceInPlace( std::string& str, std::string const& replaceThis, std::string const& withThis ) {
  7549. bool replaced = false;
  7550. std::size_t i = str.find( replaceThis );
  7551. while( i != std::string::npos ) {
  7552. replaced = true;
  7553. str = str.substr( 0, i ) + withThis + str.substr( i+replaceThis.size() );
  7554. if( i < str.size()-withThis.size() )
  7555. i = str.find( replaceThis, i+withThis.size() );
  7556. else
  7557. i = std::string::npos;
  7558. }
  7559. return replaced;
  7560. }
  7561. pluralise::pluralise( std::size_t count, std::string const& label )
  7562. : m_count( count ),
  7563. m_label( label )
  7564. {}
  7565. std::ostream& operator << ( std::ostream& os, pluralise const& pluraliser ) {
  7566. os << pluraliser.m_count << ' ' << pluraliser.m_label;
  7567. if( pluraliser.m_count != 1 )
  7568. os << 's';
  7569. return os;
  7570. }
  7571. }
  7572. // end catch_string_manip.cpp
  7573. // start catch_stringref.cpp
  7574. #if defined(__clang__)
  7575. # pragma clang diagnostic push
  7576. # pragma clang diagnostic ignored "-Wexit-time-destructors"
  7577. #endif
  7578. #include <ostream>
  7579. #include <cstring>
  7580. namespace Catch {
  7581. StringRef::StringRef( char const* rawChars ) noexcept
  7582. : StringRef( rawChars, static_cast<StringRef::size_type>(std::strlen(rawChars) ) )
  7583. {}
  7584. StringRef::operator std::string() const {
  7585. return std::string( m_start, m_size );
  7586. }
  7587. void StringRef::swap( StringRef& other ) noexcept {
  7588. std::swap( m_start, other.m_start );
  7589. std::swap( m_size, other.m_size );
  7590. std::swap( m_data, other.m_data );
  7591. }
  7592. auto StringRef::c_str() const -> char const* {
  7593. if( isSubstring() )
  7594. const_cast<StringRef*>( this )->takeOwnership();
  7595. return m_start;
  7596. }
  7597. auto StringRef::data() const noexcept -> char const* {
  7598. return m_start;
  7599. }
  7600. auto StringRef::isOwned() const noexcept -> bool {
  7601. return m_data != nullptr;
  7602. }
  7603. auto StringRef::isSubstring() const noexcept -> bool {
  7604. return m_start[m_size] != '\0';
  7605. }
  7606. void StringRef::takeOwnership() {
  7607. if( !isOwned() ) {
  7608. m_data = new char[m_size+1];
  7609. memcpy( m_data, m_start, m_size );
  7610. m_data[m_size] = '\0';
  7611. m_start = m_data;
  7612. }
  7613. }
  7614. auto StringRef::substr( size_type start, size_type size ) const noexcept -> StringRef {
  7615. if( start < m_size )
  7616. return StringRef( m_start+start, size );
  7617. else
  7618. return StringRef();
  7619. }
  7620. auto StringRef::operator == ( StringRef const& other ) const noexcept -> bool {
  7621. return
  7622. size() == other.size() &&
  7623. (std::strncmp( m_start, other.m_start, size() ) == 0);
  7624. }
  7625. auto StringRef::operator != ( StringRef const& other ) const noexcept -> bool {
  7626. return !operator==( other );
  7627. }
  7628. auto StringRef::operator[](size_type index) const noexcept -> char {
  7629. return m_start[index];
  7630. }
  7631. auto StringRef::numberOfCharacters() const noexcept -> size_type {
  7632. size_type noChars = m_size;
  7633. // Make adjustments for uft encodings
  7634. for( size_type i=0; i < m_size; ++i ) {
  7635. char c = m_start[i];
  7636. if( ( c & 0b11000000 ) == 0b11000000 ) {
  7637. if( ( c & 0b11100000 ) == 0b11000000 )
  7638. noChars--;
  7639. else if( ( c & 0b11110000 ) == 0b11100000 )
  7640. noChars-=2;
  7641. else if( ( c & 0b11111000 ) == 0b11110000 )
  7642. noChars-=3;
  7643. }
  7644. }
  7645. return noChars;
  7646. }
  7647. auto operator + ( StringRef const& lhs, StringRef const& rhs ) -> std::string {
  7648. std::string str;
  7649. str.reserve( lhs.size() + rhs.size() );
  7650. str += lhs;
  7651. str += rhs;
  7652. return str;
  7653. }
  7654. auto operator + ( StringRef const& lhs, const char* rhs ) -> std::string {
  7655. return std::string( lhs ) + std::string( rhs );
  7656. }
  7657. auto operator + ( char const* lhs, StringRef const& rhs ) -> std::string {
  7658. return std::string( lhs ) + std::string( rhs );
  7659. }
  7660. auto operator << ( std::ostream& os, StringRef const& str ) -> std::ostream& {
  7661. return os << str.c_str();
  7662. }
  7663. } // namespace Catch
  7664. #if defined(__clang__)
  7665. # pragma clang diagnostic pop
  7666. #endif
  7667. // end catch_stringref.cpp
  7668. // start catch_tag_alias.cpp
  7669. namespace Catch {
  7670. TagAlias::TagAlias(std::string const & _tag, SourceLineInfo _lineInfo): tag(_tag), lineInfo(_lineInfo) {}
  7671. }
  7672. // end catch_tag_alias.cpp
  7673. // start catch_tag_alias_autoregistrar.cpp
  7674. namespace Catch {
  7675. RegistrarForTagAliases::RegistrarForTagAliases(char const* alias, char const* tag, SourceLineInfo const& lineInfo) {
  7676. try {
  7677. getMutableRegistryHub().registerTagAlias(alias, tag, lineInfo);
  7678. } catch (...) {
  7679. // Do not throw when constructing global objects, instead register the exception to be processed later
  7680. getMutableRegistryHub().registerStartupException();
  7681. }
  7682. }
  7683. }
  7684. // end catch_tag_alias_autoregistrar.cpp
  7685. // start catch_tag_alias_registry.cpp
  7686. #include <sstream>
  7687. namespace Catch {
  7688. TagAliasRegistry::~TagAliasRegistry() {}
  7689. TagAlias const* TagAliasRegistry::find( std::string const& alias ) const {
  7690. auto it = m_registry.find( alias );
  7691. if( it != m_registry.end() )
  7692. return &(it->second);
  7693. else
  7694. return nullptr;
  7695. }
  7696. std::string TagAliasRegistry::expandAliases( std::string const& unexpandedTestSpec ) const {
  7697. std::string expandedTestSpec = unexpandedTestSpec;
  7698. for( auto const& registryKvp : m_registry ) {
  7699. std::size_t pos = expandedTestSpec.find( registryKvp.first );
  7700. if( pos != std::string::npos ) {
  7701. expandedTestSpec = expandedTestSpec.substr( 0, pos ) +
  7702. registryKvp.second.tag +
  7703. expandedTestSpec.substr( pos + registryKvp.first.size() );
  7704. }
  7705. }
  7706. return expandedTestSpec;
  7707. }
  7708. void TagAliasRegistry::add( std::string const& alias, std::string const& tag, SourceLineInfo const& lineInfo ) {
  7709. CATCH_ENFORCE( startsWith(alias, "[@") && endsWith(alias, ']'),
  7710. "error: tag alias, '" << alias << "' is not of the form [@alias name].\n" << lineInfo );
  7711. CATCH_ENFORCE( m_registry.insert(std::make_pair(alias, TagAlias(tag, lineInfo))).second,
  7712. "error: tag alias, '" << alias << "' already registered.\n"
  7713. << "\tFirst seen at: " << find(alias)->lineInfo << "\n"
  7714. << "\tRedefined at: " << lineInfo );
  7715. }
  7716. ITagAliasRegistry::~ITagAliasRegistry() {}
  7717. ITagAliasRegistry const& ITagAliasRegistry::get() {
  7718. return getRegistryHub().getTagAliasRegistry();
  7719. }
  7720. } // end namespace Catch
  7721. // end catch_tag_alias_registry.cpp
  7722. // start catch_test_case_info.cpp
  7723. #include <cctype>
  7724. #include <exception>
  7725. #include <algorithm>
  7726. #include <sstream>
  7727. namespace Catch {
  7728. TestCaseInfo::SpecialProperties parseSpecialTag( std::string const& tag ) {
  7729. if( startsWith( tag, '.' ) ||
  7730. tag == "!hide" )
  7731. return TestCaseInfo::IsHidden;
  7732. else if( tag == "!throws" )
  7733. return TestCaseInfo::Throws;
  7734. else if( tag == "!shouldfail" )
  7735. return TestCaseInfo::ShouldFail;
  7736. else if( tag == "!mayfail" )
  7737. return TestCaseInfo::MayFail;
  7738. else if( tag == "!nonportable" )
  7739. return TestCaseInfo::NonPortable;
  7740. else if( tag == "!benchmark" )
  7741. return static_cast<TestCaseInfo::SpecialProperties>( TestCaseInfo::Benchmark | TestCaseInfo::IsHidden );
  7742. else
  7743. return TestCaseInfo::None;
  7744. }
  7745. bool isReservedTag( std::string const& tag ) {
  7746. return parseSpecialTag( tag ) == TestCaseInfo::None && tag.size() > 0 && !std::isalnum( tag[0] );
  7747. }
  7748. void enforceNotReservedTag( std::string const& tag, SourceLineInfo const& _lineInfo ) {
  7749. CATCH_ENFORCE( !isReservedTag(tag),
  7750. "Tag name: [" << tag << "] is not allowed.\n"
  7751. << "Tag names starting with non alpha-numeric characters are reserved\n"
  7752. << _lineInfo );
  7753. }
  7754. TestCase makeTestCase( ITestInvoker* _testCase,
  7755. std::string const& _className,
  7756. std::string const& _name,
  7757. std::string const& _descOrTags,
  7758. SourceLineInfo const& _lineInfo )
  7759. {
  7760. bool isHidden = false;
  7761. // Parse out tags
  7762. std::vector<std::string> tags;
  7763. std::string desc, tag;
  7764. bool inTag = false;
  7765. for (char c : _descOrTags) {
  7766. if( !inTag ) {
  7767. if( c == '[' )
  7768. inTag = true;
  7769. else
  7770. desc += c;
  7771. }
  7772. else {
  7773. if( c == ']' ) {
  7774. TestCaseInfo::SpecialProperties prop = parseSpecialTag( tag );
  7775. if( ( prop & TestCaseInfo::IsHidden ) != 0 )
  7776. isHidden = true;
  7777. else if( prop == TestCaseInfo::None )
  7778. enforceNotReservedTag( tag, _lineInfo );
  7779. tags.push_back( tag );
  7780. tag.clear();
  7781. inTag = false;
  7782. }
  7783. else
  7784. tag += c;
  7785. }
  7786. }
  7787. if( isHidden ) {
  7788. tags.push_back( "." );
  7789. }
  7790. TestCaseInfo info( _name, _className, desc, tags, _lineInfo );
  7791. return TestCase( _testCase, info );
  7792. }
  7793. void setTags( TestCaseInfo& testCaseInfo, std::vector<std::string> tags ) {
  7794. std::sort(begin(tags), end(tags));
  7795. tags.erase(std::unique(begin(tags), end(tags)), end(tags));
  7796. testCaseInfo.lcaseTags.clear();
  7797. for( auto const& tag : tags ) {
  7798. std::string lcaseTag = toLower( tag );
  7799. testCaseInfo.properties = static_cast<TestCaseInfo::SpecialProperties>( testCaseInfo.properties | parseSpecialTag( lcaseTag ) );
  7800. testCaseInfo.lcaseTags.push_back( lcaseTag );
  7801. }
  7802. testCaseInfo.tags = std::move(tags);
  7803. }
  7804. TestCaseInfo::TestCaseInfo( std::string const& _name,
  7805. std::string const& _className,
  7806. std::string const& _description,
  7807. std::vector<std::string> const& _tags,
  7808. SourceLineInfo const& _lineInfo )
  7809. : name( _name ),
  7810. className( _className ),
  7811. description( _description ),
  7812. lineInfo( _lineInfo ),
  7813. properties( None )
  7814. {
  7815. setTags( *this, _tags );
  7816. }
  7817. bool TestCaseInfo::isHidden() const {
  7818. return ( properties & IsHidden ) != 0;
  7819. }
  7820. bool TestCaseInfo::throws() const {
  7821. return ( properties & Throws ) != 0;
  7822. }
  7823. bool TestCaseInfo::okToFail() const {
  7824. return ( properties & (ShouldFail | MayFail ) ) != 0;
  7825. }
  7826. bool TestCaseInfo::expectedToFail() const {
  7827. return ( properties & (ShouldFail ) ) != 0;
  7828. }
  7829. std::string TestCaseInfo::tagsAsString() const {
  7830. std::string ret;
  7831. // '[' and ']' per tag
  7832. std::size_t full_size = 2 * tags.size();
  7833. for (const auto& tag : tags) {
  7834. full_size += tag.size();
  7835. }
  7836. ret.reserve(full_size);
  7837. for (const auto& tag : tags) {
  7838. ret.push_back('[');
  7839. ret.append(tag);
  7840. ret.push_back(']');
  7841. }
  7842. return ret;
  7843. }
  7844. TestCase::TestCase( ITestInvoker* testCase, TestCaseInfo const& info ) : TestCaseInfo( info ), test( testCase ) {}
  7845. TestCase TestCase::withName( std::string const& _newName ) const {
  7846. TestCase other( *this );
  7847. other.name = _newName;
  7848. return other;
  7849. }
  7850. void TestCase::invoke() const {
  7851. test->invoke();
  7852. }
  7853. bool TestCase::operator == ( TestCase const& other ) const {
  7854. return test.get() == other.test.get() &&
  7855. name == other.name &&
  7856. className == other.className;
  7857. }
  7858. bool TestCase::operator < ( TestCase const& other ) const {
  7859. return name < other.name;
  7860. }
  7861. TestCaseInfo const& TestCase::getTestCaseInfo() const
  7862. {
  7863. return *this;
  7864. }
  7865. } // end namespace Catch
  7866. // end catch_test_case_info.cpp
  7867. // start catch_test_case_registry_impl.cpp
  7868. #include <sstream>
  7869. namespace Catch {
  7870. std::vector<TestCase> sortTests( IConfig const& config, std::vector<TestCase> const& unsortedTestCases ) {
  7871. std::vector<TestCase> sorted = unsortedTestCases;
  7872. switch( config.runOrder() ) {
  7873. case RunTests::InLexicographicalOrder:
  7874. std::sort( sorted.begin(), sorted.end() );
  7875. break;
  7876. case RunTests::InRandomOrder:
  7877. seedRng( config );
  7878. RandomNumberGenerator::shuffle( sorted );
  7879. break;
  7880. case RunTests::InDeclarationOrder:
  7881. // already in declaration order
  7882. break;
  7883. }
  7884. return sorted;
  7885. }
  7886. bool matchTest( TestCase const& testCase, TestSpec const& testSpec, IConfig const& config ) {
  7887. return testSpec.matches( testCase ) && ( config.allowThrows() || !testCase.throws() );
  7888. }
  7889. void enforceNoDuplicateTestCases( std::vector<TestCase> const& functions ) {
  7890. std::set<TestCase> seenFunctions;
  7891. for( auto const& function : functions ) {
  7892. auto prev = seenFunctions.insert( function );
  7893. CATCH_ENFORCE( prev.second,
  7894. "error: TEST_CASE( \"" << function.name << "\" ) already defined.\n"
  7895. << "\tFirst seen at " << prev.first->getTestCaseInfo().lineInfo << "\n"
  7896. << "\tRedefined at " << function.getTestCaseInfo().lineInfo );
  7897. }
  7898. }
  7899. std::vector<TestCase> filterTests( std::vector<TestCase> const& testCases, TestSpec const& testSpec, IConfig const& config ) {
  7900. std::vector<TestCase> filtered;
  7901. filtered.reserve( testCases.size() );
  7902. for( auto const& testCase : testCases )
  7903. if( matchTest( testCase, testSpec, config ) )
  7904. filtered.push_back( testCase );
  7905. return filtered;
  7906. }
  7907. std::vector<TestCase> const& getAllTestCasesSorted( IConfig const& config ) {
  7908. return getRegistryHub().getTestCaseRegistry().getAllTestsSorted( config );
  7909. }
  7910. void TestRegistry::registerTest( TestCase const& testCase ) {
  7911. std::string name = testCase.getTestCaseInfo().name;
  7912. if( name.empty() ) {
  7913. ReusableStringStream rss;
  7914. rss << "Anonymous test case " << ++m_unnamedCount;
  7915. return registerTest( testCase.withName( rss.str() ) );
  7916. }
  7917. m_functions.push_back( testCase );
  7918. }
  7919. std::vector<TestCase> const& TestRegistry::getAllTests() const {
  7920. return m_functions;
  7921. }
  7922. std::vector<TestCase> const& TestRegistry::getAllTestsSorted( IConfig const& config ) const {
  7923. if( m_sortedFunctions.empty() )
  7924. enforceNoDuplicateTestCases( m_functions );
  7925. if( m_currentSortOrder != config.runOrder() || m_sortedFunctions.empty() ) {
  7926. m_sortedFunctions = sortTests( config, m_functions );
  7927. m_currentSortOrder = config.runOrder();
  7928. }
  7929. return m_sortedFunctions;
  7930. }
  7931. ///////////////////////////////////////////////////////////////////////////
  7932. TestInvokerAsFunction::TestInvokerAsFunction( void(*testAsFunction)() ) noexcept : m_testAsFunction( testAsFunction ) {}
  7933. void TestInvokerAsFunction::invoke() const {
  7934. m_testAsFunction();
  7935. }
  7936. std::string extractClassName( std::string const& classOrQualifiedMethodName ) {
  7937. std::string className = classOrQualifiedMethodName;
  7938. if( startsWith( className, '&' ) )
  7939. {
  7940. std::size_t lastColons = className.rfind( "::" );
  7941. std::size_t penultimateColons = className.rfind( "::", lastColons-1 );
  7942. if( penultimateColons == std::string::npos )
  7943. penultimateColons = 1;
  7944. className = className.substr( penultimateColons, lastColons-penultimateColons );
  7945. }
  7946. return className;
  7947. }
  7948. } // end namespace Catch
  7949. // end catch_test_case_registry_impl.cpp
  7950. // start catch_test_case_tracker.cpp
  7951. #include <algorithm>
  7952. #include <assert.h>
  7953. #include <stdexcept>
  7954. #include <memory>
  7955. #include <sstream>
  7956. #if defined(__clang__)
  7957. # pragma clang diagnostic push
  7958. # pragma clang diagnostic ignored "-Wexit-time-destructors"
  7959. #endif
  7960. namespace Catch {
  7961. namespace TestCaseTracking {
  7962. NameAndLocation::NameAndLocation( std::string const& _name, SourceLineInfo const& _location )
  7963. : name( _name ),
  7964. location( _location )
  7965. {}
  7966. ITracker::~ITracker() = default;
  7967. TrackerContext& TrackerContext::instance() {
  7968. static TrackerContext s_instance;
  7969. return s_instance;
  7970. }
  7971. ITracker& TrackerContext::startRun() {
  7972. m_rootTracker = std::make_shared<SectionTracker>( NameAndLocation( "{root}", CATCH_INTERNAL_LINEINFO ), *this, nullptr );
  7973. m_currentTracker = nullptr;
  7974. m_runState = Executing;
  7975. return *m_rootTracker;
  7976. }
  7977. void TrackerContext::endRun() {
  7978. m_rootTracker.reset();
  7979. m_currentTracker = nullptr;
  7980. m_runState = NotStarted;
  7981. }
  7982. void TrackerContext::startCycle() {
  7983. m_currentTracker = m_rootTracker.get();
  7984. m_runState = Executing;
  7985. }
  7986. void TrackerContext::completeCycle() {
  7987. m_runState = CompletedCycle;
  7988. }
  7989. bool TrackerContext::completedCycle() const {
  7990. return m_runState == CompletedCycle;
  7991. }
  7992. ITracker& TrackerContext::currentTracker() {
  7993. return *m_currentTracker;
  7994. }
  7995. void TrackerContext::setCurrentTracker( ITracker* tracker ) {
  7996. m_currentTracker = tracker;
  7997. }
  7998. TrackerBase::TrackerHasName::TrackerHasName( NameAndLocation const& nameAndLocation ) : m_nameAndLocation( nameAndLocation ) {}
  7999. bool TrackerBase::TrackerHasName::operator ()( ITrackerPtr const& tracker ) const {
  8000. return
  8001. tracker->nameAndLocation().name == m_nameAndLocation.name &&
  8002. tracker->nameAndLocation().location == m_nameAndLocation.location;
  8003. }
  8004. TrackerBase::TrackerBase( NameAndLocation const& nameAndLocation, TrackerContext& ctx, ITracker* parent )
  8005. : m_nameAndLocation( nameAndLocation ),
  8006. m_ctx( ctx ),
  8007. m_parent( parent )
  8008. {}
  8009. NameAndLocation const& TrackerBase::nameAndLocation() const {
  8010. return m_nameAndLocation;
  8011. }
  8012. bool TrackerBase::isComplete() const {
  8013. return m_runState == CompletedSuccessfully || m_runState == Failed;
  8014. }
  8015. bool TrackerBase::isSuccessfullyCompleted() const {
  8016. return m_runState == CompletedSuccessfully;
  8017. }
  8018. bool TrackerBase::isOpen() const {
  8019. return m_runState != NotStarted && !isComplete();
  8020. }
  8021. bool TrackerBase::hasChildren() const {
  8022. return !m_children.empty();
  8023. }
  8024. void TrackerBase::addChild( ITrackerPtr const& child ) {
  8025. m_children.push_back( child );
  8026. }
  8027. ITrackerPtr TrackerBase::findChild( NameAndLocation const& nameAndLocation ) {
  8028. auto it = std::find_if( m_children.begin(), m_children.end(), TrackerHasName( nameAndLocation ) );
  8029. return( it != m_children.end() )
  8030. ? *it
  8031. : nullptr;
  8032. }
  8033. ITracker& TrackerBase::parent() {
  8034. assert( m_parent ); // Should always be non-null except for root
  8035. return *m_parent;
  8036. }
  8037. void TrackerBase::openChild() {
  8038. if( m_runState != ExecutingChildren ) {
  8039. m_runState = ExecutingChildren;
  8040. if( m_parent )
  8041. m_parent->openChild();
  8042. }
  8043. }
  8044. bool TrackerBase::isSectionTracker() const { return false; }
  8045. bool TrackerBase::isIndexTracker() const { return false; }
  8046. void TrackerBase::open() {
  8047. m_runState = Executing;
  8048. moveToThis();
  8049. if( m_parent )
  8050. m_parent->openChild();
  8051. }
  8052. void TrackerBase::close() {
  8053. // Close any still open children (e.g. generators)
  8054. while( &m_ctx.currentTracker() != this )
  8055. m_ctx.currentTracker().close();
  8056. switch( m_runState ) {
  8057. case NeedsAnotherRun:
  8058. break;
  8059. case Executing:
  8060. m_runState = CompletedSuccessfully;
  8061. break;
  8062. case ExecutingChildren:
  8063. if( m_children.empty() || m_children.back()->isComplete() )
  8064. m_runState = CompletedSuccessfully;
  8065. break;
  8066. case NotStarted:
  8067. case CompletedSuccessfully:
  8068. case Failed:
  8069. CATCH_INTERNAL_ERROR( "Illogical state: " << m_runState );
  8070. default:
  8071. CATCH_INTERNAL_ERROR( "Unknown state: " << m_runState );
  8072. }
  8073. moveToParent();
  8074. m_ctx.completeCycle();
  8075. }
  8076. void TrackerBase::fail() {
  8077. m_runState = Failed;
  8078. if( m_parent )
  8079. m_parent->markAsNeedingAnotherRun();
  8080. moveToParent();
  8081. m_ctx.completeCycle();
  8082. }
  8083. void TrackerBase::markAsNeedingAnotherRun() {
  8084. m_runState = NeedsAnotherRun;
  8085. }
  8086. void TrackerBase::moveToParent() {
  8087. assert( m_parent );
  8088. m_ctx.setCurrentTracker( m_parent );
  8089. }
  8090. void TrackerBase::moveToThis() {
  8091. m_ctx.setCurrentTracker( this );
  8092. }
  8093. SectionTracker::SectionTracker( NameAndLocation const& nameAndLocation, TrackerContext& ctx, ITracker* parent )
  8094. : TrackerBase( nameAndLocation, ctx, parent )
  8095. {
  8096. if( parent ) {
  8097. while( !parent->isSectionTracker() )
  8098. parent = &parent->parent();
  8099. SectionTracker& parentSection = static_cast<SectionTracker&>( *parent );
  8100. addNextFilters( parentSection.m_filters );
  8101. }
  8102. }
  8103. bool SectionTracker::isSectionTracker() const { return true; }
  8104. SectionTracker& SectionTracker::acquire( TrackerContext& ctx, NameAndLocation const& nameAndLocation ) {
  8105. std::shared_ptr<SectionTracker> section;
  8106. ITracker& currentTracker = ctx.currentTracker();
  8107. if( ITrackerPtr childTracker = currentTracker.findChild( nameAndLocation ) ) {
  8108. assert( childTracker );
  8109. assert( childTracker->isSectionTracker() );
  8110. section = std::static_pointer_cast<SectionTracker>( childTracker );
  8111. }
  8112. else {
  8113. section = std::make_shared<SectionTracker>( nameAndLocation, ctx, &currentTracker );
  8114. currentTracker.addChild( section );
  8115. }
  8116. if( !ctx.completedCycle() )
  8117. section->tryOpen();
  8118. return *section;
  8119. }
  8120. void SectionTracker::tryOpen() {
  8121. if( !isComplete() && (m_filters.empty() || m_filters[0].empty() || m_filters[0] == m_nameAndLocation.name ) )
  8122. open();
  8123. }
  8124. void SectionTracker::addInitialFilters( std::vector<std::string> const& filters ) {
  8125. if( !filters.empty() ) {
  8126. m_filters.push_back(""); // Root - should never be consulted
  8127. m_filters.push_back(""); // Test Case - not a section filter
  8128. m_filters.insert( m_filters.end(), filters.begin(), filters.end() );
  8129. }
  8130. }
  8131. void SectionTracker::addNextFilters( std::vector<std::string> const& filters ) {
  8132. if( filters.size() > 1 )
  8133. m_filters.insert( m_filters.end(), ++filters.begin(), filters.end() );
  8134. }
  8135. IndexTracker::IndexTracker( NameAndLocation const& nameAndLocation, TrackerContext& ctx, ITracker* parent, int size )
  8136. : TrackerBase( nameAndLocation, ctx, parent ),
  8137. m_size( size )
  8138. {}
  8139. bool IndexTracker::isIndexTracker() const { return true; }
  8140. IndexTracker& IndexTracker::acquire( TrackerContext& ctx, NameAndLocation const& nameAndLocation, int size ) {
  8141. std::shared_ptr<IndexTracker> tracker;
  8142. ITracker& currentTracker = ctx.currentTracker();
  8143. if( ITrackerPtr childTracker = currentTracker.findChild( nameAndLocation ) ) {
  8144. assert( childTracker );
  8145. assert( childTracker->isIndexTracker() );
  8146. tracker = std::static_pointer_cast<IndexTracker>( childTracker );
  8147. }
  8148. else {
  8149. tracker = std::make_shared<IndexTracker>( nameAndLocation, ctx, &currentTracker, size );
  8150. currentTracker.addChild( tracker );
  8151. }
  8152. if( !ctx.completedCycle() && !tracker->isComplete() ) {
  8153. if( tracker->m_runState != ExecutingChildren && tracker->m_runState != NeedsAnotherRun )
  8154. tracker->moveNext();
  8155. tracker->open();
  8156. }
  8157. return *tracker;
  8158. }
  8159. int IndexTracker::index() const { return m_index; }
  8160. void IndexTracker::moveNext() {
  8161. m_index++;
  8162. m_children.clear();
  8163. }
  8164. void IndexTracker::close() {
  8165. TrackerBase::close();
  8166. if( m_runState == CompletedSuccessfully && m_index < m_size-1 )
  8167. m_runState = Executing;
  8168. }
  8169. } // namespace TestCaseTracking
  8170. using TestCaseTracking::ITracker;
  8171. using TestCaseTracking::TrackerContext;
  8172. using TestCaseTracking::SectionTracker;
  8173. using TestCaseTracking::IndexTracker;
  8174. } // namespace Catch
  8175. #if defined(__clang__)
  8176. # pragma clang diagnostic pop
  8177. #endif
  8178. // end catch_test_case_tracker.cpp
  8179. // start catch_test_registry.cpp
  8180. namespace Catch {
  8181. auto makeTestInvoker( void(*testAsFunction)() ) noexcept -> ITestInvoker* {
  8182. return new(std::nothrow) TestInvokerAsFunction( testAsFunction );
  8183. }
  8184. NameAndTags::NameAndTags( StringRef name_ , StringRef tags_ ) noexcept : name( name_ ), tags( tags_ ) {}
  8185. AutoReg::AutoReg( ITestInvoker* invoker, SourceLineInfo const& lineInfo, StringRef classOrMethod, NameAndTags const& nameAndTags ) noexcept {
  8186. try {
  8187. getMutableRegistryHub()
  8188. .registerTest(
  8189. makeTestCase(
  8190. invoker,
  8191. extractClassName( classOrMethod ),
  8192. nameAndTags.name,
  8193. nameAndTags.tags,
  8194. lineInfo));
  8195. } catch (...) {
  8196. // Do not throw when constructing global objects, instead register the exception to be processed later
  8197. getMutableRegistryHub().registerStartupException();
  8198. }
  8199. }
  8200. AutoReg::~AutoReg() = default;
  8201. }
  8202. // end catch_test_registry.cpp
  8203. // start catch_test_spec.cpp
  8204. #include <algorithm>
  8205. #include <string>
  8206. #include <vector>
  8207. #include <memory>
  8208. namespace Catch {
  8209. TestSpec::Pattern::~Pattern() = default;
  8210. TestSpec::NamePattern::~NamePattern() = default;
  8211. TestSpec::TagPattern::~TagPattern() = default;
  8212. TestSpec::ExcludedPattern::~ExcludedPattern() = default;
  8213. TestSpec::NamePattern::NamePattern( std::string const& name )
  8214. : m_wildcardPattern( toLower( name ), CaseSensitive::No )
  8215. {}
  8216. bool TestSpec::NamePattern::matches( TestCaseInfo const& testCase ) const {
  8217. return m_wildcardPattern.matches( toLower( testCase.name ) );
  8218. }
  8219. TestSpec::TagPattern::TagPattern( std::string const& tag ) : m_tag( toLower( tag ) ) {}
  8220. bool TestSpec::TagPattern::matches( TestCaseInfo const& testCase ) const {
  8221. return std::find(begin(testCase.lcaseTags),
  8222. end(testCase.lcaseTags),
  8223. m_tag) != end(testCase.lcaseTags);
  8224. }
  8225. TestSpec::ExcludedPattern::ExcludedPattern( PatternPtr const& underlyingPattern ) : m_underlyingPattern( underlyingPattern ) {}
  8226. bool TestSpec::ExcludedPattern::matches( TestCaseInfo const& testCase ) const { return !m_underlyingPattern->matches( testCase ); }
  8227. bool TestSpec::Filter::matches( TestCaseInfo const& testCase ) const {
  8228. // All patterns in a filter must match for the filter to be a match
  8229. for( auto const& pattern : m_patterns ) {
  8230. if( !pattern->matches( testCase ) )
  8231. return false;
  8232. }
  8233. return true;
  8234. }
  8235. bool TestSpec::hasFilters() const {
  8236. return !m_filters.empty();
  8237. }
  8238. bool TestSpec::matches( TestCaseInfo const& testCase ) const {
  8239. // A TestSpec matches if any filter matches
  8240. for( auto const& filter : m_filters )
  8241. if( filter.matches( testCase ) )
  8242. return true;
  8243. return false;
  8244. }
  8245. }
  8246. // end catch_test_spec.cpp
  8247. // start catch_test_spec_parser.cpp
  8248. namespace Catch {
  8249. TestSpecParser::TestSpecParser( ITagAliasRegistry const& tagAliases ) : m_tagAliases( &tagAliases ) {}
  8250. TestSpecParser& TestSpecParser::parse( std::string const& arg ) {
  8251. m_mode = None;
  8252. m_exclusion = false;
  8253. m_start = std::string::npos;
  8254. m_arg = m_tagAliases->expandAliases( arg );
  8255. m_escapeChars.clear();
  8256. for( m_pos = 0; m_pos < m_arg.size(); ++m_pos )
  8257. visitChar( m_arg[m_pos] );
  8258. if( m_mode == Name )
  8259. addPattern<TestSpec::NamePattern>();
  8260. return *this;
  8261. }
  8262. TestSpec TestSpecParser::testSpec() {
  8263. addFilter();
  8264. return m_testSpec;
  8265. }
  8266. void TestSpecParser::visitChar( char c ) {
  8267. if( m_mode == None ) {
  8268. switch( c ) {
  8269. case ' ': return;
  8270. case '~': m_exclusion = true; return;
  8271. case '[': return startNewMode( Tag, ++m_pos );
  8272. case '"': return startNewMode( QuotedName, ++m_pos );
  8273. case '\\': return escape();
  8274. default: startNewMode( Name, m_pos ); break;
  8275. }
  8276. }
  8277. if( m_mode == Name ) {
  8278. if( c == ',' ) {
  8279. addPattern<TestSpec::NamePattern>();
  8280. addFilter();
  8281. }
  8282. else if( c == '[' ) {
  8283. if( subString() == "exclude:" )
  8284. m_exclusion = true;
  8285. else
  8286. addPattern<TestSpec::NamePattern>();
  8287. startNewMode( Tag, ++m_pos );
  8288. }
  8289. else if( c == '\\' )
  8290. escape();
  8291. }
  8292. else if( m_mode == EscapedName )
  8293. m_mode = Name;
  8294. else if( m_mode == QuotedName && c == '"' )
  8295. addPattern<TestSpec::NamePattern>();
  8296. else if( m_mode == Tag && c == ']' )
  8297. addPattern<TestSpec::TagPattern>();
  8298. }
  8299. void TestSpecParser::startNewMode( Mode mode, std::size_t start ) {
  8300. m_mode = mode;
  8301. m_start = start;
  8302. }
  8303. void TestSpecParser::escape() {
  8304. if( m_mode == None )
  8305. m_start = m_pos;
  8306. m_mode = EscapedName;
  8307. m_escapeChars.push_back( m_pos );
  8308. }
  8309. std::string TestSpecParser::subString() const { return m_arg.substr( m_start, m_pos - m_start ); }
  8310. void TestSpecParser::addFilter() {
  8311. if( !m_currentFilter.m_patterns.empty() ) {
  8312. m_testSpec.m_filters.push_back( m_currentFilter );
  8313. m_currentFilter = TestSpec::Filter();
  8314. }
  8315. }
  8316. TestSpec parseTestSpec( std::string const& arg ) {
  8317. return TestSpecParser( ITagAliasRegistry::get() ).parse( arg ).testSpec();
  8318. }
  8319. } // namespace Catch
  8320. // end catch_test_spec_parser.cpp
  8321. // start catch_timer.cpp
  8322. #include <chrono>
  8323. namespace Catch {
  8324. auto getCurrentNanosecondsSinceEpoch() -> uint64_t {
  8325. return std::chrono::duration_cast<std::chrono::nanoseconds>( std::chrono::high_resolution_clock::now().time_since_epoch() ).count();
  8326. }
  8327. auto estimateClockResolution() -> uint64_t {
  8328. uint64_t sum = 0;
  8329. static const uint64_t iterations = 1000000;
  8330. for( std::size_t i = 0; i < iterations; ++i ) {
  8331. uint64_t ticks;
  8332. uint64_t baseTicks = getCurrentNanosecondsSinceEpoch();
  8333. do {
  8334. ticks = getCurrentNanosecondsSinceEpoch();
  8335. }
  8336. while( ticks == baseTicks );
  8337. auto delta = ticks - baseTicks;
  8338. sum += delta;
  8339. }
  8340. // We're just taking the mean, here. To do better we could take the std. dev and exclude outliers
  8341. // - and potentially do more iterations if there's a high variance.
  8342. return sum/iterations;
  8343. }
  8344. auto getEstimatedClockResolution() -> uint64_t {
  8345. static auto s_resolution = estimateClockResolution();
  8346. return s_resolution;
  8347. }
  8348. void Timer::start() {
  8349. m_nanoseconds = getCurrentNanosecondsSinceEpoch();
  8350. }
  8351. auto Timer::getElapsedNanoseconds() const -> uint64_t {
  8352. return getCurrentNanosecondsSinceEpoch() - m_nanoseconds;
  8353. }
  8354. auto Timer::getElapsedMicroseconds() const -> uint64_t {
  8355. return getElapsedNanoseconds()/1000;
  8356. }
  8357. auto Timer::getElapsedMilliseconds() const -> unsigned int {
  8358. return static_cast<unsigned int>(getElapsedMicroseconds()/1000);
  8359. }
  8360. auto Timer::getElapsedSeconds() const -> double {
  8361. return getElapsedMicroseconds()/1000000.0;
  8362. }
  8363. } // namespace Catch
  8364. // end catch_timer.cpp
  8365. // start catch_tostring.cpp
  8366. #if defined(__clang__)
  8367. # pragma clang diagnostic push
  8368. # pragma clang diagnostic ignored "-Wexit-time-destructors"
  8369. # pragma clang diagnostic ignored "-Wglobal-constructors"
  8370. #endif
  8371. // Enable specific decls locally
  8372. #if !defined(CATCH_CONFIG_ENABLE_CHRONO_STRINGMAKER)
  8373. #define CATCH_CONFIG_ENABLE_CHRONO_STRINGMAKER
  8374. #endif
  8375. #include <cmath>
  8376. #include <iomanip>
  8377. namespace Catch {
  8378. namespace Detail {
  8379. const std::string unprintableString = "{?}";
  8380. namespace {
  8381. const int hexThreshold = 255;
  8382. struct Endianness {
  8383. enum Arch { Big, Little };
  8384. static Arch which() {
  8385. union _{
  8386. int asInt;
  8387. char asChar[sizeof (int)];
  8388. } u;
  8389. u.asInt = 1;
  8390. return ( u.asChar[sizeof(int)-1] == 1 ) ? Big : Little;
  8391. }
  8392. };
  8393. }
  8394. std::string rawMemoryToString( const void *object, std::size_t size ) {
  8395. // Reverse order for little endian architectures
  8396. int i = 0, end = static_cast<int>( size ), inc = 1;
  8397. if( Endianness::which() == Endianness::Little ) {
  8398. i = end-1;
  8399. end = inc = -1;
  8400. }
  8401. unsigned char const *bytes = static_cast<unsigned char const *>(object);
  8402. ReusableStringStream rss;
  8403. rss << "0x" << std::setfill('0') << std::hex;
  8404. for( ; i != end; i += inc )
  8405. rss << std::setw(2) << static_cast<unsigned>(bytes[i]);
  8406. return rss.str();
  8407. }
  8408. }
  8409. template<typename T>
  8410. std::string fpToString( T value, int precision ) {
  8411. if (std::isnan(value)) {
  8412. return "nan";
  8413. }
  8414. ReusableStringStream rss;
  8415. rss << std::setprecision( precision )
  8416. << std::fixed
  8417. << value;
  8418. std::string d = rss.str();
  8419. std::size_t i = d.find_last_not_of( '0' );
  8420. if( i != std::string::npos && i != d.size()-1 ) {
  8421. if( d[i] == '.' )
  8422. i++;
  8423. d = d.substr( 0, i+1 );
  8424. }
  8425. return d;
  8426. }
  8427. //// ======================================================= ////
  8428. //
  8429. // Out-of-line defs for full specialization of StringMaker
  8430. //
  8431. //// ======================================================= ////
  8432. std::string StringMaker<std::string>::convert(const std::string& str) {
  8433. if (!getCurrentContext().getConfig()->showInvisibles()) {
  8434. return '"' + str + '"';
  8435. }
  8436. std::string s("\"");
  8437. for (char c : str) {
  8438. switch (c) {
  8439. case '\n':
  8440. s.append("\\n");
  8441. break;
  8442. case '\t':
  8443. s.append("\\t");
  8444. break;
  8445. default:
  8446. s.push_back(c);
  8447. break;
  8448. }
  8449. }
  8450. s.append("\"");
  8451. return s;
  8452. }
  8453. std::string StringMaker<std::wstring>::convert(const std::wstring& wstr) {
  8454. std::string s;
  8455. s.reserve(wstr.size());
  8456. for (auto c : wstr) {
  8457. s += (c <= 0xff) ? static_cast<char>(c) : '?';
  8458. }
  8459. return ::Catch::Detail::stringify(s);
  8460. }
  8461. std::string StringMaker<char const*>::convert(char const* str) {
  8462. if (str) {
  8463. return ::Catch::Detail::stringify(std::string{ str });
  8464. } else {
  8465. return{ "{null string}" };
  8466. }
  8467. }
  8468. std::string StringMaker<char*>::convert(char* str) {
  8469. if (str) {
  8470. return ::Catch::Detail::stringify(std::string{ str });
  8471. } else {
  8472. return{ "{null string}" };
  8473. }
  8474. }
  8475. std::string StringMaker<wchar_t const*>::convert(wchar_t const * str) {
  8476. if (str) {
  8477. return ::Catch::Detail::stringify(std::wstring{ str });
  8478. } else {
  8479. return{ "{null string}" };
  8480. }
  8481. }
  8482. std::string StringMaker<wchar_t *>::convert(wchar_t * str) {
  8483. if (str) {
  8484. return ::Catch::Detail::stringify(std::wstring{ str });
  8485. } else {
  8486. return{ "{null string}" };
  8487. }
  8488. }
  8489. std::string StringMaker<int>::convert(int value) {
  8490. return ::Catch::Detail::stringify(static_cast<long long>(value));
  8491. }
  8492. std::string StringMaker<long>::convert(long value) {
  8493. return ::Catch::Detail::stringify(static_cast<long long>(value));
  8494. }
  8495. std::string StringMaker<long long>::convert(long long value) {
  8496. ReusableStringStream rss;
  8497. rss << value;
  8498. if (value > Detail::hexThreshold) {
  8499. rss << " (0x" << std::hex << value << ')';
  8500. }
  8501. return rss.str();
  8502. }
  8503. std::string StringMaker<unsigned int>::convert(unsigned int value) {
  8504. return ::Catch::Detail::stringify(static_cast<unsigned long long>(value));
  8505. }
  8506. std::string StringMaker<unsigned long>::convert(unsigned long value) {
  8507. return ::Catch::Detail::stringify(static_cast<unsigned long long>(value));
  8508. }
  8509. std::string StringMaker<unsigned long long>::convert(unsigned long long value) {
  8510. ReusableStringStream rss;
  8511. rss << value;
  8512. if (value > Detail::hexThreshold) {
  8513. rss << " (0x" << std::hex << value << ')';
  8514. }
  8515. return rss.str();
  8516. }
  8517. std::string StringMaker<bool>::convert(bool b) {
  8518. return b ? "true" : "false";
  8519. }
  8520. std::string StringMaker<char>::convert(char value) {
  8521. if (value == '\r') {
  8522. return "'\\r'";
  8523. } else if (value == '\f') {
  8524. return "'\\f'";
  8525. } else if (value == '\n') {
  8526. return "'\\n'";
  8527. } else if (value == '\t') {
  8528. return "'\\t'";
  8529. } else if ('\0' <= value && value < ' ') {
  8530. return ::Catch::Detail::stringify(static_cast<unsigned int>(value));
  8531. } else {
  8532. char chstr[] = "' '";
  8533. chstr[1] = value;
  8534. return chstr;
  8535. }
  8536. }
  8537. std::string StringMaker<signed char>::convert(signed char c) {
  8538. return ::Catch::Detail::stringify(static_cast<char>(c));
  8539. }
  8540. std::string StringMaker<unsigned char>::convert(unsigned char c) {
  8541. return ::Catch::Detail::stringify(static_cast<char>(c));
  8542. }
  8543. std::string StringMaker<std::nullptr_t>::convert(std::nullptr_t) {
  8544. return "nullptr";
  8545. }
  8546. std::string StringMaker<float>::convert(float value) {
  8547. return fpToString(value, 5) + 'f';
  8548. }
  8549. std::string StringMaker<double>::convert(double value) {
  8550. return fpToString(value, 10);
  8551. }
  8552. std::string ratio_string<std::atto>::symbol() { return "a"; }
  8553. std::string ratio_string<std::femto>::symbol() { return "f"; }
  8554. std::string ratio_string<std::pico>::symbol() { return "p"; }
  8555. std::string ratio_string<std::nano>::symbol() { return "n"; }
  8556. std::string ratio_string<std::micro>::symbol() { return "u"; }
  8557. std::string ratio_string<std::milli>::symbol() { return "m"; }
  8558. } // end namespace Catch
  8559. #if defined(__clang__)
  8560. # pragma clang diagnostic pop
  8561. #endif
  8562. // end catch_tostring.cpp
  8563. // start catch_totals.cpp
  8564. namespace Catch {
  8565. Counts Counts::operator - ( Counts const& other ) const {
  8566. Counts diff;
  8567. diff.passed = passed - other.passed;
  8568. diff.failed = failed - other.failed;
  8569. diff.failedButOk = failedButOk - other.failedButOk;
  8570. return diff;
  8571. }
  8572. Counts& Counts::operator += ( Counts const& other ) {
  8573. passed += other.passed;
  8574. failed += other.failed;
  8575. failedButOk += other.failedButOk;
  8576. return *this;
  8577. }
  8578. std::size_t Counts::total() const {
  8579. return passed + failed + failedButOk;
  8580. }
  8581. bool Counts::allPassed() const {
  8582. return failed == 0 && failedButOk == 0;
  8583. }
  8584. bool Counts::allOk() const {
  8585. return failed == 0;
  8586. }
  8587. Totals Totals::operator - ( Totals const& other ) const {
  8588. Totals diff;
  8589. diff.assertions = assertions - other.assertions;
  8590. diff.testCases = testCases - other.testCases;
  8591. return diff;
  8592. }
  8593. Totals& Totals::operator += ( Totals const& other ) {
  8594. assertions += other.assertions;
  8595. testCases += other.testCases;
  8596. return *this;
  8597. }
  8598. Totals Totals::delta( Totals const& prevTotals ) const {
  8599. Totals diff = *this - prevTotals;
  8600. if( diff.assertions.failed > 0 )
  8601. ++diff.testCases.failed;
  8602. else if( diff.assertions.failedButOk > 0 )
  8603. ++diff.testCases.failedButOk;
  8604. else
  8605. ++diff.testCases.passed;
  8606. return diff;
  8607. }
  8608. }
  8609. // end catch_totals.cpp
  8610. // start catch_version.cpp
  8611. #include <ostream>
  8612. namespace Catch {
  8613. Version::Version
  8614. ( unsigned int _majorVersion,
  8615. unsigned int _minorVersion,
  8616. unsigned int _patchNumber,
  8617. char const * const _branchName,
  8618. unsigned int _buildNumber )
  8619. : majorVersion( _majorVersion ),
  8620. minorVersion( _minorVersion ),
  8621. patchNumber( _patchNumber ),
  8622. branchName( _branchName ),
  8623. buildNumber( _buildNumber )
  8624. {}
  8625. std::ostream& operator << ( std::ostream& os, Version const& version ) {
  8626. os << version.majorVersion << '.'
  8627. << version.minorVersion << '.'
  8628. << version.patchNumber;
  8629. // branchName is never null -> 0th char is \0 if it is empty
  8630. if (version.branchName[0]) {
  8631. os << '-' << version.branchName
  8632. << '.' << version.buildNumber;
  8633. }
  8634. return os;
  8635. }
  8636. Version const& libraryVersion() {
  8637. static Version version( 2, 1, 1, "", 0 );
  8638. return version;
  8639. }
  8640. }
  8641. // end catch_version.cpp
  8642. // start catch_wildcard_pattern.cpp
  8643. #include <sstream>
  8644. namespace Catch {
  8645. WildcardPattern::WildcardPattern( std::string const& pattern,
  8646. CaseSensitive::Choice caseSensitivity )
  8647. : m_caseSensitivity( caseSensitivity ),
  8648. m_pattern( adjustCase( pattern ) )
  8649. {
  8650. if( startsWith( m_pattern, '*' ) ) {
  8651. m_pattern = m_pattern.substr( 1 );
  8652. m_wildcard = WildcardAtStart;
  8653. }
  8654. if( endsWith( m_pattern, '*' ) ) {
  8655. m_pattern = m_pattern.substr( 0, m_pattern.size()-1 );
  8656. m_wildcard = static_cast<WildcardPosition>( m_wildcard | WildcardAtEnd );
  8657. }
  8658. }
  8659. bool WildcardPattern::matches( std::string const& str ) const {
  8660. switch( m_wildcard ) {
  8661. case NoWildcard:
  8662. return m_pattern == adjustCase( str );
  8663. case WildcardAtStart:
  8664. return endsWith( adjustCase( str ), m_pattern );
  8665. case WildcardAtEnd:
  8666. return startsWith( adjustCase( str ), m_pattern );
  8667. case WildcardAtBothEnds:
  8668. return contains( adjustCase( str ), m_pattern );
  8669. default:
  8670. CATCH_INTERNAL_ERROR( "Unknown enum" );
  8671. }
  8672. }
  8673. std::string WildcardPattern::adjustCase( std::string const& str ) const {
  8674. return m_caseSensitivity == CaseSensitive::No ? toLower( str ) : str;
  8675. }
  8676. }
  8677. // end catch_wildcard_pattern.cpp
  8678. // start catch_xmlwriter.cpp
  8679. #include <iomanip>
  8680. namespace Catch {
  8681. XmlEncode::XmlEncode( std::string const& str, ForWhat forWhat )
  8682. : m_str( str ),
  8683. m_forWhat( forWhat )
  8684. {}
  8685. void XmlEncode::encodeTo( std::ostream& os ) const {
  8686. // Apostrophe escaping not necessary if we always use " to write attributes
  8687. // (see: http://www.w3.org/TR/xml/#syntax)
  8688. for( std::size_t i = 0; i < m_str.size(); ++ i ) {
  8689. char c = m_str[i];
  8690. switch( c ) {
  8691. case '<': os << "&lt;"; break;
  8692. case '&': os << "&amp;"; break;
  8693. case '>':
  8694. // See: http://www.w3.org/TR/xml/#syntax
  8695. if( i > 2 && m_str[i-1] == ']' && m_str[i-2] == ']' )
  8696. os << "&gt;";
  8697. else
  8698. os << c;
  8699. break;
  8700. case '\"':
  8701. if( m_forWhat == ForAttributes )
  8702. os << "&quot;";
  8703. else
  8704. os << c;
  8705. break;
  8706. default:
  8707. // Escape control chars - based on contribution by @espenalb in PR #465 and
  8708. // by @mrpi PR #588
  8709. if ( ( c >= 0 && c < '\x09' ) || ( c > '\x0D' && c < '\x20') || c=='\x7F' ) {
  8710. // see http://stackoverflow.com/questions/404107/why-are-control-characters-illegal-in-xml-1-0
  8711. os << "\\x" << std::uppercase << std::hex << std::setfill('0') << std::setw(2)
  8712. << static_cast<int>( c );
  8713. }
  8714. else
  8715. os << c;
  8716. }
  8717. }
  8718. }
  8719. std::ostream& operator << ( std::ostream& os, XmlEncode const& xmlEncode ) {
  8720. xmlEncode.encodeTo( os );
  8721. return os;
  8722. }
  8723. XmlWriter::ScopedElement::ScopedElement( XmlWriter* writer )
  8724. : m_writer( writer )
  8725. {}
  8726. XmlWriter::ScopedElement::ScopedElement( ScopedElement&& other ) noexcept
  8727. : m_writer( other.m_writer ){
  8728. other.m_writer = nullptr;
  8729. }
  8730. XmlWriter::ScopedElement& XmlWriter::ScopedElement::operator=( ScopedElement&& other ) noexcept {
  8731. if ( m_writer ) {
  8732. m_writer->endElement();
  8733. }
  8734. m_writer = other.m_writer;
  8735. other.m_writer = nullptr;
  8736. return *this;
  8737. }
  8738. XmlWriter::ScopedElement::~ScopedElement() {
  8739. if( m_writer )
  8740. m_writer->endElement();
  8741. }
  8742. XmlWriter::ScopedElement& XmlWriter::ScopedElement::writeText( std::string const& text, bool indent ) {
  8743. m_writer->writeText( text, indent );
  8744. return *this;
  8745. }
  8746. XmlWriter::XmlWriter( std::ostream& os ) : m_os( os )
  8747. {
  8748. writeDeclaration();
  8749. }
  8750. XmlWriter::~XmlWriter() {
  8751. while( !m_tags.empty() )
  8752. endElement();
  8753. }
  8754. XmlWriter& XmlWriter::startElement( std::string const& name ) {
  8755. ensureTagClosed();
  8756. newlineIfNecessary();
  8757. m_os << m_indent << '<' << name;
  8758. m_tags.push_back( name );
  8759. m_indent += " ";
  8760. m_tagIsOpen = true;
  8761. return *this;
  8762. }
  8763. XmlWriter::ScopedElement XmlWriter::scopedElement( std::string const& name ) {
  8764. ScopedElement scoped( this );
  8765. startElement( name );
  8766. return scoped;
  8767. }
  8768. XmlWriter& XmlWriter::endElement() {
  8769. newlineIfNecessary();
  8770. m_indent = m_indent.substr( 0, m_indent.size()-2 );
  8771. if( m_tagIsOpen ) {
  8772. m_os << "/>";
  8773. m_tagIsOpen = false;
  8774. }
  8775. else {
  8776. m_os << m_indent << "</" << m_tags.back() << ">";
  8777. }
  8778. m_os << std::endl;
  8779. m_tags.pop_back();
  8780. return *this;
  8781. }
  8782. XmlWriter& XmlWriter::writeAttribute( std::string const& name, std::string const& attribute ) {
  8783. if( !name.empty() && !attribute.empty() )
  8784. m_os << ' ' << name << "=\"" << XmlEncode( attribute, XmlEncode::ForAttributes ) << '"';
  8785. return *this;
  8786. }
  8787. XmlWriter& XmlWriter::writeAttribute( std::string const& name, bool attribute ) {
  8788. m_os << ' ' << name << "=\"" << ( attribute ? "true" : "false" ) << '"';
  8789. return *this;
  8790. }
  8791. XmlWriter& XmlWriter::writeText( std::string const& text, bool indent ) {
  8792. if( !text.empty() ){
  8793. bool tagWasOpen = m_tagIsOpen;
  8794. ensureTagClosed();
  8795. if( tagWasOpen && indent )
  8796. m_os << m_indent;
  8797. m_os << XmlEncode( text );
  8798. m_needsNewline = true;
  8799. }
  8800. return *this;
  8801. }
  8802. XmlWriter& XmlWriter::writeComment( std::string const& text ) {
  8803. ensureTagClosed();
  8804. m_os << m_indent << "<!--" << text << "-->";
  8805. m_needsNewline = true;
  8806. return *this;
  8807. }
  8808. void XmlWriter::writeStylesheetRef( std::string const& url ) {
  8809. m_os << "<?xml-stylesheet type=\"text/xsl\" href=\"" << url << "\"?>\n";
  8810. }
  8811. XmlWriter& XmlWriter::writeBlankLine() {
  8812. ensureTagClosed();
  8813. m_os << '\n';
  8814. return *this;
  8815. }
  8816. void XmlWriter::ensureTagClosed() {
  8817. if( m_tagIsOpen ) {
  8818. m_os << ">" << std::endl;
  8819. m_tagIsOpen = false;
  8820. }
  8821. }
  8822. void XmlWriter::writeDeclaration() {
  8823. m_os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
  8824. }
  8825. void XmlWriter::newlineIfNecessary() {
  8826. if( m_needsNewline ) {
  8827. m_os << std::endl;
  8828. m_needsNewline = false;
  8829. }
  8830. }
  8831. }
  8832. // end catch_xmlwriter.cpp
  8833. // start catch_reporter_bases.cpp
  8834. #include <cstring>
  8835. #include <cfloat>
  8836. #include <cstdio>
  8837. #include <assert.h>
  8838. #include <memory>
  8839. namespace Catch {
  8840. void prepareExpandedExpression(AssertionResult& result) {
  8841. result.getExpandedExpression();
  8842. }
  8843. // Because formatting using c++ streams is stateful, drop down to C is required
  8844. // Alternatively we could use stringstream, but its performance is... not good.
  8845. std::string getFormattedDuration( double duration ) {
  8846. // Max exponent + 1 is required to represent the whole part
  8847. // + 1 for decimal point
  8848. // + 3 for the 3 decimal places
  8849. // + 1 for null terminator
  8850. const std::size_t maxDoubleSize = DBL_MAX_10_EXP + 1 + 1 + 3 + 1;
  8851. char buffer[maxDoubleSize];
  8852. // Save previous errno, to prevent sprintf from overwriting it
  8853. ErrnoGuard guard;
  8854. #ifdef _MSC_VER
  8855. sprintf_s(buffer, "%.3f", duration);
  8856. #else
  8857. sprintf(buffer, "%.3f", duration);
  8858. #endif
  8859. return std::string(buffer);
  8860. }
  8861. TestEventListenerBase::TestEventListenerBase(ReporterConfig const & _config)
  8862. :StreamingReporterBase(_config) {}
  8863. void TestEventListenerBase::assertionStarting(AssertionInfo const &) {}
  8864. bool TestEventListenerBase::assertionEnded(AssertionStats const &) {
  8865. return false;
  8866. }
  8867. } // end namespace Catch
  8868. // end catch_reporter_bases.cpp
  8869. // start catch_reporter_compact.cpp
  8870. namespace {
  8871. #ifdef CATCH_PLATFORM_MAC
  8872. const char* failedString() { return "FAILED"; }
  8873. const char* passedString() { return "PASSED"; }
  8874. #else
  8875. const char* failedString() { return "failed"; }
  8876. const char* passedString() { return "passed"; }
  8877. #endif
  8878. // Colour::LightGrey
  8879. Catch::Colour::Code dimColour() { return Catch::Colour::FileName; }
  8880. std::string bothOrAll( std::size_t count ) {
  8881. return count == 1 ? std::string() :
  8882. count == 2 ? "both " : "all " ;
  8883. }
  8884. } // anon namespace
  8885. namespace Catch {
  8886. namespace {
  8887. // Colour, message variants:
  8888. // - white: No tests ran.
  8889. // - red: Failed [both/all] N test cases, failed [both/all] M assertions.
  8890. // - white: Passed [both/all] N test cases (no assertions).
  8891. // - red: Failed N tests cases, failed M assertions.
  8892. // - green: Passed [both/all] N tests cases with M assertions.
  8893. void printTotals(std::ostream& out, const Totals& totals) {
  8894. if (totals.testCases.total() == 0) {
  8895. out << "No tests ran.";
  8896. } else if (totals.testCases.failed == totals.testCases.total()) {
  8897. Colour colour(Colour::ResultError);
  8898. const std::string qualify_assertions_failed =
  8899. totals.assertions.failed == totals.assertions.total() ?
  8900. bothOrAll(totals.assertions.failed) : std::string();
  8901. out <<
  8902. "Failed " << bothOrAll(totals.testCases.failed)
  8903. << pluralise(totals.testCases.failed, "test case") << ", "
  8904. "failed " << qualify_assertions_failed <<
  8905. pluralise(totals.assertions.failed, "assertion") << '.';
  8906. } else if (totals.assertions.total() == 0) {
  8907. out <<
  8908. "Passed " << bothOrAll(totals.testCases.total())
  8909. << pluralise(totals.testCases.total(), "test case")
  8910. << " (no assertions).";
  8911. } else if (totals.assertions.failed) {
  8912. Colour colour(Colour::ResultError);
  8913. out <<
  8914. "Failed " << pluralise(totals.testCases.failed, "test case") << ", "
  8915. "failed " << pluralise(totals.assertions.failed, "assertion") << '.';
  8916. } else {
  8917. Colour colour(Colour::ResultSuccess);
  8918. out <<
  8919. "Passed " << bothOrAll(totals.testCases.passed)
  8920. << pluralise(totals.testCases.passed, "test case") <<
  8921. " with " << pluralise(totals.assertions.passed, "assertion") << '.';
  8922. }
  8923. }
  8924. // Implementation of CompactReporter formatting
  8925. class AssertionPrinter {
  8926. public:
  8927. AssertionPrinter& operator= (AssertionPrinter const&) = delete;
  8928. AssertionPrinter(AssertionPrinter const&) = delete;
  8929. AssertionPrinter(std::ostream& _stream, AssertionStats const& _stats, bool _printInfoMessages)
  8930. : stream(_stream)
  8931. , result(_stats.assertionResult)
  8932. , messages(_stats.infoMessages)
  8933. , itMessage(_stats.infoMessages.begin())
  8934. , printInfoMessages(_printInfoMessages) {}
  8935. void print() {
  8936. printSourceInfo();
  8937. itMessage = messages.begin();
  8938. switch (result.getResultType()) {
  8939. case ResultWas::Ok:
  8940. printResultType(Colour::ResultSuccess, passedString());
  8941. printOriginalExpression();
  8942. printReconstructedExpression();
  8943. if (!result.hasExpression())
  8944. printRemainingMessages(Colour::None);
  8945. else
  8946. printRemainingMessages();
  8947. break;
  8948. case ResultWas::ExpressionFailed:
  8949. if (result.isOk())
  8950. printResultType(Colour::ResultSuccess, failedString() + std::string(" - but was ok"));
  8951. else
  8952. printResultType(Colour::Error, failedString());
  8953. printOriginalExpression();
  8954. printReconstructedExpression();
  8955. printRemainingMessages();
  8956. break;
  8957. case ResultWas::ThrewException:
  8958. printResultType(Colour::Error, failedString());
  8959. printIssue("unexpected exception with message:");
  8960. printMessage();
  8961. printExpressionWas();
  8962. printRemainingMessages();
  8963. break;
  8964. case ResultWas::FatalErrorCondition:
  8965. printResultType(Colour::Error, failedString());
  8966. printIssue("fatal error condition with message:");
  8967. printMessage();
  8968. printExpressionWas();
  8969. printRemainingMessages();
  8970. break;
  8971. case ResultWas::DidntThrowException:
  8972. printResultType(Colour::Error, failedString());
  8973. printIssue("expected exception, got none");
  8974. printExpressionWas();
  8975. printRemainingMessages();
  8976. break;
  8977. case ResultWas::Info:
  8978. printResultType(Colour::None, "info");
  8979. printMessage();
  8980. printRemainingMessages();
  8981. break;
  8982. case ResultWas::Warning:
  8983. printResultType(Colour::None, "warning");
  8984. printMessage();
  8985. printRemainingMessages();
  8986. break;
  8987. case ResultWas::ExplicitFailure:
  8988. printResultType(Colour::Error, failedString());
  8989. printIssue("explicitly");
  8990. printRemainingMessages(Colour::None);
  8991. break;
  8992. // These cases are here to prevent compiler warnings
  8993. case ResultWas::Unknown:
  8994. case ResultWas::FailureBit:
  8995. case ResultWas::Exception:
  8996. printResultType(Colour::Error, "** internal error **");
  8997. break;
  8998. }
  8999. }
  9000. private:
  9001. void printSourceInfo() const {
  9002. Colour colourGuard(Colour::FileName);
  9003. stream << result.getSourceInfo() << ':';
  9004. }
  9005. void printResultType(Colour::Code colour, std::string const& passOrFail) const {
  9006. if (!passOrFail.empty()) {
  9007. {
  9008. Colour colourGuard(colour);
  9009. stream << ' ' << passOrFail;
  9010. }
  9011. stream << ':';
  9012. }
  9013. }
  9014. void printIssue(std::string const& issue) const {
  9015. stream << ' ' << issue;
  9016. }
  9017. void printExpressionWas() {
  9018. if (result.hasExpression()) {
  9019. stream << ';';
  9020. {
  9021. Colour colour(dimColour());
  9022. stream << " expression was:";
  9023. }
  9024. printOriginalExpression();
  9025. }
  9026. }
  9027. void printOriginalExpression() const {
  9028. if (result.hasExpression()) {
  9029. stream << ' ' << result.getExpression();
  9030. }
  9031. }
  9032. void printReconstructedExpression() const {
  9033. if (result.hasExpandedExpression()) {
  9034. {
  9035. Colour colour(dimColour());
  9036. stream << " for: ";
  9037. }
  9038. stream << result.getExpandedExpression();
  9039. }
  9040. }
  9041. void printMessage() {
  9042. if (itMessage != messages.end()) {
  9043. stream << " '" << itMessage->message << '\'';
  9044. ++itMessage;
  9045. }
  9046. }
  9047. void printRemainingMessages(Colour::Code colour = dimColour()) {
  9048. if (itMessage == messages.end())
  9049. return;
  9050. // using messages.end() directly yields (or auto) compilation error:
  9051. std::vector<MessageInfo>::const_iterator itEnd = messages.end();
  9052. const std::size_t N = static_cast<std::size_t>(std::distance(itMessage, itEnd));
  9053. {
  9054. Colour colourGuard(colour);
  9055. stream << " with " << pluralise(N, "message") << ':';
  9056. }
  9057. for (; itMessage != itEnd; ) {
  9058. // If this assertion is a warning ignore any INFO messages
  9059. if (printInfoMessages || itMessage->type != ResultWas::Info) {
  9060. stream << " '" << itMessage->message << '\'';
  9061. if (++itMessage != itEnd) {
  9062. Colour colourGuard(dimColour());
  9063. stream << " and";
  9064. }
  9065. }
  9066. }
  9067. }
  9068. private:
  9069. std::ostream& stream;
  9070. AssertionResult const& result;
  9071. std::vector<MessageInfo> messages;
  9072. std::vector<MessageInfo>::const_iterator itMessage;
  9073. bool printInfoMessages;
  9074. };
  9075. } // anon namespace
  9076. std::string CompactReporter::getDescription() {
  9077. return "Reports test results on a single line, suitable for IDEs";
  9078. }
  9079. ReporterPreferences CompactReporter::getPreferences() const {
  9080. ReporterPreferences prefs;
  9081. prefs.shouldRedirectStdOut = false;
  9082. return prefs;
  9083. }
  9084. void CompactReporter::noMatchingTestCases( std::string const& spec ) {
  9085. stream << "No test cases matched '" << spec << '\'' << std::endl;
  9086. }
  9087. void CompactReporter::assertionStarting( AssertionInfo const& ) {}
  9088. bool CompactReporter::assertionEnded( AssertionStats const& _assertionStats ) {
  9089. AssertionResult const& result = _assertionStats.assertionResult;
  9090. bool printInfoMessages = true;
  9091. // Drop out if result was successful and we're not printing those
  9092. if( !m_config->includeSuccessfulResults() && result.isOk() ) {
  9093. if( result.getResultType() != ResultWas::Warning )
  9094. return false;
  9095. printInfoMessages = false;
  9096. }
  9097. AssertionPrinter printer( stream, _assertionStats, printInfoMessages );
  9098. printer.print();
  9099. stream << std::endl;
  9100. return true;
  9101. }
  9102. void CompactReporter::sectionEnded(SectionStats const& _sectionStats) {
  9103. if (m_config->showDurations() == ShowDurations::Always) {
  9104. stream << getFormattedDuration(_sectionStats.durationInSeconds) << " s: " << _sectionStats.sectionInfo.name << std::endl;
  9105. }
  9106. }
  9107. void CompactReporter::testRunEnded( TestRunStats const& _testRunStats ) {
  9108. printTotals( stream, _testRunStats.totals );
  9109. stream << '\n' << std::endl;
  9110. StreamingReporterBase::testRunEnded( _testRunStats );
  9111. }
  9112. CompactReporter::~CompactReporter() {}
  9113. CATCH_REGISTER_REPORTER( "compact", CompactReporter )
  9114. } // end namespace Catch
  9115. // end catch_reporter_compact.cpp
  9116. // start catch_reporter_console.cpp
  9117. #include <cfloat>
  9118. #include <cstdio>
  9119. #if defined(_MSC_VER)
  9120. #pragma warning(push)
  9121. #pragma warning(disable:4061) // Not all labels are EXPLICITLY handled in switch
  9122. // Note that 4062 (not all labels are handled
  9123. // and default is missing) is enabled
  9124. #endif
  9125. namespace Catch {
  9126. namespace {
  9127. // Formatter impl for ConsoleReporter
  9128. class ConsoleAssertionPrinter {
  9129. public:
  9130. ConsoleAssertionPrinter& operator= (ConsoleAssertionPrinter const&) = delete;
  9131. ConsoleAssertionPrinter(ConsoleAssertionPrinter const&) = delete;
  9132. ConsoleAssertionPrinter(std::ostream& _stream, AssertionStats const& _stats, bool _printInfoMessages)
  9133. : stream(_stream),
  9134. stats(_stats),
  9135. result(_stats.assertionResult),
  9136. colour(Colour::None),
  9137. message(result.getMessage()),
  9138. messages(_stats.infoMessages),
  9139. printInfoMessages(_printInfoMessages) {
  9140. switch (result.getResultType()) {
  9141. case ResultWas::Ok:
  9142. colour = Colour::Success;
  9143. passOrFail = "PASSED";
  9144. //if( result.hasMessage() )
  9145. if (_stats.infoMessages.size() == 1)
  9146. messageLabel = "with message";
  9147. if (_stats.infoMessages.size() > 1)
  9148. messageLabel = "with messages";
  9149. break;
  9150. case ResultWas::ExpressionFailed:
  9151. if (result.isOk()) {
  9152. colour = Colour::Success;
  9153. passOrFail = "FAILED - but was ok";
  9154. } else {
  9155. colour = Colour::Error;
  9156. passOrFail = "FAILED";
  9157. }
  9158. if (_stats.infoMessages.size() == 1)
  9159. messageLabel = "with message";
  9160. if (_stats.infoMessages.size() > 1)
  9161. messageLabel = "with messages";
  9162. break;
  9163. case ResultWas::ThrewException:
  9164. colour = Colour::Error;
  9165. passOrFail = "FAILED";
  9166. messageLabel = "due to unexpected exception with ";
  9167. if (_stats.infoMessages.size() == 1)
  9168. messageLabel += "message";
  9169. if (_stats.infoMessages.size() > 1)
  9170. messageLabel += "messages";
  9171. break;
  9172. case ResultWas::FatalErrorCondition:
  9173. colour = Colour::Error;
  9174. passOrFail = "FAILED";
  9175. messageLabel = "due to a fatal error condition";
  9176. break;
  9177. case ResultWas::DidntThrowException:
  9178. colour = Colour::Error;
  9179. passOrFail = "FAILED";
  9180. messageLabel = "because no exception was thrown where one was expected";
  9181. break;
  9182. case ResultWas::Info:
  9183. messageLabel = "info";
  9184. break;
  9185. case ResultWas::Warning:
  9186. messageLabel = "warning";
  9187. break;
  9188. case ResultWas::ExplicitFailure:
  9189. passOrFail = "FAILED";
  9190. colour = Colour::Error;
  9191. if (_stats.infoMessages.size() == 1)
  9192. messageLabel = "explicitly with message";
  9193. if (_stats.infoMessages.size() > 1)
  9194. messageLabel = "explicitly with messages";
  9195. break;
  9196. // These cases are here to prevent compiler warnings
  9197. case ResultWas::Unknown:
  9198. case ResultWas::FailureBit:
  9199. case ResultWas::Exception:
  9200. passOrFail = "** internal error **";
  9201. colour = Colour::Error;
  9202. break;
  9203. }
  9204. }
  9205. void print() const {
  9206. printSourceInfo();
  9207. if (stats.totals.assertions.total() > 0) {
  9208. if (result.isOk())
  9209. stream << '\n';
  9210. printResultType();
  9211. printOriginalExpression();
  9212. printReconstructedExpression();
  9213. } else {
  9214. stream << '\n';
  9215. }
  9216. printMessage();
  9217. }
  9218. private:
  9219. void printResultType() const {
  9220. if (!passOrFail.empty()) {
  9221. Colour colourGuard(colour);
  9222. stream << passOrFail << ":\n";
  9223. }
  9224. }
  9225. void printOriginalExpression() const {
  9226. if (result.hasExpression()) {
  9227. Colour colourGuard(Colour::OriginalExpression);
  9228. stream << " ";
  9229. stream << result.getExpressionInMacro();
  9230. stream << '\n';
  9231. }
  9232. }
  9233. void printReconstructedExpression() const {
  9234. if (result.hasExpandedExpression()) {
  9235. stream << "with expansion:\n";
  9236. Colour colourGuard(Colour::ReconstructedExpression);
  9237. stream << Column(result.getExpandedExpression()).indent(2) << '\n';
  9238. }
  9239. }
  9240. void printMessage() const {
  9241. if (!messageLabel.empty())
  9242. stream << messageLabel << ':' << '\n';
  9243. for (auto const& msg : messages) {
  9244. // If this assertion is a warning ignore any INFO messages
  9245. if (printInfoMessages || msg.type != ResultWas::Info)
  9246. stream << Column(msg.message).indent(2) << '\n';
  9247. }
  9248. }
  9249. void printSourceInfo() const {
  9250. Colour colourGuard(Colour::FileName);
  9251. stream << result.getSourceInfo() << ": ";
  9252. }
  9253. std::ostream& stream;
  9254. AssertionStats const& stats;
  9255. AssertionResult const& result;
  9256. Colour::Code colour;
  9257. std::string passOrFail;
  9258. std::string messageLabel;
  9259. std::string message;
  9260. std::vector<MessageInfo> messages;
  9261. bool printInfoMessages;
  9262. };
  9263. std::size_t makeRatio(std::size_t number, std::size_t total) {
  9264. std::size_t ratio = total > 0 ? CATCH_CONFIG_CONSOLE_WIDTH * number / total : 0;
  9265. return (ratio == 0 && number > 0) ? 1 : ratio;
  9266. }
  9267. std::size_t& findMax(std::size_t& i, std::size_t& j, std::size_t& k) {
  9268. if (i > j && i > k)
  9269. return i;
  9270. else if (j > k)
  9271. return j;
  9272. else
  9273. return k;
  9274. }
  9275. struct ColumnInfo {
  9276. enum Justification { Left, Right };
  9277. std::string name;
  9278. int width;
  9279. Justification justification;
  9280. };
  9281. struct ColumnBreak {};
  9282. struct RowBreak {};
  9283. class Duration {
  9284. enum class Unit {
  9285. Auto,
  9286. Nanoseconds,
  9287. Microseconds,
  9288. Milliseconds,
  9289. Seconds,
  9290. Minutes
  9291. };
  9292. static const uint64_t s_nanosecondsInAMicrosecond = 1000;
  9293. static const uint64_t s_nanosecondsInAMillisecond = 1000 * s_nanosecondsInAMicrosecond;
  9294. static const uint64_t s_nanosecondsInASecond = 1000 * s_nanosecondsInAMillisecond;
  9295. static const uint64_t s_nanosecondsInAMinute = 60 * s_nanosecondsInASecond;
  9296. uint64_t m_inNanoseconds;
  9297. Unit m_units;
  9298. public:
  9299. explicit Duration(uint64_t inNanoseconds, Unit units = Unit::Auto)
  9300. : m_inNanoseconds(inNanoseconds),
  9301. m_units(units) {
  9302. if (m_units == Unit::Auto) {
  9303. if (m_inNanoseconds < s_nanosecondsInAMicrosecond)
  9304. m_units = Unit::Nanoseconds;
  9305. else if (m_inNanoseconds < s_nanosecondsInAMillisecond)
  9306. m_units = Unit::Microseconds;
  9307. else if (m_inNanoseconds < s_nanosecondsInASecond)
  9308. m_units = Unit::Milliseconds;
  9309. else if (m_inNanoseconds < s_nanosecondsInAMinute)
  9310. m_units = Unit::Seconds;
  9311. else
  9312. m_units = Unit::Minutes;
  9313. }
  9314. }
  9315. auto value() const -> double {
  9316. switch (m_units) {
  9317. case Unit::Microseconds:
  9318. return m_inNanoseconds / static_cast<double>(s_nanosecondsInAMicrosecond);
  9319. case Unit::Milliseconds:
  9320. return m_inNanoseconds / static_cast<double>(s_nanosecondsInAMillisecond);
  9321. case Unit::Seconds:
  9322. return m_inNanoseconds / static_cast<double>(s_nanosecondsInASecond);
  9323. case Unit::Minutes:
  9324. return m_inNanoseconds / static_cast<double>(s_nanosecondsInAMinute);
  9325. default:
  9326. return static_cast<double>(m_inNanoseconds);
  9327. }
  9328. }
  9329. auto unitsAsString() const -> std::string {
  9330. switch (m_units) {
  9331. case Unit::Nanoseconds:
  9332. return "ns";
  9333. case Unit::Microseconds:
  9334. return "µs";
  9335. case Unit::Milliseconds:
  9336. return "ms";
  9337. case Unit::Seconds:
  9338. return "s";
  9339. case Unit::Minutes:
  9340. return "m";
  9341. default:
  9342. return "** internal error **";
  9343. }
  9344. }
  9345. friend auto operator << (std::ostream& os, Duration const& duration) -> std::ostream& {
  9346. return os << duration.value() << " " << duration.unitsAsString();
  9347. }
  9348. };
  9349. } // end anon namespace
  9350. class TablePrinter {
  9351. std::ostream& m_os;
  9352. std::vector<ColumnInfo> m_columnInfos;
  9353. std::ostringstream m_oss;
  9354. int m_currentColumn = -1;
  9355. bool m_isOpen = false;
  9356. public:
  9357. TablePrinter( std::ostream& os, std::vector<ColumnInfo> columnInfos )
  9358. : m_os( os ),
  9359. m_columnInfos( std::move( columnInfos ) ) {}
  9360. auto columnInfos() const -> std::vector<ColumnInfo> const& {
  9361. return m_columnInfos;
  9362. }
  9363. void open() {
  9364. if (!m_isOpen) {
  9365. m_isOpen = true;
  9366. *this << RowBreak();
  9367. for (auto const& info : m_columnInfos)
  9368. *this << info.name << ColumnBreak();
  9369. *this << RowBreak();
  9370. m_os << Catch::getLineOfChars<'-'>() << "\n";
  9371. }
  9372. }
  9373. void close() {
  9374. if (m_isOpen) {
  9375. *this << RowBreak();
  9376. m_os << std::endl;
  9377. m_isOpen = false;
  9378. }
  9379. }
  9380. template<typename T>
  9381. friend TablePrinter& operator << (TablePrinter& tp, T const& value) {
  9382. tp.m_oss << value;
  9383. return tp;
  9384. }
  9385. friend TablePrinter& operator << (TablePrinter& tp, ColumnBreak) {
  9386. auto colStr = tp.m_oss.str();
  9387. // This takes account of utf8 encodings
  9388. auto strSize = Catch::StringRef(colStr).numberOfCharacters();
  9389. tp.m_oss.str("");
  9390. tp.open();
  9391. if (tp.m_currentColumn == static_cast<int>(tp.m_columnInfos.size() - 1)) {
  9392. tp.m_currentColumn = -1;
  9393. tp.m_os << "\n";
  9394. }
  9395. tp.m_currentColumn++;
  9396. auto colInfo = tp.m_columnInfos[tp.m_currentColumn];
  9397. auto padding = (strSize + 2 < static_cast<std::size_t>(colInfo.width))
  9398. ? std::string(colInfo.width - (strSize + 2), ' ')
  9399. : std::string();
  9400. if (colInfo.justification == ColumnInfo::Left)
  9401. tp.m_os << colStr << padding << " ";
  9402. else
  9403. tp.m_os << padding << colStr << " ";
  9404. return tp;
  9405. }
  9406. friend TablePrinter& operator << (TablePrinter& tp, RowBreak) {
  9407. if (tp.m_currentColumn > 0) {
  9408. tp.m_os << "\n";
  9409. tp.m_currentColumn = -1;
  9410. }
  9411. return tp;
  9412. }
  9413. };
  9414. ConsoleReporter::ConsoleReporter(ReporterConfig const& config)
  9415. : StreamingReporterBase(config),
  9416. m_tablePrinter(new TablePrinter(config.stream(),
  9417. {
  9418. { "benchmark name", CATCH_CONFIG_CONSOLE_WIDTH - 32, ColumnInfo::Left },
  9419. { "iters", 8, ColumnInfo::Right },
  9420. { "elapsed ns", 14, ColumnInfo::Right },
  9421. { "average", 14, ColumnInfo::Right }
  9422. })) {}
  9423. ConsoleReporter::~ConsoleReporter() = default;
  9424. std::string ConsoleReporter::getDescription() {
  9425. return "Reports test results as plain lines of text";
  9426. }
  9427. void ConsoleReporter::noMatchingTestCases(std::string const& spec) {
  9428. stream << "No test cases matched '" << spec << '\'' << std::endl;
  9429. }
  9430. void ConsoleReporter::assertionStarting(AssertionInfo const&) {}
  9431. bool ConsoleReporter::assertionEnded(AssertionStats const& _assertionStats) {
  9432. AssertionResult const& result = _assertionStats.assertionResult;
  9433. bool includeResults = m_config->includeSuccessfulResults() || !result.isOk();
  9434. // Drop out if result was successful but we're not printing them.
  9435. if (!includeResults && result.getResultType() != ResultWas::Warning)
  9436. return false;
  9437. lazyPrint();
  9438. ConsoleAssertionPrinter printer(stream, _assertionStats, includeResults);
  9439. printer.print();
  9440. stream << std::endl;
  9441. return true;
  9442. }
  9443. void ConsoleReporter::sectionStarting(SectionInfo const& _sectionInfo) {
  9444. m_headerPrinted = false;
  9445. StreamingReporterBase::sectionStarting(_sectionInfo);
  9446. }
  9447. void ConsoleReporter::sectionEnded(SectionStats const& _sectionStats) {
  9448. m_tablePrinter->close();
  9449. if (_sectionStats.missingAssertions) {
  9450. lazyPrint();
  9451. Colour colour(Colour::ResultError);
  9452. if (m_sectionStack.size() > 1)
  9453. stream << "\nNo assertions in section";
  9454. else
  9455. stream << "\nNo assertions in test case";
  9456. stream << " '" << _sectionStats.sectionInfo.name << "'\n" << std::endl;
  9457. }
  9458. if (m_config->showDurations() == ShowDurations::Always) {
  9459. stream << getFormattedDuration(_sectionStats.durationInSeconds) << " s: " << _sectionStats.sectionInfo.name << std::endl;
  9460. }
  9461. if (m_headerPrinted) {
  9462. m_headerPrinted = false;
  9463. }
  9464. StreamingReporterBase::sectionEnded(_sectionStats);
  9465. }
  9466. void ConsoleReporter::benchmarkStarting(BenchmarkInfo const& info) {
  9467. lazyPrintWithoutClosingBenchmarkTable();
  9468. auto nameCol = Column( info.name ).width( static_cast<std::size_t>( m_tablePrinter->columnInfos()[0].width - 2 ) );
  9469. bool firstLine = true;
  9470. for (auto line : nameCol) {
  9471. if (!firstLine)
  9472. (*m_tablePrinter) << ColumnBreak() << ColumnBreak() << ColumnBreak();
  9473. else
  9474. firstLine = false;
  9475. (*m_tablePrinter) << line << ColumnBreak();
  9476. }
  9477. }
  9478. void ConsoleReporter::benchmarkEnded(BenchmarkStats const& stats) {
  9479. Duration average(stats.elapsedTimeInNanoseconds / stats.iterations);
  9480. (*m_tablePrinter)
  9481. << stats.iterations << ColumnBreak()
  9482. << stats.elapsedTimeInNanoseconds << ColumnBreak()
  9483. << average << ColumnBreak();
  9484. }
  9485. void ConsoleReporter::testCaseEnded(TestCaseStats const& _testCaseStats) {
  9486. m_tablePrinter->close();
  9487. StreamingReporterBase::testCaseEnded(_testCaseStats);
  9488. m_headerPrinted = false;
  9489. }
  9490. void ConsoleReporter::testGroupEnded(TestGroupStats const& _testGroupStats) {
  9491. if (currentGroupInfo.used) {
  9492. printSummaryDivider();
  9493. stream << "Summary for group '" << _testGroupStats.groupInfo.name << "':\n";
  9494. printTotals(_testGroupStats.totals);
  9495. stream << '\n' << std::endl;
  9496. }
  9497. StreamingReporterBase::testGroupEnded(_testGroupStats);
  9498. }
  9499. void ConsoleReporter::testRunEnded(TestRunStats const& _testRunStats) {
  9500. printTotalsDivider(_testRunStats.totals);
  9501. printTotals(_testRunStats.totals);
  9502. stream << std::endl;
  9503. StreamingReporterBase::testRunEnded(_testRunStats);
  9504. }
  9505. void ConsoleReporter::lazyPrint() {
  9506. m_tablePrinter->close();
  9507. lazyPrintWithoutClosingBenchmarkTable();
  9508. }
  9509. void ConsoleReporter::lazyPrintWithoutClosingBenchmarkTable() {
  9510. if (!currentTestRunInfo.used)
  9511. lazyPrintRunInfo();
  9512. if (!currentGroupInfo.used)
  9513. lazyPrintGroupInfo();
  9514. if (!m_headerPrinted) {
  9515. printTestCaseAndSectionHeader();
  9516. m_headerPrinted = true;
  9517. }
  9518. }
  9519. void ConsoleReporter::lazyPrintRunInfo() {
  9520. stream << '\n' << getLineOfChars<'~'>() << '\n';
  9521. Colour colour(Colour::SecondaryText);
  9522. stream << currentTestRunInfo->name
  9523. << " is a Catch v" << libraryVersion() << " host application.\n"
  9524. << "Run with -? for options\n\n";
  9525. if (m_config->rngSeed() != 0)
  9526. stream << "Randomness seeded to: " << m_config->rngSeed() << "\n\n";
  9527. currentTestRunInfo.used = true;
  9528. }
  9529. void ConsoleReporter::lazyPrintGroupInfo() {
  9530. if (!currentGroupInfo->name.empty() && currentGroupInfo->groupsCounts > 1) {
  9531. printClosedHeader("Group: " + currentGroupInfo->name);
  9532. currentGroupInfo.used = true;
  9533. }
  9534. }
  9535. void ConsoleReporter::printTestCaseAndSectionHeader() {
  9536. assert(!m_sectionStack.empty());
  9537. printOpenHeader(currentTestCaseInfo->name);
  9538. if (m_sectionStack.size() > 1) {
  9539. Colour colourGuard(Colour::Headers);
  9540. auto
  9541. it = m_sectionStack.begin() + 1, // Skip first section (test case)
  9542. itEnd = m_sectionStack.end();
  9543. for (; it != itEnd; ++it)
  9544. printHeaderString(it->name, 2);
  9545. }
  9546. SourceLineInfo lineInfo = m_sectionStack.back().lineInfo;
  9547. if (!lineInfo.empty()) {
  9548. stream << getLineOfChars<'-'>() << '\n';
  9549. Colour colourGuard(Colour::FileName);
  9550. stream << lineInfo << '\n';
  9551. }
  9552. stream << getLineOfChars<'.'>() << '\n' << std::endl;
  9553. }
  9554. void ConsoleReporter::printClosedHeader(std::string const& _name) {
  9555. printOpenHeader(_name);
  9556. stream << getLineOfChars<'.'>() << '\n';
  9557. }
  9558. void ConsoleReporter::printOpenHeader(std::string const& _name) {
  9559. stream << getLineOfChars<'-'>() << '\n';
  9560. {
  9561. Colour colourGuard(Colour::Headers);
  9562. printHeaderString(_name);
  9563. }
  9564. }
  9565. // if string has a : in first line will set indent to follow it on
  9566. // subsequent lines
  9567. void ConsoleReporter::printHeaderString(std::string const& _string, std::size_t indent) {
  9568. std::size_t i = _string.find(": ");
  9569. if (i != std::string::npos)
  9570. i += 2;
  9571. else
  9572. i = 0;
  9573. stream << Column(_string).indent(indent + i).initialIndent(indent) << '\n';
  9574. }
  9575. struct SummaryColumn {
  9576. SummaryColumn( std::string _label, Colour::Code _colour )
  9577. : label( std::move( _label ) ),
  9578. colour( _colour ) {}
  9579. SummaryColumn addRow( std::size_t count ) {
  9580. ReusableStringStream rss;
  9581. rss << count;
  9582. std::string row = rss.str();
  9583. for (auto& oldRow : rows) {
  9584. while (oldRow.size() < row.size())
  9585. oldRow = ' ' + oldRow;
  9586. while (oldRow.size() > row.size())
  9587. row = ' ' + row;
  9588. }
  9589. rows.push_back(row);
  9590. return *this;
  9591. }
  9592. std::string label;
  9593. Colour::Code colour;
  9594. std::vector<std::string> rows;
  9595. };
  9596. void ConsoleReporter::printTotals( Totals const& totals ) {
  9597. if (totals.testCases.total() == 0) {
  9598. stream << Colour(Colour::Warning) << "No tests ran\n";
  9599. } else if (totals.assertions.total() > 0 && totals.testCases.allPassed()) {
  9600. stream << Colour(Colour::ResultSuccess) << "All tests passed";
  9601. stream << " ("
  9602. << pluralise(totals.assertions.passed, "assertion") << " in "
  9603. << pluralise(totals.testCases.passed, "test case") << ')'
  9604. << '\n';
  9605. } else {
  9606. std::vector<SummaryColumn> columns;
  9607. columns.push_back(SummaryColumn("", Colour::None)
  9608. .addRow(totals.testCases.total())
  9609. .addRow(totals.assertions.total()));
  9610. columns.push_back(SummaryColumn("passed", Colour::Success)
  9611. .addRow(totals.testCases.passed)
  9612. .addRow(totals.assertions.passed));
  9613. columns.push_back(SummaryColumn("failed", Colour::ResultError)
  9614. .addRow(totals.testCases.failed)
  9615. .addRow(totals.assertions.failed));
  9616. columns.push_back(SummaryColumn("failed as expected", Colour::ResultExpectedFailure)
  9617. .addRow(totals.testCases.failedButOk)
  9618. .addRow(totals.assertions.failedButOk));
  9619. printSummaryRow("test cases", columns, 0);
  9620. printSummaryRow("assertions", columns, 1);
  9621. }
  9622. }
  9623. void ConsoleReporter::printSummaryRow(std::string const& label, std::vector<SummaryColumn> const& cols, std::size_t row) {
  9624. for (auto col : cols) {
  9625. std::string value = col.rows[row];
  9626. if (col.label.empty()) {
  9627. stream << label << ": ";
  9628. if (value != "0")
  9629. stream << value;
  9630. else
  9631. stream << Colour(Colour::Warning) << "- none -";
  9632. } else if (value != "0") {
  9633. stream << Colour(Colour::LightGrey) << " | ";
  9634. stream << Colour(col.colour)
  9635. << value << ' ' << col.label;
  9636. }
  9637. }
  9638. stream << '\n';
  9639. }
  9640. void ConsoleReporter::printTotalsDivider(Totals const& totals) {
  9641. if (totals.testCases.total() > 0) {
  9642. std::size_t failedRatio = makeRatio(totals.testCases.failed, totals.testCases.total());
  9643. std::size_t failedButOkRatio = makeRatio(totals.testCases.failedButOk, totals.testCases.total());
  9644. std::size_t passedRatio = makeRatio(totals.testCases.passed, totals.testCases.total());
  9645. while (failedRatio + failedButOkRatio + passedRatio < CATCH_CONFIG_CONSOLE_WIDTH - 1)
  9646. findMax(failedRatio, failedButOkRatio, passedRatio)++;
  9647. while (failedRatio + failedButOkRatio + passedRatio > CATCH_CONFIG_CONSOLE_WIDTH - 1)
  9648. findMax(failedRatio, failedButOkRatio, passedRatio)--;
  9649. stream << Colour(Colour::Error) << std::string(failedRatio, '=');
  9650. stream << Colour(Colour::ResultExpectedFailure) << std::string(failedButOkRatio, '=');
  9651. if (totals.testCases.allPassed())
  9652. stream << Colour(Colour::ResultSuccess) << std::string(passedRatio, '=');
  9653. else
  9654. stream << Colour(Colour::Success) << std::string(passedRatio, '=');
  9655. } else {
  9656. stream << Colour(Colour::Warning) << std::string(CATCH_CONFIG_CONSOLE_WIDTH - 1, '=');
  9657. }
  9658. stream << '\n';
  9659. }
  9660. void ConsoleReporter::printSummaryDivider() {
  9661. stream << getLineOfChars<'-'>() << '\n';
  9662. }
  9663. CATCH_REGISTER_REPORTER("console", ConsoleReporter)
  9664. } // end namespace Catch
  9665. #if defined(_MSC_VER)
  9666. #pragma warning(pop)
  9667. #endif
  9668. // end catch_reporter_console.cpp
  9669. // start catch_reporter_junit.cpp
  9670. #include <assert.h>
  9671. #include <sstream>
  9672. #include <ctime>
  9673. #include <algorithm>
  9674. namespace Catch {
  9675. namespace {
  9676. std::string getCurrentTimestamp() {
  9677. // Beware, this is not reentrant because of backward compatibility issues
  9678. // Also, UTC only, again because of backward compatibility (%z is C++11)
  9679. time_t rawtime;
  9680. std::time(&rawtime);
  9681. auto const timeStampSize = sizeof("2017-01-16T17:06:45Z");
  9682. #ifdef _MSC_VER
  9683. std::tm timeInfo = {};
  9684. gmtime_s(&timeInfo, &rawtime);
  9685. #else
  9686. std::tm* timeInfo;
  9687. timeInfo = std::gmtime(&rawtime);
  9688. #endif
  9689. char timeStamp[timeStampSize];
  9690. const char * const fmt = "%Y-%m-%dT%H:%M:%SZ";
  9691. #ifdef _MSC_VER
  9692. std::strftime(timeStamp, timeStampSize, fmt, &timeInfo);
  9693. #else
  9694. std::strftime(timeStamp, timeStampSize, fmt, timeInfo);
  9695. #endif
  9696. return std::string(timeStamp);
  9697. }
  9698. std::string fileNameTag(const std::vector<std::string> &tags) {
  9699. auto it = std::find_if(begin(tags),
  9700. end(tags),
  9701. [] (std::string const& tag) {return tag.front() == '#'; });
  9702. if (it != tags.end())
  9703. return it->substr(1);
  9704. return std::string();
  9705. }
  9706. } // anonymous namespace
  9707. JunitReporter::JunitReporter( ReporterConfig const& _config )
  9708. : CumulativeReporterBase( _config ),
  9709. xml( _config.stream() )
  9710. {
  9711. m_reporterPrefs.shouldRedirectStdOut = true;
  9712. }
  9713. JunitReporter::~JunitReporter() {};
  9714. std::string JunitReporter::getDescription() {
  9715. return "Reports test results in an XML format that looks like Ant's junitreport target";
  9716. }
  9717. void JunitReporter::noMatchingTestCases( std::string const& /*spec*/ ) {}
  9718. void JunitReporter::testRunStarting( TestRunInfo const& runInfo ) {
  9719. CumulativeReporterBase::testRunStarting( runInfo );
  9720. xml.startElement( "testsuites" );
  9721. }
  9722. void JunitReporter::testGroupStarting( GroupInfo const& groupInfo ) {
  9723. suiteTimer.start();
  9724. stdOutForSuite.clear();
  9725. stdErrForSuite.clear();
  9726. unexpectedExceptions = 0;
  9727. CumulativeReporterBase::testGroupStarting( groupInfo );
  9728. }
  9729. void JunitReporter::testCaseStarting( TestCaseInfo const& testCaseInfo ) {
  9730. m_okToFail = testCaseInfo.okToFail();
  9731. }
  9732. bool JunitReporter::assertionEnded( AssertionStats const& assertionStats ) {
  9733. if( assertionStats.assertionResult.getResultType() == ResultWas::ThrewException && !m_okToFail )
  9734. unexpectedExceptions++;
  9735. return CumulativeReporterBase::assertionEnded( assertionStats );
  9736. }
  9737. void JunitReporter::testCaseEnded( TestCaseStats const& testCaseStats ) {
  9738. stdOutForSuite += testCaseStats.stdOut;
  9739. stdErrForSuite += testCaseStats.stdErr;
  9740. CumulativeReporterBase::testCaseEnded( testCaseStats );
  9741. }
  9742. void JunitReporter::testGroupEnded( TestGroupStats const& testGroupStats ) {
  9743. double suiteTime = suiteTimer.getElapsedSeconds();
  9744. CumulativeReporterBase::testGroupEnded( testGroupStats );
  9745. writeGroup( *m_testGroups.back(), suiteTime );
  9746. }
  9747. void JunitReporter::testRunEndedCumulative() {
  9748. xml.endElement();
  9749. }
  9750. void JunitReporter::writeGroup( TestGroupNode const& groupNode, double suiteTime ) {
  9751. XmlWriter::ScopedElement e = xml.scopedElement( "testsuite" );
  9752. TestGroupStats const& stats = groupNode.value;
  9753. xml.writeAttribute( "name", stats.groupInfo.name );
  9754. xml.writeAttribute( "errors", unexpectedExceptions );
  9755. xml.writeAttribute( "failures", stats.totals.assertions.failed-unexpectedExceptions );
  9756. xml.writeAttribute( "tests", stats.totals.assertions.total() );
  9757. xml.writeAttribute( "hostname", "tbd" ); // !TBD
  9758. if( m_config->showDurations() == ShowDurations::Never )
  9759. xml.writeAttribute( "time", "" );
  9760. else
  9761. xml.writeAttribute( "time", suiteTime );
  9762. xml.writeAttribute( "timestamp", getCurrentTimestamp() );
  9763. // Write test cases
  9764. for( auto const& child : groupNode.children )
  9765. writeTestCase( *child );
  9766. xml.scopedElement( "system-out" ).writeText( trim( stdOutForSuite ), false );
  9767. xml.scopedElement( "system-err" ).writeText( trim( stdErrForSuite ), false );
  9768. }
  9769. void JunitReporter::writeTestCase( TestCaseNode const& testCaseNode ) {
  9770. TestCaseStats const& stats = testCaseNode.value;
  9771. // All test cases have exactly one section - which represents the
  9772. // test case itself. That section may have 0-n nested sections
  9773. assert( testCaseNode.children.size() == 1 );
  9774. SectionNode const& rootSection = *testCaseNode.children.front();
  9775. std::string className = stats.testInfo.className;
  9776. if( className.empty() ) {
  9777. className = fileNameTag(stats.testInfo.tags);
  9778. if ( className.empty() )
  9779. className = "global";
  9780. }
  9781. if ( !m_config->name().empty() )
  9782. className = m_config->name() + "." + className;
  9783. writeSection( className, "", rootSection );
  9784. }
  9785. void JunitReporter::writeSection( std::string const& className,
  9786. std::string const& rootName,
  9787. SectionNode const& sectionNode ) {
  9788. std::string name = trim( sectionNode.stats.sectionInfo.name );
  9789. if( !rootName.empty() )
  9790. name = rootName + '/' + name;
  9791. if( !sectionNode.assertions.empty() ||
  9792. !sectionNode.stdOut.empty() ||
  9793. !sectionNode.stdErr.empty() ) {
  9794. XmlWriter::ScopedElement e = xml.scopedElement( "testcase" );
  9795. if( className.empty() ) {
  9796. xml.writeAttribute( "classname", name );
  9797. xml.writeAttribute( "name", "root" );
  9798. }
  9799. else {
  9800. xml.writeAttribute( "classname", className );
  9801. xml.writeAttribute( "name", name );
  9802. }
  9803. xml.writeAttribute( "time", ::Catch::Detail::stringify( sectionNode.stats.durationInSeconds ) );
  9804. writeAssertions( sectionNode );
  9805. if( !sectionNode.stdOut.empty() )
  9806. xml.scopedElement( "system-out" ).writeText( trim( sectionNode.stdOut ), false );
  9807. if( !sectionNode.stdErr.empty() )
  9808. xml.scopedElement( "system-err" ).writeText( trim( sectionNode.stdErr ), false );
  9809. }
  9810. for( auto const& childNode : sectionNode.childSections )
  9811. if( className.empty() )
  9812. writeSection( name, "", *childNode );
  9813. else
  9814. writeSection( className, name, *childNode );
  9815. }
  9816. void JunitReporter::writeAssertions( SectionNode const& sectionNode ) {
  9817. for( auto const& assertion : sectionNode.assertions )
  9818. writeAssertion( assertion );
  9819. }
  9820. void JunitReporter::writeAssertion( AssertionStats const& stats ) {
  9821. AssertionResult const& result = stats.assertionResult;
  9822. if( !result.isOk() ) {
  9823. std::string elementName;
  9824. switch( result.getResultType() ) {
  9825. case ResultWas::ThrewException:
  9826. case ResultWas::FatalErrorCondition:
  9827. elementName = "error";
  9828. break;
  9829. case ResultWas::ExplicitFailure:
  9830. elementName = "failure";
  9831. break;
  9832. case ResultWas::ExpressionFailed:
  9833. elementName = "failure";
  9834. break;
  9835. case ResultWas::DidntThrowException:
  9836. elementName = "failure";
  9837. break;
  9838. // We should never see these here:
  9839. case ResultWas::Info:
  9840. case ResultWas::Warning:
  9841. case ResultWas::Ok:
  9842. case ResultWas::Unknown:
  9843. case ResultWas::FailureBit:
  9844. case ResultWas::Exception:
  9845. elementName = "internalError";
  9846. break;
  9847. }
  9848. XmlWriter::ScopedElement e = xml.scopedElement( elementName );
  9849. xml.writeAttribute( "message", result.getExpandedExpression() );
  9850. xml.writeAttribute( "type", result.getTestMacroName() );
  9851. ReusableStringStream rss;
  9852. if( !result.getMessage().empty() )
  9853. rss << result.getMessage() << '\n';
  9854. for( auto const& msg : stats.infoMessages )
  9855. if( msg.type == ResultWas::Info )
  9856. rss << msg.message << '\n';
  9857. rss << "at " << result.getSourceInfo();
  9858. xml.writeText( rss.str(), false );
  9859. }
  9860. }
  9861. CATCH_REGISTER_REPORTER( "junit", JunitReporter )
  9862. } // end namespace Catch
  9863. // end catch_reporter_junit.cpp
  9864. // start catch_reporter_multi.cpp
  9865. namespace Catch {
  9866. void MultipleReporters::add( IStreamingReporterPtr&& reporter ) {
  9867. m_reporters.push_back( std::move( reporter ) );
  9868. }
  9869. ReporterPreferences MultipleReporters::getPreferences() const {
  9870. return m_reporters[0]->getPreferences();
  9871. }
  9872. std::set<Verbosity> MultipleReporters::getSupportedVerbosities() {
  9873. return std::set<Verbosity>{ };
  9874. }
  9875. void MultipleReporters::noMatchingTestCases( std::string const& spec ) {
  9876. for( auto const& reporter : m_reporters )
  9877. reporter->noMatchingTestCases( spec );
  9878. }
  9879. void MultipleReporters::benchmarkStarting( BenchmarkInfo const& benchmarkInfo ) {
  9880. for( auto const& reporter : m_reporters )
  9881. reporter->benchmarkStarting( benchmarkInfo );
  9882. }
  9883. void MultipleReporters::benchmarkEnded( BenchmarkStats const& benchmarkStats ) {
  9884. for( auto const& reporter : m_reporters )
  9885. reporter->benchmarkEnded( benchmarkStats );
  9886. }
  9887. void MultipleReporters::testRunStarting( TestRunInfo const& testRunInfo ) {
  9888. for( auto const& reporter : m_reporters )
  9889. reporter->testRunStarting( testRunInfo );
  9890. }
  9891. void MultipleReporters::testGroupStarting( GroupInfo const& groupInfo ) {
  9892. for( auto const& reporter : m_reporters )
  9893. reporter->testGroupStarting( groupInfo );
  9894. }
  9895. void MultipleReporters::testCaseStarting( TestCaseInfo const& testInfo ) {
  9896. for( auto const& reporter : m_reporters )
  9897. reporter->testCaseStarting( testInfo );
  9898. }
  9899. void MultipleReporters::sectionStarting( SectionInfo const& sectionInfo ) {
  9900. for( auto const& reporter : m_reporters )
  9901. reporter->sectionStarting( sectionInfo );
  9902. }
  9903. void MultipleReporters::assertionStarting( AssertionInfo const& assertionInfo ) {
  9904. for( auto const& reporter : m_reporters )
  9905. reporter->assertionStarting( assertionInfo );
  9906. }
  9907. // The return value indicates if the messages buffer should be cleared:
  9908. bool MultipleReporters::assertionEnded( AssertionStats const& assertionStats ) {
  9909. bool clearBuffer = false;
  9910. for( auto const& reporter : m_reporters )
  9911. clearBuffer |= reporter->assertionEnded( assertionStats );
  9912. return clearBuffer;
  9913. }
  9914. void MultipleReporters::sectionEnded( SectionStats const& sectionStats ) {
  9915. for( auto const& reporter : m_reporters )
  9916. reporter->sectionEnded( sectionStats );
  9917. }
  9918. void MultipleReporters::testCaseEnded( TestCaseStats const& testCaseStats ) {
  9919. for( auto const& reporter : m_reporters )
  9920. reporter->testCaseEnded( testCaseStats );
  9921. }
  9922. void MultipleReporters::testGroupEnded( TestGroupStats const& testGroupStats ) {
  9923. for( auto const& reporter : m_reporters )
  9924. reporter->testGroupEnded( testGroupStats );
  9925. }
  9926. void MultipleReporters::testRunEnded( TestRunStats const& testRunStats ) {
  9927. for( auto const& reporter : m_reporters )
  9928. reporter->testRunEnded( testRunStats );
  9929. }
  9930. void MultipleReporters::skipTest( TestCaseInfo const& testInfo ) {
  9931. for( auto const& reporter : m_reporters )
  9932. reporter->skipTest( testInfo );
  9933. }
  9934. bool MultipleReporters::isMulti() const {
  9935. return true;
  9936. }
  9937. } // end namespace Catch
  9938. // end catch_reporter_multi.cpp
  9939. // start catch_reporter_xml.cpp
  9940. #if defined(_MSC_VER)
  9941. #pragma warning(push)
  9942. #pragma warning(disable:4061) // Not all labels are EXPLICITLY handled in switch
  9943. // Note that 4062 (not all labels are handled
  9944. // and default is missing) is enabled
  9945. #endif
  9946. namespace Catch {
  9947. XmlReporter::XmlReporter( ReporterConfig const& _config )
  9948. : StreamingReporterBase( _config ),
  9949. m_xml(_config.stream())
  9950. {
  9951. m_reporterPrefs.shouldRedirectStdOut = true;
  9952. }
  9953. XmlReporter::~XmlReporter() = default;
  9954. std::string XmlReporter::getDescription() {
  9955. return "Reports test results as an XML document";
  9956. }
  9957. std::string XmlReporter::getStylesheetRef() const {
  9958. return std::string();
  9959. }
  9960. void XmlReporter::writeSourceInfo( SourceLineInfo const& sourceInfo ) {
  9961. m_xml
  9962. .writeAttribute( "filename", sourceInfo.file )
  9963. .writeAttribute( "line", sourceInfo.line );
  9964. }
  9965. void XmlReporter::noMatchingTestCases( std::string const& s ) {
  9966. StreamingReporterBase::noMatchingTestCases( s );
  9967. }
  9968. void XmlReporter::testRunStarting( TestRunInfo const& testInfo ) {
  9969. StreamingReporterBase::testRunStarting( testInfo );
  9970. std::string stylesheetRef = getStylesheetRef();
  9971. if( !stylesheetRef.empty() )
  9972. m_xml.writeStylesheetRef( stylesheetRef );
  9973. m_xml.startElement( "Catch" );
  9974. if( !m_config->name().empty() )
  9975. m_xml.writeAttribute( "name", m_config->name() );
  9976. }
  9977. void XmlReporter::testGroupStarting( GroupInfo const& groupInfo ) {
  9978. StreamingReporterBase::testGroupStarting( groupInfo );
  9979. m_xml.startElement( "Group" )
  9980. .writeAttribute( "name", groupInfo.name );
  9981. }
  9982. void XmlReporter::testCaseStarting( TestCaseInfo const& testInfo ) {
  9983. StreamingReporterBase::testCaseStarting(testInfo);
  9984. m_xml.startElement( "TestCase" )
  9985. .writeAttribute( "name", trim( testInfo.name ) )
  9986. .writeAttribute( "description", testInfo.description )
  9987. .writeAttribute( "tags", testInfo.tagsAsString() );
  9988. writeSourceInfo( testInfo.lineInfo );
  9989. if ( m_config->showDurations() == ShowDurations::Always )
  9990. m_testCaseTimer.start();
  9991. m_xml.ensureTagClosed();
  9992. }
  9993. void XmlReporter::sectionStarting( SectionInfo const& sectionInfo ) {
  9994. StreamingReporterBase::sectionStarting( sectionInfo );
  9995. if( m_sectionDepth++ > 0 ) {
  9996. m_xml.startElement( "Section" )
  9997. .writeAttribute( "name", trim( sectionInfo.name ) )
  9998. .writeAttribute( "description", sectionInfo.description );
  9999. writeSourceInfo( sectionInfo.lineInfo );
  10000. m_xml.ensureTagClosed();
  10001. }
  10002. }
  10003. void XmlReporter::assertionStarting( AssertionInfo const& ) { }
  10004. bool XmlReporter::assertionEnded( AssertionStats const& assertionStats ) {
  10005. AssertionResult const& result = assertionStats.assertionResult;
  10006. bool includeResults = m_config->includeSuccessfulResults() || !result.isOk();
  10007. if( includeResults || result.getResultType() == ResultWas::Warning ) {
  10008. // Print any info messages in <Info> tags.
  10009. for( auto const& msg : assertionStats.infoMessages ) {
  10010. if( msg.type == ResultWas::Info && includeResults ) {
  10011. m_xml.scopedElement( "Info" )
  10012. .writeText( msg.message );
  10013. } else if ( msg.type == ResultWas::Warning ) {
  10014. m_xml.scopedElement( "Warning" )
  10015. .writeText( msg.message );
  10016. }
  10017. }
  10018. }
  10019. // Drop out if result was successful but we're not printing them.
  10020. if( !includeResults && result.getResultType() != ResultWas::Warning )
  10021. return true;
  10022. // Print the expression if there is one.
  10023. if( result.hasExpression() ) {
  10024. m_xml.startElement( "Expression" )
  10025. .writeAttribute( "success", result.succeeded() )
  10026. .writeAttribute( "type", result.getTestMacroName() );
  10027. writeSourceInfo( result.getSourceInfo() );
  10028. m_xml.scopedElement( "Original" )
  10029. .writeText( result.getExpression() );
  10030. m_xml.scopedElement( "Expanded" )
  10031. .writeText( result.getExpandedExpression() );
  10032. }
  10033. // And... Print a result applicable to each result type.
  10034. switch( result.getResultType() ) {
  10035. case ResultWas::ThrewException:
  10036. m_xml.startElement( "Exception" );
  10037. writeSourceInfo( result.getSourceInfo() );
  10038. m_xml.writeText( result.getMessage() );
  10039. m_xml.endElement();
  10040. break;
  10041. case ResultWas::FatalErrorCondition:
  10042. m_xml.startElement( "FatalErrorCondition" );
  10043. writeSourceInfo( result.getSourceInfo() );
  10044. m_xml.writeText( result.getMessage() );
  10045. m_xml.endElement();
  10046. break;
  10047. case ResultWas::Info:
  10048. m_xml.scopedElement( "Info" )
  10049. .writeText( result.getMessage() );
  10050. break;
  10051. case ResultWas::Warning:
  10052. // Warning will already have been written
  10053. break;
  10054. case ResultWas::ExplicitFailure:
  10055. m_xml.startElement( "Failure" );
  10056. writeSourceInfo( result.getSourceInfo() );
  10057. m_xml.writeText( result.getMessage() );
  10058. m_xml.endElement();
  10059. break;
  10060. default:
  10061. break;
  10062. }
  10063. if( result.hasExpression() )
  10064. m_xml.endElement();
  10065. return true;
  10066. }
  10067. void XmlReporter::sectionEnded( SectionStats const& sectionStats ) {
  10068. StreamingReporterBase::sectionEnded( sectionStats );
  10069. if( --m_sectionDepth > 0 ) {
  10070. XmlWriter::ScopedElement e = m_xml.scopedElement( "OverallResults" );
  10071. e.writeAttribute( "successes", sectionStats.assertions.passed );
  10072. e.writeAttribute( "failures", sectionStats.assertions.failed );
  10073. e.writeAttribute( "expectedFailures", sectionStats.assertions.failedButOk );
  10074. if ( m_config->showDurations() == ShowDurations::Always )
  10075. e.writeAttribute( "durationInSeconds", sectionStats.durationInSeconds );
  10076. m_xml.endElement();
  10077. }
  10078. }
  10079. void XmlReporter::testCaseEnded( TestCaseStats const& testCaseStats ) {
  10080. StreamingReporterBase::testCaseEnded( testCaseStats );
  10081. XmlWriter::ScopedElement e = m_xml.scopedElement( "OverallResult" );
  10082. e.writeAttribute( "success", testCaseStats.totals.assertions.allOk() );
  10083. if ( m_config->showDurations() == ShowDurations::Always )
  10084. e.writeAttribute( "durationInSeconds", m_testCaseTimer.getElapsedSeconds() );
  10085. if( !testCaseStats.stdOut.empty() )
  10086. m_xml.scopedElement( "StdOut" ).writeText( trim( testCaseStats.stdOut ), false );
  10087. if( !testCaseStats.stdErr.empty() )
  10088. m_xml.scopedElement( "StdErr" ).writeText( trim( testCaseStats.stdErr ), false );
  10089. m_xml.endElement();
  10090. }
  10091. void XmlReporter::testGroupEnded( TestGroupStats const& testGroupStats ) {
  10092. StreamingReporterBase::testGroupEnded( testGroupStats );
  10093. // TODO: Check testGroupStats.aborting and act accordingly.
  10094. m_xml.scopedElement( "OverallResults" )
  10095. .writeAttribute( "successes", testGroupStats.totals.assertions.passed )
  10096. .writeAttribute( "failures", testGroupStats.totals.assertions.failed )
  10097. .writeAttribute( "expectedFailures", testGroupStats.totals.assertions.failedButOk );
  10098. m_xml.endElement();
  10099. }
  10100. void XmlReporter::testRunEnded( TestRunStats const& testRunStats ) {
  10101. StreamingReporterBase::testRunEnded( testRunStats );
  10102. m_xml.scopedElement( "OverallResults" )
  10103. .writeAttribute( "successes", testRunStats.totals.assertions.passed )
  10104. .writeAttribute( "failures", testRunStats.totals.assertions.failed )
  10105. .writeAttribute( "expectedFailures", testRunStats.totals.assertions.failedButOk );
  10106. m_xml.endElement();
  10107. }
  10108. CATCH_REGISTER_REPORTER( "xml", XmlReporter )
  10109. } // end namespace Catch
  10110. #if defined(_MSC_VER)
  10111. #pragma warning(pop)
  10112. #endif
  10113. // end catch_reporter_xml.cpp
  10114. namespace Catch {
  10115. LeakDetector leakDetector;
  10116. }
  10117. #ifdef __clang__
  10118. #pragma clang diagnostic pop
  10119. #endif
  10120. // end catch_impl.hpp
  10121. #endif
  10122. #ifdef CATCH_CONFIG_MAIN
  10123. // start catch_default_main.hpp
  10124. #ifndef __OBJC__
  10125. #if defined(WIN32) && defined(_UNICODE) && !defined(DO_NOT_USE_WMAIN)
  10126. // Standard C/C++ Win32 Unicode wmain entry point
  10127. extern "C" int wmain (int argc, wchar_t * argv[], wchar_t * []) {
  10128. #else
  10129. // Standard C/C++ main entry point
  10130. int main (int argc, char * argv[]) {
  10131. #endif
  10132. return Catch::Session().run( argc, argv );
  10133. }
  10134. #else // __OBJC__
  10135. // Objective-C entry point
  10136. int main (int argc, char * const argv[]) {
  10137. #if !CATCH_ARC_ENABLED
  10138. NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
  10139. #endif
  10140. Catch::registerTestMethods();
  10141. int result = Catch::Session().run( argc, (char**)argv );
  10142. #if !CATCH_ARC_ENABLED
  10143. [pool drain];
  10144. #endif
  10145. return result;
  10146. }
  10147. #endif // __OBJC__
  10148. // end catch_default_main.hpp
  10149. #endif
  10150. #if !defined(CATCH_CONFIG_IMPL_ONLY)
  10151. #ifdef CLARA_CONFIG_MAIN_NOT_DEFINED
  10152. # undef CLARA_CONFIG_MAIN
  10153. #endif
  10154. #if !defined(CATCH_CONFIG_DISABLE)
  10155. //////
  10156. // If this config identifier is defined then all CATCH macros are prefixed with CATCH_
  10157. #ifdef CATCH_CONFIG_PREFIX_ALL
  10158. #define CATCH_REQUIRE( ... ) INTERNAL_CATCH_TEST( "CATCH_REQUIRE", Catch::ResultDisposition::Normal, __VA_ARGS__ )
  10159. #define CATCH_REQUIRE_FALSE( ... ) INTERNAL_CATCH_TEST( "CATCH_REQUIRE_FALSE", Catch::ResultDisposition::Normal | Catch::ResultDisposition::FalseTest, __VA_ARGS__ )
  10160. #define CATCH_REQUIRE_THROWS( ... ) INTERNAL_CATCH_THROWS( "CATCH_REQUIRE_THROWS", Catch::ResultDisposition::Normal, "", __VA_ARGS__ )
  10161. #define CATCH_REQUIRE_THROWS_AS( expr, exceptionType ) INTERNAL_CATCH_THROWS_AS( "CATCH_REQUIRE_THROWS_AS", exceptionType, Catch::ResultDisposition::Normal, expr )
  10162. #define CATCH_REQUIRE_THROWS_WITH( expr, matcher ) INTERNAL_CATCH_THROWS_STR_MATCHES( "CATCH_REQUIRE_THROWS_WITH", Catch::ResultDisposition::Normal, matcher, expr )
  10163. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  10164. #define CATCH_REQUIRE_THROWS_MATCHES( expr, exceptionType, matcher ) INTERNAL_CATCH_THROWS_MATCHES( "CATCH_REQUIRE_THROWS_MATCHES", exceptionType, Catch::ResultDisposition::Normal, matcher, expr )
  10165. #endif// CATCH_CONFIG_DISABLE_MATCHERS
  10166. #define CATCH_REQUIRE_NOTHROW( ... ) INTERNAL_CATCH_NO_THROW( "CATCH_REQUIRE_NOTHROW", Catch::ResultDisposition::Normal, __VA_ARGS__ )
  10167. #define CATCH_CHECK( ... ) INTERNAL_CATCH_TEST( "CATCH_CHECK", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  10168. #define CATCH_CHECK_FALSE( ... ) INTERNAL_CATCH_TEST( "CATCH_CHECK_FALSE", Catch::ResultDisposition::ContinueOnFailure | Catch::ResultDisposition::FalseTest, __VA_ARGS__ )
  10169. #define CATCH_CHECKED_IF( ... ) INTERNAL_CATCH_IF( "CATCH_CHECKED_IF", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  10170. #define CATCH_CHECKED_ELSE( ... ) INTERNAL_CATCH_ELSE( "CATCH_CHECKED_ELSE", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  10171. #define CATCH_CHECK_NOFAIL( ... ) INTERNAL_CATCH_TEST( "CATCH_CHECK_NOFAIL", Catch::ResultDisposition::ContinueOnFailure | Catch::ResultDisposition::SuppressFail, __VA_ARGS__ )
  10172. #define CATCH_CHECK_THROWS( ... ) INTERNAL_CATCH_THROWS( "CATCH_CHECK_THROWS", Catch::ResultDisposition::ContinueOnFailure, "", __VA_ARGS__ )
  10173. #define CATCH_CHECK_THROWS_AS( expr, exceptionType ) INTERNAL_CATCH_THROWS_AS( "CATCH_CHECK_THROWS_AS", exceptionType, Catch::ResultDisposition::ContinueOnFailure, expr )
  10174. #define CATCH_CHECK_THROWS_WITH( expr, matcher ) INTERNAL_CATCH_THROWS_STR_MATCHES( "CATCH_CHECK_THROWS_WITH", Catch::ResultDisposition::ContinueOnFailure, matcher, expr )
  10175. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  10176. #define CATCH_CHECK_THROWS_MATCHES( expr, exceptionType, matcher ) INTERNAL_CATCH_THROWS_MATCHES( "CATCH_CHECK_THROWS_MATCHES", exceptionType, Catch::ResultDisposition::ContinueOnFailure, matcher, expr )
  10177. #endif // CATCH_CONFIG_DISABLE_MATCHERS
  10178. #define CATCH_CHECK_NOTHROW( ... ) INTERNAL_CATCH_NO_THROW( "CATCH_CHECK_NOTHROW", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  10179. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  10180. #define CATCH_CHECK_THAT( arg, matcher ) INTERNAL_CHECK_THAT( "CATCH_CHECK_THAT", matcher, Catch::ResultDisposition::ContinueOnFailure, arg )
  10181. #define CATCH_REQUIRE_THAT( arg, matcher ) INTERNAL_CHECK_THAT( "CATCH_REQUIRE_THAT", matcher, Catch::ResultDisposition::Normal, arg )
  10182. #endif // CATCH_CONFIG_DISABLE_MATCHERS
  10183. #define CATCH_INFO( msg ) INTERNAL_CATCH_INFO( "CATCH_INFO", msg )
  10184. #define CATCH_WARN( msg ) INTERNAL_CATCH_MSG( "CATCH_WARN", Catch::ResultWas::Warning, Catch::ResultDisposition::ContinueOnFailure, msg )
  10185. #define CATCH_CAPTURE( msg ) INTERNAL_CATCH_INFO( "CATCH_CAPTURE", #msg " := " << ::Catch::Detail::stringify(msg) )
  10186. #define CATCH_TEST_CASE( ... ) INTERNAL_CATCH_TESTCASE( __VA_ARGS__ )
  10187. #define CATCH_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEST_CASE_METHOD( className, __VA_ARGS__ )
  10188. #define CATCH_METHOD_AS_TEST_CASE( method, ... ) INTERNAL_CATCH_METHOD_AS_TEST_CASE( method, __VA_ARGS__ )
  10189. #define CATCH_REGISTER_TEST_CASE( Function, ... ) INTERNAL_CATCH_REGISTER_TESTCASE( Function, __VA_ARGS__ )
  10190. #define CATCH_SECTION( ... ) INTERNAL_CATCH_SECTION( __VA_ARGS__ )
  10191. #define CATCH_FAIL( ... ) INTERNAL_CATCH_MSG( "CATCH_FAIL", Catch::ResultWas::ExplicitFailure, Catch::ResultDisposition::Normal, __VA_ARGS__ )
  10192. #define CATCH_FAIL_CHECK( ... ) INTERNAL_CATCH_MSG( "CATCH_FAIL_CHECK", Catch::ResultWas::ExplicitFailure, Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  10193. #define CATCH_SUCCEED( ... ) INTERNAL_CATCH_MSG( "CATCH_SUCCEED", Catch::ResultWas::Ok, Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  10194. #define CATCH_ANON_TEST_CASE() INTERNAL_CATCH_TESTCASE()
  10195. // "BDD-style" convenience wrappers
  10196. #define CATCH_SCENARIO( ... ) CATCH_TEST_CASE( "Scenario: " __VA_ARGS__ )
  10197. #define CATCH_SCENARIO_METHOD( className, ... ) INTERNAL_CATCH_TEST_CASE_METHOD( className, "Scenario: " __VA_ARGS__ )
  10198. #define CATCH_GIVEN( desc ) CATCH_SECTION( std::string( "Given: ") + desc )
  10199. #define CATCH_WHEN( desc ) CATCH_SECTION( std::string( " When: ") + desc )
  10200. #define CATCH_AND_WHEN( desc ) CATCH_SECTION( std::string( " And: ") + desc )
  10201. #define CATCH_THEN( desc ) CATCH_SECTION( std::string( " Then: ") + desc )
  10202. #define CATCH_AND_THEN( desc ) CATCH_SECTION( std::string( " And: ") + desc )
  10203. // If CATCH_CONFIG_PREFIX_ALL is not defined then the CATCH_ prefix is not required
  10204. #else
  10205. #define REQUIRE( ... ) INTERNAL_CATCH_TEST( "REQUIRE", Catch::ResultDisposition::Normal, __VA_ARGS__ )
  10206. #define REQUIRE_FALSE( ... ) INTERNAL_CATCH_TEST( "REQUIRE_FALSE", Catch::ResultDisposition::Normal | Catch::ResultDisposition::FalseTest, __VA_ARGS__ )
  10207. #define REQUIRE_THROWS( ... ) INTERNAL_CATCH_THROWS( "REQUIRE_THROWS", Catch::ResultDisposition::Normal, __VA_ARGS__ )
  10208. #define REQUIRE_THROWS_AS( expr, exceptionType ) INTERNAL_CATCH_THROWS_AS( "REQUIRE_THROWS_AS", exceptionType, Catch::ResultDisposition::Normal, expr )
  10209. #define REQUIRE_THROWS_WITH( expr, matcher ) INTERNAL_CATCH_THROWS_STR_MATCHES( "REQUIRE_THROWS_WITH", Catch::ResultDisposition::Normal, matcher, expr )
  10210. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  10211. #define REQUIRE_THROWS_MATCHES( expr, exceptionType, matcher ) INTERNAL_CATCH_THROWS_MATCHES( "REQUIRE_THROWS_MATCHES", exceptionType, Catch::ResultDisposition::Normal, matcher, expr )
  10212. #endif // CATCH_CONFIG_DISABLE_MATCHERS
  10213. #define REQUIRE_NOTHROW( ... ) INTERNAL_CATCH_NO_THROW( "REQUIRE_NOTHROW", Catch::ResultDisposition::Normal, __VA_ARGS__ )
  10214. #define CHECK( ... ) INTERNAL_CATCH_TEST( "CHECK", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  10215. #define CHECK_FALSE( ... ) INTERNAL_CATCH_TEST( "CHECK_FALSE", Catch::ResultDisposition::ContinueOnFailure | Catch::ResultDisposition::FalseTest, __VA_ARGS__ )
  10216. #define CHECKED_IF( ... ) INTERNAL_CATCH_IF( "CHECKED_IF", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  10217. #define CHECKED_ELSE( ... ) INTERNAL_CATCH_ELSE( "CHECKED_ELSE", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  10218. #define CHECK_NOFAIL( ... ) INTERNAL_CATCH_TEST( "CHECK_NOFAIL", Catch::ResultDisposition::ContinueOnFailure | Catch::ResultDisposition::SuppressFail, __VA_ARGS__ )
  10219. #define CHECK_THROWS( ... ) INTERNAL_CATCH_THROWS( "CHECK_THROWS", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  10220. #define CHECK_THROWS_AS( expr, exceptionType ) INTERNAL_CATCH_THROWS_AS( "CHECK_THROWS_AS", exceptionType, Catch::ResultDisposition::ContinueOnFailure, expr )
  10221. #define CHECK_THROWS_WITH( expr, matcher ) INTERNAL_CATCH_THROWS_STR_MATCHES( "CHECK_THROWS_WITH", Catch::ResultDisposition::ContinueOnFailure, matcher, expr )
  10222. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  10223. #define CHECK_THROWS_MATCHES( expr, exceptionType, matcher ) INTERNAL_CATCH_THROWS_MATCHES( "CHECK_THROWS_MATCHES", exceptionType, Catch::ResultDisposition::ContinueOnFailure, matcher, expr )
  10224. #endif // CATCH_CONFIG_DISABLE_MATCHERS
  10225. #define CHECK_NOTHROW( ... ) INTERNAL_CATCH_NO_THROW( "CHECK_NOTHROW", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  10226. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  10227. #define CHECK_THAT( arg, matcher ) INTERNAL_CHECK_THAT( "CHECK_THAT", matcher, Catch::ResultDisposition::ContinueOnFailure, arg )
  10228. #define REQUIRE_THAT( arg, matcher ) INTERNAL_CHECK_THAT( "REQUIRE_THAT", matcher, Catch::ResultDisposition::Normal, arg )
  10229. #endif // CATCH_CONFIG_DISABLE_MATCHERS
  10230. #define INFO( msg ) INTERNAL_CATCH_INFO( "INFO", msg )
  10231. #define WARN( msg ) INTERNAL_CATCH_MSG( "WARN", Catch::ResultWas::Warning, Catch::ResultDisposition::ContinueOnFailure, msg )
  10232. #define CAPTURE( msg ) INTERNAL_CATCH_INFO( "CAPTURE", #msg " := " << ::Catch::Detail::stringify(msg) )
  10233. #define TEST_CASE( ... ) INTERNAL_CATCH_TESTCASE( __VA_ARGS__ )
  10234. #define TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEST_CASE_METHOD( className, __VA_ARGS__ )
  10235. #define METHOD_AS_TEST_CASE( method, ... ) INTERNAL_CATCH_METHOD_AS_TEST_CASE( method, __VA_ARGS__ )
  10236. #define REGISTER_TEST_CASE( Function, ... ) INTERNAL_CATCH_REGISTER_TESTCASE( Function, __VA_ARGS__ )
  10237. #define SECTION( ... ) INTERNAL_CATCH_SECTION( __VA_ARGS__ )
  10238. #define FAIL( ... ) INTERNAL_CATCH_MSG( "FAIL", Catch::ResultWas::ExplicitFailure, Catch::ResultDisposition::Normal, __VA_ARGS__ )
  10239. #define FAIL_CHECK( ... ) INTERNAL_CATCH_MSG( "FAIL_CHECK", Catch::ResultWas::ExplicitFailure, Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  10240. #define SUCCEED( ... ) INTERNAL_CATCH_MSG( "SUCCEED", Catch::ResultWas::Ok, Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  10241. #define ANON_TEST_CASE() INTERNAL_CATCH_TESTCASE()
  10242. #endif
  10243. #define CATCH_TRANSLATE_EXCEPTION( signature ) INTERNAL_CATCH_TRANSLATE_EXCEPTION( signature )
  10244. // "BDD-style" convenience wrappers
  10245. #define SCENARIO( ... ) TEST_CASE( "Scenario: " __VA_ARGS__ )
  10246. #define SCENARIO_METHOD( className, ... ) INTERNAL_CATCH_TEST_CASE_METHOD( className, "Scenario: " __VA_ARGS__ )
  10247. #define GIVEN( desc ) SECTION( std::string(" Given: ") + desc )
  10248. #define WHEN( desc ) SECTION( std::string(" When: ") + desc )
  10249. #define AND_WHEN( desc ) SECTION( std::string("And when: ") + desc )
  10250. #define THEN( desc ) SECTION( std::string(" Then: ") + desc )
  10251. #define AND_THEN( desc ) SECTION( std::string(" And: ") + desc )
  10252. using Catch::Detail::Approx;
  10253. #else
  10254. //////
  10255. // If this config identifier is defined then all CATCH macros are prefixed with CATCH_
  10256. #ifdef CATCH_CONFIG_PREFIX_ALL
  10257. #define CATCH_REQUIRE( ... ) (void)(0)
  10258. #define CATCH_REQUIRE_FALSE( ... ) (void)(0)
  10259. #define CATCH_REQUIRE_THROWS( ... ) (void)(0)
  10260. #define CATCH_REQUIRE_THROWS_AS( expr, exceptionType ) (void)(0)
  10261. #define CATCH_REQUIRE_THROWS_WITH( expr, matcher ) (void)(0)
  10262. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  10263. #define CATCH_REQUIRE_THROWS_MATCHES( expr, exceptionType, matcher ) (void)(0)
  10264. #endif// CATCH_CONFIG_DISABLE_MATCHERS
  10265. #define CATCH_REQUIRE_NOTHROW( ... ) (void)(0)
  10266. #define CATCH_CHECK( ... ) (void)(0)
  10267. #define CATCH_CHECK_FALSE( ... ) (void)(0)
  10268. #define CATCH_CHECKED_IF( ... ) if (__VA_ARGS__)
  10269. #define CATCH_CHECKED_ELSE( ... ) if (!(__VA_ARGS__))
  10270. #define CATCH_CHECK_NOFAIL( ... ) (void)(0)
  10271. #define CATCH_CHECK_THROWS( ... ) (void)(0)
  10272. #define CATCH_CHECK_THROWS_AS( expr, exceptionType ) (void)(0)
  10273. #define CATCH_CHECK_THROWS_WITH( expr, matcher ) (void)(0)
  10274. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  10275. #define CATCH_CHECK_THROWS_MATCHES( expr, exceptionType, matcher ) (void)(0)
  10276. #endif // CATCH_CONFIG_DISABLE_MATCHERS
  10277. #define CATCH_CHECK_NOTHROW( ... ) (void)(0)
  10278. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  10279. #define CATCH_CHECK_THAT( arg, matcher ) (void)(0)
  10280. #define CATCH_REQUIRE_THAT( arg, matcher ) (void)(0)
  10281. #endif // CATCH_CONFIG_DISABLE_MATCHERS
  10282. #define CATCH_INFO( msg ) (void)(0)
  10283. #define CATCH_WARN( msg ) (void)(0)
  10284. #define CATCH_CAPTURE( msg ) (void)(0)
  10285. #define CATCH_TEST_CASE( ... ) INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ))
  10286. #define CATCH_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ))
  10287. #define CATCH_METHOD_AS_TEST_CASE( method, ... )
  10288. #define CATCH_REGISTER_TEST_CASE( Function, ... ) (void)(0)
  10289. #define CATCH_SECTION( ... )
  10290. #define CATCH_FAIL( ... ) (void)(0)
  10291. #define CATCH_FAIL_CHECK( ... ) (void)(0)
  10292. #define CATCH_SUCCEED( ... ) (void)(0)
  10293. #define CATCH_ANON_TEST_CASE() INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ))
  10294. // "BDD-style" convenience wrappers
  10295. #define CATCH_SCENARIO( ... ) INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ))
  10296. #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 )
  10297. #define CATCH_GIVEN( desc )
  10298. #define CATCH_WHEN( desc )
  10299. #define CATCH_AND_WHEN( desc )
  10300. #define CATCH_THEN( desc )
  10301. #define CATCH_AND_THEN( desc )
  10302. // If CATCH_CONFIG_PREFIX_ALL is not defined then the CATCH_ prefix is not required
  10303. #else
  10304. #define REQUIRE( ... ) (void)(0)
  10305. #define REQUIRE_FALSE( ... ) (void)(0)
  10306. #define REQUIRE_THROWS( ... ) (void)(0)
  10307. #define REQUIRE_THROWS_AS( expr, exceptionType ) (void)(0)
  10308. #define REQUIRE_THROWS_WITH( expr, matcher ) (void)(0)
  10309. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  10310. #define REQUIRE_THROWS_MATCHES( expr, exceptionType, matcher ) (void)(0)
  10311. #endif // CATCH_CONFIG_DISABLE_MATCHERS
  10312. #define REQUIRE_NOTHROW( ... ) (void)(0)
  10313. #define CHECK( ... ) (void)(0)
  10314. #define CHECK_FALSE( ... ) (void)(0)
  10315. #define CHECKED_IF( ... ) if (__VA_ARGS__)
  10316. #define CHECKED_ELSE( ... ) if (!(__VA_ARGS__))
  10317. #define CHECK_NOFAIL( ... ) (void)(0)
  10318. #define CHECK_THROWS( ... ) (void)(0)
  10319. #define CHECK_THROWS_AS( expr, exceptionType ) (void)(0)
  10320. #define CHECK_THROWS_WITH( expr, matcher ) (void)(0)
  10321. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  10322. #define CHECK_THROWS_MATCHES( expr, exceptionType, matcher ) (void)(0)
  10323. #endif // CATCH_CONFIG_DISABLE_MATCHERS
  10324. #define CHECK_NOTHROW( ... ) (void)(0)
  10325. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  10326. #define CHECK_THAT( arg, matcher ) (void)(0)
  10327. #define REQUIRE_THAT( arg, matcher ) (void)(0)
  10328. #endif // CATCH_CONFIG_DISABLE_MATCHERS
  10329. #define INFO( msg ) (void)(0)
  10330. #define WARN( msg ) (void)(0)
  10331. #define CAPTURE( msg ) (void)(0)
  10332. #define TEST_CASE( ... ) INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ))
  10333. #define TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ))
  10334. #define METHOD_AS_TEST_CASE( method, ... )
  10335. #define REGISTER_TEST_CASE( Function, ... ) (void)(0)
  10336. #define SECTION( ... )
  10337. #define FAIL( ... ) (void)(0)
  10338. #define FAIL_CHECK( ... ) (void)(0)
  10339. #define SUCCEED( ... ) (void)(0)
  10340. #define ANON_TEST_CASE() INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ))
  10341. #endif
  10342. #define CATCH_TRANSLATE_EXCEPTION( signature ) INTERNAL_CATCH_TRANSLATE_EXCEPTION_NO_REG( INTERNAL_CATCH_UNIQUE_NAME( catch_internal_ExceptionTranslator ), signature )
  10343. // "BDD-style" convenience wrappers
  10344. #define SCENARIO( ... ) INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ) )
  10345. #define SCENARIO_METHOD( className, ... ) INTERNAL_CATCH_TESTCASE_METHOD_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ), className )
  10346. #define GIVEN( desc )
  10347. #define WHEN( desc )
  10348. #define AND_WHEN( desc )
  10349. #define THEN( desc )
  10350. #define AND_THEN( desc )
  10351. using Catch::Detail::Approx;
  10352. #endif
  10353. #endif // ! CATCH_CONFIG_IMPL_ONLY
  10354. // start catch_reenable_warnings.h
  10355. #ifdef __clang__
  10356. # ifdef __ICC // icpc defines the __clang__ macro
  10357. # pragma warning(pop)
  10358. # else
  10359. # pragma clang diagnostic pop
  10360. # endif
  10361. #elif defined __GNUC__
  10362. # pragma GCC diagnostic pop
  10363. #endif
  10364. // end catch_reenable_warnings.h
  10365. // end catch.hpp
  10366. #endif // TWOBLUECUBES_SINGLE_INCLUDE_CATCH_HPP_INCLUDED