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

11805 lines
399KB

  1. /*
  2. * Catch v2.0.0-develop.4
  3. * Generated: 2017-09-19 17:37:34.480115
  4. * ----------------------------------------------------------
  5. * This file has been merged from multiple headers. Please don't edit it directly
  6. * Copyright (c) 2017 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 "-Wglobal-constructors"
  26. # pragma clang diagnostic ignored "-Wvariadic-macros"
  27. # pragma clang diagnostic ignored "-Wc99-extensions"
  28. # pragma clang diagnostic ignored "-Wunused-variable"
  29. # pragma clang diagnostic push
  30. # pragma clang diagnostic ignored "-Wpadded"
  31. # pragma clang diagnostic ignored "-Wswitch-enum"
  32. # pragma clang diagnostic ignored "-Wcovered-switch-default"
  33. # endif
  34. #elif defined __GNUC__
  35. # pragma GCC diagnostic ignored "-Wvariadic-macros"
  36. # pragma GCC diagnostic ignored "-Wunused-variable"
  37. # pragma GCC diagnostic ignored "-Wparentheses"
  38. # pragma GCC diagnostic push
  39. # pragma GCC diagnostic ignored "-Wpadded"
  40. #endif
  41. // end catch_suppress_warnings.h
  42. #if defined(CATCH_CONFIG_MAIN) || defined(CATCH_CONFIG_RUNNER)
  43. # define CATCH_IMPL
  44. # define CATCH_CONFIG_EXTERNAL_INTERFACES
  45. # if defined(CATCH_CONFIG_DISABLE_MATCHERS)
  46. # undef CATCH_CONFIG_DISABLE_MATCHERS
  47. # endif
  48. #endif
  49. // start catch_platform.h
  50. #ifdef __APPLE__
  51. # include <TargetConditionals.h>
  52. # if TARGET_OS_MAC == 1
  53. # define CATCH_PLATFORM_MAC
  54. # elif TARGET_OS_IPHONE == 1
  55. # define CATCH_PLATFORM_IPHONE
  56. # endif
  57. #elif defined(linux) || defined(__linux) || defined(__linux__)
  58. # define CATCH_PLATFORM_LINUX
  59. #elif defined(WIN32) || defined(__WIN32__) || defined(_WIN32) || defined(_MSC_VER)
  60. # define CATCH_PLATFORM_WINDOWS
  61. #endif
  62. // end catch_platform.h
  63. #ifdef CATCH_IMPL
  64. # ifndef CLARA_CONFIG_MAIN
  65. # define CLARA_CONFIG_MAIN_NOT_DEFINED
  66. # define CLARA_CONFIG_MAIN
  67. # endif
  68. #endif
  69. // start catch_tag_alias_autoregistrar.h
  70. // start catch_common.h
  71. // start catch_compiler_capabilities.h
  72. // Detect a number of compiler features - by compiler
  73. // The following features are defined:
  74. //
  75. // CATCH_CONFIG_COUNTER : is the __COUNTER__ macro supported?
  76. // CATCH_CONFIG_WINDOWS_SEH : is Windows SEH supported?
  77. // CATCH_CONFIG_POSIX_SIGNALS : are POSIX signals supported?
  78. // ****************
  79. // Note to maintainers: if new toggles are added please document them
  80. // in configuration.md, too
  81. // ****************
  82. // In general each macro has a _NO_<feature name> form
  83. // (e.g. CATCH_CONFIG_NO_POSIX_SIGNALS) which disables the feature.
  84. // Many features, at point of detection, define an _INTERNAL_ macro, so they
  85. // can be combined, en-mass, with the _NO_ forms later.
  86. #ifdef __cplusplus
  87. # if __cplusplus >= 201402L
  88. # define CATCH_CPP14_OR_GREATER
  89. # endif
  90. #endif
  91. #ifdef __clang__
  92. # define CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
  93. _Pragma( "clang diagnostic push" ) \
  94. _Pragma( "clang diagnostic ignored \"-Wexit-time-destructors\"" ) \
  95. _Pragma( "clang diagnostic ignored \"-Wglobal-constructors\"")
  96. # define CATCH_INTERNAL_UNSUPPRESS_GLOBALS_WARNINGS \
  97. _Pragma( "clang diagnostic pop" )
  98. # define CATCH_INTERNAL_SUPPRESS_PARENTHESES_WARNINGS \
  99. _Pragma( "clang diagnostic push" ) \
  100. _Pragma( "clang diagnostic ignored \"-Wparentheses\"" )
  101. # define CATCH_INTERNAL_UNSUPPRESS_PARENTHESES_WARNINGS \
  102. _Pragma( "clang diagnostic pop" )
  103. #endif // __clang__
  104. ////////////////////////////////////////////////////////////////////////////////
  105. // We know some environments not to support full POSIX signals
  106. #if defined(__CYGWIN__) || defined(__QNX__)
  107. # if !defined(CATCH_CONFIG_POSIX_SIGNALS)
  108. # define CATCH_INTERNAL_CONFIG_NO_POSIX_SIGNALS
  109. # endif
  110. #endif
  111. #ifdef __OS400__
  112. # define CATCH_INTERNAL_CONFIG_NO_POSIX_SIGNALS
  113. # define CATCH_CONFIG_COLOUR_NONE
  114. #endif
  115. ////////////////////////////////////////////////////////////////////////////////
  116. // Cygwin
  117. #ifdef __CYGWIN__
  118. // Required for some versions of Cygwin to declare gettimeofday
  119. // see: http://stackoverflow.com/questions/36901803/gettimeofday-not-declared-in-this-scope-cygwin
  120. # define _BSD_SOURCE
  121. #endif // __CYGWIN__
  122. ////////////////////////////////////////////////////////////////////////////////
  123. // Visual C++
  124. #ifdef _MSC_VER
  125. // Universal Windows platform does not support SEH
  126. // Or console colours (or console at all...)
  127. # if (WINAPI_FAMILY == WINAPI_FAMILY_APP)
  128. # define CATCH_CONFIG_COLOUR_NONE
  129. # else
  130. # define CATCH_INTERNAL_CONFIG_WINDOWS_SEH
  131. # endif
  132. #endif // _MSC_VER
  133. ////////////////////////////////////////////////////////////////////////////////
  134. // All supported compilers support COUNTER macro,
  135. //but user still might want to turn it off
  136. #define CATCH_INTERNAL_CONFIG_COUNTER
  137. // Now set the actual defines based on the above + anything the user has configured
  138. // Use of __COUNTER__ is suppressed if __JETBRAINS_IDE__ is #defined (meaning we're being parsed by a JetBrains IDE for
  139. // analytics) because, at time of writing, __COUNTER__ is not properly handled by it.
  140. // This does not affect compilation
  141. #if defined(CATCH_INTERNAL_CONFIG_COUNTER) && !defined(CATCH_CONFIG_NO_COUNTER) && !defined(CATCH_CONFIG_COUNTER) && !defined(__JETBRAINS_IDE__)
  142. # define CATCH_CONFIG_COUNTER
  143. #endif
  144. #if defined(CATCH_INTERNAL_CONFIG_WINDOWS_SEH) && !defined(CATCH_CONFIG_NO_WINDOWS_SEH) && !defined(CATCH_CONFIG_WINDOWS_SEH)
  145. # define CATCH_CONFIG_WINDOWS_SEH
  146. #endif
  147. // This is set by default, because we assume that unix compilers are posix-signal-compatible by default.
  148. #if !defined(CATCH_INTERNAL_CONFIG_NO_POSIX_SIGNALS) && !defined(CATCH_CONFIG_NO_POSIX_SIGNALS) && !defined(CATCH_CONFIG_POSIX_SIGNALS)
  149. # define CATCH_CONFIG_POSIX_SIGNALS
  150. #endif
  151. #if !defined(CATCH_INTERNAL_SUPPRESS_PARENTHESES_WARNINGS)
  152. # define CATCH_INTERNAL_SUPPRESS_PARENTHESES_WARNINGS
  153. # define CATCH_INTERNAL_UNSUPPRESS_PARENTHESES_WARNINGS
  154. #endif
  155. #if !defined(CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS)
  156. # define CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS
  157. # define CATCH_INTERNAL_UNSUPPRESS_GLOBALS_WARNINGS
  158. #endif
  159. // end catch_compiler_capabilities.h
  160. #define INTERNAL_CATCH_UNIQUE_NAME_LINE2( name, line ) name##line
  161. #define INTERNAL_CATCH_UNIQUE_NAME_LINE( name, line ) INTERNAL_CATCH_UNIQUE_NAME_LINE2( name, line )
  162. #ifdef CATCH_CONFIG_COUNTER
  163. # define INTERNAL_CATCH_UNIQUE_NAME( name ) INTERNAL_CATCH_UNIQUE_NAME_LINE( name, __COUNTER__ )
  164. #else
  165. # define INTERNAL_CATCH_UNIQUE_NAME( name ) INTERNAL_CATCH_UNIQUE_NAME_LINE( name, __LINE__ )
  166. #endif
  167. #include <iosfwd>
  168. #include <string>
  169. #include <cstdint>
  170. namespace Catch {
  171. struct CaseSensitive { enum Choice {
  172. Yes,
  173. No
  174. }; };
  175. class NonCopyable {
  176. NonCopyable( NonCopyable const& ) = delete;
  177. NonCopyable( NonCopyable && ) = delete;
  178. NonCopyable& operator = ( NonCopyable const& ) = delete;
  179. NonCopyable& operator = ( NonCopyable && ) = delete;
  180. protected:
  181. NonCopyable();
  182. virtual ~NonCopyable();
  183. };
  184. struct SourceLineInfo {
  185. SourceLineInfo() = delete;
  186. SourceLineInfo( char const* _file, std::size_t _line ) noexcept;
  187. SourceLineInfo( SourceLineInfo const& other ) = default;
  188. SourceLineInfo( SourceLineInfo && ) = default;
  189. SourceLineInfo& operator = ( SourceLineInfo const& ) = default;
  190. SourceLineInfo& operator = ( SourceLineInfo && ) = default;
  191. bool empty() const noexcept;
  192. bool operator == ( SourceLineInfo const& other ) const noexcept;
  193. bool operator < ( SourceLineInfo const& other ) const noexcept;
  194. char const* file;
  195. std::size_t line;
  196. };
  197. std::ostream& operator << ( std::ostream& os, SourceLineInfo const& info );
  198. // This is just here to avoid compiler warnings with macro constants and boolean literals
  199. bool isTrue( bool value );
  200. bool alwaysTrue();
  201. bool alwaysFalse();
  202. // Use this in variadic streaming macros to allow
  203. // >> +StreamEndStop
  204. // as well as
  205. // >> stuff +StreamEndStop
  206. struct StreamEndStop {
  207. std::string operator+() const;
  208. };
  209. template<typename T>
  210. T const& operator + ( T const& value, StreamEndStop ) {
  211. return value;
  212. }
  213. }
  214. #define CATCH_INTERNAL_LINEINFO \
  215. ::Catch::SourceLineInfo( __FILE__, static_cast<std::size_t>( __LINE__ ) )
  216. // end catch_common.h
  217. namespace Catch {
  218. struct RegistrarForTagAliases {
  219. RegistrarForTagAliases( char const* alias, char const* tag, SourceLineInfo const& lineInfo );
  220. };
  221. } // end namespace Catch
  222. #define CATCH_REGISTER_TAG_ALIAS( alias, spec ) namespace{ Catch::RegistrarForTagAliases INTERNAL_CATCH_UNIQUE_NAME( AutoRegisterTagAlias )( alias, spec, CATCH_INTERNAL_LINEINFO ); }
  223. // end catch_tag_alias_autoregistrar.h
  224. // start catch_test_registry.h
  225. // start catch_interfaces_testcase.h
  226. #include <vector>
  227. #include <memory>
  228. namespace Catch {
  229. class TestSpec;
  230. struct ITestInvoker {
  231. virtual void invoke () const = 0;
  232. virtual ~ITestInvoker();
  233. };
  234. using ITestCasePtr = std::shared_ptr<ITestInvoker>;
  235. class TestCase;
  236. struct IConfig;
  237. struct ITestCaseRegistry {
  238. virtual ~ITestCaseRegistry();
  239. virtual std::vector<TestCase> const& getAllTests() const = 0;
  240. virtual std::vector<TestCase> const& getAllTestsSorted( IConfig const& config ) const = 0;
  241. };
  242. bool matchTest( TestCase const& testCase, TestSpec const& testSpec, IConfig const& config );
  243. std::vector<TestCase> filterTests( std::vector<TestCase> const& testCases, TestSpec const& testSpec, IConfig const& config );
  244. std::vector<TestCase> const& getAllTestCasesSorted( IConfig const& config );
  245. }
  246. // end catch_interfaces_testcase.h
  247. // start catch_stringref.h
  248. #include <cstddef>
  249. #include <string>
  250. #include <iosfwd>
  251. namespace Catch {
  252. class StringData;
  253. /// A non-owning string class (similar to the forthcoming std::string_view)
  254. /// Note that, because a StringRef may be a substring of another string,
  255. /// it may not be null terminated. c_str() must return a null terminated
  256. /// string, however, and so the StringRef will internally take ownership
  257. /// (taking a copy), if necessary. In theory this ownership is not externally
  258. /// visible - but it does mean (substring) StringRefs should not be shared between
  259. /// threads.
  260. class StringRef {
  261. friend struct StringRefTestAccess;
  262. using size_type = std::size_t;
  263. char const* m_start;
  264. size_type m_size;
  265. char* m_data = nullptr;
  266. void takeOwnership();
  267. public: // construction/ assignment
  268. StringRef() noexcept;
  269. StringRef( StringRef const& other ) noexcept;
  270. StringRef( StringRef&& other ) noexcept;
  271. StringRef( char const* rawChars ) noexcept;
  272. StringRef( char const* rawChars, size_type size ) noexcept;
  273. StringRef( std::string const& stdString ) noexcept;
  274. ~StringRef() noexcept;
  275. auto operator = ( StringRef other ) noexcept -> StringRef&;
  276. operator std::string() const;
  277. void swap( StringRef& other ) noexcept;
  278. public: // operators
  279. auto operator == ( StringRef const& other ) const noexcept -> bool;
  280. auto operator != ( StringRef const& other ) const noexcept -> bool;
  281. auto operator[] ( size_type index ) const noexcept -> char;
  282. public: // named queries
  283. auto empty() const noexcept -> bool;
  284. auto size() const noexcept -> size_type;
  285. auto numberOfCharacters() const noexcept -> size_type;
  286. auto c_str() const -> char const*;
  287. public: // substrings and searches
  288. auto substr( size_type start, size_type size ) const noexcept -> StringRef;
  289. private: // ownership queries - may not be consistent between calls
  290. auto isOwned() const noexcept -> bool;
  291. auto isSubstring() const noexcept -> bool;
  292. auto data() const noexcept -> char const*;
  293. };
  294. auto operator + ( StringRef const& lhs, StringRef const& rhs ) -> std::string;
  295. auto operator + ( StringRef const& lhs, char const* rhs ) -> std::string;
  296. auto operator + ( char const* lhs, StringRef const& rhs ) -> std::string;
  297. auto operator << ( std::ostream& os, StringRef const& sr ) -> std::ostream&;
  298. } // namespace Catch
  299. // end catch_stringref.h
  300. namespace Catch {
  301. template<typename C>
  302. class TestInvokerAsMethod : public ITestInvoker {
  303. void (C::*m_testAsMethod)();
  304. public:
  305. TestInvokerAsMethod( void (C::*testAsMethod)() ) noexcept : m_testAsMethod( testAsMethod ) {}
  306. void invoke() const override {
  307. C obj;
  308. (obj.*m_testAsMethod)();
  309. }
  310. };
  311. auto makeTestInvoker( void(*testAsFunction)() ) noexcept -> ITestInvoker*;
  312. template<typename C>
  313. auto makeTestInvoker( void (C::*testAsMethod)() ) noexcept -> ITestInvoker* {
  314. return new(std::nothrow) TestInvokerAsMethod<C>( testAsMethod );
  315. }
  316. struct NameAndTags {
  317. NameAndTags( StringRef name_ = "", StringRef tags_ = "" ) noexcept;
  318. StringRef name;
  319. StringRef tags;
  320. };
  321. struct AutoReg : NonCopyable {
  322. AutoReg( ITestInvoker* invoker, SourceLineInfo const& lineInfo, StringRef classOrMethod, NameAndTags const& nameAndTags ) noexcept;
  323. ~AutoReg();
  324. };
  325. } // end namespace Catch
  326. #if defined(CATCH_CONFIG_DISABLE)
  327. #define INTERNAL_CATCH_TESTCASE_NO_REGISTRATION( TestName, ... ) \
  328. static void TestName()
  329. #define INTERNAL_CATCH_TESTCASE_METHOD_NO_REGISTRATION( TestName, ClassName, ... ) \
  330. namespace{ \
  331. struct TestName : ClassName { \
  332. void test(); \
  333. }; \
  334. } \
  335. void TestName::test()
  336. #endif
  337. ///////////////////////////////////////////////////////////////////////////////
  338. #define INTERNAL_CATCH_TESTCASE2( TestName, ... ) \
  339. static void TestName(); \
  340. CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
  341. namespace{ Catch::AutoReg INTERNAL_CATCH_UNIQUE_NAME( autoRegistrar )( Catch::makeTestInvoker( &TestName ), CATCH_INTERNAL_LINEINFO, "", Catch::NameAndTags{ __VA_ARGS__ } ); } /* NOLINT */ \
  342. CATCH_INTERNAL_UNSUPPRESS_GLOBALS_WARNINGS \
  343. static void TestName()
  344. #define INTERNAL_CATCH_TESTCASE( ... ) \
  345. INTERNAL_CATCH_TESTCASE2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ), __VA_ARGS__ )
  346. ///////////////////////////////////////////////////////////////////////////////
  347. #define INTERNAL_CATCH_METHOD_AS_TEST_CASE( QualifiedMethod, ... ) \
  348. CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
  349. namespace{ Catch::AutoReg INTERNAL_CATCH_UNIQUE_NAME( autoRegistrar )( Catch::makeTestInvoker( &QualifiedMethod ), CATCH_INTERNAL_LINEINFO, "&" #QualifiedMethod, Catch::NameAndTags{ __VA_ARGS__ } ); } /* NOLINT */ \
  350. CATCH_INTERNAL_UNSUPPRESS_GLOBALS_WARNINGS
  351. ///////////////////////////////////////////////////////////////////////////////
  352. #define INTERNAL_CATCH_TEST_CASE_METHOD2( TestName, ClassName, ... )\
  353. CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
  354. namespace{ \
  355. struct TestName : ClassName{ \
  356. void test(); \
  357. }; \
  358. Catch::AutoReg INTERNAL_CATCH_UNIQUE_NAME( autoRegistrar ) ( Catch::makeTestInvoker( &TestName::test ), CATCH_INTERNAL_LINEINFO, #ClassName, Catch::NameAndTags{ __VA_ARGS__ } ); /* NOLINT */ \
  359. } \
  360. CATCH_INTERNAL_UNSUPPRESS_GLOBALS_WARNINGS \
  361. void TestName::test()
  362. #define INTERNAL_CATCH_TEST_CASE_METHOD( ClassName, ... ) \
  363. INTERNAL_CATCH_TEST_CASE_METHOD2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ), ClassName, __VA_ARGS__ )
  364. ///////////////////////////////////////////////////////////////////////////////
  365. #define INTERNAL_CATCH_REGISTER_TESTCASE( Function, ... ) \
  366. CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
  367. Catch::AutoReg INTERNAL_CATCH_UNIQUE_NAME( autoRegistrar )( Catch::makeTestInvoker( Function ), CATCH_INTERNAL_LINEINFO, "", Catch::NameAndTags{ __VA_ARGS__ } ); /* NOLINT */ \
  368. CATCH_INTERNAL_UNSUPPRESS_GLOBALS_WARNINGS
  369. // end catch_test_registry.h
  370. // start catch_capture.hpp
  371. // start catch_assertionhandler.h
  372. // start catch_decomposer.h
  373. // start catch_tostring.h
  374. #include <sstream>
  375. #include <vector>
  376. #include <cstddef>
  377. #include <tuple>
  378. #include <type_traits>
  379. #include <string>
  380. #ifdef __OBJC__
  381. // start catch_objc_arc.hpp
  382. #import <Foundation/Foundation.h>
  383. #ifdef __has_feature
  384. #define CATCH_ARC_ENABLED __has_feature(objc_arc)
  385. #else
  386. #define CATCH_ARC_ENABLED 0
  387. #endif
  388. void arcSafeRelease( NSObject* obj );
  389. id performOptionalSelector( id obj, SEL sel );
  390. #if !CATCH_ARC_ENABLED
  391. inline void arcSafeRelease( NSObject* obj ) {
  392. [obj release];
  393. }
  394. inline id performOptionalSelector( id obj, SEL sel ) {
  395. if( [obj respondsToSelector: sel] )
  396. return [obj performSelector: sel];
  397. return nil;
  398. }
  399. #define CATCH_UNSAFE_UNRETAINED
  400. #define CATCH_ARC_STRONG
  401. #else
  402. inline void arcSafeRelease( NSObject* ){}
  403. inline id performOptionalSelector( id obj, SEL sel ) {
  404. #ifdef __clang__
  405. #pragma clang diagnostic push
  406. #pragma clang diagnostic ignored "-Warc-performSelector-leaks"
  407. #endif
  408. if( [obj respondsToSelector: sel] )
  409. return [obj performSelector: sel];
  410. #ifdef __clang__
  411. #pragma clang diagnostic pop
  412. #endif
  413. return nil;
  414. }
  415. #define CATCH_UNSAFE_UNRETAINED __unsafe_unretained
  416. #define CATCH_ARC_STRONG __strong
  417. #endif
  418. // end catch_objc_arc.hpp
  419. #endif
  420. #ifdef _MSC_VER
  421. #pragma warning(push)
  422. #pragma warning(disable:4180) // We attempt to stream a function (address) by const&, which MSVC complains about but is harmless
  423. #endif
  424. // We need a dummy global operator<< so we can bring it into Catch namespace later
  425. struct Catch_global_namespace_dummy;
  426. std::ostream& operator<<(std::ostream&, Catch_global_namespace_dummy);
  427. namespace Catch {
  428. // Bring in operator<< from global namespace into Catch namespace
  429. using ::operator<<;
  430. namespace Detail {
  431. extern const std::string unprintableString;
  432. std::string rawMemoryToString( const void *object, std::size_t size );
  433. template<typename T>
  434. std::string rawMemoryToString( const T& object ) {
  435. return rawMemoryToString( &object, sizeof(object) );
  436. }
  437. template<typename T>
  438. class IsStreamInsertable {
  439. template<typename SS, typename TT>
  440. static auto test(int)
  441. -> decltype(std::declval<SS&>() << std::declval<TT>(), std::true_type());
  442. template<typename, typename>
  443. static auto test(...)->std::false_type;
  444. public:
  445. static const bool value = decltype(test<std::ostream, const T&>(0))::value;
  446. };
  447. } // namespace Detail
  448. // If we decide for C++14, change these to enable_if_ts
  449. template <typename T>
  450. struct StringMaker {
  451. template <typename Fake = T>
  452. static
  453. typename std::enable_if<::Catch::Detail::IsStreamInsertable<Fake>::value, std::string>::type
  454. convert(const Fake& t) {
  455. std::ostringstream sstr;
  456. sstr << t;
  457. return sstr.str();
  458. }
  459. template <typename Fake = T>
  460. static
  461. typename std::enable_if<!::Catch::Detail::IsStreamInsertable<Fake>::value, std::string>::type
  462. convert(const Fake&) {
  463. return Detail::unprintableString;
  464. }
  465. };
  466. namespace Detail {
  467. // This function dispatches all stringification requests inside of Catch.
  468. // Should be preferably called fully qualified, like ::Catch::Detail::stringify
  469. template <typename T>
  470. std::string stringify(const T& e) {
  471. return ::Catch::StringMaker<typename std::remove_cv<typename std::remove_reference<T>::type>::type>::convert(e);
  472. }
  473. } // namespace Detail
  474. // Some predefined specializations
  475. template<>
  476. struct StringMaker<std::string> {
  477. static std::string convert(const std::string& str);
  478. };
  479. template<>
  480. struct StringMaker<std::wstring> {
  481. static std::string convert(const std::wstring& wstr);
  482. };
  483. template<>
  484. struct StringMaker<char const *> {
  485. static std::string convert(char const * str);
  486. };
  487. template<>
  488. struct StringMaker<char *> {
  489. static std::string convert(char * str);
  490. };
  491. template<>
  492. struct StringMaker<wchar_t const *> {
  493. static std::string convert(wchar_t const * str);
  494. };
  495. template<>
  496. struct StringMaker<wchar_t *> {
  497. static std::string convert(wchar_t * str);
  498. };
  499. template<int SZ>
  500. struct StringMaker<char[SZ]> {
  501. static std::string convert(const char* str) {
  502. return ::Catch::Detail::stringify(std::string{ str });
  503. }
  504. };
  505. template<int SZ>
  506. struct StringMaker<signed char[SZ]> {
  507. static std::string convert(const char* str) {
  508. return ::Catch::Detail::stringify(std::string{ str });
  509. }
  510. };
  511. template<int SZ>
  512. struct StringMaker<unsigned char[SZ]> {
  513. static std::string convert(const char* str) {
  514. return ::Catch::Detail::stringify(std::string{ str });
  515. }
  516. };
  517. template<>
  518. struct StringMaker<int> {
  519. static std::string convert(int value);
  520. };
  521. template<>
  522. struct StringMaker<long> {
  523. static std::string convert(long value);
  524. };
  525. template<>
  526. struct StringMaker<long long> {
  527. static std::string convert(long long value);
  528. };
  529. template<>
  530. struct StringMaker<unsigned int> {
  531. static std::string convert(unsigned int value);
  532. };
  533. template<>
  534. struct StringMaker<unsigned long> {
  535. static std::string convert(unsigned long value);
  536. };
  537. template<>
  538. struct StringMaker<unsigned long long> {
  539. static std::string convert(unsigned long long value);
  540. };
  541. template<>
  542. struct StringMaker<bool> {
  543. static std::string convert(bool b);
  544. };
  545. template<>
  546. struct StringMaker<char> {
  547. static std::string convert(char c);
  548. };
  549. template<>
  550. struct StringMaker<signed char> {
  551. static std::string convert(signed char c);
  552. };
  553. template<>
  554. struct StringMaker<unsigned char> {
  555. static std::string convert(unsigned char c);
  556. };
  557. template<>
  558. struct StringMaker<std::nullptr_t> {
  559. static std::string convert(std::nullptr_t);
  560. };
  561. template<>
  562. struct StringMaker<float> {
  563. static std::string convert(float value);
  564. };
  565. template<>
  566. struct StringMaker<double> {
  567. static std::string convert(double value);
  568. };
  569. template <typename T>
  570. struct StringMaker<T*> {
  571. template <typename U>
  572. static std::string convert(U* p) {
  573. if (p) {
  574. return ::Catch::Detail::rawMemoryToString(p);
  575. } else {
  576. return "nullptr";
  577. }
  578. }
  579. };
  580. template <typename R, typename C>
  581. struct StringMaker<R C::*> {
  582. static std::string convert(R C::* p) {
  583. if (p) {
  584. return ::Catch::Detail::rawMemoryToString(p);
  585. } else {
  586. return "nullptr";
  587. }
  588. }
  589. };
  590. namespace Detail {
  591. template<typename InputIterator>
  592. std::string rangeToString(InputIterator first, InputIterator last) {
  593. std::ostringstream oss;
  594. oss << "{ ";
  595. if (first != last) {
  596. oss << ::Catch::Detail::stringify(*first);
  597. for (++first; first != last; ++first)
  598. oss << ", " << ::Catch::Detail::stringify(*first);
  599. }
  600. oss << " }";
  601. return oss.str();
  602. }
  603. }
  604. template<typename T, typename Allocator>
  605. struct StringMaker<std::vector<T, Allocator> > {
  606. static std::string convert( std::vector<T,Allocator> const& v ) {
  607. return ::Catch::Detail::rangeToString( v.begin(), v.end() );
  608. }
  609. };
  610. // === Pair ===
  611. template<typename T1, typename T2>
  612. struct StringMaker<std::pair<T1, T2> > {
  613. static std::string convert(const std::pair<T1, T2>& pair) {
  614. std::ostringstream oss;
  615. oss << "{ "
  616. << ::Catch::Detail::stringify(pair.first)
  617. << ", "
  618. << ::Catch::Detail::stringify(pair.second)
  619. << " }";
  620. return oss.str();
  621. }
  622. };
  623. namespace Detail {
  624. template<
  625. typename Tuple,
  626. std::size_t N = 0,
  627. bool = (N < std::tuple_size<Tuple>::value)
  628. >
  629. struct TupleElementPrinter {
  630. static void print(const Tuple& tuple, std::ostream& os) {
  631. os << (N ? ", " : " ")
  632. << ::Catch::Detail::stringify(std::get<N>(tuple));
  633. TupleElementPrinter<Tuple, N + 1>::print(tuple, os);
  634. }
  635. };
  636. template<
  637. typename Tuple,
  638. std::size_t N
  639. >
  640. struct TupleElementPrinter<Tuple, N, false> {
  641. static void print(const Tuple&, std::ostream&) {}
  642. };
  643. }
  644. template<typename ...Types>
  645. struct StringMaker<std::tuple<Types...>> {
  646. static std::string convert(const std::tuple<Types...>& tuple) {
  647. std::ostringstream os;
  648. os << '{';
  649. Detail::TupleElementPrinter<std::tuple<Types...>>::print(tuple, os);
  650. os << " }";
  651. return os.str();
  652. }
  653. };
  654. template<typename T>
  655. struct EnumStringMaker {
  656. static std::string convert(const T& t) {
  657. return ::Catch::Detail::stringify(static_cast<typename std::underlying_type<T>::type>(t));
  658. }
  659. };
  660. #ifdef __OBJC__
  661. template<>
  662. struct StringMaker<NSString*> {
  663. static std::string convert(NSString * nsstring) {
  664. if (!nsstring)
  665. return "nil";
  666. return std::string("@") + [nsstring UTF8String];
  667. }
  668. };
  669. template<>
  670. struct StringMaker<NSObject*> {
  671. static std::string convert(NSObject* nsObject) {
  672. return ::Catch::Detail::stringify([nsObject description]);
  673. }
  674. };
  675. namespace Detail {
  676. inline std::string stringify( NSString* nsstring ) {
  677. return StringMaker<NSString*>::convert( nsstring );
  678. }
  679. } // namespace Detail
  680. #endif // __OBJC__
  681. } // namespace Catch
  682. #ifdef _MSC_VER
  683. #pragma warning(pop)
  684. #endif
  685. // end catch_tostring.h
  686. #include <ostream>
  687. #ifdef _MSC_VER
  688. #pragma warning(push)
  689. #pragma warning(disable:4389) // '==' : signed/unsigned mismatch
  690. #pragma warning(disable:4018) // more "signed/unsigned mismatch"
  691. #pragma warning(disable:4312) // Converting int to T* using reinterpret_cast (issue on x64 platform)
  692. #pragma warning(disable:4180) // qualifier applied to function type has no meaning
  693. #endif
  694. namespace Catch {
  695. struct ITransientExpression {
  696. virtual auto isBinaryExpression() const -> bool = 0;
  697. virtual auto getResult() const -> bool = 0;
  698. virtual void streamReconstructedExpression( std::ostream &os ) const = 0;
  699. // We don't actually need a virtual destructore, but many static analysers
  700. // complain if it's not here :-(
  701. virtual ~ITransientExpression();
  702. };
  703. void formatReconstructedExpression( std::ostream &os, std::string const& lhs, StringRef op, std::string const& rhs );
  704. template<typename LhsT, typename RhsT>
  705. class BinaryExpr : public ITransientExpression {
  706. bool m_result;
  707. LhsT m_lhs;
  708. StringRef m_op;
  709. RhsT m_rhs;
  710. auto isBinaryExpression() const -> bool override { return true; }
  711. auto getResult() const -> bool override { return m_result; }
  712. void streamReconstructedExpression( std::ostream &os ) const override {
  713. formatReconstructedExpression
  714. ( os, Catch::Detail::stringify( m_lhs ), m_op, Catch::Detail::stringify( m_rhs ) );
  715. }
  716. public:
  717. BinaryExpr( bool comparisonResult, LhsT lhs, StringRef op, RhsT rhs )
  718. : m_result( comparisonResult ),
  719. m_lhs( lhs ),
  720. m_op( op ),
  721. m_rhs( rhs )
  722. {}
  723. };
  724. template<typename LhsT>
  725. class UnaryExpr : public ITransientExpression {
  726. LhsT m_lhs;
  727. auto isBinaryExpression() const -> bool override { return false; }
  728. auto getResult() const -> bool override { return m_lhs ? true : false; }
  729. void streamReconstructedExpression( std::ostream &os ) const override {
  730. os << Catch::Detail::stringify( m_lhs );
  731. }
  732. public:
  733. UnaryExpr( LhsT lhs ) : m_lhs( lhs ) {}
  734. };
  735. // Specialised comparison functions to handle equality comparisons between ints and pointers (NULL deduces as an int)
  736. template<typename LhsT, typename RhsT>
  737. auto compareEqual( LhsT const& lhs, RhsT&& rhs ) -> bool { return lhs == rhs; };
  738. template<typename T>
  739. auto compareEqual( T* const& lhs, int rhs ) -> bool { return lhs == reinterpret_cast<void const*>( rhs ); }
  740. template<typename T>
  741. auto compareEqual( T* const& lhs, long rhs ) -> bool { return lhs == reinterpret_cast<void const*>( rhs ); }
  742. template<typename T>
  743. auto compareEqual( int lhs, T* const& rhs ) -> bool { return reinterpret_cast<void const*>( lhs ) == rhs; }
  744. template<typename T>
  745. auto compareEqual( long lhs, T* const& rhs ) -> bool { return reinterpret_cast<void const*>( lhs ) == rhs; }
  746. template<typename LhsT, typename RhsT>
  747. auto compareNotEqual( LhsT const& lhs, RhsT&& rhs ) -> bool { return lhs != rhs; };
  748. template<typename T>
  749. auto compareNotEqual( T* const& lhs, int rhs ) -> bool { return lhs != reinterpret_cast<void const*>( rhs ); }
  750. template<typename T>
  751. auto compareNotEqual( T* const& lhs, long rhs ) -> bool { return lhs != reinterpret_cast<void const*>( rhs ); }
  752. template<typename T>
  753. auto compareNotEqual( int lhs, T* const& rhs ) -> bool { return reinterpret_cast<void const*>( lhs ) != rhs; }
  754. template<typename T>
  755. auto compareNotEqual( long lhs, T* const& rhs ) -> bool { return reinterpret_cast<void const*>( lhs ) != rhs; }
  756. template<typename LhsT>
  757. class ExprLhs {
  758. LhsT m_lhs;
  759. public:
  760. ExprLhs( LhsT lhs ) : m_lhs( lhs ) {}
  761. template<typename RhsT>
  762. auto operator == ( RhsT&& rhs ) -> BinaryExpr<LhsT, RhsT&> const {
  763. return BinaryExpr<LhsT, RhsT&>( compareEqual( m_lhs, rhs ), m_lhs, "==", rhs );
  764. }
  765. auto operator == ( bool rhs ) -> BinaryExpr<LhsT, bool> const {
  766. return BinaryExpr<LhsT, bool>( m_lhs == rhs, m_lhs, "==", rhs );
  767. }
  768. template<typename RhsT>
  769. auto operator != ( RhsT&& rhs ) -> BinaryExpr<LhsT, RhsT&> const {
  770. return BinaryExpr<LhsT, RhsT&>( compareNotEqual( m_lhs, rhs ), m_lhs, "!=", rhs );
  771. }
  772. auto operator != ( bool rhs ) -> BinaryExpr<LhsT, bool> const {
  773. return BinaryExpr<LhsT, bool>( m_lhs != rhs, m_lhs, "!=", rhs );
  774. }
  775. template<typename RhsT>
  776. auto operator > ( RhsT&& rhs ) -> BinaryExpr<LhsT, RhsT&> const {
  777. return BinaryExpr<LhsT, RhsT&>( m_lhs > rhs, m_lhs, ">", rhs );
  778. }
  779. template<typename RhsT>
  780. auto operator < ( RhsT&& rhs ) -> BinaryExpr<LhsT, RhsT&> const {
  781. return BinaryExpr<LhsT, RhsT&>( m_lhs < rhs, m_lhs, "<", rhs );
  782. }
  783. template<typename RhsT>
  784. auto operator >= ( RhsT&& rhs ) -> BinaryExpr<LhsT, RhsT&> const {
  785. return BinaryExpr<LhsT, RhsT&>( m_lhs >= rhs, m_lhs, ">=", rhs );
  786. }
  787. template<typename RhsT>
  788. auto operator <= ( RhsT&& rhs ) -> BinaryExpr<LhsT, RhsT&> const {
  789. return BinaryExpr<LhsT, RhsT&>( m_lhs <= rhs, m_lhs, "<=", rhs );
  790. }
  791. auto makeUnaryExpr() const -> UnaryExpr<LhsT> {
  792. return UnaryExpr<LhsT>( m_lhs );
  793. }
  794. };
  795. void handleExpression( ITransientExpression const& expr );
  796. template<typename T>
  797. void handleExpression( ExprLhs<T> const& expr ) {
  798. handleExpression( expr.makeUnaryExpr() );
  799. }
  800. struct Decomposer {
  801. template<typename T>
  802. auto operator <= ( T const& lhs ) -> ExprLhs<T const&> {
  803. return ExprLhs<T const&>( lhs );
  804. }
  805. auto operator <=( bool value ) -> ExprLhs<bool> {
  806. return ExprLhs<bool>( value );
  807. }
  808. };
  809. } // end namespace Catch
  810. // end catch_decomposer.h
  811. // start catch_assertioninfo.h
  812. // start catch_result_type.h
  813. namespace Catch {
  814. // ResultWas::OfType enum
  815. struct ResultWas { enum OfType {
  816. Unknown = -1,
  817. Ok = 0,
  818. Info = 1,
  819. Warning = 2,
  820. FailureBit = 0x10,
  821. ExpressionFailed = FailureBit | 1,
  822. ExplicitFailure = FailureBit | 2,
  823. Exception = 0x100 | FailureBit,
  824. ThrewException = Exception | 1,
  825. DidntThrowException = Exception | 2,
  826. FatalErrorCondition = 0x200 | FailureBit
  827. }; };
  828. bool isOk( ResultWas::OfType resultType );
  829. bool isJustInfo( int flags );
  830. // ResultDisposition::Flags enum
  831. struct ResultDisposition { enum Flags {
  832. Normal = 0x01,
  833. ContinueOnFailure = 0x02, // Failures fail test, but execution continues
  834. FalseTest = 0x04, // Prefix expression with !
  835. SuppressFail = 0x08 // Failures are reported but do not fail the test
  836. }; };
  837. ResultDisposition::Flags operator | ( ResultDisposition::Flags lhs, ResultDisposition::Flags rhs );
  838. bool shouldContinueOnFailure( int flags );
  839. bool isFalseTest( int flags );
  840. bool shouldSuppressFailure( int flags );
  841. } // end namespace Catch
  842. // end catch_result_type.h
  843. namespace Catch {
  844. struct AssertionInfo
  845. {
  846. StringRef macroName;
  847. SourceLineInfo lineInfo;
  848. StringRef capturedExpression;
  849. ResultDisposition::Flags resultDisposition;
  850. // We want to delete this constructor but a compiler bug in 4.8 means
  851. // the struct is then treated as non-aggregate
  852. //AssertionInfo() = delete;
  853. };
  854. } // end namespace Catch
  855. // end catch_assertioninfo.h
  856. namespace Catch {
  857. struct TestFailureException{};
  858. struct AssertionResultData;
  859. class LazyExpression {
  860. friend class AssertionHandler;
  861. friend struct AssertionStats;
  862. ITransientExpression const* m_transientExpression = nullptr;
  863. bool m_isNegated;
  864. public:
  865. LazyExpression( bool isNegated );
  866. LazyExpression( LazyExpression const& other );
  867. LazyExpression& operator = ( LazyExpression const& ) = delete;
  868. explicit operator bool() const;
  869. friend auto operator << ( std::ostream& os, LazyExpression const& lazyExpr ) -> std::ostream&;
  870. };
  871. class AssertionHandler {
  872. AssertionInfo m_assertionInfo;
  873. bool m_shouldDebugBreak = false;
  874. bool m_shouldThrow = false;
  875. bool m_inExceptionGuard = false;
  876. public:
  877. AssertionHandler
  878. ( StringRef macroName,
  879. SourceLineInfo const& lineInfo,
  880. StringRef capturedExpression,
  881. ResultDisposition::Flags resultDisposition );
  882. ~AssertionHandler();
  883. void handle( ITransientExpression const& expr );
  884. template<typename T>
  885. void handle( ExprLhs<T> const& expr ) {
  886. handle( expr.makeUnaryExpr() );
  887. }
  888. void handle( ResultWas::OfType resultType );
  889. void handle( ResultWas::OfType resultType, StringRef const& message );
  890. void handle( ResultWas::OfType resultType, ITransientExpression const* expr, bool negated );
  891. void handle( AssertionResultData const& resultData, ITransientExpression const* expr );
  892. auto shouldDebugBreak() const -> bool;
  893. auto allowThrows() const -> bool;
  894. void reactWithDebugBreak() const;
  895. void reactWithoutDebugBreak() const;
  896. void useActiveException();
  897. void setExceptionGuard();
  898. void unsetExceptionGuard();
  899. };
  900. void handleExceptionMatchExpr( AssertionHandler& handler, std::string const& str, StringRef matcherString );
  901. } // namespace Catch
  902. // end catch_assertionhandler.h
  903. // start catch_message.h
  904. #include <string>
  905. #include <sstream>
  906. namespace Catch {
  907. struct MessageInfo {
  908. MessageInfo( std::string const& _macroName,
  909. SourceLineInfo const& _lineInfo,
  910. ResultWas::OfType _type );
  911. std::string macroName;
  912. std::string message;
  913. SourceLineInfo lineInfo;
  914. ResultWas::OfType type;
  915. unsigned int sequence;
  916. bool operator == ( MessageInfo const& other ) const;
  917. bool operator < ( MessageInfo const& other ) const;
  918. private:
  919. static unsigned int globalCount;
  920. };
  921. struct MessageStream {
  922. template<typename T>
  923. MessageStream& operator << ( T const& value ) {
  924. m_stream << value;
  925. return *this;
  926. }
  927. // !TBD reuse a global/ thread-local stream
  928. std::ostringstream m_stream;
  929. };
  930. struct MessageBuilder : MessageStream {
  931. MessageBuilder( std::string const& macroName,
  932. SourceLineInfo const& lineInfo,
  933. ResultWas::OfType type );
  934. template<typename T>
  935. MessageBuilder& operator << ( T const& value ) {
  936. m_stream << value;
  937. return *this;
  938. }
  939. MessageInfo m_info;
  940. };
  941. class ScopedMessage {
  942. public:
  943. ScopedMessage( MessageBuilder const& builder );
  944. ~ScopedMessage();
  945. MessageInfo m_info;
  946. };
  947. } // end namespace Catch
  948. // end catch_message.h
  949. // start catch_interfaces_capture.h
  950. #include <string>
  951. namespace Catch {
  952. class AssertionResult;
  953. struct AssertionInfo;
  954. struct SectionInfo;
  955. struct SectionEndInfo;
  956. struct MessageInfo;
  957. struct Counts;
  958. struct BenchmarkInfo;
  959. struct BenchmarkStats;
  960. struct IResultCapture {
  961. virtual ~IResultCapture();
  962. virtual void assertionStarting( AssertionInfo const& info ) = 0;
  963. virtual void assertionEnded( AssertionResult const& result ) = 0;
  964. virtual bool sectionStarted( SectionInfo const& sectionInfo,
  965. Counts& assertions ) = 0;
  966. virtual void sectionEnded( SectionEndInfo const& endInfo ) = 0;
  967. virtual void sectionEndedEarly( SectionEndInfo const& endInfo ) = 0;
  968. virtual void benchmarkStarting( BenchmarkInfo const& info ) = 0;
  969. virtual void benchmarkEnded( BenchmarkStats const& stats ) = 0;
  970. virtual void pushScopedMessage( MessageInfo const& message ) = 0;
  971. virtual void popScopedMessage( MessageInfo const& message ) = 0;
  972. virtual std::string getCurrentTestName() const = 0;
  973. virtual const AssertionResult* getLastResult() const = 0;
  974. virtual void exceptionEarlyReported() = 0;
  975. virtual void handleFatalErrorCondition( StringRef message ) = 0;
  976. virtual bool lastAssertionPassed() = 0;
  977. virtual void assertionPassed() = 0;
  978. virtual void assertionRun() = 0;
  979. };
  980. IResultCapture& getResultCapture();
  981. }
  982. // end catch_interfaces_capture.h
  983. // start catch_debugger.h
  984. namespace Catch {
  985. bool isDebuggerActive();
  986. }
  987. #ifdef CATCH_PLATFORM_MAC
  988. #define CATCH_TRAP() __asm__("int $3\n" : : ) /* NOLINT */
  989. #elif defined(CATCH_PLATFORM_LINUX)
  990. // If we can use inline assembler, do it because this allows us to break
  991. // directly at the location of the failing check instead of breaking inside
  992. // raise() called from it, i.e. one stack frame below.
  993. #if defined(__GNUC__) && (defined(__i386) || defined(__x86_64))
  994. #define CATCH_TRAP() asm volatile ("int $3") /* NOLINT */
  995. #else // Fall back to the generic way.
  996. #include <signal.h>
  997. #define CATCH_TRAP() raise(SIGTRAP)
  998. #endif
  999. #elif defined(_MSC_VER)
  1000. #define CATCH_TRAP() __debugbreak()
  1001. #elif defined(__MINGW32__)
  1002. extern "C" __declspec(dllimport) void __stdcall DebugBreak();
  1003. #define CATCH_TRAP() DebugBreak()
  1004. #endif
  1005. #ifdef CATCH_TRAP
  1006. #define CATCH_BREAK_INTO_DEBUGGER() if( Catch::isDebuggerActive() ) { CATCH_TRAP(); }
  1007. #else
  1008. #define CATCH_BREAK_INTO_DEBUGGER() Catch::alwaysTrue();
  1009. #endif
  1010. // end catch_debugger.h
  1011. #if !defined(CATCH_CONFIG_DISABLE)
  1012. #if !defined(CATCH_CONFIG_DISABLE_STRINGIFICATION)
  1013. #define CATCH_INTERNAL_STRINGIFY(...) #__VA_ARGS__
  1014. #else
  1015. #define CATCH_INTERNAL_STRINGIFY(...) "Disabled by CATCH_CONFIG_DISABLE_STRINGIFICATION"
  1016. #endif
  1017. #if defined(CATCH_CONFIG_FAST_COMPILE)
  1018. ///////////////////////////////////////////////////////////////////////////////
  1019. // We can speedup compilation significantly by breaking into debugger lower in
  1020. // the callstack, because then we don't have to expand CATCH_BREAK_INTO_DEBUGGER
  1021. // macro in each assertion
  1022. #define INTERNAL_CATCH_REACT( handler ) \
  1023. handler.reactWithDebugBreak();
  1024. ///////////////////////////////////////////////////////////////////////////////
  1025. // Another way to speed-up compilation is to omit local try-catch for REQUIRE*
  1026. // macros.
  1027. // This can potentially cause false negative, if the test code catches
  1028. // the exception before it propagates back up to the runner.
  1029. #define INTERNAL_CATCH_TRY( capturer ) capturer.setExceptionGuard();
  1030. #define INTERNAL_CATCH_CATCH( capturer ) capturer.unsetExceptionGuard();
  1031. #else // CATCH_CONFIG_FAST_COMPILE
  1032. ///////////////////////////////////////////////////////////////////////////////
  1033. // In the event of a failure works out if the debugger needs to be invoked
  1034. // and/or an exception thrown and takes appropriate action.
  1035. // This needs to be done as a macro so the debugger will stop in the user
  1036. // source code rather than in Catch library code
  1037. #define INTERNAL_CATCH_REACT( handler ) \
  1038. if( handler.shouldDebugBreak() ) CATCH_BREAK_INTO_DEBUGGER(); \
  1039. handler.reactWithoutDebugBreak();
  1040. #define INTERNAL_CATCH_TRY( capturer ) try
  1041. #define INTERNAL_CATCH_CATCH( capturer ) catch(...) { capturer.useActiveException(); }
  1042. #endif
  1043. ///////////////////////////////////////////////////////////////////////////////
  1044. #define INTERNAL_CATCH_TEST( macroName, resultDisposition, ... ) \
  1045. do { \
  1046. Catch::AssertionHandler catchAssertionHandler( macroName, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(__VA_ARGS__), resultDisposition ); \
  1047. INTERNAL_CATCH_TRY( catchAssertionHandler ) { \
  1048. CATCH_INTERNAL_SUPPRESS_PARENTHESES_WARNINGS \
  1049. catchAssertionHandler.handle( Catch::Decomposer() <= __VA_ARGS__ ); \
  1050. CATCH_INTERNAL_UNSUPPRESS_PARENTHESES_WARNINGS \
  1051. } INTERNAL_CATCH_CATCH( catchAssertionHandler ) \
  1052. INTERNAL_CATCH_REACT( catchAssertionHandler ) \
  1053. } while( Catch::isTrue( false && static_cast<bool>( !!(__VA_ARGS__) ) ) ) // the expression here is never evaluated at runtime but it forces the compiler to give it a look
  1054. // The double negation silences MSVC's C4800 warning, the static_cast forces short-circuit evaluation if the type has overloaded &&.
  1055. ///////////////////////////////////////////////////////////////////////////////
  1056. #define INTERNAL_CATCH_IF( macroName, resultDisposition, ... ) \
  1057. INTERNAL_CATCH_TEST( macroName, resultDisposition, __VA_ARGS__ ); \
  1058. if( Catch::getResultCapture().lastAssertionPassed() )
  1059. ///////////////////////////////////////////////////////////////////////////////
  1060. #define INTERNAL_CATCH_ELSE( macroName, resultDisposition, ... ) \
  1061. INTERNAL_CATCH_TEST( macroName, resultDisposition, __VA_ARGS__ ); \
  1062. if( !Catch::getResultCapture().lastAssertionPassed() )
  1063. ///////////////////////////////////////////////////////////////////////////////
  1064. #define INTERNAL_CATCH_NO_THROW( macroName, resultDisposition, ... ) \
  1065. do { \
  1066. Catch::AssertionHandler catchAssertionHandler( macroName, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(__VA_ARGS__), resultDisposition ); \
  1067. try { \
  1068. static_cast<void>(__VA_ARGS__); \
  1069. catchAssertionHandler.handle( Catch::ResultWas::Ok ); \
  1070. } \
  1071. catch( ... ) { \
  1072. catchAssertionHandler.useActiveException(); \
  1073. } \
  1074. INTERNAL_CATCH_REACT( catchAssertionHandler ) \
  1075. } while( Catch::alwaysFalse() )
  1076. ///////////////////////////////////////////////////////////////////////////////
  1077. #define INTERNAL_CATCH_THROWS( macroName, resultDisposition, ... ) \
  1078. do { \
  1079. Catch::AssertionHandler catchAssertionHandler( macroName, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(__VA_ARGS__), resultDisposition); \
  1080. if( catchAssertionHandler.allowThrows() ) \
  1081. try { \
  1082. static_cast<void>(__VA_ARGS__); \
  1083. catchAssertionHandler.handle( Catch::ResultWas::DidntThrowException ); \
  1084. } \
  1085. catch( ... ) { \
  1086. catchAssertionHandler.handle( Catch::ResultWas::Ok ); \
  1087. } \
  1088. else \
  1089. catchAssertionHandler.handle( Catch::ResultWas::Ok ); \
  1090. INTERNAL_CATCH_REACT( catchAssertionHandler ) \
  1091. } while( Catch::alwaysFalse() )
  1092. ///////////////////////////////////////////////////////////////////////////////
  1093. #define INTERNAL_CATCH_THROWS_AS( macroName, exceptionType, resultDisposition, expr ) \
  1094. do { \
  1095. Catch::AssertionHandler catchAssertionHandler( macroName, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(expr) ", " CATCH_INTERNAL_STRINGIFY(exceptionType), resultDisposition ); \
  1096. if( catchAssertionHandler.allowThrows() ) \
  1097. try { \
  1098. static_cast<void>(expr); \
  1099. catchAssertionHandler.handle( Catch::ResultWas::DidntThrowException ); \
  1100. } \
  1101. catch( exceptionType const& ) { \
  1102. catchAssertionHandler.handle( Catch::ResultWas::Ok ); \
  1103. } \
  1104. catch( ... ) { \
  1105. catchAssertionHandler.useActiveException(); \
  1106. } \
  1107. else \
  1108. catchAssertionHandler.handle( Catch::ResultWas::Ok ); \
  1109. INTERNAL_CATCH_REACT( catchAssertionHandler ) \
  1110. } while( Catch::alwaysFalse() )
  1111. ///////////////////////////////////////////////////////////////////////////////
  1112. #define INTERNAL_CATCH_MSG( macroName, messageType, resultDisposition, ... ) \
  1113. do { \
  1114. Catch::AssertionHandler catchAssertionHandler( macroName, CATCH_INTERNAL_LINEINFO, "", resultDisposition ); \
  1115. catchAssertionHandler.handle( messageType, ( Catch::MessageStream() << __VA_ARGS__ + ::Catch::StreamEndStop() ).m_stream.str() ); \
  1116. INTERNAL_CATCH_REACT( catchAssertionHandler ) \
  1117. } while( Catch::alwaysFalse() )
  1118. ///////////////////////////////////////////////////////////////////////////////
  1119. #define INTERNAL_CATCH_INFO( macroName, log ) \
  1120. Catch::ScopedMessage INTERNAL_CATCH_UNIQUE_NAME( scopedMessage ) = Catch::MessageBuilder( macroName, CATCH_INTERNAL_LINEINFO, Catch::ResultWas::Info ) << log;
  1121. ///////////////////////////////////////////////////////////////////////////////
  1122. // Although this is matcher-based, it can be used with just a string
  1123. #define INTERNAL_CATCH_THROWS_STR_MATCHES( macroName, resultDisposition, matcher, ... ) \
  1124. do { \
  1125. Catch::AssertionHandler catchAssertionHandler( macroName, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(__VA_ARGS__) ", " CATCH_INTERNAL_STRINGIFY(matcher), resultDisposition ); \
  1126. if( catchAssertionHandler.allowThrows() ) \
  1127. try { \
  1128. static_cast<void>(__VA_ARGS__); \
  1129. catchAssertionHandler.handle( Catch::ResultWas::DidntThrowException ); \
  1130. } \
  1131. catch( ... ) { \
  1132. handleExceptionMatchExpr( catchAssertionHandler, matcher, #matcher ); \
  1133. } \
  1134. else \
  1135. catchAssertionHandler.handle( Catch::ResultWas::Ok ); \
  1136. INTERNAL_CATCH_REACT( catchAssertionHandler ) \
  1137. } while( Catch::alwaysFalse() )
  1138. #endif // CATCH_CONFIG_DISABLE
  1139. // end catch_capture.hpp
  1140. // start catch_section.h
  1141. // start catch_section_info.h
  1142. // start catch_totals.h
  1143. #include <cstddef>
  1144. namespace Catch {
  1145. struct Counts {
  1146. Counts operator - ( Counts const& other ) const;
  1147. Counts& operator += ( Counts const& other );
  1148. std::size_t total() const;
  1149. bool allPassed() const;
  1150. bool allOk() const;
  1151. std::size_t passed = 0;
  1152. std::size_t failed = 0;
  1153. std::size_t failedButOk = 0;
  1154. };
  1155. struct Totals {
  1156. Totals operator - ( Totals const& other ) const;
  1157. Totals& operator += ( Totals const& other );
  1158. Totals delta( Totals const& prevTotals ) const;
  1159. Counts assertions;
  1160. Counts testCases;
  1161. };
  1162. }
  1163. // end catch_totals.h
  1164. #include <string>
  1165. namespace Catch {
  1166. struct SectionInfo {
  1167. SectionInfo
  1168. ( SourceLineInfo const& _lineInfo,
  1169. std::string const& _name,
  1170. std::string const& _description = std::string() );
  1171. std::string name;
  1172. std::string description;
  1173. SourceLineInfo lineInfo;
  1174. };
  1175. struct SectionEndInfo {
  1176. SectionEndInfo( SectionInfo const& _sectionInfo, Counts const& _prevAssertions, double _durationInSeconds );
  1177. SectionInfo sectionInfo;
  1178. Counts prevAssertions;
  1179. double durationInSeconds;
  1180. };
  1181. } // end namespace Catch
  1182. // end catch_section_info.h
  1183. // start catch_timer.h
  1184. #include <cstdint>
  1185. namespace Catch {
  1186. auto getCurrentNanosecondsSinceEpoch() -> uint64_t;
  1187. auto getEstimatedClockResolution() -> uint64_t;
  1188. class Timer {
  1189. uint64_t m_nanoseconds = 0;
  1190. public:
  1191. void start();
  1192. auto getElapsedNanoseconds() const -> unsigned int;
  1193. auto getElapsedMicroseconds() const -> unsigned int;
  1194. auto getElapsedMilliseconds() const -> unsigned int;
  1195. auto getElapsedSeconds() const -> double;
  1196. };
  1197. } // namespace Catch
  1198. // end catch_timer.h
  1199. #include <string>
  1200. namespace Catch {
  1201. class Section : NonCopyable {
  1202. public:
  1203. Section( SectionInfo const& info );
  1204. ~Section();
  1205. // This indicates whether the section should be executed or not
  1206. explicit operator bool() const;
  1207. private:
  1208. SectionInfo m_info;
  1209. std::string m_name;
  1210. Counts m_assertions;
  1211. bool m_sectionIncluded;
  1212. Timer m_timer;
  1213. };
  1214. } // end namespace Catch
  1215. #define INTERNAL_CATCH_SECTION( ... ) \
  1216. if( Catch::Section const& INTERNAL_CATCH_UNIQUE_NAME( catch_internal_Section ) = Catch::SectionInfo( CATCH_INTERNAL_LINEINFO, __VA_ARGS__ ) )
  1217. // end catch_section.h
  1218. // start catch_benchmark.h
  1219. #include <cstdint>
  1220. #include <string>
  1221. namespace Catch {
  1222. class BenchmarkLooper {
  1223. std::string m_name;
  1224. std::size_t m_count = 0;
  1225. std::size_t m_iterationsToRun = 1;
  1226. uint64_t m_resolution;
  1227. Timer m_timer;
  1228. static auto getResolution() -> uint64_t;
  1229. public:
  1230. // Keep most of this inline as it's on the code path that is being timed
  1231. BenchmarkLooper( StringRef name )
  1232. : m_name( name ),
  1233. m_resolution( getResolution() )
  1234. {
  1235. reportStart();
  1236. m_timer.start();
  1237. }
  1238. explicit operator bool() {
  1239. if( m_count < m_iterationsToRun )
  1240. return true;
  1241. return needsMoreIterations();
  1242. }
  1243. void increment() {
  1244. ++m_count;
  1245. }
  1246. void reportStart();
  1247. auto needsMoreIterations() -> bool;
  1248. };
  1249. } // end namespace Catch
  1250. #define BENCHMARK( name ) \
  1251. for( Catch::BenchmarkLooper looper( name ); looper; looper.increment() )
  1252. // end catch_benchmark.h
  1253. // start catch_interfaces_exception.h
  1254. // start catch_interfaces_registry_hub.h
  1255. #include <string>
  1256. #include <memory>
  1257. namespace Catch {
  1258. class TestCase;
  1259. struct ITestCaseRegistry;
  1260. struct IExceptionTranslatorRegistry;
  1261. struct IExceptionTranslator;
  1262. struct IReporterRegistry;
  1263. struct IReporterFactory;
  1264. struct ITagAliasRegistry;
  1265. class StartupExceptionRegistry;
  1266. using IReporterFactoryPtr = std::shared_ptr<IReporterFactory>;
  1267. struct IRegistryHub {
  1268. virtual ~IRegistryHub();
  1269. virtual IReporterRegistry const& getReporterRegistry() const = 0;
  1270. virtual ITestCaseRegistry const& getTestCaseRegistry() const = 0;
  1271. virtual ITagAliasRegistry const& getTagAliasRegistry() const = 0;
  1272. virtual IExceptionTranslatorRegistry& getExceptionTranslatorRegistry() = 0;
  1273. virtual StartupExceptionRegistry const& getStartupExceptionRegistry() const = 0;
  1274. };
  1275. struct IMutableRegistryHub {
  1276. virtual ~IMutableRegistryHub();
  1277. virtual void registerReporter( std::string const& name, IReporterFactoryPtr const& factory ) = 0;
  1278. virtual void registerListener( IReporterFactoryPtr const& factory ) = 0;
  1279. virtual void registerTest( TestCase const& testInfo ) = 0;
  1280. virtual void registerTranslator( const IExceptionTranslator* translator ) = 0;
  1281. virtual void registerTagAlias( std::string const& alias, std::string const& tag, SourceLineInfo const& lineInfo ) = 0;
  1282. virtual void registerStartupException() noexcept = 0;
  1283. };
  1284. IRegistryHub& getRegistryHub();
  1285. IMutableRegistryHub& getMutableRegistryHub();
  1286. void cleanUp();
  1287. std::string translateActiveException();
  1288. }
  1289. // end catch_interfaces_registry_hub.h
  1290. #if defined(CATCH_CONFIG_DISABLE)
  1291. #define INTERNAL_CATCH_TRANSLATE_EXCEPTION_NO_REG( translatorName, signature) \
  1292. static std::string translatorName( signature )
  1293. #endif
  1294. #include <string>
  1295. #include <vector>
  1296. namespace Catch {
  1297. using exceptionTranslateFunction = std::string(*)();
  1298. struct IExceptionTranslator;
  1299. using ExceptionTranslators = std::vector<std::unique_ptr<IExceptionTranslator const>>;
  1300. struct IExceptionTranslator {
  1301. virtual ~IExceptionTranslator();
  1302. virtual std::string translate( ExceptionTranslators::const_iterator it, ExceptionTranslators::const_iterator itEnd ) const = 0;
  1303. };
  1304. struct IExceptionTranslatorRegistry {
  1305. virtual ~IExceptionTranslatorRegistry();
  1306. virtual std::string translateActiveException() const = 0;
  1307. };
  1308. class ExceptionTranslatorRegistrar {
  1309. template<typename T>
  1310. class ExceptionTranslator : public IExceptionTranslator {
  1311. public:
  1312. ExceptionTranslator( std::string(*translateFunction)( T& ) )
  1313. : m_translateFunction( translateFunction )
  1314. {}
  1315. std::string translate( ExceptionTranslators::const_iterator it, ExceptionTranslators::const_iterator itEnd ) const override {
  1316. try {
  1317. if( it == itEnd )
  1318. throw;
  1319. else
  1320. return (*it)->translate( it+1, itEnd );
  1321. }
  1322. catch( T& ex ) {
  1323. return m_translateFunction( ex );
  1324. }
  1325. }
  1326. protected:
  1327. std::string(*m_translateFunction)( T& );
  1328. };
  1329. public:
  1330. template<typename T>
  1331. ExceptionTranslatorRegistrar( std::string(*translateFunction)( T& ) ) {
  1332. getMutableRegistryHub().registerTranslator
  1333. ( new ExceptionTranslator<T>( translateFunction ) );
  1334. }
  1335. };
  1336. }
  1337. ///////////////////////////////////////////////////////////////////////////////
  1338. #define INTERNAL_CATCH_TRANSLATE_EXCEPTION2( translatorName, signature ) \
  1339. static std::string translatorName( signature ); \
  1340. namespace{ Catch::ExceptionTranslatorRegistrar INTERNAL_CATCH_UNIQUE_NAME( catch_internal_ExceptionRegistrar )( &translatorName ); }\
  1341. static std::string translatorName( signature )
  1342. #define INTERNAL_CATCH_TRANSLATE_EXCEPTION( signature ) INTERNAL_CATCH_TRANSLATE_EXCEPTION2( INTERNAL_CATCH_UNIQUE_NAME( catch_internal_ExceptionTranslator ), signature )
  1343. // end catch_interfaces_exception.h
  1344. // start catch_approx.h
  1345. #include <cmath>
  1346. #include <type_traits>
  1347. namespace Catch {
  1348. namespace Detail {
  1349. double max(double lhs, double rhs);
  1350. class Approx {
  1351. public:
  1352. explicit Approx ( double value );
  1353. static Approx custom();
  1354. template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
  1355. Approx operator()( T const& value ) {
  1356. Approx approx( static_cast<double>(value) );
  1357. approx.epsilon( m_epsilon );
  1358. approx.margin( m_margin );
  1359. approx.scale( m_scale );
  1360. return approx;
  1361. }
  1362. template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
  1363. explicit Approx( T const& value ): Approx(static_cast<double>(value))
  1364. {}
  1365. template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
  1366. friend bool operator == ( const T& lhs, Approx const& rhs ) {
  1367. // Thanks to Richard Harris for his help refining this formula
  1368. auto lhs_v = static_cast<double>(lhs);
  1369. bool relativeOK = std::fabs(lhs_v - rhs.m_value) < rhs.m_epsilon * (rhs.m_scale + (max)(std::fabs(lhs_v), std::fabs(rhs.m_value)));
  1370. if (relativeOK) {
  1371. return true;
  1372. }
  1373. return std::fabs(lhs_v - rhs.m_value) < rhs.m_margin;
  1374. }
  1375. template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
  1376. friend bool operator == ( Approx const& lhs, const T& rhs ) {
  1377. return operator==( rhs, lhs );
  1378. }
  1379. template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
  1380. friend bool operator != ( T const& lhs, Approx const& rhs ) {
  1381. return !operator==( lhs, rhs );
  1382. }
  1383. template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
  1384. friend bool operator != ( Approx const& lhs, T const& rhs ) {
  1385. return !operator==( rhs, lhs );
  1386. }
  1387. template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
  1388. friend bool operator <= ( T const& lhs, Approx const& rhs ) {
  1389. return static_cast<double>(lhs) < rhs.m_value || lhs == rhs;
  1390. }
  1391. template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
  1392. friend bool operator <= ( Approx const& lhs, T const& rhs ) {
  1393. return lhs.m_value < static_cast<double>(rhs) || lhs == rhs;
  1394. }
  1395. template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
  1396. friend bool operator >= ( T const& lhs, Approx const& rhs ) {
  1397. return static_cast<double>(lhs) > rhs.m_value || lhs == rhs;
  1398. }
  1399. template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
  1400. friend bool operator >= ( Approx const& lhs, T const& rhs ) {
  1401. return lhs.m_value > static_cast<double>(rhs) || lhs == rhs;
  1402. }
  1403. template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
  1404. Approx& epsilon( T const& newEpsilon ) {
  1405. m_epsilon = static_cast<double>(newEpsilon);
  1406. return *this;
  1407. }
  1408. template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
  1409. Approx& margin( T const& newMargin ) {
  1410. m_margin = static_cast<double>(newMargin);
  1411. return *this;
  1412. }
  1413. template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
  1414. Approx& scale( T const& newScale ) {
  1415. m_scale = static_cast<double>(newScale);
  1416. return *this;
  1417. }
  1418. std::string toString() const;
  1419. private:
  1420. double m_epsilon;
  1421. double m_margin;
  1422. double m_scale;
  1423. double m_value;
  1424. };
  1425. }
  1426. template<>
  1427. struct StringMaker<Catch::Detail::Approx> {
  1428. static std::string convert(Catch::Detail::Approx const& value);
  1429. };
  1430. } // end namespace Catch
  1431. // end catch_approx.h
  1432. // start catch_string_manip.h
  1433. #include <string>
  1434. #include <iosfwd>
  1435. namespace Catch {
  1436. bool startsWith( std::string const& s, std::string const& prefix );
  1437. bool startsWith( std::string const& s, char prefix );
  1438. bool endsWith( std::string const& s, std::string const& suffix );
  1439. bool endsWith( std::string const& s, char suffix );
  1440. bool contains( std::string const& s, std::string const& infix );
  1441. void toLowerInPlace( std::string& s );
  1442. std::string toLower( std::string const& s );
  1443. std::string trim( std::string const& str );
  1444. bool replaceInPlace( std::string& str, std::string const& replaceThis, std::string const& withThis );
  1445. struct pluralise {
  1446. pluralise( std::size_t count, std::string const& label );
  1447. friend std::ostream& operator << ( std::ostream& os, pluralise const& pluraliser );
  1448. std::size_t m_count;
  1449. std::string m_label;
  1450. };
  1451. }
  1452. // end catch_string_manip.h
  1453. #ifndef CATCH_CONFIG_DISABLE_MATCHERS
  1454. // start catch_capture_matchers.h
  1455. // start catch_matchers.h
  1456. #include <string>
  1457. #include <vector>
  1458. namespace Catch {
  1459. namespace Matchers {
  1460. namespace Impl {
  1461. template<typename ArgT> struct MatchAllOf;
  1462. template<typename ArgT> struct MatchAnyOf;
  1463. template<typename ArgT> struct MatchNotOf;
  1464. class MatcherUntypedBase {
  1465. public:
  1466. MatcherUntypedBase() = default;
  1467. MatcherUntypedBase ( MatcherUntypedBase const& ) = default;
  1468. MatcherUntypedBase& operator = ( MatcherUntypedBase const& ) = delete;
  1469. std::string toString() const;
  1470. protected:
  1471. virtual ~MatcherUntypedBase();
  1472. virtual std::string describe() const = 0;
  1473. mutable std::string m_cachedToString;
  1474. };
  1475. template<typename ObjectT>
  1476. struct MatcherMethod {
  1477. virtual bool match( ObjectT const& arg ) const = 0;
  1478. };
  1479. template<typename PtrT>
  1480. struct MatcherMethod<PtrT*> {
  1481. virtual bool match( PtrT* arg ) const = 0;
  1482. };
  1483. template<typename ObjectT, typename ComparatorT = ObjectT>
  1484. struct MatcherBase : MatcherUntypedBase, MatcherMethod<ObjectT> {
  1485. MatchAllOf<ComparatorT> operator && ( MatcherBase const& other ) const;
  1486. MatchAnyOf<ComparatorT> operator || ( MatcherBase const& other ) const;
  1487. MatchNotOf<ComparatorT> operator ! () const;
  1488. };
  1489. template<typename ArgT>
  1490. struct MatchAllOf : MatcherBase<ArgT> {
  1491. bool match( ArgT const& arg ) const override {
  1492. for( auto matcher : m_matchers ) {
  1493. if (!matcher->match(arg))
  1494. return false;
  1495. }
  1496. return true;
  1497. }
  1498. std::string describe() const override {
  1499. std::string description;
  1500. description.reserve( 4 + m_matchers.size()*32 );
  1501. description += "( ";
  1502. bool first = true;
  1503. for( auto matcher : m_matchers ) {
  1504. if( first )
  1505. first = false;
  1506. else
  1507. description += " and ";
  1508. description += matcher->toString();
  1509. }
  1510. description += " )";
  1511. return description;
  1512. }
  1513. MatchAllOf<ArgT>& operator && ( MatcherBase<ArgT> const& other ) {
  1514. m_matchers.push_back( &other );
  1515. return *this;
  1516. }
  1517. std::vector<MatcherBase<ArgT> const*> m_matchers;
  1518. };
  1519. template<typename ArgT>
  1520. struct MatchAnyOf : MatcherBase<ArgT> {
  1521. bool match( ArgT const& arg ) const override {
  1522. for( auto matcher : m_matchers ) {
  1523. if (matcher->match(arg))
  1524. return true;
  1525. }
  1526. return false;
  1527. }
  1528. std::string describe() const override {
  1529. std::string description;
  1530. description.reserve( 4 + m_matchers.size()*32 );
  1531. description += "( ";
  1532. bool first = true;
  1533. for( auto matcher : m_matchers ) {
  1534. if( first )
  1535. first = false;
  1536. else
  1537. description += " or ";
  1538. description += matcher->toString();
  1539. }
  1540. description += " )";
  1541. return description;
  1542. }
  1543. MatchAnyOf<ArgT>& operator || ( MatcherBase<ArgT> const& other ) {
  1544. m_matchers.push_back( &other );
  1545. return *this;
  1546. }
  1547. std::vector<MatcherBase<ArgT> const*> m_matchers;
  1548. };
  1549. template<typename ArgT>
  1550. struct MatchNotOf : MatcherBase<ArgT> {
  1551. MatchNotOf( MatcherBase<ArgT> const& underlyingMatcher ) : m_underlyingMatcher( underlyingMatcher ) {}
  1552. bool match( ArgT const& arg ) const override {
  1553. return !m_underlyingMatcher.match( arg );
  1554. }
  1555. std::string describe() const override {
  1556. return "not " + m_underlyingMatcher.toString();
  1557. }
  1558. MatcherBase<ArgT> const& m_underlyingMatcher;
  1559. };
  1560. template<typename ObjectT, typename ComparatorT>
  1561. MatchAllOf<ComparatorT> MatcherBase<ObjectT, ComparatorT>::operator && ( MatcherBase const& other ) const {
  1562. return MatchAllOf<ComparatorT>() && *this && other;
  1563. }
  1564. template<typename ObjectT, typename ComparatorT>
  1565. MatchAnyOf<ComparatorT> MatcherBase<ObjectT, ComparatorT>::operator || ( MatcherBase const& other ) const {
  1566. return MatchAnyOf<ComparatorT>() || *this || other;
  1567. }
  1568. template<typename ObjectT, typename ComparatorT>
  1569. MatchNotOf<ComparatorT> MatcherBase<ObjectT, ComparatorT>::operator ! () const {
  1570. return MatchNotOf<ComparatorT>( *this );
  1571. }
  1572. } // namespace Impl
  1573. } // namespace Matchers
  1574. using namespace Matchers;
  1575. using Matchers::Impl::MatcherBase;
  1576. } // namespace Catch
  1577. // end catch_matchers.h
  1578. // start catch_matchers_string.h
  1579. #include <string>
  1580. namespace Catch {
  1581. namespace Matchers {
  1582. namespace StdString {
  1583. struct CasedString
  1584. {
  1585. CasedString( std::string const& str, CaseSensitive::Choice caseSensitivity );
  1586. std::string adjustString( std::string const& str ) const;
  1587. std::string caseSensitivitySuffix() const;
  1588. CaseSensitive::Choice m_caseSensitivity;
  1589. std::string m_str;
  1590. };
  1591. struct StringMatcherBase : MatcherBase<std::string> {
  1592. StringMatcherBase( std::string const& operation, CasedString const& comparator );
  1593. std::string describe() const override;
  1594. CasedString m_comparator;
  1595. std::string m_operation;
  1596. };
  1597. struct EqualsMatcher : StringMatcherBase {
  1598. EqualsMatcher( CasedString const& comparator );
  1599. bool match( std::string const& source ) const override;
  1600. };
  1601. struct ContainsMatcher : StringMatcherBase {
  1602. ContainsMatcher( CasedString const& comparator );
  1603. bool match( std::string const& source ) const override;
  1604. };
  1605. struct StartsWithMatcher : StringMatcherBase {
  1606. StartsWithMatcher( CasedString const& comparator );
  1607. bool match( std::string const& source ) const override;
  1608. };
  1609. struct EndsWithMatcher : StringMatcherBase {
  1610. EndsWithMatcher( CasedString const& comparator );
  1611. bool match( std::string const& source ) const override;
  1612. };
  1613. } // namespace StdString
  1614. // The following functions create the actual matcher objects.
  1615. // This allows the types to be inferred
  1616. StdString::EqualsMatcher Equals( std::string const& str, CaseSensitive::Choice caseSensitivity = CaseSensitive::Yes );
  1617. StdString::ContainsMatcher Contains( std::string const& str, CaseSensitive::Choice caseSensitivity = CaseSensitive::Yes );
  1618. StdString::EndsWithMatcher EndsWith( std::string const& str, CaseSensitive::Choice caseSensitivity = CaseSensitive::Yes );
  1619. StdString::StartsWithMatcher StartsWith( std::string const& str, CaseSensitive::Choice caseSensitivity = CaseSensitive::Yes );
  1620. } // namespace Matchers
  1621. } // namespace Catch
  1622. // end catch_matchers_string.h
  1623. // start catch_matchers_vector.h
  1624. namespace Catch {
  1625. namespace Matchers {
  1626. namespace Vector {
  1627. template<typename T>
  1628. struct ContainsElementMatcher : MatcherBase<std::vector<T>, T> {
  1629. ContainsElementMatcher(T const &comparator) : m_comparator( comparator) {}
  1630. bool match(std::vector<T> const &v) const override {
  1631. for (auto const& el : v) {
  1632. if (el == m_comparator) {
  1633. return true;
  1634. }
  1635. }
  1636. return false;
  1637. }
  1638. std::string describe() const override {
  1639. return "Contains: " + ::Catch::Detail::stringify( m_comparator );
  1640. }
  1641. T const& m_comparator;
  1642. };
  1643. template<typename T>
  1644. struct ContainsMatcher : MatcherBase<std::vector<T>, std::vector<T> > {
  1645. ContainsMatcher(std::vector<T> const &comparator) : m_comparator( comparator ) {}
  1646. bool match(std::vector<T> const &v) const override {
  1647. // !TBD: see note in EqualsMatcher
  1648. if (m_comparator.size() > v.size())
  1649. return false;
  1650. for (auto const& comparator : m_comparator) {
  1651. auto present = false;
  1652. for (const auto& el : v) {
  1653. if (el == comparator) {
  1654. present = true;
  1655. break;
  1656. }
  1657. }
  1658. if (!present) {
  1659. return false;
  1660. }
  1661. }
  1662. return true;
  1663. }
  1664. std::string describe() const override {
  1665. return "Contains: " + ::Catch::Detail::stringify( m_comparator );
  1666. }
  1667. std::vector<T> const& m_comparator;
  1668. };
  1669. template<typename T>
  1670. struct EqualsMatcher : MatcherBase<std::vector<T>, std::vector<T> > {
  1671. EqualsMatcher(std::vector<T> const &comparator) : m_comparator( comparator ) {}
  1672. bool match(std::vector<T> const &v) const override {
  1673. // !TBD: This currently works if all elements can be compared using !=
  1674. // - a more general approach would be via a compare template that defaults
  1675. // to using !=. but could be specialised for, e.g. std::vector<T> etc
  1676. // - then just call that directly
  1677. if (m_comparator.size() != v.size())
  1678. return false;
  1679. for (std::size_t i = 0; i < v.size(); ++i)
  1680. if (m_comparator[i] != v[i])
  1681. return false;
  1682. return true;
  1683. }
  1684. std::string describe() const override {
  1685. return "Equals: " + ::Catch::Detail::stringify( m_comparator );
  1686. }
  1687. std::vector<T> const& m_comparator;
  1688. };
  1689. } // namespace Vector
  1690. // The following functions create the actual matcher objects.
  1691. // This allows the types to be inferred
  1692. template<typename T>
  1693. Vector::ContainsMatcher<T> Contains( std::vector<T> const& comparator ) {
  1694. return Vector::ContainsMatcher<T>( comparator );
  1695. }
  1696. template<typename T>
  1697. Vector::ContainsElementMatcher<T> VectorContains( T const& comparator ) {
  1698. return Vector::ContainsElementMatcher<T>( comparator );
  1699. }
  1700. template<typename T>
  1701. Vector::EqualsMatcher<T> Equals( std::vector<T> const& comparator ) {
  1702. return Vector::EqualsMatcher<T>( comparator );
  1703. }
  1704. } // namespace Matchers
  1705. } // namespace Catch
  1706. // end catch_matchers_vector.h
  1707. namespace Catch {
  1708. template<typename ArgT, typename MatcherT>
  1709. class MatchExpr : public ITransientExpression {
  1710. ArgT const& m_arg;
  1711. MatcherT m_matcher;
  1712. StringRef m_matcherString;
  1713. bool m_result;
  1714. public:
  1715. MatchExpr( ArgT const& arg, MatcherT const& matcher, StringRef matcherString )
  1716. : m_arg( arg ),
  1717. m_matcher( matcher ),
  1718. m_matcherString( matcherString ),
  1719. m_result( matcher.match( arg ) )
  1720. {}
  1721. auto isBinaryExpression() const -> bool override { return true; }
  1722. auto getResult() const -> bool override { return m_result; }
  1723. void streamReconstructedExpression( std::ostream &os ) const override {
  1724. auto matcherAsString = m_matcher.toString();
  1725. os << Catch::Detail::stringify( m_arg ) << ' ';
  1726. if( matcherAsString == Detail::unprintableString )
  1727. os << m_matcherString;
  1728. else
  1729. os << matcherAsString;
  1730. }
  1731. };
  1732. using StringMatcher = Matchers::Impl::MatcherBase<std::string>;
  1733. void handleExceptionMatchExpr( AssertionHandler& handler, StringMatcher const& matcher, StringRef matcherString );
  1734. template<typename ArgT, typename MatcherT>
  1735. auto makeMatchExpr( ArgT const& arg, MatcherT const& matcher, StringRef matcherString ) -> MatchExpr<ArgT, MatcherT> {
  1736. return MatchExpr<ArgT, MatcherT>( arg, matcher, matcherString );
  1737. }
  1738. } // namespace Catch
  1739. ///////////////////////////////////////////////////////////////////////////////
  1740. #define INTERNAL_CHECK_THAT( macroName, matcher, resultDisposition, arg ) \
  1741. do { \
  1742. Catch::AssertionHandler catchAssertionHandler( macroName, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(arg) ", " CATCH_INTERNAL_STRINGIFY(matcher), resultDisposition ); \
  1743. INTERNAL_CATCH_TRY( catchAssertionHandler ) { \
  1744. catchAssertionHandler.handle( Catch::makeMatchExpr( arg, matcher, #matcher ) ); \
  1745. } INTERNAL_CATCH_CATCH( catchAssertionHandler ) \
  1746. INTERNAL_CATCH_REACT( catchAssertionHandler ) \
  1747. } while( Catch::alwaysFalse() )
  1748. ///////////////////////////////////////////////////////////////////////////////
  1749. #define INTERNAL_CATCH_THROWS_MATCHES( macroName, exceptionType, resultDisposition, matcher, ... ) \
  1750. do { \
  1751. Catch::AssertionHandler catchAssertionHandler( macroName, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(__VA_ARGS__) ", " CATCH_INTERNAL_STRINGIFY(exceptionType) ", " CATCH_INTERNAL_STRINGIFY(matcher), resultDisposition ); \
  1752. if( catchAssertionHandler.allowThrows() ) \
  1753. try { \
  1754. static_cast<void>(__VA_ARGS__ ); \
  1755. catchAssertionHandler.handle( Catch::ResultWas::DidntThrowException ); \
  1756. } \
  1757. catch( exceptionType const& ex ) { \
  1758. catchAssertionHandler.handle( Catch::makeMatchExpr( ex, matcher, #matcher ) ); \
  1759. } \
  1760. catch( ... ) { \
  1761. catchAssertionHandler.useActiveException(); \
  1762. } \
  1763. else \
  1764. catchAssertionHandler.handle( Catch::ResultWas::Ok ); \
  1765. INTERNAL_CATCH_REACT( catchAssertionHandler ) \
  1766. } while( Catch::alwaysFalse() )
  1767. // end catch_capture_matchers.h
  1768. #endif
  1769. // These files are included here so the single_include script doesn't put them
  1770. // in the conditionally compiled sections
  1771. // start catch_test_case_info.h
  1772. #include <string>
  1773. #include <vector>
  1774. #include <memory>
  1775. #ifdef __clang__
  1776. #pragma clang diagnostic push
  1777. #pragma clang diagnostic ignored "-Wpadded"
  1778. #endif
  1779. namespace Catch {
  1780. struct ITestInvoker;
  1781. struct TestCaseInfo {
  1782. enum SpecialProperties{
  1783. None = 0,
  1784. IsHidden = 1 << 1,
  1785. ShouldFail = 1 << 2,
  1786. MayFail = 1 << 3,
  1787. Throws = 1 << 4,
  1788. NonPortable = 1 << 5,
  1789. Benchmark = 1 << 6
  1790. };
  1791. TestCaseInfo( std::string const& _name,
  1792. std::string const& _className,
  1793. std::string const& _description,
  1794. std::vector<std::string> const& _tags,
  1795. SourceLineInfo const& _lineInfo );
  1796. friend void setTags( TestCaseInfo& testCaseInfo, std::vector<std::string> tags );
  1797. bool isHidden() const;
  1798. bool throws() const;
  1799. bool okToFail() const;
  1800. bool expectedToFail() const;
  1801. std::string tagsAsString() const;
  1802. std::string name;
  1803. std::string className;
  1804. std::string description;
  1805. std::vector<std::string> tags;
  1806. std::vector<std::string> lcaseTags;
  1807. SourceLineInfo lineInfo;
  1808. SpecialProperties properties;
  1809. };
  1810. class TestCase : public TestCaseInfo {
  1811. public:
  1812. TestCase( ITestInvoker* testCase, TestCaseInfo const& info );
  1813. TestCase withName( std::string const& _newName ) const;
  1814. void invoke() const;
  1815. TestCaseInfo const& getTestCaseInfo() const;
  1816. bool operator == ( TestCase const& other ) const;
  1817. bool operator < ( TestCase const& other ) const;
  1818. private:
  1819. std::shared_ptr<ITestInvoker> test;
  1820. };
  1821. TestCase makeTestCase( ITestInvoker* testCase,
  1822. std::string const& className,
  1823. std::string const& name,
  1824. std::string const& description,
  1825. SourceLineInfo const& lineInfo );
  1826. }
  1827. #ifdef __clang__
  1828. #pragma clang diagnostic pop
  1829. #endif
  1830. // end catch_test_case_info.h
  1831. // start catch_interfaces_runner.h
  1832. namespace Catch {
  1833. struct IRunner {
  1834. virtual ~IRunner();
  1835. virtual bool aborting() const = 0;
  1836. };
  1837. }
  1838. // end catch_interfaces_runner.h
  1839. #ifdef __OBJC__
  1840. // start catch_objc.hpp
  1841. #import <objc/runtime.h>
  1842. #include <string>
  1843. // NB. Any general catch headers included here must be included
  1844. // in catch.hpp first to make sure they are included by the single
  1845. // header for non obj-usage
  1846. ///////////////////////////////////////////////////////////////////////////////
  1847. // This protocol is really only here for (self) documenting purposes, since
  1848. // all its methods are optional.
  1849. @protocol OcFixture
  1850. @optional
  1851. -(void) setUp;
  1852. -(void) tearDown;
  1853. @end
  1854. namespace Catch {
  1855. class OcMethod : public ITestInvoker {
  1856. public:
  1857. OcMethod( Class cls, SEL sel ) : m_cls( cls ), m_sel( sel ) {}
  1858. virtual void invoke() const {
  1859. id obj = [[m_cls alloc] init];
  1860. performOptionalSelector( obj, @selector(setUp) );
  1861. performOptionalSelector( obj, m_sel );
  1862. performOptionalSelector( obj, @selector(tearDown) );
  1863. arcSafeRelease( obj );
  1864. }
  1865. private:
  1866. virtual ~OcMethod() {}
  1867. Class m_cls;
  1868. SEL m_sel;
  1869. };
  1870. namespace Detail{
  1871. inline std::string getAnnotation( Class cls,
  1872. std::string const& annotationName,
  1873. std::string const& testCaseName ) {
  1874. NSString* selStr = [[NSString alloc] initWithFormat:@"Catch_%s_%s", annotationName.c_str(), testCaseName.c_str()];
  1875. SEL sel = NSSelectorFromString( selStr );
  1876. arcSafeRelease( selStr );
  1877. id value = performOptionalSelector( cls, sel );
  1878. if( value )
  1879. return [(NSString*)value UTF8String];
  1880. return "";
  1881. }
  1882. }
  1883. inline std::size_t registerTestMethods() {
  1884. std::size_t noTestMethods = 0;
  1885. int noClasses = objc_getClassList( nullptr, 0 );
  1886. Class* classes = (CATCH_UNSAFE_UNRETAINED Class *)malloc( sizeof(Class) * noClasses);
  1887. objc_getClassList( classes, noClasses );
  1888. for( int c = 0; c < noClasses; c++ ) {
  1889. Class cls = classes[c];
  1890. {
  1891. u_int count;
  1892. Method* methods = class_copyMethodList( cls, &count );
  1893. for( u_int m = 0; m < count ; m++ ) {
  1894. SEL selector = method_getName(methods[m]);
  1895. std::string methodName = sel_getName(selector);
  1896. if( startsWith( methodName, "Catch_TestCase_" ) ) {
  1897. std::string testCaseName = methodName.substr( 15 );
  1898. std::string name = Detail::getAnnotation( cls, "Name", testCaseName );
  1899. std::string desc = Detail::getAnnotation( cls, "Description", testCaseName );
  1900. const char* className = class_getName( cls );
  1901. getMutableRegistryHub().registerTest( makeTestCase( new OcMethod( cls, selector ), className, name.c_str(), desc.c_str(), SourceLineInfo("",0) ) );
  1902. noTestMethods++;
  1903. }
  1904. }
  1905. free(methods);
  1906. }
  1907. }
  1908. return noTestMethods;
  1909. }
  1910. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  1911. namespace Matchers {
  1912. namespace Impl {
  1913. namespace NSStringMatchers {
  1914. struct StringHolder : MatcherBase<NSString*>{
  1915. StringHolder( NSString* substr ) : m_substr( [substr copy] ){}
  1916. StringHolder( StringHolder const& other ) : m_substr( [other.m_substr copy] ){}
  1917. StringHolder() {
  1918. arcSafeRelease( m_substr );
  1919. }
  1920. bool match( NSString* arg ) const override {
  1921. return false;
  1922. }
  1923. NSString* CATCH_ARC_STRONG m_substr;
  1924. };
  1925. struct Equals : StringHolder {
  1926. Equals( NSString* substr ) : StringHolder( substr ){}
  1927. bool match( NSString* str ) const override {
  1928. return (str != nil || m_substr == nil ) &&
  1929. [str isEqualToString:m_substr];
  1930. }
  1931. std::string describe() const override {
  1932. return "equals string: " + Catch::Detail::stringify( m_substr );
  1933. }
  1934. };
  1935. struct Contains : StringHolder {
  1936. Contains( NSString* substr ) : StringHolder( substr ){}
  1937. bool match( NSString* str ) const {
  1938. return (str != nil || m_substr == nil ) &&
  1939. [str rangeOfString:m_substr].location != NSNotFound;
  1940. }
  1941. std::string describe() const override {
  1942. return "contains string: " + Catch::Detail::stringify( m_substr );
  1943. }
  1944. };
  1945. struct StartsWith : StringHolder {
  1946. StartsWith( NSString* substr ) : StringHolder( substr ){}
  1947. bool match( NSString* str ) const override {
  1948. return (str != nil || m_substr == nil ) &&
  1949. [str rangeOfString:m_substr].location == 0;
  1950. }
  1951. std::string describe() const override {
  1952. return "starts with: " + Catch::Detail::stringify( m_substr );
  1953. }
  1954. };
  1955. struct EndsWith : StringHolder {
  1956. EndsWith( NSString* substr ) : StringHolder( substr ){}
  1957. bool match( NSString* str ) const override {
  1958. return (str != nil || m_substr == nil ) &&
  1959. [str rangeOfString:m_substr].location == [str length] - [m_substr length];
  1960. }
  1961. std::string describe() const override {
  1962. return "ends with: " + Catch::Detail::stringify( m_substr );
  1963. }
  1964. };
  1965. } // namespace NSStringMatchers
  1966. } // namespace Impl
  1967. inline Impl::NSStringMatchers::Equals
  1968. Equals( NSString* substr ){ return Impl::NSStringMatchers::Equals( substr ); }
  1969. inline Impl::NSStringMatchers::Contains
  1970. Contains( NSString* substr ){ return Impl::NSStringMatchers::Contains( substr ); }
  1971. inline Impl::NSStringMatchers::StartsWith
  1972. StartsWith( NSString* substr ){ return Impl::NSStringMatchers::StartsWith( substr ); }
  1973. inline Impl::NSStringMatchers::EndsWith
  1974. EndsWith( NSString* substr ){ return Impl::NSStringMatchers::EndsWith( substr ); }
  1975. } // namespace Matchers
  1976. using namespace Matchers;
  1977. #endif // CATCH_CONFIG_DISABLE_MATCHERS
  1978. } // namespace Catch
  1979. ///////////////////////////////////////////////////////////////////////////////
  1980. #define OC_MAKE_UNIQUE_NAME( root, uniqueSuffix ) root##uniqueSuffix
  1981. #define OC_TEST_CASE2( name, desc, uniqueSuffix ) \
  1982. +(NSString*) OC_MAKE_UNIQUE_NAME( Catch_Name_test_, uniqueSuffix ) \
  1983. { \
  1984. return @ name; \
  1985. } \
  1986. +(NSString*) OC_MAKE_UNIQUE_NAME( Catch_Description_test_, uniqueSuffix ) \
  1987. { \
  1988. return @ desc; \
  1989. } \
  1990. -(void) OC_MAKE_UNIQUE_NAME( Catch_TestCase_test_, uniqueSuffix )
  1991. #define OC_TEST_CASE( name, desc ) OC_TEST_CASE2( name, desc, __LINE__ )
  1992. // end catch_objc.hpp
  1993. #endif
  1994. #ifdef CATCH_CONFIG_EXTERNAL_INTERFACES
  1995. // start catch_external_interfaces.h
  1996. // start catch_reporter_bases.hpp
  1997. // start catch_enforce.h
  1998. #include <sstream>
  1999. #include <stdexcept>
  2000. #define CATCH_PREPARE_EXCEPTION( type, msg ) \
  2001. type( static_cast<std::ostringstream&&>( std::ostringstream() << msg ).str() )
  2002. #define CATCH_INTERNAL_ERROR( msg ) \
  2003. throw CATCH_PREPARE_EXCEPTION( std::logic_error, CATCH_INTERNAL_LINEINFO << ": Internal Catch error: " << msg);
  2004. #define CATCH_ERROR( msg ) \
  2005. throw CATCH_PREPARE_EXCEPTION( std::domain_error, msg )
  2006. #define CATCH_ENFORCE( condition, msg ) \
  2007. do{ if( !(condition) ) CATCH_ERROR( msg ); } while(false)
  2008. // end catch_enforce.h
  2009. // start catch_interfaces_reporter.h
  2010. // start catch_config.hpp
  2011. // start catch_test_spec_parser.h
  2012. #ifdef __clang__
  2013. #pragma clang diagnostic push
  2014. #pragma clang diagnostic ignored "-Wpadded"
  2015. #endif
  2016. // start catch_test_spec.h
  2017. #ifdef __clang__
  2018. #pragma clang diagnostic push
  2019. #pragma clang diagnostic ignored "-Wpadded"
  2020. #endif
  2021. // start catch_wildcard_pattern.h
  2022. namespace Catch
  2023. {
  2024. class WildcardPattern {
  2025. enum WildcardPosition {
  2026. NoWildcard = 0,
  2027. WildcardAtStart = 1,
  2028. WildcardAtEnd = 2,
  2029. WildcardAtBothEnds = WildcardAtStart | WildcardAtEnd
  2030. };
  2031. public:
  2032. WildcardPattern( std::string const& pattern, CaseSensitive::Choice caseSensitivity );
  2033. virtual ~WildcardPattern() = default;
  2034. virtual bool matches( std::string const& str ) const;
  2035. private:
  2036. std::string adjustCase( std::string const& str ) const;
  2037. CaseSensitive::Choice m_caseSensitivity;
  2038. WildcardPosition m_wildcard = NoWildcard;
  2039. std::string m_pattern;
  2040. };
  2041. }
  2042. // end catch_wildcard_pattern.h
  2043. #include <string>
  2044. #include <vector>
  2045. #include <memory>
  2046. namespace Catch {
  2047. class TestSpec {
  2048. struct Pattern {
  2049. virtual ~Pattern();
  2050. virtual bool matches( TestCaseInfo const& testCase ) const = 0;
  2051. };
  2052. using PatternPtr = std::shared_ptr<Pattern>;
  2053. class NamePattern : public Pattern {
  2054. public:
  2055. NamePattern( std::string const& name );
  2056. virtual ~NamePattern();
  2057. virtual bool matches( TestCaseInfo const& testCase ) const override;
  2058. private:
  2059. WildcardPattern m_wildcardPattern;
  2060. };
  2061. class TagPattern : public Pattern {
  2062. public:
  2063. TagPattern( std::string const& tag );
  2064. virtual ~TagPattern();
  2065. virtual bool matches( TestCaseInfo const& testCase ) const override;
  2066. private:
  2067. std::string m_tag;
  2068. };
  2069. class ExcludedPattern : public Pattern {
  2070. public:
  2071. ExcludedPattern( PatternPtr const& underlyingPattern );
  2072. virtual ~ExcludedPattern();
  2073. virtual bool matches( TestCaseInfo const& testCase ) const override;
  2074. private:
  2075. PatternPtr m_underlyingPattern;
  2076. };
  2077. struct Filter {
  2078. std::vector<PatternPtr> m_patterns;
  2079. bool matches( TestCaseInfo const& testCase ) const;
  2080. };
  2081. public:
  2082. bool hasFilters() const;
  2083. bool matches( TestCaseInfo const& testCase ) const;
  2084. private:
  2085. std::vector<Filter> m_filters;
  2086. friend class TestSpecParser;
  2087. };
  2088. }
  2089. #ifdef __clang__
  2090. #pragma clang diagnostic pop
  2091. #endif
  2092. // end catch_test_spec.h
  2093. // start catch_interfaces_tag_alias_registry.h
  2094. #include <string>
  2095. namespace Catch {
  2096. struct TagAlias;
  2097. struct ITagAliasRegistry {
  2098. virtual ~ITagAliasRegistry();
  2099. // Nullptr if not present
  2100. virtual TagAlias const* find( std::string const& alias ) const = 0;
  2101. virtual std::string expandAliases( std::string const& unexpandedTestSpec ) const = 0;
  2102. static ITagAliasRegistry const& get();
  2103. };
  2104. } // end namespace Catch
  2105. // end catch_interfaces_tag_alias_registry.h
  2106. namespace Catch {
  2107. class TestSpecParser {
  2108. enum Mode{ None, Name, QuotedName, Tag, EscapedName };
  2109. Mode m_mode = None;
  2110. bool m_exclusion = false;
  2111. std::size_t m_start = std::string::npos, m_pos = 0;
  2112. std::string m_arg;
  2113. std::vector<std::size_t> m_escapeChars;
  2114. TestSpec::Filter m_currentFilter;
  2115. TestSpec m_testSpec;
  2116. ITagAliasRegistry const* m_tagAliases = nullptr;
  2117. public:
  2118. TestSpecParser( ITagAliasRegistry const& tagAliases );
  2119. TestSpecParser& parse( std::string const& arg );
  2120. TestSpec testSpec();
  2121. private:
  2122. void visitChar( char c );
  2123. void startNewMode( Mode mode, std::size_t start );
  2124. void escape();
  2125. std::string subString() const;
  2126. template<typename T>
  2127. void addPattern() {
  2128. std::string token = subString();
  2129. for( std::size_t i = 0; i < m_escapeChars.size(); ++i )
  2130. token = token.substr( 0, m_escapeChars[i]-m_start-i ) + token.substr( m_escapeChars[i]-m_start-i+1 );
  2131. m_escapeChars.clear();
  2132. if( startsWith( token, "exclude:" ) ) {
  2133. m_exclusion = true;
  2134. token = token.substr( 8 );
  2135. }
  2136. if( !token.empty() ) {
  2137. TestSpec::PatternPtr pattern = std::make_shared<T>( token );
  2138. if( m_exclusion )
  2139. pattern = std::make_shared<TestSpec::ExcludedPattern>( pattern );
  2140. m_currentFilter.m_patterns.push_back( pattern );
  2141. }
  2142. m_exclusion = false;
  2143. m_mode = None;
  2144. }
  2145. void addFilter();
  2146. };
  2147. TestSpec parseTestSpec( std::string const& arg );
  2148. } // namespace Catch
  2149. #ifdef __clang__
  2150. #pragma clang diagnostic pop
  2151. #endif
  2152. // end catch_test_spec_parser.h
  2153. // start catch_interfaces_config.h
  2154. #include <iosfwd>
  2155. #include <string>
  2156. #include <vector>
  2157. #include <memory>
  2158. namespace Catch {
  2159. enum class Verbosity {
  2160. Quiet = 0,
  2161. Normal,
  2162. High
  2163. };
  2164. struct WarnAbout { enum What {
  2165. Nothing = 0x00,
  2166. NoAssertions = 0x01
  2167. }; };
  2168. struct ShowDurations { enum OrNot {
  2169. DefaultForReporter,
  2170. Always,
  2171. Never
  2172. }; };
  2173. struct RunTests { enum InWhatOrder {
  2174. InDeclarationOrder,
  2175. InLexicographicalOrder,
  2176. InRandomOrder
  2177. }; };
  2178. struct UseColour { enum YesOrNo {
  2179. Auto,
  2180. Yes,
  2181. No
  2182. }; };
  2183. struct WaitForKeypress { enum When {
  2184. Never,
  2185. BeforeStart = 1,
  2186. BeforeExit = 2,
  2187. BeforeStartAndExit = BeforeStart | BeforeExit
  2188. }; };
  2189. class TestSpec;
  2190. struct IConfig : NonCopyable {
  2191. virtual ~IConfig();
  2192. virtual bool allowThrows() const = 0;
  2193. virtual std::ostream& stream() const = 0;
  2194. virtual std::string name() const = 0;
  2195. virtual bool includeSuccessfulResults() const = 0;
  2196. virtual bool shouldDebugBreak() const = 0;
  2197. virtual bool warnAboutMissingAssertions() const = 0;
  2198. virtual int abortAfter() const = 0;
  2199. virtual bool showInvisibles() const = 0;
  2200. virtual ShowDurations::OrNot showDurations() const = 0;
  2201. virtual TestSpec const& testSpec() const = 0;
  2202. virtual RunTests::InWhatOrder runOrder() const = 0;
  2203. virtual unsigned int rngSeed() const = 0;
  2204. virtual int benchmarkResolutionMultiple() const = 0;
  2205. virtual UseColour::YesOrNo useColour() const = 0;
  2206. virtual std::vector<std::string> const& getSectionsToRun() const = 0;
  2207. virtual Verbosity verbosity() const = 0;
  2208. };
  2209. using IConfigPtr = std::shared_ptr<IConfig const>;
  2210. }
  2211. // end catch_interfaces_config.h
  2212. // Libstdc++ doesn't like incomplete classes for unique_ptr
  2213. // start catch_stream.h
  2214. // start catch_streambuf.h
  2215. #include <streambuf>
  2216. namespace Catch {
  2217. class StreamBufBase : public std::streambuf {
  2218. public:
  2219. virtual ~StreamBufBase();
  2220. };
  2221. }
  2222. // end catch_streambuf.h
  2223. #include <streambuf>
  2224. #include <ostream>
  2225. #include <fstream>
  2226. #include <memory>
  2227. namespace Catch {
  2228. std::ostream& cout();
  2229. std::ostream& cerr();
  2230. std::ostream& clog();
  2231. struct IStream {
  2232. virtual ~IStream();
  2233. virtual std::ostream& stream() const = 0;
  2234. };
  2235. class FileStream : public IStream {
  2236. mutable std::ofstream m_ofs;
  2237. public:
  2238. FileStream( std::string const& filename );
  2239. ~FileStream() override = default;
  2240. public: // IStream
  2241. std::ostream& stream() const override;
  2242. };
  2243. class CoutStream : public IStream {
  2244. mutable std::ostream m_os;
  2245. public:
  2246. CoutStream();
  2247. ~CoutStream() override = default;
  2248. public: // IStream
  2249. std::ostream& stream() const override;
  2250. };
  2251. class DebugOutStream : public IStream {
  2252. std::unique_ptr<StreamBufBase> m_streamBuf;
  2253. mutable std::ostream m_os;
  2254. public:
  2255. DebugOutStream();
  2256. ~DebugOutStream() override = default;
  2257. public: // IStream
  2258. std::ostream& stream() const override;
  2259. };
  2260. }
  2261. // end catch_stream.h
  2262. #include <memory>
  2263. #include <vector>
  2264. #include <string>
  2265. #ifndef CATCH_CONFIG_CONSOLE_WIDTH
  2266. #define CATCH_CONFIG_CONSOLE_WIDTH 80
  2267. #endif
  2268. namespace Catch {
  2269. struct IStream;
  2270. struct ConfigData {
  2271. bool listTests = false;
  2272. bool listTags = false;
  2273. bool listReporters = false;
  2274. bool listTestNamesOnly = false;
  2275. bool showSuccessfulTests = false;
  2276. bool shouldDebugBreak = false;
  2277. bool noThrow = false;
  2278. bool showHelp = false;
  2279. bool showInvisibles = false;
  2280. bool filenamesAsTags = false;
  2281. bool libIdentify = false;
  2282. int abortAfter = -1;
  2283. unsigned int rngSeed = 0;
  2284. int benchmarkResolutionMultiple = 100;
  2285. Verbosity verbosity = Verbosity::Normal;
  2286. WarnAbout::What warnings = WarnAbout::Nothing;
  2287. ShowDurations::OrNot showDurations = ShowDurations::DefaultForReporter;
  2288. RunTests::InWhatOrder runOrder = RunTests::InDeclarationOrder;
  2289. UseColour::YesOrNo useColour = UseColour::Auto;
  2290. WaitForKeypress::When waitForKeypress = WaitForKeypress::Never;
  2291. std::string outputFilename;
  2292. std::string name;
  2293. std::string processName;
  2294. std::vector<std::string> reporterNames;
  2295. std::vector<std::string> testsOrTags;
  2296. std::vector<std::string> sectionsToRun;
  2297. };
  2298. class Config : public IConfig {
  2299. public:
  2300. Config() = default;
  2301. Config( ConfigData const& data );
  2302. virtual ~Config() = default;
  2303. std::string const& getFilename() const;
  2304. bool listTests() const;
  2305. bool listTestNamesOnly() const;
  2306. bool listTags() const;
  2307. bool listReporters() const;
  2308. std::string getProcessName() const;
  2309. std::vector<std::string> const& getReporterNames() const;
  2310. std::vector<std::string> const& getSectionsToRun() const override;
  2311. virtual TestSpec const& testSpec() const override;
  2312. bool showHelp() const;
  2313. // IConfig interface
  2314. bool allowThrows() const override;
  2315. std::ostream& stream() const override;
  2316. std::string name() const override;
  2317. bool includeSuccessfulResults() const override;
  2318. bool warnAboutMissingAssertions() const override;
  2319. ShowDurations::OrNot showDurations() const override;
  2320. RunTests::InWhatOrder runOrder() const override;
  2321. unsigned int rngSeed() const override;
  2322. int benchmarkResolutionMultiple() const override;
  2323. UseColour::YesOrNo useColour() const override;
  2324. bool shouldDebugBreak() const override;
  2325. int abortAfter() const override;
  2326. bool showInvisibles() const override;
  2327. Verbosity verbosity() const override;
  2328. private:
  2329. IStream const* openStream();
  2330. ConfigData m_data;
  2331. std::unique_ptr<IStream const> m_stream;
  2332. TestSpec m_testSpec;
  2333. };
  2334. } // end namespace Catch
  2335. // end catch_config.hpp
  2336. // start catch_assertionresult.h
  2337. #include <string>
  2338. namespace Catch {
  2339. struct AssertionResultData
  2340. {
  2341. AssertionResultData() = delete;
  2342. AssertionResultData( ResultWas::OfType _resultType, LazyExpression const& _lazyExpression );
  2343. std::string message;
  2344. mutable std::string reconstructedExpression;
  2345. LazyExpression lazyExpression;
  2346. ResultWas::OfType resultType;
  2347. std::string reconstructExpression() const;
  2348. };
  2349. class AssertionResult {
  2350. public:
  2351. AssertionResult() = delete;
  2352. AssertionResult( AssertionInfo const& info, AssertionResultData const& data );
  2353. bool isOk() const;
  2354. bool succeeded() const;
  2355. ResultWas::OfType getResultType() const;
  2356. bool hasExpression() const;
  2357. bool hasMessage() const;
  2358. std::string getExpression() const;
  2359. std::string getExpressionInMacro() const;
  2360. bool hasExpandedExpression() const;
  2361. std::string getExpandedExpression() const;
  2362. std::string getMessage() const;
  2363. SourceLineInfo getSourceInfo() const;
  2364. std::string getTestMacroName() const;
  2365. //protected:
  2366. AssertionInfo m_info;
  2367. AssertionResultData m_resultData;
  2368. };
  2369. } // end namespace Catch
  2370. // end catch_assertionresult.h
  2371. // start catch_option.hpp
  2372. namespace Catch {
  2373. // An optional type
  2374. template<typename T>
  2375. class Option {
  2376. public:
  2377. Option() : nullableValue( nullptr ) {}
  2378. Option( T const& _value )
  2379. : nullableValue( new( storage ) T( _value ) )
  2380. {}
  2381. Option( Option const& _other )
  2382. : nullableValue( _other ? new( storage ) T( *_other ) : nullptr )
  2383. {}
  2384. ~Option() {
  2385. reset();
  2386. }
  2387. Option& operator= ( Option const& _other ) {
  2388. if( &_other != this ) {
  2389. reset();
  2390. if( _other )
  2391. nullableValue = new( storage ) T( *_other );
  2392. }
  2393. return *this;
  2394. }
  2395. Option& operator = ( T const& _value ) {
  2396. reset();
  2397. nullableValue = new( storage ) T( _value );
  2398. return *this;
  2399. }
  2400. void reset() {
  2401. if( nullableValue )
  2402. nullableValue->~T();
  2403. nullableValue = nullptr;
  2404. }
  2405. T& operator*() { return *nullableValue; }
  2406. T const& operator*() const { return *nullableValue; }
  2407. T* operator->() { return nullableValue; }
  2408. const T* operator->() const { return nullableValue; }
  2409. T valueOr( T const& defaultValue ) const {
  2410. return nullableValue ? *nullableValue : defaultValue;
  2411. }
  2412. bool some() const { return nullableValue != nullptr; }
  2413. bool none() const { return nullableValue == nullptr; }
  2414. bool operator !() const { return nullableValue == nullptr; }
  2415. explicit operator bool() const {
  2416. return some();
  2417. }
  2418. private:
  2419. T *nullableValue;
  2420. alignas(alignof(T)) char storage[sizeof(T)];
  2421. };
  2422. } // end namespace Catch
  2423. // end catch_option.hpp
  2424. #include <string>
  2425. #include <iosfwd>
  2426. #include <map>
  2427. #include <set>
  2428. #include <memory>
  2429. namespace Catch {
  2430. struct ReporterConfig {
  2431. explicit ReporterConfig( IConfigPtr const& _fullConfig );
  2432. ReporterConfig( IConfigPtr const& _fullConfig, std::ostream& _stream );
  2433. std::ostream& stream() const;
  2434. IConfigPtr fullConfig() const;
  2435. private:
  2436. std::ostream* m_stream;
  2437. IConfigPtr m_fullConfig;
  2438. };
  2439. struct ReporterPreferences {
  2440. bool shouldRedirectStdOut = false;
  2441. };
  2442. template<typename T>
  2443. struct LazyStat : Option<T> {
  2444. LazyStat& operator=( T const& _value ) {
  2445. Option<T>::operator=( _value );
  2446. used = false;
  2447. return *this;
  2448. }
  2449. void reset() {
  2450. Option<T>::reset();
  2451. used = false;
  2452. }
  2453. bool used = false;
  2454. };
  2455. struct TestRunInfo {
  2456. TestRunInfo( std::string const& _name );
  2457. std::string name;
  2458. };
  2459. struct GroupInfo {
  2460. GroupInfo( std::string const& _name,
  2461. std::size_t _groupIndex,
  2462. std::size_t _groupsCount );
  2463. std::string name;
  2464. std::size_t groupIndex;
  2465. std::size_t groupsCounts;
  2466. };
  2467. struct AssertionStats {
  2468. AssertionStats( AssertionResult const& _assertionResult,
  2469. std::vector<MessageInfo> const& _infoMessages,
  2470. Totals const& _totals );
  2471. AssertionStats( AssertionStats const& ) = default;
  2472. AssertionStats( AssertionStats && ) = default;
  2473. AssertionStats& operator = ( AssertionStats const& ) = default;
  2474. AssertionStats& operator = ( AssertionStats && ) = default;
  2475. virtual ~AssertionStats();
  2476. AssertionResult assertionResult;
  2477. std::vector<MessageInfo> infoMessages;
  2478. Totals totals;
  2479. };
  2480. struct SectionStats {
  2481. SectionStats( SectionInfo const& _sectionInfo,
  2482. Counts const& _assertions,
  2483. double _durationInSeconds,
  2484. bool _missingAssertions );
  2485. SectionStats( SectionStats const& ) = default;
  2486. SectionStats( SectionStats && ) = default;
  2487. SectionStats& operator = ( SectionStats const& ) = default;
  2488. SectionStats& operator = ( SectionStats && ) = default;
  2489. virtual ~SectionStats();
  2490. SectionInfo sectionInfo;
  2491. Counts assertions;
  2492. double durationInSeconds;
  2493. bool missingAssertions;
  2494. };
  2495. struct TestCaseStats {
  2496. TestCaseStats( TestCaseInfo const& _testInfo,
  2497. Totals const& _totals,
  2498. std::string const& _stdOut,
  2499. std::string const& _stdErr,
  2500. bool _aborting );
  2501. TestCaseStats( TestCaseStats const& ) = default;
  2502. TestCaseStats( TestCaseStats && ) = default;
  2503. TestCaseStats& operator = ( TestCaseStats const& ) = default;
  2504. TestCaseStats& operator = ( TestCaseStats && ) = default;
  2505. virtual ~TestCaseStats();
  2506. TestCaseInfo testInfo;
  2507. Totals totals;
  2508. std::string stdOut;
  2509. std::string stdErr;
  2510. bool aborting;
  2511. };
  2512. struct TestGroupStats {
  2513. TestGroupStats( GroupInfo const& _groupInfo,
  2514. Totals const& _totals,
  2515. bool _aborting );
  2516. TestGroupStats( GroupInfo const& _groupInfo );
  2517. TestGroupStats( TestGroupStats const& ) = default;
  2518. TestGroupStats( TestGroupStats && ) = default;
  2519. TestGroupStats& operator = ( TestGroupStats const& ) = default;
  2520. TestGroupStats& operator = ( TestGroupStats && ) = default;
  2521. virtual ~TestGroupStats();
  2522. GroupInfo groupInfo;
  2523. Totals totals;
  2524. bool aborting;
  2525. };
  2526. struct TestRunStats {
  2527. TestRunStats( TestRunInfo const& _runInfo,
  2528. Totals const& _totals,
  2529. bool _aborting );
  2530. TestRunStats( TestRunStats const& ) = default;
  2531. TestRunStats( TestRunStats && ) = default;
  2532. TestRunStats& operator = ( TestRunStats const& ) = default;
  2533. TestRunStats& operator = ( TestRunStats && ) = default;
  2534. virtual ~TestRunStats();
  2535. TestRunInfo runInfo;
  2536. Totals totals;
  2537. bool aborting;
  2538. };
  2539. struct BenchmarkInfo {
  2540. std::string name;
  2541. };
  2542. struct BenchmarkStats {
  2543. BenchmarkInfo info;
  2544. std::size_t iterations;
  2545. uint64_t elapsedTimeInNanoseconds;
  2546. };
  2547. struct IStreamingReporter {
  2548. virtual ~IStreamingReporter() = default;
  2549. // Implementing class must also provide the following static methods:
  2550. // static std::string getDescription();
  2551. // static std::set<Verbosity> getSupportedVerbosities()
  2552. virtual ReporterPreferences getPreferences() const = 0;
  2553. virtual void noMatchingTestCases( std::string const& spec ) = 0;
  2554. virtual void testRunStarting( TestRunInfo const& testRunInfo ) = 0;
  2555. virtual void testGroupStarting( GroupInfo const& groupInfo ) = 0;
  2556. virtual void testCaseStarting( TestCaseInfo const& testInfo ) = 0;
  2557. virtual void sectionStarting( SectionInfo const& sectionInfo ) = 0;
  2558. // *** experimental ***
  2559. virtual void benchmarkStarting( BenchmarkInfo const& ) {}
  2560. virtual void assertionStarting( AssertionInfo const& assertionInfo ) = 0;
  2561. // The return value indicates if the messages buffer should be cleared:
  2562. virtual bool assertionEnded( AssertionStats const& assertionStats ) = 0;
  2563. // *** experimental ***
  2564. virtual void benchmarkEnded( BenchmarkStats const& ) {}
  2565. virtual void sectionEnded( SectionStats const& sectionStats ) = 0;
  2566. virtual void testCaseEnded( TestCaseStats const& testCaseStats ) = 0;
  2567. virtual void testGroupEnded( TestGroupStats const& testGroupStats ) = 0;
  2568. virtual void testRunEnded( TestRunStats const& testRunStats ) = 0;
  2569. virtual void skipTest( TestCaseInfo const& testInfo ) = 0;
  2570. // Default empty implementation provided
  2571. virtual void fatalErrorEncountered( StringRef name );
  2572. virtual bool isMulti() const;
  2573. };
  2574. using IStreamingReporterPtr = std::unique_ptr<IStreamingReporter>;
  2575. struct IReporterFactory {
  2576. virtual ~IReporterFactory();
  2577. virtual IStreamingReporterPtr create( ReporterConfig const& config ) const = 0;
  2578. virtual std::string getDescription() const = 0;
  2579. };
  2580. using IReporterFactoryPtr = std::shared_ptr<IReporterFactory>;
  2581. struct IReporterRegistry {
  2582. using FactoryMap = std::map<std::string, IReporterFactoryPtr>;
  2583. using Listeners = std::vector<IReporterFactoryPtr>;
  2584. virtual ~IReporterRegistry();
  2585. virtual IStreamingReporterPtr create( std::string const& name, IConfigPtr const& config ) const = 0;
  2586. virtual FactoryMap const& getFactories() const = 0;
  2587. virtual Listeners const& getListeners() const = 0;
  2588. };
  2589. void addReporter( IStreamingReporterPtr& existingReporter, IStreamingReporterPtr&& additionalReporter );
  2590. } // end namespace Catch
  2591. // end catch_interfaces_reporter.h
  2592. #include <algorithm>
  2593. #include <cstring>
  2594. #include <cfloat>
  2595. #include <cstdio>
  2596. #include <assert.h>
  2597. #include <memory>
  2598. namespace Catch {
  2599. void prepareExpandedExpression(AssertionResult& result);
  2600. // Returns double formatted as %.3f (format expected on output)
  2601. std::string getFormattedDuration( double duration );
  2602. template<typename DerivedT>
  2603. struct StreamingReporterBase : IStreamingReporter {
  2604. StreamingReporterBase( ReporterConfig const& _config )
  2605. : m_config( _config.fullConfig() ),
  2606. stream( _config.stream() )
  2607. {
  2608. m_reporterPrefs.shouldRedirectStdOut = false;
  2609. CATCH_ENFORCE( DerivedT::getSupportedVerbosities().count( m_config->verbosity() ), "Verbosity level not supported by this reporter" );
  2610. }
  2611. ReporterPreferences getPreferences() const override {
  2612. return m_reporterPrefs;
  2613. }
  2614. static std::set<Verbosity> getSupportedVerbosities() {
  2615. return { Verbosity::Normal };
  2616. }
  2617. ~StreamingReporterBase() override = default;
  2618. void noMatchingTestCases(std::string const&) override {}
  2619. void testRunStarting(TestRunInfo const& _testRunInfo) override {
  2620. currentTestRunInfo = _testRunInfo;
  2621. }
  2622. void testGroupStarting(GroupInfo const& _groupInfo) override {
  2623. currentGroupInfo = _groupInfo;
  2624. }
  2625. void testCaseStarting(TestCaseInfo const& _testInfo) override {
  2626. currentTestCaseInfo = _testInfo;
  2627. }
  2628. void sectionStarting(SectionInfo const& _sectionInfo) override {
  2629. m_sectionStack.push_back(_sectionInfo);
  2630. }
  2631. void sectionEnded(SectionStats const& /* _sectionStats */) override {
  2632. m_sectionStack.pop_back();
  2633. }
  2634. void testCaseEnded(TestCaseStats const& /* _testCaseStats */) override {
  2635. currentTestCaseInfo.reset();
  2636. }
  2637. void testGroupEnded(TestGroupStats const& /* _testGroupStats */) override {
  2638. currentGroupInfo.reset();
  2639. }
  2640. void testRunEnded(TestRunStats const& /* _testRunStats */) override {
  2641. currentTestCaseInfo.reset();
  2642. currentGroupInfo.reset();
  2643. currentTestRunInfo.reset();
  2644. }
  2645. void skipTest(TestCaseInfo const&) override {
  2646. // Don't do anything with this by default.
  2647. // It can optionally be overridden in the derived class.
  2648. }
  2649. IConfigPtr m_config;
  2650. std::ostream& stream;
  2651. LazyStat<TestRunInfo> currentTestRunInfo;
  2652. LazyStat<GroupInfo> currentGroupInfo;
  2653. LazyStat<TestCaseInfo> currentTestCaseInfo;
  2654. std::vector<SectionInfo> m_sectionStack;
  2655. ReporterPreferences m_reporterPrefs;
  2656. };
  2657. template<typename DerivedT>
  2658. struct CumulativeReporterBase : IStreamingReporter {
  2659. template<typename T, typename ChildNodeT>
  2660. struct Node {
  2661. explicit Node( T const& _value ) : value( _value ) {}
  2662. virtual ~Node() {}
  2663. using ChildNodes = std::vector<std::shared_ptr<ChildNodeT>>;
  2664. T value;
  2665. ChildNodes children;
  2666. };
  2667. struct SectionNode {
  2668. explicit SectionNode(SectionStats const& _stats) : stats(_stats) {}
  2669. virtual ~SectionNode() = default;
  2670. bool operator == (SectionNode const& other) const {
  2671. return stats.sectionInfo.lineInfo == other.stats.sectionInfo.lineInfo;
  2672. }
  2673. bool operator == (std::shared_ptr<SectionNode> const& other) const {
  2674. return operator==(*other);
  2675. }
  2676. SectionStats stats;
  2677. using ChildSections = std::vector<std::shared_ptr<SectionNode>>;
  2678. using Assertions = std::vector<AssertionStats>;
  2679. ChildSections childSections;
  2680. Assertions assertions;
  2681. std::string stdOut;
  2682. std::string stdErr;
  2683. };
  2684. struct BySectionInfo {
  2685. BySectionInfo( SectionInfo const& other ) : m_other( other ) {}
  2686. BySectionInfo( BySectionInfo const& other ) : m_other( other.m_other ) {}
  2687. bool operator() (std::shared_ptr<SectionNode> const& node) const {
  2688. return ((node->stats.sectionInfo.name == m_other.name) &&
  2689. (node->stats.sectionInfo.lineInfo == m_other.lineInfo));
  2690. }
  2691. void operator=(BySectionInfo const&) = delete;
  2692. private:
  2693. SectionInfo const& m_other;
  2694. };
  2695. using TestCaseNode = Node<TestCaseStats, SectionNode>;
  2696. using TestGroupNode = Node<TestGroupStats, TestCaseNode>;
  2697. using TestRunNode = Node<TestRunStats, TestGroupNode>;
  2698. CumulativeReporterBase( ReporterConfig const& _config )
  2699. : m_config( _config.fullConfig() ),
  2700. stream( _config.stream() )
  2701. {
  2702. m_reporterPrefs.shouldRedirectStdOut = false;
  2703. CATCH_ENFORCE( DerivedT::getSupportedVerbosities().count( m_config->verbosity() ), "Verbosity level not supported by this reporter" );
  2704. }
  2705. ~CumulativeReporterBase() override = default;
  2706. ReporterPreferences getPreferences() const override {
  2707. return m_reporterPrefs;
  2708. }
  2709. static std::set<Verbosity> getSupportedVerbosities() {
  2710. return { Verbosity::Normal };
  2711. }
  2712. void testRunStarting( TestRunInfo const& ) override {}
  2713. void testGroupStarting( GroupInfo const& ) override {}
  2714. void testCaseStarting( TestCaseInfo const& ) override {}
  2715. void sectionStarting( SectionInfo const& sectionInfo ) override {
  2716. SectionStats incompleteStats( sectionInfo, Counts(), 0, false );
  2717. std::shared_ptr<SectionNode> node;
  2718. if( m_sectionStack.empty() ) {
  2719. if( !m_rootSection )
  2720. m_rootSection = std::make_shared<SectionNode>( incompleteStats );
  2721. node = m_rootSection;
  2722. }
  2723. else {
  2724. SectionNode& parentNode = *m_sectionStack.back();
  2725. auto it =
  2726. std::find_if( parentNode.childSections.begin(),
  2727. parentNode.childSections.end(),
  2728. BySectionInfo( sectionInfo ) );
  2729. if( it == parentNode.childSections.end() ) {
  2730. node = std::make_shared<SectionNode>( incompleteStats );
  2731. parentNode.childSections.push_back( node );
  2732. }
  2733. else
  2734. node = *it;
  2735. }
  2736. m_sectionStack.push_back( node );
  2737. m_deepestSection = std::move(node);
  2738. }
  2739. void assertionStarting(AssertionInfo const&) override {}
  2740. bool assertionEnded(AssertionStats const& assertionStats) override {
  2741. assert(!m_sectionStack.empty());
  2742. // AssertionResult holds a pointer to a temporary DecomposedExpression,
  2743. // which getExpandedExpression() calls to build the expression string.
  2744. // Our section stack copy of the assertionResult will likely outlive the
  2745. // temporary, so it must be expanded or discarded now to avoid calling
  2746. // a destroyed object later.
  2747. prepareExpandedExpression(const_cast<AssertionResult&>( assertionStats.assertionResult ) );
  2748. SectionNode& sectionNode = *m_sectionStack.back();
  2749. sectionNode.assertions.push_back(assertionStats);
  2750. return true;
  2751. }
  2752. void sectionEnded(SectionStats const& sectionStats) override {
  2753. assert(!m_sectionStack.empty());
  2754. SectionNode& node = *m_sectionStack.back();
  2755. node.stats = sectionStats;
  2756. m_sectionStack.pop_back();
  2757. }
  2758. void testCaseEnded(TestCaseStats const& testCaseStats) override {
  2759. auto node = std::make_shared<TestCaseNode>(testCaseStats);
  2760. assert(m_sectionStack.size() == 0);
  2761. node->children.push_back(m_rootSection);
  2762. m_testCases.push_back(node);
  2763. m_rootSection.reset();
  2764. assert(m_deepestSection);
  2765. m_deepestSection->stdOut = testCaseStats.stdOut;
  2766. m_deepestSection->stdErr = testCaseStats.stdErr;
  2767. }
  2768. void testGroupEnded(TestGroupStats const& testGroupStats) override {
  2769. auto node = std::make_shared<TestGroupNode>(testGroupStats);
  2770. node->children.swap(m_testCases);
  2771. m_testGroups.push_back(node);
  2772. }
  2773. void testRunEnded(TestRunStats const& testRunStats) override {
  2774. auto node = std::make_shared<TestRunNode>(testRunStats);
  2775. node->children.swap(m_testGroups);
  2776. m_testRuns.push_back(node);
  2777. testRunEndedCumulative();
  2778. }
  2779. virtual void testRunEndedCumulative() = 0;
  2780. void skipTest(TestCaseInfo const&) override {}
  2781. IConfigPtr m_config;
  2782. std::ostream& stream;
  2783. std::vector<AssertionStats> m_assertions;
  2784. std::vector<std::vector<std::shared_ptr<SectionNode>>> m_sections;
  2785. std::vector<std::shared_ptr<TestCaseNode>> m_testCases;
  2786. std::vector<std::shared_ptr<TestGroupNode>> m_testGroups;
  2787. std::vector<std::shared_ptr<TestRunNode>> m_testRuns;
  2788. std::shared_ptr<SectionNode> m_rootSection;
  2789. std::shared_ptr<SectionNode> m_deepestSection;
  2790. std::vector<std::shared_ptr<SectionNode>> m_sectionStack;
  2791. ReporterPreferences m_reporterPrefs;
  2792. };
  2793. template<char C>
  2794. char const* getLineOfChars() {
  2795. static char line[CATCH_CONFIG_CONSOLE_WIDTH] = {0};
  2796. if( !*line ) {
  2797. std::memset( line, C, CATCH_CONFIG_CONSOLE_WIDTH-1 );
  2798. line[CATCH_CONFIG_CONSOLE_WIDTH-1] = 0;
  2799. }
  2800. return line;
  2801. }
  2802. struct TestEventListenerBase : StreamingReporterBase<TestEventListenerBase> {
  2803. TestEventListenerBase( ReporterConfig const& _config );
  2804. void assertionStarting(AssertionInfo const&) override;
  2805. bool assertionEnded(AssertionStats const&) override;
  2806. };
  2807. } // end namespace Catch
  2808. // end catch_reporter_bases.hpp
  2809. // start catch_console_colour.h
  2810. namespace Catch {
  2811. struct Colour {
  2812. enum Code {
  2813. None = 0,
  2814. White,
  2815. Red,
  2816. Green,
  2817. Blue,
  2818. Cyan,
  2819. Yellow,
  2820. Grey,
  2821. Bright = 0x10,
  2822. BrightRed = Bright | Red,
  2823. BrightGreen = Bright | Green,
  2824. LightGrey = Bright | Grey,
  2825. BrightWhite = Bright | White,
  2826. // By intention
  2827. FileName = LightGrey,
  2828. Warning = Yellow,
  2829. ResultError = BrightRed,
  2830. ResultSuccess = BrightGreen,
  2831. ResultExpectedFailure = Warning,
  2832. Error = BrightRed,
  2833. Success = Green,
  2834. OriginalExpression = Cyan,
  2835. ReconstructedExpression = Yellow,
  2836. SecondaryText = LightGrey,
  2837. Headers = White
  2838. };
  2839. // Use constructed object for RAII guard
  2840. Colour( Code _colourCode );
  2841. Colour( Colour&& other ) noexcept;
  2842. Colour& operator=( Colour&& other ) noexcept;
  2843. ~Colour();
  2844. // Use static method for one-shot changes
  2845. static void use( Code _colourCode );
  2846. private:
  2847. bool m_moved = false;
  2848. };
  2849. std::ostream& operator << ( std::ostream& os, Colour const& );
  2850. } // end namespace Catch
  2851. // end catch_console_colour.h
  2852. // start catch_reporter_registrars.hpp
  2853. namespace Catch {
  2854. template<typename T>
  2855. class ReporterRegistrar {
  2856. class ReporterFactory : public IReporterFactory {
  2857. virtual IStreamingReporterPtr create( ReporterConfig const& config ) const override {
  2858. return std::unique_ptr<T>( new T( config ) );
  2859. }
  2860. virtual std::string getDescription() const override {
  2861. return T::getDescription();
  2862. }
  2863. };
  2864. public:
  2865. ReporterRegistrar( std::string const& name ) {
  2866. getMutableRegistryHub().registerReporter( name, std::make_shared<ReporterFactory>() );
  2867. }
  2868. };
  2869. template<typename T>
  2870. class ListenerRegistrar {
  2871. class ListenerFactory : public IReporterFactory {
  2872. virtual IStreamingReporterPtr create( ReporterConfig const& config ) const override {
  2873. return std::unique_ptr<T>( new T( config ) );
  2874. }
  2875. virtual std::string getDescription() const override {
  2876. return std::string();
  2877. }
  2878. };
  2879. public:
  2880. ListenerRegistrar() {
  2881. getMutableRegistryHub().registerListener( std::make_shared<ListenerFactory>() );
  2882. }
  2883. };
  2884. }
  2885. #if !defined(CATCH_CONFIG_DISABLE)
  2886. #define CATCH_REGISTER_REPORTER( name, reporterType ) \
  2887. CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
  2888. namespace{ Catch::ReporterRegistrar<reporterType> catch_internal_RegistrarFor##reporterType( name ); } \
  2889. CATCH_INTERNAL_UNSUPPRESS_GLOBALS_WARNINGS
  2890. #define CATCH_REGISTER_LISTENER( listenerType ) \
  2891. CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
  2892. namespace{ Catch::ListenerRegistrar<listenerType> catch_internal_RegistrarFor##listenerType; } \
  2893. CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS
  2894. #else // CATCH_CONFIG_DISABLE
  2895. #define CATCH_REGISTER_REPORTER(name, reporterType)
  2896. #define CATCH_REGISTER_LISTENER(listenerType)
  2897. #endif // CATCH_CONFIG_DISABLE
  2898. // end catch_reporter_registrars.hpp
  2899. // end catch_external_interfaces.h
  2900. #endif
  2901. #ifdef CATCH_IMPL
  2902. // start catch_impl.hpp
  2903. #ifdef __clang__
  2904. #pragma clang diagnostic push
  2905. #pragma clang diagnostic ignored "-Wweak-vtables"
  2906. #endif
  2907. // Keep these here for external reporters
  2908. // start catch_test_case_tracker.h
  2909. #include <string>
  2910. #include <vector>
  2911. #include <memory>
  2912. namespace Catch {
  2913. namespace TestCaseTracking {
  2914. struct NameAndLocation {
  2915. std::string name;
  2916. SourceLineInfo location;
  2917. NameAndLocation( std::string const& _name, SourceLineInfo const& _location );
  2918. };
  2919. struct ITracker;
  2920. using ITrackerPtr = std::shared_ptr<ITracker>;
  2921. struct ITracker {
  2922. virtual ~ITracker();
  2923. // static queries
  2924. virtual NameAndLocation const& nameAndLocation() const = 0;
  2925. // dynamic queries
  2926. virtual bool isComplete() const = 0; // Successfully completed or failed
  2927. virtual bool isSuccessfullyCompleted() const = 0;
  2928. virtual bool isOpen() const = 0; // Started but not complete
  2929. virtual bool hasChildren() const = 0;
  2930. virtual ITracker& parent() = 0;
  2931. // actions
  2932. virtual void close() = 0; // Successfully complete
  2933. virtual void fail() = 0;
  2934. virtual void markAsNeedingAnotherRun() = 0;
  2935. virtual void addChild( ITrackerPtr const& child ) = 0;
  2936. virtual ITrackerPtr findChild( NameAndLocation const& nameAndLocation ) = 0;
  2937. virtual void openChild() = 0;
  2938. // Debug/ checking
  2939. virtual bool isSectionTracker() const = 0;
  2940. virtual bool isIndexTracker() const = 0;
  2941. };
  2942. class TrackerContext {
  2943. enum RunState {
  2944. NotStarted,
  2945. Executing,
  2946. CompletedCycle
  2947. };
  2948. ITrackerPtr m_rootTracker;
  2949. ITracker* m_currentTracker = nullptr;
  2950. RunState m_runState = NotStarted;
  2951. public:
  2952. static TrackerContext& instance();
  2953. ITracker& startRun();
  2954. void endRun();
  2955. void startCycle();
  2956. void completeCycle();
  2957. bool completedCycle() const;
  2958. ITracker& currentTracker();
  2959. void setCurrentTracker( ITracker* tracker );
  2960. };
  2961. class TrackerBase : public ITracker {
  2962. protected:
  2963. enum CycleState {
  2964. NotStarted,
  2965. Executing,
  2966. ExecutingChildren,
  2967. NeedsAnotherRun,
  2968. CompletedSuccessfully,
  2969. Failed
  2970. };
  2971. class TrackerHasName {
  2972. NameAndLocation m_nameAndLocation;
  2973. public:
  2974. TrackerHasName( NameAndLocation const& nameAndLocation );
  2975. bool operator ()( ITrackerPtr const& tracker ) const;
  2976. };
  2977. using Children = std::vector<ITrackerPtr>;
  2978. NameAndLocation m_nameAndLocation;
  2979. TrackerContext& m_ctx;
  2980. ITracker* m_parent;
  2981. Children m_children;
  2982. CycleState m_runState = NotStarted;
  2983. public:
  2984. TrackerBase( NameAndLocation const& nameAndLocation, TrackerContext& ctx, ITracker* parent );
  2985. NameAndLocation const& nameAndLocation() const override;
  2986. bool isComplete() const override;
  2987. bool isSuccessfullyCompleted() const override;
  2988. bool isOpen() const override;
  2989. bool hasChildren() const override;
  2990. void addChild( ITrackerPtr const& child ) override;
  2991. ITrackerPtr findChild( NameAndLocation const& nameAndLocation ) override;
  2992. ITracker& parent() override;
  2993. void openChild() override;
  2994. bool isSectionTracker() const override;
  2995. bool isIndexTracker() const override;
  2996. void open();
  2997. void close() override;
  2998. void fail() override;
  2999. void markAsNeedingAnotherRun() override;
  3000. private:
  3001. void moveToParent();
  3002. void moveToThis();
  3003. };
  3004. class SectionTracker : public TrackerBase {
  3005. std::vector<std::string> m_filters;
  3006. public:
  3007. SectionTracker( NameAndLocation const& nameAndLocation, TrackerContext& ctx, ITracker* parent );
  3008. bool isSectionTracker() const override;
  3009. static SectionTracker& acquire( TrackerContext& ctx, NameAndLocation const& nameAndLocation );
  3010. void tryOpen();
  3011. void addInitialFilters( std::vector<std::string> const& filters );
  3012. void addNextFilters( std::vector<std::string> const& filters );
  3013. };
  3014. class IndexTracker : public TrackerBase {
  3015. int m_size;
  3016. int m_index = -1;
  3017. public:
  3018. IndexTracker( NameAndLocation const& nameAndLocation, TrackerContext& ctx, ITracker* parent, int size );
  3019. bool isIndexTracker() const override;
  3020. void close() override;
  3021. static IndexTracker& acquire( TrackerContext& ctx, NameAndLocation const& nameAndLocation, int size );
  3022. int index() const;
  3023. void moveNext();
  3024. };
  3025. } // namespace TestCaseTracking
  3026. using TestCaseTracking::ITracker;
  3027. using TestCaseTracking::TrackerContext;
  3028. using TestCaseTracking::SectionTracker;
  3029. using TestCaseTracking::IndexTracker;
  3030. } // namespace Catch
  3031. // end catch_test_case_tracker.h
  3032. // start catch_leak_detector.h
  3033. namespace Catch {
  3034. struct LeakDetector {
  3035. LeakDetector();
  3036. };
  3037. }
  3038. // end catch_leak_detector.h
  3039. // Cpp files will be included in the single-header file here
  3040. // start catch_approx.cpp
  3041. #include <limits>
  3042. namespace Catch {
  3043. namespace Detail {
  3044. double max(double lhs, double rhs) {
  3045. if (lhs < rhs) {
  3046. return rhs;
  3047. }
  3048. return lhs;
  3049. }
  3050. Approx::Approx ( double value )
  3051. : m_epsilon( std::numeric_limits<float>::epsilon()*100 ),
  3052. m_margin( 0.0 ),
  3053. m_scale( 1.0 ),
  3054. m_value( value )
  3055. {}
  3056. Approx Approx::custom() {
  3057. return Approx( 0 );
  3058. }
  3059. std::string Approx::toString() const {
  3060. std::ostringstream oss;
  3061. oss << "Approx( " << ::Catch::Detail::stringify( m_value ) << " )";
  3062. return oss.str();
  3063. }
  3064. } // end namespace Detail
  3065. std::string StringMaker<Catch::Detail::Approx>::convert(Catch::Detail::Approx const& value) {
  3066. return value.toString();
  3067. }
  3068. } // end namespace Catch
  3069. // end catch_approx.cpp
  3070. // start catch_assertionhandler.cpp
  3071. // start catch_context.h
  3072. #include <memory>
  3073. namespace Catch {
  3074. struct IResultCapture;
  3075. struct IRunner;
  3076. struct IConfig;
  3077. using IConfigPtr = std::shared_ptr<IConfig const>;
  3078. struct IContext
  3079. {
  3080. virtual ~IContext();
  3081. virtual IResultCapture* getResultCapture() = 0;
  3082. virtual IRunner* getRunner() = 0;
  3083. virtual IConfigPtr getConfig() const = 0;
  3084. };
  3085. struct IMutableContext : IContext
  3086. {
  3087. virtual ~IMutableContext();
  3088. virtual void setResultCapture( IResultCapture* resultCapture ) = 0;
  3089. virtual void setRunner( IRunner* runner ) = 0;
  3090. virtual void setConfig( IConfigPtr const& config ) = 0;
  3091. };
  3092. IContext& getCurrentContext();
  3093. IMutableContext& getCurrentMutableContext();
  3094. void cleanUpContext();
  3095. }
  3096. // end catch_context.h
  3097. #include <cassert>
  3098. namespace Catch {
  3099. auto operator <<( std::ostream& os, ITransientExpression const& expr ) -> std::ostream& {
  3100. expr.streamReconstructedExpression( os );
  3101. return os;
  3102. }
  3103. LazyExpression::LazyExpression( bool isNegated )
  3104. : m_isNegated( isNegated )
  3105. {}
  3106. LazyExpression::LazyExpression( LazyExpression const& other ) : m_isNegated( other.m_isNegated ) {}
  3107. LazyExpression::operator bool() const {
  3108. return m_transientExpression != nullptr;
  3109. }
  3110. auto operator << ( std::ostream& os, LazyExpression const& lazyExpr ) -> std::ostream& {
  3111. if( lazyExpr.m_isNegated )
  3112. os << "!";
  3113. if( lazyExpr ) {
  3114. if( lazyExpr.m_isNegated && lazyExpr.m_transientExpression->isBinaryExpression() )
  3115. os << "(" << *lazyExpr.m_transientExpression << ")";
  3116. else
  3117. os << *lazyExpr.m_transientExpression;
  3118. }
  3119. else {
  3120. os << "{** error - unchecked empty expression requested **}";
  3121. }
  3122. return os;
  3123. }
  3124. AssertionHandler::AssertionHandler
  3125. ( StringRef macroName,
  3126. SourceLineInfo const& lineInfo,
  3127. StringRef capturedExpression,
  3128. ResultDisposition::Flags resultDisposition )
  3129. : m_assertionInfo{ macroName, lineInfo, capturedExpression, resultDisposition }
  3130. {
  3131. getCurrentContext().getResultCapture()->assertionStarting( m_assertionInfo );
  3132. }
  3133. AssertionHandler::~AssertionHandler() {
  3134. if ( m_inExceptionGuard ) {
  3135. handle( ResultWas::ThrewException, "Exception translation was disabled by CATCH_CONFIG_FAST_COMPILE" );
  3136. getCurrentContext().getResultCapture()->exceptionEarlyReported();
  3137. }
  3138. }
  3139. void AssertionHandler::handle( ITransientExpression const& expr ) {
  3140. bool negated = isFalseTest( m_assertionInfo.resultDisposition );
  3141. bool result = expr.getResult() != negated;
  3142. handle( result ? ResultWas::Ok : ResultWas::ExpressionFailed, &expr, negated );
  3143. }
  3144. void AssertionHandler::handle( ResultWas::OfType resultType ) {
  3145. handle( resultType, nullptr, false );
  3146. }
  3147. void AssertionHandler::handle( ResultWas::OfType resultType, StringRef const& message ) {
  3148. AssertionResultData data( resultType, LazyExpression( false ) );
  3149. data.message = message;
  3150. handle( data, nullptr );
  3151. }
  3152. void AssertionHandler::handle( ResultWas::OfType resultType, ITransientExpression const* expr, bool negated ) {
  3153. AssertionResultData data( resultType, LazyExpression( negated ) );
  3154. handle( data, expr );
  3155. }
  3156. void AssertionHandler::handle( AssertionResultData const& resultData, ITransientExpression const* expr ) {
  3157. getResultCapture().assertionRun();
  3158. AssertionResult assertionResult{ m_assertionInfo, resultData };
  3159. assertionResult.m_resultData.lazyExpression.m_transientExpression = expr;
  3160. getResultCapture().assertionEnded( assertionResult );
  3161. if( !assertionResult.isOk() ) {
  3162. m_shouldDebugBreak = getCurrentContext().getConfig()->shouldDebugBreak();
  3163. m_shouldThrow =
  3164. getCurrentContext().getRunner()->aborting() ||
  3165. (m_assertionInfo.resultDisposition & ResultDisposition::Normal);
  3166. }
  3167. }
  3168. auto AssertionHandler::allowThrows() const -> bool {
  3169. return getCurrentContext().getConfig()->allowThrows();
  3170. }
  3171. auto AssertionHandler::shouldDebugBreak() const -> bool {
  3172. return m_shouldDebugBreak;
  3173. }
  3174. void AssertionHandler::reactWithDebugBreak() const {
  3175. if (m_shouldDebugBreak) {
  3176. ///////////////////////////////////////////////////////////////////
  3177. // To inspect the state during test, you need to go one level up the callstack
  3178. // To go back to the test and change execution, jump over the reactWithoutDebugBreak() call
  3179. ///////////////////////////////////////////////////////////////////
  3180. CATCH_BREAK_INTO_DEBUGGER();
  3181. }
  3182. reactWithoutDebugBreak();
  3183. }
  3184. void AssertionHandler::reactWithoutDebugBreak() const {
  3185. if( m_shouldThrow )
  3186. throw Catch::TestFailureException();
  3187. }
  3188. void AssertionHandler::useActiveException() {
  3189. handle( ResultWas::ThrewException, Catch::translateActiveException() );
  3190. }
  3191. void AssertionHandler::setExceptionGuard() {
  3192. assert( m_inExceptionGuard == false );
  3193. m_inExceptionGuard = true;
  3194. }
  3195. void AssertionHandler::unsetExceptionGuard() {
  3196. assert( m_inExceptionGuard == true );
  3197. m_inExceptionGuard = false;
  3198. }
  3199. // This is the overload that takes a string and infers the Equals matcher from it
  3200. // The more general overload, that takes any string matcher, is in catch_capture_matchers.cpp
  3201. void handleExceptionMatchExpr( AssertionHandler& handler, std::string const& str, StringRef matcherString ) {
  3202. handleExceptionMatchExpr( handler, Matchers::Equals( str ), matcherString );
  3203. }
  3204. } // namespace Catch
  3205. // end catch_assertionhandler.cpp
  3206. // start catch_assertionresult.cpp
  3207. namespace Catch {
  3208. AssertionResultData::AssertionResultData(ResultWas::OfType _resultType, LazyExpression const & _lazyExpression):
  3209. lazyExpression(_lazyExpression),
  3210. resultType(_resultType) {}
  3211. std::string AssertionResultData::reconstructExpression() const {
  3212. if( reconstructedExpression.empty() ) {
  3213. if( lazyExpression ) {
  3214. // !TBD Use stringstream for now, but rework above to pass stream in
  3215. std::ostringstream oss;
  3216. oss << lazyExpression;
  3217. reconstructedExpression = oss.str();
  3218. }
  3219. }
  3220. return reconstructedExpression;
  3221. }
  3222. AssertionResult::AssertionResult( AssertionInfo const& info, AssertionResultData const& data )
  3223. : m_info( info ),
  3224. m_resultData( data )
  3225. {}
  3226. // Result was a success
  3227. bool AssertionResult::succeeded() const {
  3228. return Catch::isOk( m_resultData.resultType );
  3229. }
  3230. // Result was a success, or failure is suppressed
  3231. bool AssertionResult::isOk() const {
  3232. return Catch::isOk( m_resultData.resultType ) || shouldSuppressFailure( m_info.resultDisposition );
  3233. }
  3234. ResultWas::OfType AssertionResult::getResultType() const {
  3235. return m_resultData.resultType;
  3236. }
  3237. bool AssertionResult::hasExpression() const {
  3238. return m_info.capturedExpression[0] != 0;
  3239. }
  3240. bool AssertionResult::hasMessage() const {
  3241. return !m_resultData.message.empty();
  3242. }
  3243. std::string AssertionResult::getExpression() const {
  3244. if (isFalseTest(m_info.resultDisposition))
  3245. return '!' + std::string(m_info.capturedExpression);
  3246. else
  3247. return m_info.capturedExpression;
  3248. }
  3249. std::string AssertionResult::getExpressionInMacro() const {
  3250. std::string expr;
  3251. if( m_info.macroName[0] == 0 )
  3252. expr = m_info.capturedExpression;
  3253. else {
  3254. expr.reserve( m_info.macroName.size() + m_info.capturedExpression.size() + 4 );
  3255. expr += m_info.macroName;
  3256. expr += "( ";
  3257. expr += m_info.capturedExpression;
  3258. expr += " )";
  3259. }
  3260. return expr;
  3261. }
  3262. bool AssertionResult::hasExpandedExpression() const {
  3263. return hasExpression() && getExpandedExpression() != getExpression();
  3264. }
  3265. std::string AssertionResult::getExpandedExpression() const {
  3266. std::string expr = m_resultData.reconstructExpression();
  3267. return expr.empty()
  3268. ? getExpression()
  3269. : expr;
  3270. }
  3271. std::string AssertionResult::getMessage() const {
  3272. return m_resultData.message;
  3273. }
  3274. SourceLineInfo AssertionResult::getSourceInfo() const {
  3275. return m_info.lineInfo;
  3276. }
  3277. std::string AssertionResult::getTestMacroName() const {
  3278. return m_info.macroName;
  3279. }
  3280. } // end namespace Catch
  3281. // end catch_assertionresult.cpp
  3282. // start catch_benchmark.cpp
  3283. namespace Catch {
  3284. auto BenchmarkLooper::getResolution() -> uint64_t {
  3285. return getEstimatedClockResolution() * getCurrentContext().getConfig()->benchmarkResolutionMultiple();
  3286. }
  3287. void BenchmarkLooper::reportStart() {
  3288. getResultCapture().benchmarkStarting( { m_name } );
  3289. }
  3290. auto BenchmarkLooper::needsMoreIterations() -> bool {
  3291. auto elapsed = m_timer.getElapsedNanoseconds();
  3292. // Exponentially increasing iterations until we're confident in our timer resolution
  3293. if( elapsed < m_resolution ) {
  3294. m_iterationsToRun *= 10;
  3295. return true;
  3296. }
  3297. getResultCapture().benchmarkEnded( { { m_name }, m_count, elapsed } );
  3298. return false;
  3299. }
  3300. } // end namespace Catch
  3301. // end catch_benchmark.cpp
  3302. // start catch_capture_matchers.cpp
  3303. namespace Catch {
  3304. using StringMatcher = Matchers::Impl::MatcherBase<std::string>;
  3305. // This is the general overload that takes a any string matcher
  3306. // There is another overload, in catch_assertinhandler.h/.cpp, that only takes a string and infers
  3307. // the Equals matcher (so the header does not mention matchers)
  3308. void handleExceptionMatchExpr( AssertionHandler& handler, StringMatcher const& matcher, StringRef matcherString ) {
  3309. std::string exceptionMessage = Catch::translateActiveException();
  3310. MatchExpr<std::string, StringMatcher const&> expr( exceptionMessage, matcher, matcherString );
  3311. handler.handle( expr );
  3312. }
  3313. } // namespace Catch
  3314. // end catch_capture_matchers.cpp
  3315. // start catch_commandline.cpp
  3316. // start catch_commandline.h
  3317. // start catch_clara.h
  3318. // Use Catch's value for console width (store Clara's off to the side, if present)
  3319. #ifdef CLARA_CONFIG_CONSOLE_WIDTH
  3320. #define CATCH_TEMP_CLARA_CONFIG_CONSOLE_WIDTH CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH
  3321. #undef CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH
  3322. #endif
  3323. #define CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH CATCH_CONFIG_CONSOLE_WIDTH-1
  3324. #ifdef __clang__
  3325. #pragma clang diagnostic push
  3326. #pragma clang diagnostic ignored "-Wweak-vtables"
  3327. #pragma clang diagnostic ignored "-Wexit-time-destructors"
  3328. #pragma clang diagnostic ignored "-Wshadow"
  3329. #endif
  3330. // start clara.hpp
  3331. // v1.0
  3332. // See https://github.com/philsquared/Clara
  3333. #ifndef CATCH_CLARA_CONFIG_CONSOLE_WIDTH
  3334. #define CATCH_CLARA_CONFIG_CONSOLE_WIDTH 80
  3335. #endif
  3336. // ----------- #included from clara_textflow.hpp -----------
  3337. // TextFlowCpp
  3338. //
  3339. // A single-header library for wrapping and laying out basic text, by Phil Nash
  3340. //
  3341. // This work is licensed under the BSD 2-Clause license.
  3342. // See the accompanying LICENSE file, or the one at https://opensource.org/licenses/BSD-2-Clause
  3343. //
  3344. // This project is hosted at https://github.com/philsquared/textflowcpp
  3345. #include <cassert>
  3346. #include <ostream>
  3347. #include <sstream>
  3348. #include <vector>
  3349. #ifndef CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH
  3350. #define CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH 80
  3351. #endif
  3352. namespace Catch { namespace clara { namespace TextFlow {
  3353. inline auto isWhitespace( char c ) -> bool {
  3354. static std::string chars = " \t\n\r";
  3355. return chars.find( c ) != std::string::npos;
  3356. }
  3357. inline auto isBreakableBefore( char c ) -> bool {
  3358. static std::string chars = "[({<|";
  3359. return chars.find( c ) != std::string::npos;
  3360. }
  3361. inline auto isBreakableAfter( char c ) -> bool {
  3362. static std::string chars = "])}>.,:;*+-=&/\\";
  3363. return chars.find( c ) != std::string::npos;
  3364. }
  3365. class Columns;
  3366. class Column {
  3367. std::vector<std::string> m_strings;
  3368. size_t m_width = CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH;
  3369. size_t m_indent = 0;
  3370. size_t m_initialIndent = std::string::npos;
  3371. public:
  3372. class iterator {
  3373. friend Column;
  3374. Column const& m_column;
  3375. size_t m_stringIndex = 0;
  3376. size_t m_pos = 0;
  3377. size_t m_len = 0;
  3378. size_t m_end = 0;
  3379. bool m_suffix = false;
  3380. iterator( Column const& column, size_t stringIndex )
  3381. : m_column( column ),
  3382. m_stringIndex( stringIndex )
  3383. {}
  3384. auto line() const -> std::string const& { return m_column.m_strings[m_stringIndex]; }
  3385. auto isBoundary( size_t at ) const -> bool {
  3386. assert( at > 0 );
  3387. assert( at <= line().size() );
  3388. return at == line().size() ||
  3389. ( isWhitespace( line()[at] ) && !isWhitespace( line()[at-1] ) ) ||
  3390. isBreakableBefore( line()[at] ) ||
  3391. isBreakableAfter( line()[at-1] );
  3392. }
  3393. void calcLength() {
  3394. assert( m_stringIndex < m_column.m_strings.size() );
  3395. m_suffix = false;
  3396. auto width = m_column.m_width-indent();
  3397. m_end = m_pos;
  3398. while( m_end < line().size() && line()[m_end] != '\n' )
  3399. ++m_end;
  3400. if( m_end < m_pos + width ) {
  3401. m_len = m_end - m_pos;
  3402. }
  3403. else {
  3404. size_t len = width;
  3405. while (len > 0 && !isBoundary(m_pos + len))
  3406. --len;
  3407. while (len > 0 && isWhitespace( line()[m_pos + len - 1] ))
  3408. --len;
  3409. if (len > 0) {
  3410. m_len = len;
  3411. } else {
  3412. m_suffix = true;
  3413. m_len = width - 1;
  3414. }
  3415. }
  3416. }
  3417. auto indent() const -> size_t {
  3418. auto initial = m_pos == 0 && m_stringIndex == 0 ? m_column.m_initialIndent : std::string::npos;
  3419. return initial == std::string::npos ? m_column.m_indent : initial;
  3420. }
  3421. auto addIndentAndSuffix(std::string const &plain) const -> std::string {
  3422. return std::string( indent(), ' ' ) + (m_suffix ? plain + "-" : plain);
  3423. }
  3424. public:
  3425. explicit iterator( Column const& column ) : m_column( column ) {
  3426. assert( m_column.m_width > m_column.m_indent );
  3427. assert( m_column.m_initialIndent == std::string::npos || m_column.m_width > m_column.m_initialIndent );
  3428. calcLength();
  3429. if( m_len == 0 )
  3430. m_stringIndex++; // Empty string
  3431. }
  3432. auto operator *() const -> std::string {
  3433. assert( m_stringIndex < m_column.m_strings.size() );
  3434. assert( m_pos <= m_end );
  3435. if( m_pos + m_column.m_width < m_end )
  3436. return addIndentAndSuffix(line().substr(m_pos, m_len));
  3437. else
  3438. return addIndentAndSuffix(line().substr(m_pos, m_end - m_pos));
  3439. }
  3440. auto operator ++() -> iterator& {
  3441. m_pos += m_len;
  3442. if( m_pos < line().size() && line()[m_pos] == '\n' )
  3443. m_pos += 1;
  3444. else
  3445. while( m_pos < line().size() && isWhitespace( line()[m_pos] ) )
  3446. ++m_pos;
  3447. if( m_pos == line().size() ) {
  3448. m_pos = 0;
  3449. ++m_stringIndex;
  3450. }
  3451. if( m_stringIndex < m_column.m_strings.size() )
  3452. calcLength();
  3453. return *this;
  3454. }
  3455. auto operator ++(int) -> iterator {
  3456. iterator prev( *this );
  3457. operator++();
  3458. return prev;
  3459. }
  3460. auto operator ==( iterator const& other ) const -> bool {
  3461. return
  3462. m_pos == other.m_pos &&
  3463. m_stringIndex == other.m_stringIndex &&
  3464. &m_column == &other.m_column;
  3465. }
  3466. auto operator !=( iterator const& other ) const -> bool {
  3467. return !operator==( other );
  3468. }
  3469. };
  3470. using const_iterator = iterator;
  3471. explicit Column( std::string const& text ) { m_strings.push_back( text ); }
  3472. auto width( size_t newWidth ) -> Column& {
  3473. assert( newWidth > 0 );
  3474. m_width = newWidth;
  3475. return *this;
  3476. }
  3477. auto indent( size_t newIndent ) -> Column& {
  3478. m_indent = newIndent;
  3479. return *this;
  3480. }
  3481. auto initialIndent( size_t newIndent ) -> Column& {
  3482. m_initialIndent = newIndent;
  3483. return *this;
  3484. }
  3485. auto width() const -> size_t { return m_width; }
  3486. auto begin() const -> iterator { return iterator( *this ); }
  3487. auto end() const -> iterator { return { *this, m_strings.size() }; }
  3488. inline friend std::ostream& operator << ( std::ostream& os, Column const& col ) {
  3489. bool first = true;
  3490. for( auto line : col ) {
  3491. if( first )
  3492. first = false;
  3493. else
  3494. os << "\n";
  3495. os << line;
  3496. }
  3497. return os;
  3498. }
  3499. auto operator + ( Column const& other ) -> Columns;
  3500. auto toString() const -> std::string {
  3501. std::ostringstream oss;
  3502. oss << *this;
  3503. return oss.str();
  3504. }
  3505. };
  3506. class Spacer : public Column {
  3507. public:
  3508. explicit Spacer( size_t spaceWidth ) : Column( "" ) {
  3509. width( spaceWidth );
  3510. }
  3511. };
  3512. class Columns {
  3513. std::vector<Column> m_columns;
  3514. public:
  3515. class iterator {
  3516. friend Columns;
  3517. struct EndTag {};
  3518. std::vector<Column> const& m_columns;
  3519. std::vector<Column::iterator> m_iterators;
  3520. size_t m_activeIterators;
  3521. iterator( Columns const& columns, EndTag )
  3522. : m_columns( columns.m_columns ),
  3523. m_activeIterators( 0 )
  3524. {
  3525. m_iterators.reserve( m_columns.size() );
  3526. for( auto const& col : m_columns )
  3527. m_iterators.push_back( col.end() );
  3528. }
  3529. public:
  3530. explicit iterator( Columns const& columns )
  3531. : m_columns( columns.m_columns ),
  3532. m_activeIterators( m_columns.size() )
  3533. {
  3534. m_iterators.reserve( m_columns.size() );
  3535. for( auto const& col : m_columns )
  3536. m_iterators.push_back( col.begin() );
  3537. }
  3538. auto operator ==( iterator const& other ) const -> bool {
  3539. return m_iterators == other.m_iterators;
  3540. }
  3541. auto operator !=( iterator const& other ) const -> bool {
  3542. return m_iterators != other.m_iterators;
  3543. }
  3544. auto operator *() const -> std::string {
  3545. std::string row, padding;
  3546. for( size_t i = 0; i < m_columns.size(); ++i ) {
  3547. auto width = m_columns[i].width();
  3548. if( m_iterators[i] != m_columns[i].end() ) {
  3549. std::string col = *m_iterators[i];
  3550. row += padding + col;
  3551. if( col.size() < width )
  3552. padding = std::string( width - col.size(), ' ' );
  3553. else
  3554. padding = "";
  3555. }
  3556. else {
  3557. padding += std::string( width, ' ' );
  3558. }
  3559. }
  3560. return row;
  3561. }
  3562. auto operator ++() -> iterator& {
  3563. for( size_t i = 0; i < m_columns.size(); ++i ) {
  3564. if (m_iterators[i] != m_columns[i].end())
  3565. ++m_iterators[i];
  3566. }
  3567. return *this;
  3568. }
  3569. auto operator ++(int) -> iterator {
  3570. iterator prev( *this );
  3571. operator++();
  3572. return prev;
  3573. }
  3574. };
  3575. using const_iterator = iterator;
  3576. auto begin() const -> iterator { return iterator( *this ); }
  3577. auto end() const -> iterator { return { *this, iterator::EndTag() }; }
  3578. auto operator += ( Column const& col ) -> Columns& {
  3579. m_columns.push_back( col );
  3580. return *this;
  3581. }
  3582. auto operator + ( Column const& col ) -> Columns {
  3583. Columns combined = *this;
  3584. combined += col;
  3585. return combined;
  3586. }
  3587. inline friend std::ostream& operator << ( std::ostream& os, Columns const& cols ) {
  3588. bool first = true;
  3589. for( auto line : cols ) {
  3590. if( first )
  3591. first = false;
  3592. else
  3593. os << "\n";
  3594. os << line;
  3595. }
  3596. return os;
  3597. }
  3598. auto toString() const -> std::string {
  3599. std::ostringstream oss;
  3600. oss << *this;
  3601. return oss.str();
  3602. }
  3603. };
  3604. inline auto Column::operator + ( Column const& other ) -> Columns {
  3605. Columns cols;
  3606. cols += *this;
  3607. cols += other;
  3608. return cols;
  3609. }
  3610. }}} // namespace Catch::clara::TextFlow
  3611. // ----------- end of #include from clara_textflow.hpp -----------
  3612. // ........... back in clara.hpp
  3613. #include <memory>
  3614. #include <set>
  3615. #include <algorithm>
  3616. #if !defined(CLARA_PLATFORM_WINDOWS) && ( defined(WIN32) || defined(__WIN32__) || defined(_WIN32) || defined(_MSC_VER) )
  3617. #define CLARA_PLATFORM_WINDOWS
  3618. #endif
  3619. namespace Catch { namespace clara {
  3620. namespace detail {
  3621. // Traits for extracting arg and return type of lambdas (for single argument lambdas)
  3622. template<typename L>
  3623. struct UnaryLambdaTraits : UnaryLambdaTraits<decltype(&L::operator())> {};
  3624. template<typename ClassT, typename ReturnT, typename... Args>
  3625. struct UnaryLambdaTraits<ReturnT(ClassT::*)(Args...) const> {
  3626. static const bool isValid = false;
  3627. };
  3628. template<typename ClassT, typename ReturnT, typename ArgT>
  3629. struct UnaryLambdaTraits<ReturnT(ClassT::*)(ArgT) const> {
  3630. static const bool isValid = true;
  3631. using ArgType = typename std::remove_const<typename std::remove_reference<ArgT>::type>::type;;
  3632. using ReturnType = ReturnT;
  3633. };
  3634. class TokenStream;
  3635. // Transport for raw args (copied from main args, or supplied via init list for testing)
  3636. class Args {
  3637. friend TokenStream;
  3638. std::string m_exeName;
  3639. std::vector<std::string> m_args;
  3640. public:
  3641. Args(int argc, char *argv[]) {
  3642. m_exeName = argv[0];
  3643. for (int i = 1; i < argc; ++i)
  3644. m_args.push_back(argv[i]);
  3645. }
  3646. Args(std::initializer_list<std::string> args)
  3647. : m_exeName( *args.begin() ),
  3648. m_args( args.begin()+1, args.end() )
  3649. {}
  3650. auto exeName() const -> std::string {
  3651. return m_exeName;
  3652. }
  3653. };
  3654. // Wraps a token coming from a token stream. These may not directly correspond to strings as a single string
  3655. // may encode an option + its argument if the : or = form is used
  3656. enum class TokenType {
  3657. Option, Argument
  3658. };
  3659. struct Token {
  3660. TokenType type;
  3661. std::string token;
  3662. };
  3663. // Abstracts iterators into args as a stream of tokens, with option arguments uniformly handled
  3664. class TokenStream {
  3665. using Iterator = std::vector<std::string>::const_iterator;
  3666. Iterator it;
  3667. Iterator itEnd;
  3668. std::vector<Token> m_tokenBuffer;
  3669. void loadBuffer() {
  3670. m_tokenBuffer.resize(0);
  3671. // Skip any empty strings
  3672. while (it != itEnd && it->empty())
  3673. ++it;
  3674. if (it != itEnd) {
  3675. auto const &next = *it;
  3676. if (next[0] == '-' || next[0] == '/') {
  3677. auto delimiterPos = next.find_first_of(" :=");
  3678. if (delimiterPos != std::string::npos) {
  3679. m_tokenBuffer.push_back({TokenType::Option, next.substr(0, delimiterPos)});
  3680. m_tokenBuffer.push_back({TokenType::Argument, next.substr(delimiterPos + 1)});
  3681. } else {
  3682. if (next[1] != '-' && next.size() > 2) {
  3683. std::string opt = "- ";
  3684. for (size_t i = 1; i < next.size(); ++i) {
  3685. opt[1] = next[i];
  3686. m_tokenBuffer.push_back({TokenType::Option, opt});
  3687. }
  3688. } else {
  3689. m_tokenBuffer.push_back({TokenType::Option, next});
  3690. }
  3691. }
  3692. } else {
  3693. m_tokenBuffer.push_back({TokenType::Argument, next});
  3694. }
  3695. }
  3696. }
  3697. public:
  3698. explicit TokenStream(Args const &args) : TokenStream(args.m_args.begin(), args.m_args.end()) {}
  3699. TokenStream(Iterator it, Iterator itEnd) : it(it), itEnd(itEnd) {
  3700. loadBuffer();
  3701. }
  3702. explicit operator bool() const {
  3703. return !m_tokenBuffer.empty() || it != itEnd;
  3704. }
  3705. auto count() const -> size_t { return m_tokenBuffer.size() + (itEnd - it); }
  3706. auto operator*() const -> Token {
  3707. assert(!m_tokenBuffer.empty());
  3708. return m_tokenBuffer.front();
  3709. }
  3710. auto operator->() const -> Token const * {
  3711. assert(!m_tokenBuffer.empty());
  3712. return &m_tokenBuffer.front();
  3713. }
  3714. auto operator++() -> TokenStream & {
  3715. if (m_tokenBuffer.size() >= 2) {
  3716. m_tokenBuffer.erase(m_tokenBuffer.begin());
  3717. } else {
  3718. if (it != itEnd)
  3719. ++it;
  3720. loadBuffer();
  3721. }
  3722. return *this;
  3723. }
  3724. };
  3725. class ResultBase {
  3726. public:
  3727. enum Type {
  3728. Ok, LogicError, RuntimeError
  3729. };
  3730. protected:
  3731. ResultBase(Type type) : m_type(type) {}
  3732. virtual ~ResultBase() = default;
  3733. virtual void enforceOk() const = 0;
  3734. Type m_type;
  3735. };
  3736. template<typename T>
  3737. class ResultValueBase : public ResultBase {
  3738. public:
  3739. auto value() const -> T const & {
  3740. enforceOk();
  3741. return m_value;
  3742. }
  3743. protected:
  3744. ResultValueBase(Type type) : ResultBase(type) {}
  3745. ResultValueBase(ResultValueBase const &other) : ResultBase(other) {
  3746. if (m_type == ResultBase::Ok)
  3747. new(&m_value) T(other.m_value);
  3748. }
  3749. ResultValueBase(Type, T const &value) : ResultBase(Ok) {
  3750. new(&m_value) T(value);
  3751. }
  3752. auto operator=(ResultValueBase const &other) -> ResultValueBase & {
  3753. if (m_type == ResultBase::Ok)
  3754. m_value.~T();
  3755. ResultBase::operator=(other);
  3756. if (m_type == ResultBase::Ok)
  3757. new(&m_value) T(other.m_value);
  3758. return *this;
  3759. }
  3760. ~ResultValueBase() {
  3761. if (m_type == Ok)
  3762. m_value.~T();
  3763. }
  3764. union {
  3765. T m_value;
  3766. };
  3767. };
  3768. template<>
  3769. class ResultValueBase<void> : public ResultBase {
  3770. protected:
  3771. using ResultBase::ResultBase;
  3772. };
  3773. template<typename T = void>
  3774. class BasicResult : public ResultValueBase<T> {
  3775. public:
  3776. template<typename U>
  3777. explicit BasicResult(BasicResult<U> const &other)
  3778. : ResultValueBase<T>(other.type()),
  3779. m_errorMessage(other.errorMessage()) {
  3780. assert(type() != ResultBase::Ok);
  3781. }
  3782. static auto ok() -> BasicResult { return {ResultBase::Ok}; }
  3783. template<typename U>
  3784. static auto ok(U const &value) -> BasicResult { return {ResultBase::Ok, value}; }
  3785. static auto logicError(std::string const &message) -> BasicResult { return {ResultBase::LogicError, message}; }
  3786. static auto runtimeError(std::string const &message) -> BasicResult {
  3787. return {ResultBase::RuntimeError, message};
  3788. }
  3789. explicit operator bool() const { return m_type == ResultBase::Ok; }
  3790. auto type() const -> ResultBase::Type { return m_type; }
  3791. auto errorMessage() const -> std::string { return m_errorMessage; }
  3792. protected:
  3793. virtual void enforceOk() const {
  3794. // !TBD: If no exceptions, std::terminate here or something
  3795. switch (m_type) {
  3796. case ResultBase::LogicError:
  3797. throw std::logic_error(m_errorMessage);
  3798. case ResultBase::RuntimeError:
  3799. throw std::runtime_error(m_errorMessage);
  3800. case ResultBase::Ok:
  3801. break;
  3802. }
  3803. }
  3804. std::string m_errorMessage; // Only populated if resultType is an error
  3805. BasicResult(ResultBase::Type type, std::string const &message)
  3806. : ResultValueBase<T>(type),
  3807. m_errorMessage(message) {
  3808. assert(m_type != ResultBase::Ok);
  3809. }
  3810. using ResultValueBase<T>::ResultValueBase;
  3811. using ResultBase::m_type;
  3812. };
  3813. enum class ParseResultType {
  3814. Matched, NoMatch, ShortCircuitAll, ShortCircuitSame
  3815. };
  3816. class ParseState {
  3817. public:
  3818. ParseState(ParseResultType type, TokenStream const &remainingTokens)
  3819. : m_type(type),
  3820. m_remainingTokens(remainingTokens) {}
  3821. auto type() const -> ParseResultType { return m_type; }
  3822. auto remainingTokens() const -> TokenStream { return m_remainingTokens; }
  3823. private:
  3824. ParseResultType m_type;
  3825. TokenStream m_remainingTokens;
  3826. };
  3827. using Result = BasicResult<void>;
  3828. using ParserResult = BasicResult<ParseResultType>;
  3829. using InternalParseResult = BasicResult<ParseState>;
  3830. struct HelpColumns {
  3831. std::string left;
  3832. std::string right;
  3833. };
  3834. template<typename T>
  3835. inline auto convertInto(std::string const &source, T& target) -> ParserResult {
  3836. std::stringstream ss;
  3837. ss << source;
  3838. ss >> target;
  3839. if (ss.fail())
  3840. return ParserResult::runtimeError("Unable to convert '" + source + "' to destination type");
  3841. else
  3842. return ParserResult::ok(ParseResultType::Matched);
  3843. }
  3844. inline auto convertInto(std::string const &source, std::string& target) -> ParserResult {
  3845. target = source;
  3846. return ParserResult::ok(ParseResultType::Matched);
  3847. }
  3848. inline auto convertInto(std::string const &source, bool &target) -> ParserResult {
  3849. std::string srcLC = source;
  3850. std::transform(srcLC.begin(), srcLC.end(), srcLC.begin(), [](char c) { return static_cast<char>( ::tolower(c) ); } );
  3851. if (srcLC == "y" || srcLC == "1" || srcLC == "true" || srcLC == "yes" || srcLC == "on")
  3852. target = true;
  3853. else if (srcLC == "n" || srcLC == "0" || srcLC == "false" || srcLC == "no" || srcLC == "off")
  3854. target = false;
  3855. else
  3856. return ParserResult::runtimeError("Expected a boolean value but did not recognise: '" + source + "'");
  3857. return ParserResult::ok(ParseResultType::Matched);
  3858. }
  3859. struct BoundRefBase {
  3860. BoundRefBase() = default;
  3861. BoundRefBase(BoundRefBase const &) = delete;
  3862. BoundRefBase(BoundRefBase &&) = delete;
  3863. BoundRefBase &operator=(BoundRefBase const &) = delete;
  3864. BoundRefBase &operator=(BoundRefBase &&) = delete;
  3865. virtual ~BoundRefBase() = default;
  3866. virtual auto isFlag() const -> bool = 0;
  3867. virtual auto isContainer() const -> bool { return false; }
  3868. virtual auto setValue(std::string const &arg) -> ParserResult = 0;
  3869. virtual auto setFlag(bool flag) -> ParserResult = 0;
  3870. };
  3871. struct BoundValueRefBase : BoundRefBase {
  3872. auto isFlag() const -> bool override { return false; }
  3873. auto setFlag(bool) -> ParserResult override {
  3874. return ParserResult::logicError("Flags can only be set on boolean fields");
  3875. }
  3876. };
  3877. struct BoundFlagRefBase : BoundRefBase {
  3878. auto isFlag() const -> bool override { return true; }
  3879. auto setValue(std::string const &arg) -> ParserResult override {
  3880. bool flag;
  3881. auto result = convertInto(arg, flag);
  3882. if (result)
  3883. setFlag(flag);
  3884. return result;
  3885. }
  3886. };
  3887. template<typename T>
  3888. struct BoundRef : BoundValueRefBase {
  3889. T &m_ref;
  3890. explicit BoundRef(T &ref) : m_ref(ref) {}
  3891. auto setValue(std::string const &arg) -> ParserResult override {
  3892. return convertInto(arg, m_ref);
  3893. }
  3894. };
  3895. template<typename T>
  3896. struct BoundRef<std::vector<T>> : BoundValueRefBase {
  3897. std::vector<T> &m_ref;
  3898. explicit BoundRef(std::vector<T> &ref) : m_ref(ref) {}
  3899. auto isContainer() const -> bool override { return true; }
  3900. auto setValue(std::string const &arg) -> ParserResult override {
  3901. T temp;
  3902. auto result = convertInto(arg, temp);
  3903. if (result)
  3904. m_ref.push_back(temp);
  3905. return result;
  3906. }
  3907. };
  3908. struct BoundFlagRef : BoundFlagRefBase {
  3909. bool &m_ref;
  3910. explicit BoundFlagRef(bool &ref) : m_ref(ref) {}
  3911. auto setFlag(bool flag) -> ParserResult override {
  3912. m_ref = flag;
  3913. return ParserResult::ok(ParseResultType::Matched);
  3914. }
  3915. };
  3916. template<typename ReturnType>
  3917. struct LambdaInvoker {
  3918. static_assert(std::is_same<ReturnType, ParserResult>::value, "Lambda must return void or clara::ParserResult");
  3919. template<typename L, typename ArgType>
  3920. static auto invoke(L const &lambda, ArgType const &arg) -> ParserResult {
  3921. return lambda(arg);
  3922. }
  3923. };
  3924. template<>
  3925. struct LambdaInvoker<void> {
  3926. template<typename L, typename ArgType>
  3927. static auto invoke(L const &lambda, ArgType const &arg) -> ParserResult {
  3928. lambda(arg);
  3929. return ParserResult::ok(ParseResultType::Matched);
  3930. }
  3931. };
  3932. template<typename ArgType, typename L>
  3933. inline auto invokeLambda(L const &lambda, std::string const &arg) -> ParserResult {
  3934. ArgType temp;
  3935. auto result = convertInto(arg, temp);
  3936. return !result
  3937. ? result
  3938. : LambdaInvoker<typename UnaryLambdaTraits<L>::ReturnType>::invoke(lambda, temp);
  3939. };
  3940. template<typename L>
  3941. struct BoundLambda : BoundValueRefBase {
  3942. L m_lambda;
  3943. static_assert( UnaryLambdaTraits<L>::isValid, "Supplied lambda must take exactly one argument" );
  3944. explicit BoundLambda(L const &lambda) : m_lambda(lambda) {}
  3945. auto setValue(std::string const &arg) -> ParserResult override {
  3946. return invokeLambda<typename UnaryLambdaTraits<L>::ArgType>(m_lambda, arg);
  3947. }
  3948. };
  3949. template<typename L>
  3950. struct BoundFlagLambda : BoundFlagRefBase {
  3951. L m_lambda;
  3952. static_assert( UnaryLambdaTraits<L>::isValid, "Supplied lambda must take exactly one argument" );
  3953. static_assert( std::is_same<typename UnaryLambdaTraits<L>::ArgType, bool>::value, "flags must be boolean" );
  3954. explicit BoundFlagLambda(L const &lambda) : m_lambda(lambda) {}
  3955. auto setFlag(bool flag) -> ParserResult override {
  3956. return LambdaInvoker<typename UnaryLambdaTraits<L>::ReturnType>::invoke(m_lambda, flag);
  3957. }
  3958. };
  3959. enum class Optionality {
  3960. Optional, Required
  3961. };
  3962. struct Parser;
  3963. class ParserBase {
  3964. public:
  3965. virtual ~ParserBase() = default;
  3966. virtual auto validate() const -> Result { return Result::ok(); }
  3967. virtual auto parse( std::string const& exeName, TokenStream const &tokens) const -> InternalParseResult = 0;
  3968. virtual auto cardinality() const -> size_t { return 1; }
  3969. auto parse(Args const &args) const -> InternalParseResult {
  3970. return parse( args.exeName(), TokenStream(args));
  3971. }
  3972. };
  3973. template<typename DerivedT>
  3974. class ComposableParserImpl : public ParserBase {
  3975. public:
  3976. template<typename T>
  3977. auto operator+(T const &other) const -> Parser;
  3978. };
  3979. // Common code and state for Args and Opts
  3980. template<typename DerivedT>
  3981. class ParserRefImpl : public ComposableParserImpl<DerivedT> {
  3982. protected:
  3983. Optionality m_optionality = Optionality::Optional;
  3984. std::shared_ptr<BoundRefBase> m_ref;
  3985. std::string m_hint;
  3986. std::string m_description;
  3987. explicit ParserRefImpl(std::shared_ptr<BoundRefBase> const &ref) : m_ref(ref) {}
  3988. public:
  3989. template<typename T>
  3990. ParserRefImpl(T &ref, std::string const &hint) : m_ref(std::make_shared<BoundRef<T>>(ref)), m_hint(hint) {}
  3991. template<typename LambdaT>
  3992. ParserRefImpl(LambdaT const &ref, std::string const &hint) : m_ref(std::make_shared<BoundLambda<LambdaT>>(ref)),
  3993. m_hint(hint) {}
  3994. auto operator()(std::string const &description) -> DerivedT & {
  3995. m_description = description;
  3996. return static_cast<DerivedT &>( *this );
  3997. }
  3998. auto optional() -> DerivedT & {
  3999. m_optionality = Optionality::Optional;
  4000. return static_cast<DerivedT &>( *this );
  4001. };
  4002. auto required() -> DerivedT & {
  4003. m_optionality = Optionality::Required;
  4004. return static_cast<DerivedT &>( *this );
  4005. };
  4006. auto isOptional() const -> bool {
  4007. return m_optionality == Optionality::Optional;
  4008. }
  4009. auto cardinality() const -> size_t override {
  4010. if (m_ref->isContainer())
  4011. return 0;
  4012. else
  4013. return 1;
  4014. }
  4015. auto hint() const -> std::string { return m_hint; }
  4016. };
  4017. class ExeName : public ComposableParserImpl<ExeName> {
  4018. std::shared_ptr<std::string> m_name;
  4019. std::shared_ptr<BoundRefBase> m_ref;
  4020. template<typename LambdaT>
  4021. static auto makeRef(LambdaT const &lambda) -> std::shared_ptr<BoundRefBase> {
  4022. return std::make_shared<BoundLambda<LambdaT>>(lambda);
  4023. }
  4024. public:
  4025. ExeName() : m_name(std::make_shared<std::string>("<executable>")) {}
  4026. explicit ExeName(std::string &ref) : ExeName() {
  4027. m_ref = std::make_shared<BoundRef<std::string>>( ref );
  4028. }
  4029. template<typename LambdaT>
  4030. explicit ExeName( LambdaT const& lambda ) : ExeName() {
  4031. m_ref = std::make_shared<BoundLambda<LambdaT>>( lambda );
  4032. }
  4033. // The exe name is not parsed out of the normal tokens, but is handled specially
  4034. auto parse( std::string const&, TokenStream const &tokens ) const -> InternalParseResult override {
  4035. return InternalParseResult::ok(ParseState(ParseResultType::NoMatch, tokens));
  4036. }
  4037. auto name() const -> std::string { return *m_name; }
  4038. auto set( std::string const& newName ) -> ParserResult {
  4039. auto lastSlash = newName.find_last_of( "\\/" );
  4040. auto filename = (lastSlash == std::string::npos)
  4041. ? newName
  4042. : newName.substr( lastSlash+1 );
  4043. *m_name = filename;
  4044. if( m_ref )
  4045. return m_ref->setValue( filename );
  4046. else
  4047. return ParserResult::ok( ParseResultType::Matched );
  4048. }
  4049. };
  4050. class Arg : public ParserRefImpl<Arg> {
  4051. public:
  4052. using ParserRefImpl::ParserRefImpl;
  4053. auto parse(std::string const &, TokenStream const &tokens) const -> InternalParseResult override {
  4054. auto validationResult = validate();
  4055. if (!validationResult)
  4056. return InternalParseResult(validationResult);
  4057. auto remainingTokens = tokens;
  4058. auto const &token = *remainingTokens;
  4059. if (token.type != TokenType::Argument)
  4060. return InternalParseResult::ok(ParseState(ParseResultType::NoMatch, remainingTokens));
  4061. auto result = m_ref->setValue(remainingTokens->token);
  4062. if (!result)
  4063. return InternalParseResult(result);
  4064. else
  4065. return InternalParseResult::ok(ParseState(ParseResultType::Matched, ++remainingTokens));
  4066. }
  4067. };
  4068. inline auto normaliseOpt(std::string const &optName) -> std::string {
  4069. if (optName[0] == '/')
  4070. return "-" + optName.substr(1);
  4071. else
  4072. return optName;
  4073. }
  4074. class Opt : public ParserRefImpl<Opt> {
  4075. protected:
  4076. std::vector<std::string> m_optNames;
  4077. public:
  4078. template<typename LambdaT>
  4079. explicit Opt( LambdaT const &ref ) : ParserRefImpl(std::make_shared<BoundFlagLambda<LambdaT>>(ref)) {}
  4080. explicit Opt( bool &ref ) : ParserRefImpl(std::make_shared<BoundFlagRef>(ref)) {}
  4081. template<typename LambdaT>
  4082. Opt( LambdaT const &ref, std::string const &hint ) : ParserRefImpl( ref, hint ) {}
  4083. template<typename T>
  4084. Opt( T &ref, std::string const &hint ) : ParserRefImpl( ref, hint ) {}
  4085. auto operator[](std::string const &optName) -> Opt & {
  4086. m_optNames.push_back(optName);
  4087. return *this;
  4088. }
  4089. auto getHelpColumns() const -> std::vector<HelpColumns> {
  4090. std::ostringstream oss;
  4091. bool first = true;
  4092. for (auto const &opt : m_optNames) {
  4093. if (first)
  4094. first = false;
  4095. else
  4096. oss << ", ";
  4097. oss << opt;
  4098. }
  4099. if (!m_hint.empty())
  4100. oss << " <" << m_hint << ">";
  4101. return {{oss.str(), m_description}};
  4102. }
  4103. auto isMatch(std::string const &optToken) const -> bool {
  4104. #ifdef CLARA_PLATFORM_WINDOWS
  4105. auto normalisedToken = normaliseOpt( optToken );
  4106. #else
  4107. auto const &normalisedToken = optToken;
  4108. #endif
  4109. for (auto const &name : m_optNames) {
  4110. if (normaliseOpt(name) == normalisedToken)
  4111. return true;
  4112. }
  4113. return false;
  4114. }
  4115. using ParserBase::parse;
  4116. auto parse( std::string const&, TokenStream const &tokens ) const -> InternalParseResult override {
  4117. auto validationResult = validate();
  4118. if (!validationResult)
  4119. return InternalParseResult(validationResult);
  4120. auto remainingTokens = tokens;
  4121. if (remainingTokens && remainingTokens->type == TokenType::Option) {
  4122. auto const &token = *remainingTokens;
  4123. if (isMatch(token.token)) {
  4124. if (m_ref->isFlag()) {
  4125. auto result = m_ref->setFlag(true);
  4126. if (!result)
  4127. return InternalParseResult(result);
  4128. if (result.value() == ParseResultType::ShortCircuitAll)
  4129. return InternalParseResult::ok(ParseState(result.value(), remainingTokens));
  4130. } else {
  4131. ++remainingTokens;
  4132. if (!remainingTokens)
  4133. return InternalParseResult::runtimeError("Expected argument following " + token.token);
  4134. auto const &argToken = *remainingTokens;
  4135. if (argToken.type != TokenType::Argument)
  4136. return InternalParseResult::runtimeError("Expected argument following " + token.token);
  4137. auto result = m_ref->setValue(argToken.token);
  4138. if (!result)
  4139. return InternalParseResult(result);
  4140. if (result.value() == ParseResultType::ShortCircuitAll)
  4141. return InternalParseResult::ok(ParseState(result.value(), remainingTokens));
  4142. }
  4143. return InternalParseResult::ok(ParseState(ParseResultType::Matched, ++remainingTokens));
  4144. }
  4145. }
  4146. return InternalParseResult::ok(ParseState(ParseResultType::NoMatch, remainingTokens));
  4147. }
  4148. auto validate() const -> Result override {
  4149. if (m_optNames.empty())
  4150. return Result::logicError("No options supplied to Opt");
  4151. for (auto const &name : m_optNames) {
  4152. if (name.empty())
  4153. return Result::logicError("Option name cannot be empty");
  4154. if (name[0] != '-' && name[0] != '/')
  4155. return Result::logicError("Option name must begin with '-' or '/'");
  4156. }
  4157. return ParserRefImpl::validate();
  4158. }
  4159. };
  4160. struct Help : Opt {
  4161. Help( bool &showHelpFlag )
  4162. : Opt([&]( bool flag ) {
  4163. showHelpFlag = flag;
  4164. return ParserResult::ok(ParseResultType::ShortCircuitAll);
  4165. })
  4166. {
  4167. static_cast<Opt &>(*this)
  4168. ("display usage information")
  4169. ["-?"]["-h"]["--help"]
  4170. .optional();
  4171. }
  4172. };
  4173. struct Parser : ParserBase {
  4174. mutable ExeName m_exeName;
  4175. std::vector<Opt> m_options;
  4176. std::vector<Arg> m_args;
  4177. auto operator+=(ExeName const &exeName) -> Parser & {
  4178. m_exeName = exeName;
  4179. return *this;
  4180. }
  4181. auto operator+=(Arg const &arg) -> Parser & {
  4182. m_args.push_back(arg);
  4183. return *this;
  4184. }
  4185. auto operator+=(Opt const &opt) -> Parser & {
  4186. m_options.push_back(opt);
  4187. return *this;
  4188. }
  4189. auto operator+=(Parser const &other) -> Parser & {
  4190. m_options.insert(m_options.end(), other.m_options.begin(), other.m_options.end());
  4191. m_args.insert(m_args.end(), other.m_args.begin(), other.m_args.end());
  4192. return *this;
  4193. }
  4194. template<typename T>
  4195. auto operator+(T const &other) const -> Parser {
  4196. return Parser(*this) += other;
  4197. }
  4198. auto getHelpColumns() const -> std::vector<HelpColumns> {
  4199. std::vector<HelpColumns> cols;
  4200. for (auto const &o : m_options) {
  4201. auto childCols = o.getHelpColumns();
  4202. cols.insert(cols.end(), childCols.begin(), childCols.end());
  4203. }
  4204. return cols;
  4205. }
  4206. void writeToStream(std::ostream &os) const {
  4207. if (!m_exeName.name().empty()) {
  4208. os << "usage:\n" << " " << m_exeName.name() << " ";
  4209. bool required = true, first = true;
  4210. for (auto const &arg : m_args) {
  4211. if (first)
  4212. first = false;
  4213. else
  4214. os << " ";
  4215. if (arg.isOptional() && required) {
  4216. os << "[";
  4217. required = false;
  4218. }
  4219. os << "<" << arg.hint() << ">";
  4220. if (arg.cardinality() == 0)
  4221. os << " ... ";
  4222. }
  4223. if (!required)
  4224. os << "]";
  4225. if (!m_options.empty())
  4226. os << " options";
  4227. os << "\n\nwhere options are:" << std::endl;
  4228. }
  4229. auto rows = getHelpColumns();
  4230. size_t consoleWidth = CATCH_CLARA_CONFIG_CONSOLE_WIDTH;
  4231. size_t optWidth = 0;
  4232. for (auto const &cols : rows)
  4233. optWidth = std::max(optWidth, cols.left.size() + 2);
  4234. for (auto const &cols : rows) {
  4235. auto row =
  4236. TextFlow::Column(cols.left).width(optWidth).indent(2) +
  4237. TextFlow::Spacer(4) +
  4238. TextFlow::Column(cols.right).width(consoleWidth - 7 - optWidth);
  4239. os << row << std::endl;
  4240. }
  4241. }
  4242. friend auto operator<<(std::ostream &os, Parser const &parser) -> std::ostream & {
  4243. parser.writeToStream(os);
  4244. return os;
  4245. }
  4246. auto validate() const -> Result override {
  4247. for (auto const &opt : m_options) {
  4248. auto result = opt.validate();
  4249. if (!result)
  4250. return result;
  4251. }
  4252. for (auto const &arg : m_args) {
  4253. auto result = arg.validate();
  4254. if (!result)
  4255. return result;
  4256. }
  4257. return Result::ok();
  4258. }
  4259. using ParserBase::parse;
  4260. auto parse( std::string const& exeName, TokenStream const &tokens) const -> InternalParseResult override {
  4261. std::vector<ParserBase const *> allParsers;
  4262. allParsers.reserve(m_args.size() + m_options.size());
  4263. std::set<ParserBase const *> requiredParsers;
  4264. for (auto const &opt : m_options) {
  4265. allParsers.push_back(&opt);
  4266. if (!opt.isOptional())
  4267. requiredParsers.insert(&opt);
  4268. }
  4269. size_t optionalArgs = 0;
  4270. for (auto const &arg : m_args) {
  4271. allParsers.push_back(&arg);
  4272. if (!arg.isOptional()) {
  4273. if (optionalArgs > 0)
  4274. return InternalParseResult::logicError(
  4275. "Required arguments must preceed any optional arguments");
  4276. else
  4277. ++optionalArgs;
  4278. requiredParsers.insert(&arg);
  4279. }
  4280. }
  4281. m_exeName.set( exeName );
  4282. auto result = InternalParseResult::ok(ParseState(ParseResultType::NoMatch, tokens));
  4283. while (result.value().remainingTokens()) {
  4284. auto remainingTokenCount = result.value().remainingTokens().count();
  4285. for (auto parser : allParsers) {
  4286. result = parser->parse( exeName, result.value().remainingTokens() );
  4287. if (!result || result.value().type() != ParseResultType::NoMatch) {
  4288. if (parser->cardinality() == 1)
  4289. allParsers.erase(std::remove(allParsers.begin(), allParsers.end(), parser),
  4290. allParsers.end());
  4291. requiredParsers.erase(parser);
  4292. break;
  4293. }
  4294. }
  4295. if (!result || remainingTokenCount == result.value().remainingTokens().count())
  4296. return result;
  4297. }
  4298. // !TBD Check missing required options
  4299. return result;
  4300. }
  4301. };
  4302. template<typename DerivedT>
  4303. template<typename T>
  4304. auto ComposableParserImpl<DerivedT>::operator+(T const &other) const -> Parser {
  4305. return Parser() + static_cast<DerivedT const &>( *this ) + other;
  4306. }
  4307. } // namespace detail
  4308. // A Combined parser
  4309. using detail::Parser;
  4310. // A parser for options
  4311. using detail::Opt;
  4312. // A parser for arguments
  4313. using detail::Arg;
  4314. // Wrapper for argc, argv from main()
  4315. using detail::Args;
  4316. // Specifies the name of the executable
  4317. using detail::ExeName;
  4318. // Convenience wrapper for option parser that specifies the help option
  4319. using detail::Help;
  4320. // enum of result types from a parse
  4321. using detail::ParseResultType;
  4322. // Result type for parser operation
  4323. using detail::ParserResult;
  4324. }} // namespace Catch::clara
  4325. // end clara.hpp
  4326. #ifdef __clang__
  4327. #pragma clang diagnostic pop
  4328. #endif
  4329. // Restore Clara's value for console width, if present
  4330. #ifdef CATCH_TEMP_CLARA_CONFIG_CONSOLE_WIDTH
  4331. #define CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH CATCH_TEMP_CLARA_CONFIG_CONSOLE_WIDTH
  4332. #undef CATCH_TEMP_CLARA_CONFIG_CONSOLE_WIDTH
  4333. #endif
  4334. // end catch_clara.h
  4335. namespace Catch {
  4336. clara::Parser makeCommandLineParser( ConfigData& config );
  4337. } // end namespace Catch
  4338. // end catch_commandline.h
  4339. #include <fstream>
  4340. #include <ctime>
  4341. namespace Catch {
  4342. clara::Parser makeCommandLineParser( ConfigData& config ) {
  4343. using namespace clara;
  4344. auto const setWarning = [&]( std::string const& warning ) {
  4345. if( warning != "NoAssertions" )
  4346. return ParserResult::runtimeError( "Unrecognised warning: '" + warning + "'" );
  4347. config.warnings = static_cast<WarnAbout::What>( config.warnings | WarnAbout::NoAssertions );
  4348. return ParserResult::ok( ParseResultType::Matched );
  4349. };
  4350. auto const loadTestNamesFromFile = [&]( std::string const& filename ) {
  4351. std::ifstream f( filename.c_str() );
  4352. if( !f.is_open() )
  4353. return ParserResult::runtimeError( "Unable to load input file: '" + filename + "'" );
  4354. std::string line;
  4355. while( std::getline( f, line ) ) {
  4356. line = trim(line);
  4357. if( !line.empty() && !startsWith( line, '#' ) ) {
  4358. if( !startsWith( line, '"' ) )
  4359. line = '"' + line + '"';
  4360. config.testsOrTags.push_back( line + ',' );
  4361. }
  4362. }
  4363. return ParserResult::ok( ParseResultType::Matched );
  4364. };
  4365. auto const setTestOrder = [&]( std::string const& order ) {
  4366. if( startsWith( "declared", order ) )
  4367. config.runOrder = RunTests::InDeclarationOrder;
  4368. else if( startsWith( "lexical", order ) )
  4369. config.runOrder = RunTests::InLexicographicalOrder;
  4370. else if( startsWith( "random", order ) )
  4371. config.runOrder = RunTests::InRandomOrder;
  4372. else
  4373. return clara::ParserResult::runtimeError( "Unrecognised ordering: '" + order + "'" );
  4374. return ParserResult::ok( ParseResultType::Matched );
  4375. };
  4376. auto const setRngSeed = [&]( std::string const& seed ) {
  4377. if( seed != "time" )
  4378. return clara::detail::convertInto( seed, config.rngSeed );
  4379. config.rngSeed = static_cast<unsigned int>( std::time(nullptr) );
  4380. return ParserResult::ok( ParseResultType::Matched );
  4381. };
  4382. auto const setColourUsage = [&]( std::string const& useColour ) {
  4383. auto mode = toLower( useColour );
  4384. if( mode == "yes" )
  4385. config.useColour = UseColour::Yes;
  4386. else if( mode == "no" )
  4387. config.useColour = UseColour::No;
  4388. else if( mode == "auto" )
  4389. config.useColour = UseColour::Auto;
  4390. else
  4391. return ParserResult::runtimeError( "colour mode must be one of: auto, yes or no. '" + useColour + "' not recognised" );
  4392. return ParserResult::ok( ParseResultType::Matched );
  4393. };
  4394. auto const setWaitForKeypress = [&]( std::string const& keypress ) {
  4395. auto keypressLc = toLower( keypress );
  4396. if( keypressLc == "start" )
  4397. config.waitForKeypress = WaitForKeypress::BeforeStart;
  4398. else if( keypressLc == "exit" )
  4399. config.waitForKeypress = WaitForKeypress::BeforeExit;
  4400. else if( keypressLc == "both" )
  4401. config.waitForKeypress = WaitForKeypress::BeforeStartAndExit;
  4402. else
  4403. return ParserResult::runtimeError( "keypress argument must be one of: start, exit or both. '" + keypress + "' not recognised" );
  4404. return ParserResult::ok( ParseResultType::Matched );
  4405. };
  4406. auto const setVerbosity = [&]( std::string const& verbosity ) {
  4407. auto lcVerbosity = toLower( verbosity );
  4408. if( lcVerbosity == "quiet" )
  4409. config.verbosity = Verbosity::Quiet;
  4410. else if( lcVerbosity == "normal" )
  4411. config.verbosity = Verbosity::Normal;
  4412. else if( lcVerbosity == "high" )
  4413. config.verbosity = Verbosity::High;
  4414. else
  4415. return ParserResult::runtimeError( "Unrecognised verbosity, '" + verbosity + "'" );
  4416. return ParserResult::ok( ParseResultType::Matched );
  4417. };
  4418. auto cli
  4419. = ExeName( config.processName )
  4420. + Help( config.showHelp )
  4421. + Opt( config.listTests )
  4422. ["-l"]["--list-tests"]
  4423. ( "list all/matching test cases" )
  4424. + Opt( config.listTags )
  4425. ["-t"]["--list-tags"]
  4426. ( "list all/matching tags" )
  4427. + Opt( config.showSuccessfulTests )
  4428. ["-s"]["--success"]
  4429. ( "include successful tests in output" )
  4430. + Opt( config.shouldDebugBreak )
  4431. ["-b"]["--break"]
  4432. ( "break into debugger on failure" )
  4433. + Opt( config.noThrow )
  4434. ["-e"]["--nothrow"]
  4435. ( "skip exception tests" )
  4436. + Opt( config.showInvisibles )
  4437. ["-i"]["--invisibles"]
  4438. ( "show invisibles (tabs, newlines)" )
  4439. + Opt( config.outputFilename, "filename" )
  4440. ["-o"]["--out"]
  4441. ( "output filename" )
  4442. + Opt( config.reporterNames, "name" )
  4443. ["-r"]["--reporter"]
  4444. ( "reporter to use (defaults to console)" )
  4445. + Opt( config.name, "name" )
  4446. ["-n"]["--name"]
  4447. ( "suite name" )
  4448. + Opt( [&]( bool ){ config.abortAfter = 1; } )
  4449. ["-a"]["--abort"]
  4450. ( "abort at first failure" )
  4451. + Opt( [&]( int x ){ config.abortAfter = x; }, "no. failures" )
  4452. ["-x"]["--abortx"]
  4453. ( "abort after x failures" )
  4454. + Opt( setWarning, "warning name" )
  4455. ["-w"]["--warn"]
  4456. ( "enable warnings" )
  4457. + Opt( [&]( bool flag ) { config.showDurations = flag ? ShowDurations::Always : ShowDurations::Never; }, "yes|no" )
  4458. ["-d"]["--durations"]
  4459. ( "show test durations" )
  4460. + Opt( loadTestNamesFromFile, "filename" )
  4461. ["-f"]["--input-file"]
  4462. ( "load test names to run from a file" )
  4463. + Opt( config.filenamesAsTags )
  4464. ["-#"]["--filenames-as-tags"]
  4465. ( "adds a tag for the filename" )
  4466. + Opt( config.sectionsToRun, "section name" )
  4467. ["-c"]["--section"]
  4468. ( "specify section to run" )
  4469. + Opt( setVerbosity, "quiet|normal|high" )
  4470. ["-v"]["--verbosity"]
  4471. ( "set output verbosity" )
  4472. + Opt( config.listTestNamesOnly )
  4473. ["--list-test-names-only"]
  4474. ( "list all/matching test cases names only" )
  4475. + Opt( config.listReporters )
  4476. ["--list-reporters"]
  4477. ( "list all reporters" )
  4478. + Opt( setTestOrder, "decl|lex|rand" )
  4479. ["--order"]
  4480. ( "test case order (defaults to decl)" )
  4481. + Opt( setRngSeed, "'time'|number" )
  4482. ["--rng-seed"]
  4483. ( "set a specific seed for random numbers" )
  4484. + Opt( setColourUsage, "yes|no" )
  4485. ["--use-colour"]
  4486. ( "should output be colourised" )
  4487. + Opt( config.libIdentify )
  4488. ["--libidentify"]
  4489. ( "report name and version according to libidentify standard" )
  4490. + Opt( setWaitForKeypress, "start|exit|both" )
  4491. ["--wait-for-keypress"]
  4492. ( "waits for a keypress before exiting" )
  4493. + Opt( config.benchmarkResolutionMultiple, "multiplier" )
  4494. ["--benchmark-resolution-multiple"]
  4495. ( "multiple of clock resolution to run benchmarks" )
  4496. + Arg( config.testsOrTags, "test name|pattern|tags" )
  4497. ( "which test or tests to use" );
  4498. return cli;
  4499. }
  4500. } // end namespace Catch
  4501. // end catch_commandline.cpp
  4502. // start catch_common.cpp
  4503. #include <cstring>
  4504. #include <ostream>
  4505. namespace Catch {
  4506. SourceLineInfo::SourceLineInfo( char const* _file, std::size_t _line ) noexcept
  4507. : file( _file ),
  4508. line( _line )
  4509. {}
  4510. bool SourceLineInfo::empty() const noexcept {
  4511. return file[0] == '\0';
  4512. }
  4513. bool SourceLineInfo::operator == ( SourceLineInfo const& other ) const noexcept {
  4514. return line == other.line && (file == other.file || std::strcmp(file, other.file) == 0);
  4515. }
  4516. bool SourceLineInfo::operator < ( SourceLineInfo const& other ) const noexcept {
  4517. return line < other.line || ( line == other.line && (std::strcmp(file, other.file) < 0));
  4518. }
  4519. std::ostream& operator << ( std::ostream& os, SourceLineInfo const& info ) {
  4520. #ifndef __GNUG__
  4521. os << info.file << '(' << info.line << ')';
  4522. #else
  4523. os << info.file << ':' << info.line;
  4524. #endif
  4525. return os;
  4526. }
  4527. bool isTrue( bool value ){ return value; }
  4528. bool alwaysTrue() { return true; }
  4529. bool alwaysFalse() { return false; }
  4530. std::string StreamEndStop::operator+() const {
  4531. return std::string();
  4532. }
  4533. NonCopyable::NonCopyable() = default;
  4534. NonCopyable::~NonCopyable() = default;
  4535. }
  4536. // end catch_common.cpp
  4537. // start catch_config.cpp
  4538. namespace Catch {
  4539. Config::Config( ConfigData const& data )
  4540. : m_data( data ),
  4541. m_stream( openStream() )
  4542. {
  4543. if( !data.testsOrTags.empty() ) {
  4544. TestSpecParser parser( ITagAliasRegistry::get() );
  4545. for( auto const& testOrTags : data.testsOrTags )
  4546. parser.parse( testOrTags );
  4547. m_testSpec = parser.testSpec();
  4548. }
  4549. }
  4550. std::string const& Config::getFilename() const {
  4551. return m_data.outputFilename ;
  4552. }
  4553. bool Config::listTests() const { return m_data.listTests; }
  4554. bool Config::listTestNamesOnly() const { return m_data.listTestNamesOnly; }
  4555. bool Config::listTags() const { return m_data.listTags; }
  4556. bool Config::listReporters() const { return m_data.listReporters; }
  4557. std::string Config::getProcessName() const { return m_data.processName; }
  4558. std::vector<std::string> const& Config::getReporterNames() const { return m_data.reporterNames; }
  4559. std::vector<std::string> const& Config::getSectionsToRun() const { return m_data.sectionsToRun; }
  4560. TestSpec const& Config::testSpec() const { return m_testSpec; }
  4561. bool Config::showHelp() const { return m_data.showHelp; }
  4562. // IConfig interface
  4563. bool Config::allowThrows() const { return !m_data.noThrow; }
  4564. std::ostream& Config::stream() const { return m_stream->stream(); }
  4565. std::string Config::name() const { return m_data.name.empty() ? m_data.processName : m_data.name; }
  4566. bool Config::includeSuccessfulResults() const { return m_data.showSuccessfulTests; }
  4567. bool Config::warnAboutMissingAssertions() const { return m_data.warnings & WarnAbout::NoAssertions; }
  4568. ShowDurations::OrNot Config::showDurations() const { return m_data.showDurations; }
  4569. RunTests::InWhatOrder Config::runOrder() const { return m_data.runOrder; }
  4570. unsigned int Config::rngSeed() const { return m_data.rngSeed; }
  4571. int Config::benchmarkResolutionMultiple() const { return m_data.benchmarkResolutionMultiple; }
  4572. UseColour::YesOrNo Config::useColour() const { return m_data.useColour; }
  4573. bool Config::shouldDebugBreak() const { return m_data.shouldDebugBreak; }
  4574. int Config::abortAfter() const { return m_data.abortAfter; }
  4575. bool Config::showInvisibles() const { return m_data.showInvisibles; }
  4576. Verbosity Config::verbosity() const { return m_data.verbosity; }
  4577. IStream const* Config::openStream() {
  4578. if( m_data.outputFilename.empty() )
  4579. return new CoutStream();
  4580. else if( m_data.outputFilename[0] == '%' ) {
  4581. if( m_data.outputFilename == "%debug" )
  4582. return new DebugOutStream();
  4583. else
  4584. CATCH_ERROR( "Unrecognised stream: '" << m_data.outputFilename << "'" );
  4585. }
  4586. else
  4587. return new FileStream( m_data.outputFilename );
  4588. }
  4589. } // end namespace Catch
  4590. // end catch_config.cpp
  4591. // start catch_console_colour.cpp
  4592. #if defined(__clang__)
  4593. # pragma clang diagnostic push
  4594. # pragma clang diagnostic ignored "-Wexit-time-destructors"
  4595. #endif
  4596. // start catch_errno_guard.h
  4597. namespace Catch {
  4598. class ErrnoGuard {
  4599. public:
  4600. ErrnoGuard();
  4601. ~ErrnoGuard();
  4602. private:
  4603. int m_oldErrno;
  4604. };
  4605. }
  4606. // end catch_errno_guard.h
  4607. namespace Catch {
  4608. namespace {
  4609. struct IColourImpl {
  4610. virtual ~IColourImpl() = default;
  4611. virtual void use( Colour::Code _colourCode ) = 0;
  4612. };
  4613. struct NoColourImpl : IColourImpl {
  4614. void use( Colour::Code ) {}
  4615. static IColourImpl* instance() {
  4616. static NoColourImpl s_instance;
  4617. return &s_instance;
  4618. }
  4619. };
  4620. } // anon namespace
  4621. } // namespace Catch
  4622. #if !defined( CATCH_CONFIG_COLOUR_NONE ) && !defined( CATCH_CONFIG_COLOUR_WINDOWS ) && !defined( CATCH_CONFIG_COLOUR_ANSI )
  4623. # ifdef CATCH_PLATFORM_WINDOWS
  4624. # define CATCH_CONFIG_COLOUR_WINDOWS
  4625. # else
  4626. # define CATCH_CONFIG_COLOUR_ANSI
  4627. # endif
  4628. #endif
  4629. #if defined ( CATCH_CONFIG_COLOUR_WINDOWS ) /////////////////////////////////////////
  4630. // start catch_windows_h_proxy.h
  4631. #if defined(CATCH_PLATFORM_WINDOWS)
  4632. # if !defined(NOMINMAX) && !defined(CATCH_CONFIG_NO_NOMINMAX)
  4633. # define CATCH_DEFINED_NOMINMAX
  4634. # define NOMINMAX
  4635. # endif
  4636. # if !defined(WIN32_LEAN_AND_MEAN) && !defined(CATCH_CONFIG_NO_WIN32_LEAN_AND_MEAN)
  4637. # define CATCH_DEFINED_WIN32_LEAN_AND_MEAN
  4638. # define WIN32_LEAN_AND_MEAN
  4639. # endif
  4640. #endif
  4641. #ifdef __AFXDLL
  4642. #include <AfxWin.h>
  4643. #else
  4644. #include <windows.h>
  4645. #endif
  4646. #ifdef CATCH_DEFINED_NOMINMAX
  4647. # undef NOMINMAX
  4648. #endif
  4649. #ifdef CATCH_DEFINED_WIN32_LEAN_AND_MEAN
  4650. # undef WIN32_LEAN_AND_MEAN
  4651. #endif
  4652. // end catch_windows_h_proxy.h
  4653. namespace Catch {
  4654. namespace {
  4655. class Win32ColourImpl : public IColourImpl {
  4656. public:
  4657. Win32ColourImpl() : stdoutHandle( GetStdHandle(STD_OUTPUT_HANDLE) )
  4658. {
  4659. CONSOLE_SCREEN_BUFFER_INFO csbiInfo;
  4660. GetConsoleScreenBufferInfo( stdoutHandle, &csbiInfo );
  4661. originalForegroundAttributes = csbiInfo.wAttributes & ~( BACKGROUND_GREEN | BACKGROUND_RED | BACKGROUND_BLUE | BACKGROUND_INTENSITY );
  4662. originalBackgroundAttributes = csbiInfo.wAttributes & ~( FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_BLUE | FOREGROUND_INTENSITY );
  4663. }
  4664. virtual void use( Colour::Code _colourCode ) override {
  4665. switch( _colourCode ) {
  4666. case Colour::None: return setTextAttribute( originalForegroundAttributes );
  4667. case Colour::White: return setTextAttribute( FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_BLUE );
  4668. case Colour::Red: return setTextAttribute( FOREGROUND_RED );
  4669. case Colour::Green: return setTextAttribute( FOREGROUND_GREEN );
  4670. case Colour::Blue: return setTextAttribute( FOREGROUND_BLUE );
  4671. case Colour::Cyan: return setTextAttribute( FOREGROUND_BLUE | FOREGROUND_GREEN );
  4672. case Colour::Yellow: return setTextAttribute( FOREGROUND_RED | FOREGROUND_GREEN );
  4673. case Colour::Grey: return setTextAttribute( 0 );
  4674. case Colour::LightGrey: return setTextAttribute( FOREGROUND_INTENSITY );
  4675. case Colour::BrightRed: return setTextAttribute( FOREGROUND_INTENSITY | FOREGROUND_RED );
  4676. case Colour::BrightGreen: return setTextAttribute( FOREGROUND_INTENSITY | FOREGROUND_GREEN );
  4677. case Colour::BrightWhite: return setTextAttribute( FOREGROUND_INTENSITY | FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_BLUE );
  4678. case Colour::Bright: CATCH_INTERNAL_ERROR( "not a colour" );
  4679. }
  4680. }
  4681. private:
  4682. void setTextAttribute( WORD _textAttribute ) {
  4683. SetConsoleTextAttribute( stdoutHandle, _textAttribute | originalBackgroundAttributes );
  4684. }
  4685. HANDLE stdoutHandle;
  4686. WORD originalForegroundAttributes;
  4687. WORD originalBackgroundAttributes;
  4688. };
  4689. IColourImpl* platformColourInstance() {
  4690. static Win32ColourImpl s_instance;
  4691. IConfigPtr config = getCurrentContext().getConfig();
  4692. UseColour::YesOrNo colourMode = config
  4693. ? config->useColour()
  4694. : UseColour::Auto;
  4695. if( colourMode == UseColour::Auto )
  4696. colourMode = UseColour::Yes;
  4697. return colourMode == UseColour::Yes
  4698. ? &s_instance
  4699. : NoColourImpl::instance();
  4700. }
  4701. } // end anon namespace
  4702. } // end namespace Catch
  4703. #elif defined( CATCH_CONFIG_COLOUR_ANSI ) //////////////////////////////////////
  4704. #include <unistd.h>
  4705. namespace Catch {
  4706. namespace {
  4707. // use POSIX/ ANSI console terminal codes
  4708. // Thanks to Adam Strzelecki for original contribution
  4709. // (http://github.com/nanoant)
  4710. // https://github.com/philsquared/Catch/pull/131
  4711. class PosixColourImpl : public IColourImpl {
  4712. public:
  4713. virtual void use( Colour::Code _colourCode ) override {
  4714. switch( _colourCode ) {
  4715. case Colour::None:
  4716. case Colour::White: return setColour( "[0m" );
  4717. case Colour::Red: return setColour( "[0;31m" );
  4718. case Colour::Green: return setColour( "[0;32m" );
  4719. case Colour::Blue: return setColour( "[0;34m" );
  4720. case Colour::Cyan: return setColour( "[0;36m" );
  4721. case Colour::Yellow: return setColour( "[0;33m" );
  4722. case Colour::Grey: return setColour( "[1;30m" );
  4723. case Colour::LightGrey: return setColour( "[0;37m" );
  4724. case Colour::BrightRed: return setColour( "[1;31m" );
  4725. case Colour::BrightGreen: return setColour( "[1;32m" );
  4726. case Colour::BrightWhite: return setColour( "[1;37m" );
  4727. case Colour::Bright: CATCH_INTERNAL_ERROR( "not a colour" );
  4728. }
  4729. }
  4730. static IColourImpl* instance() {
  4731. static PosixColourImpl s_instance;
  4732. return &s_instance;
  4733. }
  4734. private:
  4735. void setColour( const char* _escapeCode ) {
  4736. Catch::cout() << '\033' << _escapeCode;
  4737. }
  4738. };
  4739. bool useColourOnPlatform() {
  4740. return
  4741. #ifdef CATCH_PLATFORM_MAC
  4742. !isDebuggerActive() &&
  4743. #endif
  4744. isatty(STDOUT_FILENO);
  4745. }
  4746. IColourImpl* platformColourInstance() {
  4747. ErrnoGuard guard;
  4748. IConfigPtr config = getCurrentContext().getConfig();
  4749. UseColour::YesOrNo colourMode = config
  4750. ? config->useColour()
  4751. : UseColour::Auto;
  4752. if( colourMode == UseColour::Auto )
  4753. colourMode = useColourOnPlatform()
  4754. ? UseColour::Yes
  4755. : UseColour::No;
  4756. return colourMode == UseColour::Yes
  4757. ? PosixColourImpl::instance()
  4758. : NoColourImpl::instance();
  4759. }
  4760. } // end anon namespace
  4761. } // end namespace Catch
  4762. #else // not Windows or ANSI ///////////////////////////////////////////////
  4763. namespace Catch {
  4764. static IColourImpl* platformColourInstance() { return NoColourImpl::instance(); }
  4765. } // end namespace Catch
  4766. #endif // Windows/ ANSI/ None
  4767. namespace Catch {
  4768. Colour::Colour( Code _colourCode ) { use( _colourCode ); }
  4769. Colour::Colour( Colour&& rhs ) noexcept {
  4770. m_moved = rhs.m_moved;
  4771. rhs.m_moved = true;
  4772. }
  4773. Colour& Colour::operator=( Colour&& rhs ) noexcept {
  4774. m_moved = rhs.m_moved;
  4775. rhs.m_moved = true;
  4776. return *this;
  4777. }
  4778. Colour::~Colour(){ if( !m_moved ) use( None ); }
  4779. void Colour::use( Code _colourCode ) {
  4780. static IColourImpl* impl = platformColourInstance();
  4781. impl->use( _colourCode );
  4782. }
  4783. std::ostream& operator << ( std::ostream& os, Colour const& ) {
  4784. return os;
  4785. }
  4786. } // end namespace Catch
  4787. #if defined(__clang__)
  4788. # pragma clang diagnostic pop
  4789. #endif
  4790. // end catch_console_colour.cpp
  4791. // start catch_context.cpp
  4792. namespace Catch {
  4793. class Context : public IMutableContext, NonCopyable {
  4794. public: // IContext
  4795. virtual IResultCapture* getResultCapture() override {
  4796. return m_resultCapture;
  4797. }
  4798. virtual IRunner* getRunner() override {
  4799. return m_runner;
  4800. }
  4801. virtual IConfigPtr getConfig() const override {
  4802. return m_config;
  4803. }
  4804. virtual ~Context() override;
  4805. public: // IMutableContext
  4806. virtual void setResultCapture( IResultCapture* resultCapture ) override {
  4807. m_resultCapture = resultCapture;
  4808. }
  4809. virtual void setRunner( IRunner* runner ) override {
  4810. m_runner = runner;
  4811. }
  4812. virtual void setConfig( IConfigPtr const& config ) override {
  4813. m_config = config;
  4814. }
  4815. friend IMutableContext& getCurrentMutableContext();
  4816. private:
  4817. IConfigPtr m_config;
  4818. IRunner* m_runner = nullptr;
  4819. IResultCapture* m_resultCapture = nullptr;
  4820. };
  4821. namespace {
  4822. Context* currentContext = nullptr;
  4823. }
  4824. IMutableContext& getCurrentMutableContext() {
  4825. if( !currentContext )
  4826. currentContext = new Context();
  4827. return *currentContext;
  4828. }
  4829. IContext& getCurrentContext() {
  4830. return getCurrentMutableContext();
  4831. }
  4832. void cleanUpContext() {
  4833. delete currentContext;
  4834. currentContext = nullptr;
  4835. }
  4836. IContext::~IContext() = default;
  4837. IMutableContext::~IMutableContext() = default;
  4838. Context::~Context() = default;
  4839. }
  4840. // end catch_context.cpp
  4841. // start catch_debug_console.cpp
  4842. // start catch_debug_console.h
  4843. #include <string>
  4844. namespace Catch {
  4845. void writeToDebugConsole( std::string const& text );
  4846. }
  4847. // end catch_debug_console.h
  4848. #ifdef CATCH_PLATFORM_WINDOWS
  4849. namespace Catch {
  4850. void writeToDebugConsole( std::string const& text ) {
  4851. ::OutputDebugStringA( text.c_str() );
  4852. }
  4853. }
  4854. #else
  4855. namespace Catch {
  4856. void writeToDebugConsole( std::string const& text ) {
  4857. // !TBD: Need a version for Mac/ XCode and other IDEs
  4858. Catch::cout() << text;
  4859. }
  4860. }
  4861. #endif // Platform
  4862. // end catch_debug_console.cpp
  4863. // start catch_debugger.cpp
  4864. #ifdef CATCH_PLATFORM_MAC
  4865. #include <assert.h>
  4866. #include <stdbool.h>
  4867. #include <sys/types.h>
  4868. #include <unistd.h>
  4869. #include <sys/sysctl.h>
  4870. namespace Catch {
  4871. // The following function is taken directly from the following technical note:
  4872. // http://developer.apple.com/library/mac/#qa/qa2004/qa1361.html
  4873. // Returns true if the current process is being debugged (either
  4874. // running under the debugger or has a debugger attached post facto).
  4875. bool isDebuggerActive(){
  4876. int mib[4];
  4877. struct kinfo_proc info;
  4878. std::size_t size;
  4879. // Initialize the flags so that, if sysctl fails for some bizarre
  4880. // reason, we get a predictable result.
  4881. info.kp_proc.p_flag = 0;
  4882. // Initialize mib, which tells sysctl the info we want, in this case
  4883. // we're looking for information about a specific process ID.
  4884. mib[0] = CTL_KERN;
  4885. mib[1] = KERN_PROC;
  4886. mib[2] = KERN_PROC_PID;
  4887. mib[3] = getpid();
  4888. // Call sysctl.
  4889. size = sizeof(info);
  4890. if( sysctl(mib, sizeof(mib) / sizeof(*mib), &info, &size, nullptr, 0) != 0 ) {
  4891. Catch::cerr() << "\n** Call to sysctl failed - unable to determine if debugger is active **\n" << std::endl;
  4892. return false;
  4893. }
  4894. // We're being debugged if the P_TRACED flag is set.
  4895. return ( (info.kp_proc.p_flag & P_TRACED) != 0 );
  4896. }
  4897. } // namespace Catch
  4898. #elif defined(CATCH_PLATFORM_LINUX)
  4899. #include <fstream>
  4900. #include <string>
  4901. namespace Catch{
  4902. // The standard POSIX way of detecting a debugger is to attempt to
  4903. // ptrace() the process, but this needs to be done from a child and not
  4904. // this process itself to still allow attaching to this process later
  4905. // if wanted, so is rather heavy. Under Linux we have the PID of the
  4906. // "debugger" (which doesn't need to be gdb, of course, it could also
  4907. // be strace, for example) in /proc/$PID/status, so just get it from
  4908. // there instead.
  4909. bool isDebuggerActive(){
  4910. // Libstdc++ has a bug, where std::ifstream sets errno to 0
  4911. // This way our users can properly assert over errno values
  4912. ErrnoGuard guard;
  4913. std::ifstream in("/proc/self/status");
  4914. for( std::string line; std::getline(in, line); ) {
  4915. static const int PREFIX_LEN = 11;
  4916. if( line.compare(0, PREFIX_LEN, "TracerPid:\t") == 0 ) {
  4917. // We're traced if the PID is not 0 and no other PID starts
  4918. // with 0 digit, so it's enough to check for just a single
  4919. // character.
  4920. return line.length() > PREFIX_LEN && line[PREFIX_LEN] != '0';
  4921. }
  4922. }
  4923. return false;
  4924. }
  4925. } // namespace Catch
  4926. #elif defined(_MSC_VER)
  4927. extern "C" __declspec(dllimport) int __stdcall IsDebuggerPresent();
  4928. namespace Catch {
  4929. bool isDebuggerActive() {
  4930. return IsDebuggerPresent() != 0;
  4931. }
  4932. }
  4933. #elif defined(__MINGW32__)
  4934. extern "C" __declspec(dllimport) int __stdcall IsDebuggerPresent();
  4935. namespace Catch {
  4936. bool isDebuggerActive() {
  4937. return IsDebuggerPresent() != 0;
  4938. }
  4939. }
  4940. #else
  4941. namespace Catch {
  4942. bool isDebuggerActive() { return false; }
  4943. }
  4944. #endif // Platform
  4945. // end catch_debugger.cpp
  4946. // start catch_decomposer.cpp
  4947. namespace Catch {
  4948. ITransientExpression::~ITransientExpression() = default;
  4949. void formatReconstructedExpression( std::ostream &os, std::string const& lhs, StringRef op, std::string const& rhs ) {
  4950. if( lhs.size() + rhs.size() < 40 &&
  4951. lhs.find('\n') == std::string::npos &&
  4952. rhs.find('\n') == std::string::npos )
  4953. os << lhs << " " << op << " " << rhs;
  4954. else
  4955. os << lhs << "\n" << op << "\n" << rhs;
  4956. }
  4957. }
  4958. // end catch_decomposer.cpp
  4959. // start catch_errno_guard.cpp
  4960. #include <cerrno>
  4961. namespace Catch {
  4962. ErrnoGuard::ErrnoGuard():m_oldErrno(errno){}
  4963. ErrnoGuard::~ErrnoGuard() { errno = m_oldErrno; }
  4964. }
  4965. // end catch_errno_guard.cpp
  4966. // start catch_exception_translator_registry.cpp
  4967. // start catch_exception_translator_registry.h
  4968. #include <vector>
  4969. #include <string>
  4970. #include <memory>
  4971. namespace Catch {
  4972. class ExceptionTranslatorRegistry : public IExceptionTranslatorRegistry {
  4973. public:
  4974. ~ExceptionTranslatorRegistry();
  4975. virtual void registerTranslator( const IExceptionTranslator* translator );
  4976. virtual std::string translateActiveException() const override;
  4977. std::string tryTranslators() const;
  4978. private:
  4979. std::vector<std::unique_ptr<IExceptionTranslator const>> m_translators;
  4980. };
  4981. }
  4982. // end catch_exception_translator_registry.h
  4983. #ifdef __OBJC__
  4984. #import "Foundation/Foundation.h"
  4985. #endif
  4986. namespace Catch {
  4987. ExceptionTranslatorRegistry::~ExceptionTranslatorRegistry() {
  4988. }
  4989. void ExceptionTranslatorRegistry::registerTranslator( const IExceptionTranslator* translator ) {
  4990. m_translators.push_back( std::unique_ptr<const IExceptionTranslator>( translator ) );
  4991. }
  4992. std::string ExceptionTranslatorRegistry::translateActiveException() const {
  4993. try {
  4994. #ifdef __OBJC__
  4995. // In Objective-C try objective-c exceptions first
  4996. @try {
  4997. return tryTranslators();
  4998. }
  4999. @catch (NSException *exception) {
  5000. return Catch::Detail::stringify( [exception description] );
  5001. }
  5002. #else
  5003. return tryTranslators();
  5004. #endif
  5005. }
  5006. catch( TestFailureException& ) {
  5007. throw;
  5008. }
  5009. catch( std::exception& ex ) {
  5010. return ex.what();
  5011. }
  5012. catch( std::string& msg ) {
  5013. return msg;
  5014. }
  5015. catch( const char* msg ) {
  5016. return msg;
  5017. }
  5018. catch(...) {
  5019. return "Unknown exception";
  5020. }
  5021. }
  5022. std::string ExceptionTranslatorRegistry::tryTranslators() const {
  5023. if( m_translators.empty() )
  5024. throw;
  5025. else
  5026. return m_translators[0]->translate( m_translators.begin()+1, m_translators.end() );
  5027. }
  5028. }
  5029. // end catch_exception_translator_registry.cpp
  5030. // start catch_fatal_condition.cpp
  5031. // start catch_fatal_condition.h
  5032. #include <string>
  5033. #if defined ( CATCH_PLATFORM_WINDOWS ) /////////////////////////////////////////
  5034. # if !defined ( CATCH_CONFIG_WINDOWS_SEH )
  5035. namespace Catch {
  5036. struct FatalConditionHandler {
  5037. void reset();
  5038. };
  5039. }
  5040. # else // CATCH_CONFIG_WINDOWS_SEH is defined
  5041. namespace Catch {
  5042. struct FatalConditionHandler {
  5043. static LONG CALLBACK handleVectoredException(PEXCEPTION_POINTERS ExceptionInfo);
  5044. FatalConditionHandler();
  5045. static void reset();
  5046. ~FatalConditionHandler();
  5047. private:
  5048. static bool isSet;
  5049. static ULONG guaranteeSize;
  5050. static PVOID exceptionHandlerHandle;
  5051. };
  5052. } // namespace Catch
  5053. # endif // CATCH_CONFIG_WINDOWS_SEH
  5054. #else // Not Windows - assumed to be POSIX compatible //////////////////////////
  5055. # if !defined(CATCH_CONFIG_POSIX_SIGNALS)
  5056. namespace Catch {
  5057. struct FatalConditionHandler {
  5058. void reset();
  5059. };
  5060. }
  5061. # else // CATCH_CONFIG_POSIX_SIGNALS is defined
  5062. #include <signal.h>
  5063. namespace Catch {
  5064. struct FatalConditionHandler {
  5065. static bool isSet;
  5066. static struct sigaction oldSigActions[];// [sizeof(signalDefs) / sizeof(SignalDefs)];
  5067. static stack_t oldSigStack;
  5068. static char altStackMem[];
  5069. static void handleSignal( int sig );
  5070. FatalConditionHandler();
  5071. ~FatalConditionHandler();
  5072. static void reset();
  5073. };
  5074. } // namespace Catch
  5075. # endif // CATCH_CONFIG_POSIX_SIGNALS
  5076. #endif // not Windows
  5077. // end catch_fatal_condition.h
  5078. namespace {
  5079. // Report the error condition
  5080. void reportFatal( char const * const message ) {
  5081. Catch::getCurrentContext().getResultCapture()->handleFatalErrorCondition( message );
  5082. }
  5083. }
  5084. #if defined ( CATCH_PLATFORM_WINDOWS ) /////////////////////////////////////////
  5085. # if !defined ( CATCH_CONFIG_WINDOWS_SEH )
  5086. namespace Catch {
  5087. void FatalConditionHandler::reset() {}
  5088. }
  5089. # else // CATCH_CONFIG_WINDOWS_SEH is defined
  5090. namespace Catch {
  5091. struct SignalDefs { DWORD id; const char* name; };
  5092. // There is no 1-1 mapping between signals and windows exceptions.
  5093. // Windows can easily distinguish between SO and SigSegV,
  5094. // but SigInt, SigTerm, etc are handled differently.
  5095. static SignalDefs signalDefs[] = {
  5096. { EXCEPTION_ILLEGAL_INSTRUCTION, "SIGILL - Illegal instruction signal" },
  5097. { EXCEPTION_STACK_OVERFLOW, "SIGSEGV - Stack overflow" },
  5098. { EXCEPTION_ACCESS_VIOLATION, "SIGSEGV - Segmentation violation signal" },
  5099. { EXCEPTION_INT_DIVIDE_BY_ZERO, "Divide by zero error" },
  5100. };
  5101. LONG CALLBACK FatalConditionHandler::handleVectoredException(PEXCEPTION_POINTERS ExceptionInfo) {
  5102. for (auto const& def : signalDefs) {
  5103. if (ExceptionInfo->ExceptionRecord->ExceptionCode == def.id) {
  5104. reportFatal(def.name);
  5105. }
  5106. }
  5107. // If its not an exception we care about, pass it along.
  5108. // This stops us from eating debugger breaks etc.
  5109. return EXCEPTION_CONTINUE_SEARCH;
  5110. }
  5111. FatalConditionHandler::FatalConditionHandler() {
  5112. isSet = true;
  5113. // 32k seems enough for Catch to handle stack overflow,
  5114. // but the value was found experimentally, so there is no strong guarantee
  5115. guaranteeSize = 32 * 1024;
  5116. exceptionHandlerHandle = nullptr;
  5117. // Register as first handler in current chain
  5118. exceptionHandlerHandle = AddVectoredExceptionHandler(1, handleVectoredException);
  5119. // Pass in guarantee size to be filled
  5120. SetThreadStackGuarantee(&guaranteeSize);
  5121. }
  5122. void FatalConditionHandler::reset() {
  5123. if (isSet) {
  5124. // Unregister handler and restore the old guarantee
  5125. RemoveVectoredExceptionHandler(exceptionHandlerHandle);
  5126. SetThreadStackGuarantee(&guaranteeSize);
  5127. exceptionHandlerHandle = nullptr;
  5128. isSet = false;
  5129. }
  5130. }
  5131. FatalConditionHandler::~FatalConditionHandler() {
  5132. reset();
  5133. }
  5134. bool FatalConditionHandler::isSet = false;
  5135. ULONG FatalConditionHandler::guaranteeSize = 0;
  5136. PVOID FatalConditionHandler::exceptionHandlerHandle = nullptr;
  5137. } // namespace Catch
  5138. # endif // CATCH_CONFIG_WINDOWS_SEH
  5139. #else // Not Windows - assumed to be POSIX compatible //////////////////////////
  5140. # if !defined(CATCH_CONFIG_POSIX_SIGNALS)
  5141. namespace Catch {
  5142. void FatalConditionHandler::reset() {}
  5143. }
  5144. # else // CATCH_CONFIG_POSIX_SIGNALS is defined
  5145. #include <signal.h>
  5146. namespace Catch {
  5147. struct SignalDefs {
  5148. int id;
  5149. const char* name;
  5150. };
  5151. static SignalDefs signalDefs[] = {
  5152. { SIGINT, "SIGINT - Terminal interrupt signal" },
  5153. { SIGILL, "SIGILL - Illegal instruction signal" },
  5154. { SIGFPE, "SIGFPE - Floating point error signal" },
  5155. { SIGSEGV, "SIGSEGV - Segmentation violation signal" },
  5156. { SIGTERM, "SIGTERM - Termination request signal" },
  5157. { SIGABRT, "SIGABRT - Abort (abnormal termination) signal" }
  5158. };
  5159. void FatalConditionHandler::handleSignal( int sig ) {
  5160. char const * name = "<unknown signal>";
  5161. for (auto const& def : signalDefs) {
  5162. if (sig == def.id) {
  5163. name = def.name;
  5164. break;
  5165. }
  5166. }
  5167. reset();
  5168. reportFatal(name);
  5169. raise( sig );
  5170. }
  5171. FatalConditionHandler::FatalConditionHandler() {
  5172. isSet = true;
  5173. stack_t sigStack;
  5174. sigStack.ss_sp = altStackMem;
  5175. sigStack.ss_size = SIGSTKSZ;
  5176. sigStack.ss_flags = 0;
  5177. sigaltstack(&sigStack, &oldSigStack);
  5178. struct sigaction sa = { };
  5179. sa.sa_handler = handleSignal;
  5180. sa.sa_flags = SA_ONSTACK;
  5181. for (std::size_t i = 0; i < sizeof(signalDefs)/sizeof(SignalDefs); ++i) {
  5182. sigaction(signalDefs[i].id, &sa, &oldSigActions[i]);
  5183. }
  5184. }
  5185. FatalConditionHandler::~FatalConditionHandler() {
  5186. reset();
  5187. }
  5188. void FatalConditionHandler::reset() {
  5189. if( isSet ) {
  5190. // Set signals back to previous values -- hopefully nobody overwrote them in the meantime
  5191. for( std::size_t i = 0; i < sizeof(signalDefs)/sizeof(SignalDefs); ++i ) {
  5192. sigaction(signalDefs[i].id, &oldSigActions[i], nullptr);
  5193. }
  5194. // Return the old stack
  5195. sigaltstack(&oldSigStack, nullptr);
  5196. isSet = false;
  5197. }
  5198. }
  5199. bool FatalConditionHandler::isSet = false;
  5200. struct sigaction FatalConditionHandler::oldSigActions[sizeof(signalDefs)/sizeof(SignalDefs)] = {};
  5201. stack_t FatalConditionHandler::oldSigStack = {};
  5202. char FatalConditionHandler::altStackMem[SIGSTKSZ] = {};
  5203. } // namespace Catch
  5204. # endif // CATCH_CONFIG_POSIX_SIGNALS
  5205. #endif // not Windows
  5206. // end catch_fatal_condition.cpp
  5207. // start catch_interfaces_capture.cpp
  5208. namespace Catch {
  5209. IResultCapture::~IResultCapture() = default;
  5210. }
  5211. // end catch_interfaces_capture.cpp
  5212. // start catch_interfaces_config.cpp
  5213. namespace Catch {
  5214. IConfig::~IConfig() = default;
  5215. }
  5216. // end catch_interfaces_config.cpp
  5217. // start catch_interfaces_exception.cpp
  5218. namespace Catch {
  5219. IExceptionTranslator::~IExceptionTranslator() = default;
  5220. IExceptionTranslatorRegistry::~IExceptionTranslatorRegistry() = default;
  5221. }
  5222. // end catch_interfaces_exception.cpp
  5223. // start catch_interfaces_registry_hub.cpp
  5224. namespace Catch {
  5225. IRegistryHub::~IRegistryHub() = default;
  5226. IMutableRegistryHub::~IMutableRegistryHub() = default;
  5227. }
  5228. // end catch_interfaces_registry_hub.cpp
  5229. // start catch_interfaces_reporter.cpp
  5230. // start catch_reporter_multi.h
  5231. namespace Catch {
  5232. class MultipleReporters : public IStreamingReporter {
  5233. using Reporters = std::vector<IStreamingReporterPtr>;
  5234. Reporters m_reporters;
  5235. public:
  5236. void add( IStreamingReporterPtr&& reporter );
  5237. public: // IStreamingReporter
  5238. ReporterPreferences getPreferences() const override;
  5239. void noMatchingTestCases( std::string const& spec ) override;
  5240. static std::set<Verbosity> getSupportedVerbosities();
  5241. void testRunStarting( TestRunInfo const& testRunInfo ) override;
  5242. void testGroupStarting( GroupInfo const& groupInfo ) override;
  5243. void testCaseStarting( TestCaseInfo const& testInfo ) override;
  5244. void sectionStarting( SectionInfo const& sectionInfo ) override;
  5245. void assertionStarting( AssertionInfo const& assertionInfo ) override;
  5246. // The return value indicates if the messages buffer should be cleared:
  5247. bool assertionEnded( AssertionStats const& assertionStats ) override;
  5248. void sectionEnded( SectionStats const& sectionStats ) override;
  5249. void testCaseEnded( TestCaseStats const& testCaseStats ) override;
  5250. void testGroupEnded( TestGroupStats const& testGroupStats ) override;
  5251. void testRunEnded( TestRunStats const& testRunStats ) override;
  5252. void skipTest( TestCaseInfo const& testInfo ) override;
  5253. bool isMulti() const override;
  5254. };
  5255. } // end namespace Catch
  5256. // end catch_reporter_multi.h
  5257. namespace Catch {
  5258. ReporterConfig::ReporterConfig( IConfigPtr const& _fullConfig )
  5259. : m_stream( &_fullConfig->stream() ), m_fullConfig( _fullConfig ) {}
  5260. ReporterConfig::ReporterConfig( IConfigPtr const& _fullConfig, std::ostream& _stream )
  5261. : m_stream( &_stream ), m_fullConfig( _fullConfig ) {}
  5262. std::ostream& ReporterConfig::stream() const { return *m_stream; }
  5263. IConfigPtr ReporterConfig::fullConfig() const { return m_fullConfig; }
  5264. TestRunInfo::TestRunInfo( std::string const& _name ) : name( _name ) {}
  5265. GroupInfo::GroupInfo( std::string const& _name,
  5266. std::size_t _groupIndex,
  5267. std::size_t _groupsCount )
  5268. : name( _name ),
  5269. groupIndex( _groupIndex ),
  5270. groupsCounts( _groupsCount )
  5271. {}
  5272. AssertionStats::AssertionStats( AssertionResult const& _assertionResult,
  5273. std::vector<MessageInfo> const& _infoMessages,
  5274. Totals const& _totals )
  5275. : assertionResult( _assertionResult ),
  5276. infoMessages( _infoMessages ),
  5277. totals( _totals )
  5278. {
  5279. assertionResult.m_resultData.lazyExpression.m_transientExpression = _assertionResult.m_resultData.lazyExpression.m_transientExpression;
  5280. if( assertionResult.hasMessage() ) {
  5281. // Copy message into messages list.
  5282. // !TBD This should have been done earlier, somewhere
  5283. MessageBuilder builder( assertionResult.getTestMacroName(), assertionResult.getSourceInfo(), assertionResult.getResultType() );
  5284. builder << assertionResult.getMessage();
  5285. builder.m_info.message = builder.m_stream.str();
  5286. infoMessages.push_back( builder.m_info );
  5287. }
  5288. }
  5289. AssertionStats::~AssertionStats() = default;
  5290. SectionStats::SectionStats( SectionInfo const& _sectionInfo,
  5291. Counts const& _assertions,
  5292. double _durationInSeconds,
  5293. bool _missingAssertions )
  5294. : sectionInfo( _sectionInfo ),
  5295. assertions( _assertions ),
  5296. durationInSeconds( _durationInSeconds ),
  5297. missingAssertions( _missingAssertions )
  5298. {}
  5299. SectionStats::~SectionStats() = default;
  5300. TestCaseStats::TestCaseStats( TestCaseInfo const& _testInfo,
  5301. Totals const& _totals,
  5302. std::string const& _stdOut,
  5303. std::string const& _stdErr,
  5304. bool _aborting )
  5305. : testInfo( _testInfo ),
  5306. totals( _totals ),
  5307. stdOut( _stdOut ),
  5308. stdErr( _stdErr ),
  5309. aborting( _aborting )
  5310. {}
  5311. TestCaseStats::~TestCaseStats() = default;
  5312. TestGroupStats::TestGroupStats( GroupInfo const& _groupInfo,
  5313. Totals const& _totals,
  5314. bool _aborting )
  5315. : groupInfo( _groupInfo ),
  5316. totals( _totals ),
  5317. aborting( _aborting )
  5318. {}
  5319. TestGroupStats::TestGroupStats( GroupInfo const& _groupInfo )
  5320. : groupInfo( _groupInfo ),
  5321. aborting( false )
  5322. {}
  5323. TestGroupStats::~TestGroupStats() = default;
  5324. TestRunStats::TestRunStats( TestRunInfo const& _runInfo,
  5325. Totals const& _totals,
  5326. bool _aborting )
  5327. : runInfo( _runInfo ),
  5328. totals( _totals ),
  5329. aborting( _aborting )
  5330. {}
  5331. TestRunStats::~TestRunStats() = default;
  5332. void IStreamingReporter::fatalErrorEncountered( StringRef ) {}
  5333. bool IStreamingReporter::isMulti() const { return false; }
  5334. IReporterFactory::~IReporterFactory() = default;
  5335. IReporterRegistry::~IReporterRegistry() = default;
  5336. void addReporter( IStreamingReporterPtr& existingReporter, IStreamingReporterPtr&& additionalReporter ) {
  5337. if( !existingReporter ) {
  5338. existingReporter = std::move( additionalReporter );
  5339. return;
  5340. }
  5341. MultipleReporters* multi = nullptr;
  5342. if( existingReporter->isMulti() ) {
  5343. multi = static_cast<MultipleReporters*>( existingReporter.get() );
  5344. }
  5345. else {
  5346. auto newMulti = std::unique_ptr<MultipleReporters>( new MultipleReporters );
  5347. newMulti->add( std::move( existingReporter ) );
  5348. multi = newMulti.get();
  5349. existingReporter = std::move( newMulti );
  5350. }
  5351. multi->add( std::move( additionalReporter ) );
  5352. }
  5353. } // end namespace Catch
  5354. // end catch_interfaces_reporter.cpp
  5355. // start catch_interfaces_runner.cpp
  5356. namespace Catch {
  5357. IRunner::~IRunner() = default;
  5358. }
  5359. // end catch_interfaces_runner.cpp
  5360. // start catch_interfaces_testcase.cpp
  5361. namespace Catch {
  5362. ITestInvoker::~ITestInvoker() = default;
  5363. ITestCaseRegistry::~ITestCaseRegistry() = default;
  5364. }
  5365. // end catch_interfaces_testcase.cpp
  5366. // start catch_leak_detector.cpp
  5367. namespace Catch {
  5368. #ifdef CATCH_CONFIG_WINDOWS_CRTDBG
  5369. #include <crtdbg.h>
  5370. LeakDetector::LeakDetector() {
  5371. int flag = _CrtSetDbgFlag(_CRTDBG_REPORT_FLAG);
  5372. flag |= _CRTDBG_LEAK_CHECK_DF;
  5373. flag |= _CRTDBG_ALLOC_MEM_DF;
  5374. _CrtSetDbgFlag(flag);
  5375. _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE | _CRTDBG_MODE_DEBUG);
  5376. _CrtSetReportFile(_CRT_WARN, _CRTDBG_FILE_STDERR);
  5377. // Change this to leaking allocation's number to break there
  5378. _CrtSetBreakAlloc(-1);
  5379. }
  5380. #else
  5381. LeakDetector::LeakDetector(){}
  5382. #endif
  5383. }
  5384. // end catch_leak_detector.cpp
  5385. // start catch_list.cpp
  5386. // start catch_list.h
  5387. #include <set>
  5388. namespace Catch {
  5389. std::size_t listTests( Config const& config );
  5390. std::size_t listTestsNamesOnly( Config const& config );
  5391. struct TagInfo {
  5392. void add( std::string const& spelling );
  5393. std::string all() const;
  5394. std::set<std::string> spellings;
  5395. std::size_t count = 0;
  5396. };
  5397. std::size_t listTags( Config const& config );
  5398. std::size_t listReporters( Config const& /*config*/ );
  5399. Option<std::size_t> list( Config const& config );
  5400. } // end namespace Catch
  5401. // end catch_list.h
  5402. // start catch_text.h
  5403. namespace Catch {
  5404. using namespace clara::TextFlow;
  5405. }
  5406. // end catch_text.h
  5407. #include <limits>
  5408. #include <algorithm>
  5409. #include <iomanip>
  5410. namespace Catch {
  5411. std::size_t listTests( Config const& config ) {
  5412. TestSpec testSpec = config.testSpec();
  5413. if( config.testSpec().hasFilters() )
  5414. Catch::cout() << "Matching test cases:\n";
  5415. else {
  5416. Catch::cout() << "All available test cases:\n";
  5417. testSpec = TestSpecParser( ITagAliasRegistry::get() ).parse( "*" ).testSpec();
  5418. }
  5419. auto matchedTestCases = filterTests( getAllTestCasesSorted( config ), testSpec, config );
  5420. for( auto const& testCaseInfo : matchedTestCases ) {
  5421. Colour::Code colour = testCaseInfo.isHidden()
  5422. ? Colour::SecondaryText
  5423. : Colour::None;
  5424. Colour colourGuard( colour );
  5425. Catch::cout() << Column( testCaseInfo.name ).initialIndent( 2 ).indent( 4 ) << "\n";
  5426. if( config.verbosity() >= Verbosity::High ) {
  5427. Catch::cout() << Column( Catch::Detail::stringify( testCaseInfo.lineInfo ) ).indent(4) << std::endl;
  5428. std::string description = testCaseInfo.description;
  5429. if( description.empty() )
  5430. description = "(NO DESCRIPTION)";
  5431. Catch::cout() << Column( description ).indent(4) << std::endl;
  5432. }
  5433. if( !testCaseInfo.tags.empty() )
  5434. Catch::cout() << Column( testCaseInfo.tagsAsString() ).indent( 6 ) << "\n";
  5435. }
  5436. if( !config.testSpec().hasFilters() )
  5437. Catch::cout() << pluralise( matchedTestCases.size(), "test case" ) << '\n' << std::endl;
  5438. else
  5439. Catch::cout() << pluralise( matchedTestCases.size(), "matching test case" ) << '\n' << std::endl;
  5440. return matchedTestCases.size();
  5441. }
  5442. std::size_t listTestsNamesOnly( Config const& config ) {
  5443. TestSpec testSpec = config.testSpec();
  5444. if( !config.testSpec().hasFilters() )
  5445. testSpec = TestSpecParser( ITagAliasRegistry::get() ).parse( "*" ).testSpec();
  5446. std::size_t matchedTests = 0;
  5447. std::vector<TestCase> matchedTestCases = filterTests( getAllTestCasesSorted( config ), testSpec, config );
  5448. for( auto const& testCaseInfo : matchedTestCases ) {
  5449. matchedTests++;
  5450. if( startsWith( testCaseInfo.name, '#' ) )
  5451. Catch::cout() << '"' << testCaseInfo.name << '"';
  5452. else
  5453. Catch::cout() << testCaseInfo.name;
  5454. if ( config.verbosity() >= Verbosity::High )
  5455. Catch::cout() << "\t@" << testCaseInfo.lineInfo;
  5456. Catch::cout() << std::endl;
  5457. }
  5458. return matchedTests;
  5459. }
  5460. void TagInfo::add( std::string const& spelling ) {
  5461. ++count;
  5462. spellings.insert( spelling );
  5463. }
  5464. std::string TagInfo::all() const {
  5465. std::string out;
  5466. for( auto const& spelling : spellings )
  5467. out += "[" + spelling + "]";
  5468. return out;
  5469. }
  5470. std::size_t listTags( Config const& config ) {
  5471. TestSpec testSpec = config.testSpec();
  5472. if( config.testSpec().hasFilters() )
  5473. Catch::cout() << "Tags for matching test cases:\n";
  5474. else {
  5475. Catch::cout() << "All available tags:\n";
  5476. testSpec = TestSpecParser( ITagAliasRegistry::get() ).parse( "*" ).testSpec();
  5477. }
  5478. std::map<std::string, TagInfo> tagCounts;
  5479. std::vector<TestCase> matchedTestCases = filterTests( getAllTestCasesSorted( config ), testSpec, config );
  5480. for( auto const& testCase : matchedTestCases ) {
  5481. for( auto const& tagName : testCase.getTestCaseInfo().tags ) {
  5482. std::string lcaseTagName = toLower( tagName );
  5483. auto countIt = tagCounts.find( lcaseTagName );
  5484. if( countIt == tagCounts.end() )
  5485. countIt = tagCounts.insert( std::make_pair( lcaseTagName, TagInfo() ) ).first;
  5486. countIt->second.add( tagName );
  5487. }
  5488. }
  5489. for( auto const& tagCount : tagCounts ) {
  5490. std::ostringstream oss;
  5491. oss << " " << std::setw(2) << tagCount.second.count << " ";
  5492. auto wrapper = Column( tagCount.second.all() )
  5493. .initialIndent( 0 )
  5494. .indent( oss.str().size() )
  5495. .width( CATCH_CONFIG_CONSOLE_WIDTH-10 );
  5496. Catch::cout() << oss.str() << wrapper << '\n';
  5497. }
  5498. Catch::cout() << pluralise( tagCounts.size(), "tag" ) << '\n' << std::endl;
  5499. return tagCounts.size();
  5500. }
  5501. std::size_t listReporters( Config const& /*config*/ ) {
  5502. Catch::cout() << "Available reporters:\n";
  5503. IReporterRegistry::FactoryMap const& factories = getRegistryHub().getReporterRegistry().getFactories();
  5504. std::size_t maxNameLen = 0;
  5505. for( auto const& factoryKvp : factories )
  5506. maxNameLen = (std::max)( maxNameLen, factoryKvp.first.size() );
  5507. for( auto const& factoryKvp : factories ) {
  5508. Catch::cout()
  5509. << Column( factoryKvp.first + ":" )
  5510. .indent(2)
  5511. .width( 5+maxNameLen )
  5512. + Column( factoryKvp.second->getDescription() )
  5513. .initialIndent(0)
  5514. .indent(2)
  5515. .width( CATCH_CONFIG_CONSOLE_WIDTH - maxNameLen-8 )
  5516. << "\n";
  5517. }
  5518. Catch::cout() << std::endl;
  5519. return factories.size();
  5520. }
  5521. Option<std::size_t> list( Config const& config ) {
  5522. Option<std::size_t> listedCount;
  5523. if( config.listTests() )
  5524. listedCount = listedCount.valueOr(0) + listTests( config );
  5525. if( config.listTestNamesOnly() )
  5526. listedCount = listedCount.valueOr(0) + listTestsNamesOnly( config );
  5527. if( config.listTags() )
  5528. listedCount = listedCount.valueOr(0) + listTags( config );
  5529. if( config.listReporters() )
  5530. listedCount = listedCount.valueOr(0) + listReporters( config );
  5531. return listedCount;
  5532. }
  5533. } // end namespace Catch
  5534. // end catch_list.cpp
  5535. // start catch_matchers.cpp
  5536. namespace Catch {
  5537. namespace Matchers {
  5538. namespace Impl {
  5539. std::string MatcherUntypedBase::toString() const {
  5540. if( m_cachedToString.empty() )
  5541. m_cachedToString = describe();
  5542. return m_cachedToString;
  5543. }
  5544. MatcherUntypedBase::~MatcherUntypedBase() = default;
  5545. } // namespace Impl
  5546. } // namespace Matchers
  5547. using namespace Matchers;
  5548. using Matchers::Impl::MatcherBase;
  5549. } // namespace Catch
  5550. // end catch_matchers.cpp
  5551. // start catch_matchers_string.cpp
  5552. namespace Catch {
  5553. namespace Matchers {
  5554. namespace StdString {
  5555. CasedString::CasedString( std::string const& str, CaseSensitive::Choice caseSensitivity )
  5556. : m_caseSensitivity( caseSensitivity ),
  5557. m_str( adjustString( str ) )
  5558. {}
  5559. std::string CasedString::adjustString( std::string const& str ) const {
  5560. return m_caseSensitivity == CaseSensitive::No
  5561. ? toLower( str )
  5562. : str;
  5563. }
  5564. std::string CasedString::caseSensitivitySuffix() const {
  5565. return m_caseSensitivity == CaseSensitive::No
  5566. ? " (case insensitive)"
  5567. : std::string();
  5568. }
  5569. StringMatcherBase::StringMatcherBase( std::string const& operation, CasedString const& comparator )
  5570. : m_comparator( comparator ),
  5571. m_operation( operation ) {
  5572. }
  5573. std::string StringMatcherBase::describe() const {
  5574. std::string description;
  5575. description.reserve(5 + m_operation.size() + m_comparator.m_str.size() +
  5576. m_comparator.caseSensitivitySuffix().size());
  5577. description += m_operation;
  5578. description += ": \"";
  5579. description += m_comparator.m_str;
  5580. description += "\"";
  5581. description += m_comparator.caseSensitivitySuffix();
  5582. return description;
  5583. }
  5584. EqualsMatcher::EqualsMatcher( CasedString const& comparator ) : StringMatcherBase( "equals", comparator ) {}
  5585. bool EqualsMatcher::match( std::string const& source ) const {
  5586. return m_comparator.adjustString( source ) == m_comparator.m_str;
  5587. }
  5588. ContainsMatcher::ContainsMatcher( CasedString const& comparator ) : StringMatcherBase( "contains", comparator ) {}
  5589. bool ContainsMatcher::match( std::string const& source ) const {
  5590. return contains( m_comparator.adjustString( source ), m_comparator.m_str );
  5591. }
  5592. StartsWithMatcher::StartsWithMatcher( CasedString const& comparator ) : StringMatcherBase( "starts with", comparator ) {}
  5593. bool StartsWithMatcher::match( std::string const& source ) const {
  5594. return startsWith( m_comparator.adjustString( source ), m_comparator.m_str );
  5595. }
  5596. EndsWithMatcher::EndsWithMatcher( CasedString const& comparator ) : StringMatcherBase( "ends with", comparator ) {}
  5597. bool EndsWithMatcher::match( std::string const& source ) const {
  5598. return endsWith( m_comparator.adjustString( source ), m_comparator.m_str );
  5599. }
  5600. } // namespace StdString
  5601. StdString::EqualsMatcher Equals( std::string const& str, CaseSensitive::Choice caseSensitivity ) {
  5602. return StdString::EqualsMatcher( StdString::CasedString( str, caseSensitivity) );
  5603. }
  5604. StdString::ContainsMatcher Contains( std::string const& str, CaseSensitive::Choice caseSensitivity ) {
  5605. return StdString::ContainsMatcher( StdString::CasedString( str, caseSensitivity) );
  5606. }
  5607. StdString::EndsWithMatcher EndsWith( std::string const& str, CaseSensitive::Choice caseSensitivity ) {
  5608. return StdString::EndsWithMatcher( StdString::CasedString( str, caseSensitivity) );
  5609. }
  5610. StdString::StartsWithMatcher StartsWith( std::string const& str, CaseSensitive::Choice caseSensitivity ) {
  5611. return StdString::StartsWithMatcher( StdString::CasedString( str, caseSensitivity) );
  5612. }
  5613. } // namespace Matchers
  5614. } // namespace Catch
  5615. // end catch_matchers_string.cpp
  5616. // start catch_message.cpp
  5617. namespace Catch {
  5618. MessageInfo::MessageInfo( std::string const& _macroName,
  5619. SourceLineInfo const& _lineInfo,
  5620. ResultWas::OfType _type )
  5621. : macroName( _macroName ),
  5622. lineInfo( _lineInfo ),
  5623. type( _type ),
  5624. sequence( ++globalCount )
  5625. {}
  5626. bool MessageInfo::operator==( MessageInfo const& other ) const {
  5627. return sequence == other.sequence;
  5628. }
  5629. bool MessageInfo::operator<( MessageInfo const& other ) const {
  5630. return sequence < other.sequence;
  5631. }
  5632. // This may need protecting if threading support is added
  5633. unsigned int MessageInfo::globalCount = 0;
  5634. ////////////////////////////////////////////////////////////////////////////
  5635. Catch::MessageBuilder::MessageBuilder( std::string const& macroName,
  5636. SourceLineInfo const& lineInfo,
  5637. ResultWas::OfType type )
  5638. :m_info(macroName, lineInfo, type) {}
  5639. ////////////////////////////////////////////////////////////////////////////
  5640. ScopedMessage::ScopedMessage( MessageBuilder const& builder )
  5641. : m_info( builder.m_info )
  5642. {
  5643. m_info.message = builder.m_stream.str();
  5644. getResultCapture().pushScopedMessage( m_info );
  5645. }
  5646. ScopedMessage::~ScopedMessage() {
  5647. if ( !std::uncaught_exception() ){
  5648. getResultCapture().popScopedMessage(m_info);
  5649. }
  5650. }
  5651. } // end namespace Catch
  5652. // end catch_message.cpp
  5653. // start catch_random_number_generator.cpp
  5654. // start catch_random_number_generator.h
  5655. #include <algorithm>
  5656. namespace Catch {
  5657. struct IConfig;
  5658. void seedRng( IConfig const& config );
  5659. unsigned int rngSeed();
  5660. struct RandomNumberGenerator {
  5661. using result_type = std::ptrdiff_t;
  5662. static constexpr result_type min() { return 0; }
  5663. static constexpr result_type max() { return 1000000; }
  5664. result_type operator()( result_type n ) const;
  5665. result_type operator()() const;
  5666. template<typename V>
  5667. static void shuffle( V& vector ) {
  5668. RandomNumberGenerator rng;
  5669. std::shuffle( vector.begin(), vector.end(), rng );
  5670. }
  5671. };
  5672. }
  5673. // end catch_random_number_generator.h
  5674. #include <cstdlib>
  5675. namespace Catch {
  5676. void seedRng( IConfig const& config ) {
  5677. if( config.rngSeed() != 0 )
  5678. std::srand( config.rngSeed() );
  5679. }
  5680. unsigned int rngSeed() {
  5681. return getCurrentContext().getConfig()->rngSeed();
  5682. }
  5683. RandomNumberGenerator::result_type RandomNumberGenerator::operator()( result_type n ) const {
  5684. return std::rand() % n;
  5685. }
  5686. RandomNumberGenerator::result_type RandomNumberGenerator::operator()() const {
  5687. return std::rand() % max();
  5688. }
  5689. }
  5690. // end catch_random_number_generator.cpp
  5691. // start catch_registry_hub.cpp
  5692. // start catch_test_case_registry_impl.h
  5693. #include <vector>
  5694. #include <set>
  5695. #include <algorithm>
  5696. #include <ios>
  5697. namespace Catch {
  5698. class TestCase;
  5699. struct IConfig;
  5700. std::vector<TestCase> sortTests( IConfig const& config, std::vector<TestCase> const& unsortedTestCases );
  5701. bool matchTest( TestCase const& testCase, TestSpec const& testSpec, IConfig const& config );
  5702. void enforceNoDuplicateTestCases( std::vector<TestCase> const& functions );
  5703. std::vector<TestCase> filterTests( std::vector<TestCase> const& testCases, TestSpec const& testSpec, IConfig const& config );
  5704. std::vector<TestCase> const& getAllTestCasesSorted( IConfig const& config );
  5705. class TestRegistry : public ITestCaseRegistry {
  5706. public:
  5707. virtual ~TestRegistry() = default;
  5708. virtual void registerTest( TestCase const& testCase );
  5709. std::vector<TestCase> const& getAllTests() const override;
  5710. std::vector<TestCase> const& getAllTestsSorted( IConfig const& config ) const override;
  5711. private:
  5712. std::vector<TestCase> m_functions;
  5713. mutable RunTests::InWhatOrder m_currentSortOrder = RunTests::InDeclarationOrder;
  5714. mutable std::vector<TestCase> m_sortedFunctions;
  5715. std::size_t m_unnamedCount = 0;
  5716. std::ios_base::Init m_ostreamInit; // Forces cout/ cerr to be initialised
  5717. };
  5718. ///////////////////////////////////////////////////////////////////////////
  5719. class TestInvokerAsFunction : public ITestInvoker {
  5720. void(*m_testAsFunction)();
  5721. public:
  5722. TestInvokerAsFunction( void(*testAsFunction)() ) noexcept;
  5723. void invoke() const override;
  5724. };
  5725. std::string extractClassName( std::string const& classOrQualifiedMethodName );
  5726. ///////////////////////////////////////////////////////////////////////////
  5727. } // end namespace Catch
  5728. // end catch_test_case_registry_impl.h
  5729. // start catch_reporter_registry.h
  5730. #include <map>
  5731. namespace Catch {
  5732. class ReporterRegistry : public IReporterRegistry {
  5733. public:
  5734. ~ReporterRegistry() override;
  5735. IStreamingReporterPtr create( std::string const& name, IConfigPtr const& config ) const override;
  5736. void registerReporter( std::string const& name, IReporterFactoryPtr const& factory );
  5737. void registerListener( IReporterFactoryPtr const& factory );
  5738. FactoryMap const& getFactories() const override;
  5739. Listeners const& getListeners() const override;
  5740. private:
  5741. FactoryMap m_factories;
  5742. Listeners m_listeners;
  5743. };
  5744. }
  5745. // end catch_reporter_registry.h
  5746. // start catch_tag_alias_registry.h
  5747. // start catch_tag_alias.h
  5748. #include <string>
  5749. namespace Catch {
  5750. struct TagAlias {
  5751. TagAlias(std::string const& _tag, SourceLineInfo _lineInfo);
  5752. std::string tag;
  5753. SourceLineInfo lineInfo;
  5754. };
  5755. } // end namespace Catch
  5756. // end catch_tag_alias.h
  5757. #include <map>
  5758. namespace Catch {
  5759. class TagAliasRegistry : public ITagAliasRegistry {
  5760. public:
  5761. ~TagAliasRegistry() override;
  5762. TagAlias const* find( std::string const& alias ) const override;
  5763. std::string expandAliases( std::string const& unexpandedTestSpec ) const override;
  5764. void add( std::string const& alias, std::string const& tag, SourceLineInfo const& lineInfo );
  5765. private:
  5766. std::map<std::string, TagAlias> m_registry;
  5767. };
  5768. } // end namespace Catch
  5769. // end catch_tag_alias_registry.h
  5770. // start catch_startup_exception_registry.h
  5771. #include <vector>
  5772. #include <exception>
  5773. namespace Catch {
  5774. class StartupExceptionRegistry {
  5775. public:
  5776. void add(std::exception_ptr const& exception) noexcept;
  5777. std::vector<std::exception_ptr> const& getExceptions() const noexcept;
  5778. private:
  5779. std::vector<std::exception_ptr> m_exceptions;
  5780. };
  5781. } // end namespace Catch
  5782. // end catch_startup_exception_registry.h
  5783. namespace Catch {
  5784. namespace {
  5785. class RegistryHub : public IRegistryHub, public IMutableRegistryHub,
  5786. private NonCopyable {
  5787. public: // IRegistryHub
  5788. RegistryHub() = default;
  5789. IReporterRegistry const& getReporterRegistry() const override {
  5790. return m_reporterRegistry;
  5791. }
  5792. ITestCaseRegistry const& getTestCaseRegistry() const override {
  5793. return m_testCaseRegistry;
  5794. }
  5795. IExceptionTranslatorRegistry& getExceptionTranslatorRegistry() override {
  5796. return m_exceptionTranslatorRegistry;
  5797. }
  5798. ITagAliasRegistry const& getTagAliasRegistry() const override {
  5799. return m_tagAliasRegistry;
  5800. }
  5801. StartupExceptionRegistry const& getStartupExceptionRegistry() const override {
  5802. return m_exceptionRegistry;
  5803. }
  5804. public: // IMutableRegistryHub
  5805. void registerReporter( std::string const& name, IReporterFactoryPtr const& factory ) override {
  5806. m_reporterRegistry.registerReporter( name, factory );
  5807. }
  5808. void registerListener( IReporterFactoryPtr const& factory ) override {
  5809. m_reporterRegistry.registerListener( factory );
  5810. }
  5811. void registerTest( TestCase const& testInfo ) override {
  5812. m_testCaseRegistry.registerTest( testInfo );
  5813. }
  5814. void registerTranslator( const IExceptionTranslator* translator ) override {
  5815. m_exceptionTranslatorRegistry.registerTranslator( translator );
  5816. }
  5817. void registerTagAlias( std::string const& alias, std::string const& tag, SourceLineInfo const& lineInfo ) override {
  5818. m_tagAliasRegistry.add( alias, tag, lineInfo );
  5819. }
  5820. void registerStartupException() noexcept override {
  5821. m_exceptionRegistry.add(std::current_exception());
  5822. }
  5823. private:
  5824. TestRegistry m_testCaseRegistry;
  5825. ReporterRegistry m_reporterRegistry;
  5826. ExceptionTranslatorRegistry m_exceptionTranslatorRegistry;
  5827. TagAliasRegistry m_tagAliasRegistry;
  5828. StartupExceptionRegistry m_exceptionRegistry;
  5829. };
  5830. // Single, global, instance
  5831. RegistryHub*& getTheRegistryHub() {
  5832. static RegistryHub* theRegistryHub = nullptr;
  5833. if( !theRegistryHub )
  5834. theRegistryHub = new RegistryHub();
  5835. return theRegistryHub;
  5836. }
  5837. }
  5838. IRegistryHub& getRegistryHub() {
  5839. return *getTheRegistryHub();
  5840. }
  5841. IMutableRegistryHub& getMutableRegistryHub() {
  5842. return *getTheRegistryHub();
  5843. }
  5844. void cleanUp() {
  5845. delete getTheRegistryHub();
  5846. getTheRegistryHub() = nullptr;
  5847. cleanUpContext();
  5848. }
  5849. std::string translateActiveException() {
  5850. return getRegistryHub().getExceptionTranslatorRegistry().translateActiveException();
  5851. }
  5852. } // end namespace Catch
  5853. // end catch_registry_hub.cpp
  5854. // start catch_reporter_registry.cpp
  5855. namespace Catch {
  5856. ReporterRegistry::~ReporterRegistry() = default;
  5857. IStreamingReporterPtr ReporterRegistry::create( std::string const& name, IConfigPtr const& config ) const {
  5858. auto it = m_factories.find( name );
  5859. if( it == m_factories.end() )
  5860. return nullptr;
  5861. return it->second->create( ReporterConfig( config ) );
  5862. }
  5863. void ReporterRegistry::registerReporter( std::string const& name, IReporterFactoryPtr const& factory ) {
  5864. m_factories.emplace(name, factory);
  5865. }
  5866. void ReporterRegistry::registerListener( IReporterFactoryPtr const& factory ) {
  5867. m_listeners.push_back( factory );
  5868. }
  5869. IReporterRegistry::FactoryMap const& ReporterRegistry::getFactories() const {
  5870. return m_factories;
  5871. }
  5872. IReporterRegistry::Listeners const& ReporterRegistry::getListeners() const {
  5873. return m_listeners;
  5874. }
  5875. }
  5876. // end catch_reporter_registry.cpp
  5877. // start catch_result_type.cpp
  5878. namespace Catch {
  5879. bool isOk( ResultWas::OfType resultType ) {
  5880. return ( resultType & ResultWas::FailureBit ) == 0;
  5881. }
  5882. bool isJustInfo( int flags ) {
  5883. return flags == ResultWas::Info;
  5884. }
  5885. ResultDisposition::Flags operator | ( ResultDisposition::Flags lhs, ResultDisposition::Flags rhs ) {
  5886. return static_cast<ResultDisposition::Flags>( static_cast<int>( lhs ) | static_cast<int>( rhs ) );
  5887. }
  5888. bool shouldContinueOnFailure( int flags ) { return ( flags & ResultDisposition::ContinueOnFailure ) != 0; }
  5889. bool isFalseTest( int flags ) { return ( flags & ResultDisposition::FalseTest ) != 0; }
  5890. bool shouldSuppressFailure( int flags ) { return ( flags & ResultDisposition::SuppressFail ) != 0; }
  5891. } // end namespace Catch
  5892. // end catch_result_type.cpp
  5893. // start catch_run_context.cpp
  5894. // start catch_run_context.h
  5895. #include <string>
  5896. namespace Catch {
  5897. struct IMutableContext;
  5898. class StreamRedirect {
  5899. public:
  5900. StreamRedirect(std::ostream& stream, std::string& targetString);
  5901. ~StreamRedirect();
  5902. private:
  5903. std::ostream& m_stream;
  5904. std::streambuf* m_prevBuf;
  5905. std::ostringstream m_oss;
  5906. std::string& m_targetString;
  5907. };
  5908. // StdErr has two constituent streams in C++, std::cerr and std::clog
  5909. // This means that we need to redirect 2 streams into 1 to keep proper
  5910. // order of writes and cannot use StreamRedirect on its own
  5911. class StdErrRedirect {
  5912. public:
  5913. StdErrRedirect(std::string& targetString);
  5914. ~StdErrRedirect();
  5915. private:
  5916. std::streambuf* m_cerrBuf;
  5917. std::streambuf* m_clogBuf;
  5918. std::ostringstream m_oss;
  5919. std::string& m_targetString;
  5920. };
  5921. ///////////////////////////////////////////////////////////////////////////
  5922. class RunContext : public IResultCapture, public IRunner {
  5923. public:
  5924. RunContext( RunContext const& ) = delete;
  5925. RunContext& operator =( RunContext const& ) = delete;
  5926. explicit RunContext(IConfigPtr const& _config, IStreamingReporterPtr&& reporter);
  5927. virtual ~RunContext();
  5928. void testGroupStarting(std::string const& testSpec, std::size_t groupIndex, std::size_t groupsCount);
  5929. void testGroupEnded(std::string const& testSpec, Totals const& totals, std::size_t groupIndex, std::size_t groupsCount);
  5930. Totals runTest(TestCase const& testCase);
  5931. IConfigPtr config() const;
  5932. IStreamingReporter& reporter() const;
  5933. private: // IResultCapture
  5934. void assertionStarting(AssertionInfo const& info) override;
  5935. void assertionEnded(AssertionResult const& result) override;
  5936. bool sectionStarted( SectionInfo const& sectionInfo, Counts& assertions ) override;
  5937. bool testForMissingAssertions(Counts& assertions);
  5938. void sectionEnded(SectionEndInfo const& endInfo) override;
  5939. void sectionEndedEarly(SectionEndInfo const& endInfo) override;
  5940. void benchmarkStarting( BenchmarkInfo const& info ) override;
  5941. void benchmarkEnded( BenchmarkStats const& stats ) override;
  5942. void pushScopedMessage(MessageInfo const& message) override;
  5943. void popScopedMessage(MessageInfo const& message) override;
  5944. std::string getCurrentTestName() const override;
  5945. const AssertionResult* getLastResult() const override;
  5946. void exceptionEarlyReported() override;
  5947. void handleFatalErrorCondition( StringRef message ) override;
  5948. bool lastAssertionPassed() override;
  5949. void assertionPassed() override;
  5950. void assertionRun() override;
  5951. public:
  5952. // !TBD We need to do this another way!
  5953. bool aborting() const override;
  5954. private:
  5955. void runCurrentTest(std::string& redirectedCout, std::string& redirectedCerr);
  5956. void invokeActiveTestCase();
  5957. private:
  5958. void handleUnfinishedSections();
  5959. TestRunInfo m_runInfo;
  5960. IMutableContext& m_context;
  5961. TestCase const* m_activeTestCase = nullptr;
  5962. ITracker* m_testCaseTracker;
  5963. Option<AssertionResult> m_lastResult;
  5964. IConfigPtr m_config;
  5965. Totals m_totals;
  5966. IStreamingReporterPtr m_reporter;
  5967. std::vector<MessageInfo> m_messages;
  5968. AssertionInfo m_lastAssertionInfo;
  5969. std::vector<SectionEndInfo> m_unfinishedSections;
  5970. std::vector<ITracker*> m_activeSections;
  5971. TrackerContext m_trackerContext;
  5972. std::size_t m_prevPassed = 0;
  5973. bool m_shouldReportUnexpected = true;
  5974. };
  5975. IResultCapture& getResultCapture();
  5976. } // end namespace Catch
  5977. // end catch_run_context.h
  5978. #include <cassert>
  5979. #include <algorithm>
  5980. namespace Catch {
  5981. StreamRedirect::StreamRedirect(std::ostream& stream, std::string& targetString)
  5982. : m_stream(stream),
  5983. m_prevBuf(stream.rdbuf()),
  5984. m_targetString(targetString) {
  5985. stream.rdbuf(m_oss.rdbuf());
  5986. }
  5987. StreamRedirect::~StreamRedirect() {
  5988. m_targetString += m_oss.str();
  5989. m_stream.rdbuf(m_prevBuf);
  5990. }
  5991. StdErrRedirect::StdErrRedirect(std::string & targetString)
  5992. :m_cerrBuf(cerr().rdbuf()), m_clogBuf(clog().rdbuf()),
  5993. m_targetString(targetString) {
  5994. cerr().rdbuf(m_oss.rdbuf());
  5995. clog().rdbuf(m_oss.rdbuf());
  5996. }
  5997. StdErrRedirect::~StdErrRedirect() {
  5998. m_targetString += m_oss.str();
  5999. cerr().rdbuf(m_cerrBuf);
  6000. clog().rdbuf(m_clogBuf);
  6001. }
  6002. RunContext::RunContext(IConfigPtr const& _config, IStreamingReporterPtr&& reporter)
  6003. : m_runInfo(_config->name()),
  6004. m_context(getCurrentMutableContext()),
  6005. m_config(_config),
  6006. m_reporter(std::move(reporter)),
  6007. m_lastAssertionInfo{ "", SourceLineInfo("",0), "", ResultDisposition::Normal }
  6008. {
  6009. m_context.setRunner(this);
  6010. m_context.setConfig(m_config);
  6011. m_context.setResultCapture(this);
  6012. m_reporter->testRunStarting(m_runInfo);
  6013. }
  6014. RunContext::~RunContext() {
  6015. m_reporter->testRunEnded(TestRunStats(m_runInfo, m_totals, aborting()));
  6016. }
  6017. void RunContext::testGroupStarting(std::string const& testSpec, std::size_t groupIndex, std::size_t groupsCount) {
  6018. m_reporter->testGroupStarting(GroupInfo(testSpec, groupIndex, groupsCount));
  6019. }
  6020. void RunContext::testGroupEnded(std::string const& testSpec, Totals const& totals, std::size_t groupIndex, std::size_t groupsCount) {
  6021. m_reporter->testGroupEnded(TestGroupStats(GroupInfo(testSpec, groupIndex, groupsCount), totals, aborting()));
  6022. }
  6023. Totals RunContext::runTest(TestCase const& testCase) {
  6024. Totals prevTotals = m_totals;
  6025. std::string redirectedCout;
  6026. std::string redirectedCerr;
  6027. TestCaseInfo testInfo = testCase.getTestCaseInfo();
  6028. m_reporter->testCaseStarting(testInfo);
  6029. m_activeTestCase = &testCase;
  6030. ITracker& rootTracker = m_trackerContext.startRun();
  6031. assert(rootTracker.isSectionTracker());
  6032. static_cast<SectionTracker&>(rootTracker).addInitialFilters(m_config->getSectionsToRun());
  6033. do {
  6034. m_trackerContext.startCycle();
  6035. m_testCaseTracker = &SectionTracker::acquire(m_trackerContext, TestCaseTracking::NameAndLocation(testInfo.name, testInfo.lineInfo));
  6036. runCurrentTest(redirectedCout, redirectedCerr);
  6037. } while (!m_testCaseTracker->isSuccessfullyCompleted() && !aborting());
  6038. Totals deltaTotals = m_totals.delta(prevTotals);
  6039. if (testInfo.expectedToFail() && deltaTotals.testCases.passed > 0) {
  6040. deltaTotals.assertions.failed++;
  6041. deltaTotals.testCases.passed--;
  6042. deltaTotals.testCases.failed++;
  6043. }
  6044. m_totals.testCases += deltaTotals.testCases;
  6045. m_reporter->testCaseEnded(TestCaseStats(testInfo,
  6046. deltaTotals,
  6047. redirectedCout,
  6048. redirectedCerr,
  6049. aborting()));
  6050. m_activeTestCase = nullptr;
  6051. m_testCaseTracker = nullptr;
  6052. return deltaTotals;
  6053. }
  6054. IConfigPtr RunContext::config() const {
  6055. return m_config;
  6056. }
  6057. IStreamingReporter& RunContext::reporter() const {
  6058. return *m_reporter;
  6059. }
  6060. void RunContext::assertionStarting(AssertionInfo const& info) {
  6061. m_reporter->assertionStarting( info );
  6062. }
  6063. void RunContext::assertionEnded(AssertionResult const & result) {
  6064. if (result.getResultType() == ResultWas::Ok) {
  6065. m_totals.assertions.passed++;
  6066. } else if (!result.isOk()) {
  6067. if( m_activeTestCase->getTestCaseInfo().okToFail() )
  6068. m_totals.assertions.failedButOk++;
  6069. else
  6070. m_totals.assertions.failed++;
  6071. }
  6072. // We have no use for the return value (whether messages should be cleared), because messages were made scoped
  6073. // and should be let to clear themselves out.
  6074. static_cast<void>(m_reporter->assertionEnded(AssertionStats(result, m_messages, m_totals)));
  6075. // Reset working state
  6076. m_lastAssertionInfo = { "", m_lastAssertionInfo.lineInfo, "{Unknown expression after the reported line}", m_lastAssertionInfo.resultDisposition };
  6077. m_lastResult = result;
  6078. }
  6079. bool RunContext::sectionStarted(SectionInfo const & sectionInfo, Counts & assertions) {
  6080. ITracker& sectionTracker = SectionTracker::acquire(m_trackerContext, TestCaseTracking::NameAndLocation(sectionInfo.name, sectionInfo.lineInfo));
  6081. if (!sectionTracker.isOpen())
  6082. return false;
  6083. m_activeSections.push_back(&sectionTracker);
  6084. m_lastAssertionInfo.lineInfo = sectionInfo.lineInfo;
  6085. m_reporter->sectionStarting(sectionInfo);
  6086. assertions = m_totals.assertions;
  6087. return true;
  6088. }
  6089. bool RunContext::testForMissingAssertions(Counts& assertions) {
  6090. if (assertions.total() != 0)
  6091. return false;
  6092. if (!m_config->warnAboutMissingAssertions())
  6093. return false;
  6094. if (m_trackerContext.currentTracker().hasChildren())
  6095. return false;
  6096. m_totals.assertions.failed++;
  6097. assertions.failed++;
  6098. return true;
  6099. }
  6100. void RunContext::sectionEnded(SectionEndInfo const & endInfo) {
  6101. Counts assertions = m_totals.assertions - endInfo.prevAssertions;
  6102. bool missingAssertions = testForMissingAssertions(assertions);
  6103. if (!m_activeSections.empty()) {
  6104. m_activeSections.back()->close();
  6105. m_activeSections.pop_back();
  6106. }
  6107. m_reporter->sectionEnded(SectionStats(endInfo.sectionInfo, assertions, endInfo.durationInSeconds, missingAssertions));
  6108. m_messages.clear();
  6109. }
  6110. void RunContext::sectionEndedEarly(SectionEndInfo const & endInfo) {
  6111. if (m_unfinishedSections.empty())
  6112. m_activeSections.back()->fail();
  6113. else
  6114. m_activeSections.back()->close();
  6115. m_activeSections.pop_back();
  6116. m_unfinishedSections.push_back(endInfo);
  6117. }
  6118. void RunContext::benchmarkStarting( BenchmarkInfo const& info ) {
  6119. m_reporter->benchmarkStarting( info );
  6120. }
  6121. void RunContext::benchmarkEnded( BenchmarkStats const& stats ) {
  6122. m_reporter->benchmarkEnded( stats );
  6123. }
  6124. void RunContext::pushScopedMessage(MessageInfo const & message) {
  6125. m_messages.push_back(message);
  6126. }
  6127. void RunContext::popScopedMessage(MessageInfo const & message) {
  6128. m_messages.erase(std::remove(m_messages.begin(), m_messages.end(), message), m_messages.end());
  6129. }
  6130. std::string RunContext::getCurrentTestName() const {
  6131. return m_activeTestCase
  6132. ? m_activeTestCase->getTestCaseInfo().name
  6133. : std::string();
  6134. }
  6135. const AssertionResult * RunContext::getLastResult() const {
  6136. return &(*m_lastResult);
  6137. }
  6138. void RunContext::exceptionEarlyReported() {
  6139. m_shouldReportUnexpected = false;
  6140. }
  6141. void RunContext::handleFatalErrorCondition( StringRef message ) {
  6142. // First notify reporter that bad things happened
  6143. m_reporter->fatalErrorEncountered(message);
  6144. // Don't rebuild the result -- the stringification itself can cause more fatal errors
  6145. // Instead, fake a result data.
  6146. AssertionResultData tempResult( ResultWas::FatalErrorCondition, { false } );
  6147. tempResult.message = message;
  6148. AssertionResult result(m_lastAssertionInfo, tempResult);
  6149. getResultCapture().assertionEnded(result);
  6150. handleUnfinishedSections();
  6151. // Recreate section for test case (as we will lose the one that was in scope)
  6152. auto const& testCaseInfo = m_activeTestCase->getTestCaseInfo();
  6153. SectionInfo testCaseSection(testCaseInfo.lineInfo, testCaseInfo.name, testCaseInfo.description);
  6154. Counts assertions;
  6155. assertions.failed = 1;
  6156. SectionStats testCaseSectionStats(testCaseSection, assertions, 0, false);
  6157. m_reporter->sectionEnded(testCaseSectionStats);
  6158. auto const& testInfo = m_activeTestCase->getTestCaseInfo();
  6159. Totals deltaTotals;
  6160. deltaTotals.testCases.failed = 1;
  6161. deltaTotals.assertions.failed = 1;
  6162. m_reporter->testCaseEnded(TestCaseStats(testInfo,
  6163. deltaTotals,
  6164. std::string(),
  6165. std::string(),
  6166. false));
  6167. m_totals.testCases.failed++;
  6168. testGroupEnded(std::string(), m_totals, 1, 1);
  6169. m_reporter->testRunEnded(TestRunStats(m_runInfo, m_totals, false));
  6170. }
  6171. bool RunContext::lastAssertionPassed() {
  6172. return m_totals.assertions.passed == (m_prevPassed + 1);
  6173. }
  6174. void RunContext::assertionPassed() {
  6175. ++m_totals.assertions.passed;
  6176. m_lastAssertionInfo.capturedExpression = "{Unknown expression after the reported line}";
  6177. m_lastAssertionInfo.macroName = "";
  6178. }
  6179. void RunContext::assertionRun() {
  6180. m_prevPassed = m_totals.assertions.passed;
  6181. }
  6182. bool RunContext::aborting() const {
  6183. return m_totals.assertions.failed == static_cast<std::size_t>(m_config->abortAfter());
  6184. }
  6185. void RunContext::runCurrentTest(std::string & redirectedCout, std::string & redirectedCerr) {
  6186. auto const& testCaseInfo = m_activeTestCase->getTestCaseInfo();
  6187. SectionInfo testCaseSection(testCaseInfo.lineInfo, testCaseInfo.name, testCaseInfo.description);
  6188. m_reporter->sectionStarting(testCaseSection);
  6189. Counts prevAssertions = m_totals.assertions;
  6190. double duration = 0;
  6191. m_shouldReportUnexpected = true;
  6192. try {
  6193. m_lastAssertionInfo = { "TEST_CASE", testCaseInfo.lineInfo, "", ResultDisposition::Normal };
  6194. seedRng(*m_config);
  6195. Timer timer;
  6196. timer.start();
  6197. if (m_reporter->getPreferences().shouldRedirectStdOut) {
  6198. StreamRedirect coutRedir(cout(), redirectedCout);
  6199. StdErrRedirect errRedir(redirectedCerr);
  6200. invokeActiveTestCase();
  6201. } else {
  6202. invokeActiveTestCase();
  6203. }
  6204. duration = timer.getElapsedSeconds();
  6205. } catch (TestFailureException&) {
  6206. // This just means the test was aborted due to failure
  6207. } catch (...) {
  6208. // Under CATCH_CONFIG_FAST_COMPILE, unexpected exceptions under REQUIRE assertions
  6209. // are reported without translation at the point of origin.
  6210. if (m_shouldReportUnexpected) {
  6211. AssertionHandler
  6212. ( m_lastAssertionInfo.macroName,
  6213. m_lastAssertionInfo.lineInfo,
  6214. m_lastAssertionInfo.capturedExpression,
  6215. m_lastAssertionInfo.resultDisposition ).useActiveException();
  6216. }
  6217. }
  6218. m_testCaseTracker->close();
  6219. handleUnfinishedSections();
  6220. m_messages.clear();
  6221. Counts assertions = m_totals.assertions - prevAssertions;
  6222. bool missingAssertions = testForMissingAssertions(assertions);
  6223. SectionStats testCaseSectionStats(testCaseSection, assertions, duration, missingAssertions);
  6224. m_reporter->sectionEnded(testCaseSectionStats);
  6225. }
  6226. void RunContext::invokeActiveTestCase() {
  6227. FatalConditionHandler fatalConditionHandler; // Handle signals
  6228. m_activeTestCase->invoke();
  6229. fatalConditionHandler.reset();
  6230. }
  6231. void RunContext::handleUnfinishedSections() {
  6232. // If sections ended prematurely due to an exception we stored their
  6233. // infos here so we can tear them down outside the unwind process.
  6234. for (auto it = m_unfinishedSections.rbegin(),
  6235. itEnd = m_unfinishedSections.rend();
  6236. it != itEnd;
  6237. ++it)
  6238. sectionEnded(*it);
  6239. m_unfinishedSections.clear();
  6240. }
  6241. IResultCapture& getResultCapture() {
  6242. if (auto* capture = getCurrentContext().getResultCapture())
  6243. return *capture;
  6244. else
  6245. CATCH_INTERNAL_ERROR("No result capture instance");
  6246. }
  6247. }
  6248. // end catch_run_context.cpp
  6249. // start catch_section.cpp
  6250. namespace Catch {
  6251. Section::Section( SectionInfo const& info )
  6252. : m_info( info ),
  6253. m_sectionIncluded( getResultCapture().sectionStarted( m_info, m_assertions ) )
  6254. {
  6255. m_timer.start();
  6256. }
  6257. #if defined(_MSC_VER)
  6258. #pragma warning(push)
  6259. #pragma warning(disable:4996) // std::uncaught_exception is deprecated in C++17
  6260. #endif
  6261. Section::~Section() {
  6262. if( m_sectionIncluded ) {
  6263. SectionEndInfo endInfo( m_info, m_assertions, m_timer.getElapsedSeconds() );
  6264. if( std::uncaught_exception() )
  6265. getResultCapture().sectionEndedEarly( endInfo );
  6266. else
  6267. getResultCapture().sectionEnded( endInfo );
  6268. }
  6269. }
  6270. #if defined(_MSC_VER)
  6271. #pragma warning(pop)
  6272. #endif
  6273. // This indicates whether the section should be executed or not
  6274. Section::operator bool() const {
  6275. return m_sectionIncluded;
  6276. }
  6277. } // end namespace Catch
  6278. // end catch_section.cpp
  6279. // start catch_section_info.cpp
  6280. namespace Catch {
  6281. SectionInfo::SectionInfo
  6282. ( SourceLineInfo const& _lineInfo,
  6283. std::string const& _name,
  6284. std::string const& _description )
  6285. : name( _name ),
  6286. description( _description ),
  6287. lineInfo( _lineInfo )
  6288. {}
  6289. SectionEndInfo::SectionEndInfo( SectionInfo const& _sectionInfo, Counts const& _prevAssertions, double _durationInSeconds )
  6290. : sectionInfo( _sectionInfo ), prevAssertions( _prevAssertions ), durationInSeconds( _durationInSeconds )
  6291. {}
  6292. } // end namespace Catch
  6293. // end catch_section_info.cpp
  6294. // start catch_session.cpp
  6295. // start catch_session.h
  6296. #include <memory>
  6297. namespace Catch {
  6298. class Session : NonCopyable {
  6299. public:
  6300. Session();
  6301. ~Session() override;
  6302. void showHelp() const;
  6303. void libIdentify();
  6304. int applyCommandLine( int argc, char* argv[] );
  6305. void useConfigData( ConfigData const& configData );
  6306. int run( int argc, char* argv[] );
  6307. #if defined(WIN32) && defined(UNICODE)
  6308. int run( int argc, wchar_t* const argv[] );
  6309. #endif
  6310. int run();
  6311. clara::Parser const& cli() const;
  6312. void cli( clara::Parser const& newParser );
  6313. ConfigData& configData();
  6314. Config& config();
  6315. private:
  6316. int runInternal();
  6317. clara::Parser m_cli;
  6318. ConfigData m_configData;
  6319. std::shared_ptr<Config> m_config;
  6320. };
  6321. } // end namespace Catch
  6322. // end catch_session.h
  6323. // start catch_version.h
  6324. #include <iosfwd>
  6325. namespace Catch {
  6326. // Versioning information
  6327. struct Version {
  6328. Version( Version const& ) = delete;
  6329. Version& operator=( Version const& ) = delete;
  6330. Version( unsigned int _majorVersion,
  6331. unsigned int _minorVersion,
  6332. unsigned int _patchNumber,
  6333. char const * const _branchName,
  6334. unsigned int _buildNumber );
  6335. unsigned int const majorVersion;
  6336. unsigned int const minorVersion;
  6337. unsigned int const patchNumber;
  6338. // buildNumber is only used if branchName is not null
  6339. char const * const branchName;
  6340. unsigned int const buildNumber;
  6341. friend std::ostream& operator << ( std::ostream& os, Version const& version );
  6342. };
  6343. Version const& libraryVersion();
  6344. }
  6345. // end catch_version.h
  6346. #include <cstdlib>
  6347. #include <iomanip>
  6348. namespace {
  6349. const int MaxExitCode = 255;
  6350. using Catch::IStreamingReporterPtr;
  6351. using Catch::IConfigPtr;
  6352. using Catch::Config;
  6353. IStreamingReporterPtr createReporter(std::string const& reporterName, IConfigPtr const& config) {
  6354. auto reporter = Catch::getRegistryHub().getReporterRegistry().create(reporterName, config);
  6355. CATCH_ENFORCE(reporter, "No reporter registered with name: '" << reporterName << "'");
  6356. return reporter;
  6357. }
  6358. #ifndef CATCH_CONFIG_DEFAULT_REPORTER
  6359. #define CATCH_CONFIG_DEFAULT_REPORTER "console"
  6360. #endif
  6361. IStreamingReporterPtr makeReporter(std::shared_ptr<Config> const& config) {
  6362. auto const& reporterNames = config->getReporterNames();
  6363. if (reporterNames.empty())
  6364. return createReporter(CATCH_CONFIG_DEFAULT_REPORTER, config);
  6365. IStreamingReporterPtr reporter;
  6366. for (auto const& name : reporterNames)
  6367. addReporter(reporter, createReporter(name, config));
  6368. return reporter;
  6369. }
  6370. #undef CATCH_CONFIG_DEFAULT_REPORTER
  6371. void addListeners(IStreamingReporterPtr& reporters, IConfigPtr const& config) {
  6372. auto const& listeners = Catch::getRegistryHub().getReporterRegistry().getListeners();
  6373. for (auto const& listener : listeners)
  6374. addReporter(reporters, listener->create(Catch::ReporterConfig(config)));
  6375. }
  6376. Catch::Totals runTests(std::shared_ptr<Config> const& config) {
  6377. using namespace Catch;
  6378. IStreamingReporterPtr reporter = makeReporter(config);
  6379. addListeners(reporter, config);
  6380. RunContext context(config, std::move(reporter));
  6381. Totals totals;
  6382. context.testGroupStarting(config->name(), 1, 1);
  6383. TestSpec testSpec = config->testSpec();
  6384. if (!testSpec.hasFilters())
  6385. testSpec = TestSpecParser(ITagAliasRegistry::get()).parse("~[.]").testSpec(); // All not hidden tests
  6386. auto const& allTestCases = getAllTestCasesSorted(*config);
  6387. for (auto const& testCase : allTestCases) {
  6388. if (!context.aborting() && matchTest(testCase, testSpec, *config))
  6389. totals += context.runTest(testCase);
  6390. else
  6391. context.reporter().skipTest(testCase);
  6392. }
  6393. context.testGroupEnded(config->name(), totals, 1, 1);
  6394. return totals;
  6395. }
  6396. void applyFilenamesAsTags(Catch::IConfig const& config) {
  6397. using namespace Catch;
  6398. auto& tests = const_cast<std::vector<TestCase>&>(getAllTestCasesSorted(config));
  6399. for (auto& testCase : tests) {
  6400. auto tags = testCase.tags;
  6401. std::string filename = testCase.lineInfo.file;
  6402. auto lastSlash = filename.find_last_of("\\/");
  6403. if (lastSlash != std::string::npos) {
  6404. filename.erase(0, lastSlash);
  6405. filename[0] = '#';
  6406. }
  6407. auto lastDot = filename.find_last_of('.');
  6408. if (lastDot != std::string::npos) {
  6409. filename.erase(lastDot);
  6410. }
  6411. tags.push_back(std::move(filename));
  6412. setTags(testCase, tags);
  6413. }
  6414. }
  6415. }
  6416. namespace Catch {
  6417. Session::Session() {
  6418. static bool alreadyInstantiated = false;
  6419. if( alreadyInstantiated )
  6420. CATCH_INTERNAL_ERROR( "Only one instance of Catch::Session can ever be used" );
  6421. alreadyInstantiated = true;
  6422. m_cli = makeCommandLineParser( m_configData );
  6423. }
  6424. Session::~Session() {
  6425. Catch::cleanUp();
  6426. }
  6427. void Session::showHelp() const {
  6428. Catch::cout()
  6429. << "\nCatch v" << libraryVersion() << "\n"
  6430. << m_cli << std::endl
  6431. << "For more detailed usage please see the project docs\n" << std::endl;
  6432. }
  6433. void Session::libIdentify() {
  6434. Catch::cout()
  6435. << std::left << std::setw(16) << "description: " << "A Catch test executable\n"
  6436. << std::left << std::setw(16) << "category: " << "testframework\n"
  6437. << std::left << std::setw(16) << "framework: " << "Catch Test\n"
  6438. << std::left << std::setw(16) << "version: " << libraryVersion() << std::endl;
  6439. }
  6440. int Session::applyCommandLine( int argc, char* argv[] ) {
  6441. auto result = m_cli.parse( clara::Args( argc, argv ) );
  6442. if( !result ) {
  6443. Catch::cerr()
  6444. << Colour( Colour::Red )
  6445. << "\nError(s) in input:\n"
  6446. << Column( result.errorMessage() ).indent( 2 )
  6447. << "\n\n";
  6448. Catch::cerr() << "Run with -? for usage\n" << std::endl;
  6449. return MaxExitCode;
  6450. }
  6451. if( m_configData.showHelp )
  6452. showHelp();
  6453. if( m_configData.libIdentify )
  6454. libIdentify();
  6455. m_config.reset();
  6456. return 0;
  6457. }
  6458. void Session::useConfigData( ConfigData const& configData ) {
  6459. m_configData = configData;
  6460. m_config.reset();
  6461. }
  6462. int Session::run( int argc, char* argv[] ) {
  6463. const auto& exceptions = getRegistryHub().getStartupExceptionRegistry().getExceptions();
  6464. if ( !exceptions.empty() ) {
  6465. Catch::cerr() << "Errors occured during startup!" << '\n';
  6466. // iterate over all exceptions and notify user
  6467. for ( const auto& ex_ptr : exceptions ) {
  6468. try {
  6469. std::rethrow_exception(ex_ptr);
  6470. } catch ( std::exception const& ex ) {
  6471. Catch::cerr() << ex.what() << '\n';
  6472. }
  6473. }
  6474. return 1;
  6475. }
  6476. int returnCode = applyCommandLine( argc, argv );
  6477. if( returnCode == 0 )
  6478. returnCode = run();
  6479. return returnCode;
  6480. }
  6481. #if defined(WIN32) && defined(UNICODE)
  6482. int Session::run( int argc, wchar_t* const argv[] ) {
  6483. char **utf8Argv = new char *[ argc ];
  6484. for ( int i = 0; i < argc; ++i ) {
  6485. int bufSize = WideCharToMultiByte( CP_UTF8, 0, argv[i], -1, NULL, 0, NULL, NULL );
  6486. utf8Argv[ i ] = new char[ bufSize ];
  6487. WideCharToMultiByte( CP_UTF8, 0, argv[i], -1, utf8Argv[i], bufSize, NULL, NULL );
  6488. }
  6489. int returnCode = run( argc, utf8Argv );
  6490. for ( int i = 0; i < argc; ++i )
  6491. delete [] utf8Argv[ i ];
  6492. delete [] utf8Argv;
  6493. return returnCode;
  6494. }
  6495. #endif
  6496. int Session::run() {
  6497. if( ( m_configData.waitForKeypress & WaitForKeypress::BeforeStart ) != 0 ) {
  6498. Catch::cout() << "...waiting for enter/ return before starting" << std::endl;
  6499. static_cast<void>(std::getchar());
  6500. }
  6501. int exitCode = runInternal();
  6502. if( ( m_configData.waitForKeypress & WaitForKeypress::BeforeExit ) != 0 ) {
  6503. Catch::cout() << "...waiting for enter/ return before exiting, with code: " << exitCode << std::endl;
  6504. static_cast<void>(std::getchar());
  6505. }
  6506. return exitCode;
  6507. }
  6508. clara::Parser const& Session::cli() const {
  6509. return m_cli;
  6510. }
  6511. void Session::cli( clara::Parser const& newParser ) {
  6512. m_cli = newParser;
  6513. }
  6514. ConfigData& Session::configData() {
  6515. return m_configData;
  6516. }
  6517. Config& Session::config() {
  6518. if( !m_config )
  6519. m_config = std::make_shared<Config>( m_configData );
  6520. return *m_config;
  6521. }
  6522. int Session::runInternal() {
  6523. if( m_configData.showHelp || m_configData.libIdentify )
  6524. return 0;
  6525. try
  6526. {
  6527. config(); // Force config to be constructed
  6528. seedRng( *m_config );
  6529. if( m_configData.filenamesAsTags )
  6530. applyFilenamesAsTags( *m_config );
  6531. // Handle list request
  6532. if( Option<std::size_t> listed = list( config() ) )
  6533. return static_cast<int>( *listed );
  6534. return (std::min)( MaxExitCode, static_cast<int>( runTests( m_config ).assertions.failed ) );
  6535. }
  6536. catch( std::exception& ex ) {
  6537. Catch::cerr() << ex.what() << std::endl;
  6538. return MaxExitCode;
  6539. }
  6540. }
  6541. } // end namespace Catch
  6542. // end catch_session.cpp
  6543. // start catch_startup_exception_registry.cpp
  6544. namespace Catch {
  6545. void StartupExceptionRegistry::add( std::exception_ptr const& exception ) noexcept {
  6546. try {
  6547. m_exceptions.push_back(exception);
  6548. }
  6549. catch(...) {
  6550. // If we run out of memory during start-up there's really not a lot more we can do about it
  6551. std::terminate();
  6552. }
  6553. }
  6554. std::vector<std::exception_ptr> const& StartupExceptionRegistry::getExceptions() const noexcept {
  6555. return m_exceptions;
  6556. }
  6557. } // end namespace Catch
  6558. // end catch_startup_exception_registry.cpp
  6559. // start catch_stream.cpp
  6560. #include <stdexcept>
  6561. #include <cstdio>
  6562. #include <iostream>
  6563. namespace Catch {
  6564. template<typename WriterF, std::size_t bufferSize=256>
  6565. class StreamBufImpl : public StreamBufBase {
  6566. char data[bufferSize];
  6567. WriterF m_writer;
  6568. public:
  6569. StreamBufImpl() {
  6570. setp( data, data + sizeof(data) );
  6571. }
  6572. ~StreamBufImpl() noexcept {
  6573. StreamBufImpl::sync();
  6574. }
  6575. private:
  6576. int overflow( int c ) override {
  6577. sync();
  6578. if( c != EOF ) {
  6579. if( pbase() == epptr() )
  6580. m_writer( std::string( 1, static_cast<char>( c ) ) );
  6581. else
  6582. sputc( static_cast<char>( c ) );
  6583. }
  6584. return 0;
  6585. }
  6586. int sync() override {
  6587. if( pbase() != pptr() ) {
  6588. m_writer( std::string( pbase(), static_cast<std::string::size_type>( pptr() - pbase() ) ) );
  6589. setp( pbase(), epptr() );
  6590. }
  6591. return 0;
  6592. }
  6593. };
  6594. ///////////////////////////////////////////////////////////////////////////
  6595. Catch::IStream::~IStream() = default;
  6596. FileStream::FileStream( std::string const& filename ) {
  6597. m_ofs.open( filename.c_str() );
  6598. CATCH_ENFORCE( !m_ofs.fail(), "Unable to open file: '" << filename << "'" );
  6599. }
  6600. std::ostream& FileStream::stream() const {
  6601. return m_ofs;
  6602. }
  6603. struct OutputDebugWriter {
  6604. void operator()( std::string const&str ) {
  6605. writeToDebugConsole( str );
  6606. }
  6607. };
  6608. DebugOutStream::DebugOutStream()
  6609. : m_streamBuf( new StreamBufImpl<OutputDebugWriter>() ),
  6610. m_os( m_streamBuf.get() )
  6611. {}
  6612. std::ostream& DebugOutStream::stream() const {
  6613. return m_os;
  6614. }
  6615. // Store the streambuf from cout up-front because
  6616. // cout may get redirected when running tests
  6617. CoutStream::CoutStream()
  6618. : m_os( Catch::cout().rdbuf() )
  6619. {}
  6620. std::ostream& CoutStream::stream() const {
  6621. return m_os;
  6622. }
  6623. #ifndef CATCH_CONFIG_NOSTDOUT // If you #define this you must implement these functions
  6624. std::ostream& cout() {
  6625. return std::cout;
  6626. }
  6627. std::ostream& cerr() {
  6628. return std::cerr;
  6629. }
  6630. std::ostream& clog() {
  6631. return std::clog;
  6632. }
  6633. #endif
  6634. }
  6635. // end catch_stream.cpp
  6636. // start catch_streambuf.cpp
  6637. namespace Catch {
  6638. StreamBufBase::~StreamBufBase() = default;
  6639. }
  6640. // end catch_streambuf.cpp
  6641. // start catch_string_manip.cpp
  6642. #include <algorithm>
  6643. #include <ostream>
  6644. #include <cstring>
  6645. #include <cctype>
  6646. namespace Catch {
  6647. bool startsWith( std::string const& s, std::string const& prefix ) {
  6648. return s.size() >= prefix.size() && std::equal(prefix.begin(), prefix.end(), s.begin());
  6649. }
  6650. bool startsWith( std::string const& s, char prefix ) {
  6651. return !s.empty() && s[0] == prefix;
  6652. }
  6653. bool endsWith( std::string const& s, std::string const& suffix ) {
  6654. return s.size() >= suffix.size() && std::equal(suffix.rbegin(), suffix.rend(), s.rbegin());
  6655. }
  6656. bool endsWith( std::string const& s, char suffix ) {
  6657. return !s.empty() && s[s.size()-1] == suffix;
  6658. }
  6659. bool contains( std::string const& s, std::string const& infix ) {
  6660. return s.find( infix ) != std::string::npos;
  6661. }
  6662. char toLowerCh(char c) {
  6663. return static_cast<char>( std::tolower( c ) );
  6664. }
  6665. void toLowerInPlace( std::string& s ) {
  6666. std::transform( s.begin(), s.end(), s.begin(), toLowerCh );
  6667. }
  6668. std::string toLower( std::string const& s ) {
  6669. std::string lc = s;
  6670. toLowerInPlace( lc );
  6671. return lc;
  6672. }
  6673. std::string trim( std::string const& str ) {
  6674. static char const* whitespaceChars = "\n\r\t ";
  6675. std::string::size_type start = str.find_first_not_of( whitespaceChars );
  6676. std::string::size_type end = str.find_last_not_of( whitespaceChars );
  6677. return start != std::string::npos ? str.substr( start, 1+end-start ) : std::string();
  6678. }
  6679. bool replaceInPlace( std::string& str, std::string const& replaceThis, std::string const& withThis ) {
  6680. bool replaced = false;
  6681. std::size_t i = str.find( replaceThis );
  6682. while( i != std::string::npos ) {
  6683. replaced = true;
  6684. str = str.substr( 0, i ) + withThis + str.substr( i+replaceThis.size() );
  6685. if( i < str.size()-withThis.size() )
  6686. i = str.find( replaceThis, i+withThis.size() );
  6687. else
  6688. i = std::string::npos;
  6689. }
  6690. return replaced;
  6691. }
  6692. pluralise::pluralise( std::size_t count, std::string const& label )
  6693. : m_count( count ),
  6694. m_label( label )
  6695. {}
  6696. std::ostream& operator << ( std::ostream& os, pluralise const& pluraliser ) {
  6697. os << pluraliser.m_count << ' ' << pluraliser.m_label;
  6698. if( pluraliser.m_count != 1 )
  6699. os << 's';
  6700. return os;
  6701. }
  6702. }
  6703. // end catch_string_manip.cpp
  6704. // start catch_stringref.cpp
  6705. #if defined(__clang__)
  6706. # pragma clang diagnostic push
  6707. # pragma clang diagnostic ignored "-Wexit-time-destructors"
  6708. #endif
  6709. #include <ostream>
  6710. #include <cassert>
  6711. #include <cstring>
  6712. namespace Catch {
  6713. auto getEmptyStringRef() -> StringRef {
  6714. static StringRef s_emptyStringRef("");
  6715. return s_emptyStringRef;
  6716. }
  6717. StringRef::StringRef() noexcept
  6718. : StringRef( getEmptyStringRef() )
  6719. {}
  6720. StringRef::StringRef( StringRef const& other ) noexcept
  6721. : m_start( other.m_start ),
  6722. m_size( other.m_size )
  6723. {}
  6724. StringRef::StringRef( StringRef&& other ) noexcept
  6725. : m_start( other.m_start ),
  6726. m_size( other.m_size ),
  6727. m_data( other.m_data )
  6728. {
  6729. other.m_data = nullptr;
  6730. }
  6731. StringRef::StringRef( char const* rawChars ) noexcept
  6732. : m_start( rawChars ),
  6733. m_size( static_cast<size_type>( std::strlen( rawChars ) ) )
  6734. {
  6735. assert( rawChars != nullptr );
  6736. }
  6737. StringRef::StringRef( char const* rawChars, size_type size ) noexcept
  6738. : m_start( rawChars ),
  6739. m_size( size )
  6740. {
  6741. size_type rawSize = rawChars == nullptr ? 0 : static_cast<size_type>( std::strlen( rawChars ) );
  6742. if( rawSize < size )
  6743. m_size = rawSize;
  6744. }
  6745. StringRef::StringRef( std::string const& stdString ) noexcept
  6746. : m_start( stdString.c_str() ),
  6747. m_size( stdString.size() )
  6748. {}
  6749. StringRef::~StringRef() noexcept {
  6750. delete[] m_data;
  6751. }
  6752. auto StringRef::operator = ( StringRef other ) noexcept -> StringRef& {
  6753. swap( other );
  6754. return *this;
  6755. }
  6756. StringRef::operator std::string() const {
  6757. return std::string( m_start, m_size );
  6758. }
  6759. void StringRef::swap( StringRef& other ) noexcept {
  6760. std::swap( m_start, other.m_start );
  6761. std::swap( m_size, other.m_size );
  6762. std::swap( m_data, other.m_data );
  6763. }
  6764. auto StringRef::c_str() const -> char const* {
  6765. if( isSubstring() )
  6766. const_cast<StringRef*>( this )->takeOwnership();
  6767. return m_start;
  6768. }
  6769. auto StringRef::data() const noexcept -> char const* {
  6770. return m_start;
  6771. }
  6772. auto StringRef::isOwned() const noexcept -> bool {
  6773. return m_data != nullptr;
  6774. }
  6775. auto StringRef::isSubstring() const noexcept -> bool {
  6776. return m_start[m_size] != '\0';
  6777. }
  6778. void StringRef::takeOwnership() {
  6779. if( !isOwned() ) {
  6780. m_data = new char[m_size+1];
  6781. memcpy( m_data, m_start, m_size );
  6782. m_data[m_size] = '\0';
  6783. m_start = m_data;
  6784. }
  6785. }
  6786. auto StringRef::substr( size_type start, size_type size ) const noexcept -> StringRef {
  6787. if( start < m_size )
  6788. return StringRef( m_start+start, size );
  6789. else
  6790. return StringRef();
  6791. }
  6792. auto StringRef::operator == ( StringRef const& other ) const noexcept -> bool {
  6793. return
  6794. size() == other.size() &&
  6795. (std::strncmp( m_start, other.m_start, size() ) == 0);
  6796. }
  6797. auto StringRef::operator != ( StringRef const& other ) const noexcept -> bool {
  6798. return !operator==( other );
  6799. }
  6800. auto StringRef::operator[](size_type index) const noexcept -> char {
  6801. return m_start[index];
  6802. }
  6803. auto StringRef::empty() const noexcept -> bool {
  6804. return m_size == 0;
  6805. }
  6806. auto StringRef::size() const noexcept -> size_type {
  6807. return m_size;
  6808. }
  6809. auto StringRef::numberOfCharacters() const noexcept -> size_type {
  6810. size_type noChars = m_size;
  6811. // Make adjustments for uft encodings
  6812. for( size_type i=0; i < m_size; ++i ) {
  6813. char c = m_start[i];
  6814. if( ( c & 0b11000000 ) == 0b11000000 ) {
  6815. if( ( c & 0b11100000 ) == 0b11000000 )
  6816. noChars--;
  6817. else if( ( c & 0b11110000 ) == 0b11100000 )
  6818. noChars-=2;
  6819. else if( ( c & 0b11111000 ) == 0b11110000 )
  6820. noChars-=3;
  6821. }
  6822. }
  6823. return noChars;
  6824. }
  6825. auto operator + ( StringRef const& lhs, StringRef const& rhs ) -> std::string {
  6826. std::string str;
  6827. str.reserve( lhs.size() + rhs.size() );
  6828. str += lhs;
  6829. str += rhs;
  6830. return str;
  6831. }
  6832. auto operator + ( StringRef const& lhs, const char* rhs ) -> std::string {
  6833. return std::string( lhs ) + std::string( rhs );
  6834. }
  6835. auto operator + ( char const* lhs, StringRef const& rhs ) -> std::string {
  6836. return std::string( lhs ) + std::string( rhs );
  6837. }
  6838. auto operator << ( std::ostream& os, StringRef const& str ) -> std::ostream& {
  6839. return os << str.c_str();
  6840. }
  6841. } // namespace Catch
  6842. #if defined(__clang__)
  6843. # pragma clang diagnostic pop
  6844. #endif
  6845. // end catch_stringref.cpp
  6846. // start catch_tag_alias.cpp
  6847. namespace Catch {
  6848. TagAlias::TagAlias(std::string const & _tag, SourceLineInfo _lineInfo): tag(_tag), lineInfo(_lineInfo) {}
  6849. }
  6850. // end catch_tag_alias.cpp
  6851. // start catch_tag_alias_autoregistrar.cpp
  6852. namespace Catch {
  6853. RegistrarForTagAliases::RegistrarForTagAliases(char const* alias, char const* tag, SourceLineInfo const& lineInfo) {
  6854. try {
  6855. getMutableRegistryHub().registerTagAlias(alias, tag, lineInfo);
  6856. } catch (...) {
  6857. // Do not throw when constructing global objects, instead register the exception to be processed later
  6858. getMutableRegistryHub().registerStartupException();
  6859. }
  6860. }
  6861. }
  6862. // end catch_tag_alias_autoregistrar.cpp
  6863. // start catch_tag_alias_registry.cpp
  6864. namespace Catch {
  6865. TagAliasRegistry::~TagAliasRegistry() {}
  6866. TagAlias const* TagAliasRegistry::find( std::string const& alias ) const {
  6867. auto it = m_registry.find( alias );
  6868. if( it != m_registry.end() )
  6869. return &(it->second);
  6870. else
  6871. return nullptr;
  6872. }
  6873. std::string TagAliasRegistry::expandAliases( std::string const& unexpandedTestSpec ) const {
  6874. std::string expandedTestSpec = unexpandedTestSpec;
  6875. for( auto const& registryKvp : m_registry ) {
  6876. std::size_t pos = expandedTestSpec.find( registryKvp.first );
  6877. if( pos != std::string::npos ) {
  6878. expandedTestSpec = expandedTestSpec.substr( 0, pos ) +
  6879. registryKvp.second.tag +
  6880. expandedTestSpec.substr( pos + registryKvp.first.size() );
  6881. }
  6882. }
  6883. return expandedTestSpec;
  6884. }
  6885. void TagAliasRegistry::add( std::string const& alias, std::string const& tag, SourceLineInfo const& lineInfo ) {
  6886. CATCH_ENFORCE( startsWith(alias, "[@") && endsWith(alias, ']'),
  6887. "error: tag alias, '" << alias << "' is not of the form [@alias name].\n" << lineInfo );
  6888. CATCH_ENFORCE( m_registry.insert(std::make_pair(alias, TagAlias(tag, lineInfo))).second,
  6889. "error: tag alias, '" << alias << "' already registered.\n"
  6890. << "\tFirst seen at: " << find(alias)->lineInfo << "\n"
  6891. << "\tRedefined at: " << lineInfo );
  6892. }
  6893. ITagAliasRegistry::~ITagAliasRegistry() {}
  6894. ITagAliasRegistry const& ITagAliasRegistry::get() {
  6895. return getRegistryHub().getTagAliasRegistry();
  6896. }
  6897. } // end namespace Catch
  6898. // end catch_tag_alias_registry.cpp
  6899. // start catch_test_case_info.cpp
  6900. #include <cctype>
  6901. #include <exception>
  6902. #include <algorithm>
  6903. namespace Catch {
  6904. TestCaseInfo::SpecialProperties parseSpecialTag( std::string const& tag ) {
  6905. if( startsWith( tag, '.' ) ||
  6906. tag == "!hide" )
  6907. return TestCaseInfo::IsHidden;
  6908. else if( tag == "!throws" )
  6909. return TestCaseInfo::Throws;
  6910. else if( tag == "!shouldfail" )
  6911. return TestCaseInfo::ShouldFail;
  6912. else if( tag == "!mayfail" )
  6913. return TestCaseInfo::MayFail;
  6914. else if( tag == "!nonportable" )
  6915. return TestCaseInfo::NonPortable;
  6916. else if( tag == "!benchmark" )
  6917. return static_cast<TestCaseInfo::SpecialProperties>( TestCaseInfo::Benchmark | TestCaseInfo::IsHidden );
  6918. else
  6919. return TestCaseInfo::None;
  6920. }
  6921. bool isReservedTag( std::string const& tag ) {
  6922. return parseSpecialTag( tag ) == TestCaseInfo::None && tag.size() > 0 && !std::isalnum( tag[0] );
  6923. }
  6924. void enforceNotReservedTag( std::string const& tag, SourceLineInfo const& _lineInfo ) {
  6925. CATCH_ENFORCE( !isReservedTag(tag),
  6926. "Tag name: [" << tag << "] is not allowed.\n"
  6927. << "Tag names starting with non alpha-numeric characters are reserved\n"
  6928. << _lineInfo );
  6929. }
  6930. TestCase makeTestCase( ITestInvoker* _testCase,
  6931. std::string const& _className,
  6932. std::string const& _name,
  6933. std::string const& _descOrTags,
  6934. SourceLineInfo const& _lineInfo )
  6935. {
  6936. bool isHidden = false;
  6937. // Parse out tags
  6938. std::vector<std::string> tags;
  6939. std::string desc, tag;
  6940. bool inTag = false;
  6941. for (char c : _descOrTags) {
  6942. if( !inTag ) {
  6943. if( c == '[' )
  6944. inTag = true;
  6945. else
  6946. desc += c;
  6947. }
  6948. else {
  6949. if( c == ']' ) {
  6950. TestCaseInfo::SpecialProperties prop = parseSpecialTag( tag );
  6951. if( ( prop & TestCaseInfo::IsHidden ) != 0 )
  6952. isHidden = true;
  6953. else if( prop == TestCaseInfo::None )
  6954. enforceNotReservedTag( tag, _lineInfo );
  6955. tags.push_back( tag );
  6956. tag.clear();
  6957. inTag = false;
  6958. }
  6959. else
  6960. tag += c;
  6961. }
  6962. }
  6963. if( isHidden ) {
  6964. tags.push_back( "." );
  6965. }
  6966. TestCaseInfo info( _name, _className, desc, tags, _lineInfo );
  6967. return TestCase( _testCase, info );
  6968. }
  6969. void setTags( TestCaseInfo& testCaseInfo, std::vector<std::string> tags ) {
  6970. std::sort(begin(tags), end(tags));
  6971. tags.erase(std::unique(begin(tags), end(tags)), end(tags));
  6972. testCaseInfo.lcaseTags.clear();
  6973. for( auto const& tag : tags ) {
  6974. std::string lcaseTag = toLower( tag );
  6975. testCaseInfo.properties = static_cast<TestCaseInfo::SpecialProperties>( testCaseInfo.properties | parseSpecialTag( lcaseTag ) );
  6976. testCaseInfo.lcaseTags.push_back( lcaseTag );
  6977. }
  6978. testCaseInfo.tags = std::move(tags);
  6979. }
  6980. TestCaseInfo::TestCaseInfo( std::string const& _name,
  6981. std::string const& _className,
  6982. std::string const& _description,
  6983. std::vector<std::string> const& _tags,
  6984. SourceLineInfo const& _lineInfo )
  6985. : name( _name ),
  6986. className( _className ),
  6987. description( _description ),
  6988. lineInfo( _lineInfo ),
  6989. properties( None )
  6990. {
  6991. setTags( *this, _tags );
  6992. }
  6993. bool TestCaseInfo::isHidden() const {
  6994. return ( properties & IsHidden ) != 0;
  6995. }
  6996. bool TestCaseInfo::throws() const {
  6997. return ( properties & Throws ) != 0;
  6998. }
  6999. bool TestCaseInfo::okToFail() const {
  7000. return ( properties & (ShouldFail | MayFail ) ) != 0;
  7001. }
  7002. bool TestCaseInfo::expectedToFail() const {
  7003. return ( properties & (ShouldFail ) ) != 0;
  7004. }
  7005. std::string TestCaseInfo::tagsAsString() const {
  7006. std::string ret;
  7007. // '[' and ']' per tag
  7008. std::size_t full_size = 2 * tags.size();
  7009. for (const auto& tag : tags) {
  7010. full_size += tag.size();
  7011. }
  7012. ret.reserve(full_size);
  7013. for (const auto& tag : tags) {
  7014. ret.push_back('[');
  7015. ret.append(tag);
  7016. ret.push_back(']');
  7017. }
  7018. return ret;
  7019. }
  7020. TestCase::TestCase( ITestInvoker* testCase, TestCaseInfo const& info ) : TestCaseInfo( info ), test( testCase ) {}
  7021. TestCase TestCase::withName( std::string const& _newName ) const {
  7022. TestCase other( *this );
  7023. other.name = _newName;
  7024. return other;
  7025. }
  7026. void TestCase::invoke() const {
  7027. test->invoke();
  7028. }
  7029. bool TestCase::operator == ( TestCase const& other ) const {
  7030. return test.get() == other.test.get() &&
  7031. name == other.name &&
  7032. className == other.className;
  7033. }
  7034. bool TestCase::operator < ( TestCase const& other ) const {
  7035. return name < other.name;
  7036. }
  7037. TestCaseInfo const& TestCase::getTestCaseInfo() const
  7038. {
  7039. return *this;
  7040. }
  7041. } // end namespace Catch
  7042. // end catch_test_case_info.cpp
  7043. // start catch_test_case_registry_impl.cpp
  7044. #include <sstream>
  7045. namespace Catch {
  7046. std::vector<TestCase> sortTests( IConfig const& config, std::vector<TestCase> const& unsortedTestCases ) {
  7047. std::vector<TestCase> sorted = unsortedTestCases;
  7048. switch( config.runOrder() ) {
  7049. case RunTests::InLexicographicalOrder:
  7050. std::sort( sorted.begin(), sorted.end() );
  7051. break;
  7052. case RunTests::InRandomOrder:
  7053. seedRng( config );
  7054. RandomNumberGenerator::shuffle( sorted );
  7055. break;
  7056. case RunTests::InDeclarationOrder:
  7057. // already in declaration order
  7058. break;
  7059. }
  7060. return sorted;
  7061. }
  7062. bool matchTest( TestCase const& testCase, TestSpec const& testSpec, IConfig const& config ) {
  7063. return testSpec.matches( testCase ) && ( config.allowThrows() || !testCase.throws() );
  7064. }
  7065. void enforceNoDuplicateTestCases( std::vector<TestCase> const& functions ) {
  7066. std::set<TestCase> seenFunctions;
  7067. for( auto const& function : functions ) {
  7068. auto prev = seenFunctions.insert( function );
  7069. CATCH_ENFORCE( prev.second,
  7070. "error: TEST_CASE( \"" << function.name << "\" ) already defined.\n"
  7071. << "\tFirst seen at " << prev.first->getTestCaseInfo().lineInfo << "\n"
  7072. << "\tRedefined at " << function.getTestCaseInfo().lineInfo );
  7073. }
  7074. }
  7075. std::vector<TestCase> filterTests( std::vector<TestCase> const& testCases, TestSpec const& testSpec, IConfig const& config ) {
  7076. std::vector<TestCase> filtered;
  7077. filtered.reserve( testCases.size() );
  7078. for( auto const& testCase : testCases )
  7079. if( matchTest( testCase, testSpec, config ) )
  7080. filtered.push_back( testCase );
  7081. return filtered;
  7082. }
  7083. std::vector<TestCase> const& getAllTestCasesSorted( IConfig const& config ) {
  7084. return getRegistryHub().getTestCaseRegistry().getAllTestsSorted( config );
  7085. }
  7086. void TestRegistry::registerTest( TestCase const& testCase ) {
  7087. std::string name = testCase.getTestCaseInfo().name;
  7088. if( name.empty() ) {
  7089. std::ostringstream oss;
  7090. oss << "Anonymous test case " << ++m_unnamedCount;
  7091. return registerTest( testCase.withName( oss.str() ) );
  7092. }
  7093. m_functions.push_back( testCase );
  7094. }
  7095. std::vector<TestCase> const& TestRegistry::getAllTests() const {
  7096. return m_functions;
  7097. }
  7098. std::vector<TestCase> const& TestRegistry::getAllTestsSorted( IConfig const& config ) const {
  7099. if( m_sortedFunctions.empty() )
  7100. enforceNoDuplicateTestCases( m_functions );
  7101. if( m_currentSortOrder != config.runOrder() || m_sortedFunctions.empty() ) {
  7102. m_sortedFunctions = sortTests( config, m_functions );
  7103. m_currentSortOrder = config.runOrder();
  7104. }
  7105. return m_sortedFunctions;
  7106. }
  7107. ///////////////////////////////////////////////////////////////////////////
  7108. TestInvokerAsFunction::TestInvokerAsFunction( void(*testAsFunction)() ) noexcept : m_testAsFunction( testAsFunction ) {}
  7109. void TestInvokerAsFunction::invoke() const {
  7110. m_testAsFunction();
  7111. }
  7112. std::string extractClassName( std::string const& classOrQualifiedMethodName ) {
  7113. std::string className = classOrQualifiedMethodName;
  7114. if( startsWith( className, '&' ) )
  7115. {
  7116. std::size_t lastColons = className.rfind( "::" );
  7117. std::size_t penultimateColons = className.rfind( "::", lastColons-1 );
  7118. if( penultimateColons == std::string::npos )
  7119. penultimateColons = 1;
  7120. className = className.substr( penultimateColons, lastColons-penultimateColons );
  7121. }
  7122. return className;
  7123. }
  7124. } // end namespace Catch
  7125. // end catch_test_case_registry_impl.cpp
  7126. // start catch_test_case_tracker.cpp
  7127. #include <algorithm>
  7128. #include <assert.h>
  7129. #include <stdexcept>
  7130. #include <memory>
  7131. #if defined(__clang__)
  7132. # pragma clang diagnostic push
  7133. # pragma clang diagnostic ignored "-Wexit-time-destructors"
  7134. #endif
  7135. namespace Catch {
  7136. namespace TestCaseTracking {
  7137. NameAndLocation::NameAndLocation( std::string const& _name, SourceLineInfo const& _location )
  7138. : name( _name ),
  7139. location( _location )
  7140. {}
  7141. ITracker::~ITracker() = default;
  7142. TrackerContext& TrackerContext::instance() {
  7143. static TrackerContext s_instance;
  7144. return s_instance;
  7145. }
  7146. ITracker& TrackerContext::startRun() {
  7147. m_rootTracker = std::make_shared<SectionTracker>( NameAndLocation( "{root}", CATCH_INTERNAL_LINEINFO ), *this, nullptr );
  7148. m_currentTracker = nullptr;
  7149. m_runState = Executing;
  7150. return *m_rootTracker;
  7151. }
  7152. void TrackerContext::endRun() {
  7153. m_rootTracker.reset();
  7154. m_currentTracker = nullptr;
  7155. m_runState = NotStarted;
  7156. }
  7157. void TrackerContext::startCycle() {
  7158. m_currentTracker = m_rootTracker.get();
  7159. m_runState = Executing;
  7160. }
  7161. void TrackerContext::completeCycle() {
  7162. m_runState = CompletedCycle;
  7163. }
  7164. bool TrackerContext::completedCycle() const {
  7165. return m_runState == CompletedCycle;
  7166. }
  7167. ITracker& TrackerContext::currentTracker() {
  7168. return *m_currentTracker;
  7169. }
  7170. void TrackerContext::setCurrentTracker( ITracker* tracker ) {
  7171. m_currentTracker = tracker;
  7172. }
  7173. TrackerBase::TrackerHasName::TrackerHasName( NameAndLocation const& nameAndLocation ) : m_nameAndLocation( nameAndLocation ) {}
  7174. bool TrackerBase::TrackerHasName::operator ()( ITrackerPtr const& tracker ) const {
  7175. return
  7176. tracker->nameAndLocation().name == m_nameAndLocation.name &&
  7177. tracker->nameAndLocation().location == m_nameAndLocation.location;
  7178. }
  7179. TrackerBase::TrackerBase( NameAndLocation const& nameAndLocation, TrackerContext& ctx, ITracker* parent )
  7180. : m_nameAndLocation( nameAndLocation ),
  7181. m_ctx( ctx ),
  7182. m_parent( parent )
  7183. {}
  7184. NameAndLocation const& TrackerBase::nameAndLocation() const {
  7185. return m_nameAndLocation;
  7186. }
  7187. bool TrackerBase::isComplete() const {
  7188. return m_runState == CompletedSuccessfully || m_runState == Failed;
  7189. }
  7190. bool TrackerBase::isSuccessfullyCompleted() const {
  7191. return m_runState == CompletedSuccessfully;
  7192. }
  7193. bool TrackerBase::isOpen() const {
  7194. return m_runState != NotStarted && !isComplete();
  7195. }
  7196. bool TrackerBase::hasChildren() const {
  7197. return !m_children.empty();
  7198. }
  7199. void TrackerBase::addChild( ITrackerPtr const& child ) {
  7200. m_children.push_back( child );
  7201. }
  7202. ITrackerPtr TrackerBase::findChild( NameAndLocation const& nameAndLocation ) {
  7203. auto it = std::find_if( m_children.begin(), m_children.end(), TrackerHasName( nameAndLocation ) );
  7204. return( it != m_children.end() )
  7205. ? *it
  7206. : nullptr;
  7207. }
  7208. ITracker& TrackerBase::parent() {
  7209. assert( m_parent ); // Should always be non-null except for root
  7210. return *m_parent;
  7211. }
  7212. void TrackerBase::openChild() {
  7213. if( m_runState != ExecutingChildren ) {
  7214. m_runState = ExecutingChildren;
  7215. if( m_parent )
  7216. m_parent->openChild();
  7217. }
  7218. }
  7219. bool TrackerBase::isSectionTracker() const { return false; }
  7220. bool TrackerBase::isIndexTracker() const { return false; }
  7221. void TrackerBase::open() {
  7222. m_runState = Executing;
  7223. moveToThis();
  7224. if( m_parent )
  7225. m_parent->openChild();
  7226. }
  7227. void TrackerBase::close() {
  7228. // Close any still open children (e.g. generators)
  7229. while( &m_ctx.currentTracker() != this )
  7230. m_ctx.currentTracker().close();
  7231. switch( m_runState ) {
  7232. case NeedsAnotherRun:
  7233. break;
  7234. case Executing:
  7235. m_runState = CompletedSuccessfully;
  7236. break;
  7237. case ExecutingChildren:
  7238. if( m_children.empty() || m_children.back()->isComplete() )
  7239. m_runState = CompletedSuccessfully;
  7240. break;
  7241. case NotStarted:
  7242. case CompletedSuccessfully:
  7243. case Failed:
  7244. CATCH_INTERNAL_ERROR( "Illogical state: " << m_runState );
  7245. default:
  7246. CATCH_INTERNAL_ERROR( "Unknown state: " << m_runState );
  7247. }
  7248. moveToParent();
  7249. m_ctx.completeCycle();
  7250. }
  7251. void TrackerBase::fail() {
  7252. m_runState = Failed;
  7253. if( m_parent )
  7254. m_parent->markAsNeedingAnotherRun();
  7255. moveToParent();
  7256. m_ctx.completeCycle();
  7257. }
  7258. void TrackerBase::markAsNeedingAnotherRun() {
  7259. m_runState = NeedsAnotherRun;
  7260. }
  7261. void TrackerBase::moveToParent() {
  7262. assert( m_parent );
  7263. m_ctx.setCurrentTracker( m_parent );
  7264. }
  7265. void TrackerBase::moveToThis() {
  7266. m_ctx.setCurrentTracker( this );
  7267. }
  7268. SectionTracker::SectionTracker( NameAndLocation const& nameAndLocation, TrackerContext& ctx, ITracker* parent )
  7269. : TrackerBase( nameAndLocation, ctx, parent )
  7270. {
  7271. if( parent ) {
  7272. while( !parent->isSectionTracker() )
  7273. parent = &parent->parent();
  7274. SectionTracker& parentSection = static_cast<SectionTracker&>( *parent );
  7275. addNextFilters( parentSection.m_filters );
  7276. }
  7277. }
  7278. bool SectionTracker::isSectionTracker() const { return true; }
  7279. SectionTracker& SectionTracker::acquire( TrackerContext& ctx, NameAndLocation const& nameAndLocation ) {
  7280. std::shared_ptr<SectionTracker> section;
  7281. ITracker& currentTracker = ctx.currentTracker();
  7282. if( ITrackerPtr childTracker = currentTracker.findChild( nameAndLocation ) ) {
  7283. assert( childTracker );
  7284. assert( childTracker->isSectionTracker() );
  7285. section = std::static_pointer_cast<SectionTracker>( childTracker );
  7286. }
  7287. else {
  7288. section = std::make_shared<SectionTracker>( nameAndLocation, ctx, &currentTracker );
  7289. currentTracker.addChild( section );
  7290. }
  7291. if( !ctx.completedCycle() )
  7292. section->tryOpen();
  7293. return *section;
  7294. }
  7295. void SectionTracker::tryOpen() {
  7296. if( !isComplete() && (m_filters.empty() || m_filters[0].empty() || m_filters[0] == m_nameAndLocation.name ) )
  7297. open();
  7298. }
  7299. void SectionTracker::addInitialFilters( std::vector<std::string> const& filters ) {
  7300. if( !filters.empty() ) {
  7301. m_filters.push_back(""); // Root - should never be consulted
  7302. m_filters.push_back(""); // Test Case - not a section filter
  7303. m_filters.insert( m_filters.end(), filters.begin(), filters.end() );
  7304. }
  7305. }
  7306. void SectionTracker::addNextFilters( std::vector<std::string> const& filters ) {
  7307. if( filters.size() > 1 )
  7308. m_filters.insert( m_filters.end(), ++filters.begin(), filters.end() );
  7309. }
  7310. IndexTracker::IndexTracker( NameAndLocation const& nameAndLocation, TrackerContext& ctx, ITracker* parent, int size )
  7311. : TrackerBase( nameAndLocation, ctx, parent ),
  7312. m_size( size )
  7313. {}
  7314. bool IndexTracker::isIndexTracker() const { return true; }
  7315. IndexTracker& IndexTracker::acquire( TrackerContext& ctx, NameAndLocation const& nameAndLocation, int size ) {
  7316. std::shared_ptr<IndexTracker> tracker;
  7317. ITracker& currentTracker = ctx.currentTracker();
  7318. if( ITrackerPtr childTracker = currentTracker.findChild( nameAndLocation ) ) {
  7319. assert( childTracker );
  7320. assert( childTracker->isIndexTracker() );
  7321. tracker = std::static_pointer_cast<IndexTracker>( childTracker );
  7322. }
  7323. else {
  7324. tracker = std::make_shared<IndexTracker>( nameAndLocation, ctx, &currentTracker, size );
  7325. currentTracker.addChild( tracker );
  7326. }
  7327. if( !ctx.completedCycle() && !tracker->isComplete() ) {
  7328. if( tracker->m_runState != ExecutingChildren && tracker->m_runState != NeedsAnotherRun )
  7329. tracker->moveNext();
  7330. tracker->open();
  7331. }
  7332. return *tracker;
  7333. }
  7334. int IndexTracker::index() const { return m_index; }
  7335. void IndexTracker::moveNext() {
  7336. m_index++;
  7337. m_children.clear();
  7338. }
  7339. void IndexTracker::close() {
  7340. TrackerBase::close();
  7341. if( m_runState == CompletedSuccessfully && m_index < m_size-1 )
  7342. m_runState = Executing;
  7343. }
  7344. } // namespace TestCaseTracking
  7345. using TestCaseTracking::ITracker;
  7346. using TestCaseTracking::TrackerContext;
  7347. using TestCaseTracking::SectionTracker;
  7348. using TestCaseTracking::IndexTracker;
  7349. } // namespace Catch
  7350. #if defined(__clang__)
  7351. # pragma clang diagnostic pop
  7352. #endif
  7353. // end catch_test_case_tracker.cpp
  7354. // start catch_test_registry.cpp
  7355. namespace Catch {
  7356. auto makeTestInvoker( void(*testAsFunction)() ) noexcept -> ITestInvoker* {
  7357. return new(std::nothrow) TestInvokerAsFunction( testAsFunction );
  7358. }
  7359. NameAndTags::NameAndTags( StringRef name_ , StringRef tags_ ) noexcept : name( name_ ), tags( tags_ ) {}
  7360. AutoReg::AutoReg( ITestInvoker* invoker, SourceLineInfo const& lineInfo, StringRef classOrMethod, NameAndTags const& nameAndTags ) noexcept {
  7361. try {
  7362. getMutableRegistryHub()
  7363. .registerTest(
  7364. makeTestCase(
  7365. invoker,
  7366. extractClassName( classOrMethod ),
  7367. nameAndTags.name,
  7368. nameAndTags.tags,
  7369. lineInfo));
  7370. } catch (...) {
  7371. // Do not throw when constructing global objects, instead register the exception to be processed later
  7372. getMutableRegistryHub().registerStartupException();
  7373. }
  7374. }
  7375. AutoReg::~AutoReg() = default;
  7376. }
  7377. // end catch_test_registry.cpp
  7378. // start catch_test_spec.cpp
  7379. #include <algorithm>
  7380. #include <string>
  7381. #include <vector>
  7382. #include <memory>
  7383. namespace Catch {
  7384. TestSpec::Pattern::~Pattern() = default;
  7385. TestSpec::NamePattern::~NamePattern() = default;
  7386. TestSpec::TagPattern::~TagPattern() = default;
  7387. TestSpec::ExcludedPattern::~ExcludedPattern() = default;
  7388. TestSpec::NamePattern::NamePattern( std::string const& name )
  7389. : m_wildcardPattern( toLower( name ), CaseSensitive::No )
  7390. {}
  7391. bool TestSpec::NamePattern::matches( TestCaseInfo const& testCase ) const {
  7392. return m_wildcardPattern.matches( toLower( testCase.name ) );
  7393. }
  7394. TestSpec::TagPattern::TagPattern( std::string const& tag ) : m_tag( toLower( tag ) ) {}
  7395. bool TestSpec::TagPattern::matches( TestCaseInfo const& testCase ) const {
  7396. return std::find(begin(testCase.lcaseTags),
  7397. end(testCase.lcaseTags),
  7398. m_tag) != end(testCase.lcaseTags);
  7399. }
  7400. TestSpec::ExcludedPattern::ExcludedPattern( PatternPtr const& underlyingPattern ) : m_underlyingPattern( underlyingPattern ) {}
  7401. bool TestSpec::ExcludedPattern::matches( TestCaseInfo const& testCase ) const { return !m_underlyingPattern->matches( testCase ); }
  7402. bool TestSpec::Filter::matches( TestCaseInfo const& testCase ) const {
  7403. // All patterns in a filter must match for the filter to be a match
  7404. for( auto const& pattern : m_patterns ) {
  7405. if( !pattern->matches( testCase ) )
  7406. return false;
  7407. }
  7408. return true;
  7409. }
  7410. bool TestSpec::hasFilters() const {
  7411. return !m_filters.empty();
  7412. }
  7413. bool TestSpec::matches( TestCaseInfo const& testCase ) const {
  7414. // A TestSpec matches if any filter matches
  7415. for( auto const& filter : m_filters )
  7416. if( filter.matches( testCase ) )
  7417. return true;
  7418. return false;
  7419. }
  7420. }
  7421. // end catch_test_spec.cpp
  7422. // start catch_test_spec_parser.cpp
  7423. namespace Catch {
  7424. TestSpecParser::TestSpecParser( ITagAliasRegistry const& tagAliases ) : m_tagAliases( &tagAliases ) {}
  7425. TestSpecParser& TestSpecParser::parse( std::string const& arg ) {
  7426. m_mode = None;
  7427. m_exclusion = false;
  7428. m_start = std::string::npos;
  7429. m_arg = m_tagAliases->expandAliases( arg );
  7430. m_escapeChars.clear();
  7431. for( m_pos = 0; m_pos < m_arg.size(); ++m_pos )
  7432. visitChar( m_arg[m_pos] );
  7433. if( m_mode == Name )
  7434. addPattern<TestSpec::NamePattern>();
  7435. return *this;
  7436. }
  7437. TestSpec TestSpecParser::testSpec() {
  7438. addFilter();
  7439. return m_testSpec;
  7440. }
  7441. void TestSpecParser::visitChar( char c ) {
  7442. if( m_mode == None ) {
  7443. switch( c ) {
  7444. case ' ': return;
  7445. case '~': m_exclusion = true; return;
  7446. case '[': return startNewMode( Tag, ++m_pos );
  7447. case '"': return startNewMode( QuotedName, ++m_pos );
  7448. case '\\': return escape();
  7449. default: startNewMode( Name, m_pos ); break;
  7450. }
  7451. }
  7452. if( m_mode == Name ) {
  7453. if( c == ',' ) {
  7454. addPattern<TestSpec::NamePattern>();
  7455. addFilter();
  7456. }
  7457. else if( c == '[' ) {
  7458. if( subString() == "exclude:" )
  7459. m_exclusion = true;
  7460. else
  7461. addPattern<TestSpec::NamePattern>();
  7462. startNewMode( Tag, ++m_pos );
  7463. }
  7464. else if( c == '\\' )
  7465. escape();
  7466. }
  7467. else if( m_mode == EscapedName )
  7468. m_mode = Name;
  7469. else if( m_mode == QuotedName && c == '"' )
  7470. addPattern<TestSpec::NamePattern>();
  7471. else if( m_mode == Tag && c == ']' )
  7472. addPattern<TestSpec::TagPattern>();
  7473. }
  7474. void TestSpecParser::startNewMode( Mode mode, std::size_t start ) {
  7475. m_mode = mode;
  7476. m_start = start;
  7477. }
  7478. void TestSpecParser::escape() {
  7479. if( m_mode == None )
  7480. m_start = m_pos;
  7481. m_mode = EscapedName;
  7482. m_escapeChars.push_back( m_pos );
  7483. }
  7484. std::string TestSpecParser::subString() const { return m_arg.substr( m_start, m_pos - m_start ); }
  7485. void TestSpecParser::addFilter() {
  7486. if( !m_currentFilter.m_patterns.empty() ) {
  7487. m_testSpec.m_filters.push_back( m_currentFilter );
  7488. m_currentFilter = TestSpec::Filter();
  7489. }
  7490. }
  7491. TestSpec parseTestSpec( std::string const& arg ) {
  7492. return TestSpecParser( ITagAliasRegistry::get() ).parse( arg ).testSpec();
  7493. }
  7494. } // namespace Catch
  7495. // end catch_test_spec_parser.cpp
  7496. // start catch_timer.cpp
  7497. #include <chrono>
  7498. namespace Catch {
  7499. auto getCurrentNanosecondsSinceEpoch() -> uint64_t {
  7500. return std::chrono::duration_cast<std::chrono::nanoseconds>( std::chrono::high_resolution_clock::now().time_since_epoch() ).count();
  7501. }
  7502. auto estimateClockResolution() -> uint64_t {
  7503. uint64_t sum = 0;
  7504. static const uint64_t iterations = 1000000;
  7505. for( std::size_t i = 0; i < iterations; ++i ) {
  7506. uint64_t ticks;
  7507. uint64_t baseTicks = getCurrentNanosecondsSinceEpoch();
  7508. do {
  7509. ticks = getCurrentNanosecondsSinceEpoch();
  7510. }
  7511. while( ticks == baseTicks );
  7512. auto delta = ticks - baseTicks;
  7513. sum += delta;
  7514. }
  7515. // We're just taking the mean, here. To do better we could take the std. dev and exclude outliers
  7516. // - and potentially do more iterations if there's a high variance.
  7517. return sum/iterations;
  7518. }
  7519. auto getEstimatedClockResolution() -> uint64_t {
  7520. static auto s_resolution = estimateClockResolution();
  7521. return s_resolution;
  7522. }
  7523. void Timer::start() {
  7524. m_nanoseconds = getCurrentNanosecondsSinceEpoch();
  7525. }
  7526. auto Timer::getElapsedNanoseconds() const -> unsigned int {
  7527. return static_cast<unsigned int>(getCurrentNanosecondsSinceEpoch() - m_nanoseconds);
  7528. }
  7529. auto Timer::getElapsedMicroseconds() const -> unsigned int {
  7530. return static_cast<unsigned int>(getElapsedNanoseconds()/1000);
  7531. }
  7532. auto Timer::getElapsedMilliseconds() const -> unsigned int {
  7533. return static_cast<unsigned int>(getElapsedMicroseconds()/1000);
  7534. }
  7535. auto Timer::getElapsedSeconds() const -> double {
  7536. return getElapsedMicroseconds()/1000000.0;
  7537. }
  7538. } // namespace Catch
  7539. // end catch_timer.cpp
  7540. // start catch_tostring.cpp
  7541. #if defined(__clang__)
  7542. # pragma clang diagnostic push
  7543. # pragma clang diagnostic ignored "-Wexit-time-destructors"
  7544. # pragma clang diagnostic ignored "-Wglobal-constructors"
  7545. #endif
  7546. #include <iomanip>
  7547. namespace Catch {
  7548. namespace Detail {
  7549. const std::string unprintableString = "{?}";
  7550. namespace {
  7551. const int hexThreshold = 255;
  7552. struct Endianness {
  7553. enum Arch { Big, Little };
  7554. static Arch which() {
  7555. union _{
  7556. int asInt;
  7557. char asChar[sizeof (int)];
  7558. } u;
  7559. u.asInt = 1;
  7560. return ( u.asChar[sizeof(int)-1] == 1 ) ? Big : Little;
  7561. }
  7562. };
  7563. }
  7564. std::string rawMemoryToString( const void *object, std::size_t size ) {
  7565. // Reverse order for little endian architectures
  7566. int i = 0, end = static_cast<int>( size ), inc = 1;
  7567. if( Endianness::which() == Endianness::Little ) {
  7568. i = end-1;
  7569. end = inc = -1;
  7570. }
  7571. unsigned char const *bytes = static_cast<unsigned char const *>(object);
  7572. std::ostringstream os;
  7573. os << "0x" << std::setfill('0') << std::hex;
  7574. for( ; i != end; i += inc )
  7575. os << std::setw(2) << static_cast<unsigned>(bytes[i]);
  7576. return os.str();
  7577. }
  7578. }
  7579. template<typename T>
  7580. std::string fpToString( T value, int precision ) {
  7581. std::ostringstream oss;
  7582. oss << std::setprecision( precision )
  7583. << std::fixed
  7584. << value;
  7585. std::string d = oss.str();
  7586. std::size_t i = d.find_last_not_of( '0' );
  7587. if( i != std::string::npos && i != d.size()-1 ) {
  7588. if( d[i] == '.' )
  7589. i++;
  7590. d = d.substr( 0, i+1 );
  7591. }
  7592. return d;
  7593. }
  7594. //// ======================================================= ////
  7595. //
  7596. // Out-of-line defs for full specialization of StringMaker
  7597. //
  7598. //// ======================================================= ////
  7599. std::string StringMaker<std::string>::convert(const std::string& str) {
  7600. if (!getCurrentContext().getConfig()->showInvisibles()) {
  7601. return '"' + str + '"';
  7602. }
  7603. std::string s("\"");
  7604. for (char c : str) {
  7605. switch (c) {
  7606. case '\n':
  7607. s.append("\\n");
  7608. break;
  7609. case '\t':
  7610. s.append("\\t");
  7611. break;
  7612. default:
  7613. s.push_back(c);
  7614. break;
  7615. }
  7616. }
  7617. s.append("\"");
  7618. return s;
  7619. }
  7620. std::string StringMaker<std::wstring>::convert(const std::wstring& wstr) {
  7621. std::string s;
  7622. s.reserve(wstr.size());
  7623. for (auto c : wstr) {
  7624. s += (c <= 0xff) ? static_cast<char>(c) : '?';
  7625. }
  7626. return ::Catch::Detail::stringify(s);
  7627. }
  7628. std::string StringMaker<char const*>::convert(char const* str) {
  7629. if (str) {
  7630. return ::Catch::Detail::stringify(std::string{ str });
  7631. } else {
  7632. return{ "{null string}" };
  7633. }
  7634. }
  7635. std::string StringMaker<char*>::convert(char* str) {
  7636. if (str) {
  7637. return ::Catch::Detail::stringify(std::string{ str });
  7638. } else {
  7639. return{ "{null string}" };
  7640. }
  7641. }
  7642. std::string StringMaker<wchar_t const*>::convert(wchar_t const * str) {
  7643. if (str) {
  7644. return ::Catch::Detail::stringify(std::wstring{ str });
  7645. } else {
  7646. return{ "{null string}" };
  7647. }
  7648. }
  7649. std::string StringMaker<wchar_t *>::convert(wchar_t * str) {
  7650. if (str) {
  7651. return ::Catch::Detail::stringify(std::wstring{ str });
  7652. } else {
  7653. return{ "{null string}" };
  7654. }
  7655. }
  7656. std::string StringMaker<int>::convert(int value) {
  7657. return ::Catch::Detail::stringify(static_cast<long long>(value));
  7658. }
  7659. std::string StringMaker<long>::convert(long value) {
  7660. return ::Catch::Detail::stringify(static_cast<long long>(value));
  7661. }
  7662. std::string StringMaker<long long>::convert(long long value) {
  7663. std::ostringstream oss;
  7664. oss << value;
  7665. if (value > Detail::hexThreshold) {
  7666. oss << " (0x" << std::hex << value << ')';
  7667. }
  7668. return oss.str();
  7669. }
  7670. std::string StringMaker<unsigned int>::convert(unsigned int value) {
  7671. return ::Catch::Detail::stringify(static_cast<unsigned long long>(value));
  7672. }
  7673. std::string StringMaker<unsigned long>::convert(unsigned long value) {
  7674. return ::Catch::Detail::stringify(static_cast<unsigned long long>(value));
  7675. }
  7676. std::string StringMaker<unsigned long long>::convert(unsigned long long value) {
  7677. std::ostringstream oss;
  7678. oss << value;
  7679. if (value > Detail::hexThreshold) {
  7680. oss << " (0x" << std::hex << value << ')';
  7681. }
  7682. return oss.str();
  7683. }
  7684. std::string StringMaker<bool>::convert(bool b) {
  7685. return b ? "true" : "false";
  7686. }
  7687. std::string StringMaker<char>::convert(char value) {
  7688. if (value == '\r') {
  7689. return "'\\r'";
  7690. } else if (value == '\f') {
  7691. return "'\\f'";
  7692. } else if (value == '\n') {
  7693. return "'\\n'";
  7694. } else if (value == '\t') {
  7695. return "'\\t'";
  7696. } else if ('\0' <= value && value < ' ') {
  7697. return ::Catch::Detail::stringify(static_cast<unsigned int>(value));
  7698. } else {
  7699. char chstr[] = "' '";
  7700. chstr[1] = value;
  7701. return chstr;
  7702. }
  7703. }
  7704. std::string StringMaker<signed char>::convert(signed char c) {
  7705. return ::Catch::Detail::stringify(static_cast<char>(c));
  7706. }
  7707. std::string StringMaker<unsigned char>::convert(unsigned char c) {
  7708. return ::Catch::Detail::stringify(static_cast<char>(c));
  7709. }
  7710. std::string StringMaker<std::nullptr_t>::convert(std::nullptr_t) {
  7711. return "nullptr";
  7712. }
  7713. std::string StringMaker<float>::convert(float value) {
  7714. return fpToString(value, 5) + 'f';
  7715. }
  7716. std::string StringMaker<double>::convert(double value) {
  7717. return fpToString(value, 10);
  7718. }
  7719. } // end namespace Catch
  7720. #if defined(__clang__)
  7721. # pragma clang diagnostic pop
  7722. #endif
  7723. // end catch_tostring.cpp
  7724. // start catch_totals.cpp
  7725. namespace Catch {
  7726. Counts Counts::operator - ( Counts const& other ) const {
  7727. Counts diff;
  7728. diff.passed = passed - other.passed;
  7729. diff.failed = failed - other.failed;
  7730. diff.failedButOk = failedButOk - other.failedButOk;
  7731. return diff;
  7732. }
  7733. Counts& Counts::operator += ( Counts const& other ) {
  7734. passed += other.passed;
  7735. failed += other.failed;
  7736. failedButOk += other.failedButOk;
  7737. return *this;
  7738. }
  7739. std::size_t Counts::total() const {
  7740. return passed + failed + failedButOk;
  7741. }
  7742. bool Counts::allPassed() const {
  7743. return failed == 0 && failedButOk == 0;
  7744. }
  7745. bool Counts::allOk() const {
  7746. return failed == 0;
  7747. }
  7748. Totals Totals::operator - ( Totals const& other ) const {
  7749. Totals diff;
  7750. diff.assertions = assertions - other.assertions;
  7751. diff.testCases = testCases - other.testCases;
  7752. return diff;
  7753. }
  7754. Totals& Totals::operator += ( Totals const& other ) {
  7755. assertions += other.assertions;
  7756. testCases += other.testCases;
  7757. return *this;
  7758. }
  7759. Totals Totals::delta( Totals const& prevTotals ) const {
  7760. Totals diff = *this - prevTotals;
  7761. if( diff.assertions.failed > 0 )
  7762. ++diff.testCases.failed;
  7763. else if( diff.assertions.failedButOk > 0 )
  7764. ++diff.testCases.failedButOk;
  7765. else
  7766. ++diff.testCases.passed;
  7767. return diff;
  7768. }
  7769. }
  7770. // end catch_totals.cpp
  7771. // start catch_version.cpp
  7772. #include <ostream>
  7773. namespace Catch {
  7774. Version::Version
  7775. ( unsigned int _majorVersion,
  7776. unsigned int _minorVersion,
  7777. unsigned int _patchNumber,
  7778. char const * const _branchName,
  7779. unsigned int _buildNumber )
  7780. : majorVersion( _majorVersion ),
  7781. minorVersion( _minorVersion ),
  7782. patchNumber( _patchNumber ),
  7783. branchName( _branchName ),
  7784. buildNumber( _buildNumber )
  7785. {}
  7786. std::ostream& operator << ( std::ostream& os, Version const& version ) {
  7787. os << version.majorVersion << '.'
  7788. << version.minorVersion << '.'
  7789. << version.patchNumber;
  7790. // branchName is never null -> 0th char is \0 if it is empty
  7791. if (version.branchName[0]) {
  7792. os << '-' << version.branchName
  7793. << '.' << version.buildNumber;
  7794. }
  7795. return os;
  7796. }
  7797. Version const& libraryVersion() {
  7798. static Version version( 2, 0, 0, "develop", 4 );
  7799. return version;
  7800. }
  7801. }
  7802. // end catch_version.cpp
  7803. // start catch_wildcard_pattern.cpp
  7804. namespace Catch {
  7805. WildcardPattern::WildcardPattern( std::string const& pattern,
  7806. CaseSensitive::Choice caseSensitivity )
  7807. : m_caseSensitivity( caseSensitivity ),
  7808. m_pattern( adjustCase( pattern ) )
  7809. {
  7810. if( startsWith( m_pattern, '*' ) ) {
  7811. m_pattern = m_pattern.substr( 1 );
  7812. m_wildcard = WildcardAtStart;
  7813. }
  7814. if( endsWith( m_pattern, '*' ) ) {
  7815. m_pattern = m_pattern.substr( 0, m_pattern.size()-1 );
  7816. m_wildcard = static_cast<WildcardPosition>( m_wildcard | WildcardAtEnd );
  7817. }
  7818. }
  7819. bool WildcardPattern::matches( std::string const& str ) const {
  7820. switch( m_wildcard ) {
  7821. case NoWildcard:
  7822. return m_pattern == adjustCase( str );
  7823. case WildcardAtStart:
  7824. return endsWith( adjustCase( str ), m_pattern );
  7825. case WildcardAtEnd:
  7826. return startsWith( adjustCase( str ), m_pattern );
  7827. case WildcardAtBothEnds:
  7828. return contains( adjustCase( str ), m_pattern );
  7829. default:
  7830. CATCH_INTERNAL_ERROR( "Unknown enum" );
  7831. }
  7832. }
  7833. std::string WildcardPattern::adjustCase( std::string const& str ) const {
  7834. return m_caseSensitivity == CaseSensitive::No ? toLower( str ) : str;
  7835. }
  7836. }
  7837. // end catch_wildcard_pattern.cpp
  7838. // start catch_xmlwriter.cpp
  7839. // start catch_xmlwriter.h
  7840. #include <sstream>
  7841. #include <vector>
  7842. namespace Catch {
  7843. class XmlEncode {
  7844. public:
  7845. enum ForWhat { ForTextNodes, ForAttributes };
  7846. XmlEncode( std::string const& str, ForWhat forWhat = ForTextNodes );
  7847. void encodeTo( std::ostream& os ) const;
  7848. friend std::ostream& operator << ( std::ostream& os, XmlEncode const& xmlEncode );
  7849. private:
  7850. std::string m_str;
  7851. ForWhat m_forWhat;
  7852. };
  7853. class XmlWriter {
  7854. public:
  7855. class ScopedElement {
  7856. public:
  7857. ScopedElement( XmlWriter* writer );
  7858. ScopedElement( ScopedElement&& other ) noexcept;
  7859. ScopedElement& operator=( ScopedElement&& other ) noexcept;
  7860. ~ScopedElement();
  7861. ScopedElement& writeText( std::string const& text, bool indent = true );
  7862. template<typename T>
  7863. ScopedElement& writeAttribute( std::string const& name, T const& attribute ) {
  7864. m_writer->writeAttribute( name, attribute );
  7865. return *this;
  7866. }
  7867. private:
  7868. mutable XmlWriter* m_writer = nullptr;
  7869. };
  7870. XmlWriter( std::ostream& os = Catch::cout() );
  7871. ~XmlWriter();
  7872. XmlWriter( XmlWriter const& ) = delete;
  7873. XmlWriter& operator=( XmlWriter const& ) = delete;
  7874. XmlWriter& startElement( std::string const& name );
  7875. ScopedElement scopedElement( std::string const& name );
  7876. XmlWriter& endElement();
  7877. XmlWriter& writeAttribute( std::string const& name, std::string const& attribute );
  7878. XmlWriter& writeAttribute( std::string const& name, bool attribute );
  7879. template<typename T>
  7880. XmlWriter& writeAttribute( std::string const& name, T const& attribute ) {
  7881. m_oss.clear();
  7882. m_oss.str(std::string());
  7883. m_oss << attribute;
  7884. return writeAttribute( name, m_oss.str() );
  7885. }
  7886. XmlWriter& writeText( std::string const& text, bool indent = true );
  7887. XmlWriter& writeComment( std::string const& text );
  7888. void writeStylesheetRef( std::string const& url );
  7889. XmlWriter& writeBlankLine();
  7890. void ensureTagClosed();
  7891. private:
  7892. void writeDeclaration();
  7893. void newlineIfNecessary();
  7894. bool m_tagIsOpen = false;
  7895. bool m_needsNewline = false;
  7896. std::vector<std::string> m_tags;
  7897. std::string m_indent;
  7898. std::ostream& m_os;
  7899. std::ostringstream m_oss;
  7900. };
  7901. }
  7902. // end catch_xmlwriter.h
  7903. #include <iomanip>
  7904. namespace Catch {
  7905. XmlEncode::XmlEncode( std::string const& str, ForWhat forWhat )
  7906. : m_str( str ),
  7907. m_forWhat( forWhat )
  7908. {}
  7909. void XmlEncode::encodeTo( std::ostream& os ) const {
  7910. // Apostrophe escaping not necessary if we always use " to write attributes
  7911. // (see: http://www.w3.org/TR/xml/#syntax)
  7912. for( std::size_t i = 0; i < m_str.size(); ++ i ) {
  7913. char c = m_str[i];
  7914. switch( c ) {
  7915. case '<': os << "&lt;"; break;
  7916. case '&': os << "&amp;"; break;
  7917. case '>':
  7918. // See: http://www.w3.org/TR/xml/#syntax
  7919. if( i > 2 && m_str[i-1] == ']' && m_str[i-2] == ']' )
  7920. os << "&gt;";
  7921. else
  7922. os << c;
  7923. break;
  7924. case '\"':
  7925. if( m_forWhat == ForAttributes )
  7926. os << "&quot;";
  7927. else
  7928. os << c;
  7929. break;
  7930. default:
  7931. // Escape control chars - based on contribution by @espenalb in PR #465 and
  7932. // by @mrpi PR #588
  7933. if ( ( c >= 0 && c < '\x09' ) || ( c > '\x0D' && c < '\x20') || c=='\x7F' ) {
  7934. // see http://stackoverflow.com/questions/404107/why-are-control-characters-illegal-in-xml-1-0
  7935. os << "\\x" << std::uppercase << std::hex << std::setfill('0') << std::setw(2)
  7936. << static_cast<int>( c );
  7937. }
  7938. else
  7939. os << c;
  7940. }
  7941. }
  7942. }
  7943. std::ostream& operator << ( std::ostream& os, XmlEncode const& xmlEncode ) {
  7944. xmlEncode.encodeTo( os );
  7945. return os;
  7946. }
  7947. XmlWriter::ScopedElement::ScopedElement( XmlWriter* writer )
  7948. : m_writer( writer )
  7949. {}
  7950. XmlWriter::ScopedElement::ScopedElement( ScopedElement&& other ) noexcept
  7951. : m_writer( other.m_writer ){
  7952. other.m_writer = nullptr;
  7953. }
  7954. XmlWriter::ScopedElement& XmlWriter::ScopedElement::operator=( ScopedElement&& other ) noexcept {
  7955. if ( m_writer ) {
  7956. m_writer->endElement();
  7957. }
  7958. m_writer = other.m_writer;
  7959. other.m_writer = nullptr;
  7960. return *this;
  7961. }
  7962. XmlWriter::ScopedElement::~ScopedElement() {
  7963. if( m_writer )
  7964. m_writer->endElement();
  7965. }
  7966. XmlWriter::ScopedElement& XmlWriter::ScopedElement::writeText( std::string const& text, bool indent ) {
  7967. m_writer->writeText( text, indent );
  7968. return *this;
  7969. }
  7970. XmlWriter::XmlWriter( std::ostream& os ) : m_os( os )
  7971. {
  7972. writeDeclaration();
  7973. }
  7974. XmlWriter::~XmlWriter() {
  7975. while( !m_tags.empty() )
  7976. endElement();
  7977. }
  7978. XmlWriter& XmlWriter::startElement( std::string const& name ) {
  7979. ensureTagClosed();
  7980. newlineIfNecessary();
  7981. m_os << m_indent << '<' << name;
  7982. m_tags.push_back( name );
  7983. m_indent += " ";
  7984. m_tagIsOpen = true;
  7985. return *this;
  7986. }
  7987. XmlWriter::ScopedElement XmlWriter::scopedElement( std::string const& name ) {
  7988. ScopedElement scoped( this );
  7989. startElement( name );
  7990. return scoped;
  7991. }
  7992. XmlWriter& XmlWriter::endElement() {
  7993. newlineIfNecessary();
  7994. m_indent = m_indent.substr( 0, m_indent.size()-2 );
  7995. if( m_tagIsOpen ) {
  7996. m_os << "/>";
  7997. m_tagIsOpen = false;
  7998. }
  7999. else {
  8000. m_os << m_indent << "</" << m_tags.back() << ">";
  8001. }
  8002. m_os << std::endl;
  8003. m_tags.pop_back();
  8004. return *this;
  8005. }
  8006. XmlWriter& XmlWriter::writeAttribute( std::string const& name, std::string const& attribute ) {
  8007. if( !name.empty() && !attribute.empty() )
  8008. m_os << ' ' << name << "=\"" << XmlEncode( attribute, XmlEncode::ForAttributes ) << '"';
  8009. return *this;
  8010. }
  8011. XmlWriter& XmlWriter::writeAttribute( std::string const& name, bool attribute ) {
  8012. m_os << ' ' << name << "=\"" << ( attribute ? "true" : "false" ) << '"';
  8013. return *this;
  8014. }
  8015. XmlWriter& XmlWriter::writeText( std::string const& text, bool indent ) {
  8016. if( !text.empty() ){
  8017. bool tagWasOpen = m_tagIsOpen;
  8018. ensureTagClosed();
  8019. if( tagWasOpen && indent )
  8020. m_os << m_indent;
  8021. m_os << XmlEncode( text );
  8022. m_needsNewline = true;
  8023. }
  8024. return *this;
  8025. }
  8026. XmlWriter& XmlWriter::writeComment( std::string const& text ) {
  8027. ensureTagClosed();
  8028. m_os << m_indent << "<!--" << text << "-->";
  8029. m_needsNewline = true;
  8030. return *this;
  8031. }
  8032. void XmlWriter::writeStylesheetRef( std::string const& url ) {
  8033. m_os << "<?xml-stylesheet type=\"text/xsl\" href=\"" << url << "\"?>\n";
  8034. }
  8035. XmlWriter& XmlWriter::writeBlankLine() {
  8036. ensureTagClosed();
  8037. m_os << '\n';
  8038. return *this;
  8039. }
  8040. void XmlWriter::ensureTagClosed() {
  8041. if( m_tagIsOpen ) {
  8042. m_os << ">" << std::endl;
  8043. m_tagIsOpen = false;
  8044. }
  8045. }
  8046. void XmlWriter::writeDeclaration() {
  8047. m_os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
  8048. }
  8049. void XmlWriter::newlineIfNecessary() {
  8050. if( m_needsNewline ) {
  8051. m_os << std::endl;
  8052. m_needsNewline = false;
  8053. }
  8054. }
  8055. }
  8056. // end catch_xmlwriter.cpp
  8057. // start catch_reporter_bases.cpp
  8058. #include <cstring>
  8059. #include <cfloat>
  8060. #include <cstdio>
  8061. #include <assert.h>
  8062. #include <memory>
  8063. namespace Catch {
  8064. void prepareExpandedExpression(AssertionResult& result) {
  8065. result.getExpandedExpression();
  8066. }
  8067. // Because formatting using c++ streams is stateful, drop down to C is required
  8068. // Alternatively we could use stringstream, but its performance is... not good.
  8069. std::string getFormattedDuration( double duration ) {
  8070. // Max exponent + 1 is required to represent the whole part
  8071. // + 1 for decimal point
  8072. // + 3 for the 3 decimal places
  8073. // + 1 for null terminator
  8074. const std::size_t maxDoubleSize = DBL_MAX_10_EXP + 1 + 1 + 3 + 1;
  8075. char buffer[maxDoubleSize];
  8076. // Save previous errno, to prevent sprintf from overwriting it
  8077. ErrnoGuard guard;
  8078. #ifdef _MSC_VER
  8079. sprintf_s(buffer, "%.3f", duration);
  8080. #else
  8081. sprintf(buffer, "%.3f", duration);
  8082. #endif
  8083. return std::string(buffer);
  8084. }
  8085. TestEventListenerBase::TestEventListenerBase(ReporterConfig const & _config)
  8086. :StreamingReporterBase(_config) {}
  8087. void TestEventListenerBase::assertionStarting(AssertionInfo const &) {}
  8088. bool TestEventListenerBase::assertionEnded(AssertionStats const &) {
  8089. return false;
  8090. }
  8091. } // end namespace Catch
  8092. // end catch_reporter_bases.cpp
  8093. // start catch_reporter_compact.cpp
  8094. namespace {
  8095. #ifdef CATCH_PLATFORM_MAC
  8096. const char* failedString() { return "FAILED"; }
  8097. const char* passedString() { return "PASSED"; }
  8098. #else
  8099. const char* failedString() { return "failed"; }
  8100. const char* passedString() { return "passed"; }
  8101. #endif
  8102. // Colour::LightGrey
  8103. Catch::Colour::Code dimColour() { return Catch::Colour::FileName; }
  8104. std::string bothOrAll( std::size_t count ) {
  8105. return count == 1 ? std::string() :
  8106. count == 2 ? "both " : "all " ;
  8107. }
  8108. }
  8109. namespace Catch {
  8110. struct CompactReporter : StreamingReporterBase<CompactReporter> {
  8111. using StreamingReporterBase::StreamingReporterBase;
  8112. ~CompactReporter() override;
  8113. static std::string getDescription() {
  8114. return "Reports test results on a single line, suitable for IDEs";
  8115. }
  8116. ReporterPreferences getPreferences() const override {
  8117. ReporterPreferences prefs;
  8118. prefs.shouldRedirectStdOut = false;
  8119. return prefs;
  8120. }
  8121. void noMatchingTestCases( std::string const& spec ) override {
  8122. stream << "No test cases matched '" << spec << '\'' << std::endl;
  8123. }
  8124. void assertionStarting( AssertionInfo const& ) override {}
  8125. bool assertionEnded( AssertionStats const& _assertionStats ) override {
  8126. AssertionResult const& result = _assertionStats.assertionResult;
  8127. bool printInfoMessages = true;
  8128. // Drop out if result was successful and we're not printing those
  8129. if( !m_config->includeSuccessfulResults() && result.isOk() ) {
  8130. if( result.getResultType() != ResultWas::Warning )
  8131. return false;
  8132. printInfoMessages = false;
  8133. }
  8134. AssertionPrinter printer( stream, _assertionStats, printInfoMessages );
  8135. printer.print();
  8136. stream << std::endl;
  8137. return true;
  8138. }
  8139. void sectionEnded(SectionStats const& _sectionStats) override {
  8140. if (m_config->showDurations() == ShowDurations::Always) {
  8141. stream << getFormattedDuration(_sectionStats.durationInSeconds) << " s: " << _sectionStats.sectionInfo.name << std::endl;
  8142. }
  8143. }
  8144. void testRunEnded( TestRunStats const& _testRunStats ) override {
  8145. printTotals( _testRunStats.totals );
  8146. stream << '\n' << std::endl;
  8147. StreamingReporterBase::testRunEnded( _testRunStats );
  8148. }
  8149. private:
  8150. class AssertionPrinter {
  8151. public:
  8152. AssertionPrinter& operator= ( AssertionPrinter const& ) = delete;
  8153. AssertionPrinter( AssertionPrinter const& ) = delete;
  8154. AssertionPrinter( std::ostream& _stream, AssertionStats const& _stats, bool _printInfoMessages )
  8155. : stream( _stream )
  8156. , result( _stats.assertionResult )
  8157. , messages( _stats.infoMessages )
  8158. , itMessage( _stats.infoMessages.begin() )
  8159. , printInfoMessages( _printInfoMessages )
  8160. {}
  8161. void print() {
  8162. printSourceInfo();
  8163. itMessage = messages.begin();
  8164. switch( result.getResultType() ) {
  8165. case ResultWas::Ok:
  8166. printResultType( Colour::ResultSuccess, passedString() );
  8167. printOriginalExpression();
  8168. printReconstructedExpression();
  8169. if ( ! result.hasExpression() )
  8170. printRemainingMessages( Colour::None );
  8171. else
  8172. printRemainingMessages();
  8173. break;
  8174. case ResultWas::ExpressionFailed:
  8175. if( result.isOk() )
  8176. printResultType( Colour::ResultSuccess, failedString() + std::string( " - but was ok" ) );
  8177. else
  8178. printResultType( Colour::Error, failedString() );
  8179. printOriginalExpression();
  8180. printReconstructedExpression();
  8181. printRemainingMessages();
  8182. break;
  8183. case ResultWas::ThrewException:
  8184. printResultType( Colour::Error, failedString() );
  8185. printIssue( "unexpected exception with message:" );
  8186. printMessage();
  8187. printExpressionWas();
  8188. printRemainingMessages();
  8189. break;
  8190. case ResultWas::FatalErrorCondition:
  8191. printResultType( Colour::Error, failedString() );
  8192. printIssue( "fatal error condition with message:" );
  8193. printMessage();
  8194. printExpressionWas();
  8195. printRemainingMessages();
  8196. break;
  8197. case ResultWas::DidntThrowException:
  8198. printResultType( Colour::Error, failedString() );
  8199. printIssue( "expected exception, got none" );
  8200. printExpressionWas();
  8201. printRemainingMessages();
  8202. break;
  8203. case ResultWas::Info:
  8204. printResultType( Colour::None, "info" );
  8205. printMessage();
  8206. printRemainingMessages();
  8207. break;
  8208. case ResultWas::Warning:
  8209. printResultType( Colour::None, "warning" );
  8210. printMessage();
  8211. printRemainingMessages();
  8212. break;
  8213. case ResultWas::ExplicitFailure:
  8214. printResultType( Colour::Error, failedString() );
  8215. printIssue( "explicitly" );
  8216. printRemainingMessages( Colour::None );
  8217. break;
  8218. // These cases are here to prevent compiler warnings
  8219. case ResultWas::Unknown:
  8220. case ResultWas::FailureBit:
  8221. case ResultWas::Exception:
  8222. printResultType( Colour::Error, "** internal error **" );
  8223. break;
  8224. }
  8225. }
  8226. private:
  8227. void printSourceInfo() const {
  8228. Colour colourGuard( Colour::FileName );
  8229. stream << result.getSourceInfo() << ':';
  8230. }
  8231. void printResultType( Colour::Code colour, std::string const& passOrFail ) const {
  8232. if( !passOrFail.empty() ) {
  8233. {
  8234. Colour colourGuard( colour );
  8235. stream << ' ' << passOrFail;
  8236. }
  8237. stream << ':';
  8238. }
  8239. }
  8240. void printIssue( std::string const& issue ) const {
  8241. stream << ' ' << issue;
  8242. }
  8243. void printExpressionWas() {
  8244. if( result.hasExpression() ) {
  8245. stream << ';';
  8246. {
  8247. Colour colour( dimColour() );
  8248. stream << " expression was:";
  8249. }
  8250. printOriginalExpression();
  8251. }
  8252. }
  8253. void printOriginalExpression() const {
  8254. if( result.hasExpression() ) {
  8255. stream << ' ' << result.getExpression();
  8256. }
  8257. }
  8258. void printReconstructedExpression() const {
  8259. if( result.hasExpandedExpression() ) {
  8260. {
  8261. Colour colour( dimColour() );
  8262. stream << " for: ";
  8263. }
  8264. stream << result.getExpandedExpression();
  8265. }
  8266. }
  8267. void printMessage() {
  8268. if ( itMessage != messages.end() ) {
  8269. stream << " '" << itMessage->message << '\'';
  8270. ++itMessage;
  8271. }
  8272. }
  8273. void printRemainingMessages( Colour::Code colour = dimColour() ) {
  8274. if ( itMessage == messages.end() )
  8275. return;
  8276. // using messages.end() directly yields (or auto) compilation error:
  8277. std::vector<MessageInfo>::const_iterator itEnd = messages.end();
  8278. const std::size_t N = static_cast<std::size_t>( std::distance( itMessage, itEnd ) );
  8279. {
  8280. Colour colourGuard( colour );
  8281. stream << " with " << pluralise( N, "message" ) << ':';
  8282. }
  8283. for(; itMessage != itEnd; ) {
  8284. // If this assertion is a warning ignore any INFO messages
  8285. if( printInfoMessages || itMessage->type != ResultWas::Info ) {
  8286. stream << " '" << itMessage->message << '\'';
  8287. if ( ++itMessage != itEnd ) {
  8288. Colour colourGuard( dimColour() );
  8289. stream << " and";
  8290. }
  8291. }
  8292. }
  8293. }
  8294. private:
  8295. std::ostream& stream;
  8296. AssertionResult const& result;
  8297. std::vector<MessageInfo> messages;
  8298. std::vector<MessageInfo>::const_iterator itMessage;
  8299. bool printInfoMessages;
  8300. };
  8301. // Colour, message variants:
  8302. // - white: No tests ran.
  8303. // - red: Failed [both/all] N test cases, failed [both/all] M assertions.
  8304. // - white: Passed [both/all] N test cases (no assertions).
  8305. // - red: Failed N tests cases, failed M assertions.
  8306. // - green: Passed [both/all] N tests cases with M assertions.
  8307. void printTotals( const Totals& totals ) const {
  8308. if( totals.testCases.total() == 0 ) {
  8309. stream << "No tests ran.";
  8310. }
  8311. else if( totals.testCases.failed == totals.testCases.total() ) {
  8312. Colour colour( Colour::ResultError );
  8313. const std::string qualify_assertions_failed =
  8314. totals.assertions.failed == totals.assertions.total() ?
  8315. bothOrAll( totals.assertions.failed ) : std::string();
  8316. stream <<
  8317. "Failed " << bothOrAll( totals.testCases.failed )
  8318. << pluralise( totals.testCases.failed, "test case" ) << ", "
  8319. "failed " << qualify_assertions_failed <<
  8320. pluralise( totals.assertions.failed, "assertion" ) << '.';
  8321. }
  8322. else if( totals.assertions.total() == 0 ) {
  8323. stream <<
  8324. "Passed " << bothOrAll( totals.testCases.total() )
  8325. << pluralise( totals.testCases.total(), "test case" )
  8326. << " (no assertions).";
  8327. }
  8328. else if( totals.assertions.failed ) {
  8329. Colour colour( Colour::ResultError );
  8330. stream <<
  8331. "Failed " << pluralise( totals.testCases.failed, "test case" ) << ", "
  8332. "failed " << pluralise( totals.assertions.failed, "assertion" ) << '.';
  8333. }
  8334. else {
  8335. Colour colour( Colour::ResultSuccess );
  8336. stream <<
  8337. "Passed " << bothOrAll( totals.testCases.passed )
  8338. << pluralise( totals.testCases.passed, "test case" ) <<
  8339. " with " << pluralise( totals.assertions.passed, "assertion" ) << '.';
  8340. }
  8341. }
  8342. };
  8343. CompactReporter::~CompactReporter() {}
  8344. CATCH_REGISTER_REPORTER( "compact", CompactReporter )
  8345. } // end namespace Catch
  8346. // end catch_reporter_compact.cpp
  8347. // start catch_reporter_console.cpp
  8348. #include <cfloat>
  8349. #include <cstdio>
  8350. namespace Catch {
  8351. namespace {
  8352. std::size_t makeRatio( std::size_t number, std::size_t total ) {
  8353. std::size_t ratio = total > 0 ? CATCH_CONFIG_CONSOLE_WIDTH * number/ total : 0;
  8354. return ( ratio == 0 && number > 0 ) ? 1 : ratio;
  8355. }
  8356. std::size_t& findMax( std::size_t& i, std::size_t& j, std::size_t& k ) {
  8357. if( i > j && i > k )
  8358. return i;
  8359. else if( j > k )
  8360. return j;
  8361. else
  8362. return k;
  8363. }
  8364. struct ColumnInfo {
  8365. enum Justification { Left, Right };
  8366. std::string name;
  8367. int width;
  8368. Justification justification;
  8369. };
  8370. struct ColumnBreak {};
  8371. struct RowBreak {};
  8372. class TablePrinter {
  8373. std::ostream& m_os;
  8374. std::vector<ColumnInfo> m_columnInfos;
  8375. std::ostringstream m_oss;
  8376. int m_currentColumn = -1;
  8377. bool m_isOpen = false;
  8378. public:
  8379. TablePrinter( std::ostream& os, std::vector<ColumnInfo> const& columnInfos )
  8380. : m_os( os ),
  8381. m_columnInfos( columnInfos )
  8382. {}
  8383. auto columnInfos() const -> std::vector<ColumnInfo> const& {
  8384. return m_columnInfos;
  8385. }
  8386. void open() {
  8387. if( !m_isOpen ) {
  8388. m_isOpen = true;
  8389. *this << RowBreak();
  8390. for( auto const& info : m_columnInfos )
  8391. *this << info.name << ColumnBreak();
  8392. *this << RowBreak();
  8393. m_os << Catch::getLineOfChars<'-'>() << "\n";
  8394. }
  8395. }
  8396. void close() {
  8397. if( m_isOpen ) {
  8398. *this << RowBreak();
  8399. m_os << std::endl;
  8400. m_isOpen = false;
  8401. }
  8402. }
  8403. template<typename T>
  8404. friend TablePrinter& operator << ( TablePrinter& tp, T const& value ) {
  8405. tp.m_oss << value;
  8406. return tp;
  8407. }
  8408. friend TablePrinter& operator << ( TablePrinter& tp, ColumnBreak ) {
  8409. auto colStr = tp.m_oss.str();
  8410. // This takes account of utf8 encodings
  8411. auto strSize = Catch::StringRef( colStr ).numberOfCharacters();
  8412. tp.m_oss.str("");
  8413. tp.open();
  8414. if( tp.m_currentColumn == static_cast<int>(tp.m_columnInfos.size()-1) ) {
  8415. tp.m_currentColumn = -1;
  8416. tp.m_os << "\n";
  8417. }
  8418. tp.m_currentColumn++;
  8419. auto colInfo = tp.m_columnInfos[tp.m_currentColumn];
  8420. auto padding = ( strSize+2 < static_cast<std::size_t>( colInfo.width ) )
  8421. ? std::string( colInfo.width-(strSize+2), ' ' )
  8422. : std::string();
  8423. if( colInfo.justification == ColumnInfo::Left )
  8424. tp.m_os << colStr << padding << " ";
  8425. else
  8426. tp.m_os << padding << colStr << " ";
  8427. return tp;
  8428. }
  8429. friend TablePrinter& operator << ( TablePrinter& tp, RowBreak ) {
  8430. if( tp.m_currentColumn > 0 ) {
  8431. tp.m_os << "\n";
  8432. tp.m_currentColumn = -1;
  8433. }
  8434. return tp;
  8435. }
  8436. };
  8437. class Duration {
  8438. enum class Unit {
  8439. Auto,
  8440. Nanoseconds,
  8441. Microseconds,
  8442. Milliseconds,
  8443. Seconds,
  8444. Minutes
  8445. };
  8446. static const uint64_t s_nanosecondsInAMicrosecond = 1000;
  8447. static const uint64_t s_nanosecondsInAMillisecond = 1000*s_nanosecondsInAMicrosecond;
  8448. static const uint64_t s_nanosecondsInASecond = 1000*s_nanosecondsInAMillisecond;
  8449. static const uint64_t s_nanosecondsInAMinute = 60*s_nanosecondsInASecond;
  8450. uint64_t m_inNanoseconds;
  8451. Unit m_units;
  8452. public:
  8453. Duration( uint64_t inNanoseconds, Unit units = Unit::Auto )
  8454. : m_inNanoseconds( inNanoseconds ),
  8455. m_units( units )
  8456. {
  8457. if( m_units == Unit::Auto ) {
  8458. if( m_inNanoseconds < s_nanosecondsInAMicrosecond )
  8459. m_units = Unit::Nanoseconds;
  8460. else if( m_inNanoseconds < s_nanosecondsInAMillisecond )
  8461. m_units = Unit::Microseconds;
  8462. else if( m_inNanoseconds < s_nanosecondsInASecond )
  8463. m_units = Unit::Milliseconds;
  8464. else if( m_inNanoseconds < s_nanosecondsInAMinute )
  8465. m_units = Unit::Seconds;
  8466. else
  8467. m_units = Unit::Minutes;
  8468. }
  8469. }
  8470. auto value() const -> double {
  8471. switch( m_units ) {
  8472. case Unit::Microseconds:
  8473. return m_inNanoseconds / static_cast<double>( s_nanosecondsInAMicrosecond );
  8474. case Unit::Milliseconds:
  8475. return m_inNanoseconds / static_cast<double>( s_nanosecondsInAMillisecond );
  8476. case Unit::Seconds:
  8477. return m_inNanoseconds / static_cast<double>( s_nanosecondsInASecond );
  8478. case Unit::Minutes:
  8479. return m_inNanoseconds / static_cast<double>( s_nanosecondsInAMinute );
  8480. default:
  8481. return static_cast<double>( m_inNanoseconds );
  8482. }
  8483. }
  8484. auto unitsAsString() const -> std::string {
  8485. switch( m_units ) {
  8486. case Unit::Nanoseconds:
  8487. return "ns";
  8488. case Unit::Microseconds:
  8489. return "µs";
  8490. case Unit::Milliseconds:
  8491. return "ms";
  8492. case Unit::Seconds:
  8493. return "s";
  8494. case Unit::Minutes:
  8495. return "m";
  8496. default:
  8497. return "** internal error **";
  8498. }
  8499. }
  8500. friend auto operator << ( std::ostream& os, Duration const& duration ) -> std::ostream& {
  8501. return os << duration.value() << " " << duration.unitsAsString();
  8502. }
  8503. };
  8504. } // end anon namespace
  8505. struct ConsoleReporter : StreamingReporterBase<ConsoleReporter> {
  8506. TablePrinter m_tablePrinter;
  8507. ConsoleReporter( ReporterConfig const& config )
  8508. : StreamingReporterBase( config ),
  8509. m_tablePrinter( config.stream(),
  8510. {
  8511. { "benchmark name", CATCH_CONFIG_CONSOLE_WIDTH-32, ColumnInfo::Left },
  8512. { "iters", 8, ColumnInfo::Right },
  8513. { "elapsed ns", 14, ColumnInfo::Right },
  8514. { "average", 14, ColumnInfo::Right }
  8515. } )
  8516. {}
  8517. ~ConsoleReporter() override;
  8518. static std::string getDescription() {
  8519. return "Reports test results as plain lines of text";
  8520. }
  8521. void noMatchingTestCases( std::string const& spec ) override {
  8522. stream << "No test cases matched '" << spec << '\'' << std::endl;
  8523. }
  8524. void assertionStarting( AssertionInfo const& ) override {
  8525. }
  8526. bool assertionEnded( AssertionStats const& _assertionStats ) override {
  8527. AssertionResult const& result = _assertionStats.assertionResult;
  8528. bool includeResults = m_config->includeSuccessfulResults() || !result.isOk();
  8529. // Drop out if result was successful but we're not printing them.
  8530. if( !includeResults && result.getResultType() != ResultWas::Warning )
  8531. return false;
  8532. lazyPrint();
  8533. AssertionPrinter printer( stream, _assertionStats, includeResults );
  8534. printer.print();
  8535. stream << std::endl;
  8536. return true;
  8537. }
  8538. void sectionStarting( SectionInfo const& _sectionInfo ) override {
  8539. m_headerPrinted = false;
  8540. StreamingReporterBase::sectionStarting( _sectionInfo );
  8541. }
  8542. void sectionEnded( SectionStats const& _sectionStats ) override {
  8543. m_tablePrinter.close();
  8544. if( _sectionStats.missingAssertions ) {
  8545. lazyPrint();
  8546. Colour colour( Colour::ResultError );
  8547. if( m_sectionStack.size() > 1 )
  8548. stream << "\nNo assertions in section";
  8549. else
  8550. stream << "\nNo assertions in test case";
  8551. stream << " '" << _sectionStats.sectionInfo.name << "'\n" << std::endl;
  8552. }
  8553. if( m_config->showDurations() == ShowDurations::Always ) {
  8554. stream << getFormattedDuration(_sectionStats.durationInSeconds) << " s: " << _sectionStats.sectionInfo.name << std::endl;
  8555. }
  8556. if( m_headerPrinted ) {
  8557. m_headerPrinted = false;
  8558. }
  8559. StreamingReporterBase::sectionEnded( _sectionStats );
  8560. }
  8561. void benchmarkStarting( BenchmarkInfo const& info ) override {
  8562. lazyPrintWithoutClosingBenchmarkTable();
  8563. auto nameCol = Column( info.name ).width( m_tablePrinter.columnInfos()[0].width-2 );
  8564. bool firstLine = true;
  8565. for( auto line : nameCol ) {
  8566. if( !firstLine )
  8567. m_tablePrinter << ColumnBreak() << ColumnBreak() << ColumnBreak();
  8568. else
  8569. firstLine = false;
  8570. m_tablePrinter << line << ColumnBreak();
  8571. }
  8572. }
  8573. void benchmarkEnded( BenchmarkStats const& stats ) override {
  8574. Duration average( stats.elapsedTimeInNanoseconds/stats.iterations );
  8575. m_tablePrinter
  8576. << stats.iterations << ColumnBreak()
  8577. << stats.elapsedTimeInNanoseconds << ColumnBreak()
  8578. << average << ColumnBreak();
  8579. }
  8580. void testCaseEnded( TestCaseStats const& _testCaseStats ) override {
  8581. m_tablePrinter.close();
  8582. StreamingReporterBase::testCaseEnded( _testCaseStats );
  8583. m_headerPrinted = false;
  8584. }
  8585. void testGroupEnded( TestGroupStats const& _testGroupStats ) override {
  8586. if( currentGroupInfo.used ) {
  8587. printSummaryDivider();
  8588. stream << "Summary for group '" << _testGroupStats.groupInfo.name << "':\n";
  8589. printTotals( _testGroupStats.totals );
  8590. stream << '\n' << std::endl;
  8591. }
  8592. StreamingReporterBase::testGroupEnded( _testGroupStats );
  8593. }
  8594. void testRunEnded( TestRunStats const& _testRunStats ) override {
  8595. printTotalsDivider( _testRunStats.totals );
  8596. printTotals( _testRunStats.totals );
  8597. stream << std::endl;
  8598. StreamingReporterBase::testRunEnded( _testRunStats );
  8599. }
  8600. private:
  8601. class AssertionPrinter {
  8602. public:
  8603. AssertionPrinter& operator= ( AssertionPrinter const& ) = delete;
  8604. AssertionPrinter( AssertionPrinter const& ) = delete;
  8605. AssertionPrinter( std::ostream& _stream, AssertionStats const& _stats, bool _printInfoMessages )
  8606. : stream( _stream ),
  8607. stats( _stats ),
  8608. result( _stats.assertionResult ),
  8609. colour( Colour::None ),
  8610. message( result.getMessage() ),
  8611. messages( _stats.infoMessages ),
  8612. printInfoMessages( _printInfoMessages )
  8613. {
  8614. switch( result.getResultType() ) {
  8615. case ResultWas::Ok:
  8616. colour = Colour::Success;
  8617. passOrFail = "PASSED";
  8618. //if( result.hasMessage() )
  8619. if( _stats.infoMessages.size() == 1 )
  8620. messageLabel = "with message";
  8621. if( _stats.infoMessages.size() > 1 )
  8622. messageLabel = "with messages";
  8623. break;
  8624. case ResultWas::ExpressionFailed:
  8625. if( result.isOk() ) {
  8626. colour = Colour::Success;
  8627. passOrFail = "FAILED - but was ok";
  8628. }
  8629. else {
  8630. colour = Colour::Error;
  8631. passOrFail = "FAILED";
  8632. }
  8633. if( _stats.infoMessages.size() == 1 )
  8634. messageLabel = "with message";
  8635. if( _stats.infoMessages.size() > 1 )
  8636. messageLabel = "with messages";
  8637. break;
  8638. case ResultWas::ThrewException:
  8639. colour = Colour::Error;
  8640. passOrFail = "FAILED";
  8641. messageLabel = "due to unexpected exception with ";
  8642. if (_stats.infoMessages.size() == 1)
  8643. messageLabel += "message";
  8644. if (_stats.infoMessages.size() > 1)
  8645. messageLabel += "messages";
  8646. break;
  8647. case ResultWas::FatalErrorCondition:
  8648. colour = Colour::Error;
  8649. passOrFail = "FAILED";
  8650. messageLabel = "due to a fatal error condition";
  8651. break;
  8652. case ResultWas::DidntThrowException:
  8653. colour = Colour::Error;
  8654. passOrFail = "FAILED";
  8655. messageLabel = "because no exception was thrown where one was expected";
  8656. break;
  8657. case ResultWas::Info:
  8658. messageLabel = "info";
  8659. break;
  8660. case ResultWas::Warning:
  8661. messageLabel = "warning";
  8662. break;
  8663. case ResultWas::ExplicitFailure:
  8664. passOrFail = "FAILED";
  8665. colour = Colour::Error;
  8666. if( _stats.infoMessages.size() == 1 )
  8667. messageLabel = "explicitly with message";
  8668. if( _stats.infoMessages.size() > 1 )
  8669. messageLabel = "explicitly with messages";
  8670. break;
  8671. // These cases are here to prevent compiler warnings
  8672. case ResultWas::Unknown:
  8673. case ResultWas::FailureBit:
  8674. case ResultWas::Exception:
  8675. passOrFail = "** internal error **";
  8676. colour = Colour::Error;
  8677. break;
  8678. }
  8679. }
  8680. void print() const {
  8681. printSourceInfo();
  8682. if( stats.totals.assertions.total() > 0 ) {
  8683. if( result.isOk() )
  8684. stream << '\n';
  8685. printResultType();
  8686. printOriginalExpression();
  8687. printReconstructedExpression();
  8688. }
  8689. else {
  8690. stream << '\n';
  8691. }
  8692. printMessage();
  8693. }
  8694. private:
  8695. void printResultType() const {
  8696. if( !passOrFail.empty() ) {
  8697. Colour colourGuard( colour );
  8698. stream << passOrFail << ":\n";
  8699. }
  8700. }
  8701. void printOriginalExpression() const {
  8702. if( result.hasExpression() ) {
  8703. Colour colourGuard( Colour::OriginalExpression );
  8704. stream << " ";
  8705. stream << result.getExpressionInMacro();
  8706. stream << '\n';
  8707. }
  8708. }
  8709. void printReconstructedExpression() const {
  8710. if( result.hasExpandedExpression() ) {
  8711. stream << "with expansion:\n";
  8712. Colour colourGuard( Colour::ReconstructedExpression );
  8713. stream << Column( result.getExpandedExpression() ).indent(2) << '\n';
  8714. }
  8715. }
  8716. void printMessage() const {
  8717. if( !messageLabel.empty() )
  8718. stream << messageLabel << ':' << '\n';
  8719. for( auto const& msg : messages ) {
  8720. // If this assertion is a warning ignore any INFO messages
  8721. if( printInfoMessages || msg.type != ResultWas::Info )
  8722. stream << Column( msg.message ).indent(2) << '\n';
  8723. }
  8724. }
  8725. void printSourceInfo() const {
  8726. Colour colourGuard( Colour::FileName );
  8727. stream << result.getSourceInfo() << ": ";
  8728. }
  8729. std::ostream& stream;
  8730. AssertionStats const& stats;
  8731. AssertionResult const& result;
  8732. Colour::Code colour;
  8733. std::string passOrFail;
  8734. std::string messageLabel;
  8735. std::string message;
  8736. std::vector<MessageInfo> messages;
  8737. bool printInfoMessages;
  8738. };
  8739. void lazyPrint() {
  8740. m_tablePrinter.close();
  8741. lazyPrintWithoutClosingBenchmarkTable();
  8742. }
  8743. void lazyPrintWithoutClosingBenchmarkTable() {
  8744. if( !currentTestRunInfo.used )
  8745. lazyPrintRunInfo();
  8746. if( !currentGroupInfo.used )
  8747. lazyPrintGroupInfo();
  8748. if( !m_headerPrinted ) {
  8749. printTestCaseAndSectionHeader();
  8750. m_headerPrinted = true;
  8751. }
  8752. }
  8753. void lazyPrintRunInfo() {
  8754. stream << '\n' << getLineOfChars<'~'>() << '\n';
  8755. Colour colour( Colour::SecondaryText );
  8756. stream << currentTestRunInfo->name
  8757. << " is a Catch v" << libraryVersion() << " host application.\n"
  8758. << "Run with -? for options\n\n";
  8759. if( m_config->rngSeed() != 0 )
  8760. stream << "Randomness seeded to: " << m_config->rngSeed() << "\n\n";
  8761. currentTestRunInfo.used = true;
  8762. }
  8763. void lazyPrintGroupInfo() {
  8764. if( !currentGroupInfo->name.empty() && currentGroupInfo->groupsCounts > 1 ) {
  8765. printClosedHeader( "Group: " + currentGroupInfo->name );
  8766. currentGroupInfo.used = true;
  8767. }
  8768. }
  8769. void printTestCaseAndSectionHeader() {
  8770. assert( !m_sectionStack.empty() );
  8771. printOpenHeader( currentTestCaseInfo->name );
  8772. if( m_sectionStack.size() > 1 ) {
  8773. Colour colourGuard( Colour::Headers );
  8774. auto
  8775. it = m_sectionStack.begin()+1, // Skip first section (test case)
  8776. itEnd = m_sectionStack.end();
  8777. for( ; it != itEnd; ++it )
  8778. printHeaderString( it->name, 2 );
  8779. }
  8780. SourceLineInfo lineInfo = m_sectionStack.back().lineInfo;
  8781. if( !lineInfo.empty() ){
  8782. stream << getLineOfChars<'-'>() << '\n';
  8783. Colour colourGuard( Colour::FileName );
  8784. stream << lineInfo << '\n';
  8785. }
  8786. stream << getLineOfChars<'.'>() << '\n' << std::endl;
  8787. }
  8788. void printClosedHeader( std::string const& _name ) {
  8789. printOpenHeader( _name );
  8790. stream << getLineOfChars<'.'>() << '\n';
  8791. }
  8792. void printOpenHeader( std::string const& _name ) {
  8793. stream << getLineOfChars<'-'>() << '\n';
  8794. {
  8795. Colour colourGuard( Colour::Headers );
  8796. printHeaderString( _name );
  8797. }
  8798. }
  8799. // if string has a : in first line will set indent to follow it on
  8800. // subsequent lines
  8801. void printHeaderString( std::string const& _string, std::size_t indent = 0 ) {
  8802. std::size_t i = _string.find( ": " );
  8803. if( i != std::string::npos )
  8804. i+=2;
  8805. else
  8806. i = 0;
  8807. stream << Column( _string ).indent( indent+i ).initialIndent( indent ) << '\n';
  8808. }
  8809. struct SummaryColumn {
  8810. SummaryColumn( std::string const& _label, Colour::Code _colour )
  8811. : label( _label ),
  8812. colour( _colour )
  8813. {}
  8814. SummaryColumn addRow( std::size_t count ) {
  8815. std::ostringstream oss;
  8816. oss << count;
  8817. std::string row = oss.str();
  8818. for( auto& oldRow : rows ) {
  8819. while( oldRow.size() < row.size() )
  8820. oldRow = ' ' + oldRow;
  8821. while( oldRow.size() > row.size() )
  8822. row = ' ' + row;
  8823. }
  8824. rows.push_back( row );
  8825. return *this;
  8826. }
  8827. std::string label;
  8828. Colour::Code colour;
  8829. std::vector<std::string> rows;
  8830. };
  8831. void printTotals( Totals const& totals ) {
  8832. if( totals.testCases.total() == 0 ) {
  8833. stream << Colour( Colour::Warning ) << "No tests ran\n";
  8834. }
  8835. else if( totals.assertions.total() > 0 && totals.testCases.allPassed() ) {
  8836. stream << Colour( Colour::ResultSuccess ) << "All tests passed";
  8837. stream << " ("
  8838. << pluralise( totals.assertions.passed, "assertion" ) << " in "
  8839. << pluralise( totals.testCases.passed, "test case" ) << ')'
  8840. << '\n';
  8841. }
  8842. else {
  8843. std::vector<SummaryColumn> columns;
  8844. columns.push_back( SummaryColumn( "", Colour::None )
  8845. .addRow( totals.testCases.total() )
  8846. .addRow( totals.assertions.total() ) );
  8847. columns.push_back( SummaryColumn( "passed", Colour::Success )
  8848. .addRow( totals.testCases.passed )
  8849. .addRow( totals.assertions.passed ) );
  8850. columns.push_back( SummaryColumn( "failed", Colour::ResultError )
  8851. .addRow( totals.testCases.failed )
  8852. .addRow( totals.assertions.failed ) );
  8853. columns.push_back( SummaryColumn( "failed as expected", Colour::ResultExpectedFailure )
  8854. .addRow( totals.testCases.failedButOk )
  8855. .addRow( totals.assertions.failedButOk ) );
  8856. printSummaryRow( "test cases", columns, 0 );
  8857. printSummaryRow( "assertions", columns, 1 );
  8858. }
  8859. }
  8860. void printSummaryRow( std::string const& label, std::vector<SummaryColumn> const& cols, std::size_t row ) {
  8861. for( auto col : cols ) {
  8862. std::string value = col.rows[row];
  8863. if( col.label.empty() ) {
  8864. stream << label << ": ";
  8865. if( value != "0" )
  8866. stream << value;
  8867. else
  8868. stream << Colour( Colour::Warning ) << "- none -";
  8869. }
  8870. else if( value != "0" ) {
  8871. stream << Colour( Colour::LightGrey ) << " | ";
  8872. stream << Colour( col.colour )
  8873. << value << ' ' << col.label;
  8874. }
  8875. }
  8876. stream << '\n';
  8877. }
  8878. void printTotalsDivider( Totals const& totals ) {
  8879. if( totals.testCases.total() > 0 ) {
  8880. std::size_t failedRatio = makeRatio( totals.testCases.failed, totals.testCases.total() );
  8881. std::size_t failedButOkRatio = makeRatio( totals.testCases.failedButOk, totals.testCases.total() );
  8882. std::size_t passedRatio = makeRatio( totals.testCases.passed, totals.testCases.total() );
  8883. while( failedRatio + failedButOkRatio + passedRatio < CATCH_CONFIG_CONSOLE_WIDTH-1 )
  8884. findMax( failedRatio, failedButOkRatio, passedRatio )++;
  8885. while( failedRatio + failedButOkRatio + passedRatio > CATCH_CONFIG_CONSOLE_WIDTH-1 )
  8886. findMax( failedRatio, failedButOkRatio, passedRatio )--;
  8887. stream << Colour( Colour::Error ) << std::string( failedRatio, '=' );
  8888. stream << Colour( Colour::ResultExpectedFailure ) << std::string( failedButOkRatio, '=' );
  8889. if( totals.testCases.allPassed() )
  8890. stream << Colour( Colour::ResultSuccess ) << std::string( passedRatio, '=' );
  8891. else
  8892. stream << Colour( Colour::Success ) << std::string( passedRatio, '=' );
  8893. }
  8894. else {
  8895. stream << Colour( Colour::Warning ) << std::string( CATCH_CONFIG_CONSOLE_WIDTH-1, '=' );
  8896. }
  8897. stream << '\n';
  8898. }
  8899. void printSummaryDivider() {
  8900. stream << getLineOfChars<'-'>() << '\n';
  8901. }
  8902. private:
  8903. bool m_headerPrinted = false;
  8904. };
  8905. CATCH_REGISTER_REPORTER( "console", ConsoleReporter )
  8906. ConsoleReporter::~ConsoleReporter() {}
  8907. } // end namespace Catch
  8908. // end catch_reporter_console.cpp
  8909. // start catch_reporter_junit.cpp
  8910. #include <assert.h>
  8911. #include <ctime>
  8912. #include <algorithm>
  8913. namespace Catch {
  8914. namespace {
  8915. std::string getCurrentTimestamp() {
  8916. // Beware, this is not reentrant because of backward compatibility issues
  8917. // Also, UTC only, again because of backward compatibility (%z is C++11)
  8918. time_t rawtime;
  8919. std::time(&rawtime);
  8920. auto const timeStampSize = sizeof("2017-01-16T17:06:45Z");
  8921. #ifdef _MSC_VER
  8922. std::tm timeInfo = {};
  8923. gmtime_s(&timeInfo, &rawtime);
  8924. #else
  8925. std::tm* timeInfo;
  8926. timeInfo = std::gmtime(&rawtime);
  8927. #endif
  8928. char timeStamp[timeStampSize];
  8929. const char * const fmt = "%Y-%m-%dT%H:%M:%SZ";
  8930. #ifdef _MSC_VER
  8931. std::strftime(timeStamp, timeStampSize, fmt, &timeInfo);
  8932. #else
  8933. std::strftime(timeStamp, timeStampSize, fmt, timeInfo);
  8934. #endif
  8935. return std::string(timeStamp);
  8936. }
  8937. std::string fileNameTag(const std::vector<std::string> &tags) {
  8938. auto it = std::find_if(begin(tags),
  8939. end(tags),
  8940. [] (std::string const& tag) {return tag.front() == '#'; });
  8941. if (it != tags.end())
  8942. return it->substr(1);
  8943. return std::string();
  8944. }
  8945. }
  8946. class JunitReporter : public CumulativeReporterBase<JunitReporter> {
  8947. public:
  8948. JunitReporter( ReporterConfig const& _config )
  8949. : CumulativeReporterBase( _config ),
  8950. xml( _config.stream() )
  8951. {
  8952. m_reporterPrefs.shouldRedirectStdOut = true;
  8953. }
  8954. ~JunitReporter() override;
  8955. static std::string getDescription() {
  8956. return "Reports test results in an XML format that looks like Ant's junitreport target";
  8957. }
  8958. void noMatchingTestCases( std::string const& /*spec*/ ) override {}
  8959. void testRunStarting( TestRunInfo const& runInfo ) override {
  8960. CumulativeReporterBase::testRunStarting( runInfo );
  8961. xml.startElement( "testsuites" );
  8962. }
  8963. void testGroupStarting( GroupInfo const& groupInfo ) override {
  8964. suiteTimer.start();
  8965. stdOutForSuite.str("");
  8966. stdErrForSuite.str("");
  8967. unexpectedExceptions = 0;
  8968. CumulativeReporterBase::testGroupStarting( groupInfo );
  8969. }
  8970. void testCaseStarting( TestCaseInfo const& testCaseInfo ) override {
  8971. m_okToFail = testCaseInfo.okToFail();
  8972. }
  8973. bool assertionEnded( AssertionStats const& assertionStats ) override {
  8974. if( assertionStats.assertionResult.getResultType() == ResultWas::ThrewException && !m_okToFail )
  8975. unexpectedExceptions++;
  8976. return CumulativeReporterBase::assertionEnded( assertionStats );
  8977. }
  8978. void testCaseEnded( TestCaseStats const& testCaseStats ) override {
  8979. stdOutForSuite << testCaseStats.stdOut;
  8980. stdErrForSuite << testCaseStats.stdErr;
  8981. CumulativeReporterBase::testCaseEnded( testCaseStats );
  8982. }
  8983. void testGroupEnded( TestGroupStats const& testGroupStats ) override {
  8984. double suiteTime = suiteTimer.getElapsedSeconds();
  8985. CumulativeReporterBase::testGroupEnded( testGroupStats );
  8986. writeGroup( *m_testGroups.back(), suiteTime );
  8987. }
  8988. void testRunEndedCumulative() override {
  8989. xml.endElement();
  8990. }
  8991. void writeGroup( TestGroupNode const& groupNode, double suiteTime ) {
  8992. XmlWriter::ScopedElement e = xml.scopedElement( "testsuite" );
  8993. TestGroupStats const& stats = groupNode.value;
  8994. xml.writeAttribute( "name", stats.groupInfo.name );
  8995. xml.writeAttribute( "errors", unexpectedExceptions );
  8996. xml.writeAttribute( "failures", stats.totals.assertions.failed-unexpectedExceptions );
  8997. xml.writeAttribute( "tests", stats.totals.assertions.total() );
  8998. xml.writeAttribute( "hostname", "tbd" ); // !TBD
  8999. if( m_config->showDurations() == ShowDurations::Never )
  9000. xml.writeAttribute( "time", "" );
  9001. else
  9002. xml.writeAttribute( "time", suiteTime );
  9003. xml.writeAttribute( "timestamp", getCurrentTimestamp() );
  9004. // Write test cases
  9005. for( auto const& child : groupNode.children )
  9006. writeTestCase( *child );
  9007. xml.scopedElement( "system-out" ).writeText( trim( stdOutForSuite.str() ), false );
  9008. xml.scopedElement( "system-err" ).writeText( trim( stdErrForSuite.str() ), false );
  9009. }
  9010. void writeTestCase( TestCaseNode const& testCaseNode ) {
  9011. TestCaseStats const& stats = testCaseNode.value;
  9012. // All test cases have exactly one section - which represents the
  9013. // test case itself. That section may have 0-n nested sections
  9014. assert( testCaseNode.children.size() == 1 );
  9015. SectionNode const& rootSection = *testCaseNode.children.front();
  9016. std::string className = stats.testInfo.className;
  9017. if( className.empty() ) {
  9018. className = fileNameTag(stats.testInfo.tags);
  9019. if ( className.empty() )
  9020. className = "global";
  9021. }
  9022. if ( !m_config->name().empty() )
  9023. className = m_config->name() + "." + className;
  9024. writeSection( className, "", rootSection );
  9025. }
  9026. void writeSection( std::string const& className,
  9027. std::string const& rootName,
  9028. SectionNode const& sectionNode ) {
  9029. std::string name = trim( sectionNode.stats.sectionInfo.name );
  9030. if( !rootName.empty() )
  9031. name = rootName + '/' + name;
  9032. if( !sectionNode.assertions.empty() ||
  9033. !sectionNode.stdOut.empty() ||
  9034. !sectionNode.stdErr.empty() ) {
  9035. XmlWriter::ScopedElement e = xml.scopedElement( "testcase" );
  9036. if( className.empty() ) {
  9037. xml.writeAttribute( "classname", name );
  9038. xml.writeAttribute( "name", "root" );
  9039. }
  9040. else {
  9041. xml.writeAttribute( "classname", className );
  9042. xml.writeAttribute( "name", name );
  9043. }
  9044. xml.writeAttribute( "time", ::Catch::Detail::stringify( sectionNode.stats.durationInSeconds ) );
  9045. writeAssertions( sectionNode );
  9046. if( !sectionNode.stdOut.empty() )
  9047. xml.scopedElement( "system-out" ).writeText( trim( sectionNode.stdOut ), false );
  9048. if( !sectionNode.stdErr.empty() )
  9049. xml.scopedElement( "system-err" ).writeText( trim( sectionNode.stdErr ), false );
  9050. }
  9051. for( auto const& childNode : sectionNode.childSections )
  9052. if( className.empty() )
  9053. writeSection( name, "", *childNode );
  9054. else
  9055. writeSection( className, name, *childNode );
  9056. }
  9057. void writeAssertions( SectionNode const& sectionNode ) {
  9058. for( auto const& assertion : sectionNode.assertions )
  9059. writeAssertion( assertion );
  9060. }
  9061. void writeAssertion( AssertionStats const& stats ) {
  9062. AssertionResult const& result = stats.assertionResult;
  9063. if( !result.isOk() ) {
  9064. std::string elementName;
  9065. switch( result.getResultType() ) {
  9066. case ResultWas::ThrewException:
  9067. case ResultWas::FatalErrorCondition:
  9068. elementName = "error";
  9069. break;
  9070. case ResultWas::ExplicitFailure:
  9071. elementName = "failure";
  9072. break;
  9073. case ResultWas::ExpressionFailed:
  9074. elementName = "failure";
  9075. break;
  9076. case ResultWas::DidntThrowException:
  9077. elementName = "failure";
  9078. break;
  9079. // We should never see these here:
  9080. case ResultWas::Info:
  9081. case ResultWas::Warning:
  9082. case ResultWas::Ok:
  9083. case ResultWas::Unknown:
  9084. case ResultWas::FailureBit:
  9085. case ResultWas::Exception:
  9086. elementName = "internalError";
  9087. break;
  9088. }
  9089. XmlWriter::ScopedElement e = xml.scopedElement( elementName );
  9090. xml.writeAttribute( "message", result.getExpandedExpression() );
  9091. xml.writeAttribute( "type", result.getTestMacroName() );
  9092. std::ostringstream oss;
  9093. if( !result.getMessage().empty() )
  9094. oss << result.getMessage() << '\n';
  9095. for( auto const& msg : stats.infoMessages )
  9096. if( msg.type == ResultWas::Info )
  9097. oss << msg.message << '\n';
  9098. oss << "at " << result.getSourceInfo();
  9099. xml.writeText( oss.str(), false );
  9100. }
  9101. }
  9102. XmlWriter xml;
  9103. Timer suiteTimer;
  9104. std::ostringstream stdOutForSuite;
  9105. std::ostringstream stdErrForSuite;
  9106. unsigned int unexpectedExceptions = 0;
  9107. bool m_okToFail = false;
  9108. };
  9109. JunitReporter::~JunitReporter() {}
  9110. CATCH_REGISTER_REPORTER( "junit", JunitReporter )
  9111. } // end namespace Catch
  9112. // end catch_reporter_junit.cpp
  9113. // start catch_reporter_multi.cpp
  9114. namespace Catch {
  9115. void MultipleReporters::add( IStreamingReporterPtr&& reporter ) {
  9116. m_reporters.push_back( std::move( reporter ) );
  9117. }
  9118. ReporterPreferences MultipleReporters::getPreferences() const {
  9119. return m_reporters[0]->getPreferences();
  9120. }
  9121. std::set<Verbosity> MultipleReporters::getSupportedVerbosities() {
  9122. return std::set<Verbosity>{ };
  9123. }
  9124. void MultipleReporters::noMatchingTestCases( std::string const& spec ) {
  9125. for( auto const& reporter : m_reporters )
  9126. reporter->noMatchingTestCases( spec );
  9127. }
  9128. void MultipleReporters::testRunStarting( TestRunInfo const& testRunInfo ) {
  9129. for( auto const& reporter : m_reporters )
  9130. reporter->testRunStarting( testRunInfo );
  9131. }
  9132. void MultipleReporters::testGroupStarting( GroupInfo const& groupInfo ) {
  9133. for( auto const& reporter : m_reporters )
  9134. reporter->testGroupStarting( groupInfo );
  9135. }
  9136. void MultipleReporters::testCaseStarting( TestCaseInfo const& testInfo ) {
  9137. for( auto const& reporter : m_reporters )
  9138. reporter->testCaseStarting( testInfo );
  9139. }
  9140. void MultipleReporters::sectionStarting( SectionInfo const& sectionInfo ) {
  9141. for( auto const& reporter : m_reporters )
  9142. reporter->sectionStarting( sectionInfo );
  9143. }
  9144. void MultipleReporters::assertionStarting( AssertionInfo const& assertionInfo ) {
  9145. for( auto const& reporter : m_reporters )
  9146. reporter->assertionStarting( assertionInfo );
  9147. }
  9148. // The return value indicates if the messages buffer should be cleared:
  9149. bool MultipleReporters::assertionEnded( AssertionStats const& assertionStats ) {
  9150. bool clearBuffer = false;
  9151. for( auto const& reporter : m_reporters )
  9152. clearBuffer |= reporter->assertionEnded( assertionStats );
  9153. return clearBuffer;
  9154. }
  9155. void MultipleReporters::sectionEnded( SectionStats const& sectionStats ) {
  9156. for( auto const& reporter : m_reporters )
  9157. reporter->sectionEnded( sectionStats );
  9158. }
  9159. void MultipleReporters::testCaseEnded( TestCaseStats const& testCaseStats ) {
  9160. for( auto const& reporter : m_reporters )
  9161. reporter->testCaseEnded( testCaseStats );
  9162. }
  9163. void MultipleReporters::testGroupEnded( TestGroupStats const& testGroupStats ) {
  9164. for( auto const& reporter : m_reporters )
  9165. reporter->testGroupEnded( testGroupStats );
  9166. }
  9167. void MultipleReporters::testRunEnded( TestRunStats const& testRunStats ) {
  9168. for( auto const& reporter : m_reporters )
  9169. reporter->testRunEnded( testRunStats );
  9170. }
  9171. void MultipleReporters::skipTest( TestCaseInfo const& testInfo ) {
  9172. for( auto const& reporter : m_reporters )
  9173. reporter->skipTest( testInfo );
  9174. }
  9175. bool MultipleReporters::isMulti() const {
  9176. return true;
  9177. }
  9178. } // end namespace Catch
  9179. // end catch_reporter_multi.cpp
  9180. // start catch_reporter_xml.cpp
  9181. namespace Catch {
  9182. class XmlReporter : public StreamingReporterBase<XmlReporter> {
  9183. public:
  9184. XmlReporter( ReporterConfig const& _config )
  9185. : StreamingReporterBase( _config ),
  9186. m_xml(_config.stream())
  9187. {
  9188. m_reporterPrefs.shouldRedirectStdOut = true;
  9189. }
  9190. ~XmlReporter() override;
  9191. static std::string getDescription() {
  9192. return "Reports test results as an XML document";
  9193. }
  9194. virtual std::string getStylesheetRef() const {
  9195. return std::string();
  9196. }
  9197. void writeSourceInfo( SourceLineInfo const& sourceInfo ) {
  9198. m_xml
  9199. .writeAttribute( "filename", sourceInfo.file )
  9200. .writeAttribute( "line", sourceInfo.line );
  9201. }
  9202. public: // StreamingReporterBase
  9203. void noMatchingTestCases( std::string const& s ) override {
  9204. StreamingReporterBase::noMatchingTestCases( s );
  9205. }
  9206. void testRunStarting( TestRunInfo const& testInfo ) override {
  9207. StreamingReporterBase::testRunStarting( testInfo );
  9208. std::string stylesheetRef = getStylesheetRef();
  9209. if( !stylesheetRef.empty() )
  9210. m_xml.writeStylesheetRef( stylesheetRef );
  9211. m_xml.startElement( "Catch" );
  9212. if( !m_config->name().empty() )
  9213. m_xml.writeAttribute( "name", m_config->name() );
  9214. }
  9215. void testGroupStarting( GroupInfo const& groupInfo ) override {
  9216. StreamingReporterBase::testGroupStarting( groupInfo );
  9217. m_xml.startElement( "Group" )
  9218. .writeAttribute( "name", groupInfo.name );
  9219. }
  9220. void testCaseStarting( TestCaseInfo const& testInfo ) override {
  9221. StreamingReporterBase::testCaseStarting(testInfo);
  9222. m_xml.startElement( "TestCase" )
  9223. .writeAttribute( "name", trim( testInfo.name ) )
  9224. .writeAttribute( "description", testInfo.description )
  9225. .writeAttribute( "tags", testInfo.tagsAsString() );
  9226. writeSourceInfo( testInfo.lineInfo );
  9227. if ( m_config->showDurations() == ShowDurations::Always )
  9228. m_testCaseTimer.start();
  9229. m_xml.ensureTagClosed();
  9230. }
  9231. void sectionStarting( SectionInfo const& sectionInfo ) override {
  9232. StreamingReporterBase::sectionStarting( sectionInfo );
  9233. if( m_sectionDepth++ > 0 ) {
  9234. m_xml.startElement( "Section" )
  9235. .writeAttribute( "name", trim( sectionInfo.name ) )
  9236. .writeAttribute( "description", sectionInfo.description );
  9237. writeSourceInfo( sectionInfo.lineInfo );
  9238. m_xml.ensureTagClosed();
  9239. }
  9240. }
  9241. void assertionStarting( AssertionInfo const& ) override { }
  9242. bool assertionEnded( AssertionStats const& assertionStats ) override {
  9243. AssertionResult const& result = assertionStats.assertionResult;
  9244. bool includeResults = m_config->includeSuccessfulResults() || !result.isOk();
  9245. if( includeResults ) {
  9246. // Print any info messages in <Info> tags.
  9247. for( auto const& msg : assertionStats.infoMessages ) {
  9248. if( msg.type == ResultWas::Info ) {
  9249. m_xml.scopedElement( "Info" )
  9250. .writeText( msg.message );
  9251. } else if ( msg.type == ResultWas::Warning ) {
  9252. m_xml.scopedElement( "Warning" )
  9253. .writeText( msg.message );
  9254. }
  9255. }
  9256. }
  9257. // Drop out if result was successful but we're not printing them.
  9258. if( !includeResults && result.getResultType() != ResultWas::Warning )
  9259. return true;
  9260. // Print the expression if there is one.
  9261. if( result.hasExpression() ) {
  9262. m_xml.startElement( "Expression" )
  9263. .writeAttribute( "success", result.succeeded() )
  9264. .writeAttribute( "type", result.getTestMacroName() );
  9265. writeSourceInfo( result.getSourceInfo() );
  9266. m_xml.scopedElement( "Original" )
  9267. .writeText( result.getExpression() );
  9268. m_xml.scopedElement( "Expanded" )
  9269. .writeText( result.getExpandedExpression() );
  9270. }
  9271. // And... Print a result applicable to each result type.
  9272. switch( result.getResultType() ) {
  9273. case ResultWas::ThrewException:
  9274. m_xml.startElement( "Exception" );
  9275. writeSourceInfo( result.getSourceInfo() );
  9276. m_xml.writeText( result.getMessage() );
  9277. m_xml.endElement();
  9278. break;
  9279. case ResultWas::FatalErrorCondition:
  9280. m_xml.startElement( "FatalErrorCondition" );
  9281. writeSourceInfo( result.getSourceInfo() );
  9282. m_xml.writeText( result.getMessage() );
  9283. m_xml.endElement();
  9284. break;
  9285. case ResultWas::Info:
  9286. m_xml.scopedElement( "Info" )
  9287. .writeText( result.getMessage() );
  9288. break;
  9289. case ResultWas::Warning:
  9290. // Warning will already have been written
  9291. break;
  9292. case ResultWas::ExplicitFailure:
  9293. m_xml.startElement( "Failure" );
  9294. writeSourceInfo( result.getSourceInfo() );
  9295. m_xml.writeText( result.getMessage() );
  9296. m_xml.endElement();
  9297. break;
  9298. default:
  9299. break;
  9300. }
  9301. if( result.hasExpression() )
  9302. m_xml.endElement();
  9303. return true;
  9304. }
  9305. void sectionEnded( SectionStats const& sectionStats ) override {
  9306. StreamingReporterBase::sectionEnded( sectionStats );
  9307. if( --m_sectionDepth > 0 ) {
  9308. XmlWriter::ScopedElement e = m_xml.scopedElement( "OverallResults" );
  9309. e.writeAttribute( "successes", sectionStats.assertions.passed );
  9310. e.writeAttribute( "failures", sectionStats.assertions.failed );
  9311. e.writeAttribute( "expectedFailures", sectionStats.assertions.failedButOk );
  9312. if ( m_config->showDurations() == ShowDurations::Always )
  9313. e.writeAttribute( "durationInSeconds", sectionStats.durationInSeconds );
  9314. m_xml.endElement();
  9315. }
  9316. }
  9317. void testCaseEnded( TestCaseStats const& testCaseStats ) override {
  9318. StreamingReporterBase::testCaseEnded( testCaseStats );
  9319. XmlWriter::ScopedElement e = m_xml.scopedElement( "OverallResult" );
  9320. e.writeAttribute( "success", testCaseStats.totals.assertions.allOk() );
  9321. if ( m_config->showDurations() == ShowDurations::Always )
  9322. e.writeAttribute( "durationInSeconds", m_testCaseTimer.getElapsedSeconds() );
  9323. if( !testCaseStats.stdOut.empty() )
  9324. m_xml.scopedElement( "StdOut" ).writeText( trim( testCaseStats.stdOut ), false );
  9325. if( !testCaseStats.stdErr.empty() )
  9326. m_xml.scopedElement( "StdErr" ).writeText( trim( testCaseStats.stdErr ), false );
  9327. m_xml.endElement();
  9328. }
  9329. void testGroupEnded( TestGroupStats const& testGroupStats ) override {
  9330. StreamingReporterBase::testGroupEnded( testGroupStats );
  9331. // TODO: Check testGroupStats.aborting and act accordingly.
  9332. m_xml.scopedElement( "OverallResults" )
  9333. .writeAttribute( "successes", testGroupStats.totals.assertions.passed )
  9334. .writeAttribute( "failures", testGroupStats.totals.assertions.failed )
  9335. .writeAttribute( "expectedFailures", testGroupStats.totals.assertions.failedButOk );
  9336. m_xml.endElement();
  9337. }
  9338. void testRunEnded( TestRunStats const& testRunStats ) override {
  9339. StreamingReporterBase::testRunEnded( testRunStats );
  9340. m_xml.scopedElement( "OverallResults" )
  9341. .writeAttribute( "successes", testRunStats.totals.assertions.passed )
  9342. .writeAttribute( "failures", testRunStats.totals.assertions.failed )
  9343. .writeAttribute( "expectedFailures", testRunStats.totals.assertions.failedButOk );
  9344. m_xml.endElement();
  9345. }
  9346. private:
  9347. Timer m_testCaseTimer;
  9348. XmlWriter m_xml;
  9349. int m_sectionDepth = 0;
  9350. };
  9351. XmlReporter::~XmlReporter() {}
  9352. CATCH_REGISTER_REPORTER( "xml", XmlReporter )
  9353. } // end namespace Catch
  9354. // end catch_reporter_xml.cpp
  9355. namespace Catch {
  9356. LeakDetector leakDetector;
  9357. }
  9358. #ifdef __clang__
  9359. #pragma clang diagnostic pop
  9360. #endif
  9361. // end catch_impl.hpp
  9362. #endif
  9363. #ifdef CATCH_CONFIG_MAIN
  9364. // start catch_default_main.hpp
  9365. #ifndef __OBJC__
  9366. #if defined(WIN32) && defined(_UNICODE) && !defined(DO_NOT_USE_WMAIN)
  9367. // Standard C/C++ Win32 Unicode wmain entry point
  9368. extern "C" int wmain (int argc, wchar_t * argv[], wchar_t * []) {
  9369. #else
  9370. // Standard C/C++ main entry point
  9371. int main (int argc, char * argv[]) {
  9372. #endif
  9373. return Catch::Session().run( argc, argv );
  9374. }
  9375. #else // __OBJC__
  9376. // Objective-C entry point
  9377. int main (int argc, char * const argv[]) {
  9378. #if !CATCH_ARC_ENABLED
  9379. NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
  9380. #endif
  9381. Catch::registerTestMethods();
  9382. int result = Catch::Session().run( argc, (char**)argv );
  9383. #if !CATCH_ARC_ENABLED
  9384. [pool drain];
  9385. #endif
  9386. return result;
  9387. }
  9388. #endif // __OBJC__
  9389. // end catch_default_main.hpp
  9390. #endif
  9391. #ifdef CLARA_CONFIG_MAIN_NOT_DEFINED
  9392. # undef CLARA_CONFIG_MAIN
  9393. #endif
  9394. #if !defined(CATCH_CONFIG_DISABLE)
  9395. //////
  9396. // If this config identifier is defined then all CATCH macros are prefixed with CATCH_
  9397. #ifdef CATCH_CONFIG_PREFIX_ALL
  9398. #define CATCH_REQUIRE( ... ) INTERNAL_CATCH_TEST( "CATCH_REQUIRE", Catch::ResultDisposition::Normal, __VA_ARGS__ )
  9399. #define CATCH_REQUIRE_FALSE( ... ) INTERNAL_CATCH_TEST( "CATCH_REQUIRE_FALSE", Catch::ResultDisposition::Normal | Catch::ResultDisposition::FalseTest, __VA_ARGS__ )
  9400. #define CATCH_REQUIRE_THROWS( ... ) INTERNAL_CATCH_THROWS( "CATCH_REQUIRE_THROWS", Catch::ResultDisposition::Normal, "", __VA_ARGS__ )
  9401. #define CATCH_REQUIRE_THROWS_AS( expr, exceptionType ) INTERNAL_CATCH_THROWS_AS( "CATCH_REQUIRE_THROWS_AS", exceptionType, Catch::ResultDisposition::Normal, expr )
  9402. #define CATCH_REQUIRE_THROWS_WITH( expr, matcher ) INTERNAL_CATCH_THROWS_STR_MATCHES( "CATCH_REQUIRE_THROWS_WITH", Catch::ResultDisposition::Normal, matcher, expr )
  9403. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  9404. #define CATCH_REQUIRE_THROWS_MATCHES( expr, exceptionType, matcher ) INTERNAL_CATCH_THROWS_MATCHES( "CATCH_REQUIRE_THROWS_MATCHES", exceptionType, Catch::ResultDisposition::Normal, matcher, expr )
  9405. #endif// CATCH_CONFIG_DISABLE_MATCHERS
  9406. #define CATCH_REQUIRE_NOTHROW( ... ) INTERNAL_CATCH_NO_THROW( "CATCH_REQUIRE_NOTHROW", Catch::ResultDisposition::Normal, __VA_ARGS__ )
  9407. #define CATCH_CHECK( ... ) INTERNAL_CATCH_TEST( "CATCH_CHECK", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  9408. #define CATCH_CHECK_FALSE( ... ) INTERNAL_CATCH_TEST( "CATCH_CHECK_FALSE", Catch::ResultDisposition::ContinueOnFailure | Catch::ResultDisposition::FalseTest, __VA_ARGS__ )
  9409. #define CATCH_CHECKED_IF( ... ) INTERNAL_CATCH_IF( "CATCH_CHECKED_IF", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  9410. #define CATCH_CHECKED_ELSE( ... ) INTERNAL_CATCH_ELSE( "CATCH_CHECKED_ELSE", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  9411. #define CATCH_CHECK_NOFAIL( ... ) INTERNAL_CATCH_TEST( "CATCH_CHECK_NOFAIL", Catch::ResultDisposition::ContinueOnFailure | Catch::ResultDisposition::SuppressFail, __VA_ARGS__ )
  9412. #define CATCH_CHECK_THROWS( ... ) INTERNAL_CATCH_THROWS( "CATCH_CHECK_THROWS", Catch::ResultDisposition::ContinueOnFailure, "", __VA_ARGS__ )
  9413. #define CATCH_CHECK_THROWS_AS( expr, exceptionType ) INTERNAL_CATCH_THROWS_AS( "CATCH_CHECK_THROWS_AS", exceptionType, Catch::ResultDisposition::ContinueOnFailure, expr )
  9414. #define CATCH_CHECK_THROWS_WITH( expr, matcher ) INTERNAL_CATCH_THROWS_STR_MATCHES( "CATCH_CHECK_THROWS_WITH", Catch::ResultDisposition::ContinueOnFailure, matcher, expr )
  9415. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  9416. #define CATCH_CHECK_THROWS_MATCHES( expr, exceptionType, matcher ) INTERNAL_CATCH_THROWS_MATCHES( "CATCH_CHECK_THROWS_MATCHES", exceptionType, Catch::ResultDisposition::ContinueOnFailure, matcher, expr )
  9417. #endif // CATCH_CONFIG_DISABLE_MATCHERS
  9418. #define CATCH_CHECK_NOTHROW( ... ) INTERNAL_CATCH_NO_THROW( "CATCH_CHECK_NOTHROW", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  9419. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  9420. #define CATCH_CHECK_THAT( arg, matcher ) INTERNAL_CHECK_THAT( "CATCH_CHECK_THAT", matcher, Catch::ResultDisposition::ContinueOnFailure, arg )
  9421. #define CATCH_REQUIRE_THAT( arg, matcher ) INTERNAL_CHECK_THAT( "CATCH_REQUIRE_THAT", matcher, Catch::ResultDisposition::Normal, arg )
  9422. #endif // CATCH_CONFIG_DISABLE_MATCHERS
  9423. #define CATCH_INFO( msg ) INTERNAL_CATCH_INFO( "CATCH_INFO", msg )
  9424. #define CATCH_WARN( msg ) INTERNAL_CATCH_MSG( "CATCH_WARN", Catch::ResultWas::Warning, Catch::ResultDisposition::ContinueOnFailure, msg )
  9425. #define CATCH_CAPTURE( msg ) INTERNAL_CATCH_INFO( "CATCH_CAPTURE", #msg " := " << ::Catch::Detail::stringify(msg) )
  9426. #define CATCH_TEST_CASE( ... ) INTERNAL_CATCH_TESTCASE( __VA_ARGS__ )
  9427. #define CATCH_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEST_CASE_METHOD( className, __VA_ARGS__ )
  9428. #define CATCH_METHOD_AS_TEST_CASE( method, ... ) INTERNAL_CATCH_METHOD_AS_TEST_CASE( method, __VA_ARGS__ )
  9429. #define CATCH_REGISTER_TEST_CASE( Function, ... ) INTERNAL_CATCH_REGISTER_TESTCASE( Function, __VA_ARGS__ )
  9430. #define CATCH_SECTION( ... ) INTERNAL_CATCH_SECTION( __VA_ARGS__ )
  9431. #define CATCH_FAIL( ... ) INTERNAL_CATCH_MSG( "CATCH_FAIL", Catch::ResultWas::ExplicitFailure, Catch::ResultDisposition::Normal, __VA_ARGS__ )
  9432. #define CATCH_FAIL_CHECK( ... ) INTERNAL_CATCH_MSG( "CATCH_FAIL_CHECK", Catch::ResultWas::ExplicitFailure, Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  9433. #define CATCH_SUCCEED( ... ) INTERNAL_CATCH_MSG( "CATCH_SUCCEED", Catch::ResultWas::Ok, Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  9434. #define CATCH_ANON_TEST_CASE() INTERNAL_CATCH_TESTCASE()
  9435. // "BDD-style" convenience wrappers
  9436. #define CATCH_SCENARIO( ... ) CATCH_TEST_CASE( "Scenario: " __VA_ARGS__ )
  9437. #define CATCH_SCENARIO_METHOD( className, ... ) INTERNAL_CATCH_TEST_CASE_METHOD( className, "Scenario: " __VA_ARGS__ )
  9438. #define CATCH_GIVEN( desc ) CATCH_SECTION( std::string( "Given: ") + desc )
  9439. #define CATCH_WHEN( desc ) CATCH_SECTION( std::string( " When: ") + desc )
  9440. #define CATCH_AND_WHEN( desc ) CATCH_SECTION( std::string( " And: ") + desc )
  9441. #define CATCH_THEN( desc ) CATCH_SECTION( std::string( " Then: ") + desc )
  9442. #define CATCH_AND_THEN( desc ) CATCH_SECTION( std::string( " And: ") + desc )
  9443. // If CATCH_CONFIG_PREFIX_ALL is not defined then the CATCH_ prefix is not required
  9444. #else
  9445. #define REQUIRE( ... ) INTERNAL_CATCH_TEST( "REQUIRE", Catch::ResultDisposition::Normal, __VA_ARGS__ )
  9446. #define REQUIRE_FALSE( ... ) INTERNAL_CATCH_TEST( "REQUIRE_FALSE", Catch::ResultDisposition::Normal | Catch::ResultDisposition::FalseTest, __VA_ARGS__ )
  9447. #define REQUIRE_THROWS( ... ) INTERNAL_CATCH_THROWS( "REQUIRE_THROWS", Catch::ResultDisposition::Normal, __VA_ARGS__ )
  9448. #define REQUIRE_THROWS_AS( expr, exceptionType ) INTERNAL_CATCH_THROWS_AS( "REQUIRE_THROWS_AS", exceptionType, Catch::ResultDisposition::Normal, expr )
  9449. #define REQUIRE_THROWS_WITH( expr, matcher ) INTERNAL_CATCH_THROWS_STR_MATCHES( "REQUIRE_THROWS_WITH", Catch::ResultDisposition::Normal, matcher, expr )
  9450. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  9451. #define REQUIRE_THROWS_MATCHES( expr, exceptionType, matcher ) INTERNAL_CATCH_THROWS_MATCHES( "REQUIRE_THROWS_MATCHES", exceptionType, Catch::ResultDisposition::Normal, matcher, expr )
  9452. #endif // CATCH_CONFIG_DISABLE_MATCHERS
  9453. #define REQUIRE_NOTHROW( ... ) INTERNAL_CATCH_NO_THROW( "REQUIRE_NOTHROW", Catch::ResultDisposition::Normal, __VA_ARGS__ )
  9454. #define CHECK( ... ) INTERNAL_CATCH_TEST( "CHECK", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  9455. #define CHECK_FALSE( ... ) INTERNAL_CATCH_TEST( "CHECK_FALSE", Catch::ResultDisposition::ContinueOnFailure | Catch::ResultDisposition::FalseTest, __VA_ARGS__ )
  9456. #define CHECKED_IF( ... ) INTERNAL_CATCH_IF( "CHECKED_IF", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  9457. #define CHECKED_ELSE( ... ) INTERNAL_CATCH_ELSE( "CHECKED_ELSE", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  9458. #define CHECK_NOFAIL( ... ) INTERNAL_CATCH_TEST( "CHECK_NOFAIL", Catch::ResultDisposition::ContinueOnFailure | Catch::ResultDisposition::SuppressFail, __VA_ARGS__ )
  9459. #define CHECK_THROWS( ... ) INTERNAL_CATCH_THROWS( "CHECK_THROWS", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  9460. #define CHECK_THROWS_AS( expr, exceptionType ) INTERNAL_CATCH_THROWS_AS( "CHECK_THROWS_AS", exceptionType, Catch::ResultDisposition::ContinueOnFailure, expr )
  9461. #define CHECK_THROWS_WITH( expr, matcher ) INTERNAL_CATCH_THROWS_STR_MATCHES( "CHECK_THROWS_WITH", Catch::ResultDisposition::ContinueOnFailure, matcher, expr )
  9462. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  9463. #define CHECK_THROWS_MATCHES( expr, exceptionType, matcher ) INTERNAL_CATCH_THROWS_MATCHES( "CHECK_THROWS_MATCHES", exceptionType, Catch::ResultDisposition::ContinueOnFailure, matcher, expr )
  9464. #endif // CATCH_CONFIG_DISABLE_MATCHERS
  9465. #define CHECK_NOTHROW( ... ) INTERNAL_CATCH_NO_THROW( "CHECK_NOTHROW", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  9466. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  9467. #define CHECK_THAT( arg, matcher ) INTERNAL_CHECK_THAT( "CHECK_THAT", matcher, Catch::ResultDisposition::ContinueOnFailure, arg )
  9468. #define REQUIRE_THAT( arg, matcher ) INTERNAL_CHECK_THAT( "REQUIRE_THAT", matcher, Catch::ResultDisposition::Normal, arg )
  9469. #endif // CATCH_CONFIG_DISABLE_MATCHERS
  9470. #define INFO( msg ) INTERNAL_CATCH_INFO( "INFO", msg )
  9471. #define WARN( msg ) INTERNAL_CATCH_MSG( "WARN", Catch::ResultWas::Warning, Catch::ResultDisposition::ContinueOnFailure, msg )
  9472. #define CAPTURE( msg ) INTERNAL_CATCH_INFO( "CAPTURE", #msg " := " << ::Catch::Detail::stringify(msg) )
  9473. #define TEST_CASE( ... ) INTERNAL_CATCH_TESTCASE( __VA_ARGS__ )
  9474. #define TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEST_CASE_METHOD( className, __VA_ARGS__ )
  9475. #define METHOD_AS_TEST_CASE( method, ... ) INTERNAL_CATCH_METHOD_AS_TEST_CASE( method, __VA_ARGS__ )
  9476. #define REGISTER_TEST_CASE( Function, ... ) INTERNAL_CATCH_REGISTER_TESTCASE( Function, __VA_ARGS__ )
  9477. #define SECTION( ... ) INTERNAL_CATCH_SECTION( __VA_ARGS__ )
  9478. #define FAIL( ... ) INTERNAL_CATCH_MSG( "FAIL", Catch::ResultWas::ExplicitFailure, Catch::ResultDisposition::Normal, __VA_ARGS__ )
  9479. #define FAIL_CHECK( ... ) INTERNAL_CATCH_MSG( "FAIL_CHECK", Catch::ResultWas::ExplicitFailure, Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  9480. #define SUCCEED( ... ) INTERNAL_CATCH_MSG( "SUCCEED", Catch::ResultWas::Ok, Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  9481. #define ANON_TEST_CASE() INTERNAL_CATCH_TESTCASE()
  9482. #endif
  9483. #define CATCH_TRANSLATE_EXCEPTION( signature ) INTERNAL_CATCH_TRANSLATE_EXCEPTION( signature )
  9484. // "BDD-style" convenience wrappers
  9485. #define SCENARIO( ... ) TEST_CASE( "Scenario: " __VA_ARGS__ )
  9486. #define SCENARIO_METHOD( className, ... ) INTERNAL_CATCH_TEST_CASE_METHOD( className, "Scenario: " __VA_ARGS__ )
  9487. #define GIVEN( desc ) SECTION( std::string(" Given: ") + desc )
  9488. #define WHEN( desc ) SECTION( std::string(" When: ") + desc )
  9489. #define AND_WHEN( desc ) SECTION( std::string("And when: ") + desc )
  9490. #define THEN( desc ) SECTION( std::string(" Then: ") + desc )
  9491. #define AND_THEN( desc ) SECTION( std::string(" And: ") + desc )
  9492. using Catch::Detail::Approx;
  9493. #else
  9494. //////
  9495. // If this config identifier is defined then all CATCH macros are prefixed with CATCH_
  9496. #ifdef CATCH_CONFIG_PREFIX_ALL
  9497. #define CATCH_REQUIRE( ... ) (void)(0)
  9498. #define CATCH_REQUIRE_FALSE( ... ) (void)(0)
  9499. #define CATCH_REQUIRE_THROWS( ... ) (void)(0)
  9500. #define CATCH_REQUIRE_THROWS_AS( expr, exceptionType ) (void)(0)
  9501. #define CATCH_REQUIRE_THROWS_WITH( expr, matcher ) (void)(0)
  9502. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  9503. #define CATCH_REQUIRE_THROWS_MATCHES( expr, exceptionType, matcher ) (void)(0)
  9504. #endif// CATCH_CONFIG_DISABLE_MATCHERS
  9505. #define CATCH_REQUIRE_NOTHROW( ... ) (void)(0)
  9506. #define CATCH_CHECK( ... ) (void)(0)
  9507. #define CATCH_CHECK_FALSE( ... ) (void)(0)
  9508. #define CATCH_CHECKED_IF( ... ) if (__VA_ARGS__)
  9509. #define CATCH_CHECKED_ELSE( ... ) if (!(__VA_ARGS__))
  9510. #define CATCH_CHECK_NOFAIL( ... ) (void)(0)
  9511. #define CATCH_CHECK_THROWS( ... ) (void)(0)
  9512. #define CATCH_CHECK_THROWS_AS( expr, exceptionType ) (void)(0)
  9513. #define CATCH_CHECK_THROWS_WITH( expr, matcher ) (void)(0)
  9514. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  9515. #define CATCH_CHECK_THROWS_MATCHES( expr, exceptionType, matcher ) (void)(0)
  9516. #endif // CATCH_CONFIG_DISABLE_MATCHERS
  9517. #define CATCH_CHECK_NOTHROW( ... ) (void)(0)
  9518. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  9519. #define CATCH_CHECK_THAT( arg, matcher ) (void)(0)
  9520. #define CATCH_REQUIRE_THAT( arg, matcher ) (void)(0)
  9521. #endif // CATCH_CONFIG_DISABLE_MATCHERS
  9522. #define CATCH_INFO( msg ) (void)(0)
  9523. #define CATCH_WARN( msg ) (void)(0)
  9524. #define CATCH_CAPTURE( msg ) (void)(0)
  9525. #define CATCH_TEST_CASE( ... ) INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ))
  9526. #define CATCH_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ))
  9527. #define CATCH_METHOD_AS_TEST_CASE( method, ... )
  9528. #define CATCH_REGISTER_TEST_CASE( Function, ... ) (void)(0)
  9529. #define CATCH_SECTION( ... )
  9530. #define CATCH_FAIL( ... ) (void)(0)
  9531. #define CATCH_FAIL_CHECK( ... ) (void)(0)
  9532. #define CATCH_SUCCEED( ... ) (void)(0)
  9533. #define CATCH_ANON_TEST_CASE() INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ))
  9534. // "BDD-style" convenience wrappers
  9535. #define CATCH_SCENARIO( ... ) INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ))
  9536. #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 )
  9537. #define CATCH_GIVEN( desc )
  9538. #define CATCH_WHEN( desc )
  9539. #define CATCH_AND_WHEN( desc )
  9540. #define CATCH_THEN( desc )
  9541. #define CATCH_AND_THEN( desc )
  9542. // If CATCH_CONFIG_PREFIX_ALL is not defined then the CATCH_ prefix is not required
  9543. #else
  9544. #define REQUIRE( ... ) (void)(0)
  9545. #define REQUIRE_FALSE( ... ) (void)(0)
  9546. #define REQUIRE_THROWS( ... ) (void)(0)
  9547. #define REQUIRE_THROWS_AS( expr, exceptionType ) (void)(0)
  9548. #define REQUIRE_THROWS_WITH( expr, matcher ) (void)(0)
  9549. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  9550. #define REQUIRE_THROWS_MATCHES( expr, exceptionType, matcher ) (void)(0)
  9551. #endif // CATCH_CONFIG_DISABLE_MATCHERS
  9552. #define REQUIRE_NOTHROW( ... ) (void)(0)
  9553. #define CHECK( ... ) (void)(0)
  9554. #define CHECK_FALSE( ... ) (void)(0)
  9555. #define CHECKED_IF( ... ) if (__VA_ARGS__)
  9556. #define CHECKED_ELSE( ... ) if (!(__VA_ARGS__))
  9557. #define CHECK_NOFAIL( ... ) (void)(0)
  9558. #define CHECK_THROWS( ... ) (void)(0)
  9559. #define CHECK_THROWS_AS( expr, exceptionType ) (void)(0)
  9560. #define CHECK_THROWS_WITH( expr, matcher ) (void)(0)
  9561. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  9562. #define CHECK_THROWS_MATCHES( expr, exceptionType, matcher ) (void)(0)
  9563. #endif // CATCH_CONFIG_DISABLE_MATCHERS
  9564. #define CHECK_NOTHROW( ... ) (void)(0)
  9565. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  9566. #define CHECK_THAT( arg, matcher ) (void)(0)
  9567. #define REQUIRE_THAT( arg, matcher ) (void)(0)
  9568. #endif // CATCH_CONFIG_DISABLE_MATCHERS
  9569. #define INFO( msg ) (void)(0)
  9570. #define WARN( msg ) (void)(0)
  9571. #define CAPTURE( msg ) (void)(0)
  9572. #define TEST_CASE( ... ) INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ))
  9573. #define TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ))
  9574. #define METHOD_AS_TEST_CASE( method, ... )
  9575. #define REGISTER_TEST_CASE( Function, ... ) (void)(0)
  9576. #define SECTION( ... )
  9577. #define FAIL( ... ) (void)(0)
  9578. #define FAIL_CHECK( ... ) (void)(0)
  9579. #define SUCCEED( ... ) (void)(0)
  9580. #define ANON_TEST_CASE() INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ))
  9581. #endif
  9582. #define CATCH_TRANSLATE_EXCEPTION( signature ) INTERNAL_CATCH_TRANSLATE_EXCEPTION_NO_REG( INTERNAL_CATCH_UNIQUE_NAME( catch_internal_ExceptionTranslator ), signature )
  9583. // "BDD-style" convenience wrappers
  9584. #define SCENARIO( ... ) INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ) )
  9585. #define SCENARIO_METHOD( className, ... ) INTERNAL_CATCH_TESTCASE_METHOD_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ), className )
  9586. #define GIVEN( desc )
  9587. #define WHEN( desc )
  9588. #define AND_WHEN( desc )
  9589. #define THEN( desc )
  9590. #define AND_THEN( desc )
  9591. using Catch::Detail::Approx;
  9592. #endif
  9593. // start catch_reenable_warnings.h
  9594. #ifdef __clang__
  9595. # ifdef __ICC // icpc defines the __clang__ macro
  9596. # pragma warning(pop)
  9597. # else
  9598. # pragma clang diagnostic pop
  9599. # endif
  9600. #elif defined __GNUC__
  9601. # pragma GCC diagnostic pop
  9602. #endif
  9603. // end catch_reenable_warnings.h
  9604. // end catch.hpp
  9605. #endif // TWOBLUECUBES_SINGLE_INCLUDE_CATCH_HPP_INCLUDED