Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

11690 linhas
409KB

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