1 /*
2 * Catch v2.9.2
3 * Generated: 2019-08-08 13:35:12.279703
4 * ----------------------------------------------------------
5 * This file has been merged from multiple headers. Please don't edit it directly
6 * Copyright (c) 2019 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
15 #define CATCH_VERSION_MAJOR 2
16 #define CATCH_VERSION_MINOR 9
17 #define CATCH_VERSION_PATCH 2
18
19 #ifdef __clang__
20 # pragma clang system_header
21 #elif defined __GNUC__
22 # pragma GCC system_header
23 #endif
24
25 // start catch_suppress_warnings.h
26
27 #ifdef __clang__
28 # ifdef __ICC // icpc defines the __clang__ macro
29 # pragma warning(push)
30 # pragma warning(disable: 161 1682)
31 # else // __ICC
32 # pragma clang diagnostic push
33 # pragma clang diagnostic ignored "-Wpadded"
34 # pragma clang diagnostic ignored "-Wswitch-enum"
35 # pragma clang diagnostic ignored "-Wcovered-switch-default"
36 # endif
37 #elif defined __GNUC__
38 // Because REQUIREs trigger GCC's -Wparentheses, and because still
39 // supported version of g++ have only buggy support for _Pragmas,
40 // Wparentheses have to be suppressed globally.
41 # pragma GCC diagnostic ignored "-Wparentheses" // See #674 for details
42
43 # pragma GCC diagnostic push
44 # pragma GCC diagnostic ignored "-Wunused-variable"
45 # pragma GCC diagnostic ignored "-Wpadded"
46 #endif
47 // end catch_suppress_warnings.h
48 #if defined(CATCH_CONFIG_MAIN) || defined(CATCH_CONFIG_RUNNER)
49 # define CATCH_IMPL
50 # define CATCH_CONFIG_ALL_PARTS
51 #endif
52
53 // In the impl file, we want to have access to all parts of the headers
54 // Can also be used to sanely support PCHs
55 #if defined(CATCH_CONFIG_ALL_PARTS)
56 # define CATCH_CONFIG_EXTERNAL_INTERFACES
57 # if defined(CATCH_CONFIG_DISABLE_MATCHERS)
58 # undef CATCH_CONFIG_DISABLE_MATCHERS
59 # endif
60 # if !defined(CATCH_CONFIG_ENABLE_CHRONO_STRINGMAKER)
61 # define CATCH_CONFIG_ENABLE_CHRONO_STRINGMAKER
62 # endif
63 #endif
64
65 #if !defined(CATCH_CONFIG_IMPL_ONLY)
66 // start catch_platform.h
67
68 #ifdef __APPLE__
69 # include <TargetConditionals.h>
70 # if TARGET_OS_OSX == 1
71 # define CATCH_PLATFORM_MAC
72 # elif TARGET_OS_IPHONE == 1
73 # define CATCH_PLATFORM_IPHONE
74 # endif
75
76 #elif defined(linux) || defined(__linux) || defined(__linux__) || defined(__FreeBSD__)
77 # define CATCH_PLATFORM_LINUX
78
79 #elif defined(WIN32) || defined(__WIN32__) || defined(_WIN32) || defined(_MSC_VER) || defined(__MINGW32__)
80 # define CATCH_PLATFORM_WINDOWS
81 #endif
82
83 // end catch_platform.h
84
85 #ifdef CATCH_IMPL
86 # ifndef CLARA_CONFIG_MAIN
87 # define CLARA_CONFIG_MAIN_NOT_DEFINED
88 # define CLARA_CONFIG_MAIN
89 # endif
90 #endif
91
92 // start catch_user_interfaces.h
93
94 namespace Catch {
95 unsigned int rngSeed();
96 }
97
98 // end catch_user_interfaces.h
99 // start catch_tag_alias_autoregistrar.h
100
101 // start catch_common.h
102
103 // start catch_compiler_capabilities.h
104
105 // Detect a number of compiler features - by compiler
106 // The following features are defined:
107 //
108 // CATCH_CONFIG_COUNTER : is the __COUNTER__ macro supported?
109 // CATCH_CONFIG_WINDOWS_SEH : is Windows SEH supported?
110 // CATCH_CONFIG_POSIX_SIGNALS : are POSIX signals supported?
111 // CATCH_CONFIG_DISABLE_EXCEPTIONS : Are exceptions enabled?
112 // ****************
113 // Note to maintainers: if new toggles are added please document them
114 // in configuration.md, too
115 // ****************
116
117 // In general each macro has a _NO_<feature name> form
118 // (e.g. CATCH_CONFIG_NO_POSIX_SIGNALS) which disables the feature.
119 // Many features, at point of detection, define an _INTERNAL_ macro, so they
120 // can be combined, en-mass, with the _NO_ forms later.
121
122 #ifdef __cplusplus
123
124 # if (__cplusplus >= 201402L) || (defined(_MSVC_LANG) && _MSVC_LANG >= 201402L)
125 # define CATCH_CPP14_OR_GREATER
126 # endif
127
128 # if (__cplusplus >= 201703L) || (defined(_MSVC_LANG) && _MSVC_LANG >= 201703L)
129 # define CATCH_CPP17_OR_GREATER
130 # endif
131
132 #endif
133
134 #if defined(CATCH_CPP17_OR_GREATER)
135 # define CATCH_INTERNAL_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS
136 #endif
137
138 #ifdef __clang__
139
140 # define CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
141 _Pragma( "clang diagnostic push" ) \
142 _Pragma( "clang diagnostic ignored \"-Wexit-time-destructors\"" ) \
143 _Pragma( "clang diagnostic ignored \"-Wglobal-constructors\"")
144 # define CATCH_INTERNAL_UNSUPPRESS_GLOBALS_WARNINGS \
145 _Pragma( "clang diagnostic pop" )
146
147 # define CATCH_INTERNAL_SUPPRESS_PARENTHESES_WARNINGS \
148 _Pragma( "clang diagnostic push" ) \
149 _Pragma( "clang diagnostic ignored \"-Wparentheses\"" )
150 # define CATCH_INTERNAL_UNSUPPRESS_PARENTHESES_WARNINGS \
151 _Pragma( "clang diagnostic pop" )
152
153 # define CATCH_INTERNAL_SUPPRESS_UNUSED_WARNINGS \
154 _Pragma( "clang diagnostic push" ) \
155 _Pragma( "clang diagnostic ignored \"-Wunused-variable\"" )
156 # define CATCH_INTERNAL_UNSUPPRESS_UNUSED_WARNINGS \
157 _Pragma( "clang diagnostic pop" )
158
159 # define CATCH_INTERNAL_SUPPRESS_ZERO_VARIADIC_WARNINGS \
160 _Pragma( "clang diagnostic push" ) \
161 _Pragma( "clang diagnostic ignored \"-Wgnu-zero-variadic-macro-arguments\"" )
162 # define CATCH_INTERNAL_UNSUPPRESS_ZERO_VARIADIC_WARNINGS \
163 _Pragma( "clang diagnostic pop" )
164
165 #endif // __clang__
166
167 ////////////////////////////////////////////////////////////////////////////////
168 // Assume that non-Windows platforms support posix signals by default
169 #if !defined(CATCH_PLATFORM_WINDOWS)
170 #define CATCH_INTERNAL_CONFIG_POSIX_SIGNALS
171 #endif
172
173 ////////////////////////////////////////////////////////////////////////////////
174 // We know some environments not to support full POSIX signals
175 #if defined(__CYGWIN__) || defined(__QNX__) || defined(__EMSCRIPTEN__) || defined(__DJGPP__)
176 #define CATCH_INTERNAL_CONFIG_NO_POSIX_SIGNALS
177 #endif
178
179 #ifdef __OS400__
180 # define CATCH_INTERNAL_CONFIG_NO_POSIX_SIGNALS
181 # define CATCH_CONFIG_COLOUR_NONE
182 #endif
183
184 ////////////////////////////////////////////////////////////////////////////////
185 // Android somehow still does not support std::to_string
186 #if defined(__ANDROID__)
187 # define CATCH_INTERNAL_CONFIG_NO_CPP11_TO_STRING
188 #endif
189
190 ////////////////////////////////////////////////////////////////////////////////
191 // Not all Windows environments support SEH properly
192 #if defined(__MINGW32__)
193 # define CATCH_INTERNAL_CONFIG_NO_WINDOWS_SEH
194 #endif
195
196 ////////////////////////////////////////////////////////////////////////////////
197 // PS4
198 #if defined(__ORBIS__)
199 # define CATCH_INTERNAL_CONFIG_NO_NEW_CAPTURE
200 #endif
201
202 ////////////////////////////////////////////////////////////////////////////////
203 // Cygwin
204 #ifdef __CYGWIN__
205
206 // Required for some versions of Cygwin to declare gettimeofday
207 // see: http://stackoverflow.com/questions/36901803/gettimeofday-not-declared-in-this-scope-cygwin
208 # define _BSD_SOURCE
209 // some versions of cygwin (most) do not support std::to_string. Use the libstd check.
210 // https://gcc.gnu.org/onlinedocs/gcc-4.8.2/libstdc++/api/a01053_source.html line 2812-2813
211 # if !((__cplusplus >= 201103L) && defined(_GLIBCXX_USE_C99) \
212 && !defined(_GLIBCXX_HAVE_BROKEN_VSWPRINTF))
213
214 # define CATCH_INTERNAL_CONFIG_NO_CPP11_TO_STRING
215
216 # endif
217 #endif // __CYGWIN__
218
219 ////////////////////////////////////////////////////////////////////////////////
220 // Visual C++
221 #ifdef _MSC_VER
222
223 # if _MSC_VER >= 1900 // Visual Studio 2015 or newer
224 # define CATCH_INTERNAL_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS
225 # endif
226
227 // Universal Windows platform does not support SEH
228 // Or console colours (or console at all...)
229 # if defined(WINAPI_FAMILY) && (WINAPI_FAMILY == WINAPI_FAMILY_APP)
230 # define CATCH_CONFIG_COLOUR_NONE
231 # else
232 # define CATCH_INTERNAL_CONFIG_WINDOWS_SEH
233 # endif
234
235 // MSVC traditional preprocessor needs some workaround for __VA_ARGS__
236 // _MSVC_TRADITIONAL == 0 means new conformant preprocessor
237 // _MSVC_TRADITIONAL == 1 means old traditional non-conformant preprocessor
238 # if !defined(_MSVC_TRADITIONAL) || (defined(_MSVC_TRADITIONAL) && _MSVC_TRADITIONAL)
239 # define CATCH_INTERNAL_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
240 # endif
241 #endif // _MSC_VER
242
243 #if defined(_REENTRANT) || defined(_MSC_VER)
244 // Enable async processing, as -pthread is specified or no additional linking is required
245 # define CATCH_INTERNAL_CONFIG_USE_ASYNC
246 #endif // _MSC_VER
247
248 ////////////////////////////////////////////////////////////////////////////////
249 // Check if we are compiled with -fno-exceptions or equivalent
250 #if defined(__EXCEPTIONS) || defined(__cpp_exceptions) || defined(_CPPUNWIND)
251 # define CATCH_INTERNAL_CONFIG_EXCEPTIONS_ENABLED
252 #endif
253
254 ////////////////////////////////////////////////////////////////////////////////
255 // DJGPP
256 #ifdef __DJGPP__
257 # define CATCH_INTERNAL_CONFIG_NO_WCHAR
258 #endif // __DJGPP__
259
260 ////////////////////////////////////////////////////////////////////////////////
261 // Embarcadero C++Build
262 #if defined(__BORLANDC__)
263 #define CATCH_INTERNAL_CONFIG_POLYFILL_ISNAN
264 #endif
265
266 ////////////////////////////////////////////////////////////////////////////////
267
268 // Use of __COUNTER__ is suppressed during code analysis in
269 // CLion/AppCode 2017.2.x and former, because __COUNTER__ is not properly
270 // handled by it.
271 // Otherwise all supported compilers support COUNTER macro,
272 // but user still might want to turn it off
273 #if ( !defined(__JETBRAINS_IDE__) || __JETBRAINS_IDE__ >= 20170300L )
274 #define CATCH_INTERNAL_CONFIG_COUNTER
275 #endif
276
277 ////////////////////////////////////////////////////////////////////////////////
278
279 // RTX is a special version of Windows that is real time.
280 // This means that it is detected as Windows, but does not provide
281 // the same set of capabilities as real Windows does.
282 #if defined(UNDER_RTSS) || defined(RTX64_BUILD)
283 #define CATCH_INTERNAL_CONFIG_NO_WINDOWS_SEH
284 #define CATCH_INTERNAL_CONFIG_NO_ASYNC
285 #define CATCH_CONFIG_COLOUR_NONE
286 #endif
287
288 ////////////////////////////////////////////////////////////////////////////////
289 // Check if string_view is available and usable
290 // The check is split apart to work around v140 (VS2015) preprocessor issue...
291 #if defined(__has_include)
292 #if __has_include(<string_view>) && defined(CATCH_CPP17_OR_GREATER)
293 # define CATCH_INTERNAL_CONFIG_CPP17_STRING_VIEW
294 #endif
295 #endif
296
297 ////////////////////////////////////////////////////////////////////////////////
298 // Check if optional is available and usable
299 #if defined(__has_include)
300 # if __has_include(<optional>) && defined(CATCH_CPP17_OR_GREATER)
301 # define CATCH_INTERNAL_CONFIG_CPP17_OPTIONAL
302 # endif // __has_include(<optional>) && defined(CATCH_CPP17_OR_GREATER)
303 #endif // __has_include
304
305 ////////////////////////////////////////////////////////////////////////////////
306 // Check if byte is available and usable
307 #if defined(__has_include)
308 # if __has_include(<cstddef>) && defined(CATCH_CPP17_OR_GREATER)
309 # define CATCH_INTERNAL_CONFIG_CPP17_BYTE
310 # endif // __has_include(<cstddef>) && defined(CATCH_CPP17_OR_GREATER)
311 #endif // __has_include
312
313 ////////////////////////////////////////////////////////////////////////////////
314 // Check if variant is available and usable
315 #if defined(__has_include)
316 # if __has_include(<variant>) && defined(CATCH_CPP17_OR_GREATER)
317 # if defined(__clang__) && (__clang_major__ < 8)
318 // work around clang bug with libstdc++ https://bugs.llvm.org/show_bug.cgi?id=31852
319 // fix should be in clang 8, workaround in libstdc++ 8.2
320 # include <ciso646>
321 # if defined(__GLIBCXX__) && defined(_GLIBCXX_RELEASE) && (_GLIBCXX_RELEASE < 9)
322 # define CATCH_CONFIG_NO_CPP17_VARIANT
323 # else
324 # define CATCH_INTERNAL_CONFIG_CPP17_VARIANT
325 # endif // defined(__GLIBCXX__) && defined(_GLIBCXX_RELEASE) && (_GLIBCXX_RELEASE < 9)
326 # else
327 # define CATCH_INTERNAL_CONFIG_CPP17_VARIANT
328 # endif // defined(__clang__) && (__clang_major__ < 8)
329 # endif // __has_include(<variant>) && defined(CATCH_CPP17_OR_GREATER)
330 #endif // __has_include
331
332 #if defined(CATCH_INTERNAL_CONFIG_COUNTER) && !defined(CATCH_CONFIG_NO_COUNTER) && !defined(CATCH_CONFIG_COUNTER)
333 # define CATCH_CONFIG_COUNTER
334 #endif
335 #if defined(CATCH_INTERNAL_CONFIG_WINDOWS_SEH) && !defined(CATCH_CONFIG_NO_WINDOWS_SEH) && !defined(CATCH_CONFIG_WINDOWS_SEH) && !defined(CATCH_INTERNAL_CONFIG_NO_WINDOWS_SEH)
336 # define CATCH_CONFIG_WINDOWS_SEH
337 #endif
338 // This is set by default, because we assume that unix compilers are posix-signal-compatible by default.
339 #if defined(CATCH_INTERNAL_CONFIG_POSIX_SIGNALS) && !defined(CATCH_INTERNAL_CONFIG_NO_POSIX_SIGNALS) && !defined(CATCH_CONFIG_NO_POSIX_SIGNALS) && !defined(CATCH_CONFIG_POSIX_SIGNALS)
340 # define CATCH_CONFIG_POSIX_SIGNALS
341 #endif
342 // This is set by default, because we assume that compilers with no wchar_t support are just rare exceptions.
343 #if !defined(CATCH_INTERNAL_CONFIG_NO_WCHAR) && !defined(CATCH_CONFIG_NO_WCHAR) && !defined(CATCH_CONFIG_WCHAR)
344 # define CATCH_CONFIG_WCHAR
345 #endif
346
347 #if !defined(CATCH_INTERNAL_CONFIG_NO_CPP11_TO_STRING) && !defined(CATCH_CONFIG_NO_CPP11_TO_STRING) && !defined(CATCH_CONFIG_CPP11_TO_STRING)
348 # define CATCH_CONFIG_CPP11_TO_STRING
349 #endif
350
351 #if defined(CATCH_INTERNAL_CONFIG_CPP17_OPTIONAL) && !defined(CATCH_CONFIG_NO_CPP17_OPTIONAL) && !defined(CATCH_CONFIG_CPP17_OPTIONAL)
352 # define CATCH_CONFIG_CPP17_OPTIONAL
353 #endif
354
355 #if defined(CATCH_INTERNAL_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS) && !defined(CATCH_CONFIG_NO_CPP17_UNCAUGHT_EXCEPTIONS) && !defined(CATCH_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS)
356 # define CATCH_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS
357 #endif
358
359 #if defined(CATCH_INTERNAL_CONFIG_CPP17_STRING_VIEW) && !defined(CATCH_CONFIG_NO_CPP17_STRING_VIEW) && !defined(CATCH_CONFIG_CPP17_STRING_VIEW)
360 # define CATCH_CONFIG_CPP17_STRING_VIEW
361 #endif
362
363 #if defined(CATCH_INTERNAL_CONFIG_CPP17_VARIANT) && !defined(CATCH_CONFIG_NO_CPP17_VARIANT) && !defined(CATCH_CONFIG_CPP17_VARIANT)
364 # define CATCH_CONFIG_CPP17_VARIANT
365 #endif
366
367 #if defined(CATCH_INTERNAL_CONFIG_CPP17_BYTE) && !defined(CATCH_CONFIG_NO_CPP17_BYTE) && !defined(CATCH_CONFIG_CPP17_BYTE)
368 # define CATCH_CONFIG_CPP17_BYTE
369 #endif
370
371 #if defined(CATCH_CONFIG_EXPERIMENTAL_REDIRECT)
372 # define CATCH_INTERNAL_CONFIG_NEW_CAPTURE
373 #endif
374
375 #if defined(CATCH_INTERNAL_CONFIG_NEW_CAPTURE) && !defined(CATCH_INTERNAL_CONFIG_NO_NEW_CAPTURE) && !defined(CATCH_CONFIG_NO_NEW_CAPTURE) && !defined(CATCH_CONFIG_NEW_CAPTURE)
376 # define CATCH_CONFIG_NEW_CAPTURE
377 #endif
378
379 #if !defined(CATCH_INTERNAL_CONFIG_EXCEPTIONS_ENABLED) && !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
380 # define CATCH_CONFIG_DISABLE_EXCEPTIONS
381 #endif
382
383 #if defined(CATCH_INTERNAL_CONFIG_POLYFILL_ISNAN) && !defined(CATCH_CONFIG_NO_POLYFILL_ISNAN) && !defined(CATCH_CONFIG_POLYFILL_ISNAN)
384 # define CATCH_CONFIG_POLYFILL_ISNAN
385 #endif
386
387 #if defined(CATCH_INTERNAL_CONFIG_USE_ASYNC) && !defined(CATCH_INTERNAL_CONFIG_NO_ASYNC) && !defined(CATCH_CONFIG_NO_USE_ASYNC) && !defined(CATCH_CONFIG_USE_ASYNC)
388 # define CATCH_CONFIG_USE_ASYNC
389 #endif
390
391 #if !defined(CATCH_INTERNAL_SUPPRESS_PARENTHESES_WARNINGS)
392 # define CATCH_INTERNAL_SUPPRESS_PARENTHESES_WARNINGS
393 # define CATCH_INTERNAL_UNSUPPRESS_PARENTHESES_WARNINGS
394 #endif
395 #if !defined(CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS)
396 # define CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS
397 # define CATCH_INTERNAL_UNSUPPRESS_GLOBALS_WARNINGS
398 #endif
399 #if !defined(CATCH_INTERNAL_SUPPRESS_UNUSED_WARNINGS)
400 # define CATCH_INTERNAL_SUPPRESS_UNUSED_WARNINGS
401 # define CATCH_INTERNAL_UNSUPPRESS_UNUSED_WARNINGS
402 #endif
403 #if !defined(CATCH_INTERNAL_SUPPRESS_ZERO_VARIADIC_WARNINGS)
404 # define CATCH_INTERNAL_SUPPRESS_ZERO_VARIADIC_WARNINGS
405 # define CATCH_INTERNAL_UNSUPPRESS_ZERO_VARIADIC_WARNINGS
406 #endif
407
408 #if defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
409 #define CATCH_TRY if ((true))
410 #define CATCH_CATCH_ALL if ((false))
411 #define CATCH_CATCH_ANON(type) if ((false))
412 #else
413 #define CATCH_TRY try
414 #define CATCH_CATCH_ALL catch (...)
415 #define CATCH_CATCH_ANON(type) catch (type)
416 #endif
417
418 #if defined(CATCH_INTERNAL_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR) && !defined(CATCH_CONFIG_NO_TRADITIONAL_MSVC_PREPROCESSOR) && !defined(CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR)
419 #define CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
420 #endif
421
422 // end catch_compiler_capabilities.h
423 #define INTERNAL_CATCH_UNIQUE_NAME_LINE2( name, line ) name##line
424 #define INTERNAL_CATCH_UNIQUE_NAME_LINE( name, line ) INTERNAL_CATCH_UNIQUE_NAME_LINE2( name, line )
425 #ifdef CATCH_CONFIG_COUNTER
426 # define INTERNAL_CATCH_UNIQUE_NAME( name ) INTERNAL_CATCH_UNIQUE_NAME_LINE( name, __COUNTER__ )
427 #else
428 # define INTERNAL_CATCH_UNIQUE_NAME( name ) INTERNAL_CATCH_UNIQUE_NAME_LINE( name, __LINE__ )
429 #endif
430
431 #include <iosfwd>
432 #include <string>
433 #include <cstdint>
434
435 // We need a dummy global operator<< so we can bring it into Catch namespace later
436 struct Catch_global_namespace_dummy {};
437 std::ostream& operator<<(std::ostream&, Catch_global_namespace_dummy);
438
439 namespace Catch {
440
441 struct CaseSensitive { enum Choice {
442 Yes,
443 No
444 }; };
445
446 class NonCopyable {
447 NonCopyable( NonCopyable const& ) = delete;
448 NonCopyable( NonCopyable && ) = delete;
449 NonCopyable& operator = ( NonCopyable const& ) = delete;
450 NonCopyable& operator = ( NonCopyable && ) = delete;
451
452 protected:
453 NonCopyable();
454 virtual ~NonCopyable();
455 };
456
457 struct SourceLineInfo {
458
459 SourceLineInfo() = delete;
SourceLineInfoCatch::SourceLineInfo460 SourceLineInfo( char const* _file, std::size_t _line ) noexcept
461 : file( _file ),
462 line( _line )
463 {}
464
465 SourceLineInfo( SourceLineInfo const& other ) = default;
466 SourceLineInfo& operator = ( SourceLineInfo const& ) = default;
467 SourceLineInfo( SourceLineInfo&& ) noexcept = default;
468 SourceLineInfo& operator = ( SourceLineInfo&& ) noexcept = default;
469
470 bool empty() const noexcept;
471 bool operator == ( SourceLineInfo const& other ) const noexcept;
472 bool operator < ( SourceLineInfo const& other ) const noexcept;
473
474 char const* file;
475 std::size_t line;
476 };
477
478 std::ostream& operator << ( std::ostream& os, SourceLineInfo const& info );
479
480 // Bring in operator<< from global namespace into Catch namespace
481 // This is necessary because the overload of operator<< above makes
482 // lookup stop at namespace Catch
483 using ::operator<<;
484
485 // Use this in variadic streaming macros to allow
486 // >> +StreamEndStop
487 // as well as
488 // >> stuff +StreamEndStop
489 struct StreamEndStop {
490 std::string operator+() const;
491 };
492 template<typename T>
operator +(T const & value,StreamEndStop)493 T const& operator + ( T const& value, StreamEndStop ) {
494 return value;
495 }
496 }
497
498 #define CATCH_INTERNAL_LINEINFO \
499 ::Catch::SourceLineInfo( __FILE__, static_cast<std::size_t>( __LINE__ ) )
500
501 // end catch_common.h
502 namespace Catch {
503
504 struct RegistrarForTagAliases {
505 RegistrarForTagAliases( char const* alias, char const* tag, SourceLineInfo const& lineInfo );
506 };
507
508 } // end namespace Catch
509
510 #define CATCH_REGISTER_TAG_ALIAS( alias, spec ) \
511 CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
512 namespace{ Catch::RegistrarForTagAliases INTERNAL_CATCH_UNIQUE_NAME( AutoRegisterTagAlias )( alias, spec, CATCH_INTERNAL_LINEINFO ); } \
513 CATCH_INTERNAL_UNSUPPRESS_GLOBALS_WARNINGS
514
515 // end catch_tag_alias_autoregistrar.h
516 // start catch_test_registry.h
517
518 // start catch_interfaces_testcase.h
519
520 #include <vector>
521
522 namespace Catch {
523
524 class TestSpec;
525
526 struct ITestInvoker {
527 virtual void invoke () const = 0;
528 virtual ~ITestInvoker();
529 };
530
531 class TestCase;
532 struct IConfig;
533
534 struct ITestCaseRegistry {
535 virtual ~ITestCaseRegistry();
536 virtual std::vector<TestCase> const& getAllTests() const = 0;
537 virtual std::vector<TestCase> const& getAllTestsSorted( IConfig const& config ) const = 0;
538 };
539
540 bool isThrowSafe( TestCase const& testCase, IConfig const& config );
541 bool matchTest( TestCase const& testCase, TestSpec const& testSpec, IConfig const& config );
542 std::vector<TestCase> filterTests( std::vector<TestCase> const& testCases, TestSpec const& testSpec, IConfig const& config );
543 std::vector<TestCase> const& getAllTestCasesSorted( IConfig const& config );
544
545 }
546
547 // end catch_interfaces_testcase.h
548 // start catch_stringref.h
549
550 #include <cstddef>
551 #include <string>
552 #include <iosfwd>
553
554 namespace Catch {
555
556 /// A non-owning string class (similar to the forthcoming std::string_view)
557 /// Note that, because a StringRef may be a substring of another string,
558 /// it may not be null terminated. c_str() must return a null terminated
559 /// string, however, and so the StringRef will internally take ownership
560 /// (taking a copy), if necessary. In theory this ownership is not externally
561 /// visible - but it does mean (substring) StringRefs should not be shared between
562 /// threads.
563 class StringRef {
564 public:
565 using size_type = std::size_t;
566
567 private:
568 friend struct StringRefTestAccess;
569
570 char const* m_start;
571 size_type m_size;
572
573 char* m_data = nullptr;
574
575 void takeOwnership();
576
577 static constexpr char const* const s_empty = "";
578
579 public: // construction/ assignment
StringRef()580 StringRef() noexcept
581 : StringRef( s_empty, 0 )
582 {}
583
StringRef(StringRef const & other)584 StringRef( StringRef const& other ) noexcept
585 : m_start( other.m_start ),
586 m_size( other.m_size )
587 {}
588
StringRef(StringRef && other)589 StringRef( StringRef&& other ) noexcept
590 : m_start( other.m_start ),
591 m_size( other.m_size ),
592 m_data( other.m_data )
593 {
594 other.m_data = nullptr;
595 }
596
597 StringRef( char const* rawChars ) noexcept;
598
StringRef(char const * rawChars,size_type size)599 StringRef( char const* rawChars, size_type size ) noexcept
600 : m_start( rawChars ),
601 m_size( size )
602 {}
603
StringRef(std::string const & stdString)604 StringRef( std::string const& stdString ) noexcept
605 : m_start( stdString.c_str() ),
606 m_size( stdString.size() )
607 {}
608
~StringRef()609 ~StringRef() noexcept {
610 delete[] m_data;
611 }
612
operator =(StringRef const & other)613 auto operator = ( StringRef const &other ) noexcept -> StringRef& {
614 delete[] m_data;
615 m_data = nullptr;
616 m_start = other.m_start;
617 m_size = other.m_size;
618 return *this;
619 }
620
621 operator std::string() const;
622
623 void swap( StringRef& other ) noexcept;
624
625 public: // operators
626 auto operator == ( StringRef const& other ) const noexcept -> bool;
627 auto operator != ( StringRef const& other ) const noexcept -> bool;
628
629 auto operator[] ( size_type index ) const noexcept -> char;
630
631 public: // named queries
empty() const632 auto empty() const noexcept -> bool {
633 return m_size == 0;
634 }
size() const635 auto size() const noexcept -> size_type {
636 return m_size;
637 }
638
639 auto numberOfCharacters() const noexcept -> size_type;
640 auto c_str() const -> char const*;
641
642 public: // substrings and searches
643 auto substr( size_type start, size_type size ) const noexcept -> StringRef;
644
645 // Returns the current start pointer.
646 // Note that the pointer can change when if the StringRef is a substring
647 auto currentData() const noexcept -> char const*;
648
649 private: // ownership queries - may not be consistent between calls
650 auto isOwned() const noexcept -> bool;
651 auto isSubstring() const noexcept -> bool;
652 };
653
654 auto operator + ( StringRef const& lhs, StringRef const& rhs ) -> std::string;
655 auto operator + ( StringRef const& lhs, char const* rhs ) -> std::string;
656 auto operator + ( char const* lhs, StringRef const& rhs ) -> std::string;
657
658 auto operator += ( std::string& lhs, StringRef const& sr ) -> std::string&;
659 auto operator << ( std::ostream& os, StringRef const& sr ) -> std::ostream&;
660
operator ""_sr(char const * rawChars,std::size_t size)661 inline auto operator "" _sr( char const* rawChars, std::size_t size ) noexcept -> StringRef {
662 return StringRef( rawChars, size );
663 }
664
665 } // namespace Catch
666
operator ""_catch_sr(char const * rawChars,std::size_t size)667 inline auto operator "" _catch_sr( char const* rawChars, std::size_t size ) noexcept -> Catch::StringRef {
668 return Catch::StringRef( rawChars, size );
669 }
670
671 // end catch_stringref.h
672 // start catch_type_traits.hpp
673
674
675 #include <type_traits>
676
677 namespace Catch{
678
679 #ifdef CATCH_CPP17_OR_GREATER
680 template <typename...>
681 inline constexpr auto is_unique = std::true_type{};
682
683 template <typename T, typename... Rest>
684 inline constexpr auto is_unique<T, Rest...> = std::bool_constant<
685 (!std::is_same_v<T, Rest> && ...) && is_unique<Rest...>
686 >{};
687 #else
688
689 template <typename...>
690 struct is_unique : std::true_type{};
691
692 template <typename T0, typename T1, typename... Rest>
693 struct is_unique<T0, T1, Rest...> : std::integral_constant
694 <bool,
695 !std::is_same<T0, T1>::value
696 && is_unique<T0, Rest...>::value
697 && is_unique<T1, Rest...>::value
698 >{};
699
700 #endif
701 }
702
703 // end catch_type_traits.hpp
704 // start catch_preprocessor.hpp
705
706
707 #define CATCH_RECURSION_LEVEL0(...) __VA_ARGS__
708 #define CATCH_RECURSION_LEVEL1(...) CATCH_RECURSION_LEVEL0(CATCH_RECURSION_LEVEL0(CATCH_RECURSION_LEVEL0(__VA_ARGS__)))
709 #define CATCH_RECURSION_LEVEL2(...) CATCH_RECURSION_LEVEL1(CATCH_RECURSION_LEVEL1(CATCH_RECURSION_LEVEL1(__VA_ARGS__)))
710 #define CATCH_RECURSION_LEVEL3(...) CATCH_RECURSION_LEVEL2(CATCH_RECURSION_LEVEL2(CATCH_RECURSION_LEVEL2(__VA_ARGS__)))
711 #define CATCH_RECURSION_LEVEL4(...) CATCH_RECURSION_LEVEL3(CATCH_RECURSION_LEVEL3(CATCH_RECURSION_LEVEL3(__VA_ARGS__)))
712 #define CATCH_RECURSION_LEVEL5(...) CATCH_RECURSION_LEVEL4(CATCH_RECURSION_LEVEL4(CATCH_RECURSION_LEVEL4(__VA_ARGS__)))
713
714 #ifdef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
715 #define INTERNAL_CATCH_EXPAND_VARGS(...) __VA_ARGS__
716 // MSVC needs more evaluations
717 #define CATCH_RECURSION_LEVEL6(...) CATCH_RECURSION_LEVEL5(CATCH_RECURSION_LEVEL5(CATCH_RECURSION_LEVEL5(__VA_ARGS__)))
718 #define CATCH_RECURSE(...) CATCH_RECURSION_LEVEL6(CATCH_RECURSION_LEVEL6(__VA_ARGS__))
719 #else
720 #define CATCH_RECURSE(...) CATCH_RECURSION_LEVEL5(__VA_ARGS__)
721 #endif
722
723 #define CATCH_REC_END(...)
724 #define CATCH_REC_OUT
725
726 #define CATCH_EMPTY()
727 #define CATCH_DEFER(id) id CATCH_EMPTY()
728
729 #define CATCH_REC_GET_END2() 0, CATCH_REC_END
730 #define CATCH_REC_GET_END1(...) CATCH_REC_GET_END2
731 #define CATCH_REC_GET_END(...) CATCH_REC_GET_END1
732 #define CATCH_REC_NEXT0(test, next, ...) next CATCH_REC_OUT
733 #define CATCH_REC_NEXT1(test, next) CATCH_DEFER ( CATCH_REC_NEXT0 ) ( test, next, 0)
734 #define CATCH_REC_NEXT(test, next) CATCH_REC_NEXT1(CATCH_REC_GET_END test, next)
735
736 #define CATCH_REC_LIST0(f, x, peek, ...) , f(x) CATCH_DEFER ( CATCH_REC_NEXT(peek, CATCH_REC_LIST1) ) ( f, peek, __VA_ARGS__ )
737 #define CATCH_REC_LIST1(f, x, peek, ...) , f(x) CATCH_DEFER ( CATCH_REC_NEXT(peek, CATCH_REC_LIST0) ) ( f, peek, __VA_ARGS__ )
738 #define CATCH_REC_LIST2(f, x, peek, ...) f(x) CATCH_DEFER ( CATCH_REC_NEXT(peek, CATCH_REC_LIST1) ) ( f, peek, __VA_ARGS__ )
739
740 #define CATCH_REC_LIST0_UD(f, userdata, x, peek, ...) , f(userdata, x) CATCH_DEFER ( CATCH_REC_NEXT(peek, CATCH_REC_LIST1_UD) ) ( f, userdata, peek, __VA_ARGS__ )
741 #define CATCH_REC_LIST1_UD(f, userdata, x, peek, ...) , f(userdata, x) CATCH_DEFER ( CATCH_REC_NEXT(peek, CATCH_REC_LIST0_UD) ) ( f, userdata, peek, __VA_ARGS__ )
742 #define CATCH_REC_LIST2_UD(f, userdata, x, peek, ...) f(userdata, x) CATCH_DEFER ( CATCH_REC_NEXT(peek, CATCH_REC_LIST1_UD) ) ( f, userdata, peek, __VA_ARGS__ )
743
744 // Applies the function macro `f` to each of the remaining parameters, inserts commas between the results,
745 // and passes userdata as the first parameter to each invocation,
746 // e.g. CATCH_REC_LIST_UD(f, x, a, b, c) evaluates to f(x, a), f(x, b), f(x, c)
747 #define CATCH_REC_LIST_UD(f, userdata, ...) CATCH_RECURSE(CATCH_REC_LIST2_UD(f, userdata, __VA_ARGS__, ()()(), ()()(), ()()(), 0))
748
749 #define CATCH_REC_LIST(f, ...) CATCH_RECURSE(CATCH_REC_LIST2(f, __VA_ARGS__, ()()(), ()()(), ()()(), 0))
750
751 #define INTERNAL_CATCH_EXPAND1(param) INTERNAL_CATCH_EXPAND2(param)
752 #define INTERNAL_CATCH_EXPAND2(...) INTERNAL_CATCH_NO## __VA_ARGS__
753 #define INTERNAL_CATCH_DEF(...) INTERNAL_CATCH_DEF __VA_ARGS__
754 #define INTERNAL_CATCH_NOINTERNAL_CATCH_DEF
755 #define INTERNAL_CATCH_STRINGIZE(...) INTERNAL_CATCH_STRINGIZE2(__VA_ARGS__)
756 #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
757 #define INTERNAL_CATCH_STRINGIZE2(...) #__VA_ARGS__
758 #define INTERNAL_CATCH_STRINGIZE_WITHOUT_PARENS(param) INTERNAL_CATCH_STRINGIZE(INTERNAL_CATCH_REMOVE_PARENS(param))
759 #else
760 // MSVC is adding extra space and needs another indirection to expand INTERNAL_CATCH_NOINTERNAL_CATCH_DEF
761 #define INTERNAL_CATCH_STRINGIZE2(...) INTERNAL_CATCH_STRINGIZE3(__VA_ARGS__)
762 #define INTERNAL_CATCH_STRINGIZE3(...) #__VA_ARGS__
763 #define INTERNAL_CATCH_STRINGIZE_WITHOUT_PARENS(param) (INTERNAL_CATCH_STRINGIZE(INTERNAL_CATCH_REMOVE_PARENS(param)) + 1)
764 #endif
765
766 #define INTERNAL_CATCH_MAKE_NAMESPACE2(...) ns_##__VA_ARGS__
767 #define INTERNAL_CATCH_MAKE_NAMESPACE(name) INTERNAL_CATCH_MAKE_NAMESPACE2(name)
768
769 #define INTERNAL_CATCH_REMOVE_PARENS(...) INTERNAL_CATCH_EXPAND1(INTERNAL_CATCH_DEF __VA_ARGS__)
770
771 #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
772 #define INTERNAL_CATCH_MAKE_TYPE_LIST2(...) decltype(get_wrapper<INTERNAL_CATCH_REMOVE_PARENS_GEN(__VA_ARGS__)>())
773 #define INTERNAL_CATCH_MAKE_TYPE_LIST(...) INTERNAL_CATCH_MAKE_TYPE_LIST2(INTERNAL_CATCH_REMOVE_PARENS(__VA_ARGS__))
774 #else
775 #define INTERNAL_CATCH_MAKE_TYPE_LIST2(...) INTERNAL_CATCH_EXPAND_VARGS(decltype(get_wrapper<INTERNAL_CATCH_REMOVE_PARENS_GEN(__VA_ARGS__)>()))
776 #define INTERNAL_CATCH_MAKE_TYPE_LIST(...) INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_MAKE_TYPE_LIST2(INTERNAL_CATCH_REMOVE_PARENS(__VA_ARGS__)))
777 #endif
778
779 #define INTERNAL_CATCH_MAKE_TYPE_LISTS_FROM_TYPES(...)\
780 CATCH_REC_LIST(INTERNAL_CATCH_MAKE_TYPE_LIST,__VA_ARGS__)
781
782 #define INTERNAL_CATCH_REMOVE_PARENS_1_ARG(_0) INTERNAL_CATCH_REMOVE_PARENS(_0)
783 #define INTERNAL_CATCH_REMOVE_PARENS_2_ARG(_0, _1) INTERNAL_CATCH_REMOVE_PARENS(_0), INTERNAL_CATCH_REMOVE_PARENS_1_ARG(_1)
784 #define INTERNAL_CATCH_REMOVE_PARENS_3_ARG(_0, _1, _2) INTERNAL_CATCH_REMOVE_PARENS(_0), INTERNAL_CATCH_REMOVE_PARENS_2_ARG(_1, _2)
785 #define INTERNAL_CATCH_REMOVE_PARENS_4_ARG(_0, _1, _2, _3) INTERNAL_CATCH_REMOVE_PARENS(_0), INTERNAL_CATCH_REMOVE_PARENS_3_ARG(_1, _2, _3)
786 #define INTERNAL_CATCH_REMOVE_PARENS_5_ARG(_0, _1, _2, _3, _4) INTERNAL_CATCH_REMOVE_PARENS(_0), INTERNAL_CATCH_REMOVE_PARENS_4_ARG(_1, _2, _3, _4)
787 #define INTERNAL_CATCH_REMOVE_PARENS_6_ARG(_0, _1, _2, _3, _4, _5) INTERNAL_CATCH_REMOVE_PARENS(_0), INTERNAL_CATCH_REMOVE_PARENS_5_ARG(_1, _2, _3, _4, _5)
788 #define INTERNAL_CATCH_REMOVE_PARENS_7_ARG(_0, _1, _2, _3, _4, _5, _6) INTERNAL_CATCH_REMOVE_PARENS(_0), INTERNAL_CATCH_REMOVE_PARENS_6_ARG(_1, _2, _4, _5, _6)
789 #define INTERNAL_CATCH_REMOVE_PARENS_8_ARG(_0, _1, _2, _3, _4, _5, _6, _7) INTERNAL_CATCH_REMOVE_PARENS(_0), INTERNAL_CATCH_REMOVE_PARENS_7_ARG(_1, _2, _3, _4, _5, _6, _7)
790 #define INTERNAL_CATCH_REMOVE_PARENS_9_ARG(_0, _1, _2, _3, _4, _5, _6, _7, _8) INTERNAL_CATCH_REMOVE_PARENS(_0), INTERNAL_CATCH_REMOVE_PARENS_8_ARG(_1, _2, _3, _4, _5, _6, _7, _8)
791 #define INTERNAL_CATCH_REMOVE_PARENS_10_ARG(_0, _1, _2, _3, _4, _5, _6, _7, _8, _9) INTERNAL_CATCH_REMOVE_PARENS(_0), INTERNAL_CATCH_REMOVE_PARENS_9_ARG(_1, _2, _3, _4, _5, _6, _7, _8, _9)
792 #define INTERNAL_CATCH_REMOVE_PARENS_11_ARG(_0, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10) INTERNAL_CATCH_REMOVE_PARENS(_0), INTERNAL_CATCH_REMOVE_PARENS_10_ARG(_1, _2, _3, _4, _5, _6, _7, _8, _9, _10)
793
794 #define INTERNAL_CATCH_VA_NARGS_IMPL(_0, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, N, ...) N
795
796 #define INTERNAL_CATCH_TYPE_GEN\
797 template<typename...> struct TypeList {};\
798 template<typename...Ts>\
799 constexpr auto get_wrapper() noexcept -> TypeList<Ts...> { return {}; }\
800 \
801 template<template<typename...> class L1, typename...E1, template<typename...> class L2, typename...E2> \
802 constexpr auto append(L1<E1...>, L2<E2...>) noexcept -> L1<E1...,E2...> { return {}; }\
803 template< template<typename...> class L1, typename...E1, template<typename...> class L2, typename...E2, typename...Rest>\
804 constexpr auto append(L1<E1...>, L2<E2...>, Rest...) noexcept -> decltype(append(L1<E1...,E2...>{}, Rest{}...)) { return {}; }\
805 template< template<typename...> class L1, typename...E1, typename...Rest>\
806 constexpr auto append(L1<E1...>, TypeList<mpl_::na>, Rest...) noexcept -> L1<E1...> { return {}; }\
807 \
808 template< template<typename...> class Container, template<typename...> class List, typename...elems>\
809 constexpr auto rewrap(List<elems...>) noexcept -> TypeList<Container<elems...>> { return {}; }\
810 template< template<typename...> class Container, template<typename...> class List, class...Elems, typename...Elements>\
811 constexpr auto rewrap(List<Elems...>,Elements...) noexcept -> decltype(append(TypeList<Container<Elems...>>{}, rewrap<Container>(Elements{}...))) { return {}; }\
812 \
813 template<template <typename...> class Final, template< typename...> class...Containers, typename...Types>\
814 constexpr auto create(TypeList<Types...>) noexcept -> decltype(append(Final<>{}, rewrap<Containers>(Types{}...)...)) { return {}; }\
815 template<template <typename...> class Final, template <typename...> class List, typename...Ts>\
816 constexpr auto convert(List<Ts...>) noexcept -> decltype(append(Final<>{},TypeList<Ts>{}...)) { return {}; }
817
818 #define INTERNAL_CATCH_NTTP_1(signature, ...)\
819 template<INTERNAL_CATCH_REMOVE_PARENS(signature)> struct Nttp{};\
820 template<INTERNAL_CATCH_REMOVE_PARENS(signature)>\
821 constexpr auto get_wrapper() noexcept -> Nttp<__VA_ARGS__> { return {}; } \
822 \
823 template< template<INTERNAL_CATCH_REMOVE_PARENS(signature)> class Container, template<INTERNAL_CATCH_REMOVE_PARENS(signature)> class List, INTERNAL_CATCH_REMOVE_PARENS(signature)>\
824 constexpr auto rewrap(List<__VA_ARGS__>) noexcept -> TypeList<Container<__VA_ARGS__>> { return {}; }\
825 template< template<INTERNAL_CATCH_REMOVE_PARENS(signature)> class Container, template<INTERNAL_CATCH_REMOVE_PARENS(signature)> class List, INTERNAL_CATCH_REMOVE_PARENS(signature), typename...Elements>\
826 constexpr auto rewrap(List<__VA_ARGS__>,Elements...elems) noexcept -> decltype(append(TypeList<Container<__VA_ARGS__>>{}, rewrap<Container>(elems...))) { return {}; }\
827 template<template <typename...> class Final, template<INTERNAL_CATCH_REMOVE_PARENS(signature)> class...Containers, typename...Types>\
828 constexpr auto create(TypeList<Types...>) noexcept -> decltype(append(Final<>{}, rewrap<Containers>(Types{}...)...)) { return {}; }
829
830 #define INTERNAL_CATCH_DECLARE_SIG_TEST0(TestName)
831 #define INTERNAL_CATCH_DECLARE_SIG_TEST1(TestName, signature)\
832 template<INTERNAL_CATCH_REMOVE_PARENS(signature)>\
833 static void TestName()
834 #define INTERNAL_CATCH_DECLARE_SIG_TEST_X(TestName, signature, ...)\
835 template<INTERNAL_CATCH_REMOVE_PARENS(signature)>\
836 static void TestName()
837
838 #define INTERNAL_CATCH_DEFINE_SIG_TEST0(TestName)
839 #define INTERNAL_CATCH_DEFINE_SIG_TEST1(TestName, signature)\
840 template<INTERNAL_CATCH_REMOVE_PARENS(signature)>\
841 static void TestName()
842 #define INTERNAL_CATCH_DEFINE_SIG_TEST_X(TestName, signature,...)\
843 template<INTERNAL_CATCH_REMOVE_PARENS(signature)>\
844 static void TestName()
845
846 #define INTERNAL_CATCH_NTTP_REGISTER0(TestFunc, signature)\
847 template<typename Type>\
848 void reg_test(TypeList<Type>, Catch::NameAndTags nameAndTags)\
849 {\
850 Catch::AutoReg( Catch::makeTestInvoker(&TestFunc<Type>), CATCH_INTERNAL_LINEINFO, Catch::StringRef(), nameAndTags);\
851 }
852
853 #define INTERNAL_CATCH_NTTP_REGISTER(TestFunc, signature, ...)\
854 template<INTERNAL_CATCH_REMOVE_PARENS(signature)>\
855 void reg_test(Nttp<__VA_ARGS__>, Catch::NameAndTags nameAndTags)\
856 {\
857 Catch::AutoReg( Catch::makeTestInvoker(&TestFunc<__VA_ARGS__>), CATCH_INTERNAL_LINEINFO, Catch::StringRef(), nameAndTags);\
858 }
859
860 #define INTERNAL_CATCH_NTTP_REGISTER_METHOD0(TestName, signature, ...)\
861 template<typename Type>\
862 void reg_test(TypeList<Type>, Catch::StringRef className, Catch::NameAndTags nameAndTags)\
863 {\
864 Catch::AutoReg( Catch::makeTestInvoker(&TestName<Type>::test), CATCH_INTERNAL_LINEINFO, className, nameAndTags);\
865 }
866
867 #define INTERNAL_CATCH_NTTP_REGISTER_METHOD(TestName, signature, ...)\
868 template<INTERNAL_CATCH_REMOVE_PARENS(signature)>\
869 void reg_test(Nttp<__VA_ARGS__>, Catch::StringRef className, Catch::NameAndTags nameAndTags)\
870 {\
871 Catch::AutoReg( Catch::makeTestInvoker(&TestName<__VA_ARGS__>::test), CATCH_INTERNAL_LINEINFO, className, nameAndTags);\
872 }
873
874 #define INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD0(TestName, ClassName)
875 #define INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD1(TestName, ClassName, signature)\
876 template<typename TestType> \
877 struct TestName : INTERNAL_CATCH_REMOVE_PARENS(ClassName)<TestType> { \
878 void test();\
879 }
880
881 #define INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X(TestName, ClassName, signature, ...)\
882 template<INTERNAL_CATCH_REMOVE_PARENS(signature)> \
883 struct TestName : INTERNAL_CATCH_REMOVE_PARENS(ClassName)<__VA_ARGS__> { \
884 void test();\
885 }
886
887 #define INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD0(TestName)
888 #define INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD1(TestName, signature)\
889 template<typename TestType> \
890 void INTERNAL_CATCH_MAKE_NAMESPACE(TestName)::TestName<TestType>::test()
891 #define INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X(TestName, signature, ...)\
892 template<INTERNAL_CATCH_REMOVE_PARENS(signature)> \
893 void INTERNAL_CATCH_MAKE_NAMESPACE(TestName)::TestName<__VA_ARGS__>::test()
894
895 #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
896 #define INTERNAL_CATCH_NTTP_0
897 #define INTERNAL_CATCH_NTTP_GEN(...) INTERNAL_CATCH_VA_NARGS_IMPL(__VA_ARGS__, INTERNAL_CATCH_NTTP_1(__VA_ARGS__), INTERNAL_CATCH_NTTP_1(__VA_ARGS__), INTERNAL_CATCH_NTTP_1(__VA_ARGS__), INTERNAL_CATCH_NTTP_1(__VA_ARGS__), INTERNAL_CATCH_NTTP_1(__VA_ARGS__), INTERNAL_CATCH_NTTP_1( __VA_ARGS__), INTERNAL_CATCH_NTTP_1( __VA_ARGS__), INTERNAL_CATCH_NTTP_1( __VA_ARGS__), INTERNAL_CATCH_NTTP_1( __VA_ARGS__),INTERNAL_CATCH_NTTP_1( __VA_ARGS__), INTERNAL_CATCH_NTTP_0)
898 #define INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD(TestName, ...) INTERNAL_CATCH_VA_NARGS_IMPL( "dummy", __VA_ARGS__, INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X,INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X,INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X,INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD1, INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD0)(TestName, __VA_ARGS__)
899 #define INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD(TestName, ClassName, ...) INTERNAL_CATCH_VA_NARGS_IMPL( "dummy", __VA_ARGS__, INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X,INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X,INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X,INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD1, INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD0)(TestName, ClassName, __VA_ARGS__)
900 #define INTERNAL_CATCH_NTTP_REG_METHOD_GEN(TestName, ...) INTERNAL_CATCH_VA_NARGS_IMPL( "dummy", __VA_ARGS__, INTERNAL_CATCH_NTTP_REGISTER_METHOD, INTERNAL_CATCH_NTTP_REGISTER_METHOD, INTERNAL_CATCH_NTTP_REGISTER_METHOD, INTERNAL_CATCH_NTTP_REGISTER_METHOD, INTERNAL_CATCH_NTTP_REGISTER_METHOD, INTERNAL_CATCH_NTTP_REGISTER_METHOD, INTERNAL_CATCH_NTTP_REGISTER_METHOD, INTERNAL_CATCH_NTTP_REGISTER_METHOD, INTERNAL_CATCH_NTTP_REGISTER_METHOD, INTERNAL_CATCH_NTTP_REGISTER_METHOD0, INTERNAL_CATCH_NTTP_REGISTER_METHOD0)(TestName, __VA_ARGS__)
901 #define INTERNAL_CATCH_NTTP_REG_GEN(TestFunc, ...) INTERNAL_CATCH_VA_NARGS_IMPL( "dummy", __VA_ARGS__, INTERNAL_CATCH_NTTP_REGISTER, INTERNAL_CATCH_NTTP_REGISTER, INTERNAL_CATCH_NTTP_REGISTER, INTERNAL_CATCH_NTTP_REGISTER, INTERNAL_CATCH_NTTP_REGISTER, INTERNAL_CATCH_NTTP_REGISTER, INTERNAL_CATCH_NTTP_REGISTER, INTERNAL_CATCH_NTTP_REGISTER, INTERNAL_CATCH_NTTP_REGISTER, INTERNAL_CATCH_NTTP_REGISTER0, INTERNAL_CATCH_NTTP_REGISTER0)(TestFunc, __VA_ARGS__)
902 #define INTERNAL_CATCH_DEFINE_SIG_TEST(TestName, ...) INTERNAL_CATCH_VA_NARGS_IMPL( "dummy", __VA_ARGS__, INTERNAL_CATCH_DEFINE_SIG_TEST_X, INTERNAL_CATCH_DEFINE_SIG_TEST_X, INTERNAL_CATCH_DEFINE_SIG_TEST_X, INTERNAL_CATCH_DEFINE_SIG_TEST_X, INTERNAL_CATCH_DEFINE_SIG_TEST_X, INTERNAL_CATCH_DEFINE_SIG_TEST_X, INTERNAL_CATCH_DEFINE_SIG_TEST_X, INTERNAL_CATCH_DEFINE_SIG_TEST_X,INTERNAL_CATCH_DEFINE_SIG_TEST_X,INTERNAL_CATCH_DEFINE_SIG_TEST1, INTERNAL_CATCH_DEFINE_SIG_TEST0)(TestName, __VA_ARGS__)
903 #define INTERNAL_CATCH_DECLARE_SIG_TEST(TestName, ...) INTERNAL_CATCH_VA_NARGS_IMPL( "dummy", __VA_ARGS__, INTERNAL_CATCH_DECLARE_SIG_TEST_X,INTERNAL_CATCH_DECLARE_SIG_TEST_X, INTERNAL_CATCH_DECLARE_SIG_TEST_X, INTERNAL_CATCH_DECLARE_SIG_TEST_X, INTERNAL_CATCH_DECLARE_SIG_TEST_X, INTERNAL_CATCH_DECLARE_SIG_TEST_X, INTERNAL_CATCH_DEFINE_SIG_TEST_X,INTERNAL_CATCH_DECLARE_SIG_TEST_X,INTERNAL_CATCH_DECLARE_SIG_TEST_X, INTERNAL_CATCH_DECLARE_SIG_TEST1, INTERNAL_CATCH_DECLARE_SIG_TEST0)(TestName, __VA_ARGS__)
904 #define INTERNAL_CATCH_REMOVE_PARENS_GEN(...) INTERNAL_CATCH_VA_NARGS_IMPL(__VA_ARGS__, INTERNAL_CATCH_REMOVE_PARENS_11_ARG,INTERNAL_CATCH_REMOVE_PARENS_10_ARG,INTERNAL_CATCH_REMOVE_PARENS_9_ARG,INTERNAL_CATCH_REMOVE_PARENS_8_ARG,INTERNAL_CATCH_REMOVE_PARENS_7_ARG,INTERNAL_CATCH_REMOVE_PARENS_6_ARG,INTERNAL_CATCH_REMOVE_PARENS_5_ARG,INTERNAL_CATCH_REMOVE_PARENS_4_ARG,INTERNAL_CATCH_REMOVE_PARENS_3_ARG,INTERNAL_CATCH_REMOVE_PARENS_2_ARG,INTERNAL_CATCH_REMOVE_PARENS_1_ARG)(__VA_ARGS__)
905 #else
906 #define INTERNAL_CATCH_NTTP_0(signature)
907 #define INTERNAL_CATCH_NTTP_GEN(...) INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_VA_NARGS_IMPL(__VA_ARGS__, INTERNAL_CATCH_NTTP_1, INTERNAL_CATCH_NTTP_1, INTERNAL_CATCH_NTTP_1, INTERNAL_CATCH_NTTP_1, INTERNAL_CATCH_NTTP_1, INTERNAL_CATCH_NTTP_1, INTERNAL_CATCH_NTTP_1, INTERNAL_CATCH_NTTP_1, INTERNAL_CATCH_NTTP_1,INTERNAL_CATCH_NTTP_1, INTERNAL_CATCH_NTTP_0)( __VA_ARGS__))
908 #define INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD(TestName, ...) INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_VA_NARGS_IMPL( "dummy", __VA_ARGS__, INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X,INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X,INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X,INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD1, INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD0)(TestName, __VA_ARGS__))
909 #define INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD(TestName, ClassName, ...) INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_VA_NARGS_IMPL( "dummy", __VA_ARGS__, INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X,INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X,INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X,INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD1, INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD0)(TestName, ClassName, __VA_ARGS__))
910 #define INTERNAL_CATCH_NTTP_REG_METHOD_GEN(TestName, ...) INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_VA_NARGS_IMPL( "dummy", __VA_ARGS__, INTERNAL_CATCH_NTTP_REGISTER_METHOD, INTERNAL_CATCH_NTTP_REGISTER_METHOD, INTERNAL_CATCH_NTTP_REGISTER_METHOD, INTERNAL_CATCH_NTTP_REGISTER_METHOD, INTERNAL_CATCH_NTTP_REGISTER_METHOD, INTERNAL_CATCH_NTTP_REGISTER_METHOD, INTERNAL_CATCH_NTTP_REGISTER_METHOD, INTERNAL_CATCH_NTTP_REGISTER_METHOD, INTERNAL_CATCH_NTTP_REGISTER_METHOD, INTERNAL_CATCH_NTTP_REGISTER_METHOD0, INTERNAL_CATCH_NTTP_REGISTER_METHOD0)(TestName, __VA_ARGS__))
911 #define INTERNAL_CATCH_NTTP_REG_GEN(TestFunc, ...) INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_VA_NARGS_IMPL( "dummy", __VA_ARGS__, INTERNAL_CATCH_NTTP_REGISTER, INTERNAL_CATCH_NTTP_REGISTER, INTERNAL_CATCH_NTTP_REGISTER, INTERNAL_CATCH_NTTP_REGISTER, INTERNAL_CATCH_NTTP_REGISTER, INTERNAL_CATCH_NTTP_REGISTER, INTERNAL_CATCH_NTTP_REGISTER, INTERNAL_CATCH_NTTP_REGISTER, INTERNAL_CATCH_NTTP_REGISTER, INTERNAL_CATCH_NTTP_REGISTER0, INTERNAL_CATCH_NTTP_REGISTER0)(TestFunc, __VA_ARGS__))
912 #define INTERNAL_CATCH_DEFINE_SIG_TEST(TestName, ...) INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_VA_NARGS_IMPL( "dummy", __VA_ARGS__, INTERNAL_CATCH_DEFINE_SIG_TEST_X, INTERNAL_CATCH_DEFINE_SIG_TEST_X, INTERNAL_CATCH_DEFINE_SIG_TEST_X, INTERNAL_CATCH_DEFINE_SIG_TEST_X, INTERNAL_CATCH_DEFINE_SIG_TEST_X, INTERNAL_CATCH_DEFINE_SIG_TEST_X, INTERNAL_CATCH_DEFINE_SIG_TEST_X, INTERNAL_CATCH_DEFINE_SIG_TEST_X,INTERNAL_CATCH_DEFINE_SIG_TEST_X,INTERNAL_CATCH_DEFINE_SIG_TEST1, INTERNAL_CATCH_DEFINE_SIG_TEST0)(TestName, __VA_ARGS__))
913 #define INTERNAL_CATCH_DECLARE_SIG_TEST(TestName, ...) INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_VA_NARGS_IMPL( "dummy", __VA_ARGS__, INTERNAL_CATCH_DECLARE_SIG_TEST_X,INTERNAL_CATCH_DECLARE_SIG_TEST_X, INTERNAL_CATCH_DECLARE_SIG_TEST_X, INTERNAL_CATCH_DECLARE_SIG_TEST_X, INTERNAL_CATCH_DECLARE_SIG_TEST_X, INTERNAL_CATCH_DECLARE_SIG_TEST_X, INTERNAL_CATCH_DEFINE_SIG_TEST_X,INTERNAL_CATCH_DECLARE_SIG_TEST_X,INTERNAL_CATCH_DECLARE_SIG_TEST_X, INTERNAL_CATCH_DECLARE_SIG_TEST1, INTERNAL_CATCH_DECLARE_SIG_TEST0)(TestName, __VA_ARGS__))
914 #define INTERNAL_CATCH_REMOVE_PARENS_GEN(...) INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_VA_NARGS_IMPL(__VA_ARGS__, INTERNAL_CATCH_REMOVE_PARENS_11_ARG,INTERNAL_CATCH_REMOVE_PARENS_10_ARG,INTERNAL_CATCH_REMOVE_PARENS_9_ARG,INTERNAL_CATCH_REMOVE_PARENS_8_ARG,INTERNAL_CATCH_REMOVE_PARENS_7_ARG,INTERNAL_CATCH_REMOVE_PARENS_6_ARG,INTERNAL_CATCH_REMOVE_PARENS_5_ARG,INTERNAL_CATCH_REMOVE_PARENS_4_ARG,INTERNAL_CATCH_REMOVE_PARENS_3_ARG,INTERNAL_CATCH_REMOVE_PARENS_2_ARG,INTERNAL_CATCH_REMOVE_PARENS_1_ARG)(__VA_ARGS__))
915 #endif
916
917 // end catch_preprocessor.hpp
918 // start catch_meta.hpp
919
920
921 #include <type_traits>
922
923 namespace Catch {
924 template<typename T>
925 struct always_false : std::false_type {};
926
927 template <typename> struct true_given : std::true_type {};
928 struct is_callable_tester {
929 template <typename Fun, typename... Args>
930 true_given<decltype(std::declval<Fun>()(std::declval<Args>()...))> static test(int);
931 template <typename...>
932 std::false_type static test(...);
933 };
934
935 template <typename T>
936 struct is_callable;
937
938 template <typename Fun, typename... Args>
939 struct is_callable<Fun(Args...)> : decltype(is_callable_tester::test<Fun, Args...>(0)) {};
940
941 } // namespace Catch
942
943 namespace mpl_{
944 struct na;
945 }
946
947 // end catch_meta.hpp
948 namespace Catch {
949
950 template<typename C>
951 class TestInvokerAsMethod : public ITestInvoker {
952 void (C::*m_testAsMethod)();
953 public:
TestInvokerAsMethod(void (C::* testAsMethod)())954 TestInvokerAsMethod( void (C::*testAsMethod)() ) noexcept : m_testAsMethod( testAsMethod ) {}
955
invoke() const956 void invoke() const override {
957 C obj;
958 (obj.*m_testAsMethod)();
959 }
960 };
961
962 auto makeTestInvoker( void(*testAsFunction)() ) noexcept -> ITestInvoker*;
963
964 template<typename C>
makeTestInvoker(void (C::* testAsMethod)())965 auto makeTestInvoker( void (C::*testAsMethod)() ) noexcept -> ITestInvoker* {
966 return new(std::nothrow) TestInvokerAsMethod<C>( testAsMethod );
967 }
968
969 struct NameAndTags {
970 NameAndTags( StringRef const& name_ = StringRef(), StringRef const& tags_ = StringRef() ) noexcept;
971 StringRef name;
972 StringRef tags;
973 };
974
975 struct AutoReg : NonCopyable {
976 AutoReg( ITestInvoker* invoker, SourceLineInfo const& lineInfo, StringRef const& classOrMethod, NameAndTags const& nameAndTags ) noexcept;
977 ~AutoReg();
978 };
979
980 } // end namespace Catch
981
982 #if defined(CATCH_CONFIG_DISABLE)
983 #define INTERNAL_CATCH_TESTCASE_NO_REGISTRATION( TestName, ... ) \
984 static void TestName()
985 #define INTERNAL_CATCH_TESTCASE_METHOD_NO_REGISTRATION( TestName, ClassName, ... ) \
986 namespace{ \
987 struct TestName : INTERNAL_CATCH_REMOVE_PARENS(ClassName) { \
988 void test(); \
989 }; \
990 } \
991 void TestName::test()
992 #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION_2( TestName, TestFunc, Name, Tags, Signature, ... ) \
993 INTERNAL_CATCH_DEFINE_SIG_TEST(TestFunc, INTERNAL_CATCH_REMOVE_PARENS(Signature))
994 #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION_2( TestNameClass, TestName, ClassName, Name, Tags, Signature, ... ) \
995 namespace{ \
996 namespace INTERNAL_CATCH_MAKE_NAMESPACE(TestName) { \
997 INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD(TestName, ClassName, INTERNAL_CATCH_REMOVE_PARENS(Signature));\
998 } \
999 } \
1000 INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD(TestName, INTERNAL_CATCH_REMOVE_PARENS(Signature))
1001
1002 #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
1003 #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION(Name, Tags, ...) \
1004 INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION_2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____F_U_N_C____ ), Name, Tags, typename TestType, __VA_ARGS__ )
1005 #else
1006 #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION(Name, Tags, ...) \
1007 INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION_2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____F_U_N_C____ ), Name, Tags, typename TestType, __VA_ARGS__ ) )
1008 #endif
1009
1010 #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
1011 #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG_NO_REGISTRATION(Name, Tags, Signature, ...) \
1012 INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION_2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____F_U_N_C____ ), Name, Tags, Signature, __VA_ARGS__ )
1013 #else
1014 #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG_NO_REGISTRATION(Name, Tags, Signature, ...) \
1015 INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION_2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____F_U_N_C____ ), Name, Tags, Signature, __VA_ARGS__ ) )
1016 #endif
1017
1018 #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
1019 #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION( ClassName, Name, Tags,... ) \
1020 INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION_2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____C_L_A_S_S____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ) , ClassName, Name, Tags, typename T, __VA_ARGS__ )
1021 #else
1022 #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION( ClassName, Name, Tags,... ) \
1023 INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION_2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____C_L_A_S_S____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ) , ClassName, Name, Tags, typename T, __VA_ARGS__ ) )
1024 #endif
1025
1026 #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
1027 #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG_NO_REGISTRATION( ClassName, Name, Tags, Signature, ... ) \
1028 INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION_2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____C_L_A_S_S____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ) , ClassName, Name, Tags, Signature, __VA_ARGS__ )
1029 #else
1030 #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG_NO_REGISTRATION( ClassName, Name, Tags, Signature, ... ) \
1031 INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION_2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____C_L_A_S_S____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ) , ClassName, Name, Tags, Signature, __VA_ARGS__ ) )
1032 #endif
1033 #endif
1034
1035 ///////////////////////////////////////////////////////////////////////////////
1036 #define INTERNAL_CATCH_TESTCASE2( TestName, ... ) \
1037 static void TestName(); \
1038 CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
1039 namespace{ Catch::AutoReg INTERNAL_CATCH_UNIQUE_NAME( autoRegistrar )( Catch::makeTestInvoker( &TestName ), CATCH_INTERNAL_LINEINFO, Catch::StringRef(), Catch::NameAndTags{ __VA_ARGS__ } ); } /* NOLINT */ \
1040 CATCH_INTERNAL_UNSUPPRESS_GLOBALS_WARNINGS \
1041 static void TestName()
1042 #define INTERNAL_CATCH_TESTCASE( ... ) \
1043 INTERNAL_CATCH_TESTCASE2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ), __VA_ARGS__ )
1044
1045 ///////////////////////////////////////////////////////////////////////////////
1046 #define INTERNAL_CATCH_METHOD_AS_TEST_CASE( QualifiedMethod, ... ) \
1047 CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
1048 namespace{ Catch::AutoReg INTERNAL_CATCH_UNIQUE_NAME( autoRegistrar )( Catch::makeTestInvoker( &QualifiedMethod ), CATCH_INTERNAL_LINEINFO, "&" #QualifiedMethod, Catch::NameAndTags{ __VA_ARGS__ } ); } /* NOLINT */ \
1049 CATCH_INTERNAL_UNSUPPRESS_GLOBALS_WARNINGS
1050
1051 ///////////////////////////////////////////////////////////////////////////////
1052 #define INTERNAL_CATCH_TEST_CASE_METHOD2( TestName, ClassName, ... )\
1053 CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
1054 namespace{ \
1055 struct TestName : INTERNAL_CATCH_REMOVE_PARENS(ClassName) { \
1056 void test(); \
1057 }; \
1058 Catch::AutoReg INTERNAL_CATCH_UNIQUE_NAME( autoRegistrar ) ( Catch::makeTestInvoker( &TestName::test ), CATCH_INTERNAL_LINEINFO, #ClassName, Catch::NameAndTags{ __VA_ARGS__ } ); /* NOLINT */ \
1059 } \
1060 CATCH_INTERNAL_UNSUPPRESS_GLOBALS_WARNINGS \
1061 void TestName::test()
1062 #define INTERNAL_CATCH_TEST_CASE_METHOD( ClassName, ... ) \
1063 INTERNAL_CATCH_TEST_CASE_METHOD2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ), ClassName, __VA_ARGS__ )
1064
1065 ///////////////////////////////////////////////////////////////////////////////
1066 #define INTERNAL_CATCH_REGISTER_TESTCASE( Function, ... ) \
1067 CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
1068 Catch::AutoReg INTERNAL_CATCH_UNIQUE_NAME( autoRegistrar )( Catch::makeTestInvoker( Function ), CATCH_INTERNAL_LINEINFO, Catch::StringRef(), Catch::NameAndTags{ __VA_ARGS__ } ); /* NOLINT */ \
1069 CATCH_INTERNAL_UNSUPPRESS_GLOBALS_WARNINGS
1070
1071 ///////////////////////////////////////////////////////////////////////////////
1072 #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_2(TestName, TestFunc, Name, Tags, Signature, ... )\
1073 CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
1074 CATCH_INTERNAL_SUPPRESS_ZERO_VARIADIC_WARNINGS \
1075 INTERNAL_CATCH_DECLARE_SIG_TEST(TestFunc, INTERNAL_CATCH_REMOVE_PARENS(Signature));\
1076 namespace {\
1077 namespace INTERNAL_CATCH_MAKE_NAMESPACE(TestName){\
1078 INTERNAL_CATCH_TYPE_GEN\
1079 INTERNAL_CATCH_NTTP_GEN(INTERNAL_CATCH_REMOVE_PARENS(Signature))\
1080 INTERNAL_CATCH_NTTP_REG_GEN(TestFunc,INTERNAL_CATCH_REMOVE_PARENS(Signature))\
1081 template<typename...Types> \
1082 struct TestName{\
1083 TestName(){\
1084 int index = 0; \
1085 constexpr char const* tmpl_types[] = {CATCH_REC_LIST(INTERNAL_CATCH_STRINGIZE_WITHOUT_PARENS, __VA_ARGS__)};\
1086 using expander = int[];\
1087 (void)expander{(reg_test(Types{}, Catch::NameAndTags{ Name " - " + std::string(tmpl_types[index]), Tags } ), index++, 0)... };/* NOLINT */ \
1088 }\
1089 };\
1090 static int INTERNAL_CATCH_UNIQUE_NAME( globalRegistrar ) = [](){\
1091 TestName<INTERNAL_CATCH_MAKE_TYPE_LISTS_FROM_TYPES(__VA_ARGS__)>();\
1092 return 0;\
1093 }();\
1094 }\
1095 }\
1096 CATCH_INTERNAL_UNSUPPRESS_GLOBALS_WARNINGS \
1097 CATCH_INTERNAL_UNSUPPRESS_ZERO_VARIADIC_WARNINGS \
1098 INTERNAL_CATCH_DEFINE_SIG_TEST(TestFunc,INTERNAL_CATCH_REMOVE_PARENS(Signature))
1099
1100 #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
1101 #define INTERNAL_CATCH_TEMPLATE_TEST_CASE(Name, Tags, ...) \
1102 INTERNAL_CATCH_TEMPLATE_TEST_CASE_2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____F_U_N_C____ ), Name, Tags, typename TestType, __VA_ARGS__ )
1103 #else
1104 #define INTERNAL_CATCH_TEMPLATE_TEST_CASE(Name, Tags, ...) \
1105 INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____F_U_N_C____ ), Name, Tags, typename TestType, __VA_ARGS__ ) )
1106 #endif
1107
1108 #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
1109 #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG(Name, Tags, Signature, ...) \
1110 INTERNAL_CATCH_TEMPLATE_TEST_CASE_2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____F_U_N_C____ ), Name, Tags, Signature, __VA_ARGS__ )
1111 #else
1112 #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG(Name, Tags, Signature, ...) \
1113 INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____F_U_N_C____ ), Name, Tags, Signature, __VA_ARGS__ ) )
1114 #endif
1115
1116 #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE2(TestName, TestFuncName, Name, Tags, Signature, TmplTypes, TypesList) \
1117 CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
1118 CATCH_INTERNAL_SUPPRESS_ZERO_VARIADIC_WARNINGS \
1119 template<typename TestType> static void TestFuncName(); \
1120 namespace {\
1121 namespace INTERNAL_CATCH_MAKE_NAMESPACE(TestName) { \
1122 INTERNAL_CATCH_TYPE_GEN \
1123 INTERNAL_CATCH_NTTP_GEN(INTERNAL_CATCH_REMOVE_PARENS(Signature)) \
1124 template<typename... Types> \
1125 struct TestName { \
1126 void reg_tests() { \
1127 int index = 0; \
1128 using expander = int[]; \
1129 constexpr char const* tmpl_types[] = {CATCH_REC_LIST(INTERNAL_CATCH_STRINGIZE_WITHOUT_PARENS, INTERNAL_CATCH_REMOVE_PARENS(TmplTypes))};\
1130 constexpr char const* types_list[] = {CATCH_REC_LIST(INTERNAL_CATCH_STRINGIZE_WITHOUT_PARENS, INTERNAL_CATCH_REMOVE_PARENS(TypesList))};\
1131 constexpr auto num_types = sizeof(types_list) / sizeof(types_list[0]);\
1132 (void)expander{(Catch::AutoReg( Catch::makeTestInvoker( &TestFuncName<Types> ), CATCH_INTERNAL_LINEINFO, Catch::StringRef(), Catch::NameAndTags{ Name " - " + std::string(tmpl_types[index / num_types]) + "<" + std::string(types_list[index % num_types]) + ">", Tags } ), index++, 0)... };/* NOLINT */\
1133 } \
1134 }; \
1135 static int INTERNAL_CATCH_UNIQUE_NAME( globalRegistrar ) = [](){ \
1136 using TestInit = decltype(create<TestName, INTERNAL_CATCH_REMOVE_PARENS(TmplTypes)>(TypeList<INTERNAL_CATCH_MAKE_TYPE_LISTS_FROM_TYPES(INTERNAL_CATCH_REMOVE_PARENS(TypesList))>{})); \
1137 TestInit t; \
1138 t.reg_tests(); \
1139 return 0; \
1140 }(); \
1141 } \
1142 } \
1143 CATCH_INTERNAL_UNSUPPRESS_GLOBALS_WARNINGS \
1144 CATCH_INTERNAL_UNSUPPRESS_ZERO_VARIADIC_WARNINGS \
1145 template<typename TestType> \
1146 static void TestFuncName()
1147
1148 #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
1149 #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE(Name, Tags, ...)\
1150 INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE2(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____F_U_N_C____ ), Name, Tags, typename T,__VA_ARGS__)
1151 #else
1152 #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE(Name, Tags, ...)\
1153 INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____F_U_N_C____ ), Name, Tags, typename T, __VA_ARGS__ ) )
1154 #endif
1155
1156 #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
1157 #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG(Name, Tags, Signature, ...)\
1158 INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE2(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____F_U_N_C____ ), Name, Tags, Signature, __VA_ARGS__)
1159 #else
1160 #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG(Name, Tags, Signature, ...)\
1161 INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____F_U_N_C____ ), Name, Tags, Signature, __VA_ARGS__ ) )
1162 #endif
1163
1164 #define INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE_2(TestName, TestFunc, Name, Tags, TmplList)\
1165 CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
1166 template<typename TestType> static void TestFunc(); \
1167 namespace {\
1168 namespace INTERNAL_CATCH_MAKE_NAMESPACE(TestName){\
1169 INTERNAL_CATCH_TYPE_GEN\
1170 template<typename... Types> \
1171 struct TestName { \
1172 void reg_tests() { \
1173 int index = 0; \
1174 using expander = int[]; \
1175 (void)expander{(Catch::AutoReg( Catch::makeTestInvoker( &TestFunc<Types> ), CATCH_INTERNAL_LINEINFO, Catch::StringRef(), Catch::NameAndTags{ Name " - " + std::string(INTERNAL_CATCH_STRINGIZE(TmplList)) + " - " + std::to_string(index), Tags } ), index++, 0)... };/* NOLINT */\
1176 } \
1177 };\
1178 static int INTERNAL_CATCH_UNIQUE_NAME( globalRegistrar ) = [](){ \
1179 using TestInit = decltype(convert<TestName>(std::declval<TmplList>())); \
1180 TestInit t; \
1181 t.reg_tests(); \
1182 return 0; \
1183 }(); \
1184 }}\
1185 CATCH_INTERNAL_UNSUPPRESS_GLOBALS_WARNINGS \
1186 template<typename TestType> \
1187 static void TestFunc()
1188
1189 #define INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE(Name, Tags, TmplList) \
1190 INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE_2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____F_U_N_C____ ), Name, Tags, TmplList )
1191
1192 #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_2( TestNameClass, TestName, ClassName, Name, Tags, Signature, ... ) \
1193 CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
1194 CATCH_INTERNAL_SUPPRESS_ZERO_VARIADIC_WARNINGS \
1195 namespace {\
1196 namespace INTERNAL_CATCH_MAKE_NAMESPACE(TestName){ \
1197 INTERNAL_CATCH_TYPE_GEN\
1198 INTERNAL_CATCH_NTTP_GEN(INTERNAL_CATCH_REMOVE_PARENS(Signature))\
1199 INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD(TestName, ClassName, INTERNAL_CATCH_REMOVE_PARENS(Signature));\
1200 INTERNAL_CATCH_NTTP_REG_METHOD_GEN(TestName, INTERNAL_CATCH_REMOVE_PARENS(Signature))\
1201 template<typename...Types> \
1202 struct TestNameClass{\
1203 TestNameClass(){\
1204 int index = 0; \
1205 constexpr char const* tmpl_types[] = {CATCH_REC_LIST(INTERNAL_CATCH_STRINGIZE_WITHOUT_PARENS, __VA_ARGS__)};\
1206 using expander = int[];\
1207 (void)expander{(reg_test(Types{}, #ClassName, Catch::NameAndTags{ Name " - " + std::string(tmpl_types[index]), Tags } ), index++, 0)... };/* NOLINT */ \
1208 }\
1209 };\
1210 static int INTERNAL_CATCH_UNIQUE_NAME( globalRegistrar ) = [](){\
1211 TestNameClass<INTERNAL_CATCH_MAKE_TYPE_LISTS_FROM_TYPES(__VA_ARGS__)>();\
1212 return 0;\
1213 }();\
1214 }\
1215 }\
1216 CATCH_INTERNAL_UNSUPPRESS_GLOBALS_WARNINGS\
1217 CATCH_INTERNAL_UNSUPPRESS_ZERO_VARIADIC_WARNINGS\
1218 INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD(TestName, INTERNAL_CATCH_REMOVE_PARENS(Signature))
1219
1220 #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
1221 #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD( ClassName, Name, Tags,... ) \
1222 INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____C_L_A_S_S____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ) , ClassName, Name, Tags, typename T, __VA_ARGS__ )
1223 #else
1224 #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD( ClassName, Name, Tags,... ) \
1225 INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____C_L_A_S_S____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ) , ClassName, Name, Tags, typename T, __VA_ARGS__ ) )
1226 #endif
1227
1228 #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
1229 #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG( ClassName, Name, Tags, Signature, ... ) \
1230 INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____C_L_A_S_S____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ) , ClassName, Name, Tags, Signature, __VA_ARGS__ )
1231 #else
1232 #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG( ClassName, Name, Tags, Signature, ... ) \
1233 INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____C_L_A_S_S____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ) , ClassName, Name, Tags, Signature, __VA_ARGS__ ) )
1234 #endif
1235
1236 #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_2(TestNameClass, TestName, ClassName, Name, Tags, Signature, TmplTypes, TypesList)\
1237 CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
1238 CATCH_INTERNAL_SUPPRESS_ZERO_VARIADIC_WARNINGS \
1239 template<typename TestType> \
1240 struct TestName : INTERNAL_CATCH_REMOVE_PARENS(ClassName <TestType>) { \
1241 void test();\
1242 };\
1243 namespace {\
1244 namespace INTERNAL_CATCH_MAKE_NAMESPACE(TestNameClass) {\
1245 INTERNAL_CATCH_TYPE_GEN \
1246 INTERNAL_CATCH_NTTP_GEN(INTERNAL_CATCH_REMOVE_PARENS(Signature))\
1247 template<typename...Types>\
1248 struct TestNameClass{\
1249 void reg_tests(){\
1250 int index = 0;\
1251 using expander = int[];\
1252 constexpr char const* tmpl_types[] = {CATCH_REC_LIST(INTERNAL_CATCH_STRINGIZE_WITHOUT_PARENS, INTERNAL_CATCH_REMOVE_PARENS(TmplTypes))};\
1253 constexpr char const* types_list[] = {CATCH_REC_LIST(INTERNAL_CATCH_STRINGIZE_WITHOUT_PARENS, INTERNAL_CATCH_REMOVE_PARENS(TypesList))};\
1254 constexpr auto num_types = sizeof(types_list) / sizeof(types_list[0]);\
1255 (void)expander{(Catch::AutoReg( Catch::makeTestInvoker( &TestName<Types>::test ), CATCH_INTERNAL_LINEINFO, #ClassName, Catch::NameAndTags{ Name " - " + std::string(tmpl_types[index / num_types]) + "<" + std::string(types_list[index % num_types]) + ">", Tags } ), index++, 0)... };/* NOLINT */ \
1256 }\
1257 };\
1258 static int INTERNAL_CATCH_UNIQUE_NAME( globalRegistrar ) = [](){\
1259 using TestInit = decltype(create<TestNameClass, INTERNAL_CATCH_REMOVE_PARENS(TmplTypes)>(TypeList<INTERNAL_CATCH_MAKE_TYPE_LISTS_FROM_TYPES(INTERNAL_CATCH_REMOVE_PARENS(TypesList))>{}));\
1260 TestInit t;\
1261 t.reg_tests();\
1262 return 0;\
1263 }(); \
1264 }\
1265 }\
1266 CATCH_INTERNAL_UNSUPPRESS_GLOBALS_WARNINGS \
1267 CATCH_INTERNAL_UNSUPPRESS_ZERO_VARIADIC_WARNINGS \
1268 template<typename TestType> \
1269 void TestName<TestType>::test()
1270
1271 #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
1272 #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( ClassName, Name, Tags, ... )\
1273 INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____F_U_N_C____ ), ClassName, Name, Tags, typename T, __VA_ARGS__ )
1274 #else
1275 #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( ClassName, Name, Tags, ... )\
1276 INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____F_U_N_C____ ), ClassName, Name, Tags, typename T,__VA_ARGS__ ) )
1277 #endif
1278
1279 #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
1280 #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( ClassName, Name, Tags, Signature, ... )\
1281 INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____F_U_N_C____ ), ClassName, Name, Tags, Signature, __VA_ARGS__ )
1282 #else
1283 #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( ClassName, Name, Tags, Signature, ... )\
1284 INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____F_U_N_C____ ), ClassName, Name, Tags, Signature,__VA_ARGS__ ) )
1285 #endif
1286
1287 #define INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE_METHOD_2( TestNameClass, TestName, ClassName, Name, Tags, TmplList) \
1288 CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
1289 template<typename TestType> \
1290 struct TestName : INTERNAL_CATCH_REMOVE_PARENS(ClassName <TestType>) { \
1291 void test();\
1292 };\
1293 namespace {\
1294 namespace INTERNAL_CATCH_MAKE_NAMESPACE(TestName){ \
1295 INTERNAL_CATCH_TYPE_GEN\
1296 template<typename...Types>\
1297 struct TestNameClass{\
1298 void reg_tests(){\
1299 int index = 0;\
1300 using expander = int[];\
1301 (void)expander{(Catch::AutoReg( Catch::makeTestInvoker( &TestName<Types>::test ), CATCH_INTERNAL_LINEINFO, #ClassName, Catch::NameAndTags{ Name " - " + std::string(INTERNAL_CATCH_STRINGIZE(TmplList)) + " - " + std::to_string(index), Tags } ), index++, 0)... };/* NOLINT */ \
1302 }\
1303 };\
1304 static int INTERNAL_CATCH_UNIQUE_NAME( globalRegistrar ) = [](){\
1305 using TestInit = decltype(convert<TestNameClass>(std::declval<TmplList>()));\
1306 TestInit t;\
1307 t.reg_tests();\
1308 return 0;\
1309 }(); \
1310 }}\
1311 CATCH_INTERNAL_UNSUPPRESS_GLOBALS_WARNINGS \
1312 template<typename TestType> \
1313 void TestName<TestType>::test()
1314
1315 #define INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE_METHOD(ClassName, Name, Tags, TmplList) \
1316 INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE_METHOD_2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____F_U_N_C____ ), ClassName, Name, Tags, TmplList )
1317
1318 // end catch_test_registry.h
1319 // start catch_capture.hpp
1320
1321 // start catch_assertionhandler.h
1322
1323 // start catch_assertioninfo.h
1324
1325 // start catch_result_type.h
1326
1327 namespace Catch {
1328
1329 // ResultWas::OfType enum
1330 struct ResultWas { enum OfType {
1331 Unknown = -1,
1332 Ok = 0,
1333 Info = 1,
1334 Warning = 2,
1335
1336 FailureBit = 0x10,
1337
1338 ExpressionFailed = FailureBit | 1,
1339 ExplicitFailure = FailureBit | 2,
1340
1341 Exception = 0x100 | FailureBit,
1342
1343 ThrewException = Exception | 1,
1344 DidntThrowException = Exception | 2,
1345
1346 FatalErrorCondition = 0x200 | FailureBit
1347
1348 }; };
1349
1350 bool isOk( ResultWas::OfType resultType );
1351 bool isJustInfo( int flags );
1352
1353 // ResultDisposition::Flags enum
1354 struct ResultDisposition { enum Flags {
1355 Normal = 0x01,
1356
1357 ContinueOnFailure = 0x02, // Failures fail test, but execution continues
1358 FalseTest = 0x04, // Prefix expression with !
1359 SuppressFail = 0x08 // Failures are reported but do not fail the test
1360 }; };
1361
1362 ResultDisposition::Flags operator | ( ResultDisposition::Flags lhs, ResultDisposition::Flags rhs );
1363
1364 bool shouldContinueOnFailure( int flags );
isFalseTest(int flags)1365 inline bool isFalseTest( int flags ) { return ( flags & ResultDisposition::FalseTest ) != 0; }
1366 bool shouldSuppressFailure( int flags );
1367
1368 } // end namespace Catch
1369
1370 // end catch_result_type.h
1371 namespace Catch {
1372
1373 struct AssertionInfo
1374 {
1375 StringRef macroName;
1376 SourceLineInfo lineInfo;
1377 StringRef capturedExpression;
1378 ResultDisposition::Flags resultDisposition;
1379
1380 // We want to delete this constructor but a compiler bug in 4.8 means
1381 // the struct is then treated as non-aggregate
1382 //AssertionInfo() = delete;
1383 };
1384
1385 } // end namespace Catch
1386
1387 // end catch_assertioninfo.h
1388 // start catch_decomposer.h
1389
1390 // start catch_tostring.h
1391
1392 #include <vector>
1393 #include <cstddef>
1394 #include <type_traits>
1395 #include <string>
1396 // start catch_stream.h
1397
1398 #include <iosfwd>
1399 #include <cstddef>
1400 #include <ostream>
1401
1402 namespace Catch {
1403
1404 std::ostream& cout();
1405 std::ostream& cerr();
1406 std::ostream& clog();
1407
1408 class StringRef;
1409
1410 struct IStream {
1411 virtual ~IStream();
1412 virtual std::ostream& stream() const = 0;
1413 };
1414
1415 auto makeStream( StringRef const &filename ) -> IStream const*;
1416
1417 class ReusableStringStream {
1418 std::size_t m_index;
1419 std::ostream* m_oss;
1420 public:
1421 ReusableStringStream();
1422 ~ReusableStringStream();
1423
1424 auto str() const -> std::string;
1425
1426 template<typename T>
operator <<(T const & value)1427 auto operator << ( T const& value ) -> ReusableStringStream& {
1428 *m_oss << value;
1429 return *this;
1430 }
get()1431 auto get() -> std::ostream& { return *m_oss; }
1432 };
1433 }
1434
1435 // end catch_stream.h
1436 // start catch_interfaces_enum_values_registry.h
1437
1438 #include <vector>
1439
1440 namespace Catch {
1441
1442 namespace Detail {
1443 struct EnumInfo {
1444 StringRef m_name;
1445 std::vector<std::pair<int, std::string>> m_values;
1446
1447 ~EnumInfo();
1448
1449 StringRef lookup( int value ) const;
1450 };
1451 } // namespace Detail
1452
1453 struct IMutableEnumValuesRegistry {
1454 virtual ~IMutableEnumValuesRegistry();
1455
1456 virtual Detail::EnumInfo const& registerEnum( StringRef enumName, StringRef allEnums, std::vector<int> const& values ) = 0;
1457
1458 template<typename E>
registerEnumCatch::IMutableEnumValuesRegistry1459 Detail::EnumInfo const& registerEnum( StringRef enumName, StringRef allEnums, std::initializer_list<E> values ) {
1460 std::vector<int> intValues;
1461 intValues.reserve( values.size() );
1462 for( auto enumValue : values )
1463 intValues.push_back( static_cast<int>( enumValue ) );
1464 return registerEnum( enumName, allEnums, intValues );
1465 }
1466 };
1467
1468 } // Catch
1469
1470 // end catch_interfaces_enum_values_registry.h
1471
1472 #ifdef CATCH_CONFIG_CPP17_STRING_VIEW
1473 #include <string_view>
1474 #endif
1475
1476 #ifdef __OBJC__
1477 // start catch_objc_arc.hpp
1478
1479 #import <Foundation/Foundation.h>
1480
1481 #ifdef __has_feature
1482 #define CATCH_ARC_ENABLED __has_feature(objc_arc)
1483 #else
1484 #define CATCH_ARC_ENABLED 0
1485 #endif
1486
1487 void arcSafeRelease( NSObject* obj );
1488 id performOptionalSelector( id obj, SEL sel );
1489
1490 #if !CATCH_ARC_ENABLED
arcSafeRelease(NSObject * obj)1491 inline void arcSafeRelease( NSObject* obj ) {
1492 [obj release];
1493 }
performOptionalSelector(id obj,SEL sel)1494 inline id performOptionalSelector( id obj, SEL sel ) {
1495 if( [obj respondsToSelector: sel] )
1496 return [obj performSelector: sel];
1497 return nil;
1498 }
1499 #define CATCH_UNSAFE_UNRETAINED
1500 #define CATCH_ARC_STRONG
1501 #else
arcSafeRelease(NSObject *)1502 inline void arcSafeRelease( NSObject* ){}
performOptionalSelector(id obj,SEL sel)1503 inline id performOptionalSelector( id obj, SEL sel ) {
1504 #ifdef __clang__
1505 #pragma clang diagnostic push
1506 #pragma clang diagnostic ignored "-Warc-performSelector-leaks"
1507 #endif
1508 if( [obj respondsToSelector: sel] )
1509 return [obj performSelector: sel];
1510 #ifdef __clang__
1511 #pragma clang diagnostic pop
1512 #endif
1513 return nil;
1514 }
1515 #define CATCH_UNSAFE_UNRETAINED __unsafe_unretained
1516 #define CATCH_ARC_STRONG __strong
1517 #endif
1518
1519 // end catch_objc_arc.hpp
1520 #endif
1521
1522 #ifdef _MSC_VER
1523 #pragma warning(push)
1524 #pragma warning(disable:4180) // We attempt to stream a function (address) by const&, which MSVC complains about but is harmless
1525 #endif
1526
1527 namespace Catch {
1528 namespace Detail {
1529
1530 extern const std::string unprintableString;
1531
1532 std::string rawMemoryToString( const void *object, std::size_t size );
1533
1534 template<typename T>
rawMemoryToString(const T & object)1535 std::string rawMemoryToString( const T& object ) {
1536 return rawMemoryToString( &object, sizeof(object) );
1537 }
1538
1539 template<typename T>
1540 class IsStreamInsertable {
1541 template<typename SS, typename TT>
1542 static auto test(int)
1543 -> decltype(std::declval<SS&>() << std::declval<TT>(), std::true_type());
1544
1545 template<typename, typename>
1546 static auto test(...)->std::false_type;
1547
1548 public:
1549 static const bool value = decltype(test<std::ostream, const T&>(0))::value;
1550 };
1551
1552 template<typename E>
1553 std::string convertUnknownEnumToString( E e );
1554
1555 template<typename T>
1556 typename std::enable_if<
1557 !std::is_enum<T>::value && !std::is_base_of<std::exception, T>::value,
convertUnstreamable(T const &)1558 std::string>::type convertUnstreamable( T const& ) {
1559 return Detail::unprintableString;
1560 }
1561 template<typename T>
1562 typename std::enable_if<
1563 !std::is_enum<T>::value && std::is_base_of<std::exception, T>::value,
convertUnstreamable(T const & ex)1564 std::string>::type convertUnstreamable(T const& ex) {
1565 return ex.what();
1566 }
1567
1568 template<typename T>
1569 typename std::enable_if<
1570 std::is_enum<T>::value
convertUnstreamable(T const & value)1571 , std::string>::type convertUnstreamable( T const& value ) {
1572 return convertUnknownEnumToString( value );
1573 }
1574
1575 #if defined(_MANAGED)
1576 //! Convert a CLR string to a utf8 std::string
1577 template<typename T>
1578 std::string clrReferenceToString( T^ ref ) {
1579 if (ref == nullptr)
1580 return std::string("null");
1581 auto bytes = System::Text::Encoding::UTF8->GetBytes(ref->ToString());
1582 cli::pin_ptr<System::Byte> p = &bytes[0];
1583 return std::string(reinterpret_cast<char const *>(p), bytes->Length);
1584 }
1585 #endif
1586
1587 } // namespace Detail
1588
1589 // If we decide for C++14, change these to enable_if_ts
1590 template <typename T, typename = void>
1591 struct StringMaker {
1592 template <typename Fake = T>
1593 static
1594 typename std::enable_if<::Catch::Detail::IsStreamInsertable<Fake>::value, std::string>::type
convertCatch::StringMaker1595 convert(const Fake& value) {
1596 ReusableStringStream rss;
1597 // NB: call using the function-like syntax to avoid ambiguity with
1598 // user-defined templated operator<< under clang.
1599 rss.operator<<(value);
1600 return rss.str();
1601 }
1602
1603 template <typename Fake = T>
1604 static
1605 typename std::enable_if<!::Catch::Detail::IsStreamInsertable<Fake>::value, std::string>::type
convertCatch::StringMaker1606 convert( const Fake& value ) {
1607 #if !defined(CATCH_CONFIG_FALLBACK_STRINGIFIER)
1608 return Detail::convertUnstreamable(value);
1609 #else
1610 return CATCH_CONFIG_FALLBACK_STRINGIFIER(value);
1611 #endif
1612 }
1613 };
1614
1615 namespace Detail {
1616
1617 // This function dispatches all stringification requests inside of Catch.
1618 // Should be preferably called fully qualified, like ::Catch::Detail::stringify
1619 template <typename T>
stringify(const T & e)1620 std::string stringify(const T& e) {
1621 return ::Catch::StringMaker<typename std::remove_cv<typename std::remove_reference<T>::type>::type>::convert(e);
1622 }
1623
1624 template<typename E>
convertUnknownEnumToString(E e)1625 std::string convertUnknownEnumToString( E e ) {
1626 return ::Catch::Detail::stringify(static_cast<typename std::underlying_type<E>::type>(e));
1627 }
1628
1629 #if defined(_MANAGED)
1630 template <typename T>
1631 std::string stringify( T^ e ) {
1632 return ::Catch::StringMaker<T^>::convert(e);
1633 }
1634 #endif
1635
1636 } // namespace Detail
1637
1638 // Some predefined specializations
1639
1640 template<>
1641 struct StringMaker<std::string> {
1642 static std::string convert(const std::string& str);
1643 };
1644
1645 #ifdef CATCH_CONFIG_CPP17_STRING_VIEW
1646 template<>
1647 struct StringMaker<std::string_view> {
1648 static std::string convert(std::string_view str);
1649 };
1650 #endif
1651
1652 template<>
1653 struct StringMaker<char const *> {
1654 static std::string convert(char const * str);
1655 };
1656 template<>
1657 struct StringMaker<char *> {
1658 static std::string convert(char * str);
1659 };
1660
1661 #ifdef CATCH_CONFIG_WCHAR
1662 template<>
1663 struct StringMaker<std::wstring> {
1664 static std::string convert(const std::wstring& wstr);
1665 };
1666
1667 # ifdef CATCH_CONFIG_CPP17_STRING_VIEW
1668 template<>
1669 struct StringMaker<std::wstring_view> {
1670 static std::string convert(std::wstring_view str);
1671 };
1672 # endif
1673
1674 template<>
1675 struct StringMaker<wchar_t const *> {
1676 static std::string convert(wchar_t const * str);
1677 };
1678 template<>
1679 struct StringMaker<wchar_t *> {
1680 static std::string convert(wchar_t * str);
1681 };
1682 #endif
1683
1684 // TBD: Should we use `strnlen` to ensure that we don't go out of the buffer,
1685 // while keeping string semantics?
1686 template<int SZ>
1687 struct StringMaker<char[SZ]> {
convertCatch::StringMaker1688 static std::string convert(char const* str) {
1689 return ::Catch::Detail::stringify(std::string{ str });
1690 }
1691 };
1692 template<int SZ>
1693 struct StringMaker<signed char[SZ]> {
convertCatch::StringMaker1694 static std::string convert(signed char const* str) {
1695 return ::Catch::Detail::stringify(std::string{ reinterpret_cast<char const *>(str) });
1696 }
1697 };
1698 template<int SZ>
1699 struct StringMaker<unsigned char[SZ]> {
convertCatch::StringMaker1700 static std::string convert(unsigned char const* str) {
1701 return ::Catch::Detail::stringify(std::string{ reinterpret_cast<char const *>(str) });
1702 }
1703 };
1704
1705 #if defined(CATCH_CONFIG_CPP17_BYTE)
1706 template<>
1707 struct StringMaker<std::byte> {
1708 static std::string convert(std::byte value);
1709 };
1710 #endif // defined(CATCH_CONFIG_CPP17_BYTE)
1711 template<>
1712 struct StringMaker<int> {
1713 static std::string convert(int value);
1714 };
1715 template<>
1716 struct StringMaker<long> {
1717 static std::string convert(long value);
1718 };
1719 template<>
1720 struct StringMaker<long long> {
1721 static std::string convert(long long value);
1722 };
1723 template<>
1724 struct StringMaker<unsigned int> {
1725 static std::string convert(unsigned int value);
1726 };
1727 template<>
1728 struct StringMaker<unsigned long> {
1729 static std::string convert(unsigned long value);
1730 };
1731 template<>
1732 struct StringMaker<unsigned long long> {
1733 static std::string convert(unsigned long long value);
1734 };
1735
1736 template<>
1737 struct StringMaker<bool> {
1738 static std::string convert(bool b);
1739 };
1740
1741 template<>
1742 struct StringMaker<char> {
1743 static std::string convert(char c);
1744 };
1745 template<>
1746 struct StringMaker<signed char> {
1747 static std::string convert(signed char c);
1748 };
1749 template<>
1750 struct StringMaker<unsigned char> {
1751 static std::string convert(unsigned char c);
1752 };
1753
1754 template<>
1755 struct StringMaker<std::nullptr_t> {
1756 static std::string convert(std::nullptr_t);
1757 };
1758
1759 template<>
1760 struct StringMaker<float> {
1761 static std::string convert(float value);
1762 static int precision;
1763 };
1764
1765 template<>
1766 struct StringMaker<double> {
1767 static std::string convert(double value);
1768 static int precision;
1769 };
1770
1771 template <typename T>
1772 struct StringMaker<T*> {
1773 template <typename U>
convertCatch::StringMaker1774 static std::string convert(U* p) {
1775 if (p) {
1776 return ::Catch::Detail::rawMemoryToString(p);
1777 } else {
1778 return "nullptr";
1779 }
1780 }
1781 };
1782
1783 template <typename R, typename C>
1784 struct StringMaker<R C::*> {
convertCatch::StringMaker1785 static std::string convert(R C::* p) {
1786 if (p) {
1787 return ::Catch::Detail::rawMemoryToString(p);
1788 } else {
1789 return "nullptr";
1790 }
1791 }
1792 };
1793
1794 #if defined(_MANAGED)
1795 template <typename T>
1796 struct StringMaker<T^> {
1797 static std::string convert( T^ ref ) {
1798 return ::Catch::Detail::clrReferenceToString(ref);
1799 }
1800 };
1801 #endif
1802
1803 namespace Detail {
1804 template<typename InputIterator>
rangeToString(InputIterator first,InputIterator last)1805 std::string rangeToString(InputIterator first, InputIterator last) {
1806 ReusableStringStream rss;
1807 rss << "{ ";
1808 if (first != last) {
1809 rss << ::Catch::Detail::stringify(*first);
1810 for (++first; first != last; ++first)
1811 rss << ", " << ::Catch::Detail::stringify(*first);
1812 }
1813 rss << " }";
1814 return rss.str();
1815 }
1816 }
1817
1818 #ifdef __OBJC__
1819 template<>
1820 struct StringMaker<NSString*> {
convertCatch::StringMaker1821 static std::string convert(NSString * nsstring) {
1822 if (!nsstring)
1823 return "nil";
1824 return std::string("@") + [nsstring UTF8String];
1825 }
1826 };
1827 template<>
1828 struct StringMaker<NSObject*> {
convertCatch::StringMaker1829 static std::string convert(NSObject* nsObject) {
1830 return ::Catch::Detail::stringify([nsObject description]);
1831 }
1832
1833 };
1834 namespace Detail {
stringify(NSString * nsstring)1835 inline std::string stringify( NSString* nsstring ) {
1836 return StringMaker<NSString*>::convert( nsstring );
1837 }
1838
1839 } // namespace Detail
1840 #endif // __OBJC__
1841
1842 } // namespace Catch
1843
1844 //////////////////////////////////////////////////////
1845 // Separate std-lib types stringification, so it can be selectively enabled
1846 // This means that we do not bring in
1847
1848 #if defined(CATCH_CONFIG_ENABLE_ALL_STRINGMAKERS)
1849 # define CATCH_CONFIG_ENABLE_PAIR_STRINGMAKER
1850 # define CATCH_CONFIG_ENABLE_TUPLE_STRINGMAKER
1851 # define CATCH_CONFIG_ENABLE_VARIANT_STRINGMAKER
1852 # define CATCH_CONFIG_ENABLE_CHRONO_STRINGMAKER
1853 # define CATCH_CONFIG_ENABLE_OPTIONAL_STRINGMAKER
1854 #endif
1855
1856 // Separate std::pair specialization
1857 #if defined(CATCH_CONFIG_ENABLE_PAIR_STRINGMAKER)
1858 #include <utility>
1859 namespace Catch {
1860 template<typename T1, typename T2>
1861 struct StringMaker<std::pair<T1, T2> > {
convertCatch::StringMaker1862 static std::string convert(const std::pair<T1, T2>& pair) {
1863 ReusableStringStream rss;
1864 rss << "{ "
1865 << ::Catch::Detail::stringify(pair.first)
1866 << ", "
1867 << ::Catch::Detail::stringify(pair.second)
1868 << " }";
1869 return rss.str();
1870 }
1871 };
1872 }
1873 #endif // CATCH_CONFIG_ENABLE_PAIR_STRINGMAKER
1874
1875 #if defined(CATCH_CONFIG_ENABLE_OPTIONAL_STRINGMAKER) && defined(CATCH_CONFIG_CPP17_OPTIONAL)
1876 #include <optional>
1877 namespace Catch {
1878 template<typename T>
1879 struct StringMaker<std::optional<T> > {
convertCatch::StringMaker1880 static std::string convert(const std::optional<T>& optional) {
1881 ReusableStringStream rss;
1882 if (optional.has_value()) {
1883 rss << ::Catch::Detail::stringify(*optional);
1884 } else {
1885 rss << "{ }";
1886 }
1887 return rss.str();
1888 }
1889 };
1890 }
1891 #endif // CATCH_CONFIG_ENABLE_OPTIONAL_STRINGMAKER
1892
1893 // Separate std::tuple specialization
1894 #if defined(CATCH_CONFIG_ENABLE_TUPLE_STRINGMAKER)
1895 #include <tuple>
1896 namespace Catch {
1897 namespace Detail {
1898 template<
1899 typename Tuple,
1900 std::size_t N = 0,
1901 bool = (N < std::tuple_size<Tuple>::value)
1902 >
1903 struct TupleElementPrinter {
printCatch::Detail::TupleElementPrinter1904 static void print(const Tuple& tuple, std::ostream& os) {
1905 os << (N ? ", " : " ")
1906 << ::Catch::Detail::stringify(std::get<N>(tuple));
1907 TupleElementPrinter<Tuple, N + 1>::print(tuple, os);
1908 }
1909 };
1910
1911 template<
1912 typename Tuple,
1913 std::size_t N
1914 >
1915 struct TupleElementPrinter<Tuple, N, false> {
printCatch::Detail::TupleElementPrinter1916 static void print(const Tuple&, std::ostream&) {}
1917 };
1918
1919 }
1920
1921 template<typename ...Types>
1922 struct StringMaker<std::tuple<Types...>> {
convertCatch::StringMaker1923 static std::string convert(const std::tuple<Types...>& tuple) {
1924 ReusableStringStream rss;
1925 rss << '{';
1926 Detail::TupleElementPrinter<std::tuple<Types...>>::print(tuple, rss.get());
1927 rss << " }";
1928 return rss.str();
1929 }
1930 };
1931 }
1932 #endif // CATCH_CONFIG_ENABLE_TUPLE_STRINGMAKER
1933
1934 #if defined(CATCH_CONFIG_ENABLE_VARIANT_STRINGMAKER) && defined(CATCH_CONFIG_CPP17_VARIANT)
1935 #include <variant>
1936 namespace Catch {
1937 template<>
1938 struct StringMaker<std::monostate> {
convertCatch::StringMaker1939 static std::string convert(const std::monostate&) {
1940 return "{ }";
1941 }
1942 };
1943
1944 template<typename... Elements>
1945 struct StringMaker<std::variant<Elements...>> {
convertCatch::StringMaker1946 static std::string convert(const std::variant<Elements...>& variant) {
1947 if (variant.valueless_by_exception()) {
1948 return "{valueless variant}";
1949 } else {
1950 return std::visit(
1951 [](const auto& value) {
1952 return ::Catch::Detail::stringify(value);
1953 },
1954 variant
1955 );
1956 }
1957 }
1958 };
1959 }
1960 #endif // CATCH_CONFIG_ENABLE_VARIANT_STRINGMAKER
1961
1962 namespace Catch {
1963 struct not_this_one {}; // Tag type for detecting which begin/ end are being selected
1964
1965 // Import begin/ end from std here so they are considered alongside the fallback (...) overloads in this namespace
1966 using std::begin;
1967 using std::end;
1968
1969 not_this_one begin( ... );
1970 not_this_one end( ... );
1971
1972 template <typename T>
1973 struct is_range {
1974 static const bool value =
1975 !std::is_same<decltype(begin(std::declval<T>())), not_this_one>::value &&
1976 !std::is_same<decltype(end(std::declval<T>())), not_this_one>::value;
1977 };
1978
1979 #if defined(_MANAGED) // Managed types are never ranges
1980 template <typename T>
1981 struct is_range<T^> {
1982 static const bool value = false;
1983 };
1984 #endif
1985
1986 template<typename Range>
rangeToString(Range const & range)1987 std::string rangeToString( Range const& range ) {
1988 return ::Catch::Detail::rangeToString( begin( range ), end( range ) );
1989 }
1990
1991 // Handle vector<bool> specially
1992 template<typename Allocator>
rangeToString(std::vector<bool,Allocator> const & v)1993 std::string rangeToString( std::vector<bool, Allocator> const& v ) {
1994 ReusableStringStream rss;
1995 rss << "{ ";
1996 bool first = true;
1997 for( bool b : v ) {
1998 if( first )
1999 first = false;
2000 else
2001 rss << ", ";
2002 rss << ::Catch::Detail::stringify( b );
2003 }
2004 rss << " }";
2005 return rss.str();
2006 }
2007
2008 template<typename R>
2009 struct StringMaker<R, typename std::enable_if<is_range<R>::value && !::Catch::Detail::IsStreamInsertable<R>::value>::type> {
convertCatch::StringMaker2010 static std::string convert( R const& range ) {
2011 return rangeToString( range );
2012 }
2013 };
2014
2015 template <typename T, int SZ>
2016 struct StringMaker<T[SZ]> {
convertCatch::StringMaker2017 static std::string convert(T const(&arr)[SZ]) {
2018 return rangeToString(arr);
2019 }
2020 };
2021
2022 } // namespace Catch
2023
2024 // Separate std::chrono::duration specialization
2025 #if defined(CATCH_CONFIG_ENABLE_CHRONO_STRINGMAKER)
2026 #include <ctime>
2027 #include <ratio>
2028 #include <chrono>
2029
2030 namespace Catch {
2031
2032 template <class Ratio>
2033 struct ratio_string {
2034 static std::string symbol();
2035 };
2036
2037 template <class Ratio>
symbol()2038 std::string ratio_string<Ratio>::symbol() {
2039 Catch::ReusableStringStream rss;
2040 rss << '[' << Ratio::num << '/'
2041 << Ratio::den << ']';
2042 return rss.str();
2043 }
2044 template <>
2045 struct ratio_string<std::atto> {
2046 static std::string symbol();
2047 };
2048 template <>
2049 struct ratio_string<std::femto> {
2050 static std::string symbol();
2051 };
2052 template <>
2053 struct ratio_string<std::pico> {
2054 static std::string symbol();
2055 };
2056 template <>
2057 struct ratio_string<std::nano> {
2058 static std::string symbol();
2059 };
2060 template <>
2061 struct ratio_string<std::micro> {
2062 static std::string symbol();
2063 };
2064 template <>
2065 struct ratio_string<std::milli> {
2066 static std::string symbol();
2067 };
2068
2069 ////////////
2070 // std::chrono::duration specializations
2071 template<typename Value, typename Ratio>
2072 struct StringMaker<std::chrono::duration<Value, Ratio>> {
convertCatch::StringMaker2073 static std::string convert(std::chrono::duration<Value, Ratio> const& duration) {
2074 ReusableStringStream rss;
2075 rss << duration.count() << ' ' << ratio_string<Ratio>::symbol() << 's';
2076 return rss.str();
2077 }
2078 };
2079 template<typename Value>
2080 struct StringMaker<std::chrono::duration<Value, std::ratio<1>>> {
convertCatch::StringMaker2081 static std::string convert(std::chrono::duration<Value, std::ratio<1>> const& duration) {
2082 ReusableStringStream rss;
2083 rss << duration.count() << " s";
2084 return rss.str();
2085 }
2086 };
2087 template<typename Value>
2088 struct StringMaker<std::chrono::duration<Value, std::ratio<60>>> {
convertCatch::StringMaker2089 static std::string convert(std::chrono::duration<Value, std::ratio<60>> const& duration) {
2090 ReusableStringStream rss;
2091 rss << duration.count() << " m";
2092 return rss.str();
2093 }
2094 };
2095 template<typename Value>
2096 struct StringMaker<std::chrono::duration<Value, std::ratio<3600>>> {
convertCatch::StringMaker2097 static std::string convert(std::chrono::duration<Value, std::ratio<3600>> const& duration) {
2098 ReusableStringStream rss;
2099 rss << duration.count() << " h";
2100 return rss.str();
2101 }
2102 };
2103
2104 ////////////
2105 // std::chrono::time_point specialization
2106 // Generic time_point cannot be specialized, only std::chrono::time_point<system_clock>
2107 template<typename Clock, typename Duration>
2108 struct StringMaker<std::chrono::time_point<Clock, Duration>> {
convertCatch::StringMaker2109 static std::string convert(std::chrono::time_point<Clock, Duration> const& time_point) {
2110 return ::Catch::Detail::stringify(time_point.time_since_epoch()) + " since epoch";
2111 }
2112 };
2113 // std::chrono::time_point<system_clock> specialization
2114 template<typename Duration>
2115 struct StringMaker<std::chrono::time_point<std::chrono::system_clock, Duration>> {
convertCatch::StringMaker2116 static std::string convert(std::chrono::time_point<std::chrono::system_clock, Duration> const& time_point) {
2117 auto converted = std::chrono::system_clock::to_time_t(time_point);
2118
2119 #ifdef _MSC_VER
2120 std::tm timeInfo = {};
2121 gmtime_s(&timeInfo, &converted);
2122 #else
2123 std::tm* timeInfo = std::gmtime(&converted);
2124 #endif
2125
2126 auto const timeStampSize = sizeof("2017-01-16T17:06:45Z");
2127 char timeStamp[timeStampSize];
2128 const char * const fmt = "%Y-%m-%dT%H:%M:%SZ";
2129
2130 #ifdef _MSC_VER
2131 std::strftime(timeStamp, timeStampSize, fmt, &timeInfo);
2132 #else
2133 std::strftime(timeStamp, timeStampSize, fmt, timeInfo);
2134 #endif
2135 return std::string(timeStamp);
2136 }
2137 };
2138 }
2139 #endif // CATCH_CONFIG_ENABLE_CHRONO_STRINGMAKER
2140
2141 #define INTERNAL_CATCH_REGISTER_ENUM( enumName, ... ) \
2142 namespace Catch { \
2143 template<> struct StringMaker<enumName> { \
2144 static std::string convert( enumName value ) { \
2145 static const auto& enumInfo = ::Catch::getMutableRegistryHub().getMutableEnumValuesRegistry().registerEnum( #enumName, #__VA_ARGS__, { __VA_ARGS__ } ); \
2146 return enumInfo.lookup( static_cast<int>( value ) ); \
2147 } \
2148 }; \
2149 }
2150
2151 #define CATCH_REGISTER_ENUM( enumName, ... ) INTERNAL_CATCH_REGISTER_ENUM( enumName, __VA_ARGS__ )
2152
2153 #ifdef _MSC_VER
2154 #pragma warning(pop)
2155 #endif
2156
2157 // end catch_tostring.h
2158 #include <iosfwd>
2159
2160 #ifdef _MSC_VER
2161 #pragma warning(push)
2162 #pragma warning(disable:4389) // '==' : signed/unsigned mismatch
2163 #pragma warning(disable:4018) // more "signed/unsigned mismatch"
2164 #pragma warning(disable:4312) // Converting int to T* using reinterpret_cast (issue on x64 platform)
2165 #pragma warning(disable:4180) // qualifier applied to function type has no meaning
2166 #pragma warning(disable:4800) // Forcing result to true or false
2167 #endif
2168
2169 namespace Catch {
2170
2171 struct ITransientExpression {
isBinaryExpressionCatch::ITransientExpression2172 auto isBinaryExpression() const -> bool { return m_isBinaryExpression; }
getResultCatch::ITransientExpression2173 auto getResult() const -> bool { return m_result; }
2174 virtual void streamReconstructedExpression( std::ostream &os ) const = 0;
2175
ITransientExpressionCatch::ITransientExpression2176 ITransientExpression( bool isBinaryExpression, bool result )
2177 : m_isBinaryExpression( isBinaryExpression ),
2178 m_result( result )
2179 {}
2180
2181 // We don't actually need a virtual destructor, but many static analysers
2182 // complain if it's not here :-(
2183 virtual ~ITransientExpression();
2184
2185 bool m_isBinaryExpression;
2186 bool m_result;
2187
2188 };
2189
2190 void formatReconstructedExpression( std::ostream &os, std::string const& lhs, StringRef op, std::string const& rhs );
2191
2192 template<typename LhsT, typename RhsT>
2193 class BinaryExpr : public ITransientExpression {
2194 LhsT m_lhs;
2195 StringRef m_op;
2196 RhsT m_rhs;
2197
streamReconstructedExpression(std::ostream & os) const2198 void streamReconstructedExpression( std::ostream &os ) const override {
2199 formatReconstructedExpression
2200 ( os, Catch::Detail::stringify( m_lhs ), m_op, Catch::Detail::stringify( m_rhs ) );
2201 }
2202
2203 public:
BinaryExpr(bool comparisonResult,LhsT lhs,StringRef op,RhsT rhs)2204 BinaryExpr( bool comparisonResult, LhsT lhs, StringRef op, RhsT rhs )
2205 : ITransientExpression{ true, comparisonResult },
2206 m_lhs( lhs ),
2207 m_op( op ),
2208 m_rhs( rhs )
2209 {}
2210
2211 template<typename T>
operator &&(T) const2212 auto operator && ( T ) const -> BinaryExpr<LhsT, RhsT const&> const {
2213 static_assert(always_false<T>::value,
2214 "chained comparisons are not supported inside assertions, "
2215 "wrap the expression inside parentheses, or decompose it");
2216 }
2217
2218 template<typename T>
operator ||(T) const2219 auto operator || ( T ) const -> BinaryExpr<LhsT, RhsT const&> const {
2220 static_assert(always_false<T>::value,
2221 "chained comparisons are not supported inside assertions, "
2222 "wrap the expression inside parentheses, or decompose it");
2223 }
2224
2225 template<typename T>
operator ==(T) const2226 auto operator == ( T ) const -> BinaryExpr<LhsT, RhsT const&> const {
2227 static_assert(always_false<T>::value,
2228 "chained comparisons are not supported inside assertions, "
2229 "wrap the expression inside parentheses, or decompose it");
2230 }
2231
2232 template<typename T>
operator !=(T) const2233 auto operator != ( T ) const -> BinaryExpr<LhsT, RhsT const&> const {
2234 static_assert(always_false<T>::value,
2235 "chained comparisons are not supported inside assertions, "
2236 "wrap the expression inside parentheses, or decompose it");
2237 }
2238
2239 template<typename T>
operator >(T) const2240 auto operator > ( T ) const -> BinaryExpr<LhsT, RhsT const&> const {
2241 static_assert(always_false<T>::value,
2242 "chained comparisons are not supported inside assertions, "
2243 "wrap the expression inside parentheses, or decompose it");
2244 }
2245
2246 template<typename T>
operator <(T) const2247 auto operator < ( T ) const -> BinaryExpr<LhsT, RhsT const&> const {
2248 static_assert(always_false<T>::value,
2249 "chained comparisons are not supported inside assertions, "
2250 "wrap the expression inside parentheses, or decompose it");
2251 }
2252
2253 template<typename T>
operator >=(T) const2254 auto operator >= ( T ) const -> BinaryExpr<LhsT, RhsT const&> const {
2255 static_assert(always_false<T>::value,
2256 "chained comparisons are not supported inside assertions, "
2257 "wrap the expression inside parentheses, or decompose it");
2258 }
2259
2260 template<typename T>
operator <=(T) const2261 auto operator <= ( T ) const -> BinaryExpr<LhsT, RhsT const&> const {
2262 static_assert(always_false<T>::value,
2263 "chained comparisons are not supported inside assertions, "
2264 "wrap the expression inside parentheses, or decompose it");
2265 }
2266 };
2267
2268 template<typename LhsT>
2269 class UnaryExpr : public ITransientExpression {
2270 LhsT m_lhs;
2271
streamReconstructedExpression(std::ostream & os) const2272 void streamReconstructedExpression( std::ostream &os ) const override {
2273 os << Catch::Detail::stringify( m_lhs );
2274 }
2275
2276 public:
UnaryExpr(LhsT lhs)2277 explicit UnaryExpr( LhsT lhs )
2278 : ITransientExpression{ false, static_cast<bool>(lhs) },
2279 m_lhs( lhs )
2280 {}
2281 };
2282
2283 // Specialised comparison functions to handle equality comparisons between ints and pointers (NULL deduces as an int)
2284 template<typename LhsT, typename RhsT>
compareEqual(LhsT const & lhs,RhsT const & rhs)2285 auto compareEqual( LhsT const& lhs, RhsT const& rhs ) -> bool { return static_cast<bool>(lhs == rhs); }
2286 template<typename T>
compareEqual(T * const & lhs,int rhs)2287 auto compareEqual( T* const& lhs, int rhs ) -> bool { return lhs == reinterpret_cast<void const*>( rhs ); }
2288 template<typename T>
compareEqual(T * const & lhs,long rhs)2289 auto compareEqual( T* const& lhs, long rhs ) -> bool { return lhs == reinterpret_cast<void const*>( rhs ); }
2290 template<typename T>
compareEqual(int lhs,T * const & rhs)2291 auto compareEqual( int lhs, T* const& rhs ) -> bool { return reinterpret_cast<void const*>( lhs ) == rhs; }
2292 template<typename T>
compareEqual(long lhs,T * const & rhs)2293 auto compareEqual( long lhs, T* const& rhs ) -> bool { return reinterpret_cast<void const*>( lhs ) == rhs; }
2294
2295 template<typename LhsT, typename RhsT>
compareNotEqual(LhsT const & lhs,RhsT && rhs)2296 auto compareNotEqual( LhsT const& lhs, RhsT&& rhs ) -> bool { return static_cast<bool>(lhs != rhs); }
2297 template<typename T>
compareNotEqual(T * const & lhs,int rhs)2298 auto compareNotEqual( T* const& lhs, int rhs ) -> bool { return lhs != reinterpret_cast<void const*>( rhs ); }
2299 template<typename T>
compareNotEqual(T * const & lhs,long rhs)2300 auto compareNotEqual( T* const& lhs, long rhs ) -> bool { return lhs != reinterpret_cast<void const*>( rhs ); }
2301 template<typename T>
compareNotEqual(int lhs,T * const & rhs)2302 auto compareNotEqual( int lhs, T* const& rhs ) -> bool { return reinterpret_cast<void const*>( lhs ) != rhs; }
2303 template<typename T>
compareNotEqual(long lhs,T * const & rhs)2304 auto compareNotEqual( long lhs, T* const& rhs ) -> bool { return reinterpret_cast<void const*>( lhs ) != rhs; }
2305
2306 template<typename LhsT>
2307 class ExprLhs {
2308 LhsT m_lhs;
2309 public:
ExprLhs(LhsT lhs)2310 explicit ExprLhs( LhsT lhs ) : m_lhs( lhs ) {}
2311
2312 template<typename RhsT>
operator ==(RhsT const & rhs)2313 auto operator == ( RhsT const& rhs ) -> BinaryExpr<LhsT, RhsT const&> const {
2314 return { compareEqual( m_lhs, rhs ), m_lhs, "==", rhs };
2315 }
operator ==(bool rhs)2316 auto operator == ( bool rhs ) -> BinaryExpr<LhsT, bool> const {
2317 return { m_lhs == rhs, m_lhs, "==", rhs };
2318 }
2319
2320 template<typename RhsT>
operator !=(RhsT const & rhs)2321 auto operator != ( RhsT const& rhs ) -> BinaryExpr<LhsT, RhsT const&> const {
2322 return { compareNotEqual( m_lhs, rhs ), m_lhs, "!=", rhs };
2323 }
operator !=(bool rhs)2324 auto operator != ( bool rhs ) -> BinaryExpr<LhsT, bool> const {
2325 return { m_lhs != rhs, m_lhs, "!=", rhs };
2326 }
2327
2328 template<typename RhsT>
operator >(RhsT const & rhs)2329 auto operator > ( RhsT const& rhs ) -> BinaryExpr<LhsT, RhsT const&> const {
2330 return { static_cast<bool>(m_lhs > rhs), m_lhs, ">", rhs };
2331 }
2332 template<typename RhsT>
operator <(RhsT const & rhs)2333 auto operator < ( RhsT const& rhs ) -> BinaryExpr<LhsT, RhsT const&> const {
2334 return { static_cast<bool>(m_lhs < rhs), m_lhs, "<", rhs };
2335 }
2336 template<typename RhsT>
operator >=(RhsT const & rhs)2337 auto operator >= ( RhsT const& rhs ) -> BinaryExpr<LhsT, RhsT const&> const {
2338 return { static_cast<bool>(m_lhs >= rhs), m_lhs, ">=", rhs };
2339 }
2340 template<typename RhsT>
operator <=(RhsT const & rhs)2341 auto operator <= ( RhsT const& rhs ) -> BinaryExpr<LhsT, RhsT const&> const {
2342 return { static_cast<bool>(m_lhs <= rhs), m_lhs, "<=", rhs };
2343 }
2344
2345 template<typename RhsT>
operator &&(RhsT const &)2346 auto operator && ( RhsT const& ) -> BinaryExpr<LhsT, RhsT const&> const {
2347 static_assert(always_false<RhsT>::value,
2348 "operator&& is not supported inside assertions, "
2349 "wrap the expression inside parentheses, or decompose it");
2350 }
2351
2352 template<typename RhsT>
operator ||(RhsT const &)2353 auto operator || ( RhsT const& ) -> BinaryExpr<LhsT, RhsT const&> const {
2354 static_assert(always_false<RhsT>::value,
2355 "operator|| is not supported inside assertions, "
2356 "wrap the expression inside parentheses, or decompose it");
2357 }
2358
makeUnaryExpr() const2359 auto makeUnaryExpr() const -> UnaryExpr<LhsT> {
2360 return UnaryExpr<LhsT>{ m_lhs };
2361 }
2362 };
2363
2364 void handleExpression( ITransientExpression const& expr );
2365
2366 template<typename T>
handleExpression(ExprLhs<T> const & expr)2367 void handleExpression( ExprLhs<T> const& expr ) {
2368 handleExpression( expr.makeUnaryExpr() );
2369 }
2370
2371 struct Decomposer {
2372 template<typename T>
operator <=Catch::Decomposer2373 auto operator <= ( T const& lhs ) -> ExprLhs<T const&> {
2374 return ExprLhs<T const&>{ lhs };
2375 }
2376
operator <=Catch::Decomposer2377 auto operator <=( bool value ) -> ExprLhs<bool> {
2378 return ExprLhs<bool>{ value };
2379 }
2380 };
2381
2382 } // end namespace Catch
2383
2384 #ifdef _MSC_VER
2385 #pragma warning(pop)
2386 #endif
2387
2388 // end catch_decomposer.h
2389 // start catch_interfaces_capture.h
2390
2391 #include <string>
2392 #include <chrono>
2393
2394 namespace Catch {
2395
2396 class AssertionResult;
2397 struct AssertionInfo;
2398 struct SectionInfo;
2399 struct SectionEndInfo;
2400 struct MessageInfo;
2401 struct MessageBuilder;
2402 struct Counts;
2403 struct AssertionReaction;
2404 struct SourceLineInfo;
2405
2406 struct ITransientExpression;
2407 struct IGeneratorTracker;
2408
2409 #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
2410 struct BenchmarkInfo;
2411 template <typename Duration = std::chrono::duration<double, std::nano>>
2412 struct BenchmarkStats;
2413 #endif // CATCH_CONFIG_ENABLE_BENCHMARKING
2414
2415 struct IResultCapture {
2416
2417 virtual ~IResultCapture();
2418
2419 virtual bool sectionStarted( SectionInfo const& sectionInfo,
2420 Counts& assertions ) = 0;
2421 virtual void sectionEnded( SectionEndInfo const& endInfo ) = 0;
2422 virtual void sectionEndedEarly( SectionEndInfo const& endInfo ) = 0;
2423
2424 virtual auto acquireGeneratorTracker( SourceLineInfo const& lineInfo ) -> IGeneratorTracker& = 0;
2425
2426 #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
2427 virtual void benchmarkPreparing( std::string const& name ) = 0;
2428 virtual void benchmarkStarting( BenchmarkInfo const& info ) = 0;
2429 virtual void benchmarkEnded( BenchmarkStats<> const& stats ) = 0;
2430 virtual void benchmarkFailed( std::string const& error ) = 0;
2431 #endif // CATCH_CONFIG_ENABLE_BENCHMARKING
2432
2433 virtual void pushScopedMessage( MessageInfo const& message ) = 0;
2434 virtual void popScopedMessage( MessageInfo const& message ) = 0;
2435
2436 virtual void emplaceUnscopedMessage( MessageBuilder const& builder ) = 0;
2437
2438 virtual void handleFatalErrorCondition( StringRef message ) = 0;
2439
2440 virtual void handleExpr
2441 ( AssertionInfo const& info,
2442 ITransientExpression const& expr,
2443 AssertionReaction& reaction ) = 0;
2444 virtual void handleMessage
2445 ( AssertionInfo const& info,
2446 ResultWas::OfType resultType,
2447 StringRef const& message,
2448 AssertionReaction& reaction ) = 0;
2449 virtual void handleUnexpectedExceptionNotThrown
2450 ( AssertionInfo const& info,
2451 AssertionReaction& reaction ) = 0;
2452 virtual void handleUnexpectedInflightException
2453 ( AssertionInfo const& info,
2454 std::string const& message,
2455 AssertionReaction& reaction ) = 0;
2456 virtual void handleIncomplete
2457 ( AssertionInfo const& info ) = 0;
2458 virtual void handleNonExpr
2459 ( AssertionInfo const &info,
2460 ResultWas::OfType resultType,
2461 AssertionReaction &reaction ) = 0;
2462
2463 virtual bool lastAssertionPassed() = 0;
2464 virtual void assertionPassed() = 0;
2465
2466 // Deprecated, do not use:
2467 virtual std::string getCurrentTestName() const = 0;
2468 virtual const AssertionResult* getLastResult() const = 0;
2469 virtual void exceptionEarlyReported() = 0;
2470 };
2471
2472 IResultCapture& getResultCapture();
2473 }
2474
2475 // end catch_interfaces_capture.h
2476 namespace Catch {
2477
2478 struct TestFailureException{};
2479 struct AssertionResultData;
2480 struct IResultCapture;
2481 class RunContext;
2482
2483 class LazyExpression {
2484 friend class AssertionHandler;
2485 friend struct AssertionStats;
2486 friend class RunContext;
2487
2488 ITransientExpression const* m_transientExpression = nullptr;
2489 bool m_isNegated;
2490 public:
2491 LazyExpression( bool isNegated );
2492 LazyExpression( LazyExpression const& other );
2493 LazyExpression& operator = ( LazyExpression const& ) = delete;
2494
2495 explicit operator bool() const;
2496
2497 friend auto operator << ( std::ostream& os, LazyExpression const& lazyExpr ) -> std::ostream&;
2498 };
2499
2500 struct AssertionReaction {
2501 bool shouldDebugBreak = false;
2502 bool shouldThrow = false;
2503 };
2504
2505 class AssertionHandler {
2506 AssertionInfo m_assertionInfo;
2507 AssertionReaction m_reaction;
2508 bool m_completed = false;
2509 IResultCapture& m_resultCapture;
2510
2511 public:
2512 AssertionHandler
2513 ( StringRef const& macroName,
2514 SourceLineInfo const& lineInfo,
2515 StringRef capturedExpression,
2516 ResultDisposition::Flags resultDisposition );
~AssertionHandler()2517 ~AssertionHandler() {
2518 if ( !m_completed ) {
2519 m_resultCapture.handleIncomplete( m_assertionInfo );
2520 }
2521 }
2522
2523 template<typename T>
handleExpr(ExprLhs<T> const & expr)2524 void handleExpr( ExprLhs<T> const& expr ) {
2525 handleExpr( expr.makeUnaryExpr() );
2526 }
2527 void handleExpr( ITransientExpression const& expr );
2528
2529 void handleMessage(ResultWas::OfType resultType, StringRef const& message);
2530
2531 void handleExceptionThrownAsExpected();
2532 void handleUnexpectedExceptionNotThrown();
2533 void handleExceptionNotThrownAsExpected();
2534 void handleThrowingCallSkipped();
2535 void handleUnexpectedInflightException();
2536
2537 void complete();
2538 void setCompleted();
2539
2540 // query
2541 auto allowThrows() const -> bool;
2542 };
2543
2544 void handleExceptionMatchExpr( AssertionHandler& handler, std::string const& str, StringRef const& matcherString );
2545
2546 } // namespace Catch
2547
2548 // end catch_assertionhandler.h
2549 // start catch_message.h
2550
2551 #include <string>
2552 #include <vector>
2553
2554 namespace Catch {
2555
2556 struct MessageInfo {
2557 MessageInfo( StringRef const& _macroName,
2558 SourceLineInfo const& _lineInfo,
2559 ResultWas::OfType _type );
2560
2561 StringRef macroName;
2562 std::string message;
2563 SourceLineInfo lineInfo;
2564 ResultWas::OfType type;
2565 unsigned int sequence;
2566
2567 bool operator == ( MessageInfo const& other ) const;
2568 bool operator < ( MessageInfo const& other ) const;
2569 private:
2570 static unsigned int globalCount;
2571 };
2572
2573 struct MessageStream {
2574
2575 template<typename T>
operator <<Catch::MessageStream2576 MessageStream& operator << ( T const& value ) {
2577 m_stream << value;
2578 return *this;
2579 }
2580
2581 ReusableStringStream m_stream;
2582 };
2583
2584 struct MessageBuilder : MessageStream {
2585 MessageBuilder( StringRef const& macroName,
2586 SourceLineInfo const& lineInfo,
2587 ResultWas::OfType type );
2588
2589 template<typename T>
operator <<Catch::MessageBuilder2590 MessageBuilder& operator << ( T const& value ) {
2591 m_stream << value;
2592 return *this;
2593 }
2594
2595 MessageInfo m_info;
2596 };
2597
2598 class ScopedMessage {
2599 public:
2600 explicit ScopedMessage( MessageBuilder const& builder );
2601 ScopedMessage( ScopedMessage& duplicate ) = delete;
2602 ScopedMessage( ScopedMessage&& old );
2603 ~ScopedMessage();
2604
2605 MessageInfo m_info;
2606 bool m_moved;
2607 };
2608
2609 class Capturer {
2610 std::vector<MessageInfo> m_messages;
2611 IResultCapture& m_resultCapture = getResultCapture();
2612 size_t m_captured = 0;
2613 public:
2614 Capturer( StringRef macroName, SourceLineInfo const& lineInfo, ResultWas::OfType resultType, StringRef names );
2615 ~Capturer();
2616
2617 void captureValue( size_t index, std::string const& value );
2618
2619 template<typename T>
captureValues(size_t index,T const & value)2620 void captureValues( size_t index, T const& value ) {
2621 captureValue( index, Catch::Detail::stringify( value ) );
2622 }
2623
2624 template<typename T, typename... Ts>
captureValues(size_t index,T const & value,Ts const &...values)2625 void captureValues( size_t index, T const& value, Ts const&... values ) {
2626 captureValue( index, Catch::Detail::stringify(value) );
2627 captureValues( index+1, values... );
2628 }
2629 };
2630
2631 } // end namespace Catch
2632
2633 // end catch_message.h
2634 #if !defined(CATCH_CONFIG_DISABLE)
2635
2636 #if !defined(CATCH_CONFIG_DISABLE_STRINGIFICATION)
2637 #define CATCH_INTERNAL_STRINGIFY(...) #__VA_ARGS__
2638 #else
2639 #define CATCH_INTERNAL_STRINGIFY(...) "Disabled by CATCH_CONFIG_DISABLE_STRINGIFICATION"
2640 #endif
2641
2642 #if defined(CATCH_CONFIG_FAST_COMPILE) || defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
2643
2644 ///////////////////////////////////////////////////////////////////////////////
2645 // Another way to speed-up compilation is to omit local try-catch for REQUIRE*
2646 // macros.
2647 #define INTERNAL_CATCH_TRY
2648 #define INTERNAL_CATCH_CATCH( capturer )
2649
2650 #else // CATCH_CONFIG_FAST_COMPILE
2651
2652 #define INTERNAL_CATCH_TRY try
2653 #define INTERNAL_CATCH_CATCH( handler ) catch(...) { handler.handleUnexpectedInflightException(); }
2654
2655 #endif
2656
2657 #define INTERNAL_CATCH_REACT( handler ) handler.complete();
2658
2659 ///////////////////////////////////////////////////////////////////////////////
2660 #define INTERNAL_CATCH_TEST( macroName, resultDisposition, ... ) \
2661 do { \
2662 Catch::AssertionHandler catchAssertionHandler( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(__VA_ARGS__), resultDisposition ); \
2663 INTERNAL_CATCH_TRY { \
2664 CATCH_INTERNAL_SUPPRESS_PARENTHESES_WARNINGS \
2665 catchAssertionHandler.handleExpr( Catch::Decomposer() <= __VA_ARGS__ ); \
2666 CATCH_INTERNAL_UNSUPPRESS_PARENTHESES_WARNINGS \
2667 } INTERNAL_CATCH_CATCH( catchAssertionHandler ) \
2668 INTERNAL_CATCH_REACT( catchAssertionHandler ) \
2669 } while( (void)0, (false) && static_cast<bool>( !!(__VA_ARGS__) ) ) // the expression here is never evaluated at runtime but it forces the compiler to give it a look
2670 // The double negation silences MSVC's C4800 warning, the static_cast forces short-circuit evaluation if the type has overloaded &&.
2671
2672 ///////////////////////////////////////////////////////////////////////////////
2673 #define INTERNAL_CATCH_IF( macroName, resultDisposition, ... ) \
2674 INTERNAL_CATCH_TEST( macroName, resultDisposition, __VA_ARGS__ ); \
2675 if( Catch::getResultCapture().lastAssertionPassed() )
2676
2677 ///////////////////////////////////////////////////////////////////////////////
2678 #define INTERNAL_CATCH_ELSE( macroName, resultDisposition, ... ) \
2679 INTERNAL_CATCH_TEST( macroName, resultDisposition, __VA_ARGS__ ); \
2680 if( !Catch::getResultCapture().lastAssertionPassed() )
2681
2682 ///////////////////////////////////////////////////////////////////////////////
2683 #define INTERNAL_CATCH_NO_THROW( macroName, resultDisposition, ... ) \
2684 do { \
2685 Catch::AssertionHandler catchAssertionHandler( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(__VA_ARGS__), resultDisposition ); \
2686 try { \
2687 static_cast<void>(__VA_ARGS__); \
2688 catchAssertionHandler.handleExceptionNotThrownAsExpected(); \
2689 } \
2690 catch( ... ) { \
2691 catchAssertionHandler.handleUnexpectedInflightException(); \
2692 } \
2693 INTERNAL_CATCH_REACT( catchAssertionHandler ) \
2694 } while( false )
2695
2696 ///////////////////////////////////////////////////////////////////////////////
2697 #define INTERNAL_CATCH_THROWS( macroName, resultDisposition, ... ) \
2698 do { \
2699 Catch::AssertionHandler catchAssertionHandler( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(__VA_ARGS__), resultDisposition); \
2700 if( catchAssertionHandler.allowThrows() ) \
2701 try { \
2702 static_cast<void>(__VA_ARGS__); \
2703 catchAssertionHandler.handleUnexpectedExceptionNotThrown(); \
2704 } \
2705 catch( ... ) { \
2706 catchAssertionHandler.handleExceptionThrownAsExpected(); \
2707 } \
2708 else \
2709 catchAssertionHandler.handleThrowingCallSkipped(); \
2710 INTERNAL_CATCH_REACT( catchAssertionHandler ) \
2711 } while( false )
2712
2713 ///////////////////////////////////////////////////////////////////////////////
2714 #define INTERNAL_CATCH_THROWS_AS( macroName, exceptionType, resultDisposition, expr ) \
2715 do { \
2716 Catch::AssertionHandler catchAssertionHandler( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(expr) ", " CATCH_INTERNAL_STRINGIFY(exceptionType), resultDisposition ); \
2717 if( catchAssertionHandler.allowThrows() ) \
2718 try { \
2719 static_cast<void>(expr); \
2720 catchAssertionHandler.handleUnexpectedExceptionNotThrown(); \
2721 } \
2722 catch( exceptionType const& ) { \
2723 catchAssertionHandler.handleExceptionThrownAsExpected(); \
2724 } \
2725 catch( ... ) { \
2726 catchAssertionHandler.handleUnexpectedInflightException(); \
2727 } \
2728 else \
2729 catchAssertionHandler.handleThrowingCallSkipped(); \
2730 INTERNAL_CATCH_REACT( catchAssertionHandler ) \
2731 } while( false )
2732
2733 ///////////////////////////////////////////////////////////////////////////////
2734 #define INTERNAL_CATCH_MSG( macroName, messageType, resultDisposition, ... ) \
2735 do { \
2736 Catch::AssertionHandler catchAssertionHandler( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, Catch::StringRef(), resultDisposition ); \
2737 catchAssertionHandler.handleMessage( messageType, ( Catch::MessageStream() << __VA_ARGS__ + ::Catch::StreamEndStop() ).m_stream.str() ); \
2738 INTERNAL_CATCH_REACT( catchAssertionHandler ) \
2739 } while( false )
2740
2741 ///////////////////////////////////////////////////////////////////////////////
2742 #define INTERNAL_CATCH_CAPTURE( varName, macroName, ... ) \
2743 auto varName = Catch::Capturer( macroName, CATCH_INTERNAL_LINEINFO, Catch::ResultWas::Info, #__VA_ARGS__ ); \
2744 varName.captureValues( 0, __VA_ARGS__ )
2745
2746 ///////////////////////////////////////////////////////////////////////////////
2747 #define INTERNAL_CATCH_INFO( macroName, log ) \
2748 Catch::ScopedMessage INTERNAL_CATCH_UNIQUE_NAME( scopedMessage )( Catch::MessageBuilder( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, Catch::ResultWas::Info ) << log );
2749
2750 ///////////////////////////////////////////////////////////////////////////////
2751 #define INTERNAL_CATCH_UNSCOPED_INFO( macroName, log ) \
2752 Catch::getResultCapture().emplaceUnscopedMessage( Catch::MessageBuilder( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, Catch::ResultWas::Info ) << log )
2753
2754 ///////////////////////////////////////////////////////////////////////////////
2755 // Although this is matcher-based, it can be used with just a string
2756 #define INTERNAL_CATCH_THROWS_STR_MATCHES( macroName, resultDisposition, matcher, ... ) \
2757 do { \
2758 Catch::AssertionHandler catchAssertionHandler( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(__VA_ARGS__) ", " CATCH_INTERNAL_STRINGIFY(matcher), resultDisposition ); \
2759 if( catchAssertionHandler.allowThrows() ) \
2760 try { \
2761 static_cast<void>(__VA_ARGS__); \
2762 catchAssertionHandler.handleUnexpectedExceptionNotThrown(); \
2763 } \
2764 catch( ... ) { \
2765 Catch::handleExceptionMatchExpr( catchAssertionHandler, matcher, #matcher##_catch_sr ); \
2766 } \
2767 else \
2768 catchAssertionHandler.handleThrowingCallSkipped(); \
2769 INTERNAL_CATCH_REACT( catchAssertionHandler ) \
2770 } while( false )
2771
2772 #endif // CATCH_CONFIG_DISABLE
2773
2774 // end catch_capture.hpp
2775 // start catch_section.h
2776
2777 // start catch_section_info.h
2778
2779 // start catch_totals.h
2780
2781 #include <cstddef>
2782
2783 namespace Catch {
2784
2785 struct Counts {
2786 Counts operator - ( Counts const& other ) const;
2787 Counts& operator += ( Counts const& other );
2788
2789 std::size_t total() const;
2790 bool allPassed() const;
2791 bool allOk() const;
2792
2793 std::size_t passed = 0;
2794 std::size_t failed = 0;
2795 std::size_t failedButOk = 0;
2796 };
2797
2798 struct Totals {
2799
2800 Totals operator - ( Totals const& other ) const;
2801 Totals& operator += ( Totals const& other );
2802
2803 Totals delta( Totals const& prevTotals ) const;
2804
2805 int error = 0;
2806 Counts assertions;
2807 Counts testCases;
2808 };
2809 }
2810
2811 // end catch_totals.h
2812 #include <string>
2813
2814 namespace Catch {
2815
2816 struct SectionInfo {
2817 SectionInfo
2818 ( SourceLineInfo const& _lineInfo,
2819 std::string const& _name );
2820
2821 // Deprecated
SectionInfoCatch::SectionInfo2822 SectionInfo
2823 ( SourceLineInfo const& _lineInfo,
2824 std::string const& _name,
2825 std::string const& ) : SectionInfo( _lineInfo, _name ) {}
2826
2827 std::string name;
2828 std::string description; // !Deprecated: this will always be empty
2829 SourceLineInfo lineInfo;
2830 };
2831
2832 struct SectionEndInfo {
2833 SectionInfo sectionInfo;
2834 Counts prevAssertions;
2835 double durationInSeconds;
2836 };
2837
2838 } // end namespace Catch
2839
2840 // end catch_section_info.h
2841 // start catch_timer.h
2842
2843 #include <cstdint>
2844
2845 namespace Catch {
2846
2847 auto getCurrentNanosecondsSinceEpoch() -> uint64_t;
2848 auto getEstimatedClockResolution() -> uint64_t;
2849
2850 class Timer {
2851 uint64_t m_nanoseconds = 0;
2852 public:
2853 void start();
2854 auto getElapsedNanoseconds() const -> uint64_t;
2855 auto getElapsedMicroseconds() const -> uint64_t;
2856 auto getElapsedMilliseconds() const -> unsigned int;
2857 auto getElapsedSeconds() const -> double;
2858 };
2859
2860 } // namespace Catch
2861
2862 // end catch_timer.h
2863 #include <string>
2864
2865 namespace Catch {
2866
2867 class Section : NonCopyable {
2868 public:
2869 Section( SectionInfo const& info );
2870 ~Section();
2871
2872 // This indicates whether the section should be executed or not
2873 explicit operator bool() const;
2874
2875 private:
2876 SectionInfo m_info;
2877
2878 std::string m_name;
2879 Counts m_assertions;
2880 bool m_sectionIncluded;
2881 Timer m_timer;
2882 };
2883
2884 } // end namespace Catch
2885
2886 #define INTERNAL_CATCH_SECTION( ... ) \
2887 CATCH_INTERNAL_SUPPRESS_UNUSED_WARNINGS \
2888 if( Catch::Section const& INTERNAL_CATCH_UNIQUE_NAME( catch_internal_Section ) = Catch::SectionInfo( CATCH_INTERNAL_LINEINFO, __VA_ARGS__ ) ) \
2889 CATCH_INTERNAL_UNSUPPRESS_UNUSED_WARNINGS
2890
2891 #define INTERNAL_CATCH_DYNAMIC_SECTION( ... ) \
2892 CATCH_INTERNAL_SUPPRESS_UNUSED_WARNINGS \
2893 if( Catch::Section const& INTERNAL_CATCH_UNIQUE_NAME( catch_internal_Section ) = Catch::SectionInfo( CATCH_INTERNAL_LINEINFO, (Catch::ReusableStringStream() << __VA_ARGS__).str() ) ) \
2894 CATCH_INTERNAL_UNSUPPRESS_UNUSED_WARNINGS
2895
2896 // end catch_section.h
2897 // start catch_interfaces_exception.h
2898
2899 // start catch_interfaces_registry_hub.h
2900
2901 #include <string>
2902 #include <memory>
2903
2904 namespace Catch {
2905
2906 class TestCase;
2907 struct ITestCaseRegistry;
2908 struct IExceptionTranslatorRegistry;
2909 struct IExceptionTranslator;
2910 struct IReporterRegistry;
2911 struct IReporterFactory;
2912 struct ITagAliasRegistry;
2913 struct IMutableEnumValuesRegistry;
2914
2915 class StartupExceptionRegistry;
2916
2917 using IReporterFactoryPtr = std::shared_ptr<IReporterFactory>;
2918
2919 struct IRegistryHub {
2920 virtual ~IRegistryHub();
2921
2922 virtual IReporterRegistry const& getReporterRegistry() const = 0;
2923 virtual ITestCaseRegistry const& getTestCaseRegistry() const = 0;
2924 virtual ITagAliasRegistry const& getTagAliasRegistry() const = 0;
2925 virtual IExceptionTranslatorRegistry const& getExceptionTranslatorRegistry() const = 0;
2926
2927 virtual StartupExceptionRegistry const& getStartupExceptionRegistry() const = 0;
2928 };
2929
2930 struct IMutableRegistryHub {
2931 virtual ~IMutableRegistryHub();
2932 virtual void registerReporter( std::string const& name, IReporterFactoryPtr const& factory ) = 0;
2933 virtual void registerListener( IReporterFactoryPtr const& factory ) = 0;
2934 virtual void registerTest( TestCase const& testInfo ) = 0;
2935 virtual void registerTranslator( const IExceptionTranslator* translator ) = 0;
2936 virtual void registerTagAlias( std::string const& alias, std::string const& tag, SourceLineInfo const& lineInfo ) = 0;
2937 virtual void registerStartupException() noexcept = 0;
2938 virtual IMutableEnumValuesRegistry& getMutableEnumValuesRegistry() = 0;
2939 };
2940
2941 IRegistryHub const& getRegistryHub();
2942 IMutableRegistryHub& getMutableRegistryHub();
2943 void cleanUp();
2944 std::string translateActiveException();
2945
2946 }
2947
2948 // end catch_interfaces_registry_hub.h
2949 #if defined(CATCH_CONFIG_DISABLE)
2950 #define INTERNAL_CATCH_TRANSLATE_EXCEPTION_NO_REG( translatorName, signature) \
2951 static std::string translatorName( signature )
2952 #endif
2953
2954 #include <exception>
2955 #include <string>
2956 #include <vector>
2957
2958 namespace Catch {
2959 using exceptionTranslateFunction = std::string(*)();
2960
2961 struct IExceptionTranslator;
2962 using ExceptionTranslators = std::vector<std::unique_ptr<IExceptionTranslator const>>;
2963
2964 struct IExceptionTranslator {
2965 virtual ~IExceptionTranslator();
2966 virtual std::string translate( ExceptionTranslators::const_iterator it, ExceptionTranslators::const_iterator itEnd ) const = 0;
2967 };
2968
2969 struct IExceptionTranslatorRegistry {
2970 virtual ~IExceptionTranslatorRegistry();
2971
2972 virtual std::string translateActiveException() const = 0;
2973 };
2974
2975 class ExceptionTranslatorRegistrar {
2976 template<typename T>
2977 class ExceptionTranslator : public IExceptionTranslator {
2978 public:
2979
ExceptionTranslator(std::string (* translateFunction)(T &))2980 ExceptionTranslator( std::string(*translateFunction)( T& ) )
2981 : m_translateFunction( translateFunction )
2982 {}
2983
translate(ExceptionTranslators::const_iterator it,ExceptionTranslators::const_iterator itEnd) const2984 std::string translate( ExceptionTranslators::const_iterator it, ExceptionTranslators::const_iterator itEnd ) const override {
2985 try {
2986 if( it == itEnd )
2987 std::rethrow_exception(std::current_exception());
2988 else
2989 return (*it)->translate( it+1, itEnd );
2990 }
2991 catch( T& ex ) {
2992 return m_translateFunction( ex );
2993 }
2994 }
2995
2996 protected:
2997 std::string(*m_translateFunction)( T& );
2998 };
2999
3000 public:
3001 template<typename T>
ExceptionTranslatorRegistrar(std::string (* translateFunction)(T &))3002 ExceptionTranslatorRegistrar( std::string(*translateFunction)( T& ) ) {
3003 getMutableRegistryHub().registerTranslator
3004 ( new ExceptionTranslator<T>( translateFunction ) );
3005 }
3006 };
3007 }
3008
3009 ///////////////////////////////////////////////////////////////////////////////
3010 #define INTERNAL_CATCH_TRANSLATE_EXCEPTION2( translatorName, signature ) \
3011 static std::string translatorName( signature ); \
3012 CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
3013 namespace{ Catch::ExceptionTranslatorRegistrar INTERNAL_CATCH_UNIQUE_NAME( catch_internal_ExceptionRegistrar )( &translatorName ); } \
3014 CATCH_INTERNAL_UNSUPPRESS_GLOBALS_WARNINGS \
3015 static std::string translatorName( signature )
3016
3017 #define INTERNAL_CATCH_TRANSLATE_EXCEPTION( signature ) INTERNAL_CATCH_TRANSLATE_EXCEPTION2( INTERNAL_CATCH_UNIQUE_NAME( catch_internal_ExceptionTranslator ), signature )
3018
3019 // end catch_interfaces_exception.h
3020 // start catch_approx.h
3021
3022 #include <type_traits>
3023
3024 namespace Catch {
3025 namespace Detail {
3026
3027 class Approx {
3028 private:
3029 bool equalityComparisonImpl(double other) const;
3030 // Validates the new margin (margin >= 0)
3031 // out-of-line to avoid including stdexcept in the header
3032 void setMargin(double margin);
3033 // Validates the new epsilon (0 < epsilon < 1)
3034 // out-of-line to avoid including stdexcept in the header
3035 void setEpsilon(double epsilon);
3036
3037 public:
3038 explicit Approx ( double value );
3039
3040 static Approx custom();
3041
3042 Approx operator-() const;
3043
3044 template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
operator ()(T const & value)3045 Approx operator()( T const& value ) {
3046 Approx approx( static_cast<double>(value) );
3047 approx.m_epsilon = m_epsilon;
3048 approx.m_margin = m_margin;
3049 approx.m_scale = m_scale;
3050 return approx;
3051 }
3052
3053 template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
Approx(T const & value)3054 explicit Approx( T const& value ): Approx(static_cast<double>(value))
3055 {}
3056
3057 template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
operator ==(const T & lhs,Approx const & rhs)3058 friend bool operator == ( const T& lhs, Approx const& rhs ) {
3059 auto lhs_v = static_cast<double>(lhs);
3060 return rhs.equalityComparisonImpl(lhs_v);
3061 }
3062
3063 template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
operator ==(Approx const & lhs,const T & rhs)3064 friend bool operator == ( Approx const& lhs, const T& rhs ) {
3065 return operator==( rhs, lhs );
3066 }
3067
3068 template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
operator !=(T const & lhs,Approx const & rhs)3069 friend bool operator != ( T const& lhs, Approx const& rhs ) {
3070 return !operator==( lhs, rhs );
3071 }
3072
3073 template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
operator !=(Approx const & lhs,T const & rhs)3074 friend bool operator != ( Approx const& lhs, T const& rhs ) {
3075 return !operator==( rhs, lhs );
3076 }
3077
3078 template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
operator <=(T const & lhs,Approx const & rhs)3079 friend bool operator <= ( T const& lhs, Approx const& rhs ) {
3080 return static_cast<double>(lhs) < rhs.m_value || lhs == rhs;
3081 }
3082
3083 template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
operator <=(Approx const & lhs,T const & rhs)3084 friend bool operator <= ( Approx const& lhs, T const& rhs ) {
3085 return lhs.m_value < static_cast<double>(rhs) || lhs == rhs;
3086 }
3087
3088 template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
operator >=(T const & lhs,Approx const & rhs)3089 friend bool operator >= ( T const& lhs, Approx const& rhs ) {
3090 return static_cast<double>(lhs) > rhs.m_value || lhs == rhs;
3091 }
3092
3093 template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
operator >=(Approx const & lhs,T const & rhs)3094 friend bool operator >= ( Approx const& lhs, T const& rhs ) {
3095 return lhs.m_value > static_cast<double>(rhs) || lhs == rhs;
3096 }
3097
3098 template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
epsilon(T const & newEpsilon)3099 Approx& epsilon( T const& newEpsilon ) {
3100 double epsilonAsDouble = static_cast<double>(newEpsilon);
3101 setEpsilon(epsilonAsDouble);
3102 return *this;
3103 }
3104
3105 template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
margin(T const & newMargin)3106 Approx& margin( T const& newMargin ) {
3107 double marginAsDouble = static_cast<double>(newMargin);
3108 setMargin(marginAsDouble);
3109 return *this;
3110 }
3111
3112 template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
scale(T const & newScale)3113 Approx& scale( T const& newScale ) {
3114 m_scale = static_cast<double>(newScale);
3115 return *this;
3116 }
3117
3118 std::string toString() const;
3119
3120 private:
3121 double m_epsilon;
3122 double m_margin;
3123 double m_scale;
3124 double m_value;
3125 };
3126 } // end namespace Detail
3127
3128 namespace literals {
3129 Detail::Approx operator "" _a(long double val);
3130 Detail::Approx operator "" _a(unsigned long long val);
3131 } // end namespace literals
3132
3133 template<>
3134 struct StringMaker<Catch::Detail::Approx> {
3135 static std::string convert(Catch::Detail::Approx const& value);
3136 };
3137
3138 } // end namespace Catch
3139
3140 // end catch_approx.h
3141 // start catch_string_manip.h
3142
3143 #include <string>
3144 #include <iosfwd>
3145 #include <vector>
3146
3147 namespace Catch {
3148
3149 bool startsWith( std::string const& s, std::string const& prefix );
3150 bool startsWith( std::string const& s, char prefix );
3151 bool endsWith( std::string const& s, std::string const& suffix );
3152 bool endsWith( std::string const& s, char suffix );
3153 bool contains( std::string const& s, std::string const& infix );
3154 void toLowerInPlace( std::string& s );
3155 std::string toLower( std::string const& s );
3156 std::string trim( std::string const& str );
3157
3158 // !!! Be aware, returns refs into original string - make sure original string outlives them
3159 std::vector<StringRef> splitStringRef( StringRef str, char delimiter );
3160 bool replaceInPlace( std::string& str, std::string const& replaceThis, std::string const& withThis );
3161
3162 struct pluralise {
3163 pluralise( std::size_t count, std::string const& label );
3164
3165 friend std::ostream& operator << ( std::ostream& os, pluralise const& pluraliser );
3166
3167 std::size_t m_count;
3168 std::string m_label;
3169 };
3170 }
3171
3172 // end catch_string_manip.h
3173 #ifndef CATCH_CONFIG_DISABLE_MATCHERS
3174 // start catch_capture_matchers.h
3175
3176 // start catch_matchers.h
3177
3178 #include <string>
3179 #include <vector>
3180
3181 namespace Catch {
3182 namespace Matchers {
3183 namespace Impl {
3184
3185 template<typename ArgT> struct MatchAllOf;
3186 template<typename ArgT> struct MatchAnyOf;
3187 template<typename ArgT> struct MatchNotOf;
3188
3189 class MatcherUntypedBase {
3190 public:
3191 MatcherUntypedBase() = default;
3192 MatcherUntypedBase ( MatcherUntypedBase const& ) = default;
3193 MatcherUntypedBase& operator = ( MatcherUntypedBase const& ) = delete;
3194 std::string toString() const;
3195
3196 protected:
3197 virtual ~MatcherUntypedBase();
3198 virtual std::string describe() const = 0;
3199 mutable std::string m_cachedToString;
3200 };
3201
3202 #ifdef __clang__
3203 # pragma clang diagnostic push
3204 # pragma clang diagnostic ignored "-Wnon-virtual-dtor"
3205 #endif
3206
3207 template<typename ObjectT>
3208 struct MatcherMethod {
3209 virtual bool match( ObjectT const& arg ) const = 0;
3210 };
3211
3212 #if defined(__OBJC__)
3213 // Hack to fix Catch GH issue #1661. Could use id for generic Object support.
3214 // use of const for Object pointers is very uncommon and under ARC it causes some kind of signature mismatch that breaks compilation
3215 template<>
3216 struct MatcherMethod<NSString*> {
3217 virtual bool match( NSString* arg ) const = 0;
3218 };
3219 #endif
3220
3221 #ifdef __clang__
3222 # pragma clang diagnostic pop
3223 #endif
3224
3225 template<typename T>
3226 struct MatcherBase : MatcherUntypedBase, MatcherMethod<T> {
3227
3228 MatchAllOf<T> operator && ( MatcherBase const& other ) const;
3229 MatchAnyOf<T> operator || ( MatcherBase const& other ) const;
3230 MatchNotOf<T> operator ! () const;
3231 };
3232
3233 template<typename ArgT>
3234 struct MatchAllOf : MatcherBase<ArgT> {
matchCatch::Matchers::Impl::MatchAllOf3235 bool match( ArgT const& arg ) const override {
3236 for( auto matcher : m_matchers ) {
3237 if (!matcher->match(arg))
3238 return false;
3239 }
3240 return true;
3241 }
describeCatch::Matchers::Impl::MatchAllOf3242 std::string describe() const override {
3243 std::string description;
3244 description.reserve( 4 + m_matchers.size()*32 );
3245 description += "( ";
3246 bool first = true;
3247 for( auto matcher : m_matchers ) {
3248 if( first )
3249 first = false;
3250 else
3251 description += " and ";
3252 description += matcher->toString();
3253 }
3254 description += " )";
3255 return description;
3256 }
3257
operator &&Catch::Matchers::Impl::MatchAllOf3258 MatchAllOf<ArgT>& operator && ( MatcherBase<ArgT> const& other ) {
3259 m_matchers.push_back( &other );
3260 return *this;
3261 }
3262
3263 std::vector<MatcherBase<ArgT> const*> m_matchers;
3264 };
3265 template<typename ArgT>
3266 struct MatchAnyOf : MatcherBase<ArgT> {
3267
matchCatch::Matchers::Impl::MatchAnyOf3268 bool match( ArgT const& arg ) const override {
3269 for( auto matcher : m_matchers ) {
3270 if (matcher->match(arg))
3271 return true;
3272 }
3273 return false;
3274 }
describeCatch::Matchers::Impl::MatchAnyOf3275 std::string describe() const override {
3276 std::string description;
3277 description.reserve( 4 + m_matchers.size()*32 );
3278 description += "( ";
3279 bool first = true;
3280 for( auto matcher : m_matchers ) {
3281 if( first )
3282 first = false;
3283 else
3284 description += " or ";
3285 description += matcher->toString();
3286 }
3287 description += " )";
3288 return description;
3289 }
3290
operator ||Catch::Matchers::Impl::MatchAnyOf3291 MatchAnyOf<ArgT>& operator || ( MatcherBase<ArgT> const& other ) {
3292 m_matchers.push_back( &other );
3293 return *this;
3294 }
3295
3296 std::vector<MatcherBase<ArgT> const*> m_matchers;
3297 };
3298
3299 template<typename ArgT>
3300 struct MatchNotOf : MatcherBase<ArgT> {
3301
MatchNotOfCatch::Matchers::Impl::MatchNotOf3302 MatchNotOf( MatcherBase<ArgT> const& underlyingMatcher ) : m_underlyingMatcher( underlyingMatcher ) {}
3303
matchCatch::Matchers::Impl::MatchNotOf3304 bool match( ArgT const& arg ) const override {
3305 return !m_underlyingMatcher.match( arg );
3306 }
3307
describeCatch::Matchers::Impl::MatchNotOf3308 std::string describe() const override {
3309 return "not " + m_underlyingMatcher.toString();
3310 }
3311 MatcherBase<ArgT> const& m_underlyingMatcher;
3312 };
3313
3314 template<typename T>
operator &&(MatcherBase const & other) const3315 MatchAllOf<T> MatcherBase<T>::operator && ( MatcherBase const& other ) const {
3316 return MatchAllOf<T>() && *this && other;
3317 }
3318 template<typename T>
operator ||(MatcherBase const & other) const3319 MatchAnyOf<T> MatcherBase<T>::operator || ( MatcherBase const& other ) const {
3320 return MatchAnyOf<T>() || *this || other;
3321 }
3322 template<typename T>
operator !() const3323 MatchNotOf<T> MatcherBase<T>::operator ! () const {
3324 return MatchNotOf<T>( *this );
3325 }
3326
3327 } // namespace Impl
3328
3329 } // namespace Matchers
3330
3331 using namespace Matchers;
3332 using Matchers::Impl::MatcherBase;
3333
3334 } // namespace Catch
3335
3336 // end catch_matchers.h
3337 // start catch_matchers_floating.h
3338
3339 #include <type_traits>
3340 #include <cmath>
3341
3342 namespace Catch {
3343 namespace Matchers {
3344
3345 namespace Floating {
3346
3347 enum class FloatingPointKind : uint8_t;
3348
3349 struct WithinAbsMatcher : MatcherBase<double> {
3350 WithinAbsMatcher(double target, double margin);
3351 bool match(double const& matchee) const override;
3352 std::string describe() const override;
3353 private:
3354 double m_target;
3355 double m_margin;
3356 };
3357
3358 struct WithinUlpsMatcher : MatcherBase<double> {
3359 WithinUlpsMatcher(double target, int ulps, FloatingPointKind baseType);
3360 bool match(double const& matchee) const override;
3361 std::string describe() const override;
3362 private:
3363 double m_target;
3364 int m_ulps;
3365 FloatingPointKind m_type;
3366 };
3367
3368 } // namespace Floating
3369
3370 // The following functions create the actual matcher objects.
3371 // This allows the types to be inferred
3372 Floating::WithinUlpsMatcher WithinULP(double target, int maxUlpDiff);
3373 Floating::WithinUlpsMatcher WithinULP(float target, int maxUlpDiff);
3374 Floating::WithinAbsMatcher WithinAbs(double target, double margin);
3375
3376 } // namespace Matchers
3377 } // namespace Catch
3378
3379 // end catch_matchers_floating.h
3380 // start catch_matchers_generic.hpp
3381
3382 #include <functional>
3383 #include <string>
3384
3385 namespace Catch {
3386 namespace Matchers {
3387 namespace Generic {
3388
3389 namespace Detail {
3390 std::string finalizeDescription(const std::string& desc);
3391 }
3392
3393 template <typename T>
3394 class PredicateMatcher : public MatcherBase<T> {
3395 std::function<bool(T const&)> m_predicate;
3396 std::string m_description;
3397 public:
3398
PredicateMatcher(std::function<bool (T const &)> const & elem,std::string const & descr)3399 PredicateMatcher(std::function<bool(T const&)> const& elem, std::string const& descr)
3400 :m_predicate(std::move(elem)),
3401 m_description(Detail::finalizeDescription(descr))
3402 {}
3403
match(T const & item) const3404 bool match( T const& item ) const override {
3405 return m_predicate(item);
3406 }
3407
describe() const3408 std::string describe() const override {
3409 return m_description;
3410 }
3411 };
3412
3413 } // namespace Generic
3414
3415 // The following functions create the actual matcher objects.
3416 // The user has to explicitly specify type to the function, because
3417 // inferring std::function<bool(T const&)> is hard (but possible) and
3418 // requires a lot of TMP.
3419 template<typename T>
Predicate(std::function<bool (T const &)> const & predicate,std::string const & description="")3420 Generic::PredicateMatcher<T> Predicate(std::function<bool(T const&)> const& predicate, std::string const& description = "") {
3421 return Generic::PredicateMatcher<T>(predicate, description);
3422 }
3423
3424 } // namespace Matchers
3425 } // namespace Catch
3426
3427 // end catch_matchers_generic.hpp
3428 // start catch_matchers_string.h
3429
3430 #include <string>
3431
3432 namespace Catch {
3433 namespace Matchers {
3434
3435 namespace StdString {
3436
3437 struct CasedString
3438 {
3439 CasedString( std::string const& str, CaseSensitive::Choice caseSensitivity );
3440 std::string adjustString( std::string const& str ) const;
3441 std::string caseSensitivitySuffix() const;
3442
3443 CaseSensitive::Choice m_caseSensitivity;
3444 std::string m_str;
3445 };
3446
3447 struct StringMatcherBase : MatcherBase<std::string> {
3448 StringMatcherBase( std::string const& operation, CasedString const& comparator );
3449 std::string describe() const override;
3450
3451 CasedString m_comparator;
3452 std::string m_operation;
3453 };
3454
3455 struct EqualsMatcher : StringMatcherBase {
3456 EqualsMatcher( CasedString const& comparator );
3457 bool match( std::string const& source ) const override;
3458 };
3459 struct ContainsMatcher : StringMatcherBase {
3460 ContainsMatcher( CasedString const& comparator );
3461 bool match( std::string const& source ) const override;
3462 };
3463 struct StartsWithMatcher : StringMatcherBase {
3464 StartsWithMatcher( CasedString const& comparator );
3465 bool match( std::string const& source ) const override;
3466 };
3467 struct EndsWithMatcher : StringMatcherBase {
3468 EndsWithMatcher( CasedString const& comparator );
3469 bool match( std::string const& source ) const override;
3470 };
3471
3472 struct RegexMatcher : MatcherBase<std::string> {
3473 RegexMatcher( std::string regex, CaseSensitive::Choice caseSensitivity );
3474 bool match( std::string const& matchee ) const override;
3475 std::string describe() const override;
3476
3477 private:
3478 std::string m_regex;
3479 CaseSensitive::Choice m_caseSensitivity;
3480 };
3481
3482 } // namespace StdString
3483
3484 // The following functions create the actual matcher objects.
3485 // This allows the types to be inferred
3486
3487 StdString::EqualsMatcher Equals( std::string const& str, CaseSensitive::Choice caseSensitivity = CaseSensitive::Yes );
3488 StdString::ContainsMatcher Contains( std::string const& str, CaseSensitive::Choice caseSensitivity = CaseSensitive::Yes );
3489 StdString::EndsWithMatcher EndsWith( std::string const& str, CaseSensitive::Choice caseSensitivity = CaseSensitive::Yes );
3490 StdString::StartsWithMatcher StartsWith( std::string const& str, CaseSensitive::Choice caseSensitivity = CaseSensitive::Yes );
3491 StdString::RegexMatcher Matches( std::string const& regex, CaseSensitive::Choice caseSensitivity = CaseSensitive::Yes );
3492
3493 } // namespace Matchers
3494 } // namespace Catch
3495
3496 // end catch_matchers_string.h
3497 // start catch_matchers_vector.h
3498
3499 #include <algorithm>
3500
3501 namespace Catch {
3502 namespace Matchers {
3503
3504 namespace Vector {
3505 template<typename T>
3506 struct ContainsElementMatcher : MatcherBase<std::vector<T>> {
3507
ContainsElementMatcherCatch::Matchers::Vector::ContainsElementMatcher3508 ContainsElementMatcher(T const &comparator) : m_comparator( comparator) {}
3509
matchCatch::Matchers::Vector::ContainsElementMatcher3510 bool match(std::vector<T> const &v) const override {
3511 for (auto const& el : v) {
3512 if (el == m_comparator) {
3513 return true;
3514 }
3515 }
3516 return false;
3517 }
3518
describeCatch::Matchers::Vector::ContainsElementMatcher3519 std::string describe() const override {
3520 return "Contains: " + ::Catch::Detail::stringify( m_comparator );
3521 }
3522
3523 T const& m_comparator;
3524 };
3525
3526 template<typename T>
3527 struct ContainsMatcher : MatcherBase<std::vector<T>> {
3528
ContainsMatcherCatch::Matchers::Vector::ContainsMatcher3529 ContainsMatcher(std::vector<T> const &comparator) : m_comparator( comparator ) {}
3530
matchCatch::Matchers::Vector::ContainsMatcher3531 bool match(std::vector<T> const &v) const override {
3532 // !TBD: see note in EqualsMatcher
3533 if (m_comparator.size() > v.size())
3534 return false;
3535 for (auto const& comparator : m_comparator) {
3536 auto present = false;
3537 for (const auto& el : v) {
3538 if (el == comparator) {
3539 present = true;
3540 break;
3541 }
3542 }
3543 if (!present) {
3544 return false;
3545 }
3546 }
3547 return true;
3548 }
describeCatch::Matchers::Vector::ContainsMatcher3549 std::string describe() const override {
3550 return "Contains: " + ::Catch::Detail::stringify( m_comparator );
3551 }
3552
3553 std::vector<T> const& m_comparator;
3554 };
3555
3556 template<typename T>
3557 struct EqualsMatcher : MatcherBase<std::vector<T>> {
3558
EqualsMatcherCatch::Matchers::Vector::EqualsMatcher3559 EqualsMatcher(std::vector<T> const &comparator) : m_comparator( comparator ) {}
3560
matchCatch::Matchers::Vector::EqualsMatcher3561 bool match(std::vector<T> const &v) const override {
3562 // !TBD: This currently works if all elements can be compared using !=
3563 // - a more general approach would be via a compare template that defaults
3564 // to using !=. but could be specialised for, e.g. std::vector<T> etc
3565 // - then just call that directly
3566 if (m_comparator.size() != v.size())
3567 return false;
3568 for (std::size_t i = 0; i < v.size(); ++i)
3569 if (m_comparator[i] != v[i])
3570 return false;
3571 return true;
3572 }
describeCatch::Matchers::Vector::EqualsMatcher3573 std::string describe() const override {
3574 return "Equals: " + ::Catch::Detail::stringify( m_comparator );
3575 }
3576 std::vector<T> const& m_comparator;
3577 };
3578
3579 template<typename T>
3580 struct ApproxMatcher : MatcherBase<std::vector<T>> {
3581
ApproxMatcherCatch::Matchers::Vector::ApproxMatcher3582 ApproxMatcher(std::vector<T> const& comparator) : m_comparator( comparator ) {}
3583
matchCatch::Matchers::Vector::ApproxMatcher3584 bool match(std::vector<T> const &v) const override {
3585 if (m_comparator.size() != v.size())
3586 return false;
3587 for (std::size_t i = 0; i < v.size(); ++i)
3588 if (m_comparator[i] != approx(v[i]))
3589 return false;
3590 return true;
3591 }
describeCatch::Matchers::Vector::ApproxMatcher3592 std::string describe() const override {
3593 return "is approx: " + ::Catch::Detail::stringify( m_comparator );
3594 }
3595 template <typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
epsilonCatch::Matchers::Vector::ApproxMatcher3596 ApproxMatcher& epsilon( T const& newEpsilon ) {
3597 approx.epsilon(newEpsilon);
3598 return *this;
3599 }
3600 template <typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
marginCatch::Matchers::Vector::ApproxMatcher3601 ApproxMatcher& margin( T const& newMargin ) {
3602 approx.margin(newMargin);
3603 return *this;
3604 }
3605 template <typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
scaleCatch::Matchers::Vector::ApproxMatcher3606 ApproxMatcher& scale( T const& newScale ) {
3607 approx.scale(newScale);
3608 return *this;
3609 }
3610
3611 std::vector<T> const& m_comparator;
3612 mutable Catch::Detail::Approx approx = Catch::Detail::Approx::custom();
3613 };
3614
3615 template<typename T>
3616 struct UnorderedEqualsMatcher : MatcherBase<std::vector<T>> {
UnorderedEqualsMatcherCatch::Matchers::Vector::UnorderedEqualsMatcher3617 UnorderedEqualsMatcher(std::vector<T> const& target) : m_target(target) {}
matchCatch::Matchers::Vector::UnorderedEqualsMatcher3618 bool match(std::vector<T> const& vec) const override {
3619 // Note: This is a reimplementation of std::is_permutation,
3620 // because I don't want to include <algorithm> inside the common path
3621 if (m_target.size() != vec.size()) {
3622 return false;
3623 }
3624 return std::is_permutation(m_target.begin(), m_target.end(), vec.begin());
3625 }
3626
describeCatch::Matchers::Vector::UnorderedEqualsMatcher3627 std::string describe() const override {
3628 return "UnorderedEquals: " + ::Catch::Detail::stringify(m_target);
3629 }
3630 private:
3631 std::vector<T> const& m_target;
3632 };
3633
3634 } // namespace Vector
3635
3636 // The following functions create the actual matcher objects.
3637 // This allows the types to be inferred
3638
3639 template<typename T>
Contains(std::vector<T> const & comparator)3640 Vector::ContainsMatcher<T> Contains( std::vector<T> const& comparator ) {
3641 return Vector::ContainsMatcher<T>( comparator );
3642 }
3643
3644 template<typename T>
VectorContains(T const & comparator)3645 Vector::ContainsElementMatcher<T> VectorContains( T const& comparator ) {
3646 return Vector::ContainsElementMatcher<T>( comparator );
3647 }
3648
3649 template<typename T>
Equals(std::vector<T> const & comparator)3650 Vector::EqualsMatcher<T> Equals( std::vector<T> const& comparator ) {
3651 return Vector::EqualsMatcher<T>( comparator );
3652 }
3653
3654 template<typename T>
Approx(std::vector<T> const & comparator)3655 Vector::ApproxMatcher<T> Approx( std::vector<T> const& comparator ) {
3656 return Vector::ApproxMatcher<T>( comparator );
3657 }
3658
3659 template<typename T>
UnorderedEquals(std::vector<T> const & target)3660 Vector::UnorderedEqualsMatcher<T> UnorderedEquals(std::vector<T> const& target) {
3661 return Vector::UnorderedEqualsMatcher<T>(target);
3662 }
3663
3664 } // namespace Matchers
3665 } // namespace Catch
3666
3667 // end catch_matchers_vector.h
3668 namespace Catch {
3669
3670 template<typename ArgT, typename MatcherT>
3671 class MatchExpr : public ITransientExpression {
3672 ArgT const& m_arg;
3673 MatcherT m_matcher;
3674 StringRef m_matcherString;
3675 public:
MatchExpr(ArgT const & arg,MatcherT const & matcher,StringRef const & matcherString)3676 MatchExpr( ArgT const& arg, MatcherT const& matcher, StringRef const& matcherString )
3677 : ITransientExpression{ true, matcher.match( arg ) },
3678 m_arg( arg ),
3679 m_matcher( matcher ),
3680 m_matcherString( matcherString )
3681 {}
3682
streamReconstructedExpression(std::ostream & os) const3683 void streamReconstructedExpression( std::ostream &os ) const override {
3684 auto matcherAsString = m_matcher.toString();
3685 os << Catch::Detail::stringify( m_arg ) << ' ';
3686 if( matcherAsString == Detail::unprintableString )
3687 os << m_matcherString;
3688 else
3689 os << matcherAsString;
3690 }
3691 };
3692
3693 using StringMatcher = Matchers::Impl::MatcherBase<std::string>;
3694
3695 void handleExceptionMatchExpr( AssertionHandler& handler, StringMatcher const& matcher, StringRef const& matcherString );
3696
3697 template<typename ArgT, typename MatcherT>
makeMatchExpr(ArgT const & arg,MatcherT const & matcher,StringRef const & matcherString)3698 auto makeMatchExpr( ArgT const& arg, MatcherT const& matcher, StringRef const& matcherString ) -> MatchExpr<ArgT, MatcherT> {
3699 return MatchExpr<ArgT, MatcherT>( arg, matcher, matcherString );
3700 }
3701
3702 } // namespace Catch
3703
3704 ///////////////////////////////////////////////////////////////////////////////
3705 #define INTERNAL_CHECK_THAT( macroName, matcher, resultDisposition, arg ) \
3706 do { \
3707 Catch::AssertionHandler catchAssertionHandler( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(arg) ", " CATCH_INTERNAL_STRINGIFY(matcher), resultDisposition ); \
3708 INTERNAL_CATCH_TRY { \
3709 catchAssertionHandler.handleExpr( Catch::makeMatchExpr( arg, matcher, #matcher##_catch_sr ) ); \
3710 } INTERNAL_CATCH_CATCH( catchAssertionHandler ) \
3711 INTERNAL_CATCH_REACT( catchAssertionHandler ) \
3712 } while( false )
3713
3714 ///////////////////////////////////////////////////////////////////////////////
3715 #define INTERNAL_CATCH_THROWS_MATCHES( macroName, exceptionType, resultDisposition, matcher, ... ) \
3716 do { \
3717 Catch::AssertionHandler catchAssertionHandler( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(__VA_ARGS__) ", " CATCH_INTERNAL_STRINGIFY(exceptionType) ", " CATCH_INTERNAL_STRINGIFY(matcher), resultDisposition ); \
3718 if( catchAssertionHandler.allowThrows() ) \
3719 try { \
3720 static_cast<void>(__VA_ARGS__ ); \
3721 catchAssertionHandler.handleUnexpectedExceptionNotThrown(); \
3722 } \
3723 catch( exceptionType const& ex ) { \
3724 catchAssertionHandler.handleExpr( Catch::makeMatchExpr( ex, matcher, #matcher##_catch_sr ) ); \
3725 } \
3726 catch( ... ) { \
3727 catchAssertionHandler.handleUnexpectedInflightException(); \
3728 } \
3729 else \
3730 catchAssertionHandler.handleThrowingCallSkipped(); \
3731 INTERNAL_CATCH_REACT( catchAssertionHandler ) \
3732 } while( false )
3733
3734 // end catch_capture_matchers.h
3735 #endif
3736 // start catch_generators.hpp
3737
3738 // start catch_interfaces_generatortracker.h
3739
3740
3741 #include <memory>
3742
3743 namespace Catch {
3744
3745 namespace Generators {
3746 class GeneratorUntypedBase {
3747 public:
3748 GeneratorUntypedBase() = default;
3749 virtual ~GeneratorUntypedBase();
3750 // Attempts to move the generator to the next element
3751 //
3752 // Returns true iff the move succeeded (and a valid element
3753 // can be retrieved).
3754 virtual bool next() = 0;
3755 };
3756 using GeneratorBasePtr = std::unique_ptr<GeneratorUntypedBase>;
3757
3758 } // namespace Generators
3759
3760 struct IGeneratorTracker {
3761 virtual ~IGeneratorTracker();
3762 virtual auto hasGenerator() const -> bool = 0;
3763 virtual auto getGenerator() const -> Generators::GeneratorBasePtr const& = 0;
3764 virtual void setGenerator( Generators::GeneratorBasePtr&& generator ) = 0;
3765 };
3766
3767 } // namespace Catch
3768
3769 // end catch_interfaces_generatortracker.h
3770 // start catch_enforce.h
3771
3772 #include <exception>
3773
3774 namespace Catch {
3775 #if !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
3776 template <typename Ex>
3777 [[noreturn]]
throw_exception(Ex const & e)3778 void throw_exception(Ex const& e) {
3779 throw e;
3780 }
3781 #else // ^^ Exceptions are enabled // Exceptions are disabled vv
3782 [[noreturn]]
3783 void throw_exception(std::exception const& e);
3784 #endif
3785
3786 [[noreturn]]
3787 void throw_logic_error(std::string const& msg);
3788 [[noreturn]]
3789 void throw_domain_error(std::string const& msg);
3790 [[noreturn]]
3791 void throw_runtime_error(std::string const& msg);
3792
3793 } // namespace Catch;
3794
3795 #define CATCH_MAKE_MSG(...) \
3796 (Catch::ReusableStringStream() << __VA_ARGS__).str()
3797
3798 #define CATCH_INTERNAL_ERROR(...) \
3799 Catch::throw_logic_error(CATCH_MAKE_MSG( CATCH_INTERNAL_LINEINFO << ": Internal Catch2 error: " << __VA_ARGS__));
3800
3801 #define CATCH_ERROR(...) \
3802 Catch::throw_domain_error(CATCH_MAKE_MSG( __VA_ARGS__ ));
3803
3804 #define CATCH_RUNTIME_ERROR(...) \
3805 Catch::throw_runtime_error(CATCH_MAKE_MSG( __VA_ARGS__ ));
3806
3807 #define CATCH_ENFORCE( condition, ... ) \
3808 do{ if( !(condition) ) CATCH_ERROR( __VA_ARGS__ ); } while(false)
3809
3810 // end catch_enforce.h
3811 #include <memory>
3812 #include <vector>
3813 #include <cassert>
3814
3815 #include <utility>
3816 #include <exception>
3817
3818 namespace Catch {
3819
3820 class GeneratorException : public std::exception {
3821 const char* const m_msg = "";
3822
3823 public:
GeneratorException(const char * msg)3824 GeneratorException(const char* msg):
3825 m_msg(msg)
3826 {}
3827
3828 const char* what() const noexcept override final;
3829 };
3830
3831 namespace Generators {
3832
3833 // !TBD move this into its own location?
3834 namespace pf{
3835 template<typename T, typename... Args>
make_unique(Args &&...args)3836 std::unique_ptr<T> make_unique( Args&&... args ) {
3837 return std::unique_ptr<T>(new T(std::forward<Args>(args)...));
3838 }
3839 }
3840
3841 template<typename T>
3842 struct IGenerator : GeneratorUntypedBase {
3843 virtual ~IGenerator() = default;
3844
3845 // Returns the current element of the generator
3846 //
3847 // \Precondition The generator is either freshly constructed,
3848 // or the last call to `next()` returned true
3849 virtual T const& get() const = 0;
3850 using type = T;
3851 };
3852
3853 template<typename T>
3854 class SingleValueGenerator final : public IGenerator<T> {
3855 T m_value;
3856 public:
SingleValueGenerator(T const & value)3857 SingleValueGenerator(T const& value) : m_value( value ) {}
SingleValueGenerator(T && value)3858 SingleValueGenerator(T&& value) : m_value(std::move(value)) {}
3859
get() const3860 T const& get() const override {
3861 return m_value;
3862 }
next()3863 bool next() override {
3864 return false;
3865 }
3866 };
3867
3868 template<typename T>
3869 class FixedValuesGenerator final : public IGenerator<T> {
3870 static_assert(!std::is_same<T, bool>::value,
3871 "ValuesGenerator does not support bools because of std::vector<bool>"
3872 "specialization, use SingleValue Generator instead.");
3873 std::vector<T> m_values;
3874 size_t m_idx = 0;
3875 public:
FixedValuesGenerator(std::initializer_list<T> values)3876 FixedValuesGenerator( std::initializer_list<T> values ) : m_values( values ) {}
3877
get() const3878 T const& get() const override {
3879 return m_values[m_idx];
3880 }
next()3881 bool next() override {
3882 ++m_idx;
3883 return m_idx < m_values.size();
3884 }
3885 };
3886
3887 template <typename T>
3888 class GeneratorWrapper final {
3889 std::unique_ptr<IGenerator<T>> m_generator;
3890 public:
GeneratorWrapper(std::unique_ptr<IGenerator<T>> generator)3891 GeneratorWrapper(std::unique_ptr<IGenerator<T>> generator):
3892 m_generator(std::move(generator))
3893 {}
get() const3894 T const& get() const {
3895 return m_generator->get();
3896 }
next()3897 bool next() {
3898 return m_generator->next();
3899 }
3900 };
3901
3902 template <typename T>
value(T && value)3903 GeneratorWrapper<T> value(T&& value) {
3904 return GeneratorWrapper<T>(pf::make_unique<SingleValueGenerator<T>>(std::forward<T>(value)));
3905 }
3906 template <typename T>
values(std::initializer_list<T> values)3907 GeneratorWrapper<T> values(std::initializer_list<T> values) {
3908 return GeneratorWrapper<T>(pf::make_unique<FixedValuesGenerator<T>>(values));
3909 }
3910
3911 template<typename T>
3912 class Generators : public IGenerator<T> {
3913 std::vector<GeneratorWrapper<T>> m_generators;
3914 size_t m_current = 0;
3915
populate(GeneratorWrapper<T> && generator)3916 void populate(GeneratorWrapper<T>&& generator) {
3917 m_generators.emplace_back(std::move(generator));
3918 }
populate(T && val)3919 void populate(T&& val) {
3920 m_generators.emplace_back(value(std::move(val)));
3921 }
3922 template<typename U>
populate(U && val)3923 void populate(U&& val) {
3924 populate(T(std::move(val)));
3925 }
3926 template<typename U, typename... Gs>
populate(U && valueOrGenerator,Gs...moreGenerators)3927 void populate(U&& valueOrGenerator, Gs... moreGenerators) {
3928 populate(std::forward<U>(valueOrGenerator));
3929 populate(std::forward<Gs>(moreGenerators)...);
3930 }
3931
3932 public:
3933 template <typename... Gs>
Generators(Gs...moreGenerators)3934 Generators(Gs... moreGenerators) {
3935 m_generators.reserve(sizeof...(Gs));
3936 populate(std::forward<Gs>(moreGenerators)...);
3937 }
3938
get() const3939 T const& get() const override {
3940 return m_generators[m_current].get();
3941 }
3942
next()3943 bool next() override {
3944 if (m_current >= m_generators.size()) {
3945 return false;
3946 }
3947 const bool current_status = m_generators[m_current].next();
3948 if (!current_status) {
3949 ++m_current;
3950 }
3951 return m_current < m_generators.size();
3952 }
3953 };
3954
3955 template<typename... Ts>
table(std::initializer_list<std::tuple<typename std::decay<Ts>::type...>> tuples)3956 GeneratorWrapper<std::tuple<Ts...>> table( std::initializer_list<std::tuple<typename std::decay<Ts>::type...>> tuples ) {
3957 return values<std::tuple<Ts...>>( tuples );
3958 }
3959
3960 // Tag type to signal that a generator sequence should convert arguments to a specific type
3961 template <typename T>
3962 struct as {};
3963
3964 template<typename T, typename... Gs>
makeGenerators(GeneratorWrapper<T> && generator,Gs...moreGenerators)3965 auto makeGenerators( GeneratorWrapper<T>&& generator, Gs... moreGenerators ) -> Generators<T> {
3966 return Generators<T>(std::move(generator), std::forward<Gs>(moreGenerators)...);
3967 }
3968 template<typename T>
makeGenerators(GeneratorWrapper<T> && generator)3969 auto makeGenerators( GeneratorWrapper<T>&& generator ) -> Generators<T> {
3970 return Generators<T>(std::move(generator));
3971 }
3972 template<typename T, typename... Gs>
makeGenerators(T && val,Gs...moreGenerators)3973 auto makeGenerators( T&& val, Gs... moreGenerators ) -> Generators<T> {
3974 return makeGenerators( value( std::forward<T>( val ) ), std::forward<Gs>( moreGenerators )... );
3975 }
3976 template<typename T, typename U, typename... Gs>
makeGenerators(as<T>,U && val,Gs...moreGenerators)3977 auto makeGenerators( as<T>, U&& val, Gs... moreGenerators ) -> Generators<T> {
3978 return makeGenerators( value( T( std::forward<U>( val ) ) ), std::forward<Gs>( moreGenerators )... );
3979 }
3980
3981 auto acquireGeneratorTracker( SourceLineInfo const& lineInfo ) -> IGeneratorTracker&;
3982
3983 template<typename L>
3984 // Note: The type after -> is weird, because VS2015 cannot parse
3985 // the expression used in the typedef inside, when it is in
3986 // return type. Yeah.
generate(SourceLineInfo const & lineInfo,L const & generatorExpression)3987 auto generate( SourceLineInfo const& lineInfo, L const& generatorExpression ) -> decltype(std::declval<decltype(generatorExpression())>().get()) {
3988 using UnderlyingType = typename decltype(generatorExpression())::type;
3989
3990 IGeneratorTracker& tracker = acquireGeneratorTracker( lineInfo );
3991 if (!tracker.hasGenerator()) {
3992 tracker.setGenerator(pf::make_unique<Generators<UnderlyingType>>(generatorExpression()));
3993 }
3994
3995 auto const& generator = static_cast<IGenerator<UnderlyingType> const&>( *tracker.getGenerator() );
3996 return generator.get();
3997 }
3998
3999 } // namespace Generators
4000 } // namespace Catch
4001
4002 #define GENERATE( ... ) \
4003 Catch::Generators::generate( CATCH_INTERNAL_LINEINFO, [ ]{ using namespace Catch::Generators; return makeGenerators( __VA_ARGS__ ); } )
4004 #define GENERATE_COPY( ... ) \
4005 Catch::Generators::generate( CATCH_INTERNAL_LINEINFO, [=]{ using namespace Catch::Generators; return makeGenerators( __VA_ARGS__ ); } )
4006 #define GENERATE_REF( ... ) \
4007 Catch::Generators::generate( CATCH_INTERNAL_LINEINFO, [&]{ using namespace Catch::Generators; return makeGenerators( __VA_ARGS__ ); } )
4008
4009 // end catch_generators.hpp
4010 // start catch_generators_generic.hpp
4011
4012 namespace Catch {
4013 namespace Generators {
4014
4015 template <typename T>
4016 class TakeGenerator : public IGenerator<T> {
4017 GeneratorWrapper<T> m_generator;
4018 size_t m_returned = 0;
4019 size_t m_target;
4020 public:
TakeGenerator(size_t target,GeneratorWrapper<T> && generator)4021 TakeGenerator(size_t target, GeneratorWrapper<T>&& generator):
4022 m_generator(std::move(generator)),
4023 m_target(target)
4024 {
4025 assert(target != 0 && "Empty generators are not allowed");
4026 }
get() const4027 T const& get() const override {
4028 return m_generator.get();
4029 }
next()4030 bool next() override {
4031 ++m_returned;
4032 if (m_returned >= m_target) {
4033 return false;
4034 }
4035
4036 const auto success = m_generator.next();
4037 // If the underlying generator does not contain enough values
4038 // then we cut short as well
4039 if (!success) {
4040 m_returned = m_target;
4041 }
4042 return success;
4043 }
4044 };
4045
4046 template <typename T>
take(size_t target,GeneratorWrapper<T> && generator)4047 GeneratorWrapper<T> take(size_t target, GeneratorWrapper<T>&& generator) {
4048 return GeneratorWrapper<T>(pf::make_unique<TakeGenerator<T>>(target, std::move(generator)));
4049 }
4050
4051 template <typename T, typename Predicate>
4052 class FilterGenerator : public IGenerator<T> {
4053 GeneratorWrapper<T> m_generator;
4054 Predicate m_predicate;
4055 public:
4056 template <typename P = Predicate>
FilterGenerator(P && pred,GeneratorWrapper<T> && generator)4057 FilterGenerator(P&& pred, GeneratorWrapper<T>&& generator):
4058 m_generator(std::move(generator)),
4059 m_predicate(std::forward<P>(pred))
4060 {
4061 if (!m_predicate(m_generator.get())) {
4062 // It might happen that there are no values that pass the
4063 // filter. In that case we throw an exception.
4064 auto has_initial_value = next();
4065 if (!has_initial_value) {
4066 Catch::throw_exception(GeneratorException("No valid value found in filtered generator"));
4067 }
4068 }
4069 }
4070
get() const4071 T const& get() const override {
4072 return m_generator.get();
4073 }
4074
next()4075 bool next() override {
4076 bool success = m_generator.next();
4077 if (!success) {
4078 return false;
4079 }
4080 while (!m_predicate(m_generator.get()) && (success = m_generator.next()) == true);
4081 return success;
4082 }
4083 };
4084
4085 template <typename T, typename Predicate>
filter(Predicate && pred,GeneratorWrapper<T> && generator)4086 GeneratorWrapper<T> filter(Predicate&& pred, GeneratorWrapper<T>&& generator) {
4087 return GeneratorWrapper<T>(std::unique_ptr<IGenerator<T>>(pf::make_unique<FilterGenerator<T, Predicate>>(std::forward<Predicate>(pred), std::move(generator))));
4088 }
4089
4090 template <typename T>
4091 class RepeatGenerator : public IGenerator<T> {
4092 static_assert(!std::is_same<T, bool>::value,
4093 "RepeatGenerator currently does not support bools"
4094 "because of std::vector<bool> specialization");
4095 GeneratorWrapper<T> m_generator;
4096 mutable std::vector<T> m_returned;
4097 size_t m_target_repeats;
4098 size_t m_current_repeat = 0;
4099 size_t m_repeat_index = 0;
4100 public:
RepeatGenerator(size_t repeats,GeneratorWrapper<T> && generator)4101 RepeatGenerator(size_t repeats, GeneratorWrapper<T>&& generator):
4102 m_generator(std::move(generator)),
4103 m_target_repeats(repeats)
4104 {
4105 assert(m_target_repeats > 0 && "Repeat generator must repeat at least once");
4106 }
4107
get() const4108 T const& get() const override {
4109 if (m_current_repeat == 0) {
4110 m_returned.push_back(m_generator.get());
4111 return m_returned.back();
4112 }
4113 return m_returned[m_repeat_index];
4114 }
4115
next()4116 bool next() override {
4117 // There are 2 basic cases:
4118 // 1) We are still reading the generator
4119 // 2) We are reading our own cache
4120
4121 // In the first case, we need to poke the underlying generator.
4122 // If it happily moves, we are left in that state, otherwise it is time to start reading from our cache
4123 if (m_current_repeat == 0) {
4124 const auto success = m_generator.next();
4125 if (!success) {
4126 ++m_current_repeat;
4127 }
4128 return m_current_repeat < m_target_repeats;
4129 }
4130
4131 // In the second case, we need to move indices forward and check that we haven't run up against the end
4132 ++m_repeat_index;
4133 if (m_repeat_index == m_returned.size()) {
4134 m_repeat_index = 0;
4135 ++m_current_repeat;
4136 }
4137 return m_current_repeat < m_target_repeats;
4138 }
4139 };
4140
4141 template <typename T>
repeat(size_t repeats,GeneratorWrapper<T> && generator)4142 GeneratorWrapper<T> repeat(size_t repeats, GeneratorWrapper<T>&& generator) {
4143 return GeneratorWrapper<T>(pf::make_unique<RepeatGenerator<T>>(repeats, std::move(generator)));
4144 }
4145
4146 template <typename T, typename U, typename Func>
4147 class MapGenerator : public IGenerator<T> {
4148 // TBD: provide static assert for mapping function, for friendly error message
4149 GeneratorWrapper<U> m_generator;
4150 Func m_function;
4151 // To avoid returning dangling reference, we have to save the values
4152 T m_cache;
4153 public:
4154 template <typename F2 = Func>
MapGenerator(F2 && function,GeneratorWrapper<U> && generator)4155 MapGenerator(F2&& function, GeneratorWrapper<U>&& generator) :
4156 m_generator(std::move(generator)),
4157 m_function(std::forward<F2>(function)),
4158 m_cache(m_function(m_generator.get()))
4159 {}
4160
get() const4161 T const& get() const override {
4162 return m_cache;
4163 }
next()4164 bool next() override {
4165 const auto success = m_generator.next();
4166 if (success) {
4167 m_cache = m_function(m_generator.get());
4168 }
4169 return success;
4170 }
4171 };
4172
4173 #if defined(__cpp_lib_is_invocable) && __cpp_lib_is_invocable >= 201703
4174 // std::result_of is deprecated in C++17 and removed in C++20. Hence, it is
4175 // replaced with std::invoke_result here. Also *_t format is preferred over
4176 // typename *::type format.
4177 template <typename Func, typename U>
4178 using MapFunctionReturnType = std::remove_reference_t<std::remove_cv_t<std::invoke_result_t<Func, U>>>;
4179 #else
4180 template <typename Func, typename U>
4181 using MapFunctionReturnType = typename std::remove_reference<typename std::remove_cv<typename std::result_of<Func(U)>::type>::type>::type;
4182 #endif
4183
4184 template <typename Func, typename U, typename T = MapFunctionReturnType<Func, U>>
map(Func && function,GeneratorWrapper<U> && generator)4185 GeneratorWrapper<T> map(Func&& function, GeneratorWrapper<U>&& generator) {
4186 return GeneratorWrapper<T>(
4187 pf::make_unique<MapGenerator<T, U, Func>>(std::forward<Func>(function), std::move(generator))
4188 );
4189 }
4190
4191 template <typename T, typename U, typename Func>
map(Func && function,GeneratorWrapper<U> && generator)4192 GeneratorWrapper<T> map(Func&& function, GeneratorWrapper<U>&& generator) {
4193 return GeneratorWrapper<T>(
4194 pf::make_unique<MapGenerator<T, U, Func>>(std::forward<Func>(function), std::move(generator))
4195 );
4196 }
4197
4198 template <typename T>
4199 class ChunkGenerator final : public IGenerator<std::vector<T>> {
4200 std::vector<T> m_chunk;
4201 size_t m_chunk_size;
4202 GeneratorWrapper<T> m_generator;
4203 bool m_used_up = false;
4204 public:
ChunkGenerator(size_t size,GeneratorWrapper<T> generator)4205 ChunkGenerator(size_t size, GeneratorWrapper<T> generator) :
4206 m_chunk_size(size), m_generator(std::move(generator))
4207 {
4208 m_chunk.reserve(m_chunk_size);
4209 if (m_chunk_size != 0) {
4210 m_chunk.push_back(m_generator.get());
4211 for (size_t i = 1; i < m_chunk_size; ++i) {
4212 if (!m_generator.next()) {
4213 Catch::throw_exception(GeneratorException("Not enough values to initialize the first chunk"));
4214 }
4215 m_chunk.push_back(m_generator.get());
4216 }
4217 }
4218 }
get() const4219 std::vector<T> const& get() const override {
4220 return m_chunk;
4221 }
next()4222 bool next() override {
4223 m_chunk.clear();
4224 for (size_t idx = 0; idx < m_chunk_size; ++idx) {
4225 if (!m_generator.next()) {
4226 return false;
4227 }
4228 m_chunk.push_back(m_generator.get());
4229 }
4230 return true;
4231 }
4232 };
4233
4234 template <typename T>
chunk(size_t size,GeneratorWrapper<T> && generator)4235 GeneratorWrapper<std::vector<T>> chunk(size_t size, GeneratorWrapper<T>&& generator) {
4236 return GeneratorWrapper<std::vector<T>>(
4237 pf::make_unique<ChunkGenerator<T>>(size, std::move(generator))
4238 );
4239 }
4240
4241 } // namespace Generators
4242 } // namespace Catch
4243
4244 // end catch_generators_generic.hpp
4245 // start catch_generators_specific.hpp
4246
4247 // start catch_context.h
4248
4249 #include <memory>
4250
4251 namespace Catch {
4252
4253 struct IResultCapture;
4254 struct IRunner;
4255 struct IConfig;
4256 struct IMutableContext;
4257
4258 using IConfigPtr = std::shared_ptr<IConfig const>;
4259
4260 struct IContext
4261 {
4262 virtual ~IContext();
4263
4264 virtual IResultCapture* getResultCapture() = 0;
4265 virtual IRunner* getRunner() = 0;
4266 virtual IConfigPtr const& getConfig() const = 0;
4267 };
4268
4269 struct IMutableContext : IContext
4270 {
4271 virtual ~IMutableContext();
4272 virtual void setResultCapture( IResultCapture* resultCapture ) = 0;
4273 virtual void setRunner( IRunner* runner ) = 0;
4274 virtual void setConfig( IConfigPtr const& config ) = 0;
4275
4276 private:
4277 static IMutableContext *currentContext;
4278 friend IMutableContext& getCurrentMutableContext();
4279 friend void cleanUpContext();
4280 static void createContext();
4281 };
4282
getCurrentMutableContext()4283 inline IMutableContext& getCurrentMutableContext()
4284 {
4285 if( !IMutableContext::currentContext )
4286 IMutableContext::createContext();
4287 return *IMutableContext::currentContext;
4288 }
4289
getCurrentContext()4290 inline IContext& getCurrentContext()
4291 {
4292 return getCurrentMutableContext();
4293 }
4294
4295 void cleanUpContext();
4296 }
4297
4298 // end catch_context.h
4299 // start catch_interfaces_config.h
4300
4301 // start catch_option.hpp
4302
4303 namespace Catch {
4304
4305 // An optional type
4306 template<typename T>
4307 class Option {
4308 public:
Option()4309 Option() : nullableValue( nullptr ) {}
Option(T const & _value)4310 Option( T const& _value )
4311 : nullableValue( new( storage ) T( _value ) )
4312 {}
Option(Option const & _other)4313 Option( Option const& _other )
4314 : nullableValue( _other ? new( storage ) T( *_other ) : nullptr )
4315 {}
4316
~Option()4317 ~Option() {
4318 reset();
4319 }
4320
operator =(Option const & _other)4321 Option& operator= ( Option const& _other ) {
4322 if( &_other != this ) {
4323 reset();
4324 if( _other )
4325 nullableValue = new( storage ) T( *_other );
4326 }
4327 return *this;
4328 }
operator =(T const & _value)4329 Option& operator = ( T const& _value ) {
4330 reset();
4331 nullableValue = new( storage ) T( _value );
4332 return *this;
4333 }
4334
reset()4335 void reset() {
4336 if( nullableValue )
4337 nullableValue->~T();
4338 nullableValue = nullptr;
4339 }
4340
operator *()4341 T& operator*() { return *nullableValue; }
operator *() const4342 T const& operator*() const { return *nullableValue; }
operator ->()4343 T* operator->() { return nullableValue; }
operator ->() const4344 const T* operator->() const { return nullableValue; }
4345
valueOr(T const & defaultValue) const4346 T valueOr( T const& defaultValue ) const {
4347 return nullableValue ? *nullableValue : defaultValue;
4348 }
4349
some() const4350 bool some() const { return nullableValue != nullptr; }
none() const4351 bool none() const { return nullableValue == nullptr; }
4352
operator !() const4353 bool operator !() const { return nullableValue == nullptr; }
operator bool() const4354 explicit operator bool() const {
4355 return some();
4356 }
4357
4358 private:
4359 T *nullableValue;
4360 alignas(alignof(T)) char storage[sizeof(T)];
4361 };
4362
4363 } // end namespace Catch
4364
4365 // end catch_option.hpp
4366 #include <iosfwd>
4367 #include <string>
4368 #include <vector>
4369 #include <memory>
4370
4371 namespace Catch {
4372
4373 enum class Verbosity {
4374 Quiet = 0,
4375 Normal,
4376 High
4377 };
4378
4379 struct WarnAbout { enum What {
4380 Nothing = 0x00,
4381 NoAssertions = 0x01,
4382 NoTests = 0x02
4383 }; };
4384
4385 struct ShowDurations { enum OrNot {
4386 DefaultForReporter,
4387 Always,
4388 Never
4389 }; };
4390 struct RunTests { enum InWhatOrder {
4391 InDeclarationOrder,
4392 InLexicographicalOrder,
4393 InRandomOrder
4394 }; };
4395 struct UseColour { enum YesOrNo {
4396 Auto,
4397 Yes,
4398 No
4399 }; };
4400 struct WaitForKeypress { enum When {
4401 Never,
4402 BeforeStart = 1,
4403 BeforeExit = 2,
4404 BeforeStartAndExit = BeforeStart | BeforeExit
4405 }; };
4406
4407 class TestSpec;
4408
4409 struct IConfig : NonCopyable {
4410
4411 virtual ~IConfig();
4412
4413 virtual bool allowThrows() const = 0;
4414 virtual std::ostream& stream() const = 0;
4415 virtual std::string name() const = 0;
4416 virtual bool includeSuccessfulResults() const = 0;
4417 virtual bool shouldDebugBreak() const = 0;
4418 virtual bool warnAboutMissingAssertions() const = 0;
4419 virtual bool warnAboutNoTests() const = 0;
4420 virtual int abortAfter() const = 0;
4421 virtual bool showInvisibles() const = 0;
4422 virtual ShowDurations::OrNot showDurations() const = 0;
4423 virtual TestSpec const& testSpec() const = 0;
4424 virtual bool hasTestFilters() const = 0;
4425 virtual std::vector<std::string> const& getTestsOrTags() const = 0;
4426 virtual RunTests::InWhatOrder runOrder() const = 0;
4427 virtual unsigned int rngSeed() const = 0;
4428 virtual UseColour::YesOrNo useColour() const = 0;
4429 virtual std::vector<std::string> const& getSectionsToRun() const = 0;
4430 virtual Verbosity verbosity() const = 0;
4431
4432 virtual bool benchmarkNoAnalysis() const = 0;
4433 virtual int benchmarkSamples() const = 0;
4434 virtual double benchmarkConfidenceInterval() const = 0;
4435 virtual unsigned int benchmarkResamples() const = 0;
4436 };
4437
4438 using IConfigPtr = std::shared_ptr<IConfig const>;
4439 }
4440
4441 // end catch_interfaces_config.h
4442 #include <random>
4443
4444 namespace Catch {
4445 namespace Generators {
4446
4447 template <typename Float>
4448 class RandomFloatingGenerator final : public IGenerator<Float> {
4449 // FIXME: What is the right seed?
4450 std::minstd_rand m_rand;
4451 std::uniform_real_distribution<Float> m_dist;
4452 Float m_current_number;
4453 public:
4454
RandomFloatingGenerator(Float a,Float b)4455 RandomFloatingGenerator(Float a, Float b):
4456 m_rand(getCurrentContext().getConfig()->rngSeed()),
4457 m_dist(a, b) {
4458 static_cast<void>(next());
4459 }
4460
get() const4461 Float const& get() const override {
4462 return m_current_number;
4463 }
next()4464 bool next() override {
4465 m_current_number = m_dist(m_rand);
4466 return true;
4467 }
4468 };
4469
4470 template <typename Integer>
4471 class RandomIntegerGenerator final : public IGenerator<Integer> {
4472 std::minstd_rand m_rand;
4473 std::uniform_int_distribution<Integer> m_dist;
4474 Integer m_current_number;
4475 public:
4476
RandomIntegerGenerator(Integer a,Integer b)4477 RandomIntegerGenerator(Integer a, Integer b):
4478 m_rand(getCurrentContext().getConfig()->rngSeed()),
4479 m_dist(a, b) {
4480 static_cast<void>(next());
4481 }
4482
get() const4483 Integer const& get() const override {
4484 return m_current_number;
4485 }
next()4486 bool next() override {
4487 m_current_number = m_dist(m_rand);
4488 return true;
4489 }
4490 };
4491
4492 // TODO: Ideally this would be also constrained against the various char types,
4493 // but I don't expect users to run into that in practice.
4494 template <typename T>
4495 typename std::enable_if<std::is_integral<T>::value && !std::is_same<T, bool>::value,
4496 GeneratorWrapper<T>>::type
random(T a,T b)4497 random(T a, T b) {
4498 return GeneratorWrapper<T>(
4499 pf::make_unique<RandomIntegerGenerator<T>>(a, b)
4500 );
4501 }
4502
4503 template <typename T>
4504 typename std::enable_if<std::is_floating_point<T>::value,
4505 GeneratorWrapper<T>>::type
random(T a,T b)4506 random(T a, T b) {
4507 return GeneratorWrapper<T>(
4508 pf::make_unique<RandomFloatingGenerator<T>>(a, b)
4509 );
4510 }
4511
4512 template <typename T>
4513 class RangeGenerator final : public IGenerator<T> {
4514 T m_current;
4515 T m_end;
4516 T m_step;
4517 bool m_positive;
4518
4519 public:
RangeGenerator(T const & start,T const & end,T const & step)4520 RangeGenerator(T const& start, T const& end, T const& step):
4521 m_current(start),
4522 m_end(end),
4523 m_step(step),
4524 m_positive(m_step > T(0))
4525 {
4526 assert(m_current != m_end && "Range start and end cannot be equal");
4527 assert(m_step != T(0) && "Step size cannot be zero");
4528 assert(((m_positive && m_current <= m_end) || (!m_positive && m_current >= m_end)) && "Step moves away from end");
4529 }
4530
RangeGenerator(T const & start,T const & end)4531 RangeGenerator(T const& start, T const& end):
4532 RangeGenerator(start, end, (start < end) ? T(1) : T(-1))
4533 {}
4534
get() const4535 T const& get() const override {
4536 return m_current;
4537 }
4538
next()4539 bool next() override {
4540 m_current += m_step;
4541 return (m_positive) ? (m_current < m_end) : (m_current > m_end);
4542 }
4543 };
4544
4545 template <typename T>
range(T const & start,T const & end,T const & step)4546 GeneratorWrapper<T> range(T const& start, T const& end, T const& step) {
4547 static_assert(std::is_integral<T>::value && !std::is_same<T, bool>::value, "Type must be an integer");
4548 return GeneratorWrapper<T>(pf::make_unique<RangeGenerator<T>>(start, end, step));
4549 }
4550
4551 template <typename T>
range(T const & start,T const & end)4552 GeneratorWrapper<T> range(T const& start, T const& end) {
4553 static_assert(std::is_integral<T>::value && !std::is_same<T, bool>::value, "Type must be an integer");
4554 return GeneratorWrapper<T>(pf::make_unique<RangeGenerator<T>>(start, end));
4555 }
4556
4557 } // namespace Generators
4558 } // namespace Catch
4559
4560 // end catch_generators_specific.hpp
4561
4562 // These files are included here so the single_include script doesn't put them
4563 // in the conditionally compiled sections
4564 // start catch_test_case_info.h
4565
4566 #include <string>
4567 #include <vector>
4568 #include <memory>
4569
4570 #ifdef __clang__
4571 #pragma clang diagnostic push
4572 #pragma clang diagnostic ignored "-Wpadded"
4573 #endif
4574
4575 namespace Catch {
4576
4577 struct ITestInvoker;
4578
4579 struct TestCaseInfo {
4580 enum SpecialProperties{
4581 None = 0,
4582 IsHidden = 1 << 1,
4583 ShouldFail = 1 << 2,
4584 MayFail = 1 << 3,
4585 Throws = 1 << 4,
4586 NonPortable = 1 << 5,
4587 Benchmark = 1 << 6
4588 };
4589
4590 TestCaseInfo( std::string const& _name,
4591 std::string const& _className,
4592 std::string const& _description,
4593 std::vector<std::string> const& _tags,
4594 SourceLineInfo const& _lineInfo );
4595
4596 friend void setTags( TestCaseInfo& testCaseInfo, std::vector<std::string> tags );
4597
4598 bool isHidden() const;
4599 bool throws() const;
4600 bool okToFail() const;
4601 bool expectedToFail() const;
4602
4603 std::string tagsAsString() const;
4604
4605 std::string name;
4606 std::string className;
4607 std::string description;
4608 std::vector<std::string> tags;
4609 std::vector<std::string> lcaseTags;
4610 SourceLineInfo lineInfo;
4611 SpecialProperties properties;
4612 };
4613
4614 class TestCase : public TestCaseInfo {
4615 public:
4616
4617 TestCase( ITestInvoker* testCase, TestCaseInfo&& info );
4618
4619 TestCase withName( std::string const& _newName ) const;
4620
4621 void invoke() const;
4622
4623 TestCaseInfo const& getTestCaseInfo() const;
4624
4625 bool operator == ( TestCase const& other ) const;
4626 bool operator < ( TestCase const& other ) const;
4627
4628 private:
4629 std::shared_ptr<ITestInvoker> test;
4630 };
4631
4632 TestCase makeTestCase( ITestInvoker* testCase,
4633 std::string const& className,
4634 NameAndTags const& nameAndTags,
4635 SourceLineInfo const& lineInfo );
4636 }
4637
4638 #ifdef __clang__
4639 #pragma clang diagnostic pop
4640 #endif
4641
4642 // end catch_test_case_info.h
4643 // start catch_interfaces_runner.h
4644
4645 namespace Catch {
4646
4647 struct IRunner {
4648 virtual ~IRunner();
4649 virtual bool aborting() const = 0;
4650 };
4651 }
4652
4653 // end catch_interfaces_runner.h
4654
4655 #ifdef __OBJC__
4656 // start catch_objc.hpp
4657
4658 #import <objc/runtime.h>
4659
4660 #include <string>
4661
4662 // NB. Any general catch headers included here must be included
4663 // in catch.hpp first to make sure they are included by the single
4664 // header for non obj-usage
4665
4666 ///////////////////////////////////////////////////////////////////////////////
4667 // This protocol is really only here for (self) documenting purposes, since
4668 // all its methods are optional.
4669 @protocol OcFixture
4670
4671 @optional
4672
4673 -(void) setUp;
4674 -(void) tearDown;
4675
4676 @end
4677
4678 namespace Catch {
4679
4680 class OcMethod : public ITestInvoker {
4681
4682 public:
OcMethod(Class cls,SEL sel)4683 OcMethod( Class cls, SEL sel ) : m_cls( cls ), m_sel( sel ) {}
4684
invoke() const4685 virtual void invoke() const {
4686 id obj = [[m_cls alloc] init];
4687
4688 performOptionalSelector( obj, @selector(setUp) );
4689 performOptionalSelector( obj, m_sel );
4690 performOptionalSelector( obj, @selector(tearDown) );
4691
4692 arcSafeRelease( obj );
4693 }
4694 private:
~OcMethod()4695 virtual ~OcMethod() {}
4696
4697 Class m_cls;
4698 SEL m_sel;
4699 };
4700
4701 namespace Detail{
4702
getAnnotation(Class cls,std::string const & annotationName,std::string const & testCaseName)4703 inline std::string getAnnotation( Class cls,
4704 std::string const& annotationName,
4705 std::string const& testCaseName ) {
4706 NSString* selStr = [[NSString alloc] initWithFormat:@"Catch_%s_%s", annotationName.c_str(), testCaseName.c_str()];
4707 SEL sel = NSSelectorFromString( selStr );
4708 arcSafeRelease( selStr );
4709 id value = performOptionalSelector( cls, sel );
4710 if( value )
4711 return [(NSString*)value UTF8String];
4712 return "";
4713 }
4714 }
4715
registerTestMethods()4716 inline std::size_t registerTestMethods() {
4717 std::size_t noTestMethods = 0;
4718 int noClasses = objc_getClassList( nullptr, 0 );
4719
4720 Class* classes = (CATCH_UNSAFE_UNRETAINED Class *)malloc( sizeof(Class) * noClasses);
4721 objc_getClassList( classes, noClasses );
4722
4723 for( int c = 0; c < noClasses; c++ ) {
4724 Class cls = classes[c];
4725 {
4726 u_int count;
4727 Method* methods = class_copyMethodList( cls, &count );
4728 for( u_int m = 0; m < count ; m++ ) {
4729 SEL selector = method_getName(methods[m]);
4730 std::string methodName = sel_getName(selector);
4731 if( startsWith( methodName, "Catch_TestCase_" ) ) {
4732 std::string testCaseName = methodName.substr( 15 );
4733 std::string name = Detail::getAnnotation( cls, "Name", testCaseName );
4734 std::string desc = Detail::getAnnotation( cls, "Description", testCaseName );
4735 const char* className = class_getName( cls );
4736
4737 getMutableRegistryHub().registerTest( makeTestCase( new OcMethod( cls, selector ), className, NameAndTags( name.c_str(), desc.c_str() ), SourceLineInfo("",0) ) );
4738 noTestMethods++;
4739 }
4740 }
4741 free(methods);
4742 }
4743 }
4744 return noTestMethods;
4745 }
4746
4747 #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
4748
4749 namespace Matchers {
4750 namespace Impl {
4751 namespace NSStringMatchers {
4752
4753 struct StringHolder : MatcherBase<NSString*>{
StringHolderCatch::Matchers::Impl::NSStringMatchers::StringHolder4754 StringHolder( NSString* substr ) : m_substr( [substr copy] ){}
StringHolderCatch::Matchers::Impl::NSStringMatchers::StringHolder4755 StringHolder( StringHolder const& other ) : m_substr( [other.m_substr copy] ){}
StringHolderCatch::Matchers::Impl::NSStringMatchers::StringHolder4756 StringHolder() {
4757 arcSafeRelease( m_substr );
4758 }
4759
matchCatch::Matchers::Impl::NSStringMatchers::StringHolder4760 bool match( NSString* str ) const override {
4761 return false;
4762 }
4763
4764 NSString* CATCH_ARC_STRONG m_substr;
4765 };
4766
4767 struct Equals : StringHolder {
EqualsCatch::Matchers::Impl::NSStringMatchers::Equals4768 Equals( NSString* substr ) : StringHolder( substr ){}
4769
matchCatch::Matchers::Impl::NSStringMatchers::Equals4770 bool match( NSString* str ) const override {
4771 return (str != nil || m_substr == nil ) &&
4772 [str isEqualToString:m_substr];
4773 }
4774
describeCatch::Matchers::Impl::NSStringMatchers::Equals4775 std::string describe() const override {
4776 return "equals string: " + Catch::Detail::stringify( m_substr );
4777 }
4778 };
4779
4780 struct Contains : StringHolder {
ContainsCatch::Matchers::Impl::NSStringMatchers::Contains4781 Contains( NSString* substr ) : StringHolder( substr ){}
4782
matchCatch::Matchers::Impl::NSStringMatchers::Contains4783 bool match( NSString* str ) const override {
4784 return (str != nil || m_substr == nil ) &&
4785 [str rangeOfString:m_substr].location != NSNotFound;
4786 }
4787
describeCatch::Matchers::Impl::NSStringMatchers::Contains4788 std::string describe() const override {
4789 return "contains string: " + Catch::Detail::stringify( m_substr );
4790 }
4791 };
4792
4793 struct StartsWith : StringHolder {
StartsWithCatch::Matchers::Impl::NSStringMatchers::StartsWith4794 StartsWith( NSString* substr ) : StringHolder( substr ){}
4795
matchCatch::Matchers::Impl::NSStringMatchers::StartsWith4796 bool match( NSString* str ) const override {
4797 return (str != nil || m_substr == nil ) &&
4798 [str rangeOfString:m_substr].location == 0;
4799 }
4800
describeCatch::Matchers::Impl::NSStringMatchers::StartsWith4801 std::string describe() const override {
4802 return "starts with: " + Catch::Detail::stringify( m_substr );
4803 }
4804 };
4805 struct EndsWith : StringHolder {
EndsWithCatch::Matchers::Impl::NSStringMatchers::EndsWith4806 EndsWith( NSString* substr ) : StringHolder( substr ){}
4807
matchCatch::Matchers::Impl::NSStringMatchers::EndsWith4808 bool match( NSString* str ) const override {
4809 return (str != nil || m_substr == nil ) &&
4810 [str rangeOfString:m_substr].location == [str length] - [m_substr length];
4811 }
4812
describeCatch::Matchers::Impl::NSStringMatchers::EndsWith4813 std::string describe() const override {
4814 return "ends with: " + Catch::Detail::stringify( m_substr );
4815 }
4816 };
4817
4818 } // namespace NSStringMatchers
4819 } // namespace Impl
4820
4821 inline Impl::NSStringMatchers::Equals
Equals(NSString * substr)4822 Equals( NSString* substr ){ return Impl::NSStringMatchers::Equals( substr ); }
4823
4824 inline Impl::NSStringMatchers::Contains
Contains(NSString * substr)4825 Contains( NSString* substr ){ return Impl::NSStringMatchers::Contains( substr ); }
4826
4827 inline Impl::NSStringMatchers::StartsWith
StartsWith(NSString * substr)4828 StartsWith( NSString* substr ){ return Impl::NSStringMatchers::StartsWith( substr ); }
4829
4830 inline Impl::NSStringMatchers::EndsWith
EndsWith(NSString * substr)4831 EndsWith( NSString* substr ){ return Impl::NSStringMatchers::EndsWith( substr ); }
4832
4833 } // namespace Matchers
4834
4835 using namespace Matchers;
4836
4837 #endif // CATCH_CONFIG_DISABLE_MATCHERS
4838
4839 } // namespace Catch
4840
4841 ///////////////////////////////////////////////////////////////////////////////
4842 #define OC_MAKE_UNIQUE_NAME( root, uniqueSuffix ) root##uniqueSuffix
4843 #define OC_TEST_CASE2( name, desc, uniqueSuffix ) \
4844 +(NSString*) OC_MAKE_UNIQUE_NAME( Catch_Name_test_, uniqueSuffix ) \
4845 { \
4846 return @ name; \
4847 } \
4848 +(NSString*) OC_MAKE_UNIQUE_NAME( Catch_Description_test_, uniqueSuffix ) \
4849 { \
4850 return @ desc; \
4851 } \
4852 -(void) OC_MAKE_UNIQUE_NAME( Catch_TestCase_test_, uniqueSuffix )
4853
4854 #define OC_TEST_CASE( name, desc ) OC_TEST_CASE2( name, desc, __LINE__ )
4855
4856 // end catch_objc.hpp
4857 #endif
4858
4859 // Benchmarking needs the externally-facing parts of reporters to work
4860 #if defined(CATCH_CONFIG_EXTERNAL_INTERFACES) || defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
4861 // start catch_external_interfaces.h
4862
4863 // start catch_reporter_bases.hpp
4864
4865 // start catch_interfaces_reporter.h
4866
4867 // start catch_config.hpp
4868
4869 // start catch_test_spec_parser.h
4870
4871 #ifdef __clang__
4872 #pragma clang diagnostic push
4873 #pragma clang diagnostic ignored "-Wpadded"
4874 #endif
4875
4876 // start catch_test_spec.h
4877
4878 #ifdef __clang__
4879 #pragma clang diagnostic push
4880 #pragma clang diagnostic ignored "-Wpadded"
4881 #endif
4882
4883 // start catch_wildcard_pattern.h
4884
4885 namespace Catch
4886 {
4887 class WildcardPattern {
4888 enum WildcardPosition {
4889 NoWildcard = 0,
4890 WildcardAtStart = 1,
4891 WildcardAtEnd = 2,
4892 WildcardAtBothEnds = WildcardAtStart | WildcardAtEnd
4893 };
4894
4895 public:
4896
4897 WildcardPattern( std::string const& pattern, CaseSensitive::Choice caseSensitivity );
4898 virtual ~WildcardPattern() = default;
4899 virtual bool matches( std::string const& str ) const;
4900
4901 private:
4902 std::string adjustCase( std::string const& str ) const;
4903 CaseSensitive::Choice m_caseSensitivity;
4904 WildcardPosition m_wildcard = NoWildcard;
4905 std::string m_pattern;
4906 };
4907 }
4908
4909 // end catch_wildcard_pattern.h
4910 #include <string>
4911 #include <vector>
4912 #include <memory>
4913
4914 namespace Catch {
4915
4916 struct IConfig;
4917
4918 class TestSpec {
4919 class Pattern {
4920 public:
4921 explicit Pattern( std::string const& name );
4922 virtual ~Pattern();
4923 virtual bool matches( TestCaseInfo const& testCase ) const = 0;
4924 std::string const& name() const;
4925 private:
4926 std::string const m_name;
4927 };
4928 using PatternPtr = std::shared_ptr<Pattern>;
4929
4930 class NamePattern : public Pattern {
4931 public:
4932 explicit NamePattern( std::string const& name, std::string const& filterString );
4933 bool matches( TestCaseInfo const& testCase ) const override;
4934 private:
4935 WildcardPattern m_wildcardPattern;
4936 };
4937
4938 class TagPattern : public Pattern {
4939 public:
4940 explicit TagPattern( std::string const& tag, std::string const& filterString );
4941 bool matches( TestCaseInfo const& testCase ) const override;
4942 private:
4943 std::string m_tag;
4944 };
4945
4946 class ExcludedPattern : public Pattern {
4947 public:
4948 explicit ExcludedPattern( PatternPtr const& underlyingPattern );
4949 bool matches( TestCaseInfo const& testCase ) const override;
4950 private:
4951 PatternPtr m_underlyingPattern;
4952 };
4953
4954 struct Filter {
4955 std::vector<PatternPtr> m_patterns;
4956
4957 bool matches( TestCaseInfo const& testCase ) const;
4958 std::string name() const;
4959 };
4960
4961 public:
4962 struct FilterMatch {
4963 std::string name;
4964 std::vector<TestCase const*> tests;
4965 };
4966 using Matches = std::vector<FilterMatch>;
4967
4968 bool hasFilters() const;
4969 bool matches( TestCaseInfo const& testCase ) const;
4970 Matches matchesByFilter( std::vector<TestCase> const& testCases, IConfig const& config ) const;
4971
4972 private:
4973 std::vector<Filter> m_filters;
4974
4975 friend class TestSpecParser;
4976 };
4977 }
4978
4979 #ifdef __clang__
4980 #pragma clang diagnostic pop
4981 #endif
4982
4983 // end catch_test_spec.h
4984 // start catch_interfaces_tag_alias_registry.h
4985
4986 #include <string>
4987
4988 namespace Catch {
4989
4990 struct TagAlias;
4991
4992 struct ITagAliasRegistry {
4993 virtual ~ITagAliasRegistry();
4994 // Nullptr if not present
4995 virtual TagAlias const* find( std::string const& alias ) const = 0;
4996 virtual std::string expandAliases( std::string const& unexpandedTestSpec ) const = 0;
4997
4998 static ITagAliasRegistry const& get();
4999 };
5000
5001 } // end namespace Catch
5002
5003 // end catch_interfaces_tag_alias_registry.h
5004 namespace Catch {
5005
5006 class TestSpecParser {
5007 enum Mode{ None, Name, QuotedName, Tag, EscapedName };
5008 Mode m_mode = None;
5009 bool m_exclusion = false;
5010 std::size_t m_pos = 0;
5011 std::string m_arg;
5012 std::string m_substring;
5013 std::string m_patternName;
5014 std::vector<std::size_t> m_escapeChars;
5015 TestSpec::Filter m_currentFilter;
5016 TestSpec m_testSpec;
5017 ITagAliasRegistry const* m_tagAliases = nullptr;
5018
5019 public:
5020 TestSpecParser( ITagAliasRegistry const& tagAliases );
5021
5022 TestSpecParser& parse( std::string const& arg );
5023 TestSpec testSpec();
5024
5025 private:
5026 void visitChar( char c );
5027 void startNewMode( Mode mode );
5028 bool processNoneChar( char c );
5029 void processNameChar( char c );
5030 bool processOtherChar( char c );
5031 void endMode();
5032 void escape();
5033 bool isControlChar( char c ) const;
5034
5035 template<typename T>
addPattern()5036 void addPattern() {
5037 std::string token = m_patternName;
5038 for( std::size_t i = 0; i < m_escapeChars.size(); ++i )
5039 token = token.substr( 0, m_escapeChars[i] - i ) + token.substr( m_escapeChars[i] -i +1 );
5040 m_escapeChars.clear();
5041 if( startsWith( token, "exclude:" ) ) {
5042 m_exclusion = true;
5043 token = token.substr( 8 );
5044 }
5045 if( !token.empty() ) {
5046 TestSpec::PatternPtr pattern = std::make_shared<T>( token, m_substring );
5047 if( m_exclusion )
5048 pattern = std::make_shared<TestSpec::ExcludedPattern>( pattern );
5049 m_currentFilter.m_patterns.push_back( pattern );
5050 }
5051 m_substring.clear();
5052 m_patternName.clear();
5053 m_exclusion = false;
5054 m_mode = None;
5055 }
5056
5057 void addFilter();
5058 };
5059 TestSpec parseTestSpec( std::string const& arg );
5060
5061 } // namespace Catch
5062
5063 #ifdef __clang__
5064 #pragma clang diagnostic pop
5065 #endif
5066
5067 // end catch_test_spec_parser.h
5068 // Libstdc++ doesn't like incomplete classes for unique_ptr
5069
5070 #include <memory>
5071 #include <vector>
5072 #include <string>
5073
5074 #ifndef CATCH_CONFIG_CONSOLE_WIDTH
5075 #define CATCH_CONFIG_CONSOLE_WIDTH 80
5076 #endif
5077
5078 namespace Catch {
5079
5080 struct IStream;
5081
5082 struct ConfigData {
5083 bool listTests = false;
5084 bool listTags = false;
5085 bool listReporters = false;
5086 bool listTestNamesOnly = false;
5087
5088 bool showSuccessfulTests = false;
5089 bool shouldDebugBreak = false;
5090 bool noThrow = false;
5091 bool showHelp = false;
5092 bool showInvisibles = false;
5093 bool filenamesAsTags = false;
5094 bool libIdentify = false;
5095
5096 int abortAfter = -1;
5097 unsigned int rngSeed = 0;
5098
5099 bool benchmarkNoAnalysis = false;
5100 unsigned int benchmarkSamples = 100;
5101 double benchmarkConfidenceInterval = 0.95;
5102 unsigned int benchmarkResamples = 100000;
5103
5104 Verbosity verbosity = Verbosity::Normal;
5105 WarnAbout::What warnings = WarnAbout::Nothing;
5106 ShowDurations::OrNot showDurations = ShowDurations::DefaultForReporter;
5107 RunTests::InWhatOrder runOrder = RunTests::InDeclarationOrder;
5108 UseColour::YesOrNo useColour = UseColour::Auto;
5109 WaitForKeypress::When waitForKeypress = WaitForKeypress::Never;
5110
5111 std::string outputFilename;
5112 std::string name;
5113 std::string processName;
5114 #ifndef CATCH_CONFIG_DEFAULT_REPORTER
5115 #define CATCH_CONFIG_DEFAULT_REPORTER "console"
5116 #endif
5117 std::string reporterName = CATCH_CONFIG_DEFAULT_REPORTER;
5118 #undef CATCH_CONFIG_DEFAULT_REPORTER
5119
5120 std::vector<std::string> testsOrTags;
5121 std::vector<std::string> sectionsToRun;
5122 };
5123
5124 class Config : public IConfig {
5125 public:
5126
5127 Config() = default;
5128 Config( ConfigData const& data );
5129 virtual ~Config() = default;
5130
5131 std::string const& getFilename() const;
5132
5133 bool listTests() const;
5134 bool listTestNamesOnly() const;
5135 bool listTags() const;
5136 bool listReporters() const;
5137
5138 std::string getProcessName() const;
5139 std::string const& getReporterName() const;
5140
5141 std::vector<std::string> const& getTestsOrTags() const override;
5142 std::vector<std::string> const& getSectionsToRun() const override;
5143
5144 TestSpec const& testSpec() const override;
5145 bool hasTestFilters() const override;
5146
5147 bool showHelp() const;
5148
5149 // IConfig interface
5150 bool allowThrows() const override;
5151 std::ostream& stream() const override;
5152 std::string name() const override;
5153 bool includeSuccessfulResults() const override;
5154 bool warnAboutMissingAssertions() const override;
5155 bool warnAboutNoTests() const override;
5156 ShowDurations::OrNot showDurations() const override;
5157 RunTests::InWhatOrder runOrder() const override;
5158 unsigned int rngSeed() const override;
5159 UseColour::YesOrNo useColour() const override;
5160 bool shouldDebugBreak() const override;
5161 int abortAfter() const override;
5162 bool showInvisibles() const override;
5163 Verbosity verbosity() const override;
5164 bool benchmarkNoAnalysis() const override;
5165 int benchmarkSamples() const override;
5166 double benchmarkConfidenceInterval() const override;
5167 unsigned int benchmarkResamples() const override;
5168
5169 private:
5170
5171 IStream const* openStream();
5172 ConfigData m_data;
5173
5174 std::unique_ptr<IStream const> m_stream;
5175 TestSpec m_testSpec;
5176 bool m_hasTestFilters = false;
5177 };
5178
5179 } // end namespace Catch
5180
5181 // end catch_config.hpp
5182 // start catch_assertionresult.h
5183
5184 #include <string>
5185
5186 namespace Catch {
5187
5188 struct AssertionResultData
5189 {
5190 AssertionResultData() = delete;
5191
5192 AssertionResultData( ResultWas::OfType _resultType, LazyExpression const& _lazyExpression );
5193
5194 std::string message;
5195 mutable std::string reconstructedExpression;
5196 LazyExpression lazyExpression;
5197 ResultWas::OfType resultType;
5198
5199 std::string reconstructExpression() const;
5200 };
5201
5202 class AssertionResult {
5203 public:
5204 AssertionResult() = delete;
5205 AssertionResult( AssertionInfo const& info, AssertionResultData const& data );
5206
5207 bool isOk() const;
5208 bool succeeded() const;
5209 ResultWas::OfType getResultType() const;
5210 bool hasExpression() const;
5211 bool hasMessage() const;
5212 std::string getExpression() const;
5213 std::string getExpressionInMacro() const;
5214 bool hasExpandedExpression() const;
5215 std::string getExpandedExpression() const;
5216 std::string getMessage() const;
5217 SourceLineInfo getSourceInfo() const;
5218 StringRef getTestMacroName() const;
5219
5220 //protected:
5221 AssertionInfo m_info;
5222 AssertionResultData m_resultData;
5223 };
5224
5225 } // end namespace Catch
5226
5227 // end catch_assertionresult.h
5228 #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
5229 // start catch_estimate.hpp
5230
5231 // Statistics estimates
5232
5233
5234 namespace Catch {
5235 namespace Benchmark {
5236 template <typename Duration>
5237 struct Estimate {
5238 Duration point;
5239 Duration lower_bound;
5240 Duration upper_bound;
5241 double confidence_interval;
5242
5243 template <typename Duration2>
operator Estimate<Duration2>Catch::Benchmark::Estimate5244 operator Estimate<Duration2>() const {
5245 return { point, lower_bound, upper_bound, confidence_interval };
5246 }
5247 };
5248 } // namespace Benchmark
5249 } // namespace Catch
5250
5251 // end catch_estimate.hpp
5252 // start catch_outlier_classification.hpp
5253
5254 // Outlier information
5255
5256 namespace Catch {
5257 namespace Benchmark {
5258 struct OutlierClassification {
5259 int samples_seen = 0;
5260 int low_severe = 0; // more than 3 times IQR below Q1
5261 int low_mild = 0; // 1.5 to 3 times IQR below Q1
5262 int high_mild = 0; // 1.5 to 3 times IQR above Q3
5263 int high_severe = 0; // more than 3 times IQR above Q3
5264
totalCatch::Benchmark::OutlierClassification5265 int total() const {
5266 return low_severe + low_mild + high_mild + high_severe;
5267 }
5268 };
5269 } // namespace Benchmark
5270 } // namespace Catch
5271
5272 // end catch_outlier_classification.hpp
5273 #endif // CATCH_CONFIG_ENABLE_BENCHMARKING
5274
5275 #include <string>
5276 #include <iosfwd>
5277 #include <map>
5278 #include <set>
5279 #include <memory>
5280 #include <algorithm>
5281
5282 namespace Catch {
5283
5284 struct ReporterConfig {
5285 explicit ReporterConfig( IConfigPtr const& _fullConfig );
5286
5287 ReporterConfig( IConfigPtr const& _fullConfig, std::ostream& _stream );
5288
5289 std::ostream& stream() const;
5290 IConfigPtr fullConfig() const;
5291
5292 private:
5293 std::ostream* m_stream;
5294 IConfigPtr m_fullConfig;
5295 };
5296
5297 struct ReporterPreferences {
5298 bool shouldRedirectStdOut = false;
5299 bool shouldReportAllAssertions = false;
5300 };
5301
5302 template<typename T>
5303 struct LazyStat : Option<T> {
operator =Catch::LazyStat5304 LazyStat& operator=( T const& _value ) {
5305 Option<T>::operator=( _value );
5306 used = false;
5307 return *this;
5308 }
resetCatch::LazyStat5309 void reset() {
5310 Option<T>::reset();
5311 used = false;
5312 }
5313 bool used = false;
5314 };
5315
5316 struct TestRunInfo {
5317 TestRunInfo( std::string const& _name );
5318 std::string name;
5319 };
5320 struct GroupInfo {
5321 GroupInfo( std::string const& _name,
5322 std::size_t _groupIndex,
5323 std::size_t _groupsCount );
5324
5325 std::string name;
5326 std::size_t groupIndex;
5327 std::size_t groupsCounts;
5328 };
5329
5330 struct AssertionStats {
5331 AssertionStats( AssertionResult const& _assertionResult,
5332 std::vector<MessageInfo> const& _infoMessages,
5333 Totals const& _totals );
5334
5335 AssertionStats( AssertionStats const& ) = default;
5336 AssertionStats( AssertionStats && ) = default;
5337 AssertionStats& operator = ( AssertionStats const& ) = delete;
5338 AssertionStats& operator = ( AssertionStats && ) = delete;
5339 virtual ~AssertionStats();
5340
5341 AssertionResult assertionResult;
5342 std::vector<MessageInfo> infoMessages;
5343 Totals totals;
5344 };
5345
5346 struct SectionStats {
5347 SectionStats( SectionInfo const& _sectionInfo,
5348 Counts const& _assertions,
5349 double _durationInSeconds,
5350 bool _missingAssertions );
5351 SectionStats( SectionStats const& ) = default;
5352 SectionStats( SectionStats && ) = default;
5353 SectionStats& operator = ( SectionStats const& ) = default;
5354 SectionStats& operator = ( SectionStats && ) = default;
5355 virtual ~SectionStats();
5356
5357 SectionInfo sectionInfo;
5358 Counts assertions;
5359 double durationInSeconds;
5360 bool missingAssertions;
5361 };
5362
5363 struct TestCaseStats {
5364 TestCaseStats( TestCaseInfo const& _testInfo,
5365 Totals const& _totals,
5366 std::string const& _stdOut,
5367 std::string const& _stdErr,
5368 bool _aborting );
5369
5370 TestCaseStats( TestCaseStats const& ) = default;
5371 TestCaseStats( TestCaseStats && ) = default;
5372 TestCaseStats& operator = ( TestCaseStats const& ) = default;
5373 TestCaseStats& operator = ( TestCaseStats && ) = default;
5374 virtual ~TestCaseStats();
5375
5376 TestCaseInfo testInfo;
5377 Totals totals;
5378 std::string stdOut;
5379 std::string stdErr;
5380 bool aborting;
5381 };
5382
5383 struct TestGroupStats {
5384 TestGroupStats( GroupInfo const& _groupInfo,
5385 Totals const& _totals,
5386 bool _aborting );
5387 TestGroupStats( GroupInfo const& _groupInfo );
5388
5389 TestGroupStats( TestGroupStats const& ) = default;
5390 TestGroupStats( TestGroupStats && ) = default;
5391 TestGroupStats& operator = ( TestGroupStats const& ) = default;
5392 TestGroupStats& operator = ( TestGroupStats && ) = default;
5393 virtual ~TestGroupStats();
5394
5395 GroupInfo groupInfo;
5396 Totals totals;
5397 bool aborting;
5398 };
5399
5400 struct TestRunStats {
5401 TestRunStats( TestRunInfo const& _runInfo,
5402 Totals const& _totals,
5403 bool _aborting );
5404
5405 TestRunStats( TestRunStats const& ) = default;
5406 TestRunStats( TestRunStats && ) = default;
5407 TestRunStats& operator = ( TestRunStats const& ) = default;
5408 TestRunStats& operator = ( TestRunStats && ) = default;
5409 virtual ~TestRunStats();
5410
5411 TestRunInfo runInfo;
5412 Totals totals;
5413 bool aborting;
5414 };
5415
5416 #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
5417 struct BenchmarkInfo {
5418 std::string name;
5419 double estimatedDuration;
5420 int iterations;
5421 int samples;
5422 unsigned int resamples;
5423 double clockResolution;
5424 double clockCost;
5425 };
5426
5427 template <class Duration>
5428 struct BenchmarkStats {
5429 BenchmarkInfo info;
5430
5431 std::vector<Duration> samples;
5432 Benchmark::Estimate<Duration> mean;
5433 Benchmark::Estimate<Duration> standardDeviation;
5434 Benchmark::OutlierClassification outliers;
5435 double outlierVariance;
5436
5437 template <typename Duration2>
operator BenchmarkStats<Duration2>Catch::BenchmarkStats5438 operator BenchmarkStats<Duration2>() const {
5439 std::vector<Duration2> samples2;
5440 samples2.reserve(samples.size());
5441 std::transform(samples.begin(), samples.end(), std::back_inserter(samples2), [](Duration d) { return Duration2(d); });
5442 return {
5443 info,
5444 std::move(samples2),
5445 mean,
5446 standardDeviation,
5447 outliers,
5448 outlierVariance,
5449 };
5450 }
5451 };
5452 #endif // CATCH_CONFIG_ENABLE_BENCHMARKING
5453
5454 struct IStreamingReporter {
5455 virtual ~IStreamingReporter() = default;
5456
5457 // Implementing class must also provide the following static methods:
5458 // static std::string getDescription();
5459 // static std::set<Verbosity> getSupportedVerbosities()
5460
5461 virtual ReporterPreferences getPreferences() const = 0;
5462
5463 virtual void noMatchingTestCases( std::string const& spec ) = 0;
5464
5465 virtual void testRunStarting( TestRunInfo const& testRunInfo ) = 0;
5466 virtual void testGroupStarting( GroupInfo const& groupInfo ) = 0;
5467
5468 virtual void testCaseStarting( TestCaseInfo const& testInfo ) = 0;
5469 virtual void sectionStarting( SectionInfo const& sectionInfo ) = 0;
5470
5471 #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
benchmarkPreparingCatch::IStreamingReporter5472 virtual void benchmarkPreparing( std::string const& ) {}
benchmarkStartingCatch::IStreamingReporter5473 virtual void benchmarkStarting( BenchmarkInfo const& ) {}
benchmarkEndedCatch::IStreamingReporter5474 virtual void benchmarkEnded( BenchmarkStats<> const& ) {}
benchmarkFailedCatch::IStreamingReporter5475 virtual void benchmarkFailed( std::string const& ) {}
5476 #endif // CATCH_CONFIG_ENABLE_BENCHMARKING
5477
5478 virtual void assertionStarting( AssertionInfo const& assertionInfo ) = 0;
5479
5480 // The return value indicates if the messages buffer should be cleared:
5481 virtual bool assertionEnded( AssertionStats const& assertionStats ) = 0;
5482
5483 virtual void sectionEnded( SectionStats const& sectionStats ) = 0;
5484 virtual void testCaseEnded( TestCaseStats const& testCaseStats ) = 0;
5485 virtual void testGroupEnded( TestGroupStats const& testGroupStats ) = 0;
5486 virtual void testRunEnded( TestRunStats const& testRunStats ) = 0;
5487
5488 virtual void skipTest( TestCaseInfo const& testInfo ) = 0;
5489
5490 // Default empty implementation provided
5491 virtual void fatalErrorEncountered( StringRef name );
5492
5493 virtual bool isMulti() const;
5494 };
5495 using IStreamingReporterPtr = std::unique_ptr<IStreamingReporter>;
5496
5497 struct IReporterFactory {
5498 virtual ~IReporterFactory();
5499 virtual IStreamingReporterPtr create( ReporterConfig const& config ) const = 0;
5500 virtual std::string getDescription() const = 0;
5501 };
5502 using IReporterFactoryPtr = std::shared_ptr<IReporterFactory>;
5503
5504 struct IReporterRegistry {
5505 using FactoryMap = std::map<std::string, IReporterFactoryPtr>;
5506 using Listeners = std::vector<IReporterFactoryPtr>;
5507
5508 virtual ~IReporterRegistry();
5509 virtual IStreamingReporterPtr create( std::string const& name, IConfigPtr const& config ) const = 0;
5510 virtual FactoryMap const& getFactories() const = 0;
5511 virtual Listeners const& getListeners() const = 0;
5512 };
5513
5514 } // end namespace Catch
5515
5516 // end catch_interfaces_reporter.h
5517 #include <algorithm>
5518 #include <cstring>
5519 #include <cfloat>
5520 #include <cstdio>
5521 #include <cassert>
5522 #include <memory>
5523 #include <ostream>
5524
5525 namespace Catch {
5526 void prepareExpandedExpression(AssertionResult& result);
5527
5528 // Returns double formatted as %.3f (format expected on output)
5529 std::string getFormattedDuration( double duration );
5530
5531 std::string serializeFilters( std::vector<std::string> const& container );
5532
5533 template<typename DerivedT>
5534 struct StreamingReporterBase : IStreamingReporter {
5535
StreamingReporterBaseCatch::StreamingReporterBase5536 StreamingReporterBase( ReporterConfig const& _config )
5537 : m_config( _config.fullConfig() ),
5538 stream( _config.stream() )
5539 {
5540 m_reporterPrefs.shouldRedirectStdOut = false;
5541 if( !DerivedT::getSupportedVerbosities().count( m_config->verbosity() ) )
5542 CATCH_ERROR( "Verbosity level not supported by this reporter" );
5543 }
5544
getPreferencesCatch::StreamingReporterBase5545 ReporterPreferences getPreferences() const override {
5546 return m_reporterPrefs;
5547 }
5548
getSupportedVerbositiesCatch::StreamingReporterBase5549 static std::set<Verbosity> getSupportedVerbosities() {
5550 return { Verbosity::Normal };
5551 }
5552
5553 ~StreamingReporterBase() override = default;
5554
noMatchingTestCasesCatch::StreamingReporterBase5555 void noMatchingTestCases(std::string const&) override {}
5556
testRunStartingCatch::StreamingReporterBase5557 void testRunStarting(TestRunInfo const& _testRunInfo) override {
5558 currentTestRunInfo = _testRunInfo;
5559 }
5560
testGroupStartingCatch::StreamingReporterBase5561 void testGroupStarting(GroupInfo const& _groupInfo) override {
5562 currentGroupInfo = _groupInfo;
5563 }
5564
testCaseStartingCatch::StreamingReporterBase5565 void testCaseStarting(TestCaseInfo const& _testInfo) override {
5566 currentTestCaseInfo = _testInfo;
5567 }
sectionStartingCatch::StreamingReporterBase5568 void sectionStarting(SectionInfo const& _sectionInfo) override {
5569 m_sectionStack.push_back(_sectionInfo);
5570 }
5571
sectionEndedCatch::StreamingReporterBase5572 void sectionEnded(SectionStats const& /* _sectionStats */) override {
5573 m_sectionStack.pop_back();
5574 }
testCaseEndedCatch::StreamingReporterBase5575 void testCaseEnded(TestCaseStats const& /* _testCaseStats */) override {
5576 currentTestCaseInfo.reset();
5577 }
testGroupEndedCatch::StreamingReporterBase5578 void testGroupEnded(TestGroupStats const& /* _testGroupStats */) override {
5579 currentGroupInfo.reset();
5580 }
testRunEndedCatch::StreamingReporterBase5581 void testRunEnded(TestRunStats const& /* _testRunStats */) override {
5582 currentTestCaseInfo.reset();
5583 currentGroupInfo.reset();
5584 currentTestRunInfo.reset();
5585 }
5586
skipTestCatch::StreamingReporterBase5587 void skipTest(TestCaseInfo const&) override {
5588 // Don't do anything with this by default.
5589 // It can optionally be overridden in the derived class.
5590 }
5591
5592 IConfigPtr m_config;
5593 std::ostream& stream;
5594
5595 LazyStat<TestRunInfo> currentTestRunInfo;
5596 LazyStat<GroupInfo> currentGroupInfo;
5597 LazyStat<TestCaseInfo> currentTestCaseInfo;
5598
5599 std::vector<SectionInfo> m_sectionStack;
5600 ReporterPreferences m_reporterPrefs;
5601 };
5602
5603 template<typename DerivedT>
5604 struct CumulativeReporterBase : IStreamingReporter {
5605 template<typename T, typename ChildNodeT>
5606 struct Node {
NodeCatch::CumulativeReporterBase::Node5607 explicit Node( T const& _value ) : value( _value ) {}
~NodeCatch::CumulativeReporterBase::Node5608 virtual ~Node() {}
5609
5610 using ChildNodes = std::vector<std::shared_ptr<ChildNodeT>>;
5611 T value;
5612 ChildNodes children;
5613 };
5614 struct SectionNode {
SectionNodeCatch::CumulativeReporterBase::SectionNode5615 explicit SectionNode(SectionStats const& _stats) : stats(_stats) {}
5616 virtual ~SectionNode() = default;
5617
operator ==Catch::CumulativeReporterBase::SectionNode5618 bool operator == (SectionNode const& other) const {
5619 return stats.sectionInfo.lineInfo == other.stats.sectionInfo.lineInfo;
5620 }
operator ==Catch::CumulativeReporterBase::SectionNode5621 bool operator == (std::shared_ptr<SectionNode> const& other) const {
5622 return operator==(*other);
5623 }
5624
5625 SectionStats stats;
5626 using ChildSections = std::vector<std::shared_ptr<SectionNode>>;
5627 using Assertions = std::vector<AssertionStats>;
5628 ChildSections childSections;
5629 Assertions assertions;
5630 std::string stdOut;
5631 std::string stdErr;
5632 };
5633
5634 struct BySectionInfo {
BySectionInfoCatch::CumulativeReporterBase::BySectionInfo5635 BySectionInfo( SectionInfo const& other ) : m_other( other ) {}
BySectionInfoCatch::CumulativeReporterBase::BySectionInfo5636 BySectionInfo( BySectionInfo const& other ) : m_other( other.m_other ) {}
operator ()Catch::CumulativeReporterBase::BySectionInfo5637 bool operator() (std::shared_ptr<SectionNode> const& node) const {
5638 return ((node->stats.sectionInfo.name == m_other.name) &&
5639 (node->stats.sectionInfo.lineInfo == m_other.lineInfo));
5640 }
5641 void operator=(BySectionInfo const&) = delete;
5642
5643 private:
5644 SectionInfo const& m_other;
5645 };
5646
5647 using TestCaseNode = Node<TestCaseStats, SectionNode>;
5648 using TestGroupNode = Node<TestGroupStats, TestCaseNode>;
5649 using TestRunNode = Node<TestRunStats, TestGroupNode>;
5650
CumulativeReporterBaseCatch::CumulativeReporterBase5651 CumulativeReporterBase( ReporterConfig const& _config )
5652 : m_config( _config.fullConfig() ),
5653 stream( _config.stream() )
5654 {
5655 m_reporterPrefs.shouldRedirectStdOut = false;
5656 if( !DerivedT::getSupportedVerbosities().count( m_config->verbosity() ) )
5657 CATCH_ERROR( "Verbosity level not supported by this reporter" );
5658 }
5659 ~CumulativeReporterBase() override = default;
5660
getPreferencesCatch::CumulativeReporterBase5661 ReporterPreferences getPreferences() const override {
5662 return m_reporterPrefs;
5663 }
5664
getSupportedVerbositiesCatch::CumulativeReporterBase5665 static std::set<Verbosity> getSupportedVerbosities() {
5666 return { Verbosity::Normal };
5667 }
5668
testRunStartingCatch::CumulativeReporterBase5669 void testRunStarting( TestRunInfo const& ) override {}
testGroupStartingCatch::CumulativeReporterBase5670 void testGroupStarting( GroupInfo const& ) override {}
5671
testCaseStartingCatch::CumulativeReporterBase5672 void testCaseStarting( TestCaseInfo const& ) override {}
5673
sectionStartingCatch::CumulativeReporterBase5674 void sectionStarting( SectionInfo const& sectionInfo ) override {
5675 SectionStats incompleteStats( sectionInfo, Counts(), 0, false );
5676 std::shared_ptr<SectionNode> node;
5677 if( m_sectionStack.empty() ) {
5678 if( !m_rootSection )
5679 m_rootSection = std::make_shared<SectionNode>( incompleteStats );
5680 node = m_rootSection;
5681 }
5682 else {
5683 SectionNode& parentNode = *m_sectionStack.back();
5684 auto it =
5685 std::find_if( parentNode.childSections.begin(),
5686 parentNode.childSections.end(),
5687 BySectionInfo( sectionInfo ) );
5688 if( it == parentNode.childSections.end() ) {
5689 node = std::make_shared<SectionNode>( incompleteStats );
5690 parentNode.childSections.push_back( node );
5691 }
5692 else
5693 node = *it;
5694 }
5695 m_sectionStack.push_back( node );
5696 m_deepestSection = std::move(node);
5697 }
5698
assertionStartingCatch::CumulativeReporterBase5699 void assertionStarting(AssertionInfo const&) override {}
5700
assertionEndedCatch::CumulativeReporterBase5701 bool assertionEnded(AssertionStats const& assertionStats) override {
5702 assert(!m_sectionStack.empty());
5703 // AssertionResult holds a pointer to a temporary DecomposedExpression,
5704 // which getExpandedExpression() calls to build the expression string.
5705 // Our section stack copy of the assertionResult will likely outlive the
5706 // temporary, so it must be expanded or discarded now to avoid calling
5707 // a destroyed object later.
5708 prepareExpandedExpression(const_cast<AssertionResult&>( assertionStats.assertionResult ) );
5709 SectionNode& sectionNode = *m_sectionStack.back();
5710 sectionNode.assertions.push_back(assertionStats);
5711 return true;
5712 }
sectionEndedCatch::CumulativeReporterBase5713 void sectionEnded(SectionStats const& sectionStats) override {
5714 assert(!m_sectionStack.empty());
5715 SectionNode& node = *m_sectionStack.back();
5716 node.stats = sectionStats;
5717 m_sectionStack.pop_back();
5718 }
testCaseEndedCatch::CumulativeReporterBase5719 void testCaseEnded(TestCaseStats const& testCaseStats) override {
5720 auto node = std::make_shared<TestCaseNode>(testCaseStats);
5721 assert(m_sectionStack.size() == 0);
5722 node->children.push_back(m_rootSection);
5723 m_testCases.push_back(node);
5724 m_rootSection.reset();
5725
5726 assert(m_deepestSection);
5727 m_deepestSection->stdOut = testCaseStats.stdOut;
5728 m_deepestSection->stdErr = testCaseStats.stdErr;
5729 }
testGroupEndedCatch::CumulativeReporterBase5730 void testGroupEnded(TestGroupStats const& testGroupStats) override {
5731 auto node = std::make_shared<TestGroupNode>(testGroupStats);
5732 node->children.swap(m_testCases);
5733 m_testGroups.push_back(node);
5734 }
testRunEndedCatch::CumulativeReporterBase5735 void testRunEnded(TestRunStats const& testRunStats) override {
5736 auto node = std::make_shared<TestRunNode>(testRunStats);
5737 node->children.swap(m_testGroups);
5738 m_testRuns.push_back(node);
5739 testRunEndedCumulative();
5740 }
5741 virtual void testRunEndedCumulative() = 0;
5742
skipTestCatch::CumulativeReporterBase5743 void skipTest(TestCaseInfo const&) override {}
5744
5745 IConfigPtr m_config;
5746 std::ostream& stream;
5747 std::vector<AssertionStats> m_assertions;
5748 std::vector<std::vector<std::shared_ptr<SectionNode>>> m_sections;
5749 std::vector<std::shared_ptr<TestCaseNode>> m_testCases;
5750 std::vector<std::shared_ptr<TestGroupNode>> m_testGroups;
5751
5752 std::vector<std::shared_ptr<TestRunNode>> m_testRuns;
5753
5754 std::shared_ptr<SectionNode> m_rootSection;
5755 std::shared_ptr<SectionNode> m_deepestSection;
5756 std::vector<std::shared_ptr<SectionNode>> m_sectionStack;
5757 ReporterPreferences m_reporterPrefs;
5758 };
5759
5760 template<char C>
getLineOfChars()5761 char const* getLineOfChars() {
5762 static char line[CATCH_CONFIG_CONSOLE_WIDTH] = {0};
5763 if( !*line ) {
5764 std::memset( line, C, CATCH_CONFIG_CONSOLE_WIDTH-1 );
5765 line[CATCH_CONFIG_CONSOLE_WIDTH-1] = 0;
5766 }
5767 return line;
5768 }
5769
5770 struct TestEventListenerBase : StreamingReporterBase<TestEventListenerBase> {
5771 TestEventListenerBase( ReporterConfig const& _config );
5772
5773 static std::set<Verbosity> getSupportedVerbosities();
5774
5775 void assertionStarting(AssertionInfo const&) override;
5776 bool assertionEnded(AssertionStats const&) override;
5777 };
5778
5779 } // end namespace Catch
5780
5781 // end catch_reporter_bases.hpp
5782 // start catch_console_colour.h
5783
5784 namespace Catch {
5785
5786 struct Colour {
5787 enum Code {
5788 None = 0,
5789
5790 White,
5791 Red,
5792 Green,
5793 Blue,
5794 Cyan,
5795 Yellow,
5796 Grey,
5797
5798 Bright = 0x10,
5799
5800 BrightRed = Bright | Red,
5801 BrightGreen = Bright | Green,
5802 LightGrey = Bright | Grey,
5803 BrightWhite = Bright | White,
5804 BrightYellow = Bright | Yellow,
5805
5806 // By intention
5807 FileName = LightGrey,
5808 Warning = BrightYellow,
5809 ResultError = BrightRed,
5810 ResultSuccess = BrightGreen,
5811 ResultExpectedFailure = Warning,
5812
5813 Error = BrightRed,
5814 Success = Green,
5815
5816 OriginalExpression = Cyan,
5817 ReconstructedExpression = BrightYellow,
5818
5819 SecondaryText = LightGrey,
5820 Headers = White
5821 };
5822
5823 // Use constructed object for RAII guard
5824 Colour( Code _colourCode );
5825 Colour( Colour&& other ) noexcept;
5826 Colour& operator=( Colour&& other ) noexcept;
5827 ~Colour();
5828
5829 // Use static method for one-shot changes
5830 static void use( Code _colourCode );
5831
5832 private:
5833 bool m_moved = false;
5834 };
5835
5836 std::ostream& operator << ( std::ostream& os, Colour const& );
5837
5838 } // end namespace Catch
5839
5840 // end catch_console_colour.h
5841 // start catch_reporter_registrars.hpp
5842
5843
5844 namespace Catch {
5845
5846 template<typename T>
5847 class ReporterRegistrar {
5848
5849 class ReporterFactory : public IReporterFactory {
5850
create(ReporterConfig const & config) const5851 IStreamingReporterPtr create( ReporterConfig const& config ) const override {
5852 return std::unique_ptr<T>( new T( config ) );
5853 }
5854
getDescription() const5855 std::string getDescription() const override {
5856 return T::getDescription();
5857 }
5858 };
5859
5860 public:
5861
ReporterRegistrar(std::string const & name)5862 explicit ReporterRegistrar( std::string const& name ) {
5863 getMutableRegistryHub().registerReporter( name, std::make_shared<ReporterFactory>() );
5864 }
5865 };
5866
5867 template<typename T>
5868 class ListenerRegistrar {
5869
5870 class ListenerFactory : public IReporterFactory {
5871
create(ReporterConfig const & config) const5872 IStreamingReporterPtr create( ReporterConfig const& config ) const override {
5873 return std::unique_ptr<T>( new T( config ) );
5874 }
getDescription() const5875 std::string getDescription() const override {
5876 return std::string();
5877 }
5878 };
5879
5880 public:
5881
ListenerRegistrar()5882 ListenerRegistrar() {
5883 getMutableRegistryHub().registerListener( std::make_shared<ListenerFactory>() );
5884 }
5885 };
5886 }
5887
5888 #if !defined(CATCH_CONFIG_DISABLE)
5889
5890 #define CATCH_REGISTER_REPORTER( name, reporterType ) \
5891 CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
5892 namespace{ Catch::ReporterRegistrar<reporterType> catch_internal_RegistrarFor##reporterType( name ); } \
5893 CATCH_INTERNAL_UNSUPPRESS_GLOBALS_WARNINGS
5894
5895 #define CATCH_REGISTER_LISTENER( listenerType ) \
5896 CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
5897 namespace{ Catch::ListenerRegistrar<listenerType> catch_internal_RegistrarFor##listenerType; } \
5898 CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS
5899 #else // CATCH_CONFIG_DISABLE
5900
5901 #define CATCH_REGISTER_REPORTER(name, reporterType)
5902 #define CATCH_REGISTER_LISTENER(listenerType)
5903
5904 #endif // CATCH_CONFIG_DISABLE
5905
5906 // end catch_reporter_registrars.hpp
5907 // Allow users to base their work off existing reporters
5908 // start catch_reporter_compact.h
5909
5910 namespace Catch {
5911
5912 struct CompactReporter : StreamingReporterBase<CompactReporter> {
5913
5914 using StreamingReporterBase::StreamingReporterBase;
5915
5916 ~CompactReporter() override;
5917
5918 static std::string getDescription();
5919
5920 ReporterPreferences getPreferences() const override;
5921
5922 void noMatchingTestCases(std::string const& spec) override;
5923
5924 void assertionStarting(AssertionInfo const&) override;
5925
5926 bool assertionEnded(AssertionStats const& _assertionStats) override;
5927
5928 void sectionEnded(SectionStats const& _sectionStats) override;
5929
5930 void testRunEnded(TestRunStats const& _testRunStats) override;
5931
5932 };
5933
5934 } // end namespace Catch
5935
5936 // end catch_reporter_compact.h
5937 // start catch_reporter_console.h
5938
5939 #if defined(_MSC_VER)
5940 #pragma warning(push)
5941 #pragma warning(disable:4061) // Not all labels are EXPLICITLY handled in switch
5942 // Note that 4062 (not all labels are handled
5943 // and default is missing) is enabled
5944 #endif
5945
5946 namespace Catch {
5947 // Fwd decls
5948 struct SummaryColumn;
5949 class TablePrinter;
5950
5951 struct ConsoleReporter : StreamingReporterBase<ConsoleReporter> {
5952 std::unique_ptr<TablePrinter> m_tablePrinter;
5953
5954 ConsoleReporter(ReporterConfig const& config);
5955 ~ConsoleReporter() override;
5956 static std::string getDescription();
5957
5958 void noMatchingTestCases(std::string const& spec) override;
5959
5960 void assertionStarting(AssertionInfo const&) override;
5961
5962 bool assertionEnded(AssertionStats const& _assertionStats) override;
5963
5964 void sectionStarting(SectionInfo const& _sectionInfo) override;
5965 void sectionEnded(SectionStats const& _sectionStats) override;
5966
5967 #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
5968 void benchmarkPreparing(std::string const& name) override;
5969 void benchmarkStarting(BenchmarkInfo const& info) override;
5970 void benchmarkEnded(BenchmarkStats<> const& stats) override;
5971 void benchmarkFailed(std::string const& error) override;
5972 #endif // CATCH_CONFIG_ENABLE_BENCHMARKING
5973
5974 void testCaseEnded(TestCaseStats const& _testCaseStats) override;
5975 void testGroupEnded(TestGroupStats const& _testGroupStats) override;
5976 void testRunEnded(TestRunStats const& _testRunStats) override;
5977 void testRunStarting(TestRunInfo const& _testRunInfo) override;
5978 private:
5979
5980 void lazyPrint();
5981
5982 void lazyPrintWithoutClosingBenchmarkTable();
5983 void lazyPrintRunInfo();
5984 void lazyPrintGroupInfo();
5985 void printTestCaseAndSectionHeader();
5986
5987 void printClosedHeader(std::string const& _name);
5988 void printOpenHeader(std::string const& _name);
5989
5990 // if string has a : in first line will set indent to follow it on
5991 // subsequent lines
5992 void printHeaderString(std::string const& _string, std::size_t indent = 0);
5993
5994 void printTotals(Totals const& totals);
5995 void printSummaryRow(std::string const& label, std::vector<SummaryColumn> const& cols, std::size_t row);
5996
5997 void printTotalsDivider(Totals const& totals);
5998 void printSummaryDivider();
5999 void printTestFilters();
6000
6001 private:
6002 bool m_headerPrinted = false;
6003 };
6004
6005 } // end namespace Catch
6006
6007 #if defined(_MSC_VER)
6008 #pragma warning(pop)
6009 #endif
6010
6011 // end catch_reporter_console.h
6012 // start catch_reporter_junit.h
6013
6014 // start catch_xmlwriter.h
6015
6016 #include <vector>
6017
6018 namespace Catch {
6019
6020 class XmlEncode {
6021 public:
6022 enum ForWhat { ForTextNodes, ForAttributes };
6023
6024 XmlEncode( std::string const& str, ForWhat forWhat = ForTextNodes );
6025
6026 void encodeTo( std::ostream& os ) const;
6027
6028 friend std::ostream& operator << ( std::ostream& os, XmlEncode const& xmlEncode );
6029
6030 private:
6031 std::string m_str;
6032 ForWhat m_forWhat;
6033 };
6034
6035 class XmlWriter {
6036 public:
6037
6038 class ScopedElement {
6039 public:
6040 ScopedElement( XmlWriter* writer );
6041
6042 ScopedElement( ScopedElement&& other ) noexcept;
6043 ScopedElement& operator=( ScopedElement&& other ) noexcept;
6044
6045 ~ScopedElement();
6046
6047 ScopedElement& writeText( std::string const& text, bool indent = true );
6048
6049 template<typename T>
writeAttribute(std::string const & name,T const & attribute)6050 ScopedElement& writeAttribute( std::string const& name, T const& attribute ) {
6051 m_writer->writeAttribute( name, attribute );
6052 return *this;
6053 }
6054
6055 private:
6056 mutable XmlWriter* m_writer = nullptr;
6057 };
6058
6059 XmlWriter( std::ostream& os = Catch::cout() );
6060 ~XmlWriter();
6061
6062 XmlWriter( XmlWriter const& ) = delete;
6063 XmlWriter& operator=( XmlWriter const& ) = delete;
6064
6065 XmlWriter& startElement( std::string const& name );
6066
6067 ScopedElement scopedElement( std::string const& name );
6068
6069 XmlWriter& endElement();
6070
6071 XmlWriter& writeAttribute( std::string const& name, std::string const& attribute );
6072
6073 XmlWriter& writeAttribute( std::string const& name, bool attribute );
6074
6075 template<typename T>
writeAttribute(std::string const & name,T const & attribute)6076 XmlWriter& writeAttribute( std::string const& name, T const& attribute ) {
6077 ReusableStringStream rss;
6078 rss << attribute;
6079 return writeAttribute( name, rss.str() );
6080 }
6081
6082 XmlWriter& writeText( std::string const& text, bool indent = true );
6083
6084 XmlWriter& writeComment( std::string const& text );
6085
6086 void writeStylesheetRef( std::string const& url );
6087
6088 XmlWriter& writeBlankLine();
6089
6090 void ensureTagClosed();
6091
6092 private:
6093
6094 void writeDeclaration();
6095
6096 void newlineIfNecessary();
6097
6098 bool m_tagIsOpen = false;
6099 bool m_needsNewline = false;
6100 std::vector<std::string> m_tags;
6101 std::string m_indent;
6102 std::ostream& m_os;
6103 };
6104
6105 }
6106
6107 // end catch_xmlwriter.h
6108 namespace Catch {
6109
6110 class JunitReporter : public CumulativeReporterBase<JunitReporter> {
6111 public:
6112 JunitReporter(ReporterConfig const& _config);
6113
6114 ~JunitReporter() override;
6115
6116 static std::string getDescription();
6117
6118 void noMatchingTestCases(std::string const& /*spec*/) override;
6119
6120 void testRunStarting(TestRunInfo const& runInfo) override;
6121
6122 void testGroupStarting(GroupInfo const& groupInfo) override;
6123
6124 void testCaseStarting(TestCaseInfo const& testCaseInfo) override;
6125 bool assertionEnded(AssertionStats const& assertionStats) override;
6126
6127 void testCaseEnded(TestCaseStats const& testCaseStats) override;
6128
6129 void testGroupEnded(TestGroupStats const& testGroupStats) override;
6130
6131 void testRunEndedCumulative() override;
6132
6133 void writeGroup(TestGroupNode const& groupNode, double suiteTime);
6134
6135 void writeTestCase(TestCaseNode const& testCaseNode);
6136
6137 void writeSection(std::string const& className,
6138 std::string const& rootName,
6139 SectionNode const& sectionNode);
6140
6141 void writeAssertions(SectionNode const& sectionNode);
6142 void writeAssertion(AssertionStats const& stats);
6143
6144 XmlWriter xml;
6145 Timer suiteTimer;
6146 std::string stdOutForSuite;
6147 std::string stdErrForSuite;
6148 unsigned int unexpectedExceptions = 0;
6149 bool m_okToFail = false;
6150 };
6151
6152 } // end namespace Catch
6153
6154 // end catch_reporter_junit.h
6155 // start catch_reporter_xml.h
6156
6157 namespace Catch {
6158 class XmlReporter : public StreamingReporterBase<XmlReporter> {
6159 public:
6160 XmlReporter(ReporterConfig const& _config);
6161
6162 ~XmlReporter() override;
6163
6164 static std::string getDescription();
6165
6166 virtual std::string getStylesheetRef() const;
6167
6168 void writeSourceInfo(SourceLineInfo const& sourceInfo);
6169
6170 public: // StreamingReporterBase
6171
6172 void noMatchingTestCases(std::string const& s) override;
6173
6174 void testRunStarting(TestRunInfo const& testInfo) override;
6175
6176 void testGroupStarting(GroupInfo const& groupInfo) override;
6177
6178 void testCaseStarting(TestCaseInfo const& testInfo) override;
6179
6180 void sectionStarting(SectionInfo const& sectionInfo) override;
6181
6182 void assertionStarting(AssertionInfo const&) override;
6183
6184 bool assertionEnded(AssertionStats const& assertionStats) override;
6185
6186 void sectionEnded(SectionStats const& sectionStats) override;
6187
6188 void testCaseEnded(TestCaseStats const& testCaseStats) override;
6189
6190 void testGroupEnded(TestGroupStats const& testGroupStats) override;
6191
6192 void testRunEnded(TestRunStats const& testRunStats) override;
6193
6194 #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
6195 void benchmarkPreparing(std::string const& name) override;
6196 void benchmarkStarting(BenchmarkInfo const&) override;
6197 void benchmarkEnded(BenchmarkStats<> const&) override;
6198 void benchmarkFailed(std::string const&) override;
6199 #endif // CATCH_CONFIG_ENABLE_BENCHMARKING
6200
6201 private:
6202 Timer m_testCaseTimer;
6203 XmlWriter m_xml;
6204 int m_sectionDepth = 0;
6205 };
6206
6207 } // end namespace Catch
6208
6209 // end catch_reporter_xml.h
6210
6211 // end catch_external_interfaces.h
6212 #endif
6213
6214 #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
6215 // start catch_benchmark.hpp
6216
6217 // Benchmark
6218
6219 // start catch_chronometer.hpp
6220
6221 // User-facing chronometer
6222
6223
6224 // start catch_clock.hpp
6225
6226 // Clocks
6227
6228
6229 #include <chrono>
6230 #include <ratio>
6231
6232 namespace Catch {
6233 namespace Benchmark {
6234 template <typename Clock>
6235 using ClockDuration = typename Clock::duration;
6236 template <typename Clock>
6237 using FloatDuration = std::chrono::duration<double, typename Clock::period>;
6238
6239 template <typename Clock>
6240 using TimePoint = typename Clock::time_point;
6241
6242 using default_clock = std::chrono::steady_clock;
6243
6244 template <typename Clock>
6245 struct now {
operator ()Catch::Benchmark::now6246 TimePoint<Clock> operator()() const {
6247 return Clock::now();
6248 }
6249 };
6250
6251 using fp_seconds = std::chrono::duration<double, std::ratio<1>>;
6252 } // namespace Benchmark
6253 } // namespace Catch
6254
6255 // end catch_clock.hpp
6256 // start catch_optimizer.hpp
6257
6258 // Hinting the optimizer
6259
6260
6261 #if defined(_MSC_VER)
6262 # include <atomic> // atomic_thread_fence
6263 #endif
6264
6265 namespace Catch {
6266 namespace Benchmark {
6267 #if defined(__GNUC__) || defined(__clang__)
6268 template <typename T>
keep_memory(T * p)6269 inline void keep_memory(T* p) {
6270 asm volatile("" : : "g"(p) : "memory");
6271 }
keep_memory()6272 inline void keep_memory() {
6273 asm volatile("" : : : "memory");
6274 }
6275
6276 namespace Detail {
optimizer_barrier()6277 inline void optimizer_barrier() { keep_memory(); }
6278 } // namespace Detail
6279 #elif defined(_MSC_VER)
6280
6281 #pragma optimize("", off)
6282 template <typename T>
6283 inline void keep_memory(T* p) {
6284 // thanks @milleniumbug
6285 *reinterpret_cast<char volatile*>(p) = *reinterpret_cast<char const volatile*>(p);
6286 }
6287 // TODO equivalent keep_memory()
6288 #pragma optimize("", on)
6289
6290 namespace Detail {
6291 inline void optimizer_barrier() {
6292 std::atomic_thread_fence(std::memory_order_seq_cst);
6293 }
6294 } // namespace Detail
6295
6296 #endif
6297
6298 template <typename T>
deoptimize_value(T && x)6299 inline void deoptimize_value(T&& x) {
6300 keep_memory(&x);
6301 }
6302
6303 template <typename Fn, typename... Args>
invoke_deoptimized(Fn && fn,Args &&...args)6304 inline auto invoke_deoptimized(Fn&& fn, Args&&... args) -> typename std::enable_if<!std::is_same<void, decltype(fn(args...))>::value>::type {
6305 deoptimize_value(std::forward<Fn>(fn) (std::forward<Args...>(args...)));
6306 }
6307
6308 template <typename Fn, typename... Args>
invoke_deoptimized(Fn && fn,Args &&...args)6309 inline auto invoke_deoptimized(Fn&& fn, Args&&... args) -> typename std::enable_if<std::is_same<void, decltype(fn(args...))>::value>::type {
6310 std::forward<Fn>(fn) (std::forward<Args...>(args...));
6311 }
6312 } // namespace Benchmark
6313 } // namespace Catch
6314
6315 // end catch_optimizer.hpp
6316 // start catch_complete_invoke.hpp
6317
6318 // Invoke with a special case for void
6319
6320
6321 #include <type_traits>
6322 #include <utility>
6323
6324 namespace Catch {
6325 namespace Benchmark {
6326 namespace Detail {
6327 template <typename T>
6328 struct CompleteType { using type = T; };
6329 template <>
6330 struct CompleteType<void> { struct type {}; };
6331
6332 template <typename T>
6333 using CompleteType_t = typename CompleteType<T>::type;
6334
6335 template <typename Result>
6336 struct CompleteInvoker {
6337 template <typename Fun, typename... Args>
invokeCatch::Benchmark::Detail::CompleteInvoker6338 static Result invoke(Fun&& fun, Args&&... args) {
6339 return std::forward<Fun>(fun)(std::forward<Args>(args)...);
6340 }
6341 };
6342 template <>
6343 struct CompleteInvoker<void> {
6344 template <typename Fun, typename... Args>
invokeCatch::Benchmark::Detail::CompleteInvoker6345 static CompleteType_t<void> invoke(Fun&& fun, Args&&... args) {
6346 std::forward<Fun>(fun)(std::forward<Args>(args)...);
6347 return {};
6348 }
6349 };
6350 template <typename Sig>
6351 using ResultOf_t = typename std::result_of<Sig>::type;
6352
6353 // invoke and not return void :(
6354 template <typename Fun, typename... Args>
complete_invoke(Fun && fun,Args &&...args)6355 CompleteType_t<ResultOf_t<Fun(Args...)>> complete_invoke(Fun&& fun, Args&&... args) {
6356 return CompleteInvoker<ResultOf_t<Fun(Args...)>>::invoke(std::forward<Fun>(fun), std::forward<Args>(args)...);
6357 }
6358
6359 const std::string benchmarkErrorMsg = "a benchmark failed to run successfully";
6360 } // namespace Detail
6361
6362 template <typename Fun>
user_code(Fun && fun)6363 Detail::CompleteType_t<Detail::ResultOf_t<Fun()>> user_code(Fun&& fun) {
6364 CATCH_TRY{
6365 return Detail::complete_invoke(std::forward<Fun>(fun));
6366 } CATCH_CATCH_ALL{
6367 getResultCapture().benchmarkFailed(translateActiveException());
6368 CATCH_RUNTIME_ERROR(Detail::benchmarkErrorMsg);
6369 }
6370 }
6371 } // namespace Benchmark
6372 } // namespace Catch
6373
6374 // end catch_complete_invoke.hpp
6375 namespace Catch {
6376 namespace Benchmark {
6377 namespace Detail {
6378 struct ChronometerConcept {
6379 virtual void start() = 0;
6380 virtual void finish() = 0;
6381 virtual ~ChronometerConcept() = default;
6382 };
6383 template <typename Clock>
6384 struct ChronometerModel final : public ChronometerConcept {
startCatch::Benchmark::Detail::ChronometerModel6385 void start() override { started = Clock::now(); }
finishCatch::Benchmark::Detail::ChronometerModel6386 void finish() override { finished = Clock::now(); }
6387
elapsedCatch::Benchmark::Detail::ChronometerModel6388 ClockDuration<Clock> elapsed() const { return finished - started; }
6389
6390 TimePoint<Clock> started;
6391 TimePoint<Clock> finished;
6392 };
6393 } // namespace Detail
6394
6395 struct Chronometer {
6396 public:
6397 template <typename Fun>
measureCatch::Benchmark::Chronometer6398 void measure(Fun&& fun) { measure(std::forward<Fun>(fun), is_callable<Fun(int)>()); }
6399
runsCatch::Benchmark::Chronometer6400 int runs() const { return k; }
6401
ChronometerCatch::Benchmark::Chronometer6402 Chronometer(Detail::ChronometerConcept& meter, int k)
6403 : impl(&meter)
6404 , k(k) {}
6405
6406 private:
6407 template <typename Fun>
measureCatch::Benchmark::Chronometer6408 void measure(Fun&& fun, std::false_type) {
6409 measure([&fun](int) { return fun(); }, std::true_type());
6410 }
6411
6412 template <typename Fun>
measureCatch::Benchmark::Chronometer6413 void measure(Fun&& fun, std::true_type) {
6414 Detail::optimizer_barrier();
6415 impl->start();
6416 for (int i = 0; i < k; ++i) invoke_deoptimized(fun, i);
6417 impl->finish();
6418 Detail::optimizer_barrier();
6419 }
6420
6421 Detail::ChronometerConcept* impl;
6422 int k;
6423 };
6424 } // namespace Benchmark
6425 } // namespace Catch
6426
6427 // end catch_chronometer.hpp
6428 // start catch_environment.hpp
6429
6430 // Environment information
6431
6432
6433 namespace Catch {
6434 namespace Benchmark {
6435 template <typename Duration>
6436 struct EnvironmentEstimate {
6437 Duration mean;
6438 OutlierClassification outliers;
6439
6440 template <typename Duration2>
operator EnvironmentEstimate<Duration2>Catch::Benchmark::EnvironmentEstimate6441 operator EnvironmentEstimate<Duration2>() const {
6442 return { mean, outliers };
6443 }
6444 };
6445 template <typename Clock>
6446 struct Environment {
6447 using clock_type = Clock;
6448 EnvironmentEstimate<FloatDuration<Clock>> clock_resolution;
6449 EnvironmentEstimate<FloatDuration<Clock>> clock_cost;
6450 };
6451 } // namespace Benchmark
6452 } // namespace Catch
6453
6454 // end catch_environment.hpp
6455 // start catch_execution_plan.hpp
6456
6457 // Execution plan
6458
6459
6460 // start catch_benchmark_function.hpp
6461
6462 // Dumb std::function implementation for consistent call overhead
6463
6464
6465 #include <cassert>
6466 #include <type_traits>
6467 #include <utility>
6468 #include <memory>
6469
6470 namespace Catch {
6471 namespace Benchmark {
6472 namespace Detail {
6473 template <typename T>
6474 using Decay = typename std::decay<T>::type;
6475 template <typename T, typename U>
6476 struct is_related
6477 : std::is_same<Decay<T>, Decay<U>> {};
6478
6479 /// We need to reinvent std::function because every piece of code that might add overhead
6480 /// in a measurement context needs to have consistent performance characteristics so that we
6481 /// can account for it in the measurement.
6482 /// Implementations of std::function with optimizations that aren't always applicable, like
6483 /// small buffer optimizations, are not uncommon.
6484 /// This is effectively an implementation of std::function without any such optimizations;
6485 /// it may be slow, but it is consistently slow.
6486 struct BenchmarkFunction {
6487 private:
6488 struct callable {
6489 virtual void call(Chronometer meter) const = 0;
6490 virtual callable* clone() const = 0;
6491 virtual ~callable() = default;
6492 };
6493 template <typename Fun>
6494 struct model : public callable {
modelCatch::Benchmark::Detail::BenchmarkFunction::model6495 model(Fun&& fun) : fun(std::move(fun)) {}
modelCatch::Benchmark::Detail::BenchmarkFunction::model6496 model(Fun const& fun) : fun(fun) {}
6497
cloneCatch::Benchmark::Detail::BenchmarkFunction::model6498 model<Fun>* clone() const override { return new model<Fun>(*this); }
6499
callCatch::Benchmark::Detail::BenchmarkFunction::model6500 void call(Chronometer meter) const override {
6501 call(meter, is_callable<Fun(Chronometer)>());
6502 }
callCatch::Benchmark::Detail::BenchmarkFunction::model6503 void call(Chronometer meter, std::true_type) const {
6504 fun(meter);
6505 }
callCatch::Benchmark::Detail::BenchmarkFunction::model6506 void call(Chronometer meter, std::false_type) const {
6507 meter.measure(fun);
6508 }
6509
6510 Fun fun;
6511 };
6512
operator ()Catch::Benchmark::Detail::BenchmarkFunction::do_nothing6513 struct do_nothing { void operator()() const {} };
6514
6515 template <typename T>
BenchmarkFunctionCatch::Benchmark::Detail::BenchmarkFunction6516 BenchmarkFunction(model<T>* c) : f(c) {}
6517
6518 public:
BenchmarkFunctionCatch::Benchmark::Detail::BenchmarkFunction6519 BenchmarkFunction()
6520 : f(new model<do_nothing>{ {} }) {}
6521
6522 template <typename Fun,
6523 typename std::enable_if<!is_related<Fun, BenchmarkFunction>::value, int>::type = 0>
BenchmarkFunctionCatch::Benchmark::Detail::BenchmarkFunction6524 BenchmarkFunction(Fun&& fun)
6525 : f(new model<typename std::decay<Fun>::type>(std::forward<Fun>(fun))) {}
6526
BenchmarkFunctionCatch::Benchmark::Detail::BenchmarkFunction6527 BenchmarkFunction(BenchmarkFunction&& that)
6528 : f(std::move(that.f)) {}
6529
BenchmarkFunctionCatch::Benchmark::Detail::BenchmarkFunction6530 BenchmarkFunction(BenchmarkFunction const& that)
6531 : f(that.f->clone()) {}
6532
operator =Catch::Benchmark::Detail::BenchmarkFunction6533 BenchmarkFunction& operator=(BenchmarkFunction&& that) {
6534 f = std::move(that.f);
6535 return *this;
6536 }
6537
operator =Catch::Benchmark::Detail::BenchmarkFunction6538 BenchmarkFunction& operator=(BenchmarkFunction const& that) {
6539 f.reset(that.f->clone());
6540 return *this;
6541 }
6542
operator ()Catch::Benchmark::Detail::BenchmarkFunction6543 void operator()(Chronometer meter) const { f->call(meter); }
6544
6545 private:
6546 std::unique_ptr<callable> f;
6547 };
6548 } // namespace Detail
6549 } // namespace Benchmark
6550 } // namespace Catch
6551
6552 // end catch_benchmark_function.hpp
6553 // start catch_repeat.hpp
6554
6555 // repeat algorithm
6556
6557
6558 #include <type_traits>
6559 #include <utility>
6560
6561 namespace Catch {
6562 namespace Benchmark {
6563 namespace Detail {
6564 template <typename Fun>
6565 struct repeater {
operator ()Catch::Benchmark::Detail::repeater6566 void operator()(int k) const {
6567 for (int i = 0; i < k; ++i) {
6568 fun();
6569 }
6570 }
6571 Fun fun;
6572 };
6573 template <typename Fun>
repeat(Fun && fun)6574 repeater<typename std::decay<Fun>::type> repeat(Fun&& fun) {
6575 return { std::forward<Fun>(fun) };
6576 }
6577 } // namespace Detail
6578 } // namespace Benchmark
6579 } // namespace Catch
6580
6581 // end catch_repeat.hpp
6582 // start catch_run_for_at_least.hpp
6583
6584 // Run a function for a minimum amount of time
6585
6586
6587 // start catch_measure.hpp
6588
6589 // Measure
6590
6591
6592 // start catch_timing.hpp
6593
6594 // Timing
6595
6596
6597 #include <tuple>
6598 #include <type_traits>
6599
6600 namespace Catch {
6601 namespace Benchmark {
6602 template <typename Duration, typename Result>
6603 struct Timing {
6604 Duration elapsed;
6605 Result result;
6606 int iterations;
6607 };
6608 template <typename Clock, typename Sig>
6609 using TimingOf = Timing<ClockDuration<Clock>, Detail::CompleteType_t<Detail::ResultOf_t<Sig>>>;
6610 } // namespace Benchmark
6611 } // namespace Catch
6612
6613 // end catch_timing.hpp
6614 #include <utility>
6615
6616 namespace Catch {
6617 namespace Benchmark {
6618 namespace Detail {
6619 template <typename Clock, typename Fun, typename... Args>
measure(Fun && fun,Args &&...args)6620 TimingOf<Clock, Fun(Args...)> measure(Fun&& fun, Args&&... args) {
6621 auto start = Clock::now();
6622 auto&& r = Detail::complete_invoke(fun, std::forward<Args>(args)...);
6623 auto end = Clock::now();
6624 auto delta = end - start;
6625 return { delta, std::forward<decltype(r)>(r), 1 };
6626 }
6627 } // namespace Detail
6628 } // namespace Benchmark
6629 } // namespace Catch
6630
6631 // end catch_measure.hpp
6632 #include <utility>
6633 #include <type_traits>
6634
6635 namespace Catch {
6636 namespace Benchmark {
6637 namespace Detail {
6638 template <typename Clock, typename Fun>
measure_one(Fun && fun,int iters,std::false_type)6639 TimingOf<Clock, Fun(int)> measure_one(Fun&& fun, int iters, std::false_type) {
6640 return Detail::measure<Clock>(fun, iters);
6641 }
6642 template <typename Clock, typename Fun>
measure_one(Fun && fun,int iters,std::true_type)6643 TimingOf<Clock, Fun(Chronometer)> measure_one(Fun&& fun, int iters, std::true_type) {
6644 Detail::ChronometerModel<Clock> meter;
6645 auto&& result = Detail::complete_invoke(fun, Chronometer(meter, iters));
6646
6647 return { meter.elapsed(), std::move(result), iters };
6648 }
6649
6650 template <typename Clock, typename Fun>
6651 using run_for_at_least_argument_t = typename std::conditional<is_callable<Fun(Chronometer)>::value, Chronometer, int>::type;
6652
6653 struct optimized_away_error : std::exception {
whatCatch::Benchmark::Detail::optimized_away_error6654 const char* what() const noexcept override {
6655 return "could not measure benchmark, maybe it was optimized away";
6656 }
6657 };
6658
6659 template <typename Clock, typename Fun>
run_for_at_least(ClockDuration<Clock> how_long,int seed,Fun && fun)6660 TimingOf<Clock, Fun(run_for_at_least_argument_t<Clock, Fun>)> run_for_at_least(ClockDuration<Clock> how_long, int seed, Fun&& fun) {
6661 auto iters = seed;
6662 while (iters < (1 << 30)) {
6663 auto&& Timing = measure_one<Clock>(fun, iters, is_callable<Fun(Chronometer)>());
6664
6665 if (Timing.elapsed >= how_long) {
6666 return { Timing.elapsed, std::move(Timing.result), iters };
6667 }
6668 iters *= 2;
6669 }
6670 throw optimized_away_error{};
6671 }
6672 } // namespace Detail
6673 } // namespace Benchmark
6674 } // namespace Catch
6675
6676 // end catch_run_for_at_least.hpp
6677 #include <algorithm>
6678
6679 namespace Catch {
6680 namespace Benchmark {
6681 template <typename Duration>
6682 struct ExecutionPlan {
6683 int iterations_per_sample;
6684 Duration estimated_duration;
6685 Detail::BenchmarkFunction benchmark;
6686 Duration warmup_time;
6687 int warmup_iterations;
6688
6689 template <typename Duration2>
operator ExecutionPlan<Duration2>Catch::Benchmark::ExecutionPlan6690 operator ExecutionPlan<Duration2>() const {
6691 return { iterations_per_sample, estimated_duration, benchmark, warmup_time, warmup_iterations };
6692 }
6693
6694 template <typename Clock>
runCatch::Benchmark::ExecutionPlan6695 std::vector<FloatDuration<Clock>> run(const IConfig &cfg, Environment<FloatDuration<Clock>> env) const {
6696 // warmup a bit
6697 Detail::run_for_at_least<Clock>(std::chrono::duration_cast<ClockDuration<Clock>>(warmup_time), warmup_iterations, Detail::repeat(now<Clock>{}));
6698
6699 std::vector<FloatDuration<Clock>> times;
6700 times.reserve(cfg.benchmarkSamples());
6701 std::generate_n(std::back_inserter(times), cfg.benchmarkSamples(), [this, env] {
6702 Detail::ChronometerModel<Clock> model;
6703 this->benchmark(Chronometer(model, iterations_per_sample));
6704 auto sample_time = model.elapsed() - env.clock_cost.mean;
6705 if (sample_time < FloatDuration<Clock>::zero()) sample_time = FloatDuration<Clock>::zero();
6706 return sample_time / iterations_per_sample;
6707 });
6708 return times;
6709 }
6710 };
6711 } // namespace Benchmark
6712 } // namespace Catch
6713
6714 // end catch_execution_plan.hpp
6715 // start catch_estimate_clock.hpp
6716
6717 // Environment measurement
6718
6719
6720 // start catch_stats.hpp
6721
6722 // Statistical analysis tools
6723
6724
6725 #include <algorithm>
6726 #include <functional>
6727 #include <vector>
6728 #include <numeric>
6729 #include <tuple>
6730 #include <cmath>
6731 #include <utility>
6732 #include <cstddef>
6733
6734 namespace Catch {
6735 namespace Benchmark {
6736 namespace Detail {
6737 using sample = std::vector<double>;
6738
6739 double weighted_average_quantile(int k, int q, std::vector<double>::iterator first, std::vector<double>::iterator last);
6740
6741 template <typename Iterator>
classify_outliers(Iterator first,Iterator last)6742 OutlierClassification classify_outliers(Iterator first, Iterator last) {
6743 std::vector<double> copy(first, last);
6744
6745 auto q1 = weighted_average_quantile(1, 4, copy.begin(), copy.end());
6746 auto q3 = weighted_average_quantile(3, 4, copy.begin(), copy.end());
6747 auto iqr = q3 - q1;
6748 auto los = q1 - (iqr * 3.);
6749 auto lom = q1 - (iqr * 1.5);
6750 auto him = q3 + (iqr * 1.5);
6751 auto his = q3 + (iqr * 3.);
6752
6753 OutlierClassification o;
6754 for (; first != last; ++first) {
6755 auto&& t = *first;
6756 if (t < los) ++o.low_severe;
6757 else if (t < lom) ++o.low_mild;
6758 else if (t > his) ++o.high_severe;
6759 else if (t > him) ++o.high_mild;
6760 ++o.samples_seen;
6761 }
6762 return o;
6763 }
6764
6765 template <typename Iterator>
mean(Iterator first,Iterator last)6766 double mean(Iterator first, Iterator last) {
6767 auto count = last - first;
6768 double sum = std::accumulate(first, last, 0.);
6769 return sum / count;
6770 }
6771
6772 template <typename URng, typename Iterator, typename Estimator>
resample(URng & rng,int resamples,Iterator first,Iterator last,Estimator & estimator)6773 sample resample(URng& rng, int resamples, Iterator first, Iterator last, Estimator& estimator) {
6774 auto n = last - first;
6775 std::uniform_int_distribution<decltype(n)> dist(0, n - 1);
6776
6777 sample out;
6778 out.reserve(resamples);
6779 std::generate_n(std::back_inserter(out), resamples, [n, first, &estimator, &dist, &rng] {
6780 std::vector<double> resampled;
6781 resampled.reserve(n);
6782 std::generate_n(std::back_inserter(resampled), n, [first, &dist, &rng] { return first[dist(rng)]; });
6783 return estimator(resampled.begin(), resampled.end());
6784 });
6785 std::sort(out.begin(), out.end());
6786 return out;
6787 }
6788
6789 template <typename Estimator, typename Iterator>
jackknife(Estimator && estimator,Iterator first,Iterator last)6790 sample jackknife(Estimator&& estimator, Iterator first, Iterator last) {
6791 auto n = last - first;
6792 auto second = std::next(first);
6793 sample results;
6794 results.reserve(n);
6795
6796 for (auto it = first; it != last; ++it) {
6797 std::iter_swap(it, first);
6798 results.push_back(estimator(second, last));
6799 }
6800
6801 return results;
6802 }
6803
normal_cdf(double x)6804 inline double normal_cdf(double x) {
6805 return std::erfc(-x / std::sqrt(2.0)) / 2.0;
6806 }
6807
6808 double erfc_inv(double x);
6809
6810 double normal_quantile(double p);
6811
6812 template <typename Iterator, typename Estimator>
bootstrap(double confidence_level,Iterator first,Iterator last,sample const & resample,Estimator && estimator)6813 Estimate<double> bootstrap(double confidence_level, Iterator first, Iterator last, sample const& resample, Estimator&& estimator) {
6814 auto n_samples = last - first;
6815
6816 double point = estimator(first, last);
6817 // Degenerate case with a single sample
6818 if (n_samples == 1) return { point, point, point, confidence_level };
6819
6820 sample jack = jackknife(estimator, first, last);
6821 double jack_mean = mean(jack.begin(), jack.end());
6822 double sum_squares, sum_cubes;
6823 std::tie(sum_squares, sum_cubes) = std::accumulate(jack.begin(), jack.end(), std::make_pair(0., 0.), [jack_mean](std::pair<double, double> sqcb, double x) -> std::pair<double, double> {
6824 auto d = jack_mean - x;
6825 auto d2 = d * d;
6826 auto d3 = d2 * d;
6827 return { sqcb.first + d2, sqcb.second + d3 };
6828 });
6829
6830 double accel = sum_cubes / (6 * std::pow(sum_squares, 1.5));
6831 int n = static_cast<int>(resample.size());
6832 double prob_n = std::count_if(resample.begin(), resample.end(), [point](double x) { return x < point; }) / (double)n;
6833 // degenerate case with uniform samples
6834 if (prob_n == 0) return { point, point, point, confidence_level };
6835
6836 double bias = normal_quantile(prob_n);
6837 double z1 = normal_quantile((1. - confidence_level) / 2.);
6838
6839 auto cumn = [n](double x) -> int {
6840 return std::lround(normal_cdf(x) * n); };
6841 auto a = [bias, accel](double b) { return bias + b / (1. - accel * b); };
6842 double b1 = bias + z1;
6843 double b2 = bias - z1;
6844 double a1 = a(b1);
6845 double a2 = a(b2);
6846 auto lo = std::max(cumn(a1), 0);
6847 auto hi = std::min(cumn(a2), n - 1);
6848
6849 return { point, resample[lo], resample[hi], confidence_level };
6850 }
6851
6852 double outlier_variance(Estimate<double> mean, Estimate<double> stddev, int n);
6853
6854 struct bootstrap_analysis {
6855 Estimate<double> mean;
6856 Estimate<double> standard_deviation;
6857 double outlier_variance;
6858 };
6859
6860 bootstrap_analysis analyse_samples(double confidence_level, int n_resamples, std::vector<double>::iterator first, std::vector<double>::iterator last);
6861 } // namespace Detail
6862 } // namespace Benchmark
6863 } // namespace Catch
6864
6865 // end catch_stats.hpp
6866 #include <algorithm>
6867 #include <iterator>
6868 #include <tuple>
6869 #include <vector>
6870 #include <cmath>
6871
6872 namespace Catch {
6873 namespace Benchmark {
6874 namespace Detail {
6875 template <typename Clock>
resolution(int k)6876 std::vector<double> resolution(int k) {
6877 std::vector<TimePoint<Clock>> times;
6878 times.reserve(k + 1);
6879 std::generate_n(std::back_inserter(times), k + 1, now<Clock>{});
6880
6881 std::vector<double> deltas;
6882 deltas.reserve(k);
6883 std::transform(std::next(times.begin()), times.end(), times.begin(),
6884 std::back_inserter(deltas),
6885 [](TimePoint<Clock> a, TimePoint<Clock> b) { return static_cast<double>((a - b).count()); });
6886
6887 return deltas;
6888 }
6889
6890 const auto warmup_iterations = 10000;
6891 const auto warmup_time = std::chrono::milliseconds(100);
6892 const auto minimum_ticks = 1000;
6893 const auto warmup_seed = 10000;
6894 const auto clock_resolution_estimation_time = std::chrono::milliseconds(500);
6895 const auto clock_cost_estimation_time_limit = std::chrono::seconds(1);
6896 const auto clock_cost_estimation_tick_limit = 100000;
6897 const auto clock_cost_estimation_time = std::chrono::milliseconds(10);
6898 const auto clock_cost_estimation_iterations = 10000;
6899
6900 template <typename Clock>
warmup()6901 int warmup() {
6902 return run_for_at_least<Clock>(std::chrono::duration_cast<ClockDuration<Clock>>(warmup_time), warmup_seed, &resolution<Clock>)
6903 .iterations;
6904 }
6905 template <typename Clock>
estimate_clock_resolution(int iterations)6906 EnvironmentEstimate<FloatDuration<Clock>> estimate_clock_resolution(int iterations) {
6907 auto r = run_for_at_least<Clock>(std::chrono::duration_cast<ClockDuration<Clock>>(clock_resolution_estimation_time), iterations, &resolution<Clock>)
6908 .result;
6909 return {
6910 FloatDuration<Clock>(mean(r.begin(), r.end())),
6911 classify_outliers(r.begin(), r.end()),
6912 };
6913 }
6914 template <typename Clock>
estimate_clock_cost(FloatDuration<Clock> resolution)6915 EnvironmentEstimate<FloatDuration<Clock>> estimate_clock_cost(FloatDuration<Clock> resolution) {
6916 auto time_limit = std::min(resolution * clock_cost_estimation_tick_limit, FloatDuration<Clock>(clock_cost_estimation_time_limit));
6917 auto time_clock = [](int k) {
6918 return Detail::measure<Clock>([k] {
6919 for (int i = 0; i < k; ++i) {
6920 volatile auto ignored = Clock::now();
6921 (void)ignored;
6922 }
6923 }).elapsed;
6924 };
6925 time_clock(1);
6926 int iters = clock_cost_estimation_iterations;
6927 auto&& r = run_for_at_least<Clock>(std::chrono::duration_cast<ClockDuration<Clock>>(clock_cost_estimation_time), iters, time_clock);
6928 std::vector<double> times;
6929 int nsamples = static_cast<int>(std::ceil(time_limit / r.elapsed));
6930 times.reserve(nsamples);
6931 std::generate_n(std::back_inserter(times), nsamples, [time_clock, &r] {
6932 return static_cast<double>((time_clock(r.iterations) / r.iterations).count());
6933 });
6934 return {
6935 FloatDuration<Clock>(mean(times.begin(), times.end())),
6936 classify_outliers(times.begin(), times.end()),
6937 };
6938 }
6939
6940 template <typename Clock>
measure_environment()6941 Environment<FloatDuration<Clock>> measure_environment() {
6942 static Environment<FloatDuration<Clock>>* env = nullptr;
6943 if (env) {
6944 return *env;
6945 }
6946
6947 auto iters = Detail::warmup<Clock>();
6948 auto resolution = Detail::estimate_clock_resolution<Clock>(iters);
6949 auto cost = Detail::estimate_clock_cost<Clock>(resolution.mean);
6950
6951 env = new Environment<FloatDuration<Clock>>{ resolution, cost };
6952 return *env;
6953 }
6954 } // namespace Detail
6955 } // namespace Benchmark
6956 } // namespace Catch
6957
6958 // end catch_estimate_clock.hpp
6959 // start catch_analyse.hpp
6960
6961 // Run and analyse one benchmark
6962
6963
6964 // start catch_sample_analysis.hpp
6965
6966 // Benchmark results
6967
6968
6969 #include <algorithm>
6970 #include <vector>
6971 #include <string>
6972 #include <iterator>
6973
6974 namespace Catch {
6975 namespace Benchmark {
6976 template <typename Duration>
6977 struct SampleAnalysis {
6978 std::vector<Duration> samples;
6979 Estimate<Duration> mean;
6980 Estimate<Duration> standard_deviation;
6981 OutlierClassification outliers;
6982 double outlier_variance;
6983
6984 template <typename Duration2>
operator SampleAnalysis<Duration2>Catch::Benchmark::SampleAnalysis6985 operator SampleAnalysis<Duration2>() const {
6986 std::vector<Duration2> samples2;
6987 samples2.reserve(samples.size());
6988 std::transform(samples.begin(), samples.end(), std::back_inserter(samples2), [](Duration d) { return Duration2(d); });
6989 return {
6990 std::move(samples2),
6991 mean,
6992 standard_deviation,
6993 outliers,
6994 outlier_variance,
6995 };
6996 }
6997 };
6998 } // namespace Benchmark
6999 } // namespace Catch
7000
7001 // end catch_sample_analysis.hpp
7002 #include <algorithm>
7003 #include <iterator>
7004 #include <vector>
7005
7006 namespace Catch {
7007 namespace Benchmark {
7008 namespace Detail {
7009 template <typename Duration, typename Iterator>
analyse(const IConfig & cfg,Environment<Duration>,Iterator first,Iterator last)7010 SampleAnalysis<Duration> analyse(const IConfig &cfg, Environment<Duration>, Iterator first, Iterator last) {
7011 if (!cfg.benchmarkNoAnalysis()) {
7012 std::vector<double> samples;
7013 samples.reserve(last - first);
7014 std::transform(first, last, std::back_inserter(samples), [](Duration d) { return d.count(); });
7015
7016 auto analysis = Catch::Benchmark::Detail::analyse_samples(cfg.benchmarkConfidenceInterval(), cfg.benchmarkResamples(), samples.begin(), samples.end());
7017 auto outliers = Catch::Benchmark::Detail::classify_outliers(samples.begin(), samples.end());
7018
7019 auto wrap_estimate = [](Estimate<double> e) {
7020 return Estimate<Duration> {
7021 Duration(e.point),
7022 Duration(e.lower_bound),
7023 Duration(e.upper_bound),
7024 e.confidence_interval,
7025 };
7026 };
7027 std::vector<Duration> samples2;
7028 samples2.reserve(samples.size());
7029 std::transform(samples.begin(), samples.end(), std::back_inserter(samples2), [](double d) { return Duration(d); });
7030 return {
7031 std::move(samples2),
7032 wrap_estimate(analysis.mean),
7033 wrap_estimate(analysis.standard_deviation),
7034 outliers,
7035 analysis.outlier_variance,
7036 };
7037 } else {
7038 std::vector<Duration> samples;
7039 samples.reserve(last - first);
7040
7041 Duration mean = Duration(0);
7042 int i = 0;
7043 for (auto it = first; it < last; ++it, ++i) {
7044 samples.push_back(Duration(*it));
7045 mean += Duration(*it);
7046 }
7047 mean /= i;
7048
7049 return {
7050 std::move(samples),
7051 Estimate<Duration>{mean, mean, mean, 0.0},
7052 Estimate<Duration>{Duration(0), Duration(0), Duration(0), 0.0},
7053 OutlierClassification{},
7054 0.0
7055 };
7056 }
7057 }
7058 } // namespace Detail
7059 } // namespace Benchmark
7060 } // namespace Catch
7061
7062 // end catch_analyse.hpp
7063 #include <algorithm>
7064 #include <functional>
7065 #include <string>
7066 #include <vector>
7067 #include <cmath>
7068
7069 namespace Catch {
7070 namespace Benchmark {
7071 struct Benchmark {
BenchmarkCatch::Benchmark::Benchmark7072 Benchmark(std::string &&name)
7073 : name(std::move(name)) {}
7074
7075 template <class FUN>
BenchmarkCatch::Benchmark::Benchmark7076 Benchmark(std::string &&name, FUN &&func)
7077 : fun(std::move(func)), name(std::move(name)) {}
7078
7079 template <typename Clock>
prepareCatch::Benchmark::Benchmark7080 ExecutionPlan<FloatDuration<Clock>> prepare(const IConfig &cfg, Environment<FloatDuration<Clock>> env) const {
7081 auto min_time = env.clock_resolution.mean * Detail::minimum_ticks;
7082 auto run_time = std::max(min_time, std::chrono::duration_cast<decltype(min_time)>(Detail::warmup_time));
7083 auto&& test = Detail::run_for_at_least<Clock>(std::chrono::duration_cast<ClockDuration<Clock>>(run_time), 1, fun);
7084 int new_iters = static_cast<int>(std::ceil(min_time * test.iterations / test.elapsed));
7085 return { new_iters, test.elapsed / test.iterations * new_iters * cfg.benchmarkSamples(), fun, std::chrono::duration_cast<FloatDuration<Clock>>(Detail::warmup_time), Detail::warmup_iterations };
7086 }
7087
7088 template <typename Clock = default_clock>
runCatch::Benchmark::Benchmark7089 void run() {
7090 IConfigPtr cfg = getCurrentContext().getConfig();
7091
7092 auto env = Detail::measure_environment<Clock>();
7093
7094 getResultCapture().benchmarkPreparing(name);
7095 CATCH_TRY{
7096 auto plan = user_code([&] {
7097 return prepare<Clock>(*cfg, env);
7098 });
7099
7100 BenchmarkInfo info {
7101 name,
7102 plan.estimated_duration.count(),
7103 plan.iterations_per_sample,
7104 cfg->benchmarkSamples(),
7105 cfg->benchmarkResamples(),
7106 env.clock_resolution.mean.count(),
7107 env.clock_cost.mean.count()
7108 };
7109
7110 getResultCapture().benchmarkStarting(info);
7111
7112 auto samples = user_code([&] {
7113 return plan.template run<Clock>(*cfg, env);
7114 });
7115
7116 auto analysis = Detail::analyse(*cfg, env, samples.begin(), samples.end());
7117 BenchmarkStats<std::chrono::duration<double, std::nano>> stats{ info, analysis.samples, analysis.mean, analysis.standard_deviation, analysis.outliers, analysis.outlier_variance };
7118 getResultCapture().benchmarkEnded(stats);
7119
7120 } CATCH_CATCH_ALL{
7121 if (translateActiveException() != Detail::benchmarkErrorMsg) // benchmark errors have been reported, otherwise rethrow.
7122 std::rethrow_exception(std::current_exception());
7123 }
7124 }
7125
7126 // sets lambda to be used in fun *and* executes benchmark!
7127 template <typename Fun,
7128 typename std::enable_if<!Detail::is_related<Fun, Benchmark>::value, int>::type = 0>
operator =Catch::Benchmark::Benchmark7129 Benchmark & operator=(Fun func) {
7130 fun = Detail::BenchmarkFunction(func);
7131 run();
7132 return *this;
7133 }
7134
operator boolCatch::Benchmark::Benchmark7135 explicit operator bool() {
7136 return true;
7137 }
7138
7139 private:
7140 Detail::BenchmarkFunction fun;
7141 std::string name;
7142 };
7143 }
7144 } // namespace Catch
7145
7146 #define INTERNAL_CATCH_GET_1_ARG(arg1, arg2, ...) arg1
7147 #define INTERNAL_CATCH_GET_2_ARG(arg1, arg2, ...) arg2
7148
7149 #define INTERNAL_CATCH_BENCHMARK(BenchmarkName, name, benchmarkIndex)\
7150 if( Catch::Benchmark::Benchmark BenchmarkName{name} ) \
7151 BenchmarkName = [&](int benchmarkIndex)
7152
7153 #define INTERNAL_CATCH_BENCHMARK_ADVANCED(BenchmarkName, name)\
7154 if( Catch::Benchmark::Benchmark BenchmarkName{name} ) \
7155 BenchmarkName = [&]
7156
7157 // end catch_benchmark.hpp
7158 #endif
7159
7160 #endif // ! CATCH_CONFIG_IMPL_ONLY
7161
7162 #ifdef CATCH_IMPL
7163 // start catch_impl.hpp
7164
7165 #ifdef __clang__
7166 #pragma clang diagnostic push
7167 #pragma clang diagnostic ignored "-Wweak-vtables"
7168 #endif
7169
7170 // Keep these here for external reporters
7171 // start catch_test_case_tracker.h
7172
7173 #include <string>
7174 #include <vector>
7175 #include <memory>
7176
7177 namespace Catch {
7178 namespace TestCaseTracking {
7179
7180 struct NameAndLocation {
7181 std::string name;
7182 SourceLineInfo location;
7183
7184 NameAndLocation( std::string const& _name, SourceLineInfo const& _location );
7185 };
7186
7187 struct ITracker;
7188
7189 using ITrackerPtr = std::shared_ptr<ITracker>;
7190
7191 struct ITracker {
7192 virtual ~ITracker();
7193
7194 // static queries
7195 virtual NameAndLocation const& nameAndLocation() const = 0;
7196
7197 // dynamic queries
7198 virtual bool isComplete() const = 0; // Successfully completed or failed
7199 virtual bool isSuccessfullyCompleted() const = 0;
7200 virtual bool isOpen() const = 0; // Started but not complete
7201 virtual bool hasChildren() const = 0;
7202
7203 virtual ITracker& parent() = 0;
7204
7205 // actions
7206 virtual void close() = 0; // Successfully complete
7207 virtual void fail() = 0;
7208 virtual void markAsNeedingAnotherRun() = 0;
7209
7210 virtual void addChild( ITrackerPtr const& child ) = 0;
7211 virtual ITrackerPtr findChild( NameAndLocation const& nameAndLocation ) = 0;
7212 virtual void openChild() = 0;
7213
7214 // Debug/ checking
7215 virtual bool isSectionTracker() const = 0;
7216 virtual bool isGeneratorTracker() const = 0;
7217 };
7218
7219 class TrackerContext {
7220
7221 enum RunState {
7222 NotStarted,
7223 Executing,
7224 CompletedCycle
7225 };
7226
7227 ITrackerPtr m_rootTracker;
7228 ITracker* m_currentTracker = nullptr;
7229 RunState m_runState = NotStarted;
7230
7231 public:
7232
7233 ITracker& startRun();
7234 void endRun();
7235
7236 void startCycle();
7237 void completeCycle();
7238
7239 bool completedCycle() const;
7240 ITracker& currentTracker();
7241 void setCurrentTracker( ITracker* tracker );
7242 };
7243
7244 class TrackerBase : public ITracker {
7245 protected:
7246 enum CycleState {
7247 NotStarted,
7248 Executing,
7249 ExecutingChildren,
7250 NeedsAnotherRun,
7251 CompletedSuccessfully,
7252 Failed
7253 };
7254
7255 using Children = std::vector<ITrackerPtr>;
7256 NameAndLocation m_nameAndLocation;
7257 TrackerContext& m_ctx;
7258 ITracker* m_parent;
7259 Children m_children;
7260 CycleState m_runState = NotStarted;
7261
7262 public:
7263 TrackerBase( NameAndLocation const& nameAndLocation, TrackerContext& ctx, ITracker* parent );
7264
7265 NameAndLocation const& nameAndLocation() const override;
7266 bool isComplete() const override;
7267 bool isSuccessfullyCompleted() const override;
7268 bool isOpen() const override;
7269 bool hasChildren() const override;
7270
7271 void addChild( ITrackerPtr const& child ) override;
7272
7273 ITrackerPtr findChild( NameAndLocation const& nameAndLocation ) override;
7274 ITracker& parent() override;
7275
7276 void openChild() override;
7277
7278 bool isSectionTracker() const override;
7279 bool isGeneratorTracker() const override;
7280
7281 void open();
7282
7283 void close() override;
7284 void fail() override;
7285 void markAsNeedingAnotherRun() override;
7286
7287 private:
7288 void moveToParent();
7289 void moveToThis();
7290 };
7291
7292 class SectionTracker : public TrackerBase {
7293 std::vector<std::string> m_filters;
7294 public:
7295 SectionTracker( NameAndLocation const& nameAndLocation, TrackerContext& ctx, ITracker* parent );
7296
7297 bool isSectionTracker() const override;
7298
7299 bool isComplete() const override;
7300
7301 static SectionTracker& acquire( TrackerContext& ctx, NameAndLocation const& nameAndLocation );
7302
7303 void tryOpen();
7304
7305 void addInitialFilters( std::vector<std::string> const& filters );
7306 void addNextFilters( std::vector<std::string> const& filters );
7307 };
7308
7309 } // namespace TestCaseTracking
7310
7311 using TestCaseTracking::ITracker;
7312 using TestCaseTracking::TrackerContext;
7313 using TestCaseTracking::SectionTracker;
7314
7315 } // namespace Catch
7316
7317 // end catch_test_case_tracker.h
7318
7319 // start catch_leak_detector.h
7320
7321 namespace Catch {
7322
7323 struct LeakDetector {
7324 LeakDetector();
7325 ~LeakDetector();
7326 };
7327
7328 }
7329 // end catch_leak_detector.h
7330 // Cpp files will be included in the single-header file here
7331 // start catch_stats.cpp
7332
7333 // Statistical analysis tools
7334
7335 #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
7336
7337 #include <cassert>
7338 #include <random>
7339
7340 #if defined(CATCH_CONFIG_USE_ASYNC)
7341 #include <future>
7342 #endif
7343
7344 namespace {
erf_inv(double x)7345 double erf_inv(double x) {
7346 // Code accompanying the article "Approximating the erfinv function" in GPU Computing Gems, Volume 2
7347 double w, p;
7348
7349 w = -log((1.0 - x) * (1.0 + x));
7350
7351 if (w < 6.250000) {
7352 w = w - 3.125000;
7353 p = -3.6444120640178196996e-21;
7354 p = -1.685059138182016589e-19 + p * w;
7355 p = 1.2858480715256400167e-18 + p * w;
7356 p = 1.115787767802518096e-17 + p * w;
7357 p = -1.333171662854620906e-16 + p * w;
7358 p = 2.0972767875968561637e-17 + p * w;
7359 p = 6.6376381343583238325e-15 + p * w;
7360 p = -4.0545662729752068639e-14 + p * w;
7361 p = -8.1519341976054721522e-14 + p * w;
7362 p = 2.6335093153082322977e-12 + p * w;
7363 p = -1.2975133253453532498e-11 + p * w;
7364 p = -5.4154120542946279317e-11 + p * w;
7365 p = 1.051212273321532285e-09 + p * w;
7366 p = -4.1126339803469836976e-09 + p * w;
7367 p = -2.9070369957882005086e-08 + p * w;
7368 p = 4.2347877827932403518e-07 + p * w;
7369 p = -1.3654692000834678645e-06 + p * w;
7370 p = -1.3882523362786468719e-05 + p * w;
7371 p = 0.0001867342080340571352 + p * w;
7372 p = -0.00074070253416626697512 + p * w;
7373 p = -0.0060336708714301490533 + p * w;
7374 p = 0.24015818242558961693 + p * w;
7375 p = 1.6536545626831027356 + p * w;
7376 } else if (w < 16.000000) {
7377 w = sqrt(w) - 3.250000;
7378 p = 2.2137376921775787049e-09;
7379 p = 9.0756561938885390979e-08 + p * w;
7380 p = -2.7517406297064545428e-07 + p * w;
7381 p = 1.8239629214389227755e-08 + p * w;
7382 p = 1.5027403968909827627e-06 + p * w;
7383 p = -4.013867526981545969e-06 + p * w;
7384 p = 2.9234449089955446044e-06 + p * w;
7385 p = 1.2475304481671778723e-05 + p * w;
7386 p = -4.7318229009055733981e-05 + p * w;
7387 p = 6.8284851459573175448e-05 + p * w;
7388 p = 2.4031110387097893999e-05 + p * w;
7389 p = -0.0003550375203628474796 + p * w;
7390 p = 0.00095328937973738049703 + p * w;
7391 p = -0.0016882755560235047313 + p * w;
7392 p = 0.0024914420961078508066 + p * w;
7393 p = -0.0037512085075692412107 + p * w;
7394 p = 0.005370914553590063617 + p * w;
7395 p = 1.0052589676941592334 + p * w;
7396 p = 3.0838856104922207635 + p * w;
7397 } else {
7398 w = sqrt(w) - 5.000000;
7399 p = -2.7109920616438573243e-11;
7400 p = -2.5556418169965252055e-10 + p * w;
7401 p = 1.5076572693500548083e-09 + p * w;
7402 p = -3.7894654401267369937e-09 + p * w;
7403 p = 7.6157012080783393804e-09 + p * w;
7404 p = -1.4960026627149240478e-08 + p * w;
7405 p = 2.9147953450901080826e-08 + p * w;
7406 p = -6.7711997758452339498e-08 + p * w;
7407 p = 2.2900482228026654717e-07 + p * w;
7408 p = -9.9298272942317002539e-07 + p * w;
7409 p = 4.5260625972231537039e-06 + p * w;
7410 p = -1.9681778105531670567e-05 + p * w;
7411 p = 7.5995277030017761139e-05 + p * w;
7412 p = -0.00021503011930044477347 + p * w;
7413 p = -0.00013871931833623122026 + p * w;
7414 p = 1.0103004648645343977 + p * w;
7415 p = 4.8499064014085844221 + p * w;
7416 }
7417 return p * x;
7418 }
7419
standard_deviation(std::vector<double>::iterator first,std::vector<double>::iterator last)7420 double standard_deviation(std::vector<double>::iterator first, std::vector<double>::iterator last) {
7421 auto m = Catch::Benchmark::Detail::mean(first, last);
7422 double variance = std::accumulate(first, last, 0., [m](double a, double b) {
7423 double diff = b - m;
7424 return a + diff * diff;
7425 }) / (last - first);
7426 return std::sqrt(variance);
7427 }
7428
7429 }
7430
7431 namespace Catch {
7432 namespace Benchmark {
7433 namespace Detail {
7434
weighted_average_quantile(int k,int q,std::vector<double>::iterator first,std::vector<double>::iterator last)7435 double weighted_average_quantile(int k, int q, std::vector<double>::iterator first, std::vector<double>::iterator last) {
7436 auto count = last - first;
7437 double idx = (count - 1) * k / static_cast<double>(q);
7438 int j = static_cast<int>(idx);
7439 double g = idx - j;
7440 std::nth_element(first, first + j, last);
7441 auto xj = first[j];
7442 if (g == 0) return xj;
7443
7444 auto xj1 = *std::min_element(first + (j + 1), last);
7445 return xj + g * (xj1 - xj);
7446 }
7447
erfc_inv(double x)7448 double erfc_inv(double x) {
7449 return erf_inv(1.0 - x);
7450 }
7451
normal_quantile(double p)7452 double normal_quantile(double p) {
7453 static const double ROOT_TWO = std::sqrt(2.0);
7454
7455 double result = 0.0;
7456 assert(p >= 0 && p <= 1);
7457 if (p < 0 || p > 1) {
7458 return result;
7459 }
7460
7461 result = -erfc_inv(2.0 * p);
7462 // result *= normal distribution standard deviation (1.0) * sqrt(2)
7463 result *= /*sd * */ ROOT_TWO;
7464 // result += normal disttribution mean (0)
7465 return result;
7466 }
7467
outlier_variance(Estimate<double> mean,Estimate<double> stddev,int n)7468 double outlier_variance(Estimate<double> mean, Estimate<double> stddev, int n) {
7469 double sb = stddev.point;
7470 double mn = mean.point / n;
7471 double mg_min = mn / 2.;
7472 double sg = std::min(mg_min / 4., sb / std::sqrt(n));
7473 double sg2 = sg * sg;
7474 double sb2 = sb * sb;
7475
7476 auto c_max = [n, mn, sb2, sg2](double x) -> double {
7477 double k = mn - x;
7478 double d = k * k;
7479 double nd = n * d;
7480 double k0 = -n * nd;
7481 double k1 = sb2 - n * sg2 + nd;
7482 double det = k1 * k1 - 4 * sg2 * k0;
7483 return (int)(-2. * k0 / (k1 + std::sqrt(det)));
7484 };
7485
7486 auto var_out = [n, sb2, sg2](double c) {
7487 double nc = n - c;
7488 return (nc / n) * (sb2 - nc * sg2);
7489 };
7490
7491 return std::min(var_out(1), var_out(std::min(c_max(0.), c_max(mg_min)))) / sb2;
7492 }
7493
analyse_samples(double confidence_level,int n_resamples,std::vector<double>::iterator first,std::vector<double>::iterator last)7494 bootstrap_analysis analyse_samples(double confidence_level, int n_resamples, std::vector<double>::iterator first, std::vector<double>::iterator last) {
7495 CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS
7496 static std::random_device entropy;
7497 CATCH_INTERNAL_UNSUPPRESS_GLOBALS_WARNINGS
7498
7499 auto n = static_cast<int>(last - first); // seriously, one can't use integral types without hell in C++
7500
7501 auto mean = &Detail::mean<std::vector<double>::iterator>;
7502 auto stddev = &standard_deviation;
7503
7504 #if defined(CATCH_CONFIG_USE_ASYNC)
7505 auto Estimate = [=](double(*f)(std::vector<double>::iterator, std::vector<double>::iterator)) {
7506 auto seed = entropy();
7507 return std::async(std::launch::async, [=] {
7508 std::mt19937 rng(seed);
7509 auto resampled = resample(rng, n_resamples, first, last, f);
7510 return bootstrap(confidence_level, first, last, resampled, f);
7511 });
7512 };
7513
7514 auto mean_future = Estimate(mean);
7515 auto stddev_future = Estimate(stddev);
7516
7517 auto mean_estimate = mean_future.get();
7518 auto stddev_estimate = stddev_future.get();
7519 #else
7520 auto Estimate = [=](double(*f)(std::vector<double>::iterator, std::vector<double>::iterator)) {
7521 auto seed = entropy();
7522 std::mt19937 rng(seed);
7523 auto resampled = resample(rng, n_resamples, first, last, f);
7524 return bootstrap(confidence_level, first, last, resampled, f);
7525 };
7526
7527 auto mean_estimate = Estimate(mean);
7528 auto stddev_estimate = Estimate(stddev);
7529 #endif // CATCH_USE_ASYNC
7530
7531 double outlier_variance = Detail::outlier_variance(mean_estimate, stddev_estimate, n);
7532
7533 return { mean_estimate, stddev_estimate, outlier_variance };
7534 }
7535 } // namespace Detail
7536 } // namespace Benchmark
7537 } // namespace Catch
7538
7539 #endif // CATCH_CONFIG_ENABLE_BENCHMARKING
7540 // end catch_stats.cpp
7541 // start catch_approx.cpp
7542
7543 #include <cmath>
7544 #include <limits>
7545
7546 namespace {
7547
7548 // Performs equivalent check of std::fabs(lhs - rhs) <= margin
7549 // But without the subtraction to allow for INFINITY in comparison
marginComparison(double lhs,double rhs,double margin)7550 bool marginComparison(double lhs, double rhs, double margin) {
7551 return (lhs + margin >= rhs) && (rhs + margin >= lhs);
7552 }
7553
7554 }
7555
7556 namespace Catch {
7557 namespace Detail {
7558
Approx(double value)7559 Approx::Approx ( double value )
7560 : m_epsilon( std::numeric_limits<float>::epsilon()*100 ),
7561 m_margin( 0.0 ),
7562 m_scale( 0.0 ),
7563 m_value( value )
7564 {}
7565
custom()7566 Approx Approx::custom() {
7567 return Approx( 0 );
7568 }
7569
operator -() const7570 Approx Approx::operator-() const {
7571 auto temp(*this);
7572 temp.m_value = -temp.m_value;
7573 return temp;
7574 }
7575
toString() const7576 std::string Approx::toString() const {
7577 ReusableStringStream rss;
7578 rss << "Approx( " << ::Catch::Detail::stringify( m_value ) << " )";
7579 return rss.str();
7580 }
7581
equalityComparisonImpl(const double other) const7582 bool Approx::equalityComparisonImpl(const double other) const {
7583 // First try with fixed margin, then compute margin based on epsilon, scale and Approx's value
7584 // Thanks to Richard Harris for his help refining the scaled margin value
7585 return marginComparison(m_value, other, m_margin) || marginComparison(m_value, other, m_epsilon * (m_scale + std::fabs(m_value)));
7586 }
7587
setMargin(double newMargin)7588 void Approx::setMargin(double newMargin) {
7589 CATCH_ENFORCE(newMargin >= 0,
7590 "Invalid Approx::margin: " << newMargin << '.'
7591 << " Approx::Margin has to be non-negative.");
7592 m_margin = newMargin;
7593 }
7594
setEpsilon(double newEpsilon)7595 void Approx::setEpsilon(double newEpsilon) {
7596 CATCH_ENFORCE(newEpsilon >= 0 && newEpsilon <= 1.0,
7597 "Invalid Approx::epsilon: " << newEpsilon << '.'
7598 << " Approx::epsilon has to be in [0, 1]");
7599 m_epsilon = newEpsilon;
7600 }
7601
7602 } // end namespace Detail
7603
7604 namespace literals {
operator ""_a(long double val)7605 Detail::Approx operator "" _a(long double val) {
7606 return Detail::Approx(val);
7607 }
operator ""_a(unsigned long long val)7608 Detail::Approx operator "" _a(unsigned long long val) {
7609 return Detail::Approx(val);
7610 }
7611 } // end namespace literals
7612
convert(Catch::Detail::Approx const & value)7613 std::string StringMaker<Catch::Detail::Approx>::convert(Catch::Detail::Approx const& value) {
7614 return value.toString();
7615 }
7616
7617 } // end namespace Catch
7618 // end catch_approx.cpp
7619 // start catch_assertionhandler.cpp
7620
7621 // start catch_debugger.h
7622
7623 namespace Catch {
7624 bool isDebuggerActive();
7625 }
7626
7627 #ifdef CATCH_PLATFORM_MAC
7628 #if defined(__x86_64__ )
7629 #define CATCH_TRAP() __asm__("int $3\n" : : ) /* NOLINT */
7630 #else
7631 #define CATCH_TRAP()
7632 #endif
7633
7634 #elif defined(CATCH_PLATFORM_LINUX)
7635 // If we can use inline assembler, do it because this allows us to break
7636 // directly at the location of the failing check instead of breaking inside
7637 // raise() called from it, i.e. one stack frame below.
7638 #if defined(__GNUC__) && (defined(__i386) || defined(__x86_64))
7639 #define CATCH_TRAP() asm volatile ("int $3") /* NOLINT */
7640 #else // Fall back to the generic way.
7641 #include <signal.h>
7642
7643 #define CATCH_TRAP() raise(SIGTRAP)
7644 #endif
7645 #elif defined(_MSC_VER)
7646 #define CATCH_TRAP() __debugbreak()
7647 #elif defined(__MINGW32__)
7648 extern "C" __declspec(dllimport) void __stdcall DebugBreak();
7649 #define CATCH_TRAP() DebugBreak()
7650 #endif
7651
7652 #ifdef CATCH_TRAP
7653 #define CATCH_BREAK_INTO_DEBUGGER() []{ if( Catch::isDebuggerActive() ) { CATCH_TRAP(); } }()
7654 #else
7655 #define CATCH_BREAK_INTO_DEBUGGER() []{}()
7656 #endif
7657
7658 // end catch_debugger.h
7659 // start catch_run_context.h
7660
7661 // start catch_fatal_condition.h
7662
7663 // start catch_windows_h_proxy.h
7664
7665
7666 #if defined(CATCH_PLATFORM_WINDOWS)
7667
7668 #if !defined(NOMINMAX) && !defined(CATCH_CONFIG_NO_NOMINMAX)
7669 # define CATCH_DEFINED_NOMINMAX
7670 # define NOMINMAX
7671 #endif
7672 #if !defined(WIN32_LEAN_AND_MEAN) && !defined(CATCH_CONFIG_NO_WIN32_LEAN_AND_MEAN)
7673 # define CATCH_DEFINED_WIN32_LEAN_AND_MEAN
7674 # define WIN32_LEAN_AND_MEAN
7675 #endif
7676
7677 #ifdef __AFXDLL
7678 #include <AfxWin.h>
7679 #else
7680 #include <windows.h>
7681 #endif
7682
7683 #ifdef CATCH_DEFINED_NOMINMAX
7684 # undef NOMINMAX
7685 #endif
7686 #ifdef CATCH_DEFINED_WIN32_LEAN_AND_MEAN
7687 # undef WIN32_LEAN_AND_MEAN
7688 #endif
7689
7690 #endif // defined(CATCH_PLATFORM_WINDOWS)
7691
7692 // end catch_windows_h_proxy.h
7693 #if defined( CATCH_CONFIG_WINDOWS_SEH )
7694
7695 namespace Catch {
7696
7697 struct FatalConditionHandler {
7698
7699 static LONG CALLBACK handleVectoredException(PEXCEPTION_POINTERS ExceptionInfo);
7700 FatalConditionHandler();
7701 static void reset();
7702 ~FatalConditionHandler();
7703
7704 private:
7705 static bool isSet;
7706 static ULONG guaranteeSize;
7707 static PVOID exceptionHandlerHandle;
7708 };
7709
7710 } // namespace Catch
7711
7712 #elif defined ( CATCH_CONFIG_POSIX_SIGNALS )
7713
7714 #include <signal.h>
7715
7716 namespace Catch {
7717
7718 struct FatalConditionHandler {
7719
7720 static bool isSet;
7721 static struct sigaction oldSigActions[];
7722 static stack_t oldSigStack;
7723 static char altStackMem[];
7724
7725 static void handleSignal( int sig );
7726
7727 FatalConditionHandler();
7728 ~FatalConditionHandler();
7729 static void reset();
7730 };
7731
7732 } // namespace Catch
7733
7734 #else
7735
7736 namespace Catch {
7737 struct FatalConditionHandler {
7738 void reset();
7739 };
7740 }
7741
7742 #endif
7743
7744 // end catch_fatal_condition.h
7745 #include <string>
7746
7747 namespace Catch {
7748
7749 struct IMutableContext;
7750
7751 ///////////////////////////////////////////////////////////////////////////
7752
7753 class RunContext : public IResultCapture, public IRunner {
7754
7755 public:
7756 RunContext( RunContext const& ) = delete;
7757 RunContext& operator =( RunContext const& ) = delete;
7758
7759 explicit RunContext( IConfigPtr const& _config, IStreamingReporterPtr&& reporter );
7760
7761 ~RunContext() override;
7762
7763 void testGroupStarting( std::string const& testSpec, std::size_t groupIndex, std::size_t groupsCount );
7764 void testGroupEnded( std::string const& testSpec, Totals const& totals, std::size_t groupIndex, std::size_t groupsCount );
7765
7766 Totals runTest(TestCase const& testCase);
7767
7768 IConfigPtr config() const;
7769 IStreamingReporter& reporter() const;
7770
7771 public: // IResultCapture
7772
7773 // Assertion handlers
7774 void handleExpr
7775 ( AssertionInfo const& info,
7776 ITransientExpression const& expr,
7777 AssertionReaction& reaction ) override;
7778 void handleMessage
7779 ( AssertionInfo const& info,
7780 ResultWas::OfType resultType,
7781 StringRef const& message,
7782 AssertionReaction& reaction ) override;
7783 void handleUnexpectedExceptionNotThrown
7784 ( AssertionInfo const& info,
7785 AssertionReaction& reaction ) override;
7786 void handleUnexpectedInflightException
7787 ( AssertionInfo const& info,
7788 std::string const& message,
7789 AssertionReaction& reaction ) override;
7790 void handleIncomplete
7791 ( AssertionInfo const& info ) override;
7792 void handleNonExpr
7793 ( AssertionInfo const &info,
7794 ResultWas::OfType resultType,
7795 AssertionReaction &reaction ) override;
7796
7797 bool sectionStarted( SectionInfo const& sectionInfo, Counts& assertions ) override;
7798
7799 void sectionEnded( SectionEndInfo const& endInfo ) override;
7800 void sectionEndedEarly( SectionEndInfo const& endInfo ) override;
7801
7802 auto acquireGeneratorTracker( SourceLineInfo const& lineInfo ) -> IGeneratorTracker& override;
7803
7804 #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
7805 void benchmarkPreparing( std::string const& name ) override;
7806 void benchmarkStarting( BenchmarkInfo const& info ) override;
7807 void benchmarkEnded( BenchmarkStats<> const& stats ) override;
7808 void benchmarkFailed( std::string const& error ) override;
7809 #endif // CATCH_CONFIG_ENABLE_BENCHMARKING
7810
7811 void pushScopedMessage( MessageInfo const& message ) override;
7812 void popScopedMessage( MessageInfo const& message ) override;
7813
7814 void emplaceUnscopedMessage( MessageBuilder const& builder ) override;
7815
7816 std::string getCurrentTestName() const override;
7817
7818 const AssertionResult* getLastResult() const override;
7819
7820 void exceptionEarlyReported() override;
7821
7822 void handleFatalErrorCondition( StringRef message ) override;
7823
7824 bool lastAssertionPassed() override;
7825
7826 void assertionPassed() override;
7827
7828 public:
7829 // !TBD We need to do this another way!
7830 bool aborting() const final;
7831
7832 private:
7833
7834 void runCurrentTest( std::string& redirectedCout, std::string& redirectedCerr );
7835 void invokeActiveTestCase();
7836
7837 void resetAssertionInfo();
7838 bool testForMissingAssertions( Counts& assertions );
7839
7840 void assertionEnded( AssertionResult const& result );
7841 void reportExpr
7842 ( AssertionInfo const &info,
7843 ResultWas::OfType resultType,
7844 ITransientExpression const *expr,
7845 bool negated );
7846
7847 void populateReaction( AssertionReaction& reaction );
7848
7849 private:
7850
7851 void handleUnfinishedSections();
7852
7853 TestRunInfo m_runInfo;
7854 IMutableContext& m_context;
7855 TestCase const* m_activeTestCase = nullptr;
7856 ITracker* m_testCaseTracker = nullptr;
7857 Option<AssertionResult> m_lastResult;
7858
7859 IConfigPtr m_config;
7860 Totals m_totals;
7861 IStreamingReporterPtr m_reporter;
7862 std::vector<MessageInfo> m_messages;
7863 std::vector<ScopedMessage> m_messageScopes; /* Keeps owners of so-called unscoped messages. */
7864 AssertionInfo m_lastAssertionInfo;
7865 std::vector<SectionEndInfo> m_unfinishedSections;
7866 std::vector<ITracker*> m_activeSections;
7867 TrackerContext m_trackerContext;
7868 bool m_lastAssertionPassed = false;
7869 bool m_shouldReportUnexpected = true;
7870 bool m_includeSuccessfulResults;
7871 };
7872
7873 } // end namespace Catch
7874
7875 // end catch_run_context.h
7876 namespace Catch {
7877
7878 namespace {
operator <<(std::ostream & os,ITransientExpression const & expr)7879 auto operator <<( std::ostream& os, ITransientExpression const& expr ) -> std::ostream& {
7880 expr.streamReconstructedExpression( os );
7881 return os;
7882 }
7883 }
7884
LazyExpression(bool isNegated)7885 LazyExpression::LazyExpression( bool isNegated )
7886 : m_isNegated( isNegated )
7887 {}
7888
LazyExpression(LazyExpression const & other)7889 LazyExpression::LazyExpression( LazyExpression const& other ) : m_isNegated( other.m_isNegated ) {}
7890
operator bool() const7891 LazyExpression::operator bool() const {
7892 return m_transientExpression != nullptr;
7893 }
7894
operator <<(std::ostream & os,LazyExpression const & lazyExpr)7895 auto operator << ( std::ostream& os, LazyExpression const& lazyExpr ) -> std::ostream& {
7896 if( lazyExpr.m_isNegated )
7897 os << "!";
7898
7899 if( lazyExpr ) {
7900 if( lazyExpr.m_isNegated && lazyExpr.m_transientExpression->isBinaryExpression() )
7901 os << "(" << *lazyExpr.m_transientExpression << ")";
7902 else
7903 os << *lazyExpr.m_transientExpression;
7904 }
7905 else {
7906 os << "{** error - unchecked empty expression requested **}";
7907 }
7908 return os;
7909 }
7910
AssertionHandler(StringRef const & macroName,SourceLineInfo const & lineInfo,StringRef capturedExpression,ResultDisposition::Flags resultDisposition)7911 AssertionHandler::AssertionHandler
7912 ( StringRef const& macroName,
7913 SourceLineInfo const& lineInfo,
7914 StringRef capturedExpression,
7915 ResultDisposition::Flags resultDisposition )
7916 : m_assertionInfo{ macroName, lineInfo, capturedExpression, resultDisposition },
7917 m_resultCapture( getResultCapture() )
7918 {}
7919
handleExpr(ITransientExpression const & expr)7920 void AssertionHandler::handleExpr( ITransientExpression const& expr ) {
7921 m_resultCapture.handleExpr( m_assertionInfo, expr, m_reaction );
7922 }
handleMessage(ResultWas::OfType resultType,StringRef const & message)7923 void AssertionHandler::handleMessage(ResultWas::OfType resultType, StringRef const& message) {
7924 m_resultCapture.handleMessage( m_assertionInfo, resultType, message, m_reaction );
7925 }
7926
allowThrows() const7927 auto AssertionHandler::allowThrows() const -> bool {
7928 return getCurrentContext().getConfig()->allowThrows();
7929 }
7930
complete()7931 void AssertionHandler::complete() {
7932 setCompleted();
7933 if( m_reaction.shouldDebugBreak ) {
7934
7935 // If you find your debugger stopping you here then go one level up on the
7936 // call-stack for the code that caused it (typically a failed assertion)
7937
7938 // (To go back to the test and change execution, jump over the throw, next)
7939 CATCH_BREAK_INTO_DEBUGGER();
7940 }
7941 if (m_reaction.shouldThrow) {
7942 #if !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
7943 throw Catch::TestFailureException();
7944 #else
7945 CATCH_ERROR( "Test failure requires aborting test!" );
7946 #endif
7947 }
7948 }
setCompleted()7949 void AssertionHandler::setCompleted() {
7950 m_completed = true;
7951 }
7952
handleUnexpectedInflightException()7953 void AssertionHandler::handleUnexpectedInflightException() {
7954 m_resultCapture.handleUnexpectedInflightException( m_assertionInfo, Catch::translateActiveException(), m_reaction );
7955 }
7956
handleExceptionThrownAsExpected()7957 void AssertionHandler::handleExceptionThrownAsExpected() {
7958 m_resultCapture.handleNonExpr(m_assertionInfo, ResultWas::Ok, m_reaction);
7959 }
handleExceptionNotThrownAsExpected()7960 void AssertionHandler::handleExceptionNotThrownAsExpected() {
7961 m_resultCapture.handleNonExpr(m_assertionInfo, ResultWas::Ok, m_reaction);
7962 }
7963
handleUnexpectedExceptionNotThrown()7964 void AssertionHandler::handleUnexpectedExceptionNotThrown() {
7965 m_resultCapture.handleUnexpectedExceptionNotThrown( m_assertionInfo, m_reaction );
7966 }
7967
handleThrowingCallSkipped()7968 void AssertionHandler::handleThrowingCallSkipped() {
7969 m_resultCapture.handleNonExpr(m_assertionInfo, ResultWas::Ok, m_reaction);
7970 }
7971
7972 // This is the overload that takes a string and infers the Equals matcher from it
7973 // The more general overload, that takes any string matcher, is in catch_capture_matchers.cpp
handleExceptionMatchExpr(AssertionHandler & handler,std::string const & str,StringRef const & matcherString)7974 void handleExceptionMatchExpr( AssertionHandler& handler, std::string const& str, StringRef const& matcherString ) {
7975 handleExceptionMatchExpr( handler, Matchers::Equals( str ), matcherString );
7976 }
7977
7978 } // namespace Catch
7979 // end catch_assertionhandler.cpp
7980 // start catch_assertionresult.cpp
7981
7982 namespace Catch {
AssertionResultData(ResultWas::OfType _resultType,LazyExpression const & _lazyExpression)7983 AssertionResultData::AssertionResultData(ResultWas::OfType _resultType, LazyExpression const & _lazyExpression):
7984 lazyExpression(_lazyExpression),
7985 resultType(_resultType) {}
7986
reconstructExpression() const7987 std::string AssertionResultData::reconstructExpression() const {
7988
7989 if( reconstructedExpression.empty() ) {
7990 if( lazyExpression ) {
7991 ReusableStringStream rss;
7992 rss << lazyExpression;
7993 reconstructedExpression = rss.str();
7994 }
7995 }
7996 return reconstructedExpression;
7997 }
7998
AssertionResult(AssertionInfo const & info,AssertionResultData const & data)7999 AssertionResult::AssertionResult( AssertionInfo const& info, AssertionResultData const& data )
8000 : m_info( info ),
8001 m_resultData( data )
8002 {}
8003
8004 // Result was a success
succeeded() const8005 bool AssertionResult::succeeded() const {
8006 return Catch::isOk( m_resultData.resultType );
8007 }
8008
8009 // Result was a success, or failure is suppressed
isOk() const8010 bool AssertionResult::isOk() const {
8011 return Catch::isOk( m_resultData.resultType ) || shouldSuppressFailure( m_info.resultDisposition );
8012 }
8013
getResultType() const8014 ResultWas::OfType AssertionResult::getResultType() const {
8015 return m_resultData.resultType;
8016 }
8017
hasExpression() const8018 bool AssertionResult::hasExpression() const {
8019 return m_info.capturedExpression[0] != 0;
8020 }
8021
hasMessage() const8022 bool AssertionResult::hasMessage() const {
8023 return !m_resultData.message.empty();
8024 }
8025
getExpression() const8026 std::string AssertionResult::getExpression() const {
8027 if( isFalseTest( m_info.resultDisposition ) )
8028 return "!(" + m_info.capturedExpression + ")";
8029 else
8030 return m_info.capturedExpression;
8031 }
8032
getExpressionInMacro() const8033 std::string AssertionResult::getExpressionInMacro() const {
8034 std::string expr;
8035 if( m_info.macroName[0] == 0 )
8036 expr = m_info.capturedExpression;
8037 else {
8038 expr.reserve( m_info.macroName.size() + m_info.capturedExpression.size() + 4 );
8039 expr += m_info.macroName;
8040 expr += "( ";
8041 expr += m_info.capturedExpression;
8042 expr += " )";
8043 }
8044 return expr;
8045 }
8046
hasExpandedExpression() const8047 bool AssertionResult::hasExpandedExpression() const {
8048 return hasExpression() && getExpandedExpression() != getExpression();
8049 }
8050
getExpandedExpression() const8051 std::string AssertionResult::getExpandedExpression() const {
8052 std::string expr = m_resultData.reconstructExpression();
8053 return expr.empty()
8054 ? getExpression()
8055 : expr;
8056 }
8057
getMessage() const8058 std::string AssertionResult::getMessage() const {
8059 return m_resultData.message;
8060 }
getSourceInfo() const8061 SourceLineInfo AssertionResult::getSourceInfo() const {
8062 return m_info.lineInfo;
8063 }
8064
getTestMacroName() const8065 StringRef AssertionResult::getTestMacroName() const {
8066 return m_info.macroName;
8067 }
8068
8069 } // end namespace Catch
8070 // end catch_assertionresult.cpp
8071 // start catch_capture_matchers.cpp
8072
8073 namespace Catch {
8074
8075 using StringMatcher = Matchers::Impl::MatcherBase<std::string>;
8076
8077 // This is the general overload that takes a any string matcher
8078 // There is another overload, in catch_assertionhandler.h/.cpp, that only takes a string and infers
8079 // the Equals matcher (so the header does not mention matchers)
handleExceptionMatchExpr(AssertionHandler & handler,StringMatcher const & matcher,StringRef const & matcherString)8080 void handleExceptionMatchExpr( AssertionHandler& handler, StringMatcher const& matcher, StringRef const& matcherString ) {
8081 std::string exceptionMessage = Catch::translateActiveException();
8082 MatchExpr<std::string, StringMatcher const&> expr( exceptionMessage, matcher, matcherString );
8083 handler.handleExpr( expr );
8084 }
8085
8086 } // namespace Catch
8087 // end catch_capture_matchers.cpp
8088 // start catch_commandline.cpp
8089
8090 // start catch_commandline.h
8091
8092 // start catch_clara.h
8093
8094 // Use Catch's value for console width (store Clara's off to the side, if present)
8095 #ifdef CLARA_CONFIG_CONSOLE_WIDTH
8096 #define CATCH_TEMP_CLARA_CONFIG_CONSOLE_WIDTH CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH
8097 #undef CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH
8098 #endif
8099 #define CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH CATCH_CONFIG_CONSOLE_WIDTH-1
8100
8101 #ifdef __clang__
8102 #pragma clang diagnostic push
8103 #pragma clang diagnostic ignored "-Wweak-vtables"
8104 #pragma clang diagnostic ignored "-Wexit-time-destructors"
8105 #pragma clang diagnostic ignored "-Wshadow"
8106 #endif
8107
8108 // start clara.hpp
8109 // Copyright 2017 Two Blue Cubes Ltd. All rights reserved.
8110 //
8111 // Distributed under the Boost Software License, Version 1.0. (See accompanying
8112 // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
8113 //
8114 // See https://github.com/philsquared/Clara for more details
8115
8116 // Clara v1.1.5
8117
8118
8119 #ifndef CATCH_CLARA_CONFIG_CONSOLE_WIDTH
8120 #define CATCH_CLARA_CONFIG_CONSOLE_WIDTH 80
8121 #endif
8122
8123 #ifndef CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH
8124 #define CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH CATCH_CLARA_CONFIG_CONSOLE_WIDTH
8125 #endif
8126
8127 #ifndef CLARA_CONFIG_OPTIONAL_TYPE
8128 #ifdef __has_include
8129 #if __has_include(<optional>) && __cplusplus >= 201703L
8130 #include <optional>
8131 #define CLARA_CONFIG_OPTIONAL_TYPE std::optional
8132 #endif
8133 #endif
8134 #endif
8135
8136 // ----------- #included from clara_textflow.hpp -----------
8137
8138 // TextFlowCpp
8139 //
8140 // A single-header library for wrapping and laying out basic text, by Phil Nash
8141 //
8142 // Distributed under the Boost Software License, Version 1.0. (See accompanying
8143 // file LICENSE.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
8144 //
8145 // This project is hosted at https://github.com/philsquared/textflowcpp
8146
8147
8148 #include <cassert>
8149 #include <ostream>
8150 #include <sstream>
8151 #include <vector>
8152
8153 #ifndef CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH
8154 #define CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH 80
8155 #endif
8156
8157 namespace Catch {
8158 namespace clara {
8159 namespace TextFlow {
8160
isWhitespace(char c)8161 inline auto isWhitespace(char c) -> bool {
8162 static std::string chars = " \t\n\r";
8163 return chars.find(c) != std::string::npos;
8164 }
isBreakableBefore(char c)8165 inline auto isBreakableBefore(char c) -> bool {
8166 static std::string chars = "[({<|";
8167 return chars.find(c) != std::string::npos;
8168 }
isBreakableAfter(char c)8169 inline auto isBreakableAfter(char c) -> bool {
8170 static std::string chars = "])}>.,:;*+-=&/\\";
8171 return chars.find(c) != std::string::npos;
8172 }
8173
8174 class Columns;
8175
8176 class Column {
8177 std::vector<std::string> m_strings;
8178 size_t m_width = CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH;
8179 size_t m_indent = 0;
8180 size_t m_initialIndent = std::string::npos;
8181
8182 public:
8183 class iterator {
8184 friend Column;
8185
8186 Column const& m_column;
8187 size_t m_stringIndex = 0;
8188 size_t m_pos = 0;
8189
8190 size_t m_len = 0;
8191 size_t m_end = 0;
8192 bool m_suffix = false;
8193
iterator(Column const & column,size_t stringIndex)8194 iterator(Column const& column, size_t stringIndex)
8195 : m_column(column),
8196 m_stringIndex(stringIndex) {}
8197
line() const8198 auto line() const -> std::string const& { return m_column.m_strings[m_stringIndex]; }
8199
isBoundary(size_t at) const8200 auto isBoundary(size_t at) const -> bool {
8201 assert(at > 0);
8202 assert(at <= line().size());
8203
8204 return at == line().size() ||
8205 (isWhitespace(line()[at]) && !isWhitespace(line()[at - 1])) ||
8206 isBreakableBefore(line()[at]) ||
8207 isBreakableAfter(line()[at - 1]);
8208 }
8209
calcLength()8210 void calcLength() {
8211 assert(m_stringIndex < m_column.m_strings.size());
8212
8213 m_suffix = false;
8214 auto width = m_column.m_width - indent();
8215 m_end = m_pos;
8216 if (line()[m_pos] == '\n') {
8217 ++m_end;
8218 }
8219 while (m_end < line().size() && line()[m_end] != '\n')
8220 ++m_end;
8221
8222 if (m_end < m_pos + width) {
8223 m_len = m_end - m_pos;
8224 } else {
8225 size_t len = width;
8226 while (len > 0 && !isBoundary(m_pos + len))
8227 --len;
8228 while (len > 0 && isWhitespace(line()[m_pos + len - 1]))
8229 --len;
8230
8231 if (len > 0) {
8232 m_len = len;
8233 } else {
8234 m_suffix = true;
8235 m_len = width - 1;
8236 }
8237 }
8238 }
8239
indent() const8240 auto indent() const -> size_t {
8241 auto initial = m_pos == 0 && m_stringIndex == 0 ? m_column.m_initialIndent : std::string::npos;
8242 return initial == std::string::npos ? m_column.m_indent : initial;
8243 }
8244
addIndentAndSuffix(std::string const & plain) const8245 auto addIndentAndSuffix(std::string const &plain) const -> std::string {
8246 return std::string(indent(), ' ') + (m_suffix ? plain + "-" : plain);
8247 }
8248
8249 public:
8250 using difference_type = std::ptrdiff_t;
8251 using value_type = std::string;
8252 using pointer = value_type * ;
8253 using reference = value_type & ;
8254 using iterator_category = std::forward_iterator_tag;
8255
iterator(Column const & column)8256 explicit iterator(Column const& column) : m_column(column) {
8257 assert(m_column.m_width > m_column.m_indent);
8258 assert(m_column.m_initialIndent == std::string::npos || m_column.m_width > m_column.m_initialIndent);
8259 calcLength();
8260 if (m_len == 0)
8261 m_stringIndex++; // Empty string
8262 }
8263
operator *() const8264 auto operator *() const -> std::string {
8265 assert(m_stringIndex < m_column.m_strings.size());
8266 assert(m_pos <= m_end);
8267 return addIndentAndSuffix(line().substr(m_pos, m_len));
8268 }
8269
operator ++()8270 auto operator ++() -> iterator& {
8271 m_pos += m_len;
8272 if (m_pos < line().size() && line()[m_pos] == '\n')
8273 m_pos += 1;
8274 else
8275 while (m_pos < line().size() && isWhitespace(line()[m_pos]))
8276 ++m_pos;
8277
8278 if (m_pos == line().size()) {
8279 m_pos = 0;
8280 ++m_stringIndex;
8281 }
8282 if (m_stringIndex < m_column.m_strings.size())
8283 calcLength();
8284 return *this;
8285 }
operator ++(int)8286 auto operator ++(int) -> iterator {
8287 iterator prev(*this);
8288 operator++();
8289 return prev;
8290 }
8291
operator ==(iterator const & other) const8292 auto operator ==(iterator const& other) const -> bool {
8293 return
8294 m_pos == other.m_pos &&
8295 m_stringIndex == other.m_stringIndex &&
8296 &m_column == &other.m_column;
8297 }
operator !=(iterator const & other) const8298 auto operator !=(iterator const& other) const -> bool {
8299 return !operator==(other);
8300 }
8301 };
8302 using const_iterator = iterator;
8303
Column(std::string const & text)8304 explicit Column(std::string const& text) { m_strings.push_back(text); }
8305
width(size_t newWidth)8306 auto width(size_t newWidth) -> Column& {
8307 assert(newWidth > 0);
8308 m_width = newWidth;
8309 return *this;
8310 }
indent(size_t newIndent)8311 auto indent(size_t newIndent) -> Column& {
8312 m_indent = newIndent;
8313 return *this;
8314 }
initialIndent(size_t newIndent)8315 auto initialIndent(size_t newIndent) -> Column& {
8316 m_initialIndent = newIndent;
8317 return *this;
8318 }
8319
width() const8320 auto width() const -> size_t { return m_width; }
begin() const8321 auto begin() const -> iterator { return iterator(*this); }
end() const8322 auto end() const -> iterator { return { *this, m_strings.size() }; }
8323
operator <<(std::ostream & os,Column const & col)8324 inline friend std::ostream& operator << (std::ostream& os, Column const& col) {
8325 bool first = true;
8326 for (auto line : col) {
8327 if (first)
8328 first = false;
8329 else
8330 os << "\n";
8331 os << line;
8332 }
8333 return os;
8334 }
8335
8336 auto operator + (Column const& other)->Columns;
8337
toString() const8338 auto toString() const -> std::string {
8339 std::ostringstream oss;
8340 oss << *this;
8341 return oss.str();
8342 }
8343 };
8344
8345 class Spacer : public Column {
8346
8347 public:
Spacer(size_t spaceWidth)8348 explicit Spacer(size_t spaceWidth) : Column("") {
8349 width(spaceWidth);
8350 }
8351 };
8352
8353 class Columns {
8354 std::vector<Column> m_columns;
8355
8356 public:
8357
8358 class iterator {
8359 friend Columns;
8360 struct EndTag {};
8361
8362 std::vector<Column> const& m_columns;
8363 std::vector<Column::iterator> m_iterators;
8364 size_t m_activeIterators;
8365
iterator(Columns const & columns,EndTag)8366 iterator(Columns const& columns, EndTag)
8367 : m_columns(columns.m_columns),
8368 m_activeIterators(0) {
8369 m_iterators.reserve(m_columns.size());
8370
8371 for (auto const& col : m_columns)
8372 m_iterators.push_back(col.end());
8373 }
8374
8375 public:
8376 using difference_type = std::ptrdiff_t;
8377 using value_type = std::string;
8378 using pointer = value_type * ;
8379 using reference = value_type & ;
8380 using iterator_category = std::forward_iterator_tag;
8381
iterator(Columns const & columns)8382 explicit iterator(Columns const& columns)
8383 : m_columns(columns.m_columns),
8384 m_activeIterators(m_columns.size()) {
8385 m_iterators.reserve(m_columns.size());
8386
8387 for (auto const& col : m_columns)
8388 m_iterators.push_back(col.begin());
8389 }
8390
operator ==(iterator const & other) const8391 auto operator ==(iterator const& other) const -> bool {
8392 return m_iterators == other.m_iterators;
8393 }
operator !=(iterator const & other) const8394 auto operator !=(iterator const& other) const -> bool {
8395 return m_iterators != other.m_iterators;
8396 }
operator *() const8397 auto operator *() const -> std::string {
8398 std::string row, padding;
8399
8400 for (size_t i = 0; i < m_columns.size(); ++i) {
8401 auto width = m_columns[i].width();
8402 if (m_iterators[i] != m_columns[i].end()) {
8403 std::string col = *m_iterators[i];
8404 row += padding + col;
8405 if (col.size() < width)
8406 padding = std::string(width - col.size(), ' ');
8407 else
8408 padding = "";
8409 } else {
8410 padding += std::string(width, ' ');
8411 }
8412 }
8413 return row;
8414 }
operator ++()8415 auto operator ++() -> iterator& {
8416 for (size_t i = 0; i < m_columns.size(); ++i) {
8417 if (m_iterators[i] != m_columns[i].end())
8418 ++m_iterators[i];
8419 }
8420 return *this;
8421 }
operator ++(int)8422 auto operator ++(int) -> iterator {
8423 iterator prev(*this);
8424 operator++();
8425 return prev;
8426 }
8427 };
8428 using const_iterator = iterator;
8429
begin() const8430 auto begin() const -> iterator { return iterator(*this); }
end() const8431 auto end() const -> iterator { return { *this, iterator::EndTag() }; }
8432
operator +=(Column const & col)8433 auto operator += (Column const& col) -> Columns& {
8434 m_columns.push_back(col);
8435 return *this;
8436 }
operator +(Column const & col)8437 auto operator + (Column const& col) -> Columns {
8438 Columns combined = *this;
8439 combined += col;
8440 return combined;
8441 }
8442
operator <<(std::ostream & os,Columns const & cols)8443 inline friend std::ostream& operator << (std::ostream& os, Columns const& cols) {
8444
8445 bool first = true;
8446 for (auto line : cols) {
8447 if (first)
8448 first = false;
8449 else
8450 os << "\n";
8451 os << line;
8452 }
8453 return os;
8454 }
8455
toString() const8456 auto toString() const -> std::string {
8457 std::ostringstream oss;
8458 oss << *this;
8459 return oss.str();
8460 }
8461 };
8462
operator +(Column const & other)8463 inline auto Column::operator + (Column const& other) -> Columns {
8464 Columns cols;
8465 cols += *this;
8466 cols += other;
8467 return cols;
8468 }
8469 }
8470
8471 }
8472 }
8473
8474 // ----------- end of #include from clara_textflow.hpp -----------
8475 // ........... back in clara.hpp
8476
8477 #include <cctype>
8478 #include <string>
8479 #include <memory>
8480 #include <set>
8481 #include <algorithm>
8482
8483 #if !defined(CATCH_PLATFORM_WINDOWS) && ( defined(WIN32) || defined(__WIN32__) || defined(_WIN32) || defined(_MSC_VER) )
8484 #define CATCH_PLATFORM_WINDOWS
8485 #endif
8486
8487 namespace Catch { namespace clara {
8488 namespace detail {
8489
8490 // Traits for extracting arg and return type of lambdas (for single argument lambdas)
8491 template<typename L>
8492 struct UnaryLambdaTraits : UnaryLambdaTraits<decltype( &L::operator() )> {};
8493
8494 template<typename ClassT, typename ReturnT, typename... Args>
8495 struct UnaryLambdaTraits<ReturnT( ClassT::* )( Args... ) const> {
8496 static const bool isValid = false;
8497 };
8498
8499 template<typename ClassT, typename ReturnT, typename ArgT>
8500 struct UnaryLambdaTraits<ReturnT( ClassT::* )( ArgT ) const> {
8501 static const bool isValid = true;
8502 using ArgType = typename std::remove_const<typename std::remove_reference<ArgT>::type>::type;
8503 using ReturnType = ReturnT;
8504 };
8505
8506 class TokenStream;
8507
8508 // Transport for raw args (copied from main args, or supplied via init list for testing)
8509 class Args {
8510 friend TokenStream;
8511 std::string m_exeName;
8512 std::vector<std::string> m_args;
8513
8514 public:
Args(int argc,char const * const * argv)8515 Args( int argc, char const* const* argv )
8516 : m_exeName(argv[0]),
8517 m_args(argv + 1, argv + argc) {}
8518
Args(std::initializer_list<std::string> args)8519 Args( std::initializer_list<std::string> args )
8520 : m_exeName( *args.begin() ),
8521 m_args( args.begin()+1, args.end() )
8522 {}
8523
exeName() const8524 auto exeName() const -> std::string {
8525 return m_exeName;
8526 }
8527 };
8528
8529 // Wraps a token coming from a token stream. These may not directly correspond to strings as a single string
8530 // may encode an option + its argument if the : or = form is used
8531 enum class TokenType {
8532 Option, Argument
8533 };
8534 struct Token {
8535 TokenType type;
8536 std::string token;
8537 };
8538
isOptPrefix(char c)8539 inline auto isOptPrefix( char c ) -> bool {
8540 return c == '-'
8541 #ifdef CATCH_PLATFORM_WINDOWS
8542 || c == '/'
8543 #endif
8544 ;
8545 }
8546
8547 // Abstracts iterators into args as a stream of tokens, with option arguments uniformly handled
8548 class TokenStream {
8549 using Iterator = std::vector<std::string>::const_iterator;
8550 Iterator it;
8551 Iterator itEnd;
8552 std::vector<Token> m_tokenBuffer;
8553
loadBuffer()8554 void loadBuffer() {
8555 m_tokenBuffer.resize( 0 );
8556
8557 // Skip any empty strings
8558 while( it != itEnd && it->empty() )
8559 ++it;
8560
8561 if( it != itEnd ) {
8562 auto const &next = *it;
8563 if( isOptPrefix( next[0] ) ) {
8564 auto delimiterPos = next.find_first_of( " :=" );
8565 if( delimiterPos != std::string::npos ) {
8566 m_tokenBuffer.push_back( { TokenType::Option, next.substr( 0, delimiterPos ) } );
8567 m_tokenBuffer.push_back( { TokenType::Argument, next.substr( delimiterPos + 1 ) } );
8568 } else {
8569 if( next[1] != '-' && next.size() > 2 ) {
8570 std::string opt = "- ";
8571 for( size_t i = 1; i < next.size(); ++i ) {
8572 opt[1] = next[i];
8573 m_tokenBuffer.push_back( { TokenType::Option, opt } );
8574 }
8575 } else {
8576 m_tokenBuffer.push_back( { TokenType::Option, next } );
8577 }
8578 }
8579 } else {
8580 m_tokenBuffer.push_back( { TokenType::Argument, next } );
8581 }
8582 }
8583 }
8584
8585 public:
TokenStream(Args const & args)8586 explicit TokenStream( Args const &args ) : TokenStream( args.m_args.begin(), args.m_args.end() ) {}
8587
TokenStream(Iterator it,Iterator itEnd)8588 TokenStream( Iterator it, Iterator itEnd ) : it( it ), itEnd( itEnd ) {
8589 loadBuffer();
8590 }
8591
operator bool() const8592 explicit operator bool() const {
8593 return !m_tokenBuffer.empty() || it != itEnd;
8594 }
8595
count() const8596 auto count() const -> size_t { return m_tokenBuffer.size() + (itEnd - it); }
8597
operator *() const8598 auto operator*() const -> Token {
8599 assert( !m_tokenBuffer.empty() );
8600 return m_tokenBuffer.front();
8601 }
8602
operator ->() const8603 auto operator->() const -> Token const * {
8604 assert( !m_tokenBuffer.empty() );
8605 return &m_tokenBuffer.front();
8606 }
8607
operator ++()8608 auto operator++() -> TokenStream & {
8609 if( m_tokenBuffer.size() >= 2 ) {
8610 m_tokenBuffer.erase( m_tokenBuffer.begin() );
8611 } else {
8612 if( it != itEnd )
8613 ++it;
8614 loadBuffer();
8615 }
8616 return *this;
8617 }
8618 };
8619
8620 class ResultBase {
8621 public:
8622 enum Type {
8623 Ok, LogicError, RuntimeError
8624 };
8625
8626 protected:
ResultBase(Type type)8627 ResultBase( Type type ) : m_type( type ) {}
8628 virtual ~ResultBase() = default;
8629
8630 virtual void enforceOk() const = 0;
8631
8632 Type m_type;
8633 };
8634
8635 template<typename T>
8636 class ResultValueBase : public ResultBase {
8637 public:
value() const8638 auto value() const -> T const & {
8639 enforceOk();
8640 return m_value;
8641 }
8642
8643 protected:
ResultValueBase(Type type)8644 ResultValueBase( Type type ) : ResultBase( type ) {}
8645
ResultValueBase(ResultValueBase const & other)8646 ResultValueBase( ResultValueBase const &other ) : ResultBase( other ) {
8647 if( m_type == ResultBase::Ok )
8648 new( &m_value ) T( other.m_value );
8649 }
8650
ResultValueBase(Type,T const & value)8651 ResultValueBase( Type, T const &value ) : ResultBase( Ok ) {
8652 new( &m_value ) T( value );
8653 }
8654
operator =(ResultValueBase const & other)8655 auto operator=( ResultValueBase const &other ) -> ResultValueBase & {
8656 if( m_type == ResultBase::Ok )
8657 m_value.~T();
8658 ResultBase::operator=(other);
8659 if( m_type == ResultBase::Ok )
8660 new( &m_value ) T( other.m_value );
8661 return *this;
8662 }
8663
~ResultValueBase()8664 ~ResultValueBase() override {
8665 if( m_type == Ok )
8666 m_value.~T();
8667 }
8668
8669 union {
8670 T m_value;
8671 };
8672 };
8673
8674 template<>
8675 class ResultValueBase<void> : public ResultBase {
8676 protected:
8677 using ResultBase::ResultBase;
8678 };
8679
8680 template<typename T = void>
8681 class BasicResult : public ResultValueBase<T> {
8682 public:
8683 template<typename U>
BasicResult(BasicResult<U> const & other)8684 explicit BasicResult( BasicResult<U> const &other )
8685 : ResultValueBase<T>( other.type() ),
8686 m_errorMessage( other.errorMessage() )
8687 {
8688 assert( type() != ResultBase::Ok );
8689 }
8690
8691 template<typename U>
ok(U const & value)8692 static auto ok( U const &value ) -> BasicResult { return { ResultBase::Ok, value }; }
ok()8693 static auto ok() -> BasicResult { return { ResultBase::Ok }; }
logicError(std::string const & message)8694 static auto logicError( std::string const &message ) -> BasicResult { return { ResultBase::LogicError, message }; }
runtimeError(std::string const & message)8695 static auto runtimeError( std::string const &message ) -> BasicResult { return { ResultBase::RuntimeError, message }; }
8696
operator bool() const8697 explicit operator bool() const { return m_type == ResultBase::Ok; }
type() const8698 auto type() const -> ResultBase::Type { return m_type; }
errorMessage() const8699 auto errorMessage() const -> std::string { return m_errorMessage; }
8700
8701 protected:
enforceOk() const8702 void enforceOk() const override {
8703
8704 // Errors shouldn't reach this point, but if they do
8705 // the actual error message will be in m_errorMessage
8706 assert( m_type != ResultBase::LogicError );
8707 assert( m_type != ResultBase::RuntimeError );
8708 if( m_type != ResultBase::Ok )
8709 std::abort();
8710 }
8711
8712 std::string m_errorMessage; // Only populated if resultType is an error
8713
BasicResult(ResultBase::Type type,std::string const & message)8714 BasicResult( ResultBase::Type type, std::string const &message )
8715 : ResultValueBase<T>(type),
8716 m_errorMessage(message)
8717 {
8718 assert( m_type != ResultBase::Ok );
8719 }
8720
8721 using ResultValueBase<T>::ResultValueBase;
8722 using ResultBase::m_type;
8723 };
8724
8725 enum class ParseResultType {
8726 Matched, NoMatch, ShortCircuitAll, ShortCircuitSame
8727 };
8728
8729 class ParseState {
8730 public:
8731
ParseState(ParseResultType type,TokenStream const & remainingTokens)8732 ParseState( ParseResultType type, TokenStream const &remainingTokens )
8733 : m_type(type),
8734 m_remainingTokens( remainingTokens )
8735 {}
8736
type() const8737 auto type() const -> ParseResultType { return m_type; }
remainingTokens() const8738 auto remainingTokens() const -> TokenStream { return m_remainingTokens; }
8739
8740 private:
8741 ParseResultType m_type;
8742 TokenStream m_remainingTokens;
8743 };
8744
8745 using Result = BasicResult<void>;
8746 using ParserResult = BasicResult<ParseResultType>;
8747 using InternalParseResult = BasicResult<ParseState>;
8748
8749 struct HelpColumns {
8750 std::string left;
8751 std::string right;
8752 };
8753
8754 template<typename T>
convertInto(std::string const & source,T & target)8755 inline auto convertInto( std::string const &source, T& target ) -> ParserResult {
8756 std::stringstream ss;
8757 ss << source;
8758 ss >> target;
8759 if( ss.fail() )
8760 return ParserResult::runtimeError( "Unable to convert '" + source + "' to destination type" );
8761 else
8762 return ParserResult::ok( ParseResultType::Matched );
8763 }
convertInto(std::string const & source,std::string & target)8764 inline auto convertInto( std::string const &source, std::string& target ) -> ParserResult {
8765 target = source;
8766 return ParserResult::ok( ParseResultType::Matched );
8767 }
convertInto(std::string const & source,bool & target)8768 inline auto convertInto( std::string const &source, bool &target ) -> ParserResult {
8769 std::string srcLC = source;
8770 std::transform( srcLC.begin(), srcLC.end(), srcLC.begin(), []( char c ) { return static_cast<char>( std::tolower(c) ); } );
8771 if (srcLC == "y" || srcLC == "1" || srcLC == "true" || srcLC == "yes" || srcLC == "on")
8772 target = true;
8773 else if (srcLC == "n" || srcLC == "0" || srcLC == "false" || srcLC == "no" || srcLC == "off")
8774 target = false;
8775 else
8776 return ParserResult::runtimeError( "Expected a boolean value but did not recognise: '" + source + "'" );
8777 return ParserResult::ok( ParseResultType::Matched );
8778 }
8779 #ifdef CLARA_CONFIG_OPTIONAL_TYPE
8780 template<typename T>
convertInto(std::string const & source,CLARA_CONFIG_OPTIONAL_TYPE<T> & target)8781 inline auto convertInto( std::string const &source, CLARA_CONFIG_OPTIONAL_TYPE<T>& target ) -> ParserResult {
8782 T temp;
8783 auto result = convertInto( source, temp );
8784 if( result )
8785 target = std::move(temp);
8786 return result;
8787 }
8788 #endif // CLARA_CONFIG_OPTIONAL_TYPE
8789
8790 struct NonCopyable {
8791 NonCopyable() = default;
8792 NonCopyable( NonCopyable const & ) = delete;
8793 NonCopyable( NonCopyable && ) = delete;
8794 NonCopyable &operator=( NonCopyable const & ) = delete;
8795 NonCopyable &operator=( NonCopyable && ) = delete;
8796 };
8797
8798 struct BoundRef : NonCopyable {
8799 virtual ~BoundRef() = default;
isContainerCatch::clara::detail::BoundRef8800 virtual auto isContainer() const -> bool { return false; }
isFlagCatch::clara::detail::BoundRef8801 virtual auto isFlag() const -> bool { return false; }
8802 };
8803 struct BoundValueRefBase : BoundRef {
8804 virtual auto setValue( std::string const &arg ) -> ParserResult = 0;
8805 };
8806 struct BoundFlagRefBase : BoundRef {
8807 virtual auto setFlag( bool flag ) -> ParserResult = 0;
isFlagCatch::clara::detail::BoundFlagRefBase8808 virtual auto isFlag() const -> bool { return true; }
8809 };
8810
8811 template<typename T>
8812 struct BoundValueRef : BoundValueRefBase {
8813 T &m_ref;
8814
BoundValueRefCatch::clara::detail::BoundValueRef8815 explicit BoundValueRef( T &ref ) : m_ref( ref ) {}
8816
setValueCatch::clara::detail::BoundValueRef8817 auto setValue( std::string const &arg ) -> ParserResult override {
8818 return convertInto( arg, m_ref );
8819 }
8820 };
8821
8822 template<typename T>
8823 struct BoundValueRef<std::vector<T>> : BoundValueRefBase {
8824 std::vector<T> &m_ref;
8825
BoundValueRefCatch::clara::detail::BoundValueRef8826 explicit BoundValueRef( std::vector<T> &ref ) : m_ref( ref ) {}
8827
isContainerCatch::clara::detail::BoundValueRef8828 auto isContainer() const -> bool override { return true; }
8829
setValueCatch::clara::detail::BoundValueRef8830 auto setValue( std::string const &arg ) -> ParserResult override {
8831 T temp;
8832 auto result = convertInto( arg, temp );
8833 if( result )
8834 m_ref.push_back( temp );
8835 return result;
8836 }
8837 };
8838
8839 struct BoundFlagRef : BoundFlagRefBase {
8840 bool &m_ref;
8841
BoundFlagRefCatch::clara::detail::BoundFlagRef8842 explicit BoundFlagRef( bool &ref ) : m_ref( ref ) {}
8843
setFlagCatch::clara::detail::BoundFlagRef8844 auto setFlag( bool flag ) -> ParserResult override {
8845 m_ref = flag;
8846 return ParserResult::ok( ParseResultType::Matched );
8847 }
8848 };
8849
8850 template<typename ReturnType>
8851 struct LambdaInvoker {
8852 static_assert( std::is_same<ReturnType, ParserResult>::value, "Lambda must return void or clara::ParserResult" );
8853
8854 template<typename L, typename ArgType>
invokeCatch::clara::detail::LambdaInvoker8855 static auto invoke( L const &lambda, ArgType const &arg ) -> ParserResult {
8856 return lambda( arg );
8857 }
8858 };
8859
8860 template<>
8861 struct LambdaInvoker<void> {
8862 template<typename L, typename ArgType>
invokeCatch::clara::detail::LambdaInvoker8863 static auto invoke( L const &lambda, ArgType const &arg ) -> ParserResult {
8864 lambda( arg );
8865 return ParserResult::ok( ParseResultType::Matched );
8866 }
8867 };
8868
8869 template<typename ArgType, typename L>
invokeLambda(L const & lambda,std::string const & arg)8870 inline auto invokeLambda( L const &lambda, std::string const &arg ) -> ParserResult {
8871 ArgType temp{};
8872 auto result = convertInto( arg, temp );
8873 return !result
8874 ? result
8875 : LambdaInvoker<typename UnaryLambdaTraits<L>::ReturnType>::invoke( lambda, temp );
8876 }
8877
8878 template<typename L>
8879 struct BoundLambda : BoundValueRefBase {
8880 L m_lambda;
8881
8882 static_assert( UnaryLambdaTraits<L>::isValid, "Supplied lambda must take exactly one argument" );
BoundLambdaCatch::clara::detail::BoundLambda8883 explicit BoundLambda( L const &lambda ) : m_lambda( lambda ) {}
8884
setValueCatch::clara::detail::BoundLambda8885 auto setValue( std::string const &arg ) -> ParserResult override {
8886 return invokeLambda<typename UnaryLambdaTraits<L>::ArgType>( m_lambda, arg );
8887 }
8888 };
8889
8890 template<typename L>
8891 struct BoundFlagLambda : BoundFlagRefBase {
8892 L m_lambda;
8893
8894 static_assert( UnaryLambdaTraits<L>::isValid, "Supplied lambda must take exactly one argument" );
8895 static_assert( std::is_same<typename UnaryLambdaTraits<L>::ArgType, bool>::value, "flags must be boolean" );
8896
BoundFlagLambdaCatch::clara::detail::BoundFlagLambda8897 explicit BoundFlagLambda( L const &lambda ) : m_lambda( lambda ) {}
8898
setFlagCatch::clara::detail::BoundFlagLambda8899 auto setFlag( bool flag ) -> ParserResult override {
8900 return LambdaInvoker<typename UnaryLambdaTraits<L>::ReturnType>::invoke( m_lambda, flag );
8901 }
8902 };
8903
8904 enum class Optionality { Optional, Required };
8905
8906 struct Parser;
8907
8908 class ParserBase {
8909 public:
8910 virtual ~ParserBase() = default;
validate() const8911 virtual auto validate() const -> Result { return Result::ok(); }
8912 virtual auto parse( std::string const& exeName, TokenStream const &tokens) const -> InternalParseResult = 0;
cardinality() const8913 virtual auto cardinality() const -> size_t { return 1; }
8914
parse(Args const & args) const8915 auto parse( Args const &args ) const -> InternalParseResult {
8916 return parse( args.exeName(), TokenStream( args ) );
8917 }
8918 };
8919
8920 template<typename DerivedT>
8921 class ComposableParserImpl : public ParserBase {
8922 public:
8923 template<typename T>
8924 auto operator|( T const &other ) const -> Parser;
8925
8926 template<typename T>
8927 auto operator+( T const &other ) const -> Parser;
8928 };
8929
8930 // Common code and state for Args and Opts
8931 template<typename DerivedT>
8932 class ParserRefImpl : public ComposableParserImpl<DerivedT> {
8933 protected:
8934 Optionality m_optionality = Optionality::Optional;
8935 std::shared_ptr<BoundRef> m_ref;
8936 std::string m_hint;
8937 std::string m_description;
8938
ParserRefImpl(std::shared_ptr<BoundRef> const & ref)8939 explicit ParserRefImpl( std::shared_ptr<BoundRef> const &ref ) : m_ref( ref ) {}
8940
8941 public:
8942 template<typename T>
ParserRefImpl(T & ref,std::string const & hint)8943 ParserRefImpl( T &ref, std::string const &hint )
8944 : m_ref( std::make_shared<BoundValueRef<T>>( ref ) ),
8945 m_hint( hint )
8946 {}
8947
8948 template<typename LambdaT>
ParserRefImpl(LambdaT const & ref,std::string const & hint)8949 ParserRefImpl( LambdaT const &ref, std::string const &hint )
8950 : m_ref( std::make_shared<BoundLambda<LambdaT>>( ref ) ),
8951 m_hint(hint)
8952 {}
8953
operator ()(std::string const & description)8954 auto operator()( std::string const &description ) -> DerivedT & {
8955 m_description = description;
8956 return static_cast<DerivedT &>( *this );
8957 }
8958
optional()8959 auto optional() -> DerivedT & {
8960 m_optionality = Optionality::Optional;
8961 return static_cast<DerivedT &>( *this );
8962 };
8963
required()8964 auto required() -> DerivedT & {
8965 m_optionality = Optionality::Required;
8966 return static_cast<DerivedT &>( *this );
8967 };
8968
isOptional() const8969 auto isOptional() const -> bool {
8970 return m_optionality == Optionality::Optional;
8971 }
8972
cardinality() const8973 auto cardinality() const -> size_t override {
8974 if( m_ref->isContainer() )
8975 return 0;
8976 else
8977 return 1;
8978 }
8979
hint() const8980 auto hint() const -> std::string { return m_hint; }
8981 };
8982
8983 class ExeName : public ComposableParserImpl<ExeName> {
8984 std::shared_ptr<std::string> m_name;
8985 std::shared_ptr<BoundValueRefBase> m_ref;
8986
8987 template<typename LambdaT>
makeRef(LambdaT const & lambda)8988 static auto makeRef(LambdaT const &lambda) -> std::shared_ptr<BoundValueRefBase> {
8989 return std::make_shared<BoundLambda<LambdaT>>( lambda) ;
8990 }
8991
8992 public:
ExeName()8993 ExeName() : m_name( std::make_shared<std::string>( "<executable>" ) ) {}
8994
ExeName(std::string & ref)8995 explicit ExeName( std::string &ref ) : ExeName() {
8996 m_ref = std::make_shared<BoundValueRef<std::string>>( ref );
8997 }
8998
8999 template<typename LambdaT>
ExeName(LambdaT const & lambda)9000 explicit ExeName( LambdaT const& lambda ) : ExeName() {
9001 m_ref = std::make_shared<BoundLambda<LambdaT>>( lambda );
9002 }
9003
9004 // The exe name is not parsed out of the normal tokens, but is handled specially
parse(std::string const &,TokenStream const & tokens) const9005 auto parse( std::string const&, TokenStream const &tokens ) const -> InternalParseResult override {
9006 return InternalParseResult::ok( ParseState( ParseResultType::NoMatch, tokens ) );
9007 }
9008
name() const9009 auto name() const -> std::string { return *m_name; }
set(std::string const & newName)9010 auto set( std::string const& newName ) -> ParserResult {
9011
9012 auto lastSlash = newName.find_last_of( "\\/" );
9013 auto filename = ( lastSlash == std::string::npos )
9014 ? newName
9015 : newName.substr( lastSlash+1 );
9016
9017 *m_name = filename;
9018 if( m_ref )
9019 return m_ref->setValue( filename );
9020 else
9021 return ParserResult::ok( ParseResultType::Matched );
9022 }
9023 };
9024
9025 class Arg : public ParserRefImpl<Arg> {
9026 public:
9027 using ParserRefImpl::ParserRefImpl;
9028
parse(std::string const &,TokenStream const & tokens) const9029 auto parse( std::string const &, TokenStream const &tokens ) const -> InternalParseResult override {
9030 auto validationResult = validate();
9031 if( !validationResult )
9032 return InternalParseResult( validationResult );
9033
9034 auto remainingTokens = tokens;
9035 auto const &token = *remainingTokens;
9036 if( token.type != TokenType::Argument )
9037 return InternalParseResult::ok( ParseState( ParseResultType::NoMatch, remainingTokens ) );
9038
9039 assert( !m_ref->isFlag() );
9040 auto valueRef = static_cast<detail::BoundValueRefBase*>( m_ref.get() );
9041
9042 auto result = valueRef->setValue( remainingTokens->token );
9043 if( !result )
9044 return InternalParseResult( result );
9045 else
9046 return InternalParseResult::ok( ParseState( ParseResultType::Matched, ++remainingTokens ) );
9047 }
9048 };
9049
normaliseOpt(std::string const & optName)9050 inline auto normaliseOpt( std::string const &optName ) -> std::string {
9051 #ifdef CATCH_PLATFORM_WINDOWS
9052 if( optName[0] == '/' )
9053 return "-" + optName.substr( 1 );
9054 else
9055 #endif
9056 return optName;
9057 }
9058
9059 class Opt : public ParserRefImpl<Opt> {
9060 protected:
9061 std::vector<std::string> m_optNames;
9062
9063 public:
9064 template<typename LambdaT>
Opt(LambdaT const & ref)9065 explicit Opt( LambdaT const &ref ) : ParserRefImpl( std::make_shared<BoundFlagLambda<LambdaT>>( ref ) ) {}
9066
Opt(bool & ref)9067 explicit Opt( bool &ref ) : ParserRefImpl( std::make_shared<BoundFlagRef>( ref ) ) {}
9068
9069 template<typename LambdaT>
Opt(LambdaT const & ref,std::string const & hint)9070 Opt( LambdaT const &ref, std::string const &hint ) : ParserRefImpl( ref, hint ) {}
9071
9072 template<typename T>
Opt(T & ref,std::string const & hint)9073 Opt( T &ref, std::string const &hint ) : ParserRefImpl( ref, hint ) {}
9074
operator [](std::string const & optName)9075 auto operator[]( std::string const &optName ) -> Opt & {
9076 m_optNames.push_back( optName );
9077 return *this;
9078 }
9079
getHelpColumns() const9080 auto getHelpColumns() const -> std::vector<HelpColumns> {
9081 std::ostringstream oss;
9082 bool first = true;
9083 for( auto const &opt : m_optNames ) {
9084 if (first)
9085 first = false;
9086 else
9087 oss << ", ";
9088 oss << opt;
9089 }
9090 if( !m_hint.empty() )
9091 oss << " <" << m_hint << ">";
9092 return { { oss.str(), m_description } };
9093 }
9094
isMatch(std::string const & optToken) const9095 auto isMatch( std::string const &optToken ) const -> bool {
9096 auto normalisedToken = normaliseOpt( optToken );
9097 for( auto const &name : m_optNames ) {
9098 if( normaliseOpt( name ) == normalisedToken )
9099 return true;
9100 }
9101 return false;
9102 }
9103
9104 using ParserBase::parse;
9105
parse(std::string const &,TokenStream const & tokens) const9106 auto parse( std::string const&, TokenStream const &tokens ) const -> InternalParseResult override {
9107 auto validationResult = validate();
9108 if( !validationResult )
9109 return InternalParseResult( validationResult );
9110
9111 auto remainingTokens = tokens;
9112 if( remainingTokens && remainingTokens->type == TokenType::Option ) {
9113 auto const &token = *remainingTokens;
9114 if( isMatch(token.token ) ) {
9115 if( m_ref->isFlag() ) {
9116 auto flagRef = static_cast<detail::BoundFlagRefBase*>( m_ref.get() );
9117 auto result = flagRef->setFlag( true );
9118 if( !result )
9119 return InternalParseResult( result );
9120 if( result.value() == ParseResultType::ShortCircuitAll )
9121 return InternalParseResult::ok( ParseState( result.value(), remainingTokens ) );
9122 } else {
9123 auto valueRef = static_cast<detail::BoundValueRefBase*>( m_ref.get() );
9124 ++remainingTokens;
9125 if( !remainingTokens )
9126 return InternalParseResult::runtimeError( "Expected argument following " + token.token );
9127 auto const &argToken = *remainingTokens;
9128 if( argToken.type != TokenType::Argument )
9129 return InternalParseResult::runtimeError( "Expected argument following " + token.token );
9130 auto result = valueRef->setValue( argToken.token );
9131 if( !result )
9132 return InternalParseResult( result );
9133 if( result.value() == ParseResultType::ShortCircuitAll )
9134 return InternalParseResult::ok( ParseState( result.value(), remainingTokens ) );
9135 }
9136 return InternalParseResult::ok( ParseState( ParseResultType::Matched, ++remainingTokens ) );
9137 }
9138 }
9139 return InternalParseResult::ok( ParseState( ParseResultType::NoMatch, remainingTokens ) );
9140 }
9141
validate() const9142 auto validate() const -> Result override {
9143 if( m_optNames.empty() )
9144 return Result::logicError( "No options supplied to Opt" );
9145 for( auto const &name : m_optNames ) {
9146 if( name.empty() )
9147 return Result::logicError( "Option name cannot be empty" );
9148 #ifdef CATCH_PLATFORM_WINDOWS
9149 if( name[0] != '-' && name[0] != '/' )
9150 return Result::logicError( "Option name must begin with '-' or '/'" );
9151 #else
9152 if( name[0] != '-' )
9153 return Result::logicError( "Option name must begin with '-'" );
9154 #endif
9155 }
9156 return ParserRefImpl::validate();
9157 }
9158 };
9159
9160 struct Help : Opt {
HelpCatch::clara::detail::Help9161 Help( bool &showHelpFlag )
9162 : Opt([&]( bool flag ) {
9163 showHelpFlag = flag;
9164 return ParserResult::ok( ParseResultType::ShortCircuitAll );
9165 })
9166 {
9167 static_cast<Opt &>( *this )
9168 ("display usage information")
9169 ["-?"]["-h"]["--help"]
9170 .optional();
9171 }
9172 };
9173
9174 struct Parser : ParserBase {
9175
9176 mutable ExeName m_exeName;
9177 std::vector<Opt> m_options;
9178 std::vector<Arg> m_args;
9179
operator |=Catch::clara::detail::Parser9180 auto operator|=( ExeName const &exeName ) -> Parser & {
9181 m_exeName = exeName;
9182 return *this;
9183 }
9184
operator |=Catch::clara::detail::Parser9185 auto operator|=( Arg const &arg ) -> Parser & {
9186 m_args.push_back(arg);
9187 return *this;
9188 }
9189
operator |=Catch::clara::detail::Parser9190 auto operator|=( Opt const &opt ) -> Parser & {
9191 m_options.push_back(opt);
9192 return *this;
9193 }
9194
operator |=Catch::clara::detail::Parser9195 auto operator|=( Parser const &other ) -> Parser & {
9196 m_options.insert(m_options.end(), other.m_options.begin(), other.m_options.end());
9197 m_args.insert(m_args.end(), other.m_args.begin(), other.m_args.end());
9198 return *this;
9199 }
9200
9201 template<typename T>
operator |Catch::clara::detail::Parser9202 auto operator|( T const &other ) const -> Parser {
9203 return Parser( *this ) |= other;
9204 }
9205
9206 // Forward deprecated interface with '+' instead of '|'
9207 template<typename T>
operator +=Catch::clara::detail::Parser9208 auto operator+=( T const &other ) -> Parser & { return operator|=( other ); }
9209 template<typename T>
operator +Catch::clara::detail::Parser9210 auto operator+( T const &other ) const -> Parser { return operator|( other ); }
9211
getHelpColumnsCatch::clara::detail::Parser9212 auto getHelpColumns() const -> std::vector<HelpColumns> {
9213 std::vector<HelpColumns> cols;
9214 for (auto const &o : m_options) {
9215 auto childCols = o.getHelpColumns();
9216 cols.insert( cols.end(), childCols.begin(), childCols.end() );
9217 }
9218 return cols;
9219 }
9220
writeToStreamCatch::clara::detail::Parser9221 void writeToStream( std::ostream &os ) const {
9222 if (!m_exeName.name().empty()) {
9223 os << "usage:\n" << " " << m_exeName.name() << " ";
9224 bool required = true, first = true;
9225 for( auto const &arg : m_args ) {
9226 if (first)
9227 first = false;
9228 else
9229 os << " ";
9230 if( arg.isOptional() && required ) {
9231 os << "[";
9232 required = false;
9233 }
9234 os << "<" << arg.hint() << ">";
9235 if( arg.cardinality() == 0 )
9236 os << " ... ";
9237 }
9238 if( !required )
9239 os << "]";
9240 if( !m_options.empty() )
9241 os << " options";
9242 os << "\n\nwhere options are:" << std::endl;
9243 }
9244
9245 auto rows = getHelpColumns();
9246 size_t consoleWidth = CATCH_CLARA_CONFIG_CONSOLE_WIDTH;
9247 size_t optWidth = 0;
9248 for( auto const &cols : rows )
9249 optWidth = (std::max)(optWidth, cols.left.size() + 2);
9250
9251 optWidth = (std::min)(optWidth, consoleWidth/2);
9252
9253 for( auto const &cols : rows ) {
9254 auto row =
9255 TextFlow::Column( cols.left ).width( optWidth ).indent( 2 ) +
9256 TextFlow::Spacer(4) +
9257 TextFlow::Column( cols.right ).width( consoleWidth - 7 - optWidth );
9258 os << row << std::endl;
9259 }
9260 }
9261
operator <<(std::ostream & os,Parser const & parser)9262 friend auto operator<<( std::ostream &os, Parser const &parser ) -> std::ostream& {
9263 parser.writeToStream( os );
9264 return os;
9265 }
9266
validateCatch::clara::detail::Parser9267 auto validate() const -> Result override {
9268 for( auto const &opt : m_options ) {
9269 auto result = opt.validate();
9270 if( !result )
9271 return result;
9272 }
9273 for( auto const &arg : m_args ) {
9274 auto result = arg.validate();
9275 if( !result )
9276 return result;
9277 }
9278 return Result::ok();
9279 }
9280
9281 using ParserBase::parse;
9282
parseCatch::clara::detail::Parser9283 auto parse( std::string const& exeName, TokenStream const &tokens ) const -> InternalParseResult override {
9284
9285 struct ParserInfo {
9286 ParserBase const* parser = nullptr;
9287 size_t count = 0;
9288 };
9289 const size_t totalParsers = m_options.size() + m_args.size();
9290 assert( totalParsers < 512 );
9291 // ParserInfo parseInfos[totalParsers]; // <-- this is what we really want to do
9292 ParserInfo parseInfos[512];
9293
9294 {
9295 size_t i = 0;
9296 for (auto const &opt : m_options) parseInfos[i++].parser = &opt;
9297 for (auto const &arg : m_args) parseInfos[i++].parser = &arg;
9298 }
9299
9300 m_exeName.set( exeName );
9301
9302 auto result = InternalParseResult::ok( ParseState( ParseResultType::NoMatch, tokens ) );
9303 while( result.value().remainingTokens() ) {
9304 bool tokenParsed = false;
9305
9306 for( size_t i = 0; i < totalParsers; ++i ) {
9307 auto& parseInfo = parseInfos[i];
9308 if( parseInfo.parser->cardinality() == 0 || parseInfo.count < parseInfo.parser->cardinality() ) {
9309 result = parseInfo.parser->parse(exeName, result.value().remainingTokens());
9310 if (!result)
9311 return result;
9312 if (result.value().type() != ParseResultType::NoMatch) {
9313 tokenParsed = true;
9314 ++parseInfo.count;
9315 break;
9316 }
9317 }
9318 }
9319
9320 if( result.value().type() == ParseResultType::ShortCircuitAll )
9321 return result;
9322 if( !tokenParsed )
9323 return InternalParseResult::runtimeError( "Unrecognised token: " + result.value().remainingTokens()->token );
9324 }
9325 // !TBD Check missing required options
9326 return result;
9327 }
9328 };
9329
9330 template<typename DerivedT>
9331 template<typename T>
operator |(T const & other) const9332 auto ComposableParserImpl<DerivedT>::operator|( T const &other ) const -> Parser {
9333 return Parser() | static_cast<DerivedT const &>( *this ) | other;
9334 }
9335 } // namespace detail
9336
9337 // A Combined parser
9338 using detail::Parser;
9339
9340 // A parser for options
9341 using detail::Opt;
9342
9343 // A parser for arguments
9344 using detail::Arg;
9345
9346 // Wrapper for argc, argv from main()
9347 using detail::Args;
9348
9349 // Specifies the name of the executable
9350 using detail::ExeName;
9351
9352 // Convenience wrapper for option parser that specifies the help option
9353 using detail::Help;
9354
9355 // enum of result types from a parse
9356 using detail::ParseResultType;
9357
9358 // Result type for parser operation
9359 using detail::ParserResult;
9360
9361 }} // namespace Catch::clara
9362
9363 // end clara.hpp
9364 #ifdef __clang__
9365 #pragma clang diagnostic pop
9366 #endif
9367
9368 // Restore Clara's value for console width, if present
9369 #ifdef CATCH_TEMP_CLARA_CONFIG_CONSOLE_WIDTH
9370 #define CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH CATCH_TEMP_CLARA_CONFIG_CONSOLE_WIDTH
9371 #undef CATCH_TEMP_CLARA_CONFIG_CONSOLE_WIDTH
9372 #endif
9373
9374 // end catch_clara.h
9375 namespace Catch {
9376
9377 clara::Parser makeCommandLineParser( ConfigData& config );
9378
9379 } // end namespace Catch
9380
9381 // end catch_commandline.h
9382 #include <fstream>
9383 #include <ctime>
9384
9385 namespace Catch {
9386
makeCommandLineParser(ConfigData & config)9387 clara::Parser makeCommandLineParser( ConfigData& config ) {
9388
9389 using namespace clara;
9390
9391 auto const setWarning = [&]( std::string const& warning ) {
9392 auto warningSet = [&]() {
9393 if( warning == "NoAssertions" )
9394 return WarnAbout::NoAssertions;
9395
9396 if ( warning == "NoTests" )
9397 return WarnAbout::NoTests;
9398
9399 return WarnAbout::Nothing;
9400 }();
9401
9402 if (warningSet == WarnAbout::Nothing)
9403 return ParserResult::runtimeError( "Unrecognised warning: '" + warning + "'" );
9404 config.warnings = static_cast<WarnAbout::What>( config.warnings | warningSet );
9405 return ParserResult::ok( ParseResultType::Matched );
9406 };
9407 auto const loadTestNamesFromFile = [&]( std::string const& filename ) {
9408 std::ifstream f( filename.c_str() );
9409 if( !f.is_open() )
9410 return ParserResult::runtimeError( "Unable to load input file: '" + filename + "'" );
9411
9412 std::string line;
9413 while( std::getline( f, line ) ) {
9414 line = trim(line);
9415 if( !line.empty() && !startsWith( line, '#' ) ) {
9416 if( !startsWith( line, '"' ) )
9417 line = '"' + line + '"';
9418 config.testsOrTags.push_back( line + ',' );
9419 }
9420 }
9421 return ParserResult::ok( ParseResultType::Matched );
9422 };
9423 auto const setTestOrder = [&]( std::string const& order ) {
9424 if( startsWith( "declared", order ) )
9425 config.runOrder = RunTests::InDeclarationOrder;
9426 else if( startsWith( "lexical", order ) )
9427 config.runOrder = RunTests::InLexicographicalOrder;
9428 else if( startsWith( "random", order ) )
9429 config.runOrder = RunTests::InRandomOrder;
9430 else
9431 return clara::ParserResult::runtimeError( "Unrecognised ordering: '" + order + "'" );
9432 return ParserResult::ok( ParseResultType::Matched );
9433 };
9434 auto const setRngSeed = [&]( std::string const& seed ) {
9435 if( seed != "time" )
9436 return clara::detail::convertInto( seed, config.rngSeed );
9437 config.rngSeed = static_cast<unsigned int>( std::time(nullptr) );
9438 return ParserResult::ok( ParseResultType::Matched );
9439 };
9440 auto const setColourUsage = [&]( std::string const& useColour ) {
9441 auto mode = toLower( useColour );
9442
9443 if( mode == "yes" )
9444 config.useColour = UseColour::Yes;
9445 else if( mode == "no" )
9446 config.useColour = UseColour::No;
9447 else if( mode == "auto" )
9448 config.useColour = UseColour::Auto;
9449 else
9450 return ParserResult::runtimeError( "colour mode must be one of: auto, yes or no. '" + useColour + "' not recognised" );
9451 return ParserResult::ok( ParseResultType::Matched );
9452 };
9453 auto const setWaitForKeypress = [&]( std::string const& keypress ) {
9454 auto keypressLc = toLower( keypress );
9455 if( keypressLc == "start" )
9456 config.waitForKeypress = WaitForKeypress::BeforeStart;
9457 else if( keypressLc == "exit" )
9458 config.waitForKeypress = WaitForKeypress::BeforeExit;
9459 else if( keypressLc == "both" )
9460 config.waitForKeypress = WaitForKeypress::BeforeStartAndExit;
9461 else
9462 return ParserResult::runtimeError( "keypress argument must be one of: start, exit or both. '" + keypress + "' not recognised" );
9463 return ParserResult::ok( ParseResultType::Matched );
9464 };
9465 auto const setVerbosity = [&]( std::string const& verbosity ) {
9466 auto lcVerbosity = toLower( verbosity );
9467 if( lcVerbosity == "quiet" )
9468 config.verbosity = Verbosity::Quiet;
9469 else if( lcVerbosity == "normal" )
9470 config.verbosity = Verbosity::Normal;
9471 else if( lcVerbosity == "high" )
9472 config.verbosity = Verbosity::High;
9473 else
9474 return ParserResult::runtimeError( "Unrecognised verbosity, '" + verbosity + "'" );
9475 return ParserResult::ok( ParseResultType::Matched );
9476 };
9477 auto const setReporter = [&]( std::string const& reporter ) {
9478 IReporterRegistry::FactoryMap const& factories = getRegistryHub().getReporterRegistry().getFactories();
9479
9480 auto lcReporter = toLower( reporter );
9481 auto result = factories.find( lcReporter );
9482
9483 if( factories.end() != result )
9484 config.reporterName = lcReporter;
9485 else
9486 return ParserResult::runtimeError( "Unrecognized reporter, '" + reporter + "'. Check available with --list-reporters" );
9487 return ParserResult::ok( ParseResultType::Matched );
9488 };
9489
9490 auto cli
9491 = ExeName( config.processName )
9492 | Help( config.showHelp )
9493 | Opt( config.listTests )
9494 ["-l"]["--list-tests"]
9495 ( "list all/matching test cases" )
9496 | Opt( config.listTags )
9497 ["-t"]["--list-tags"]
9498 ( "list all/matching tags" )
9499 | Opt( config.showSuccessfulTests )
9500 ["-s"]["--success"]
9501 ( "include successful tests in output" )
9502 | Opt( config.shouldDebugBreak )
9503 ["-b"]["--break"]
9504 ( "break into debugger on failure" )
9505 | Opt( config.noThrow )
9506 ["-e"]["--nothrow"]
9507 ( "skip exception tests" )
9508 | Opt( config.showInvisibles )
9509 ["-i"]["--invisibles"]
9510 ( "show invisibles (tabs, newlines)" )
9511 | Opt( config.outputFilename, "filename" )
9512 ["-o"]["--out"]
9513 ( "output filename" )
9514 | Opt( setReporter, "name" )
9515 ["-r"]["--reporter"]
9516 ( "reporter to use (defaults to console)" )
9517 | Opt( config.name, "name" )
9518 ["-n"]["--name"]
9519 ( "suite name" )
9520 | Opt( [&]( bool ){ config.abortAfter = 1; } )
9521 ["-a"]["--abort"]
9522 ( "abort at first failure" )
9523 | Opt( [&]( int x ){ config.abortAfter = x; }, "no. failures" )
9524 ["-x"]["--abortx"]
9525 ( "abort after x failures" )
9526 | Opt( setWarning, "warning name" )
9527 ["-w"]["--warn"]
9528 ( "enable warnings" )
9529 | Opt( [&]( bool flag ) { config.showDurations = flag ? ShowDurations::Always : ShowDurations::Never; }, "yes|no" )
9530 ["-d"]["--durations"]
9531 ( "show test durations" )
9532 | Opt( loadTestNamesFromFile, "filename" )
9533 ["-f"]["--input-file"]
9534 ( "load test names to run from a file" )
9535 | Opt( config.filenamesAsTags )
9536 ["-#"]["--filenames-as-tags"]
9537 ( "adds a tag for the filename" )
9538 | Opt( config.sectionsToRun, "section name" )
9539 ["-c"]["--section"]
9540 ( "specify section to run" )
9541 | Opt( setVerbosity, "quiet|normal|high" )
9542 ["-v"]["--verbosity"]
9543 ( "set output verbosity" )
9544 | Opt( config.listTestNamesOnly )
9545 ["--list-test-names-only"]
9546 ( "list all/matching test cases names only" )
9547 | Opt( config.listReporters )
9548 ["--list-reporters"]
9549 ( "list all reporters" )
9550 | Opt( setTestOrder, "decl|lex|rand" )
9551 ["--order"]
9552 ( "test case order (defaults to decl)" )
9553 | Opt( setRngSeed, "'time'|number" )
9554 ["--rng-seed"]
9555 ( "set a specific seed for random numbers" )
9556 | Opt( setColourUsage, "yes|no" )
9557 ["--use-colour"]
9558 ( "should output be colourised" )
9559 | Opt( config.libIdentify )
9560 ["--libidentify"]
9561 ( "report name and version according to libidentify standard" )
9562 | Opt( setWaitForKeypress, "start|exit|both" )
9563 ["--wait-for-keypress"]
9564 ( "waits for a keypress before exiting" )
9565 | Opt( config.benchmarkSamples, "samples" )
9566 ["--benchmark-samples"]
9567 ( "number of samples to collect (default: 100)" )
9568 | Opt( config.benchmarkResamples, "resamples" )
9569 ["--benchmark-resamples"]
9570 ( "number of resamples for the bootstrap (default: 100000)" )
9571 | Opt( config.benchmarkConfidenceInterval, "confidence interval" )
9572 ["--benchmark-confidence-interval"]
9573 ( "confidence interval for the bootstrap (between 0 and 1, default: 0.95)" )
9574 | Opt( config.benchmarkNoAnalysis )
9575 ["--benchmark-no-analysis"]
9576 ( "perform only measurements; do not perform any analysis" )
9577 | Arg( config.testsOrTags, "test name|pattern|tags" )
9578 ( "which test or tests to use" );
9579
9580 return cli;
9581 }
9582
9583 } // end namespace Catch
9584 // end catch_commandline.cpp
9585 // start catch_common.cpp
9586
9587 #include <cstring>
9588 #include <ostream>
9589
9590 namespace Catch {
9591
empty() const9592 bool SourceLineInfo::empty() const noexcept {
9593 return file[0] == '\0';
9594 }
operator ==(SourceLineInfo const & other) const9595 bool SourceLineInfo::operator == ( SourceLineInfo const& other ) const noexcept {
9596 return line == other.line && (file == other.file || std::strcmp(file, other.file) == 0);
9597 }
operator <(SourceLineInfo const & other) const9598 bool SourceLineInfo::operator < ( SourceLineInfo const& other ) const noexcept {
9599 // We can assume that the same file will usually have the same pointer.
9600 // Thus, if the pointers are the same, there is no point in calling the strcmp
9601 return line < other.line || ( line == other.line && file != other.file && (std::strcmp(file, other.file) < 0));
9602 }
9603
operator <<(std::ostream & os,SourceLineInfo const & info)9604 std::ostream& operator << ( std::ostream& os, SourceLineInfo const& info ) {
9605 #ifndef __GNUG__
9606 os << info.file << '(' << info.line << ')';
9607 #else
9608 os << info.file << ':' << info.line;
9609 #endif
9610 return os;
9611 }
9612
operator +() const9613 std::string StreamEndStop::operator+() const {
9614 return std::string();
9615 }
9616
9617 NonCopyable::NonCopyable() = default;
9618 NonCopyable::~NonCopyable() = default;
9619
9620 }
9621 // end catch_common.cpp
9622 // start catch_config.cpp
9623
9624 namespace Catch {
9625
Config(ConfigData const & data)9626 Config::Config( ConfigData const& data )
9627 : m_data( data ),
9628 m_stream( openStream() )
9629 {
9630 TestSpecParser parser(ITagAliasRegistry::get());
9631 if (!data.testsOrTags.empty()) {
9632 m_hasTestFilters = true;
9633 for( auto const& testOrTags : data.testsOrTags )
9634 parser.parse( testOrTags );
9635 }
9636 m_testSpec = parser.testSpec();
9637 }
9638
getFilename() const9639 std::string const& Config::getFilename() const {
9640 return m_data.outputFilename ;
9641 }
9642
listTests() const9643 bool Config::listTests() const { return m_data.listTests; }
listTestNamesOnly() const9644 bool Config::listTestNamesOnly() const { return m_data.listTestNamesOnly; }
listTags() const9645 bool Config::listTags() const { return m_data.listTags; }
listReporters() const9646 bool Config::listReporters() const { return m_data.listReporters; }
9647
getProcessName() const9648 std::string Config::getProcessName() const { return m_data.processName; }
getReporterName() const9649 std::string const& Config::getReporterName() const { return m_data.reporterName; }
9650
getTestsOrTags() const9651 std::vector<std::string> const& Config::getTestsOrTags() const { return m_data.testsOrTags; }
getSectionsToRun() const9652 std::vector<std::string> const& Config::getSectionsToRun() const { return m_data.sectionsToRun; }
9653
testSpec() const9654 TestSpec const& Config::testSpec() const { return m_testSpec; }
hasTestFilters() const9655 bool Config::hasTestFilters() const { return m_hasTestFilters; }
9656
showHelp() const9657 bool Config::showHelp() const { return m_data.showHelp; }
9658
9659 // IConfig interface
allowThrows() const9660 bool Config::allowThrows() const { return !m_data.noThrow; }
stream() const9661 std::ostream& Config::stream() const { return m_stream->stream(); }
name() const9662 std::string Config::name() const { return m_data.name.empty() ? m_data.processName : m_data.name; }
includeSuccessfulResults() const9663 bool Config::includeSuccessfulResults() const { return m_data.showSuccessfulTests; }
warnAboutMissingAssertions() const9664 bool Config::warnAboutMissingAssertions() const { return !!(m_data.warnings & WarnAbout::NoAssertions); }
warnAboutNoTests() const9665 bool Config::warnAboutNoTests() const { return !!(m_data.warnings & WarnAbout::NoTests); }
showDurations() const9666 ShowDurations::OrNot Config::showDurations() const { return m_data.showDurations; }
runOrder() const9667 RunTests::InWhatOrder Config::runOrder() const { return m_data.runOrder; }
rngSeed() const9668 unsigned int Config::rngSeed() const { return m_data.rngSeed; }
useColour() const9669 UseColour::YesOrNo Config::useColour() const { return m_data.useColour; }
shouldDebugBreak() const9670 bool Config::shouldDebugBreak() const { return m_data.shouldDebugBreak; }
abortAfter() const9671 int Config::abortAfter() const { return m_data.abortAfter; }
showInvisibles() const9672 bool Config::showInvisibles() const { return m_data.showInvisibles; }
verbosity() const9673 Verbosity Config::verbosity() const { return m_data.verbosity; }
9674
benchmarkNoAnalysis() const9675 bool Config::benchmarkNoAnalysis() const { return m_data.benchmarkNoAnalysis; }
benchmarkSamples() const9676 int Config::benchmarkSamples() const { return m_data.benchmarkSamples; }
benchmarkConfidenceInterval() const9677 double Config::benchmarkConfidenceInterval() const { return m_data.benchmarkConfidenceInterval; }
benchmarkResamples() const9678 unsigned int Config::benchmarkResamples() const { return m_data.benchmarkResamples; }
9679
openStream()9680 IStream const* Config::openStream() {
9681 return Catch::makeStream(m_data.outputFilename);
9682 }
9683
9684 } // end namespace Catch
9685 // end catch_config.cpp
9686 // start catch_console_colour.cpp
9687
9688 #if defined(__clang__)
9689 # pragma clang diagnostic push
9690 # pragma clang diagnostic ignored "-Wexit-time-destructors"
9691 #endif
9692
9693 // start catch_errno_guard.h
9694
9695 namespace Catch {
9696
9697 class ErrnoGuard {
9698 public:
9699 ErrnoGuard();
9700 ~ErrnoGuard();
9701 private:
9702 int m_oldErrno;
9703 };
9704
9705 }
9706
9707 // end catch_errno_guard.h
9708 #include <sstream>
9709
9710 namespace Catch {
9711 namespace {
9712
9713 struct IColourImpl {
9714 virtual ~IColourImpl() = default;
9715 virtual void use( Colour::Code _colourCode ) = 0;
9716 };
9717
9718 struct NoColourImpl : IColourImpl {
useCatch::__anon73d2dbed2d11::NoColourImpl9719 void use( Colour::Code ) {}
9720
instanceCatch::__anon73d2dbed2d11::NoColourImpl9721 static IColourImpl* instance() {
9722 static NoColourImpl s_instance;
9723 return &s_instance;
9724 }
9725 };
9726
9727 } // anon namespace
9728 } // namespace Catch
9729
9730 #if !defined( CATCH_CONFIG_COLOUR_NONE ) && !defined( CATCH_CONFIG_COLOUR_WINDOWS ) && !defined( CATCH_CONFIG_COLOUR_ANSI )
9731 # ifdef CATCH_PLATFORM_WINDOWS
9732 # define CATCH_CONFIG_COLOUR_WINDOWS
9733 # else
9734 # define CATCH_CONFIG_COLOUR_ANSI
9735 # endif
9736 #endif
9737
9738 #if defined ( CATCH_CONFIG_COLOUR_WINDOWS ) /////////////////////////////////////////
9739
9740 namespace Catch {
9741 namespace {
9742
9743 class Win32ColourImpl : public IColourImpl {
9744 public:
Win32ColourImpl()9745 Win32ColourImpl() : stdoutHandle( GetStdHandle(STD_OUTPUT_HANDLE) )
9746 {
9747 CONSOLE_SCREEN_BUFFER_INFO csbiInfo;
9748 GetConsoleScreenBufferInfo( stdoutHandle, &csbiInfo );
9749 originalForegroundAttributes = csbiInfo.wAttributes & ~( BACKGROUND_GREEN | BACKGROUND_RED | BACKGROUND_BLUE | BACKGROUND_INTENSITY );
9750 originalBackgroundAttributes = csbiInfo.wAttributes & ~( FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_BLUE | FOREGROUND_INTENSITY );
9751 }
9752
use(Colour::Code _colourCode)9753 void use( Colour::Code _colourCode ) override {
9754 switch( _colourCode ) {
9755 case Colour::None: return setTextAttribute( originalForegroundAttributes );
9756 case Colour::White: return setTextAttribute( FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_BLUE );
9757 case Colour::Red: return setTextAttribute( FOREGROUND_RED );
9758 case Colour::Green: return setTextAttribute( FOREGROUND_GREEN );
9759 case Colour::Blue: return setTextAttribute( FOREGROUND_BLUE );
9760 case Colour::Cyan: return setTextAttribute( FOREGROUND_BLUE | FOREGROUND_GREEN );
9761 case Colour::Yellow: return setTextAttribute( FOREGROUND_RED | FOREGROUND_GREEN );
9762 case Colour::Grey: return setTextAttribute( 0 );
9763
9764 case Colour::LightGrey: return setTextAttribute( FOREGROUND_INTENSITY );
9765 case Colour::BrightRed: return setTextAttribute( FOREGROUND_INTENSITY | FOREGROUND_RED );
9766 case Colour::BrightGreen: return setTextAttribute( FOREGROUND_INTENSITY | FOREGROUND_GREEN );
9767 case Colour::BrightWhite: return setTextAttribute( FOREGROUND_INTENSITY | FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_BLUE );
9768 case Colour::BrightYellow: return setTextAttribute( FOREGROUND_INTENSITY | FOREGROUND_RED | FOREGROUND_GREEN );
9769
9770 case Colour::Bright: CATCH_INTERNAL_ERROR( "not a colour" );
9771
9772 default:
9773 CATCH_ERROR( "Unknown colour requested" );
9774 }
9775 }
9776
9777 private:
setTextAttribute(WORD _textAttribute)9778 void setTextAttribute( WORD _textAttribute ) {
9779 SetConsoleTextAttribute( stdoutHandle, _textAttribute | originalBackgroundAttributes );
9780 }
9781 HANDLE stdoutHandle;
9782 WORD originalForegroundAttributes;
9783 WORD originalBackgroundAttributes;
9784 };
9785
platformColourInstance()9786 IColourImpl* platformColourInstance() {
9787 static Win32ColourImpl s_instance;
9788
9789 IConfigPtr config = getCurrentContext().getConfig();
9790 UseColour::YesOrNo colourMode = config
9791 ? config->useColour()
9792 : UseColour::Auto;
9793 if( colourMode == UseColour::Auto )
9794 colourMode = UseColour::Yes;
9795 return colourMode == UseColour::Yes
9796 ? &s_instance
9797 : NoColourImpl::instance();
9798 }
9799
9800 } // end anon namespace
9801 } // end namespace Catch
9802
9803 #elif defined( CATCH_CONFIG_COLOUR_ANSI ) //////////////////////////////////////
9804
9805 #include <unistd.h>
9806
9807 namespace Catch {
9808 namespace {
9809
9810 // use POSIX/ ANSI console terminal codes
9811 // Thanks to Adam Strzelecki for original contribution
9812 // (http://github.com/nanoant)
9813 // https://github.com/philsquared/Catch/pull/131
9814 class PosixColourImpl : public IColourImpl {
9815 public:
use(Colour::Code _colourCode)9816 void use( Colour::Code _colourCode ) override {
9817 switch( _colourCode ) {
9818 case Colour::None:
9819 case Colour::White: return setColour( "[0m" );
9820 case Colour::Red: return setColour( "[0;31m" );
9821 case Colour::Green: return setColour( "[0;32m" );
9822 case Colour::Blue: return setColour( "[0;34m" );
9823 case Colour::Cyan: return setColour( "[0;36m" );
9824 case Colour::Yellow: return setColour( "[0;33m" );
9825 case Colour::Grey: return setColour( "[1;30m" );
9826
9827 case Colour::LightGrey: return setColour( "[0;37m" );
9828 case Colour::BrightRed: return setColour( "[1;31m" );
9829 case Colour::BrightGreen: return setColour( "[1;32m" );
9830 case Colour::BrightWhite: return setColour( "[1;37m" );
9831 case Colour::BrightYellow: return setColour( "[1;33m" );
9832
9833 case Colour::Bright: CATCH_INTERNAL_ERROR( "not a colour" );
9834 default: CATCH_INTERNAL_ERROR( "Unknown colour requested" );
9835 }
9836 }
instance()9837 static IColourImpl* instance() {
9838 static PosixColourImpl s_instance;
9839 return &s_instance;
9840 }
9841
9842 private:
setColour(const char * _escapeCode)9843 void setColour( const char* _escapeCode ) {
9844 getCurrentContext().getConfig()->stream()
9845 << '\033' << _escapeCode;
9846 }
9847 };
9848
useColourOnPlatform()9849 bool useColourOnPlatform() {
9850 return
9851 #ifdef CATCH_PLATFORM_MAC
9852 !isDebuggerActive() &&
9853 #endif
9854 #if !(defined(__DJGPP__) && defined(__STRICT_ANSI__))
9855 isatty(STDOUT_FILENO)
9856 #else
9857 false
9858 #endif
9859 ;
9860 }
platformColourInstance()9861 IColourImpl* platformColourInstance() {
9862 ErrnoGuard guard;
9863 IConfigPtr config = getCurrentContext().getConfig();
9864 UseColour::YesOrNo colourMode = config
9865 ? config->useColour()
9866 : UseColour::Auto;
9867 if( colourMode == UseColour::Auto )
9868 colourMode = useColourOnPlatform()
9869 ? UseColour::Yes
9870 : UseColour::No;
9871 return colourMode == UseColour::Yes
9872 ? PosixColourImpl::instance()
9873 : NoColourImpl::instance();
9874 }
9875
9876 } // end anon namespace
9877 } // end namespace Catch
9878
9879 #else // not Windows or ANSI ///////////////////////////////////////////////
9880
9881 namespace Catch {
9882
platformColourInstance()9883 static IColourImpl* platformColourInstance() { return NoColourImpl::instance(); }
9884
9885 } // end namespace Catch
9886
9887 #endif // Windows/ ANSI/ None
9888
9889 namespace Catch {
9890
Colour(Code _colourCode)9891 Colour::Colour( Code _colourCode ) { use( _colourCode ); }
Colour(Colour && rhs)9892 Colour::Colour( Colour&& rhs ) noexcept {
9893 m_moved = rhs.m_moved;
9894 rhs.m_moved = true;
9895 }
operator =(Colour && rhs)9896 Colour& Colour::operator=( Colour&& rhs ) noexcept {
9897 m_moved = rhs.m_moved;
9898 rhs.m_moved = true;
9899 return *this;
9900 }
9901
~Colour()9902 Colour::~Colour(){ if( !m_moved ) use( None ); }
9903
use(Code _colourCode)9904 void Colour::use( Code _colourCode ) {
9905 static IColourImpl* impl = platformColourInstance();
9906 // Strictly speaking, this cannot possibly happen.
9907 // However, under some conditions it does happen (see #1626),
9908 // and this change is small enough that we can let practicality
9909 // triumph over purity in this case.
9910 if (impl != NULL) {
9911 impl->use( _colourCode );
9912 }
9913 }
9914
operator <<(std::ostream & os,Colour const &)9915 std::ostream& operator << ( std::ostream& os, Colour const& ) {
9916 return os;
9917 }
9918
9919 } // end namespace Catch
9920
9921 #if defined(__clang__)
9922 # pragma clang diagnostic pop
9923 #endif
9924
9925 // end catch_console_colour.cpp
9926 // start catch_context.cpp
9927
9928 namespace Catch {
9929
9930 class Context : public IMutableContext, NonCopyable {
9931
9932 public: // IContext
getResultCapture()9933 IResultCapture* getResultCapture() override {
9934 return m_resultCapture;
9935 }
getRunner()9936 IRunner* getRunner() override {
9937 return m_runner;
9938 }
9939
getConfig() const9940 IConfigPtr const& getConfig() const override {
9941 return m_config;
9942 }
9943
9944 ~Context() override;
9945
9946 public: // IMutableContext
setResultCapture(IResultCapture * resultCapture)9947 void setResultCapture( IResultCapture* resultCapture ) override {
9948 m_resultCapture = resultCapture;
9949 }
setRunner(IRunner * runner)9950 void setRunner( IRunner* runner ) override {
9951 m_runner = runner;
9952 }
setConfig(IConfigPtr const & config)9953 void setConfig( IConfigPtr const& config ) override {
9954 m_config = config;
9955 }
9956
9957 friend IMutableContext& getCurrentMutableContext();
9958
9959 private:
9960 IConfigPtr m_config;
9961 IRunner* m_runner = nullptr;
9962 IResultCapture* m_resultCapture = nullptr;
9963 };
9964
9965 IMutableContext *IMutableContext::currentContext = nullptr;
9966
createContext()9967 void IMutableContext::createContext()
9968 {
9969 currentContext = new Context();
9970 }
9971
cleanUpContext()9972 void cleanUpContext() {
9973 delete IMutableContext::currentContext;
9974 IMutableContext::currentContext = nullptr;
9975 }
9976 IContext::~IContext() = default;
9977 IMutableContext::~IMutableContext() = default;
9978 Context::~Context() = default;
9979 }
9980 // end catch_context.cpp
9981 // start catch_debug_console.cpp
9982
9983 // start catch_debug_console.h
9984
9985 #include <string>
9986
9987 namespace Catch {
9988 void writeToDebugConsole( std::string const& text );
9989 }
9990
9991 // end catch_debug_console.h
9992 #if defined(__ANDROID__)
9993 #include <android/log.h>
9994
9995 namespace Catch {
writeToDebugConsole(std::string const & text)9996 void writeToDebugConsole( std::string const& text ) {
9997 __android_log_print( ANDROID_LOG_DEBUG, "Catch", text.c_str() );
9998 }
9999 }
10000
10001 #elif defined(CATCH_PLATFORM_WINDOWS)
10002
10003 namespace Catch {
writeToDebugConsole(std::string const & text)10004 void writeToDebugConsole( std::string const& text ) {
10005 ::OutputDebugStringA( text.c_str() );
10006 }
10007 }
10008
10009 #else
10010
10011 namespace Catch {
writeToDebugConsole(std::string const & text)10012 void writeToDebugConsole( std::string const& text ) {
10013 // !TBD: Need a version for Mac/ XCode and other IDEs
10014 Catch::cout() << text;
10015 }
10016 }
10017
10018 #endif // Platform
10019 // end catch_debug_console.cpp
10020 // start catch_debugger.cpp
10021
10022 #ifdef CATCH_PLATFORM_MAC
10023
10024 # include <assert.h>
10025 # include <stdbool.h>
10026 # include <sys/types.h>
10027 # include <unistd.h>
10028 # include <cstddef>
10029 # include <ostream>
10030
10031 #ifdef __apple_build_version__
10032 // These headers will only compile with AppleClang (XCode)
10033 // For other compilers (Clang, GCC, ... ) we need to exclude them
10034 # include <sys/sysctl.h>
10035 #endif
10036
10037 namespace Catch {
10038 #ifdef __apple_build_version__
10039 // The following function is taken directly from the following technical note:
10040 // https://developer.apple.com/library/archive/qa/qa1361/_index.html
10041
10042 // Returns true if the current process is being debugged (either
10043 // running under the debugger or has a debugger attached post facto).
isDebuggerActive()10044 bool isDebuggerActive(){
10045 int mib[4];
10046 struct kinfo_proc info;
10047 std::size_t size;
10048
10049 // Initialize the flags so that, if sysctl fails for some bizarre
10050 // reason, we get a predictable result.
10051
10052 info.kp_proc.p_flag = 0;
10053
10054 // Initialize mib, which tells sysctl the info we want, in this case
10055 // we're looking for information about a specific process ID.
10056
10057 mib[0] = CTL_KERN;
10058 mib[1] = KERN_PROC;
10059 mib[2] = KERN_PROC_PID;
10060 mib[3] = getpid();
10061
10062 // Call sysctl.
10063
10064 size = sizeof(info);
10065 if( sysctl(mib, sizeof(mib) / sizeof(*mib), &info, &size, nullptr, 0) != 0 ) {
10066 Catch::cerr() << "\n** Call to sysctl failed - unable to determine if debugger is active **\n" << std::endl;
10067 return false;
10068 }
10069
10070 // We're being debugged if the P_TRACED flag is set.
10071
10072 return ( (info.kp_proc.p_flag & P_TRACED) != 0 );
10073 }
10074 #else
10075 bool isDebuggerActive() {
10076 // We need to find another way to determine this for non-appleclang compilers on macOS
10077 return false;
10078 }
10079 #endif
10080 } // namespace Catch
10081
10082 #elif defined(CATCH_PLATFORM_LINUX)
10083 #include <fstream>
10084 #include <string>
10085
10086 namespace Catch{
10087 // The standard POSIX way of detecting a debugger is to attempt to
10088 // ptrace() the process, but this needs to be done from a child and not
10089 // this process itself to still allow attaching to this process later
10090 // if wanted, so is rather heavy. Under Linux we have the PID of the
10091 // "debugger" (which doesn't need to be gdb, of course, it could also
10092 // be strace, for example) in /proc/$PID/status, so just get it from
10093 // there instead.
isDebuggerActive()10094 bool isDebuggerActive(){
10095 // Libstdc++ has a bug, where std::ifstream sets errno to 0
10096 // This way our users can properly assert over errno values
10097 ErrnoGuard guard;
10098 std::ifstream in("/proc/self/status");
10099 for( std::string line; std::getline(in, line); ) {
10100 static const int PREFIX_LEN = 11;
10101 if( line.compare(0, PREFIX_LEN, "TracerPid:\t") == 0 ) {
10102 // We're traced if the PID is not 0 and no other PID starts
10103 // with 0 digit, so it's enough to check for just a single
10104 // character.
10105 return line.length() > PREFIX_LEN && line[PREFIX_LEN] != '0';
10106 }
10107 }
10108
10109 return false;
10110 }
10111 } // namespace Catch
10112 #elif defined(_MSC_VER)
10113 extern "C" __declspec(dllimport) int __stdcall IsDebuggerPresent();
10114 namespace Catch {
isDebuggerActive()10115 bool isDebuggerActive() {
10116 return IsDebuggerPresent() != 0;
10117 }
10118 }
10119 #elif defined(__MINGW32__)
10120 extern "C" __declspec(dllimport) int __stdcall IsDebuggerPresent();
10121 namespace Catch {
isDebuggerActive()10122 bool isDebuggerActive() {
10123 return IsDebuggerPresent() != 0;
10124 }
10125 }
10126 #else
10127 namespace Catch {
isDebuggerActive()10128 bool isDebuggerActive() { return false; }
10129 }
10130 #endif // Platform
10131 // end catch_debugger.cpp
10132 // start catch_decomposer.cpp
10133
10134 namespace Catch {
10135
10136 ITransientExpression::~ITransientExpression() = default;
10137
formatReconstructedExpression(std::ostream & os,std::string const & lhs,StringRef op,std::string const & rhs)10138 void formatReconstructedExpression( std::ostream &os, std::string const& lhs, StringRef op, std::string const& rhs ) {
10139 if( lhs.size() + rhs.size() < 40 &&
10140 lhs.find('\n') == std::string::npos &&
10141 rhs.find('\n') == std::string::npos )
10142 os << lhs << " " << op << " " << rhs;
10143 else
10144 os << lhs << "\n" << op << "\n" << rhs;
10145 }
10146 }
10147 // end catch_decomposer.cpp
10148 // start catch_enforce.cpp
10149
10150 #include <stdexcept>
10151
10152 namespace Catch {
10153 #if defined(CATCH_CONFIG_DISABLE_EXCEPTIONS) && !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS_CUSTOM_HANDLER)
10154 [[noreturn]]
throw_exception(std::exception const & e)10155 void throw_exception(std::exception const& e) {
10156 Catch::cerr() << "Catch will terminate because it needed to throw an exception.\n"
10157 << "The message was: " << e.what() << '\n';
10158 std::terminate();
10159 }
10160 #endif
10161
10162 [[noreturn]]
throw_logic_error(std::string const & msg)10163 void throw_logic_error(std::string const& msg) {
10164 throw_exception(std::logic_error(msg));
10165 }
10166
10167 [[noreturn]]
throw_domain_error(std::string const & msg)10168 void throw_domain_error(std::string const& msg) {
10169 throw_exception(std::domain_error(msg));
10170 }
10171
10172 [[noreturn]]
throw_runtime_error(std::string const & msg)10173 void throw_runtime_error(std::string const& msg) {
10174 throw_exception(std::runtime_error(msg));
10175 }
10176
10177 } // namespace Catch;
10178 // end catch_enforce.cpp
10179 // start catch_enum_values_registry.cpp
10180 // start catch_enum_values_registry.h
10181
10182 #include <vector>
10183 #include <memory>
10184
10185 namespace Catch {
10186
10187 namespace Detail {
10188
10189 std::unique_ptr<EnumInfo> makeEnumInfo( StringRef enumName, StringRef allValueNames, std::vector<int> const& values );
10190
10191 class EnumValuesRegistry : public IMutableEnumValuesRegistry {
10192
10193 std::vector<std::unique_ptr<EnumInfo>> m_enumInfos;
10194
10195 EnumInfo const& registerEnum( StringRef enumName, StringRef allEnums, std::vector<int> const& values) override;
10196 };
10197
10198 std::vector<std::string> parseEnums( StringRef enums );
10199
10200 } // Detail
10201
10202 } // Catch
10203
10204 // end catch_enum_values_registry.h
10205
10206 #include <map>
10207 #include <cassert>
10208
10209 namespace Catch {
10210
~IMutableEnumValuesRegistry()10211 IMutableEnumValuesRegistry::~IMutableEnumValuesRegistry() {}
10212
10213 namespace Detail {
10214
parseEnums(StringRef enums)10215 std::vector<std::string> parseEnums( StringRef enums ) {
10216 auto enumValues = splitStringRef( enums, ',' );
10217 std::vector<std::string> parsed;
10218 parsed.reserve( enumValues.size() );
10219 for( auto const& enumValue : enumValues ) {
10220 auto identifiers = splitStringRef( enumValue, ':' );
10221 parsed.push_back( Catch::trim( identifiers.back() ) );
10222 }
10223 return parsed;
10224 }
10225
~EnumInfo()10226 EnumInfo::~EnumInfo() {}
10227
lookup(int value) const10228 StringRef EnumInfo::lookup( int value ) const {
10229 for( auto const& valueToName : m_values ) {
10230 if( valueToName.first == value )
10231 return valueToName.second;
10232 }
10233 return "{** unexpected enum value **}";
10234 }
10235
makeEnumInfo(StringRef enumName,StringRef allValueNames,std::vector<int> const & values)10236 std::unique_ptr<EnumInfo> makeEnumInfo( StringRef enumName, StringRef allValueNames, std::vector<int> const& values ) {
10237 std::unique_ptr<EnumInfo> enumInfo( new EnumInfo );
10238 enumInfo->m_name = enumName;
10239 enumInfo->m_values.reserve( values.size() );
10240
10241 const auto valueNames = Catch::Detail::parseEnums( allValueNames );
10242 assert( valueNames.size() == values.size() );
10243 std::size_t i = 0;
10244 for( auto value : values )
10245 enumInfo->m_values.push_back({ value, valueNames[i++] });
10246
10247 return enumInfo;
10248 }
10249
registerEnum(StringRef enumName,StringRef allValueNames,std::vector<int> const & values)10250 EnumInfo const& EnumValuesRegistry::registerEnum( StringRef enumName, StringRef allValueNames, std::vector<int> const& values ) {
10251 auto enumInfo = makeEnumInfo( enumName, allValueNames, values );
10252 EnumInfo* raw = enumInfo.get();
10253 m_enumInfos.push_back( std::move( enumInfo ) );
10254 return *raw;
10255 }
10256
10257 } // Detail
10258 } // Catch
10259
10260 // end catch_enum_values_registry.cpp
10261 // start catch_errno_guard.cpp
10262
10263 #include <cerrno>
10264
10265 namespace Catch {
ErrnoGuard()10266 ErrnoGuard::ErrnoGuard():m_oldErrno(errno){}
~ErrnoGuard()10267 ErrnoGuard::~ErrnoGuard() { errno = m_oldErrno; }
10268 }
10269 // end catch_errno_guard.cpp
10270 // start catch_exception_translator_registry.cpp
10271
10272 // start catch_exception_translator_registry.h
10273
10274 #include <vector>
10275 #include <string>
10276 #include <memory>
10277
10278 namespace Catch {
10279
10280 class ExceptionTranslatorRegistry : public IExceptionTranslatorRegistry {
10281 public:
10282 ~ExceptionTranslatorRegistry();
10283 virtual void registerTranslator( const IExceptionTranslator* translator );
10284 std::string translateActiveException() const override;
10285 std::string tryTranslators() const;
10286
10287 private:
10288 std::vector<std::unique_ptr<IExceptionTranslator const>> m_translators;
10289 };
10290 }
10291
10292 // end catch_exception_translator_registry.h
10293 #ifdef __OBJC__
10294 #import "Foundation/Foundation.h"
10295 #endif
10296
10297 namespace Catch {
10298
~ExceptionTranslatorRegistry()10299 ExceptionTranslatorRegistry::~ExceptionTranslatorRegistry() {
10300 }
10301
registerTranslator(const IExceptionTranslator * translator)10302 void ExceptionTranslatorRegistry::registerTranslator( const IExceptionTranslator* translator ) {
10303 m_translators.push_back( std::unique_ptr<const IExceptionTranslator>( translator ) );
10304 }
10305
10306 #if !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
translateActiveException() const10307 std::string ExceptionTranslatorRegistry::translateActiveException() const {
10308 try {
10309 #ifdef __OBJC__
10310 // In Objective-C try objective-c exceptions first
10311 @try {
10312 return tryTranslators();
10313 }
10314 @catch (NSException *exception) {
10315 return Catch::Detail::stringify( [exception description] );
10316 }
10317 #else
10318 // Compiling a mixed mode project with MSVC means that CLR
10319 // exceptions will be caught in (...) as well. However, these
10320 // do not fill-in std::current_exception and thus lead to crash
10321 // when attempting rethrow.
10322 // /EHa switch also causes structured exceptions to be caught
10323 // here, but they fill-in current_exception properly, so
10324 // at worst the output should be a little weird, instead of
10325 // causing a crash.
10326 if (std::current_exception() == nullptr) {
10327 return "Non C++ exception. Possibly a CLR exception.";
10328 }
10329 return tryTranslators();
10330 #endif
10331 }
10332 catch( TestFailureException& ) {
10333 std::rethrow_exception(std::current_exception());
10334 }
10335 catch( std::exception& ex ) {
10336 return ex.what();
10337 }
10338 catch( std::string& msg ) {
10339 return msg;
10340 }
10341 catch( const char* msg ) {
10342 return msg;
10343 }
10344 catch(...) {
10345 return "Unknown exception";
10346 }
10347 }
10348
tryTranslators() const10349 std::string ExceptionTranslatorRegistry::tryTranslators() const {
10350 if (m_translators.empty()) {
10351 std::rethrow_exception(std::current_exception());
10352 } else {
10353 return m_translators[0]->translate(m_translators.begin() + 1, m_translators.end());
10354 }
10355 }
10356
10357 #else // ^^ Exceptions are enabled // Exceptions are disabled vv
translateActiveException() const10358 std::string ExceptionTranslatorRegistry::translateActiveException() const {
10359 CATCH_INTERNAL_ERROR("Attempted to translate active exception under CATCH_CONFIG_DISABLE_EXCEPTIONS!");
10360 }
10361
tryTranslators() const10362 std::string ExceptionTranslatorRegistry::tryTranslators() const {
10363 CATCH_INTERNAL_ERROR("Attempted to use exception translators under CATCH_CONFIG_DISABLE_EXCEPTIONS!");
10364 }
10365 #endif
10366
10367 }
10368 // end catch_exception_translator_registry.cpp
10369 // start catch_fatal_condition.cpp
10370
10371 #if defined(__GNUC__)
10372 # pragma GCC diagnostic push
10373 # pragma GCC diagnostic ignored "-Wmissing-field-initializers"
10374 #endif
10375
10376 #if defined( CATCH_CONFIG_WINDOWS_SEH ) || defined( CATCH_CONFIG_POSIX_SIGNALS )
10377
10378 namespace {
10379 // Report the error condition
reportFatal(char const * const message)10380 void reportFatal( char const * const message ) {
10381 Catch::getCurrentContext().getResultCapture()->handleFatalErrorCondition( message );
10382 }
10383 }
10384
10385 #endif // signals/SEH handling
10386
10387 #if defined( CATCH_CONFIG_WINDOWS_SEH )
10388
10389 namespace Catch {
10390 struct SignalDefs { DWORD id; const char* name; };
10391
10392 // There is no 1-1 mapping between signals and windows exceptions.
10393 // Windows can easily distinguish between SO and SigSegV,
10394 // but SigInt, SigTerm, etc are handled differently.
10395 static SignalDefs signalDefs[] = {
10396 { static_cast<DWORD>(EXCEPTION_ILLEGAL_INSTRUCTION), "SIGILL - Illegal instruction signal" },
10397 { static_cast<DWORD>(EXCEPTION_STACK_OVERFLOW), "SIGSEGV - Stack overflow" },
10398 { static_cast<DWORD>(EXCEPTION_ACCESS_VIOLATION), "SIGSEGV - Segmentation violation signal" },
10399 { static_cast<DWORD>(EXCEPTION_INT_DIVIDE_BY_ZERO), "Divide by zero error" },
10400 };
10401
handleVectoredException(PEXCEPTION_POINTERS ExceptionInfo)10402 LONG CALLBACK FatalConditionHandler::handleVectoredException(PEXCEPTION_POINTERS ExceptionInfo) {
10403 for (auto const& def : signalDefs) {
10404 if (ExceptionInfo->ExceptionRecord->ExceptionCode == def.id) {
10405 reportFatal(def.name);
10406 }
10407 }
10408 // If its not an exception we care about, pass it along.
10409 // This stops us from eating debugger breaks etc.
10410 return EXCEPTION_CONTINUE_SEARCH;
10411 }
10412
FatalConditionHandler()10413 FatalConditionHandler::FatalConditionHandler() {
10414 isSet = true;
10415 // 32k seems enough for Catch to handle stack overflow,
10416 // but the value was found experimentally, so there is no strong guarantee
10417 guaranteeSize = 32 * 1024;
10418 exceptionHandlerHandle = nullptr;
10419 // Register as first handler in current chain
10420 exceptionHandlerHandle = AddVectoredExceptionHandler(1, handleVectoredException);
10421 // Pass in guarantee size to be filled
10422 SetThreadStackGuarantee(&guaranteeSize);
10423 }
10424
reset()10425 void FatalConditionHandler::reset() {
10426 if (isSet) {
10427 RemoveVectoredExceptionHandler(exceptionHandlerHandle);
10428 SetThreadStackGuarantee(&guaranteeSize);
10429 exceptionHandlerHandle = nullptr;
10430 isSet = false;
10431 }
10432 }
10433
~FatalConditionHandler()10434 FatalConditionHandler::~FatalConditionHandler() {
10435 reset();
10436 }
10437
10438 bool FatalConditionHandler::isSet = false;
10439 ULONG FatalConditionHandler::guaranteeSize = 0;
10440 PVOID FatalConditionHandler::exceptionHandlerHandle = nullptr;
10441
10442 } // namespace Catch
10443
10444 #elif defined( CATCH_CONFIG_POSIX_SIGNALS )
10445
10446 namespace Catch {
10447
10448 struct SignalDefs {
10449 int id;
10450 const char* name;
10451 };
10452
10453 // 32kb for the alternate stack seems to be sufficient. However, this value
10454 // is experimentally determined, so that's not guaranteed.
10455 static constexpr std::size_t sigStackSize = 32768 >= MINSIGSTKSZ ? 32768 : MINSIGSTKSZ;
10456
10457 static SignalDefs signalDefs[] = {
10458 { SIGINT, "SIGINT - Terminal interrupt signal" },
10459 { SIGILL, "SIGILL - Illegal instruction signal" },
10460 { SIGFPE, "SIGFPE - Floating point error signal" },
10461 { SIGSEGV, "SIGSEGV - Segmentation violation signal" },
10462 { SIGTERM, "SIGTERM - Termination request signal" },
10463 { SIGABRT, "SIGABRT - Abort (abnormal termination) signal" }
10464 };
10465
handleSignal(int sig)10466 void FatalConditionHandler::handleSignal( int sig ) {
10467 char const * name = "<unknown signal>";
10468 for (auto const& def : signalDefs) {
10469 if (sig == def.id) {
10470 name = def.name;
10471 break;
10472 }
10473 }
10474 reset();
10475 reportFatal(name);
10476 raise( sig );
10477 }
10478
FatalConditionHandler()10479 FatalConditionHandler::FatalConditionHandler() {
10480 isSet = true;
10481 stack_t sigStack;
10482 sigStack.ss_sp = altStackMem;
10483 sigStack.ss_size = sigStackSize;
10484 sigStack.ss_flags = 0;
10485 sigaltstack(&sigStack, &oldSigStack);
10486 struct sigaction sa = { };
10487
10488 sa.sa_handler = handleSignal;
10489 sa.sa_flags = SA_ONSTACK;
10490 for (std::size_t i = 0; i < sizeof(signalDefs)/sizeof(SignalDefs); ++i) {
10491 sigaction(signalDefs[i].id, &sa, &oldSigActions[i]);
10492 }
10493 }
10494
~FatalConditionHandler()10495 FatalConditionHandler::~FatalConditionHandler() {
10496 reset();
10497 }
10498
reset()10499 void FatalConditionHandler::reset() {
10500 if( isSet ) {
10501 // Set signals back to previous values -- hopefully nobody overwrote them in the meantime
10502 for( std::size_t i = 0; i < sizeof(signalDefs)/sizeof(SignalDefs); ++i ) {
10503 sigaction(signalDefs[i].id, &oldSigActions[i], nullptr);
10504 }
10505 // Return the old stack
10506 sigaltstack(&oldSigStack, nullptr);
10507 isSet = false;
10508 }
10509 }
10510
10511 bool FatalConditionHandler::isSet = false;
10512 struct sigaction FatalConditionHandler::oldSigActions[sizeof(signalDefs)/sizeof(SignalDefs)] = {};
10513 stack_t FatalConditionHandler::oldSigStack = {};
10514 char FatalConditionHandler::altStackMem[sigStackSize] = {};
10515
10516 } // namespace Catch
10517
10518 #else
10519
10520 namespace Catch {
reset()10521 void FatalConditionHandler::reset() {}
10522 }
10523
10524 #endif // signals/SEH handling
10525
10526 #if defined(__GNUC__)
10527 # pragma GCC diagnostic pop
10528 #endif
10529 // end catch_fatal_condition.cpp
10530 // start catch_generators.cpp
10531
10532 // start catch_random_number_generator.h
10533
10534 #include <algorithm>
10535 #include <random>
10536
10537 namespace Catch {
10538
10539 struct IConfig;
10540
10541 std::mt19937& rng();
10542 void seedRng( IConfig const& config );
10543 unsigned int rngSeed();
10544
10545 }
10546
10547 // end catch_random_number_generator.h
10548 #include <limits>
10549 #include <set>
10550
10551 namespace Catch {
10552
~IGeneratorTracker()10553 IGeneratorTracker::~IGeneratorTracker() {}
10554
what() const10555 const char* GeneratorException::what() const noexcept {
10556 return m_msg;
10557 }
10558
10559 namespace Generators {
10560
~GeneratorUntypedBase()10561 GeneratorUntypedBase::~GeneratorUntypedBase() {}
10562
acquireGeneratorTracker(SourceLineInfo const & lineInfo)10563 auto acquireGeneratorTracker( SourceLineInfo const& lineInfo ) -> IGeneratorTracker& {
10564 return getResultCapture().acquireGeneratorTracker( lineInfo );
10565 }
10566
10567 } // namespace Generators
10568 } // namespace Catch
10569 // end catch_generators.cpp
10570 // start catch_interfaces_capture.cpp
10571
10572 namespace Catch {
10573 IResultCapture::~IResultCapture() = default;
10574 }
10575 // end catch_interfaces_capture.cpp
10576 // start catch_interfaces_config.cpp
10577
10578 namespace Catch {
10579 IConfig::~IConfig() = default;
10580 }
10581 // end catch_interfaces_config.cpp
10582 // start catch_interfaces_exception.cpp
10583
10584 namespace Catch {
10585 IExceptionTranslator::~IExceptionTranslator() = default;
10586 IExceptionTranslatorRegistry::~IExceptionTranslatorRegistry() = default;
10587 }
10588 // end catch_interfaces_exception.cpp
10589 // start catch_interfaces_registry_hub.cpp
10590
10591 namespace Catch {
10592 IRegistryHub::~IRegistryHub() = default;
10593 IMutableRegistryHub::~IMutableRegistryHub() = default;
10594 }
10595 // end catch_interfaces_registry_hub.cpp
10596 // start catch_interfaces_reporter.cpp
10597
10598 // start catch_reporter_listening.h
10599
10600 namespace Catch {
10601
10602 class ListeningReporter : public IStreamingReporter {
10603 using Reporters = std::vector<IStreamingReporterPtr>;
10604 Reporters m_listeners;
10605 IStreamingReporterPtr m_reporter = nullptr;
10606 ReporterPreferences m_preferences;
10607
10608 public:
10609 ListeningReporter();
10610
10611 void addListener( IStreamingReporterPtr&& listener );
10612 void addReporter( IStreamingReporterPtr&& reporter );
10613
10614 public: // IStreamingReporter
10615
10616 ReporterPreferences getPreferences() const override;
10617
10618 void noMatchingTestCases( std::string const& spec ) override;
10619
10620 static std::set<Verbosity> getSupportedVerbosities();
10621
10622 #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
10623 void benchmarkPreparing(std::string const& name) override;
10624 void benchmarkStarting( BenchmarkInfo const& benchmarkInfo ) override;
10625 void benchmarkEnded( BenchmarkStats<> const& benchmarkStats ) override;
10626 void benchmarkFailed(std::string const&) override;
10627 #endif // CATCH_CONFIG_ENABLE_BENCHMARKING
10628
10629 void testRunStarting( TestRunInfo const& testRunInfo ) override;
10630 void testGroupStarting( GroupInfo const& groupInfo ) override;
10631 void testCaseStarting( TestCaseInfo const& testInfo ) override;
10632 void sectionStarting( SectionInfo const& sectionInfo ) override;
10633 void assertionStarting( AssertionInfo const& assertionInfo ) override;
10634
10635 // The return value indicates if the messages buffer should be cleared:
10636 bool assertionEnded( AssertionStats const& assertionStats ) override;
10637 void sectionEnded( SectionStats const& sectionStats ) override;
10638 void testCaseEnded( TestCaseStats const& testCaseStats ) override;
10639 void testGroupEnded( TestGroupStats const& testGroupStats ) override;
10640 void testRunEnded( TestRunStats const& testRunStats ) override;
10641
10642 void skipTest( TestCaseInfo const& testInfo ) override;
10643 bool isMulti() const override;
10644
10645 };
10646
10647 } // end namespace Catch
10648
10649 // end catch_reporter_listening.h
10650 namespace Catch {
10651
ReporterConfig(IConfigPtr const & _fullConfig)10652 ReporterConfig::ReporterConfig( IConfigPtr const& _fullConfig )
10653 : m_stream( &_fullConfig->stream() ), m_fullConfig( _fullConfig ) {}
10654
ReporterConfig(IConfigPtr const & _fullConfig,std::ostream & _stream)10655 ReporterConfig::ReporterConfig( IConfigPtr const& _fullConfig, std::ostream& _stream )
10656 : m_stream( &_stream ), m_fullConfig( _fullConfig ) {}
10657
stream() const10658 std::ostream& ReporterConfig::stream() const { return *m_stream; }
fullConfig() const10659 IConfigPtr ReporterConfig::fullConfig() const { return m_fullConfig; }
10660
TestRunInfo(std::string const & _name)10661 TestRunInfo::TestRunInfo( std::string const& _name ) : name( _name ) {}
10662
GroupInfo(std::string const & _name,std::size_t _groupIndex,std::size_t _groupsCount)10663 GroupInfo::GroupInfo( std::string const& _name,
10664 std::size_t _groupIndex,
10665 std::size_t _groupsCount )
10666 : name( _name ),
10667 groupIndex( _groupIndex ),
10668 groupsCounts( _groupsCount )
10669 {}
10670
AssertionStats(AssertionResult const & _assertionResult,std::vector<MessageInfo> const & _infoMessages,Totals const & _totals)10671 AssertionStats::AssertionStats( AssertionResult const& _assertionResult,
10672 std::vector<MessageInfo> const& _infoMessages,
10673 Totals const& _totals )
10674 : assertionResult( _assertionResult ),
10675 infoMessages( _infoMessages ),
10676 totals( _totals )
10677 {
10678 assertionResult.m_resultData.lazyExpression.m_transientExpression = _assertionResult.m_resultData.lazyExpression.m_transientExpression;
10679
10680 if( assertionResult.hasMessage() ) {
10681 // Copy message into messages list.
10682 // !TBD This should have been done earlier, somewhere
10683 MessageBuilder builder( assertionResult.getTestMacroName(), assertionResult.getSourceInfo(), assertionResult.getResultType() );
10684 builder << assertionResult.getMessage();
10685 builder.m_info.message = builder.m_stream.str();
10686
10687 infoMessages.push_back( builder.m_info );
10688 }
10689 }
10690
10691 AssertionStats::~AssertionStats() = default;
10692
SectionStats(SectionInfo const & _sectionInfo,Counts const & _assertions,double _durationInSeconds,bool _missingAssertions)10693 SectionStats::SectionStats( SectionInfo const& _sectionInfo,
10694 Counts const& _assertions,
10695 double _durationInSeconds,
10696 bool _missingAssertions )
10697 : sectionInfo( _sectionInfo ),
10698 assertions( _assertions ),
10699 durationInSeconds( _durationInSeconds ),
10700 missingAssertions( _missingAssertions )
10701 {}
10702
10703 SectionStats::~SectionStats() = default;
10704
TestCaseStats(TestCaseInfo const & _testInfo,Totals const & _totals,std::string const & _stdOut,std::string const & _stdErr,bool _aborting)10705 TestCaseStats::TestCaseStats( TestCaseInfo const& _testInfo,
10706 Totals const& _totals,
10707 std::string const& _stdOut,
10708 std::string const& _stdErr,
10709 bool _aborting )
10710 : testInfo( _testInfo ),
10711 totals( _totals ),
10712 stdOut( _stdOut ),
10713 stdErr( _stdErr ),
10714 aborting( _aborting )
10715 {}
10716
10717 TestCaseStats::~TestCaseStats() = default;
10718
TestGroupStats(GroupInfo const & _groupInfo,Totals const & _totals,bool _aborting)10719 TestGroupStats::TestGroupStats( GroupInfo const& _groupInfo,
10720 Totals const& _totals,
10721 bool _aborting )
10722 : groupInfo( _groupInfo ),
10723 totals( _totals ),
10724 aborting( _aborting )
10725 {}
10726
TestGroupStats(GroupInfo const & _groupInfo)10727 TestGroupStats::TestGroupStats( GroupInfo const& _groupInfo )
10728 : groupInfo( _groupInfo ),
10729 aborting( false )
10730 {}
10731
10732 TestGroupStats::~TestGroupStats() = default;
10733
TestRunStats(TestRunInfo const & _runInfo,Totals const & _totals,bool _aborting)10734 TestRunStats::TestRunStats( TestRunInfo const& _runInfo,
10735 Totals const& _totals,
10736 bool _aborting )
10737 : runInfo( _runInfo ),
10738 totals( _totals ),
10739 aborting( _aborting )
10740 {}
10741
10742 TestRunStats::~TestRunStats() = default;
10743
fatalErrorEncountered(StringRef)10744 void IStreamingReporter::fatalErrorEncountered( StringRef ) {}
isMulti() const10745 bool IStreamingReporter::isMulti() const { return false; }
10746
10747 IReporterFactory::~IReporterFactory() = default;
10748 IReporterRegistry::~IReporterRegistry() = default;
10749
10750 } // end namespace Catch
10751 // end catch_interfaces_reporter.cpp
10752 // start catch_interfaces_runner.cpp
10753
10754 namespace Catch {
10755 IRunner::~IRunner() = default;
10756 }
10757 // end catch_interfaces_runner.cpp
10758 // start catch_interfaces_testcase.cpp
10759
10760 namespace Catch {
10761 ITestInvoker::~ITestInvoker() = default;
10762 ITestCaseRegistry::~ITestCaseRegistry() = default;
10763 }
10764 // end catch_interfaces_testcase.cpp
10765 // start catch_leak_detector.cpp
10766
10767 #ifdef CATCH_CONFIG_WINDOWS_CRTDBG
10768 #include <crtdbg.h>
10769
10770 namespace Catch {
10771
LeakDetector()10772 LeakDetector::LeakDetector() {
10773 int flag = _CrtSetDbgFlag(_CRTDBG_REPORT_FLAG);
10774 flag |= _CRTDBG_LEAK_CHECK_DF;
10775 flag |= _CRTDBG_ALLOC_MEM_DF;
10776 _CrtSetDbgFlag(flag);
10777 _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE | _CRTDBG_MODE_DEBUG);
10778 _CrtSetReportFile(_CRT_WARN, _CRTDBG_FILE_STDERR);
10779 // Change this to leaking allocation's number to break there
10780 _CrtSetBreakAlloc(-1);
10781 }
10782 }
10783
10784 #else
10785
LeakDetector()10786 Catch::LeakDetector::LeakDetector() {}
10787
10788 #endif
10789
~LeakDetector()10790 Catch::LeakDetector::~LeakDetector() {
10791 Catch::cleanUp();
10792 }
10793 // end catch_leak_detector.cpp
10794 // start catch_list.cpp
10795
10796 // start catch_list.h
10797
10798 #include <set>
10799
10800 namespace Catch {
10801
10802 std::size_t listTests( Config const& config );
10803
10804 std::size_t listTestsNamesOnly( Config const& config );
10805
10806 struct TagInfo {
10807 void add( std::string const& spelling );
10808 std::string all() const;
10809
10810 std::set<std::string> spellings;
10811 std::size_t count = 0;
10812 };
10813
10814 std::size_t listTags( Config const& config );
10815
10816 std::size_t listReporters();
10817
10818 Option<std::size_t> list( std::shared_ptr<Config> const& config );
10819
10820 } // end namespace Catch
10821
10822 // end catch_list.h
10823 // start catch_text.h
10824
10825 namespace Catch {
10826 using namespace clara::TextFlow;
10827 }
10828
10829 // end catch_text.h
10830 #include <limits>
10831 #include <algorithm>
10832 #include <iomanip>
10833
10834 namespace Catch {
10835
listTests(Config const & config)10836 std::size_t listTests( Config const& config ) {
10837 TestSpec testSpec = config.testSpec();
10838 if( config.hasTestFilters() )
10839 Catch::cout() << "Matching test cases:\n";
10840 else {
10841 Catch::cout() << "All available test cases:\n";
10842 }
10843
10844 auto matchedTestCases = filterTests( getAllTestCasesSorted( config ), testSpec, config );
10845 for( auto const& testCaseInfo : matchedTestCases ) {
10846 Colour::Code colour = testCaseInfo.isHidden()
10847 ? Colour::SecondaryText
10848 : Colour::None;
10849 Colour colourGuard( colour );
10850
10851 Catch::cout() << Column( testCaseInfo.name ).initialIndent( 2 ).indent( 4 ) << "\n";
10852 if( config.verbosity() >= Verbosity::High ) {
10853 Catch::cout() << Column( Catch::Detail::stringify( testCaseInfo.lineInfo ) ).indent(4) << std::endl;
10854 std::string description = testCaseInfo.description;
10855 if( description.empty() )
10856 description = "(NO DESCRIPTION)";
10857 Catch::cout() << Column( description ).indent(4) << std::endl;
10858 }
10859 if( !testCaseInfo.tags.empty() )
10860 Catch::cout() << Column( testCaseInfo.tagsAsString() ).indent( 6 ) << "\n";
10861 }
10862
10863 if( !config.hasTestFilters() )
10864 Catch::cout() << pluralise( matchedTestCases.size(), "test case" ) << '\n' << std::endl;
10865 else
10866 Catch::cout() << pluralise( matchedTestCases.size(), "matching test case" ) << '\n' << std::endl;
10867 return matchedTestCases.size();
10868 }
10869
listTestsNamesOnly(Config const & config)10870 std::size_t listTestsNamesOnly( Config const& config ) {
10871 TestSpec testSpec = config.testSpec();
10872 std::size_t matchedTests = 0;
10873 std::vector<TestCase> matchedTestCases = filterTests( getAllTestCasesSorted( config ), testSpec, config );
10874 for( auto const& testCaseInfo : matchedTestCases ) {
10875 matchedTests++;
10876 if( startsWith( testCaseInfo.name, '#' ) )
10877 Catch::cout() << '"' << testCaseInfo.name << '"';
10878 else
10879 Catch::cout() << testCaseInfo.name;
10880 if ( config.verbosity() >= Verbosity::High )
10881 Catch::cout() << "\t@" << testCaseInfo.lineInfo;
10882 Catch::cout() << std::endl;
10883 }
10884 return matchedTests;
10885 }
10886
add(std::string const & spelling)10887 void TagInfo::add( std::string const& spelling ) {
10888 ++count;
10889 spellings.insert( spelling );
10890 }
10891
all() const10892 std::string TagInfo::all() const {
10893 size_t size = 0;
10894 for (auto const& spelling : spellings) {
10895 // Add 2 for the brackes
10896 size += spelling.size() + 2;
10897 }
10898
10899 std::string out; out.reserve(size);
10900 for (auto const& spelling : spellings) {
10901 out += '[';
10902 out += spelling;
10903 out += ']';
10904 }
10905 return out;
10906 }
10907
listTags(Config const & config)10908 std::size_t listTags( Config const& config ) {
10909 TestSpec testSpec = config.testSpec();
10910 if( config.hasTestFilters() )
10911 Catch::cout() << "Tags for matching test cases:\n";
10912 else {
10913 Catch::cout() << "All available tags:\n";
10914 }
10915
10916 std::map<std::string, TagInfo> tagCounts;
10917
10918 std::vector<TestCase> matchedTestCases = filterTests( getAllTestCasesSorted( config ), testSpec, config );
10919 for( auto const& testCase : matchedTestCases ) {
10920 for( auto const& tagName : testCase.getTestCaseInfo().tags ) {
10921 std::string lcaseTagName = toLower( tagName );
10922 auto countIt = tagCounts.find( lcaseTagName );
10923 if( countIt == tagCounts.end() )
10924 countIt = tagCounts.insert( std::make_pair( lcaseTagName, TagInfo() ) ).first;
10925 countIt->second.add( tagName );
10926 }
10927 }
10928
10929 for( auto const& tagCount : tagCounts ) {
10930 ReusableStringStream rss;
10931 rss << " " << std::setw(2) << tagCount.second.count << " ";
10932 auto str = rss.str();
10933 auto wrapper = Column( tagCount.second.all() )
10934 .initialIndent( 0 )
10935 .indent( str.size() )
10936 .width( CATCH_CONFIG_CONSOLE_WIDTH-10 );
10937 Catch::cout() << str << wrapper << '\n';
10938 }
10939 Catch::cout() << pluralise( tagCounts.size(), "tag" ) << '\n' << std::endl;
10940 return tagCounts.size();
10941 }
10942
listReporters()10943 std::size_t listReporters() {
10944 Catch::cout() << "Available reporters:\n";
10945 IReporterRegistry::FactoryMap const& factories = getRegistryHub().getReporterRegistry().getFactories();
10946 std::size_t maxNameLen = 0;
10947 for( auto const& factoryKvp : factories )
10948 maxNameLen = (std::max)( maxNameLen, factoryKvp.first.size() );
10949
10950 for( auto const& factoryKvp : factories ) {
10951 Catch::cout()
10952 << Column( factoryKvp.first + ":" )
10953 .indent(2)
10954 .width( 5+maxNameLen )
10955 + Column( factoryKvp.second->getDescription() )
10956 .initialIndent(0)
10957 .indent(2)
10958 .width( CATCH_CONFIG_CONSOLE_WIDTH - maxNameLen-8 )
10959 << "\n";
10960 }
10961 Catch::cout() << std::endl;
10962 return factories.size();
10963 }
10964
list(std::shared_ptr<Config> const & config)10965 Option<std::size_t> list( std::shared_ptr<Config> const& config ) {
10966 Option<std::size_t> listedCount;
10967 getCurrentMutableContext().setConfig( config );
10968 if( config->listTests() )
10969 listedCount = listedCount.valueOr(0) + listTests( *config );
10970 if( config->listTestNamesOnly() )
10971 listedCount = listedCount.valueOr(0) + listTestsNamesOnly( *config );
10972 if( config->listTags() )
10973 listedCount = listedCount.valueOr(0) + listTags( *config );
10974 if( config->listReporters() )
10975 listedCount = listedCount.valueOr(0) + listReporters();
10976 return listedCount;
10977 }
10978
10979 } // end namespace Catch
10980 // end catch_list.cpp
10981 // start catch_matchers.cpp
10982
10983 namespace Catch {
10984 namespace Matchers {
10985 namespace Impl {
10986
toString() const10987 std::string MatcherUntypedBase::toString() const {
10988 if( m_cachedToString.empty() )
10989 m_cachedToString = describe();
10990 return m_cachedToString;
10991 }
10992
10993 MatcherUntypedBase::~MatcherUntypedBase() = default;
10994
10995 } // namespace Impl
10996 } // namespace Matchers
10997
10998 using namespace Matchers;
10999 using Matchers::Impl::MatcherBase;
11000
11001 } // namespace Catch
11002 // end catch_matchers.cpp
11003 // start catch_matchers_floating.cpp
11004
11005 // start catch_polyfills.hpp
11006
11007 namespace Catch {
11008 bool isnan(float f);
11009 bool isnan(double d);
11010 }
11011
11012 // end catch_polyfills.hpp
11013 // start catch_to_string.hpp
11014
11015 #include <string>
11016
11017 namespace Catch {
11018 template <typename T>
to_string(T const & t)11019 std::string to_string(T const& t) {
11020 #if defined(CATCH_CONFIG_CPP11_TO_STRING)
11021 return std::to_string(t);
11022 #else
11023 ReusableStringStream rss;
11024 rss << t;
11025 return rss.str();
11026 #endif
11027 }
11028 } // end namespace Catch
11029
11030 // end catch_to_string.hpp
11031 #include <cstdlib>
11032 #include <cstdint>
11033 #include <cstring>
11034 #include <sstream>
11035 #include <iomanip>
11036 #include <limits>
11037
11038 namespace Catch {
11039 namespace Matchers {
11040 namespace Floating {
11041 enum class FloatingPointKind : uint8_t {
11042 Float,
11043 Double
11044 };
11045 }
11046 }
11047 }
11048
11049 namespace {
11050
11051 template <typename T>
11052 struct Converter;
11053
11054 template <>
11055 struct Converter<float> {
11056 static_assert(sizeof(float) == sizeof(int32_t), "Important ULP matcher assumption violated");
Converter__anon73d2dbed3111::Converter11057 Converter(float f) {
11058 std::memcpy(&i, &f, sizeof(f));
11059 }
11060 int32_t i;
11061 };
11062
11063 template <>
11064 struct Converter<double> {
11065 static_assert(sizeof(double) == sizeof(int64_t), "Important ULP matcher assumption violated");
Converter__anon73d2dbed3111::Converter11066 Converter(double d) {
11067 std::memcpy(&i, &d, sizeof(d));
11068 }
11069 int64_t i;
11070 };
11071
11072 template <typename T>
convert(T t)11073 auto convert(T t) -> Converter<T> {
11074 return Converter<T>(t);
11075 }
11076
11077 template <typename FP>
almostEqualUlps(FP lhs,FP rhs,int maxUlpDiff)11078 bool almostEqualUlps(FP lhs, FP rhs, int maxUlpDiff) {
11079 // Comparison with NaN should always be false.
11080 // This way we can rule it out before getting into the ugly details
11081 if (Catch::isnan(lhs) || Catch::isnan(rhs)) {
11082 return false;
11083 }
11084
11085 auto lc = convert(lhs);
11086 auto rc = convert(rhs);
11087
11088 if ((lc.i < 0) != (rc.i < 0)) {
11089 // Potentially we can have +0 and -0
11090 return lhs == rhs;
11091 }
11092
11093 auto ulpDiff = std::abs(lc.i - rc.i);
11094 return ulpDiff <= maxUlpDiff;
11095 }
11096
11097 template <typename FP>
step(FP start,FP direction,int steps)11098 FP step(FP start, FP direction, int steps) {
11099 for (int i = 0; i < steps; ++i) {
11100 start = std::nextafter(start, direction);
11101 }
11102 return start;
11103 }
11104
11105 } // end anonymous namespace
11106
11107 namespace Catch {
11108 namespace Matchers {
11109 namespace Floating {
WithinAbsMatcher(double target,double margin)11110 WithinAbsMatcher::WithinAbsMatcher(double target, double margin)
11111 :m_target{ target }, m_margin{ margin } {
11112 CATCH_ENFORCE(margin >= 0, "Invalid margin: " << margin << '.'
11113 << " Margin has to be non-negative.");
11114 }
11115
11116 // Performs equivalent check of std::fabs(lhs - rhs) <= margin
11117 // But without the subtraction to allow for INFINITY in comparison
match(double const & matchee) const11118 bool WithinAbsMatcher::match(double const& matchee) const {
11119 return (matchee + m_margin >= m_target) && (m_target + m_margin >= matchee);
11120 }
11121
describe() const11122 std::string WithinAbsMatcher::describe() const {
11123 return "is within " + ::Catch::Detail::stringify(m_margin) + " of " + ::Catch::Detail::stringify(m_target);
11124 }
11125
WithinUlpsMatcher(double target,int ulps,FloatingPointKind baseType)11126 WithinUlpsMatcher::WithinUlpsMatcher(double target, int ulps, FloatingPointKind baseType)
11127 :m_target{ target }, m_ulps{ ulps }, m_type{ baseType } {
11128 CATCH_ENFORCE(ulps >= 0, "Invalid ULP setting: " << ulps << '.'
11129 << " ULPs have to be non-negative.");
11130 }
11131
11132 #if defined(__clang__)
11133 #pragma clang diagnostic push
11134 // Clang <3.5 reports on the default branch in the switch below
11135 #pragma clang diagnostic ignored "-Wunreachable-code"
11136 #endif
11137
match(double const & matchee) const11138 bool WithinUlpsMatcher::match(double const& matchee) const {
11139 switch (m_type) {
11140 case FloatingPointKind::Float:
11141 return almostEqualUlps<float>(static_cast<float>(matchee), static_cast<float>(m_target), m_ulps);
11142 case FloatingPointKind::Double:
11143 return almostEqualUlps<double>(matchee, m_target, m_ulps);
11144 default:
11145 CATCH_INTERNAL_ERROR( "Unknown FloatingPointKind value" );
11146 }
11147 }
11148
11149 #if defined(__clang__)
11150 #pragma clang diagnostic pop
11151 #endif
11152
describe() const11153 std::string WithinUlpsMatcher::describe() const {
11154 std::stringstream ret;
11155
11156 ret << "is within " << m_ulps << " ULPs of " << ::Catch::Detail::stringify(m_target);
11157
11158 if (m_type == FloatingPointKind::Float) {
11159 ret << 'f';
11160 }
11161
11162 ret << " ([";
11163 ret << std::fixed << std::setprecision(std::numeric_limits<double>::max_digits10);
11164 if (m_type == FloatingPointKind::Double) {
11165 ret << step(m_target, static_cast<double>(-INFINITY), m_ulps)
11166 << ", "
11167 << step(m_target, static_cast<double>(INFINITY), m_ulps);
11168 } else {
11169 ret << step<float>(static_cast<float>(m_target), -INFINITY, m_ulps)
11170 << ", "
11171 << step<float>(static_cast<float>(m_target), INFINITY, m_ulps);
11172 }
11173 ret << "])";
11174
11175 return ret.str();
11176 //return "is within " + Catch::to_string(m_ulps) + " ULPs of " + ::Catch::Detail::stringify(m_target) + ((m_type == FloatingPointKind::Float)? "f" : "");
11177 }
11178
11179 }// namespace Floating
11180
WithinULP(double target,int maxUlpDiff)11181 Floating::WithinUlpsMatcher WithinULP(double target, int maxUlpDiff) {
11182 return Floating::WithinUlpsMatcher(target, maxUlpDiff, Floating::FloatingPointKind::Double);
11183 }
11184
WithinULP(float target,int maxUlpDiff)11185 Floating::WithinUlpsMatcher WithinULP(float target, int maxUlpDiff) {
11186 return Floating::WithinUlpsMatcher(target, maxUlpDiff, Floating::FloatingPointKind::Float);
11187 }
11188
WithinAbs(double target,double margin)11189 Floating::WithinAbsMatcher WithinAbs(double target, double margin) {
11190 return Floating::WithinAbsMatcher(target, margin);
11191 }
11192
11193 } // namespace Matchers
11194 } // namespace Catch
11195
11196 // end catch_matchers_floating.cpp
11197 // start catch_matchers_generic.cpp
11198
finalizeDescription(const std::string & desc)11199 std::string Catch::Matchers::Generic::Detail::finalizeDescription(const std::string& desc) {
11200 if (desc.empty()) {
11201 return "matches undescribed predicate";
11202 } else {
11203 return "matches predicate: \"" + desc + '"';
11204 }
11205 }
11206 // end catch_matchers_generic.cpp
11207 // start catch_matchers_string.cpp
11208
11209 #include <regex>
11210
11211 namespace Catch {
11212 namespace Matchers {
11213
11214 namespace StdString {
11215
CasedString(std::string const & str,CaseSensitive::Choice caseSensitivity)11216 CasedString::CasedString( std::string const& str, CaseSensitive::Choice caseSensitivity )
11217 : m_caseSensitivity( caseSensitivity ),
11218 m_str( adjustString( str ) )
11219 {}
adjustString(std::string const & str) const11220 std::string CasedString::adjustString( std::string const& str ) const {
11221 return m_caseSensitivity == CaseSensitive::No
11222 ? toLower( str )
11223 : str;
11224 }
caseSensitivitySuffix() const11225 std::string CasedString::caseSensitivitySuffix() const {
11226 return m_caseSensitivity == CaseSensitive::No
11227 ? " (case insensitive)"
11228 : std::string();
11229 }
11230
StringMatcherBase(std::string const & operation,CasedString const & comparator)11231 StringMatcherBase::StringMatcherBase( std::string const& operation, CasedString const& comparator )
11232 : m_comparator( comparator ),
11233 m_operation( operation ) {
11234 }
11235
describe() const11236 std::string StringMatcherBase::describe() const {
11237 std::string description;
11238 description.reserve(5 + m_operation.size() + m_comparator.m_str.size() +
11239 m_comparator.caseSensitivitySuffix().size());
11240 description += m_operation;
11241 description += ": \"";
11242 description += m_comparator.m_str;
11243 description += "\"";
11244 description += m_comparator.caseSensitivitySuffix();
11245 return description;
11246 }
11247
EqualsMatcher(CasedString const & comparator)11248 EqualsMatcher::EqualsMatcher( CasedString const& comparator ) : StringMatcherBase( "equals", comparator ) {}
11249
match(std::string const & source) const11250 bool EqualsMatcher::match( std::string const& source ) const {
11251 return m_comparator.adjustString( source ) == m_comparator.m_str;
11252 }
11253
ContainsMatcher(CasedString const & comparator)11254 ContainsMatcher::ContainsMatcher( CasedString const& comparator ) : StringMatcherBase( "contains", comparator ) {}
11255
match(std::string const & source) const11256 bool ContainsMatcher::match( std::string const& source ) const {
11257 return contains( m_comparator.adjustString( source ), m_comparator.m_str );
11258 }
11259
StartsWithMatcher(CasedString const & comparator)11260 StartsWithMatcher::StartsWithMatcher( CasedString const& comparator ) : StringMatcherBase( "starts with", comparator ) {}
11261
match(std::string const & source) const11262 bool StartsWithMatcher::match( std::string const& source ) const {
11263 return startsWith( m_comparator.adjustString( source ), m_comparator.m_str );
11264 }
11265
EndsWithMatcher(CasedString const & comparator)11266 EndsWithMatcher::EndsWithMatcher( CasedString const& comparator ) : StringMatcherBase( "ends with", comparator ) {}
11267
match(std::string const & source) const11268 bool EndsWithMatcher::match( std::string const& source ) const {
11269 return endsWith( m_comparator.adjustString( source ), m_comparator.m_str );
11270 }
11271
RegexMatcher(std::string regex,CaseSensitive::Choice caseSensitivity)11272 RegexMatcher::RegexMatcher(std::string regex, CaseSensitive::Choice caseSensitivity): m_regex(std::move(regex)), m_caseSensitivity(caseSensitivity) {}
11273
match(std::string const & matchee) const11274 bool RegexMatcher::match(std::string const& matchee) const {
11275 auto flags = std::regex::ECMAScript; // ECMAScript is the default syntax option anyway
11276 if (m_caseSensitivity == CaseSensitive::Choice::No) {
11277 flags |= std::regex::icase;
11278 }
11279 auto reg = std::regex(m_regex, flags);
11280 return std::regex_match(matchee, reg);
11281 }
11282
describe() const11283 std::string RegexMatcher::describe() const {
11284 return "matches " + ::Catch::Detail::stringify(m_regex) + ((m_caseSensitivity == CaseSensitive::Choice::Yes)? " case sensitively" : " case insensitively");
11285 }
11286
11287 } // namespace StdString
11288
Equals(std::string const & str,CaseSensitive::Choice caseSensitivity)11289 StdString::EqualsMatcher Equals( std::string const& str, CaseSensitive::Choice caseSensitivity ) {
11290 return StdString::EqualsMatcher( StdString::CasedString( str, caseSensitivity) );
11291 }
Contains(std::string const & str,CaseSensitive::Choice caseSensitivity)11292 StdString::ContainsMatcher Contains( std::string const& str, CaseSensitive::Choice caseSensitivity ) {
11293 return StdString::ContainsMatcher( StdString::CasedString( str, caseSensitivity) );
11294 }
EndsWith(std::string const & str,CaseSensitive::Choice caseSensitivity)11295 StdString::EndsWithMatcher EndsWith( std::string const& str, CaseSensitive::Choice caseSensitivity ) {
11296 return StdString::EndsWithMatcher( StdString::CasedString( str, caseSensitivity) );
11297 }
StartsWith(std::string const & str,CaseSensitive::Choice caseSensitivity)11298 StdString::StartsWithMatcher StartsWith( std::string const& str, CaseSensitive::Choice caseSensitivity ) {
11299 return StdString::StartsWithMatcher( StdString::CasedString( str, caseSensitivity) );
11300 }
11301
Matches(std::string const & regex,CaseSensitive::Choice caseSensitivity)11302 StdString::RegexMatcher Matches(std::string const& regex, CaseSensitive::Choice caseSensitivity) {
11303 return StdString::RegexMatcher(regex, caseSensitivity);
11304 }
11305
11306 } // namespace Matchers
11307 } // namespace Catch
11308 // end catch_matchers_string.cpp
11309 // start catch_message.cpp
11310
11311 // start catch_uncaught_exceptions.h
11312
11313 namespace Catch {
11314 bool uncaught_exceptions();
11315 } // end namespace Catch
11316
11317 // end catch_uncaught_exceptions.h
11318 #include <cassert>
11319 #include <stack>
11320
11321 namespace Catch {
11322
MessageInfo(StringRef const & _macroName,SourceLineInfo const & _lineInfo,ResultWas::OfType _type)11323 MessageInfo::MessageInfo( StringRef const& _macroName,
11324 SourceLineInfo const& _lineInfo,
11325 ResultWas::OfType _type )
11326 : macroName( _macroName ),
11327 lineInfo( _lineInfo ),
11328 type( _type ),
11329 sequence( ++globalCount )
11330 {}
11331
operator ==(MessageInfo const & other) const11332 bool MessageInfo::operator==( MessageInfo const& other ) const {
11333 return sequence == other.sequence;
11334 }
11335
operator <(MessageInfo const & other) const11336 bool MessageInfo::operator<( MessageInfo const& other ) const {
11337 return sequence < other.sequence;
11338 }
11339
11340 // This may need protecting if threading support is added
11341 unsigned int MessageInfo::globalCount = 0;
11342
11343 ////////////////////////////////////////////////////////////////////////////
11344
MessageBuilder(StringRef const & macroName,SourceLineInfo const & lineInfo,ResultWas::OfType type)11345 Catch::MessageBuilder::MessageBuilder( StringRef const& macroName,
11346 SourceLineInfo const& lineInfo,
11347 ResultWas::OfType type )
11348 :m_info(macroName, lineInfo, type) {}
11349
11350 ////////////////////////////////////////////////////////////////////////////
11351
ScopedMessage(MessageBuilder const & builder)11352 ScopedMessage::ScopedMessage( MessageBuilder const& builder )
11353 : m_info( builder.m_info ), m_moved()
11354 {
11355 m_info.message = builder.m_stream.str();
11356 getResultCapture().pushScopedMessage( m_info );
11357 }
11358
ScopedMessage(ScopedMessage && old)11359 ScopedMessage::ScopedMessage( ScopedMessage&& old )
11360 : m_info( old.m_info ), m_moved()
11361 {
11362 old.m_moved = true;
11363 }
11364
~ScopedMessage()11365 ScopedMessage::~ScopedMessage() {
11366 if ( !uncaught_exceptions() && !m_moved ){
11367 getResultCapture().popScopedMessage(m_info);
11368 }
11369 }
11370
Capturer(StringRef macroName,SourceLineInfo const & lineInfo,ResultWas::OfType resultType,StringRef names)11371 Capturer::Capturer( StringRef macroName, SourceLineInfo const& lineInfo, ResultWas::OfType resultType, StringRef names ) {
11372 auto trimmed = [&] (size_t start, size_t end) {
11373 while (names[start] == ',' || isspace(names[start])) {
11374 ++start;
11375 }
11376 while (names[end] == ',' || isspace(names[end])) {
11377 --end;
11378 }
11379 return names.substr(start, end - start + 1);
11380 };
11381 auto skipq = [&] (size_t start, char quote) {
11382 for (auto i = start + 1; i < names.size() ; ++i) {
11383 if (names[i] == quote)
11384 return i;
11385 if (names[i] == '\\')
11386 ++i;
11387 }
11388 CATCH_INTERNAL_ERROR("CAPTURE parsing encountered unmatched quote");
11389 };
11390
11391 size_t start = 0;
11392 std::stack<char> openings;
11393 for (size_t pos = 0; pos < names.size(); ++pos) {
11394 char c = names[pos];
11395 switch (c) {
11396 case '[':
11397 case '{':
11398 case '(':
11399 // It is basically impossible to disambiguate between
11400 // comparison and start of template args in this context
11401 // case '<':
11402 openings.push(c);
11403 break;
11404 case ']':
11405 case '}':
11406 case ')':
11407 // case '>':
11408 openings.pop();
11409 break;
11410 case '"':
11411 case '\'':
11412 pos = skipq(pos, c);
11413 break;
11414 case ',':
11415 if (start != pos && openings.size() == 0) {
11416 m_messages.emplace_back(macroName, lineInfo, resultType);
11417 m_messages.back().message = trimmed(start, pos);
11418 m_messages.back().message += " := ";
11419 start = pos;
11420 }
11421 }
11422 }
11423 assert(openings.size() == 0 && "Mismatched openings");
11424 m_messages.emplace_back(macroName, lineInfo, resultType);
11425 m_messages.back().message = trimmed(start, names.size() - 1);
11426 m_messages.back().message += " := ";
11427 }
~Capturer()11428 Capturer::~Capturer() {
11429 if ( !uncaught_exceptions() ){
11430 assert( m_captured == m_messages.size() );
11431 for( size_t i = 0; i < m_captured; ++i )
11432 m_resultCapture.popScopedMessage( m_messages[i] );
11433 }
11434 }
11435
captureValue(size_t index,std::string const & value)11436 void Capturer::captureValue( size_t index, std::string const& value ) {
11437 assert( index < m_messages.size() );
11438 m_messages[index].message += value;
11439 m_resultCapture.pushScopedMessage( m_messages[index] );
11440 m_captured++;
11441 }
11442
11443 } // end namespace Catch
11444 // end catch_message.cpp
11445 // start catch_output_redirect.cpp
11446
11447 // start catch_output_redirect.h
11448 #ifndef TWOBLUECUBES_CATCH_OUTPUT_REDIRECT_H
11449 #define TWOBLUECUBES_CATCH_OUTPUT_REDIRECT_H
11450
11451 #include <cstdio>
11452 #include <iosfwd>
11453 #include <string>
11454
11455 namespace Catch {
11456
11457 class RedirectedStream {
11458 std::ostream& m_originalStream;
11459 std::ostream& m_redirectionStream;
11460 std::streambuf* m_prevBuf;
11461
11462 public:
11463 RedirectedStream( std::ostream& originalStream, std::ostream& redirectionStream );
11464 ~RedirectedStream();
11465 };
11466
11467 class RedirectedStdOut {
11468 ReusableStringStream m_rss;
11469 RedirectedStream m_cout;
11470 public:
11471 RedirectedStdOut();
11472 auto str() const -> std::string;
11473 };
11474
11475 // StdErr has two constituent streams in C++, std::cerr and std::clog
11476 // This means that we need to redirect 2 streams into 1 to keep proper
11477 // order of writes
11478 class RedirectedStdErr {
11479 ReusableStringStream m_rss;
11480 RedirectedStream m_cerr;
11481 RedirectedStream m_clog;
11482 public:
11483 RedirectedStdErr();
11484 auto str() const -> std::string;
11485 };
11486
11487 class RedirectedStreams {
11488 public:
11489 RedirectedStreams(RedirectedStreams const&) = delete;
11490 RedirectedStreams& operator=(RedirectedStreams const&) = delete;
11491 RedirectedStreams(RedirectedStreams&&) = delete;
11492 RedirectedStreams& operator=(RedirectedStreams&&) = delete;
11493
11494 RedirectedStreams(std::string& redirectedCout, std::string& redirectedCerr);
11495 ~RedirectedStreams();
11496 private:
11497 std::string& m_redirectedCout;
11498 std::string& m_redirectedCerr;
11499 RedirectedStdOut m_redirectedStdOut;
11500 RedirectedStdErr m_redirectedStdErr;
11501 };
11502
11503 #if defined(CATCH_CONFIG_NEW_CAPTURE)
11504
11505 // Windows's implementation of std::tmpfile is terrible (it tries
11506 // to create a file inside system folder, thus requiring elevated
11507 // privileges for the binary), so we have to use tmpnam(_s) and
11508 // create the file ourselves there.
11509 class TempFile {
11510 public:
11511 TempFile(TempFile const&) = delete;
11512 TempFile& operator=(TempFile const&) = delete;
11513 TempFile(TempFile&&) = delete;
11514 TempFile& operator=(TempFile&&) = delete;
11515
11516 TempFile();
11517 ~TempFile();
11518
11519 std::FILE* getFile();
11520 std::string getContents();
11521
11522 private:
11523 std::FILE* m_file = nullptr;
11524 #if defined(_MSC_VER)
11525 char m_buffer[L_tmpnam] = { 0 };
11526 #endif
11527 };
11528
11529 class OutputRedirect {
11530 public:
11531 OutputRedirect(OutputRedirect const&) = delete;
11532 OutputRedirect& operator=(OutputRedirect const&) = delete;
11533 OutputRedirect(OutputRedirect&&) = delete;
11534 OutputRedirect& operator=(OutputRedirect&&) = delete;
11535
11536 OutputRedirect(std::string& stdout_dest, std::string& stderr_dest);
11537 ~OutputRedirect();
11538
11539 private:
11540 int m_originalStdout = -1;
11541 int m_originalStderr = -1;
11542 TempFile m_stdoutFile;
11543 TempFile m_stderrFile;
11544 std::string& m_stdoutDest;
11545 std::string& m_stderrDest;
11546 };
11547
11548 #endif
11549
11550 } // end namespace Catch
11551
11552 #endif // TWOBLUECUBES_CATCH_OUTPUT_REDIRECT_H
11553 // end catch_output_redirect.h
11554 #include <cstdio>
11555 #include <cstring>
11556 #include <fstream>
11557 #include <sstream>
11558 #include <stdexcept>
11559
11560 #if defined(CATCH_CONFIG_NEW_CAPTURE)
11561 #if defined(_MSC_VER)
11562 #include <io.h> //_dup and _dup2
11563 #define dup _dup
11564 #define dup2 _dup2
11565 #define fileno _fileno
11566 #else
11567 #include <unistd.h> // dup and dup2
11568 #endif
11569 #endif
11570
11571 namespace Catch {
11572
RedirectedStream(std::ostream & originalStream,std::ostream & redirectionStream)11573 RedirectedStream::RedirectedStream( std::ostream& originalStream, std::ostream& redirectionStream )
11574 : m_originalStream( originalStream ),
11575 m_redirectionStream( redirectionStream ),
11576 m_prevBuf( m_originalStream.rdbuf() )
11577 {
11578 m_originalStream.rdbuf( m_redirectionStream.rdbuf() );
11579 }
11580
~RedirectedStream()11581 RedirectedStream::~RedirectedStream() {
11582 m_originalStream.rdbuf( m_prevBuf );
11583 }
11584
RedirectedStdOut()11585 RedirectedStdOut::RedirectedStdOut() : m_cout( Catch::cout(), m_rss.get() ) {}
str() const11586 auto RedirectedStdOut::str() const -> std::string { return m_rss.str(); }
11587
RedirectedStdErr()11588 RedirectedStdErr::RedirectedStdErr()
11589 : m_cerr( Catch::cerr(), m_rss.get() ),
11590 m_clog( Catch::clog(), m_rss.get() )
11591 {}
str() const11592 auto RedirectedStdErr::str() const -> std::string { return m_rss.str(); }
11593
RedirectedStreams(std::string & redirectedCout,std::string & redirectedCerr)11594 RedirectedStreams::RedirectedStreams(std::string& redirectedCout, std::string& redirectedCerr)
11595 : m_redirectedCout(redirectedCout),
11596 m_redirectedCerr(redirectedCerr)
11597 {}
11598
~RedirectedStreams()11599 RedirectedStreams::~RedirectedStreams() {
11600 m_redirectedCout += m_redirectedStdOut.str();
11601 m_redirectedCerr += m_redirectedStdErr.str();
11602 }
11603
11604 #if defined(CATCH_CONFIG_NEW_CAPTURE)
11605
11606 #if defined(_MSC_VER)
TempFile()11607 TempFile::TempFile() {
11608 if (tmpnam_s(m_buffer)) {
11609 CATCH_RUNTIME_ERROR("Could not get a temp filename");
11610 }
11611 if (fopen_s(&m_file, m_buffer, "w")) {
11612 char buffer[100];
11613 if (strerror_s(buffer, errno)) {
11614 CATCH_RUNTIME_ERROR("Could not translate errno to a string");
11615 }
11616 CATCH_RUNTIME_ERROR("Could not open the temp file: '" << m_buffer << "' because: " << buffer);
11617 }
11618 }
11619 #else
TempFile()11620 TempFile::TempFile() {
11621 m_file = std::tmpfile();
11622 if (!m_file) {
11623 CATCH_RUNTIME_ERROR("Could not create a temp file.");
11624 }
11625 }
11626
11627 #endif
11628
~TempFile()11629 TempFile::~TempFile() {
11630 // TBD: What to do about errors here?
11631 std::fclose(m_file);
11632 // We manually create the file on Windows only, on Linux
11633 // it will be autodeleted
11634 #if defined(_MSC_VER)
11635 std::remove(m_buffer);
11636 #endif
11637 }
11638
getFile()11639 FILE* TempFile::getFile() {
11640 return m_file;
11641 }
11642
getContents()11643 std::string TempFile::getContents() {
11644 std::stringstream sstr;
11645 char buffer[100] = {};
11646 std::rewind(m_file);
11647 while (std::fgets(buffer, sizeof(buffer), m_file)) {
11648 sstr << buffer;
11649 }
11650 return sstr.str();
11651 }
11652
OutputRedirect(std::string & stdout_dest,std::string & stderr_dest)11653 OutputRedirect::OutputRedirect(std::string& stdout_dest, std::string& stderr_dest) :
11654 m_originalStdout(dup(1)),
11655 m_originalStderr(dup(2)),
11656 m_stdoutDest(stdout_dest),
11657 m_stderrDest(stderr_dest) {
11658 dup2(fileno(m_stdoutFile.getFile()), 1);
11659 dup2(fileno(m_stderrFile.getFile()), 2);
11660 }
11661
~OutputRedirect()11662 OutputRedirect::~OutputRedirect() {
11663 Catch::cout() << std::flush;
11664 fflush(stdout);
11665 // Since we support overriding these streams, we flush cerr
11666 // even though std::cerr is unbuffered
11667 Catch::cerr() << std::flush;
11668 Catch::clog() << std::flush;
11669 fflush(stderr);
11670
11671 dup2(m_originalStdout, 1);
11672 dup2(m_originalStderr, 2);
11673
11674 m_stdoutDest += m_stdoutFile.getContents();
11675 m_stderrDest += m_stderrFile.getContents();
11676 }
11677
11678 #endif // CATCH_CONFIG_NEW_CAPTURE
11679
11680 } // namespace Catch
11681
11682 #if defined(CATCH_CONFIG_NEW_CAPTURE)
11683 #if defined(_MSC_VER)
11684 #undef dup
11685 #undef dup2
11686 #undef fileno
11687 #endif
11688 #endif
11689 // end catch_output_redirect.cpp
11690 // start catch_polyfills.cpp
11691
11692 #include <cmath>
11693
11694 namespace Catch {
11695
11696 #if !defined(CATCH_CONFIG_POLYFILL_ISNAN)
isnan(float f)11697 bool isnan(float f) {
11698 return std::isnan(f);
11699 }
isnan(double d)11700 bool isnan(double d) {
11701 return std::isnan(d);
11702 }
11703 #else
11704 // For now we only use this for embarcadero
11705 bool isnan(float f) {
11706 return std::_isnan(f);
11707 }
11708 bool isnan(double d) {
11709 return std::_isnan(d);
11710 }
11711 #endif
11712
11713 } // end namespace Catch
11714 // end catch_polyfills.cpp
11715 // start catch_random_number_generator.cpp
11716
11717 namespace Catch {
11718
rng()11719 std::mt19937& rng() {
11720 static std::mt19937 s_rng;
11721 return s_rng;
11722 }
11723
seedRng(IConfig const & config)11724 void seedRng( IConfig const& config ) {
11725 if( config.rngSeed() != 0 ) {
11726 std::srand( config.rngSeed() );
11727 rng().seed( config.rngSeed() );
11728 }
11729 }
11730
rngSeed()11731 unsigned int rngSeed() {
11732 return getCurrentContext().getConfig()->rngSeed();
11733 }
11734 }
11735 // end catch_random_number_generator.cpp
11736 // start catch_registry_hub.cpp
11737
11738 // start catch_test_case_registry_impl.h
11739
11740 #include <vector>
11741 #include <set>
11742 #include <algorithm>
11743 #include <ios>
11744
11745 namespace Catch {
11746
11747 class TestCase;
11748 struct IConfig;
11749
11750 std::vector<TestCase> sortTests( IConfig const& config, std::vector<TestCase> const& unsortedTestCases );
11751
11752 bool isThrowSafe( TestCase const& testCase, IConfig const& config );
11753 bool matchTest( TestCase const& testCase, TestSpec const& testSpec, IConfig const& config );
11754
11755 void enforceNoDuplicateTestCases( std::vector<TestCase> const& functions );
11756
11757 std::vector<TestCase> filterTests( std::vector<TestCase> const& testCases, TestSpec const& testSpec, IConfig const& config );
11758 std::vector<TestCase> const& getAllTestCasesSorted( IConfig const& config );
11759
11760 class TestRegistry : public ITestCaseRegistry {
11761 public:
11762 virtual ~TestRegistry() = default;
11763
11764 virtual void registerTest( TestCase const& testCase );
11765
11766 std::vector<TestCase> const& getAllTests() const override;
11767 std::vector<TestCase> const& getAllTestsSorted( IConfig const& config ) const override;
11768
11769 private:
11770 std::vector<TestCase> m_functions;
11771 mutable RunTests::InWhatOrder m_currentSortOrder = RunTests::InDeclarationOrder;
11772 mutable std::vector<TestCase> m_sortedFunctions;
11773 std::size_t m_unnamedCount = 0;
11774 std::ios_base::Init m_ostreamInit; // Forces cout/ cerr to be initialised
11775 };
11776
11777 ///////////////////////////////////////////////////////////////////////////
11778
11779 class TestInvokerAsFunction : public ITestInvoker {
11780 void(*m_testAsFunction)();
11781 public:
11782 TestInvokerAsFunction( void(*testAsFunction)() ) noexcept;
11783
11784 void invoke() const override;
11785 };
11786
11787 std::string extractClassName( StringRef const& classOrQualifiedMethodName );
11788
11789 ///////////////////////////////////////////////////////////////////////////
11790
11791 } // end namespace Catch
11792
11793 // end catch_test_case_registry_impl.h
11794 // start catch_reporter_registry.h
11795
11796 #include <map>
11797
11798 namespace Catch {
11799
11800 class ReporterRegistry : public IReporterRegistry {
11801
11802 public:
11803
11804 ~ReporterRegistry() override;
11805
11806 IStreamingReporterPtr create( std::string const& name, IConfigPtr const& config ) const override;
11807
11808 void registerReporter( std::string const& name, IReporterFactoryPtr const& factory );
11809 void registerListener( IReporterFactoryPtr const& factory );
11810
11811 FactoryMap const& getFactories() const override;
11812 Listeners const& getListeners() const override;
11813
11814 private:
11815 FactoryMap m_factories;
11816 Listeners m_listeners;
11817 };
11818 }
11819
11820 // end catch_reporter_registry.h
11821 // start catch_tag_alias_registry.h
11822
11823 // start catch_tag_alias.h
11824
11825 #include <string>
11826
11827 namespace Catch {
11828
11829 struct TagAlias {
11830 TagAlias(std::string const& _tag, SourceLineInfo _lineInfo);
11831
11832 std::string tag;
11833 SourceLineInfo lineInfo;
11834 };
11835
11836 } // end namespace Catch
11837
11838 // end catch_tag_alias.h
11839 #include <map>
11840
11841 namespace Catch {
11842
11843 class TagAliasRegistry : public ITagAliasRegistry {
11844 public:
11845 ~TagAliasRegistry() override;
11846 TagAlias const* find( std::string const& alias ) const override;
11847 std::string expandAliases( std::string const& unexpandedTestSpec ) const override;
11848 void add( std::string const& alias, std::string const& tag, SourceLineInfo const& lineInfo );
11849
11850 private:
11851 std::map<std::string, TagAlias> m_registry;
11852 };
11853
11854 } // end namespace Catch
11855
11856 // end catch_tag_alias_registry.h
11857 // start catch_startup_exception_registry.h
11858
11859 #include <vector>
11860 #include <exception>
11861
11862 namespace Catch {
11863
11864 class StartupExceptionRegistry {
11865 public:
11866 void add(std::exception_ptr const& exception) noexcept;
11867 std::vector<std::exception_ptr> const& getExceptions() const noexcept;
11868 private:
11869 std::vector<std::exception_ptr> m_exceptions;
11870 };
11871
11872 } // end namespace Catch
11873
11874 // end catch_startup_exception_registry.h
11875 // start catch_singletons.hpp
11876
11877 namespace Catch {
11878
11879 struct ISingleton {
11880 virtual ~ISingleton();
11881 };
11882
11883 void addSingleton( ISingleton* singleton );
11884 void cleanupSingletons();
11885
11886 template<typename SingletonImplT, typename InterfaceT = SingletonImplT, typename MutableInterfaceT = InterfaceT>
11887 class Singleton : SingletonImplT, public ISingleton {
11888
getInternal()11889 static auto getInternal() -> Singleton* {
11890 static Singleton* s_instance = nullptr;
11891 if( !s_instance ) {
11892 s_instance = new Singleton;
11893 addSingleton( s_instance );
11894 }
11895 return s_instance;
11896 }
11897
11898 public:
get()11899 static auto get() -> InterfaceT const& {
11900 return *getInternal();
11901 }
getMutable()11902 static auto getMutable() -> MutableInterfaceT& {
11903 return *getInternal();
11904 }
11905 };
11906
11907 } // namespace Catch
11908
11909 // end catch_singletons.hpp
11910 namespace Catch {
11911
11912 namespace {
11913
11914 class RegistryHub : public IRegistryHub, public IMutableRegistryHub,
11915 private NonCopyable {
11916
11917 public: // IRegistryHub
11918 RegistryHub() = default;
getReporterRegistry() const11919 IReporterRegistry const& getReporterRegistry() const override {
11920 return m_reporterRegistry;
11921 }
getTestCaseRegistry() const11922 ITestCaseRegistry const& getTestCaseRegistry() const override {
11923 return m_testCaseRegistry;
11924 }
getExceptionTranslatorRegistry() const11925 IExceptionTranslatorRegistry const& getExceptionTranslatorRegistry() const override {
11926 return m_exceptionTranslatorRegistry;
11927 }
getTagAliasRegistry() const11928 ITagAliasRegistry const& getTagAliasRegistry() const override {
11929 return m_tagAliasRegistry;
11930 }
getStartupExceptionRegistry() const11931 StartupExceptionRegistry const& getStartupExceptionRegistry() const override {
11932 return m_exceptionRegistry;
11933 }
11934
11935 public: // IMutableRegistryHub
registerReporter(std::string const & name,IReporterFactoryPtr const & factory)11936 void registerReporter( std::string const& name, IReporterFactoryPtr const& factory ) override {
11937 m_reporterRegistry.registerReporter( name, factory );
11938 }
registerListener(IReporterFactoryPtr const & factory)11939 void registerListener( IReporterFactoryPtr const& factory ) override {
11940 m_reporterRegistry.registerListener( factory );
11941 }
registerTest(TestCase const & testInfo)11942 void registerTest( TestCase const& testInfo ) override {
11943 m_testCaseRegistry.registerTest( testInfo );
11944 }
registerTranslator(const IExceptionTranslator * translator)11945 void registerTranslator( const IExceptionTranslator* translator ) override {
11946 m_exceptionTranslatorRegistry.registerTranslator( translator );
11947 }
registerTagAlias(std::string const & alias,std::string const & tag,SourceLineInfo const & lineInfo)11948 void registerTagAlias( std::string const& alias, std::string const& tag, SourceLineInfo const& lineInfo ) override {
11949 m_tagAliasRegistry.add( alias, tag, lineInfo );
11950 }
registerStartupException()11951 void registerStartupException() noexcept override {
11952 m_exceptionRegistry.add(std::current_exception());
11953 }
getMutableEnumValuesRegistry()11954 IMutableEnumValuesRegistry& getMutableEnumValuesRegistry() override {
11955 return m_enumValuesRegistry;
11956 }
11957
11958 private:
11959 TestRegistry m_testCaseRegistry;
11960 ReporterRegistry m_reporterRegistry;
11961 ExceptionTranslatorRegistry m_exceptionTranslatorRegistry;
11962 TagAliasRegistry m_tagAliasRegistry;
11963 StartupExceptionRegistry m_exceptionRegistry;
11964 Detail::EnumValuesRegistry m_enumValuesRegistry;
11965 };
11966 }
11967
11968 using RegistryHubSingleton = Singleton<RegistryHub, IRegistryHub, IMutableRegistryHub>;
11969
getRegistryHub()11970 IRegistryHub const& getRegistryHub() {
11971 return RegistryHubSingleton::get();
11972 }
getMutableRegistryHub()11973 IMutableRegistryHub& getMutableRegistryHub() {
11974 return RegistryHubSingleton::getMutable();
11975 }
cleanUp()11976 void cleanUp() {
11977 cleanupSingletons();
11978 cleanUpContext();
11979 }
translateActiveException()11980 std::string translateActiveException() {
11981 return getRegistryHub().getExceptionTranslatorRegistry().translateActiveException();
11982 }
11983
11984 } // end namespace Catch
11985 // end catch_registry_hub.cpp
11986 // start catch_reporter_registry.cpp
11987
11988 namespace Catch {
11989
11990 ReporterRegistry::~ReporterRegistry() = default;
11991
create(std::string const & name,IConfigPtr const & config) const11992 IStreamingReporterPtr ReporterRegistry::create( std::string const& name, IConfigPtr const& config ) const {
11993 auto it = m_factories.find( name );
11994 if( it == m_factories.end() )
11995 return nullptr;
11996 return it->second->create( ReporterConfig( config ) );
11997 }
11998
registerReporter(std::string const & name,IReporterFactoryPtr const & factory)11999 void ReporterRegistry::registerReporter( std::string const& name, IReporterFactoryPtr const& factory ) {
12000 m_factories.emplace(name, factory);
12001 }
registerListener(IReporterFactoryPtr const & factory)12002 void ReporterRegistry::registerListener( IReporterFactoryPtr const& factory ) {
12003 m_listeners.push_back( factory );
12004 }
12005
getFactories() const12006 IReporterRegistry::FactoryMap const& ReporterRegistry::getFactories() const {
12007 return m_factories;
12008 }
getListeners() const12009 IReporterRegistry::Listeners const& ReporterRegistry::getListeners() const {
12010 return m_listeners;
12011 }
12012
12013 }
12014 // end catch_reporter_registry.cpp
12015 // start catch_result_type.cpp
12016
12017 namespace Catch {
12018
isOk(ResultWas::OfType resultType)12019 bool isOk( ResultWas::OfType resultType ) {
12020 return ( resultType & ResultWas::FailureBit ) == 0;
12021 }
isJustInfo(int flags)12022 bool isJustInfo( int flags ) {
12023 return flags == ResultWas::Info;
12024 }
12025
operator |(ResultDisposition::Flags lhs,ResultDisposition::Flags rhs)12026 ResultDisposition::Flags operator | ( ResultDisposition::Flags lhs, ResultDisposition::Flags rhs ) {
12027 return static_cast<ResultDisposition::Flags>( static_cast<int>( lhs ) | static_cast<int>( rhs ) );
12028 }
12029
shouldContinueOnFailure(int flags)12030 bool shouldContinueOnFailure( int flags ) { return ( flags & ResultDisposition::ContinueOnFailure ) != 0; }
shouldSuppressFailure(int flags)12031 bool shouldSuppressFailure( int flags ) { return ( flags & ResultDisposition::SuppressFail ) != 0; }
12032
12033 } // end namespace Catch
12034 // end catch_result_type.cpp
12035 // start catch_run_context.cpp
12036
12037 #include <cassert>
12038 #include <algorithm>
12039 #include <sstream>
12040
12041 namespace Catch {
12042
12043 namespace Generators {
12044 struct GeneratorTracker : TestCaseTracking::TrackerBase, IGeneratorTracker {
12045 GeneratorBasePtr m_generator;
12046
GeneratorTrackerCatch::Generators::GeneratorTracker12047 GeneratorTracker( TestCaseTracking::NameAndLocation const& nameAndLocation, TrackerContext& ctx, ITracker* parent )
12048 : TrackerBase( nameAndLocation, ctx, parent )
12049 {}
12050 ~GeneratorTracker();
12051
acquireCatch::Generators::GeneratorTracker12052 static GeneratorTracker& acquire( TrackerContext& ctx, TestCaseTracking::NameAndLocation const& nameAndLocation ) {
12053 std::shared_ptr<GeneratorTracker> tracker;
12054
12055 ITracker& currentTracker = ctx.currentTracker();
12056 if( TestCaseTracking::ITrackerPtr childTracker = currentTracker.findChild( nameAndLocation ) ) {
12057 assert( childTracker );
12058 assert( childTracker->isGeneratorTracker() );
12059 tracker = std::static_pointer_cast<GeneratorTracker>( childTracker );
12060 }
12061 else {
12062 tracker = std::make_shared<GeneratorTracker>( nameAndLocation, ctx, ¤tTracker );
12063 currentTracker.addChild( tracker );
12064 }
12065
12066 if( !ctx.completedCycle() && !tracker->isComplete() ) {
12067 tracker->open();
12068 }
12069
12070 return *tracker;
12071 }
12072
12073 // TrackerBase interface
isGeneratorTrackerCatch::Generators::GeneratorTracker12074 bool isGeneratorTracker() const override { return true; }
hasGeneratorCatch::Generators::GeneratorTracker12075 auto hasGenerator() const -> bool override {
12076 return !!m_generator;
12077 }
closeCatch::Generators::GeneratorTracker12078 void close() override {
12079 TrackerBase::close();
12080 // Generator interface only finds out if it has another item on atual move
12081 if (m_runState == CompletedSuccessfully && m_generator->next()) {
12082 m_children.clear();
12083 m_runState = Executing;
12084 }
12085 }
12086
12087 // IGeneratorTracker interface
getGeneratorCatch::Generators::GeneratorTracker12088 auto getGenerator() const -> GeneratorBasePtr const& override {
12089 return m_generator;
12090 }
setGeneratorCatch::Generators::GeneratorTracker12091 void setGenerator( GeneratorBasePtr&& generator ) override {
12092 m_generator = std::move( generator );
12093 }
12094 };
~GeneratorTracker()12095 GeneratorTracker::~GeneratorTracker() {}
12096 }
12097
RunContext(IConfigPtr const & _config,IStreamingReporterPtr && reporter)12098 RunContext::RunContext(IConfigPtr const& _config, IStreamingReporterPtr&& reporter)
12099 : m_runInfo(_config->name()),
12100 m_context(getCurrentMutableContext()),
12101 m_config(_config),
12102 m_reporter(std::move(reporter)),
12103 m_lastAssertionInfo{ StringRef(), SourceLineInfo("",0), StringRef(), ResultDisposition::Normal },
12104 m_includeSuccessfulResults( m_config->includeSuccessfulResults() || m_reporter->getPreferences().shouldReportAllAssertions )
12105 {
12106 m_context.setRunner(this);
12107 m_context.setConfig(m_config);
12108 m_context.setResultCapture(this);
12109 m_reporter->testRunStarting(m_runInfo);
12110 }
12111
~RunContext()12112 RunContext::~RunContext() {
12113 m_reporter->testRunEnded(TestRunStats(m_runInfo, m_totals, aborting()));
12114 }
12115
testGroupStarting(std::string const & testSpec,std::size_t groupIndex,std::size_t groupsCount)12116 void RunContext::testGroupStarting(std::string const& testSpec, std::size_t groupIndex, std::size_t groupsCount) {
12117 m_reporter->testGroupStarting(GroupInfo(testSpec, groupIndex, groupsCount));
12118 }
12119
testGroupEnded(std::string const & testSpec,Totals const & totals,std::size_t groupIndex,std::size_t groupsCount)12120 void RunContext::testGroupEnded(std::string const& testSpec, Totals const& totals, std::size_t groupIndex, std::size_t groupsCount) {
12121 m_reporter->testGroupEnded(TestGroupStats(GroupInfo(testSpec, groupIndex, groupsCount), totals, aborting()));
12122 }
12123
runTest(TestCase const & testCase)12124 Totals RunContext::runTest(TestCase const& testCase) {
12125 Totals prevTotals = m_totals;
12126
12127 std::string redirectedCout;
12128 std::string redirectedCerr;
12129
12130 auto const& testInfo = testCase.getTestCaseInfo();
12131
12132 m_reporter->testCaseStarting(testInfo);
12133
12134 m_activeTestCase = &testCase;
12135
12136 ITracker& rootTracker = m_trackerContext.startRun();
12137 assert(rootTracker.isSectionTracker());
12138 static_cast<SectionTracker&>(rootTracker).addInitialFilters(m_config->getSectionsToRun());
12139 do {
12140 m_trackerContext.startCycle();
12141 m_testCaseTracker = &SectionTracker::acquire(m_trackerContext, TestCaseTracking::NameAndLocation(testInfo.name, testInfo.lineInfo));
12142 runCurrentTest(redirectedCout, redirectedCerr);
12143 } while (!m_testCaseTracker->isSuccessfullyCompleted() && !aborting());
12144
12145 Totals deltaTotals = m_totals.delta(prevTotals);
12146 if (testInfo.expectedToFail() && deltaTotals.testCases.passed > 0) {
12147 deltaTotals.assertions.failed++;
12148 deltaTotals.testCases.passed--;
12149 deltaTotals.testCases.failed++;
12150 }
12151 m_totals.testCases += deltaTotals.testCases;
12152 m_reporter->testCaseEnded(TestCaseStats(testInfo,
12153 deltaTotals,
12154 redirectedCout,
12155 redirectedCerr,
12156 aborting()));
12157
12158 m_activeTestCase = nullptr;
12159 m_testCaseTracker = nullptr;
12160
12161 return deltaTotals;
12162 }
12163
config() const12164 IConfigPtr RunContext::config() const {
12165 return m_config;
12166 }
12167
reporter() const12168 IStreamingReporter& RunContext::reporter() const {
12169 return *m_reporter;
12170 }
12171
assertionEnded(AssertionResult const & result)12172 void RunContext::assertionEnded(AssertionResult const & result) {
12173 if (result.getResultType() == ResultWas::Ok) {
12174 m_totals.assertions.passed++;
12175 m_lastAssertionPassed = true;
12176 } else if (!result.isOk()) {
12177 m_lastAssertionPassed = false;
12178 if( m_activeTestCase->getTestCaseInfo().okToFail() )
12179 m_totals.assertions.failedButOk++;
12180 else
12181 m_totals.assertions.failed++;
12182 }
12183 else {
12184 m_lastAssertionPassed = true;
12185 }
12186
12187 // We have no use for the return value (whether messages should be cleared), because messages were made scoped
12188 // and should be let to clear themselves out.
12189 static_cast<void>(m_reporter->assertionEnded(AssertionStats(result, m_messages, m_totals)));
12190
12191 if (result.getResultType() != ResultWas::Warning)
12192 m_messageScopes.clear();
12193
12194 // Reset working state
12195 resetAssertionInfo();
12196 m_lastResult = result;
12197 }
resetAssertionInfo()12198 void RunContext::resetAssertionInfo() {
12199 m_lastAssertionInfo.macroName = StringRef();
12200 m_lastAssertionInfo.capturedExpression = "{Unknown expression after the reported line}"_sr;
12201 }
12202
sectionStarted(SectionInfo const & sectionInfo,Counts & assertions)12203 bool RunContext::sectionStarted(SectionInfo const & sectionInfo, Counts & assertions) {
12204 ITracker& sectionTracker = SectionTracker::acquire(m_trackerContext, TestCaseTracking::NameAndLocation(sectionInfo.name, sectionInfo.lineInfo));
12205 if (!sectionTracker.isOpen())
12206 return false;
12207 m_activeSections.push_back(§ionTracker);
12208
12209 m_lastAssertionInfo.lineInfo = sectionInfo.lineInfo;
12210
12211 m_reporter->sectionStarting(sectionInfo);
12212
12213 assertions = m_totals.assertions;
12214
12215 return true;
12216 }
acquireGeneratorTracker(SourceLineInfo const & lineInfo)12217 auto RunContext::acquireGeneratorTracker( SourceLineInfo const& lineInfo ) -> IGeneratorTracker& {
12218 using namespace Generators;
12219 GeneratorTracker& tracker = GeneratorTracker::acquire( m_trackerContext, TestCaseTracking::NameAndLocation( "generator", lineInfo ) );
12220 assert( tracker.isOpen() );
12221 m_lastAssertionInfo.lineInfo = lineInfo;
12222 return tracker;
12223 }
12224
testForMissingAssertions(Counts & assertions)12225 bool RunContext::testForMissingAssertions(Counts& assertions) {
12226 if (assertions.total() != 0)
12227 return false;
12228 if (!m_config->warnAboutMissingAssertions())
12229 return false;
12230 if (m_trackerContext.currentTracker().hasChildren())
12231 return false;
12232 m_totals.assertions.failed++;
12233 assertions.failed++;
12234 return true;
12235 }
12236
sectionEnded(SectionEndInfo const & endInfo)12237 void RunContext::sectionEnded(SectionEndInfo const & endInfo) {
12238 Counts assertions = m_totals.assertions - endInfo.prevAssertions;
12239 bool missingAssertions = testForMissingAssertions(assertions);
12240
12241 if (!m_activeSections.empty()) {
12242 m_activeSections.back()->close();
12243 m_activeSections.pop_back();
12244 }
12245
12246 m_reporter->sectionEnded(SectionStats(endInfo.sectionInfo, assertions, endInfo.durationInSeconds, missingAssertions));
12247 m_messages.clear();
12248 m_messageScopes.clear();
12249 }
12250
sectionEndedEarly(SectionEndInfo const & endInfo)12251 void RunContext::sectionEndedEarly(SectionEndInfo const & endInfo) {
12252 if (m_unfinishedSections.empty())
12253 m_activeSections.back()->fail();
12254 else
12255 m_activeSections.back()->close();
12256 m_activeSections.pop_back();
12257
12258 m_unfinishedSections.push_back(endInfo);
12259 }
12260
12261 #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
benchmarkPreparing(std::string const & name)12262 void RunContext::benchmarkPreparing(std::string const& name) {
12263 m_reporter->benchmarkPreparing(name);
12264 }
benchmarkStarting(BenchmarkInfo const & info)12265 void RunContext::benchmarkStarting( BenchmarkInfo const& info ) {
12266 m_reporter->benchmarkStarting( info );
12267 }
benchmarkEnded(BenchmarkStats<> const & stats)12268 void RunContext::benchmarkEnded( BenchmarkStats<> const& stats ) {
12269 m_reporter->benchmarkEnded( stats );
12270 }
benchmarkFailed(std::string const & error)12271 void RunContext::benchmarkFailed(std::string const & error) {
12272 m_reporter->benchmarkFailed(error);
12273 }
12274 #endif // CATCH_CONFIG_ENABLE_BENCHMARKING
12275
pushScopedMessage(MessageInfo const & message)12276 void RunContext::pushScopedMessage(MessageInfo const & message) {
12277 m_messages.push_back(message);
12278 }
12279
popScopedMessage(MessageInfo const & message)12280 void RunContext::popScopedMessage(MessageInfo const & message) {
12281 m_messages.erase(std::remove(m_messages.begin(), m_messages.end(), message), m_messages.end());
12282 }
12283
emplaceUnscopedMessage(MessageBuilder const & builder)12284 void RunContext::emplaceUnscopedMessage( MessageBuilder const& builder ) {
12285 m_messageScopes.emplace_back( builder );
12286 }
12287
getCurrentTestName() const12288 std::string RunContext::getCurrentTestName() const {
12289 return m_activeTestCase
12290 ? m_activeTestCase->getTestCaseInfo().name
12291 : std::string();
12292 }
12293
getLastResult() const12294 const AssertionResult * RunContext::getLastResult() const {
12295 return &(*m_lastResult);
12296 }
12297
exceptionEarlyReported()12298 void RunContext::exceptionEarlyReported() {
12299 m_shouldReportUnexpected = false;
12300 }
12301
handleFatalErrorCondition(StringRef message)12302 void RunContext::handleFatalErrorCondition( StringRef message ) {
12303 // First notify reporter that bad things happened
12304 m_reporter->fatalErrorEncountered(message);
12305
12306 // Don't rebuild the result -- the stringification itself can cause more fatal errors
12307 // Instead, fake a result data.
12308 AssertionResultData tempResult( ResultWas::FatalErrorCondition, { false } );
12309 tempResult.message = message;
12310 AssertionResult result(m_lastAssertionInfo, tempResult);
12311
12312 assertionEnded(result);
12313
12314 handleUnfinishedSections();
12315
12316 // Recreate section for test case (as we will lose the one that was in scope)
12317 auto const& testCaseInfo = m_activeTestCase->getTestCaseInfo();
12318 SectionInfo testCaseSection(testCaseInfo.lineInfo, testCaseInfo.name);
12319
12320 Counts assertions;
12321 assertions.failed = 1;
12322 SectionStats testCaseSectionStats(testCaseSection, assertions, 0, false);
12323 m_reporter->sectionEnded(testCaseSectionStats);
12324
12325 auto const& testInfo = m_activeTestCase->getTestCaseInfo();
12326
12327 Totals deltaTotals;
12328 deltaTotals.testCases.failed = 1;
12329 deltaTotals.assertions.failed = 1;
12330 m_reporter->testCaseEnded(TestCaseStats(testInfo,
12331 deltaTotals,
12332 std::string(),
12333 std::string(),
12334 false));
12335 m_totals.testCases.failed++;
12336 testGroupEnded(std::string(), m_totals, 1, 1);
12337 m_reporter->testRunEnded(TestRunStats(m_runInfo, m_totals, false));
12338 }
12339
lastAssertionPassed()12340 bool RunContext::lastAssertionPassed() {
12341 return m_lastAssertionPassed;
12342 }
12343
assertionPassed()12344 void RunContext::assertionPassed() {
12345 m_lastAssertionPassed = true;
12346 ++m_totals.assertions.passed;
12347 resetAssertionInfo();
12348 m_messageScopes.clear();
12349 }
12350
aborting() const12351 bool RunContext::aborting() const {
12352 return m_totals.assertions.failed >= static_cast<std::size_t>(m_config->abortAfter());
12353 }
12354
runCurrentTest(std::string & redirectedCout,std::string & redirectedCerr)12355 void RunContext::runCurrentTest(std::string & redirectedCout, std::string & redirectedCerr) {
12356 auto const& testCaseInfo = m_activeTestCase->getTestCaseInfo();
12357 SectionInfo testCaseSection(testCaseInfo.lineInfo, testCaseInfo.name);
12358 m_reporter->sectionStarting(testCaseSection);
12359 Counts prevAssertions = m_totals.assertions;
12360 double duration = 0;
12361 m_shouldReportUnexpected = true;
12362 m_lastAssertionInfo = { "TEST_CASE"_sr, testCaseInfo.lineInfo, StringRef(), ResultDisposition::Normal };
12363
12364 seedRng(*m_config);
12365
12366 Timer timer;
12367 CATCH_TRY {
12368 if (m_reporter->getPreferences().shouldRedirectStdOut) {
12369 #if !defined(CATCH_CONFIG_EXPERIMENTAL_REDIRECT)
12370 RedirectedStreams redirectedStreams(redirectedCout, redirectedCerr);
12371
12372 timer.start();
12373 invokeActiveTestCase();
12374 #else
12375 OutputRedirect r(redirectedCout, redirectedCerr);
12376 timer.start();
12377 invokeActiveTestCase();
12378 #endif
12379 } else {
12380 timer.start();
12381 invokeActiveTestCase();
12382 }
12383 duration = timer.getElapsedSeconds();
12384 } CATCH_CATCH_ANON (TestFailureException&) {
12385 // This just means the test was aborted due to failure
12386 } CATCH_CATCH_ALL {
12387 // Under CATCH_CONFIG_FAST_COMPILE, unexpected exceptions under REQUIRE assertions
12388 // are reported without translation at the point of origin.
12389 if( m_shouldReportUnexpected ) {
12390 AssertionReaction dummyReaction;
12391 handleUnexpectedInflightException( m_lastAssertionInfo, translateActiveException(), dummyReaction );
12392 }
12393 }
12394 Counts assertions = m_totals.assertions - prevAssertions;
12395 bool missingAssertions = testForMissingAssertions(assertions);
12396
12397 m_testCaseTracker->close();
12398 handleUnfinishedSections();
12399 m_messages.clear();
12400 m_messageScopes.clear();
12401
12402 SectionStats testCaseSectionStats(testCaseSection, assertions, duration, missingAssertions);
12403 m_reporter->sectionEnded(testCaseSectionStats);
12404 }
12405
invokeActiveTestCase()12406 void RunContext::invokeActiveTestCase() {
12407 FatalConditionHandler fatalConditionHandler; // Handle signals
12408 m_activeTestCase->invoke();
12409 fatalConditionHandler.reset();
12410 }
12411
handleUnfinishedSections()12412 void RunContext::handleUnfinishedSections() {
12413 // If sections ended prematurely due to an exception we stored their
12414 // infos here so we can tear them down outside the unwind process.
12415 for (auto it = m_unfinishedSections.rbegin(),
12416 itEnd = m_unfinishedSections.rend();
12417 it != itEnd;
12418 ++it)
12419 sectionEnded(*it);
12420 m_unfinishedSections.clear();
12421 }
12422
handleExpr(AssertionInfo const & info,ITransientExpression const & expr,AssertionReaction & reaction)12423 void RunContext::handleExpr(
12424 AssertionInfo const& info,
12425 ITransientExpression const& expr,
12426 AssertionReaction& reaction
12427 ) {
12428 m_reporter->assertionStarting( info );
12429
12430 bool negated = isFalseTest( info.resultDisposition );
12431 bool result = expr.getResult() != negated;
12432
12433 if( result ) {
12434 if (!m_includeSuccessfulResults) {
12435 assertionPassed();
12436 }
12437 else {
12438 reportExpr(info, ResultWas::Ok, &expr, negated);
12439 }
12440 }
12441 else {
12442 reportExpr(info, ResultWas::ExpressionFailed, &expr, negated );
12443 populateReaction( reaction );
12444 }
12445 }
reportExpr(AssertionInfo const & info,ResultWas::OfType resultType,ITransientExpression const * expr,bool negated)12446 void RunContext::reportExpr(
12447 AssertionInfo const &info,
12448 ResultWas::OfType resultType,
12449 ITransientExpression const *expr,
12450 bool negated ) {
12451
12452 m_lastAssertionInfo = info;
12453 AssertionResultData data( resultType, LazyExpression( negated ) );
12454
12455 AssertionResult assertionResult{ info, data };
12456 assertionResult.m_resultData.lazyExpression.m_transientExpression = expr;
12457
12458 assertionEnded( assertionResult );
12459 }
12460
handleMessage(AssertionInfo const & info,ResultWas::OfType resultType,StringRef const & message,AssertionReaction & reaction)12461 void RunContext::handleMessage(
12462 AssertionInfo const& info,
12463 ResultWas::OfType resultType,
12464 StringRef const& message,
12465 AssertionReaction& reaction
12466 ) {
12467 m_reporter->assertionStarting( info );
12468
12469 m_lastAssertionInfo = info;
12470
12471 AssertionResultData data( resultType, LazyExpression( false ) );
12472 data.message = message;
12473 AssertionResult assertionResult{ m_lastAssertionInfo, data };
12474 assertionEnded( assertionResult );
12475 if( !assertionResult.isOk() )
12476 populateReaction( reaction );
12477 }
handleUnexpectedExceptionNotThrown(AssertionInfo const & info,AssertionReaction & reaction)12478 void RunContext::handleUnexpectedExceptionNotThrown(
12479 AssertionInfo const& info,
12480 AssertionReaction& reaction
12481 ) {
12482 handleNonExpr(info, Catch::ResultWas::DidntThrowException, reaction);
12483 }
12484
handleUnexpectedInflightException(AssertionInfo const & info,std::string const & message,AssertionReaction & reaction)12485 void RunContext::handleUnexpectedInflightException(
12486 AssertionInfo const& info,
12487 std::string const& message,
12488 AssertionReaction& reaction
12489 ) {
12490 m_lastAssertionInfo = info;
12491
12492 AssertionResultData data( ResultWas::ThrewException, LazyExpression( false ) );
12493 data.message = message;
12494 AssertionResult assertionResult{ info, data };
12495 assertionEnded( assertionResult );
12496 populateReaction( reaction );
12497 }
12498
populateReaction(AssertionReaction & reaction)12499 void RunContext::populateReaction( AssertionReaction& reaction ) {
12500 reaction.shouldDebugBreak = m_config->shouldDebugBreak();
12501 reaction.shouldThrow = aborting() || (m_lastAssertionInfo.resultDisposition & ResultDisposition::Normal);
12502 }
12503
handleIncomplete(AssertionInfo const & info)12504 void RunContext::handleIncomplete(
12505 AssertionInfo const& info
12506 ) {
12507 m_lastAssertionInfo = info;
12508
12509 AssertionResultData data( ResultWas::ThrewException, LazyExpression( false ) );
12510 data.message = "Exception translation was disabled by CATCH_CONFIG_FAST_COMPILE";
12511 AssertionResult assertionResult{ info, data };
12512 assertionEnded( assertionResult );
12513 }
handleNonExpr(AssertionInfo const & info,ResultWas::OfType resultType,AssertionReaction & reaction)12514 void RunContext::handleNonExpr(
12515 AssertionInfo const &info,
12516 ResultWas::OfType resultType,
12517 AssertionReaction &reaction
12518 ) {
12519 m_lastAssertionInfo = info;
12520
12521 AssertionResultData data( resultType, LazyExpression( false ) );
12522 AssertionResult assertionResult{ info, data };
12523 assertionEnded( assertionResult );
12524
12525 if( !assertionResult.isOk() )
12526 populateReaction( reaction );
12527 }
12528
getResultCapture()12529 IResultCapture& getResultCapture() {
12530 if (auto* capture = getCurrentContext().getResultCapture())
12531 return *capture;
12532 else
12533 CATCH_INTERNAL_ERROR("No result capture instance");
12534 }
12535 }
12536 // end catch_run_context.cpp
12537 // start catch_section.cpp
12538
12539 namespace Catch {
12540
Section(SectionInfo const & info)12541 Section::Section( SectionInfo const& info )
12542 : m_info( info ),
12543 m_sectionIncluded( getResultCapture().sectionStarted( m_info, m_assertions ) )
12544 {
12545 m_timer.start();
12546 }
12547
~Section()12548 Section::~Section() {
12549 if( m_sectionIncluded ) {
12550 SectionEndInfo endInfo{ m_info, m_assertions, m_timer.getElapsedSeconds() };
12551 if( uncaught_exceptions() )
12552 getResultCapture().sectionEndedEarly( endInfo );
12553 else
12554 getResultCapture().sectionEnded( endInfo );
12555 }
12556 }
12557
12558 // This indicates whether the section should be executed or not
operator bool() const12559 Section::operator bool() const {
12560 return m_sectionIncluded;
12561 }
12562
12563 } // end namespace Catch
12564 // end catch_section.cpp
12565 // start catch_section_info.cpp
12566
12567 namespace Catch {
12568
SectionInfo(SourceLineInfo const & _lineInfo,std::string const & _name)12569 SectionInfo::SectionInfo
12570 ( SourceLineInfo const& _lineInfo,
12571 std::string const& _name )
12572 : name( _name ),
12573 lineInfo( _lineInfo )
12574 {}
12575
12576 } // end namespace Catch
12577 // end catch_section_info.cpp
12578 // start catch_session.cpp
12579
12580 // start catch_session.h
12581
12582 #include <memory>
12583
12584 namespace Catch {
12585
12586 class Session : NonCopyable {
12587 public:
12588
12589 Session();
12590 ~Session() override;
12591
12592 void showHelp() const;
12593 void libIdentify();
12594
12595 int applyCommandLine( int argc, char const * const * argv );
12596 #if defined(CATCH_CONFIG_WCHAR) && defined(_WIN32) && defined(UNICODE)
12597 int applyCommandLine( int argc, wchar_t const * const * argv );
12598 #endif
12599
12600 void useConfigData( ConfigData const& configData );
12601
12602 template<typename CharT>
run(int argc,CharT const * const argv[])12603 int run(int argc, CharT const * const argv[]) {
12604 if (m_startupExceptions)
12605 return 1;
12606 int returnCode = applyCommandLine(argc, argv);
12607 if (returnCode == 0)
12608 returnCode = run();
12609 return returnCode;
12610 }
12611
12612 int run();
12613
12614 clara::Parser const& cli() const;
12615 void cli( clara::Parser const& newParser );
12616 ConfigData& configData();
12617 Config& config();
12618 private:
12619 int runInternal();
12620
12621 clara::Parser m_cli;
12622 ConfigData m_configData;
12623 std::shared_ptr<Config> m_config;
12624 bool m_startupExceptions = false;
12625 };
12626
12627 } // end namespace Catch
12628
12629 // end catch_session.h
12630 // start catch_version.h
12631
12632 #include <iosfwd>
12633
12634 namespace Catch {
12635
12636 // Versioning information
12637 struct Version {
12638 Version( Version const& ) = delete;
12639 Version& operator=( Version const& ) = delete;
12640 Version( unsigned int _majorVersion,
12641 unsigned int _minorVersion,
12642 unsigned int _patchNumber,
12643 char const * const _branchName,
12644 unsigned int _buildNumber );
12645
12646 unsigned int const majorVersion;
12647 unsigned int const minorVersion;
12648 unsigned int const patchNumber;
12649
12650 // buildNumber is only used if branchName is not null
12651 char const * const branchName;
12652 unsigned int const buildNumber;
12653
12654 friend std::ostream& operator << ( std::ostream& os, Version const& version );
12655 };
12656
12657 Version const& libraryVersion();
12658 }
12659
12660 // end catch_version.h
12661 #include <cstdlib>
12662 #include <iomanip>
12663 #include <set>
12664 #include <iterator>
12665
12666 namespace Catch {
12667
12668 namespace {
12669 const int MaxExitCode = 255;
12670
createReporter(std::string const & reporterName,IConfigPtr const & config)12671 IStreamingReporterPtr createReporter(std::string const& reporterName, IConfigPtr const& config) {
12672 auto reporter = Catch::getRegistryHub().getReporterRegistry().create(reporterName, config);
12673 CATCH_ENFORCE(reporter, "No reporter registered with name: '" << reporterName << "'");
12674
12675 return reporter;
12676 }
12677
makeReporter(std::shared_ptr<Config> const & config)12678 IStreamingReporterPtr makeReporter(std::shared_ptr<Config> const& config) {
12679 if (Catch::getRegistryHub().getReporterRegistry().getListeners().empty()) {
12680 return createReporter(config->getReporterName(), config);
12681 }
12682
12683 // On older platforms, returning std::unique_ptr<ListeningReporter>
12684 // when the return type is std::unique_ptr<IStreamingReporter>
12685 // doesn't compile without a std::move call. However, this causes
12686 // a warning on newer platforms. Thus, we have to work around
12687 // it a bit and downcast the pointer manually.
12688 auto ret = std::unique_ptr<IStreamingReporter>(new ListeningReporter);
12689 auto& multi = static_cast<ListeningReporter&>(*ret);
12690 auto const& listeners = Catch::getRegistryHub().getReporterRegistry().getListeners();
12691 for (auto const& listener : listeners) {
12692 multi.addListener(listener->create(Catch::ReporterConfig(config)));
12693 }
12694 multi.addReporter(createReporter(config->getReporterName(), config));
12695 return ret;
12696 }
12697
12698 class TestGroup {
12699 public:
TestGroup(std::shared_ptr<Config> const & config)12700 explicit TestGroup(std::shared_ptr<Config> const& config)
12701 : m_config{config}
12702 , m_context{config, makeReporter(config)}
12703 {
12704 auto const& allTestCases = getAllTestCasesSorted(*m_config);
12705 m_matches = m_config->testSpec().matchesByFilter(allTestCases, *m_config);
12706
12707 if (m_matches.empty()) {
12708 for (auto const& test : allTestCases)
12709 if (!test.isHidden())
12710 m_tests.emplace(&test);
12711 } else {
12712 for (auto const& match : m_matches)
12713 m_tests.insert(match.tests.begin(), match.tests.end());
12714 }
12715 }
12716
execute()12717 Totals execute() {
12718 Totals totals;
12719 m_context.testGroupStarting(m_config->name(), 1, 1);
12720 for (auto const& testCase : m_tests) {
12721 if (!m_context.aborting())
12722 totals += m_context.runTest(*testCase);
12723 else
12724 m_context.reporter().skipTest(*testCase);
12725 }
12726
12727 for (auto const& match : m_matches) {
12728 if (match.tests.empty()) {
12729 m_context.reporter().noMatchingTestCases(match.name);
12730 totals.error = -1;
12731 }
12732 }
12733 m_context.testGroupEnded(m_config->name(), totals, 1, 1);
12734 return totals;
12735 }
12736
12737 private:
12738 using Tests = std::set<TestCase const*>;
12739
12740 std::shared_ptr<Config> m_config;
12741 RunContext m_context;
12742 Tests m_tests;
12743 TestSpec::Matches m_matches;
12744 };
12745
applyFilenamesAsTags(Catch::IConfig const & config)12746 void applyFilenamesAsTags(Catch::IConfig const& config) {
12747 auto& tests = const_cast<std::vector<TestCase>&>(getAllTestCasesSorted(config));
12748 for (auto& testCase : tests) {
12749 auto tags = testCase.tags;
12750
12751 std::string filename = testCase.lineInfo.file;
12752 auto lastSlash = filename.find_last_of("\\/");
12753 if (lastSlash != std::string::npos) {
12754 filename.erase(0, lastSlash);
12755 filename[0] = '#';
12756 }
12757
12758 auto lastDot = filename.find_last_of('.');
12759 if (lastDot != std::string::npos) {
12760 filename.erase(lastDot);
12761 }
12762
12763 tags.push_back(std::move(filename));
12764 setTags(testCase, tags);
12765 }
12766 }
12767
12768 } // anon namespace
12769
Session()12770 Session::Session() {
12771 static bool alreadyInstantiated = false;
12772 if( alreadyInstantiated ) {
12773 CATCH_TRY { CATCH_INTERNAL_ERROR( "Only one instance of Catch::Session can ever be used" ); }
12774 CATCH_CATCH_ALL { getMutableRegistryHub().registerStartupException(); }
12775 }
12776
12777 // There cannot be exceptions at startup in no-exception mode.
12778 #if !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
12779 const auto& exceptions = getRegistryHub().getStartupExceptionRegistry().getExceptions();
12780 if ( !exceptions.empty() ) {
12781 config();
12782 getCurrentMutableContext().setConfig(m_config);
12783
12784 m_startupExceptions = true;
12785 Colour colourGuard( Colour::Red );
12786 Catch::cerr() << "Errors occurred during startup!" << '\n';
12787 // iterate over all exceptions and notify user
12788 for ( const auto& ex_ptr : exceptions ) {
12789 try {
12790 std::rethrow_exception(ex_ptr);
12791 } catch ( std::exception const& ex ) {
12792 Catch::cerr() << Column( ex.what() ).indent(2) << '\n';
12793 }
12794 }
12795 }
12796 #endif
12797
12798 alreadyInstantiated = true;
12799 m_cli = makeCommandLineParser( m_configData );
12800 }
~Session()12801 Session::~Session() {
12802 Catch::cleanUp();
12803 }
12804
showHelp() const12805 void Session::showHelp() const {
12806 Catch::cout()
12807 << "\nCatch v" << libraryVersion() << "\n"
12808 << m_cli << std::endl
12809 << "For more detailed usage please see the project docs\n" << std::endl;
12810 }
libIdentify()12811 void Session::libIdentify() {
12812 Catch::cout()
12813 << std::left << std::setw(16) << "description: " << "A Catch test executable\n"
12814 << std::left << std::setw(16) << "category: " << "testframework\n"
12815 << std::left << std::setw(16) << "framework: " << "Catch Test\n"
12816 << std::left << std::setw(16) << "version: " << libraryVersion() << std::endl;
12817 }
12818
applyCommandLine(int argc,char const * const * argv)12819 int Session::applyCommandLine( int argc, char const * const * argv ) {
12820 if( m_startupExceptions )
12821 return 1;
12822
12823 auto result = m_cli.parse( clara::Args( argc, argv ) );
12824 if( !result ) {
12825 config();
12826 getCurrentMutableContext().setConfig(m_config);
12827 Catch::cerr()
12828 << Colour( Colour::Red )
12829 << "\nError(s) in input:\n"
12830 << Column( result.errorMessage() ).indent( 2 )
12831 << "\n\n";
12832 Catch::cerr() << "Run with -? for usage\n" << std::endl;
12833 return MaxExitCode;
12834 }
12835
12836 if( m_configData.showHelp )
12837 showHelp();
12838 if( m_configData.libIdentify )
12839 libIdentify();
12840 m_config.reset();
12841 return 0;
12842 }
12843
12844 #if defined(CATCH_CONFIG_WCHAR) && defined(_WIN32) && defined(UNICODE)
applyCommandLine(int argc,wchar_t const * const * argv)12845 int Session::applyCommandLine( int argc, wchar_t const * const * argv ) {
12846
12847 char **utf8Argv = new char *[ argc ];
12848
12849 for ( int i = 0; i < argc; ++i ) {
12850 int bufSize = WideCharToMultiByte( CP_UTF8, 0, argv[i], -1, NULL, 0, NULL, NULL );
12851
12852 utf8Argv[ i ] = new char[ bufSize ];
12853
12854 WideCharToMultiByte( CP_UTF8, 0, argv[i], -1, utf8Argv[i], bufSize, NULL, NULL );
12855 }
12856
12857 int returnCode = applyCommandLine( argc, utf8Argv );
12858
12859 for ( int i = 0; i < argc; ++i )
12860 delete [] utf8Argv[ i ];
12861
12862 delete [] utf8Argv;
12863
12864 return returnCode;
12865 }
12866 #endif
12867
useConfigData(ConfigData const & configData)12868 void Session::useConfigData( ConfigData const& configData ) {
12869 m_configData = configData;
12870 m_config.reset();
12871 }
12872
run()12873 int Session::run() {
12874 if( ( m_configData.waitForKeypress & WaitForKeypress::BeforeStart ) != 0 ) {
12875 Catch::cout() << "...waiting for enter/ return before starting" << std::endl;
12876 static_cast<void>(std::getchar());
12877 }
12878 int exitCode = runInternal();
12879 if( ( m_configData.waitForKeypress & WaitForKeypress::BeforeExit ) != 0 ) {
12880 Catch::cout() << "...waiting for enter/ return before exiting, with code: " << exitCode << std::endl;
12881 static_cast<void>(std::getchar());
12882 }
12883 return exitCode;
12884 }
12885
cli() const12886 clara::Parser const& Session::cli() const {
12887 return m_cli;
12888 }
cli(clara::Parser const & newParser)12889 void Session::cli( clara::Parser const& newParser ) {
12890 m_cli = newParser;
12891 }
configData()12892 ConfigData& Session::configData() {
12893 return m_configData;
12894 }
config()12895 Config& Session::config() {
12896 if( !m_config )
12897 m_config = std::make_shared<Config>( m_configData );
12898 return *m_config;
12899 }
12900
runInternal()12901 int Session::runInternal() {
12902 if( m_startupExceptions )
12903 return 1;
12904
12905 if (m_configData.showHelp || m_configData.libIdentify) {
12906 return 0;
12907 }
12908
12909 CATCH_TRY {
12910 config(); // Force config to be constructed
12911
12912 seedRng( *m_config );
12913
12914 if( m_configData.filenamesAsTags )
12915 applyFilenamesAsTags( *m_config );
12916
12917 // Handle list request
12918 if( Option<std::size_t> listed = list( m_config ) )
12919 return static_cast<int>( *listed );
12920
12921 TestGroup tests { m_config };
12922 auto const totals = tests.execute();
12923
12924 if( m_config->warnAboutNoTests() && totals.error == -1 )
12925 return 2;
12926
12927 // Note that on unices only the lower 8 bits are usually used, clamping
12928 // the return value to 255 prevents false negative when some multiple
12929 // of 256 tests has failed
12930 return (std::min) (MaxExitCode, (std::max) (totals.error, static_cast<int>(totals.assertions.failed)));
12931 }
12932 #if !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
12933 catch( std::exception& ex ) {
12934 Catch::cerr() << ex.what() << std::endl;
12935 return MaxExitCode;
12936 }
12937 #endif
12938 }
12939
12940 } // end namespace Catch
12941 // end catch_session.cpp
12942 // start catch_singletons.cpp
12943
12944 #include <vector>
12945
12946 namespace Catch {
12947
12948 namespace {
getSingletons()12949 static auto getSingletons() -> std::vector<ISingleton*>*& {
12950 static std::vector<ISingleton*>* g_singletons = nullptr;
12951 if( !g_singletons )
12952 g_singletons = new std::vector<ISingleton*>();
12953 return g_singletons;
12954 }
12955 }
12956
~ISingleton()12957 ISingleton::~ISingleton() {}
12958
addSingleton(ISingleton * singleton)12959 void addSingleton(ISingleton* singleton ) {
12960 getSingletons()->push_back( singleton );
12961 }
cleanupSingletons()12962 void cleanupSingletons() {
12963 auto& singletons = getSingletons();
12964 for( auto singleton : *singletons )
12965 delete singleton;
12966 delete singletons;
12967 singletons = nullptr;
12968 }
12969
12970 } // namespace Catch
12971 // end catch_singletons.cpp
12972 // start catch_startup_exception_registry.cpp
12973
12974 namespace Catch {
add(std::exception_ptr const & exception)12975 void StartupExceptionRegistry::add( std::exception_ptr const& exception ) noexcept {
12976 CATCH_TRY {
12977 m_exceptions.push_back(exception);
12978 } CATCH_CATCH_ALL {
12979 // If we run out of memory during start-up there's really not a lot more we can do about it
12980 std::terminate();
12981 }
12982 }
12983
getExceptions() const12984 std::vector<std::exception_ptr> const& StartupExceptionRegistry::getExceptions() const noexcept {
12985 return m_exceptions;
12986 }
12987
12988 } // end namespace Catch
12989 // end catch_startup_exception_registry.cpp
12990 // start catch_stream.cpp
12991
12992 #include <cstdio>
12993 #include <iostream>
12994 #include <fstream>
12995 #include <sstream>
12996 #include <vector>
12997 #include <memory>
12998
12999 namespace Catch {
13000
13001 Catch::IStream::~IStream() = default;
13002
13003 namespace Detail { namespace {
13004 template<typename WriterF, std::size_t bufferSize=256>
13005 class StreamBufImpl : public std::streambuf {
13006 char data[bufferSize];
13007 WriterF m_writer;
13008
13009 public:
StreamBufImpl()13010 StreamBufImpl() {
13011 setp( data, data + sizeof(data) );
13012 }
13013
~StreamBufImpl()13014 ~StreamBufImpl() noexcept {
13015 StreamBufImpl::sync();
13016 }
13017
13018 private:
overflow(int c)13019 int overflow( int c ) override {
13020 sync();
13021
13022 if( c != EOF ) {
13023 if( pbase() == epptr() )
13024 m_writer( std::string( 1, static_cast<char>( c ) ) );
13025 else
13026 sputc( static_cast<char>( c ) );
13027 }
13028 return 0;
13029 }
13030
sync()13031 int sync() override {
13032 if( pbase() != pptr() ) {
13033 m_writer( std::string( pbase(), static_cast<std::string::size_type>( pptr() - pbase() ) ) );
13034 setp( pbase(), epptr() );
13035 }
13036 return 0;
13037 }
13038 };
13039
13040 ///////////////////////////////////////////////////////////////////////////
13041
13042 struct OutputDebugWriter {
13043
operator ()Catch::Detail::__anon73d2dbed3711::OutputDebugWriter13044 void operator()( std::string const&str ) {
13045 writeToDebugConsole( str );
13046 }
13047 };
13048
13049 ///////////////////////////////////////////////////////////////////////////
13050
13051 class FileStream : public IStream {
13052 mutable std::ofstream m_ofs;
13053 public:
FileStream(StringRef filename)13054 FileStream( StringRef filename ) {
13055 m_ofs.open( filename.c_str() );
13056 CATCH_ENFORCE( !m_ofs.fail(), "Unable to open file: '" << filename << "'" );
13057 }
13058 ~FileStream() override = default;
13059 public: // IStream
stream() const13060 std::ostream& stream() const override {
13061 return m_ofs;
13062 }
13063 };
13064
13065 ///////////////////////////////////////////////////////////////////////////
13066
13067 class CoutStream : public IStream {
13068 mutable std::ostream m_os;
13069 public:
13070 // Store the streambuf from cout up-front because
13071 // cout may get redirected when running tests
CoutStream()13072 CoutStream() : m_os( Catch::cout().rdbuf() ) {}
13073 ~CoutStream() override = default;
13074
13075 public: // IStream
stream() const13076 std::ostream& stream() const override { return m_os; }
13077 };
13078
13079 ///////////////////////////////////////////////////////////////////////////
13080
13081 class DebugOutStream : public IStream {
13082 std::unique_ptr<StreamBufImpl<OutputDebugWriter>> m_streamBuf;
13083 mutable std::ostream m_os;
13084 public:
DebugOutStream()13085 DebugOutStream()
13086 : m_streamBuf( new StreamBufImpl<OutputDebugWriter>() ),
13087 m_os( m_streamBuf.get() )
13088 {}
13089
13090 ~DebugOutStream() override = default;
13091
13092 public: // IStream
stream() const13093 std::ostream& stream() const override { return m_os; }
13094 };
13095
13096 }} // namespace anon::detail
13097
13098 ///////////////////////////////////////////////////////////////////////////
13099
makeStream(StringRef const & filename)13100 auto makeStream( StringRef const &filename ) -> IStream const* {
13101 if( filename.empty() )
13102 return new Detail::CoutStream();
13103 else if( filename[0] == '%' ) {
13104 if( filename == "%debug" )
13105 return new Detail::DebugOutStream();
13106 else
13107 CATCH_ERROR( "Unrecognised stream: '" << filename << "'" );
13108 }
13109 else
13110 return new Detail::FileStream( filename );
13111 }
13112
13113 // This class encapsulates the idea of a pool of ostringstreams that can be reused.
13114 struct StringStreams {
13115 std::vector<std::unique_ptr<std::ostringstream>> m_streams;
13116 std::vector<std::size_t> m_unused;
13117 std::ostringstream m_referenceStream; // Used for copy state/ flags from
13118
addCatch::StringStreams13119 auto add() -> std::size_t {
13120 if( m_unused.empty() ) {
13121 m_streams.push_back( std::unique_ptr<std::ostringstream>( new std::ostringstream ) );
13122 return m_streams.size()-1;
13123 }
13124 else {
13125 auto index = m_unused.back();
13126 m_unused.pop_back();
13127 return index;
13128 }
13129 }
13130
releaseCatch::StringStreams13131 void release( std::size_t index ) {
13132 m_streams[index]->copyfmt( m_referenceStream ); // Restore initial flags and other state
13133 m_unused.push_back(index);
13134 }
13135 };
13136
ReusableStringStream()13137 ReusableStringStream::ReusableStringStream()
13138 : m_index( Singleton<StringStreams>::getMutable().add() ),
13139 m_oss( Singleton<StringStreams>::getMutable().m_streams[m_index].get() )
13140 {}
13141
~ReusableStringStream()13142 ReusableStringStream::~ReusableStringStream() {
13143 static_cast<std::ostringstream*>( m_oss )->str("");
13144 m_oss->clear();
13145 Singleton<StringStreams>::getMutable().release( m_index );
13146 }
13147
str() const13148 auto ReusableStringStream::str() const -> std::string {
13149 return static_cast<std::ostringstream*>( m_oss )->str();
13150 }
13151
13152 ///////////////////////////////////////////////////////////////////////////
13153
13154 #ifndef CATCH_CONFIG_NOSTDOUT // If you #define this you must implement these functions
cout()13155 std::ostream& cout() { return std::cout; }
cerr()13156 std::ostream& cerr() { return std::cerr; }
clog()13157 std::ostream& clog() { return std::clog; }
13158 #endif
13159 }
13160 // end catch_stream.cpp
13161 // start catch_string_manip.cpp
13162
13163 #include <algorithm>
13164 #include <ostream>
13165 #include <cstring>
13166 #include <cctype>
13167 #include <vector>
13168
13169 namespace Catch {
13170
13171 namespace {
toLowerCh(char c)13172 char toLowerCh(char c) {
13173 return static_cast<char>( std::tolower( c ) );
13174 }
13175 }
13176
startsWith(std::string const & s,std::string const & prefix)13177 bool startsWith( std::string const& s, std::string const& prefix ) {
13178 return s.size() >= prefix.size() && std::equal(prefix.begin(), prefix.end(), s.begin());
13179 }
startsWith(std::string const & s,char prefix)13180 bool startsWith( std::string const& s, char prefix ) {
13181 return !s.empty() && s[0] == prefix;
13182 }
endsWith(std::string const & s,std::string const & suffix)13183 bool endsWith( std::string const& s, std::string const& suffix ) {
13184 return s.size() >= suffix.size() && std::equal(suffix.rbegin(), suffix.rend(), s.rbegin());
13185 }
endsWith(std::string const & s,char suffix)13186 bool endsWith( std::string const& s, char suffix ) {
13187 return !s.empty() && s[s.size()-1] == suffix;
13188 }
contains(std::string const & s,std::string const & infix)13189 bool contains( std::string const& s, std::string const& infix ) {
13190 return s.find( infix ) != std::string::npos;
13191 }
toLowerInPlace(std::string & s)13192 void toLowerInPlace( std::string& s ) {
13193 std::transform( s.begin(), s.end(), s.begin(), toLowerCh );
13194 }
toLower(std::string const & s)13195 std::string toLower( std::string const& s ) {
13196 std::string lc = s;
13197 toLowerInPlace( lc );
13198 return lc;
13199 }
trim(std::string const & str)13200 std::string trim( std::string const& str ) {
13201 static char const* whitespaceChars = "\n\r\t ";
13202 std::string::size_type start = str.find_first_not_of( whitespaceChars );
13203 std::string::size_type end = str.find_last_not_of( whitespaceChars );
13204
13205 return start != std::string::npos ? str.substr( start, 1+end-start ) : std::string();
13206 }
13207
replaceInPlace(std::string & str,std::string const & replaceThis,std::string const & withThis)13208 bool replaceInPlace( std::string& str, std::string const& replaceThis, std::string const& withThis ) {
13209 bool replaced = false;
13210 std::size_t i = str.find( replaceThis );
13211 while( i != std::string::npos ) {
13212 replaced = true;
13213 str = str.substr( 0, i ) + withThis + str.substr( i+replaceThis.size() );
13214 if( i < str.size()-withThis.size() )
13215 i = str.find( replaceThis, i+withThis.size() );
13216 else
13217 i = std::string::npos;
13218 }
13219 return replaced;
13220 }
13221
splitStringRef(StringRef str,char delimiter)13222 std::vector<StringRef> splitStringRef( StringRef str, char delimiter ) {
13223 std::vector<StringRef> subStrings;
13224 std::size_t start = 0;
13225 for(std::size_t pos = 0; pos < str.size(); ++pos ) {
13226 if( str[pos] == delimiter ) {
13227 if( pos - start > 1 )
13228 subStrings.push_back( str.substr( start, pos-start ) );
13229 start = pos+1;
13230 }
13231 }
13232 if( start < str.size() )
13233 subStrings.push_back( str.substr( start, str.size()-start ) );
13234 return subStrings;
13235 }
13236
pluralise(std::size_t count,std::string const & label)13237 pluralise::pluralise( std::size_t count, std::string const& label )
13238 : m_count( count ),
13239 m_label( label )
13240 {}
13241
operator <<(std::ostream & os,pluralise const & pluraliser)13242 std::ostream& operator << ( std::ostream& os, pluralise const& pluraliser ) {
13243 os << pluraliser.m_count << ' ' << pluraliser.m_label;
13244 if( pluraliser.m_count != 1 )
13245 os << 's';
13246 return os;
13247 }
13248
13249 }
13250 // end catch_string_manip.cpp
13251 // start catch_stringref.cpp
13252
13253 #if defined(__clang__)
13254 # pragma clang diagnostic push
13255 # pragma clang diagnostic ignored "-Wexit-time-destructors"
13256 #endif
13257
13258 #include <ostream>
13259 #include <cstring>
13260 #include <cstdint>
13261
13262 namespace {
13263 const uint32_t byte_2_lead = 0xC0;
13264 const uint32_t byte_3_lead = 0xE0;
13265 const uint32_t byte_4_lead = 0xF0;
13266 }
13267
13268 namespace Catch {
StringRef(char const * rawChars)13269 StringRef::StringRef( char const* rawChars ) noexcept
13270 : StringRef( rawChars, static_cast<StringRef::size_type>(std::strlen(rawChars) ) )
13271 {}
13272
operator std::string() const13273 StringRef::operator std::string() const {
13274 return std::string( m_start, m_size );
13275 }
13276
swap(StringRef & other)13277 void StringRef::swap( StringRef& other ) noexcept {
13278 std::swap( m_start, other.m_start );
13279 std::swap( m_size, other.m_size );
13280 std::swap( m_data, other.m_data );
13281 }
13282
c_str() const13283 auto StringRef::c_str() const -> char const* {
13284 if( !isSubstring() )
13285 return m_start;
13286
13287 const_cast<StringRef *>( this )->takeOwnership();
13288 return m_data;
13289 }
currentData() const13290 auto StringRef::currentData() const noexcept -> char const* {
13291 return m_start;
13292 }
13293
isOwned() const13294 auto StringRef::isOwned() const noexcept -> bool {
13295 return m_data != nullptr;
13296 }
isSubstring() const13297 auto StringRef::isSubstring() const noexcept -> bool {
13298 return m_start[m_size] != '\0';
13299 }
13300
takeOwnership()13301 void StringRef::takeOwnership() {
13302 if( !isOwned() ) {
13303 m_data = new char[m_size+1];
13304 memcpy( m_data, m_start, m_size );
13305 m_data[m_size] = '\0';
13306 }
13307 }
substr(size_type start,size_type size) const13308 auto StringRef::substr( size_type start, size_type size ) const noexcept -> StringRef {
13309 if( start < m_size )
13310 return StringRef( m_start+start, size );
13311 else
13312 return StringRef();
13313 }
operator ==(StringRef const & other) const13314 auto StringRef::operator == ( StringRef const& other ) const noexcept -> bool {
13315 return
13316 size() == other.size() &&
13317 (std::strncmp( m_start, other.m_start, size() ) == 0);
13318 }
operator !=(StringRef const & other) const13319 auto StringRef::operator != ( StringRef const& other ) const noexcept -> bool {
13320 return !operator==( other );
13321 }
13322
operator [](size_type index) const13323 auto StringRef::operator[](size_type index) const noexcept -> char {
13324 return m_start[index];
13325 }
13326
numberOfCharacters() const13327 auto StringRef::numberOfCharacters() const noexcept -> size_type {
13328 size_type noChars = m_size;
13329 // Make adjustments for uft encodings
13330 for( size_type i=0; i < m_size; ++i ) {
13331 char c = m_start[i];
13332 if( ( c & byte_2_lead ) == byte_2_lead ) {
13333 noChars--;
13334 if (( c & byte_3_lead ) == byte_3_lead )
13335 noChars--;
13336 if( ( c & byte_4_lead ) == byte_4_lead )
13337 noChars--;
13338 }
13339 }
13340 return noChars;
13341 }
13342
operator +(StringRef const & lhs,StringRef const & rhs)13343 auto operator + ( StringRef const& lhs, StringRef const& rhs ) -> std::string {
13344 std::string str;
13345 str.reserve( lhs.size() + rhs.size() );
13346 str += lhs;
13347 str += rhs;
13348 return str;
13349 }
operator +(StringRef const & lhs,const char * rhs)13350 auto operator + ( StringRef const& lhs, const char* rhs ) -> std::string {
13351 return std::string( lhs ) + std::string( rhs );
13352 }
operator +(char const * lhs,StringRef const & rhs)13353 auto operator + ( char const* lhs, StringRef const& rhs ) -> std::string {
13354 return std::string( lhs ) + std::string( rhs );
13355 }
13356
operator <<(std::ostream & os,StringRef const & str)13357 auto operator << ( std::ostream& os, StringRef const& str ) -> std::ostream& {
13358 return os.write(str.currentData(), str.size());
13359 }
13360
operator +=(std::string & lhs,StringRef const & rhs)13361 auto operator+=( std::string& lhs, StringRef const& rhs ) -> std::string& {
13362 lhs.append(rhs.currentData(), rhs.size());
13363 return lhs;
13364 }
13365
13366 } // namespace Catch
13367
13368 #if defined(__clang__)
13369 # pragma clang diagnostic pop
13370 #endif
13371 // end catch_stringref.cpp
13372 // start catch_tag_alias.cpp
13373
13374 namespace Catch {
TagAlias(std::string const & _tag,SourceLineInfo _lineInfo)13375 TagAlias::TagAlias(std::string const & _tag, SourceLineInfo _lineInfo): tag(_tag), lineInfo(_lineInfo) {}
13376 }
13377 // end catch_tag_alias.cpp
13378 // start catch_tag_alias_autoregistrar.cpp
13379
13380 namespace Catch {
13381
RegistrarForTagAliases(char const * alias,char const * tag,SourceLineInfo const & lineInfo)13382 RegistrarForTagAliases::RegistrarForTagAliases(char const* alias, char const* tag, SourceLineInfo const& lineInfo) {
13383 CATCH_TRY {
13384 getMutableRegistryHub().registerTagAlias(alias, tag, lineInfo);
13385 } CATCH_CATCH_ALL {
13386 // Do not throw when constructing global objects, instead register the exception to be processed later
13387 getMutableRegistryHub().registerStartupException();
13388 }
13389 }
13390
13391 }
13392 // end catch_tag_alias_autoregistrar.cpp
13393 // start catch_tag_alias_registry.cpp
13394
13395 #include <sstream>
13396
13397 namespace Catch {
13398
~TagAliasRegistry()13399 TagAliasRegistry::~TagAliasRegistry() {}
13400
find(std::string const & alias) const13401 TagAlias const* TagAliasRegistry::find( std::string const& alias ) const {
13402 auto it = m_registry.find( alias );
13403 if( it != m_registry.end() )
13404 return &(it->second);
13405 else
13406 return nullptr;
13407 }
13408
expandAliases(std::string const & unexpandedTestSpec) const13409 std::string TagAliasRegistry::expandAliases( std::string const& unexpandedTestSpec ) const {
13410 std::string expandedTestSpec = unexpandedTestSpec;
13411 for( auto const& registryKvp : m_registry ) {
13412 std::size_t pos = expandedTestSpec.find( registryKvp.first );
13413 if( pos != std::string::npos ) {
13414 expandedTestSpec = expandedTestSpec.substr( 0, pos ) +
13415 registryKvp.second.tag +
13416 expandedTestSpec.substr( pos + registryKvp.first.size() );
13417 }
13418 }
13419 return expandedTestSpec;
13420 }
13421
add(std::string const & alias,std::string const & tag,SourceLineInfo const & lineInfo)13422 void TagAliasRegistry::add( std::string const& alias, std::string const& tag, SourceLineInfo const& lineInfo ) {
13423 CATCH_ENFORCE( startsWith(alias, "[@") && endsWith(alias, ']'),
13424 "error: tag alias, '" << alias << "' is not of the form [@alias name].\n" << lineInfo );
13425
13426 CATCH_ENFORCE( m_registry.insert(std::make_pair(alias, TagAlias(tag, lineInfo))).second,
13427 "error: tag alias, '" << alias << "' already registered.\n"
13428 << "\tFirst seen at: " << find(alias)->lineInfo << "\n"
13429 << "\tRedefined at: " << lineInfo );
13430 }
13431
~ITagAliasRegistry()13432 ITagAliasRegistry::~ITagAliasRegistry() {}
13433
get()13434 ITagAliasRegistry const& ITagAliasRegistry::get() {
13435 return getRegistryHub().getTagAliasRegistry();
13436 }
13437
13438 } // end namespace Catch
13439 // end catch_tag_alias_registry.cpp
13440 // start catch_test_case_info.cpp
13441
13442 #include <cctype>
13443 #include <exception>
13444 #include <algorithm>
13445 #include <sstream>
13446
13447 namespace Catch {
13448
13449 namespace {
parseSpecialTag(std::string const & tag)13450 TestCaseInfo::SpecialProperties parseSpecialTag( std::string const& tag ) {
13451 if( startsWith( tag, '.' ) ||
13452 tag == "!hide" )
13453 return TestCaseInfo::IsHidden;
13454 else if( tag == "!throws" )
13455 return TestCaseInfo::Throws;
13456 else if( tag == "!shouldfail" )
13457 return TestCaseInfo::ShouldFail;
13458 else if( tag == "!mayfail" )
13459 return TestCaseInfo::MayFail;
13460 else if( tag == "!nonportable" )
13461 return TestCaseInfo::NonPortable;
13462 else if( tag == "!benchmark" )
13463 return static_cast<TestCaseInfo::SpecialProperties>( TestCaseInfo::Benchmark | TestCaseInfo::IsHidden );
13464 else
13465 return TestCaseInfo::None;
13466 }
isReservedTag(std::string const & tag)13467 bool isReservedTag( std::string const& tag ) {
13468 return parseSpecialTag( tag ) == TestCaseInfo::None && tag.size() > 0 && !std::isalnum( static_cast<unsigned char>(tag[0]) );
13469 }
enforceNotReservedTag(std::string const & tag,SourceLineInfo const & _lineInfo)13470 void enforceNotReservedTag( std::string const& tag, SourceLineInfo const& _lineInfo ) {
13471 CATCH_ENFORCE( !isReservedTag(tag),
13472 "Tag name: [" << tag << "] is not allowed.\n"
13473 << "Tag names starting with non alphanumeric characters are reserved\n"
13474 << _lineInfo );
13475 }
13476 }
13477
makeTestCase(ITestInvoker * _testCase,std::string const & _className,NameAndTags const & nameAndTags,SourceLineInfo const & _lineInfo)13478 TestCase makeTestCase( ITestInvoker* _testCase,
13479 std::string const& _className,
13480 NameAndTags const& nameAndTags,
13481 SourceLineInfo const& _lineInfo )
13482 {
13483 bool isHidden = false;
13484
13485 // Parse out tags
13486 std::vector<std::string> tags;
13487 std::string desc, tag;
13488 bool inTag = false;
13489 std::string _descOrTags = nameAndTags.tags;
13490 for (char c : _descOrTags) {
13491 if( !inTag ) {
13492 if( c == '[' )
13493 inTag = true;
13494 else
13495 desc += c;
13496 }
13497 else {
13498 if( c == ']' ) {
13499 TestCaseInfo::SpecialProperties prop = parseSpecialTag( tag );
13500 if( ( prop & TestCaseInfo::IsHidden ) != 0 )
13501 isHidden = true;
13502 else if( prop == TestCaseInfo::None )
13503 enforceNotReservedTag( tag, _lineInfo );
13504
13505 // Merged hide tags like `[.approvals]` should be added as
13506 // `[.][approvals]`. The `[.]` is added at later point, so
13507 // we only strip the prefix
13508 if (startsWith(tag, '.') && tag.size() > 1) {
13509 tag.erase(0, 1);
13510 }
13511 tags.push_back( tag );
13512 tag.clear();
13513 inTag = false;
13514 }
13515 else
13516 tag += c;
13517 }
13518 }
13519 if( isHidden ) {
13520 tags.push_back( "." );
13521 }
13522
13523 TestCaseInfo info( nameAndTags.name, _className, desc, tags, _lineInfo );
13524 return TestCase( _testCase, std::move(info) );
13525 }
13526
setTags(TestCaseInfo & testCaseInfo,std::vector<std::string> tags)13527 void setTags( TestCaseInfo& testCaseInfo, std::vector<std::string> tags ) {
13528 std::sort(begin(tags), end(tags));
13529 tags.erase(std::unique(begin(tags), end(tags)), end(tags));
13530 testCaseInfo.lcaseTags.clear();
13531
13532 for( auto const& tag : tags ) {
13533 std::string lcaseTag = toLower( tag );
13534 testCaseInfo.properties = static_cast<TestCaseInfo::SpecialProperties>( testCaseInfo.properties | parseSpecialTag( lcaseTag ) );
13535 testCaseInfo.lcaseTags.push_back( lcaseTag );
13536 }
13537 testCaseInfo.tags = std::move(tags);
13538 }
13539
TestCaseInfo(std::string const & _name,std::string const & _className,std::string const & _description,std::vector<std::string> const & _tags,SourceLineInfo const & _lineInfo)13540 TestCaseInfo::TestCaseInfo( std::string const& _name,
13541 std::string const& _className,
13542 std::string const& _description,
13543 std::vector<std::string> const& _tags,
13544 SourceLineInfo const& _lineInfo )
13545 : name( _name ),
13546 className( _className ),
13547 description( _description ),
13548 lineInfo( _lineInfo ),
13549 properties( None )
13550 {
13551 setTags( *this, _tags );
13552 }
13553
isHidden() const13554 bool TestCaseInfo::isHidden() const {
13555 return ( properties & IsHidden ) != 0;
13556 }
throws() const13557 bool TestCaseInfo::throws() const {
13558 return ( properties & Throws ) != 0;
13559 }
okToFail() const13560 bool TestCaseInfo::okToFail() const {
13561 return ( properties & (ShouldFail | MayFail ) ) != 0;
13562 }
expectedToFail() const13563 bool TestCaseInfo::expectedToFail() const {
13564 return ( properties & (ShouldFail ) ) != 0;
13565 }
13566
tagsAsString() const13567 std::string TestCaseInfo::tagsAsString() const {
13568 std::string ret;
13569 // '[' and ']' per tag
13570 std::size_t full_size = 2 * tags.size();
13571 for (const auto& tag : tags) {
13572 full_size += tag.size();
13573 }
13574 ret.reserve(full_size);
13575 for (const auto& tag : tags) {
13576 ret.push_back('[');
13577 ret.append(tag);
13578 ret.push_back(']');
13579 }
13580
13581 return ret;
13582 }
13583
TestCase(ITestInvoker * testCase,TestCaseInfo && info)13584 TestCase::TestCase( ITestInvoker* testCase, TestCaseInfo&& info ) : TestCaseInfo( std::move(info) ), test( testCase ) {}
13585
withName(std::string const & _newName) const13586 TestCase TestCase::withName( std::string const& _newName ) const {
13587 TestCase other( *this );
13588 other.name = _newName;
13589 return other;
13590 }
13591
invoke() const13592 void TestCase::invoke() const {
13593 test->invoke();
13594 }
13595
operator ==(TestCase const & other) const13596 bool TestCase::operator == ( TestCase const& other ) const {
13597 return test.get() == other.test.get() &&
13598 name == other.name &&
13599 className == other.className;
13600 }
13601
operator <(TestCase const & other) const13602 bool TestCase::operator < ( TestCase const& other ) const {
13603 return name < other.name;
13604 }
13605
getTestCaseInfo() const13606 TestCaseInfo const& TestCase::getTestCaseInfo() const
13607 {
13608 return *this;
13609 }
13610
13611 } // end namespace Catch
13612 // end catch_test_case_info.cpp
13613 // start catch_test_case_registry_impl.cpp
13614
13615 #include <sstream>
13616
13617 namespace Catch {
13618
sortTests(IConfig const & config,std::vector<TestCase> const & unsortedTestCases)13619 std::vector<TestCase> sortTests( IConfig const& config, std::vector<TestCase> const& unsortedTestCases ) {
13620
13621 std::vector<TestCase> sorted = unsortedTestCases;
13622
13623 switch( config.runOrder() ) {
13624 case RunTests::InLexicographicalOrder:
13625 std::sort( sorted.begin(), sorted.end() );
13626 break;
13627 case RunTests::InRandomOrder:
13628 seedRng( config );
13629 std::shuffle( sorted.begin(), sorted.end(), rng() );
13630 break;
13631 case RunTests::InDeclarationOrder:
13632 // already in declaration order
13633 break;
13634 }
13635 return sorted;
13636 }
13637
isThrowSafe(TestCase const & testCase,IConfig const & config)13638 bool isThrowSafe( TestCase const& testCase, IConfig const& config ) {
13639 return !testCase.throws() || config.allowThrows();
13640 }
13641
matchTest(TestCase const & testCase,TestSpec const & testSpec,IConfig const & config)13642 bool matchTest( TestCase const& testCase, TestSpec const& testSpec, IConfig const& config ) {
13643 return testSpec.matches( testCase ) && isThrowSafe( testCase, config );
13644 }
13645
enforceNoDuplicateTestCases(std::vector<TestCase> const & functions)13646 void enforceNoDuplicateTestCases( std::vector<TestCase> const& functions ) {
13647 std::set<TestCase> seenFunctions;
13648 for( auto const& function : functions ) {
13649 auto prev = seenFunctions.insert( function );
13650 CATCH_ENFORCE( prev.second,
13651 "error: TEST_CASE( \"" << function.name << "\" ) already defined.\n"
13652 << "\tFirst seen at " << prev.first->getTestCaseInfo().lineInfo << "\n"
13653 << "\tRedefined at " << function.getTestCaseInfo().lineInfo );
13654 }
13655 }
13656
filterTests(std::vector<TestCase> const & testCases,TestSpec const & testSpec,IConfig const & config)13657 std::vector<TestCase> filterTests( std::vector<TestCase> const& testCases, TestSpec const& testSpec, IConfig const& config ) {
13658 std::vector<TestCase> filtered;
13659 filtered.reserve( testCases.size() );
13660 for (auto const& testCase : testCases) {
13661 if ((!testSpec.hasFilters() && !testCase.isHidden()) ||
13662 (testSpec.hasFilters() && matchTest(testCase, testSpec, config))) {
13663 filtered.push_back(testCase);
13664 }
13665 }
13666 return filtered;
13667 }
getAllTestCasesSorted(IConfig const & config)13668 std::vector<TestCase> const& getAllTestCasesSorted( IConfig const& config ) {
13669 return getRegistryHub().getTestCaseRegistry().getAllTestsSorted( config );
13670 }
13671
registerTest(TestCase const & testCase)13672 void TestRegistry::registerTest( TestCase const& testCase ) {
13673 std::string name = testCase.getTestCaseInfo().name;
13674 if( name.empty() ) {
13675 ReusableStringStream rss;
13676 rss << "Anonymous test case " << ++m_unnamedCount;
13677 return registerTest( testCase.withName( rss.str() ) );
13678 }
13679 m_functions.push_back( testCase );
13680 }
13681
getAllTests() const13682 std::vector<TestCase> const& TestRegistry::getAllTests() const {
13683 return m_functions;
13684 }
getAllTestsSorted(IConfig const & config) const13685 std::vector<TestCase> const& TestRegistry::getAllTestsSorted( IConfig const& config ) const {
13686 if( m_sortedFunctions.empty() )
13687 enforceNoDuplicateTestCases( m_functions );
13688
13689 if( m_currentSortOrder != config.runOrder() || m_sortedFunctions.empty() ) {
13690 m_sortedFunctions = sortTests( config, m_functions );
13691 m_currentSortOrder = config.runOrder();
13692 }
13693 return m_sortedFunctions;
13694 }
13695
13696 ///////////////////////////////////////////////////////////////////////////
TestInvokerAsFunction(void (* testAsFunction)())13697 TestInvokerAsFunction::TestInvokerAsFunction( void(*testAsFunction)() ) noexcept : m_testAsFunction( testAsFunction ) {}
13698
invoke() const13699 void TestInvokerAsFunction::invoke() const {
13700 m_testAsFunction();
13701 }
13702
extractClassName(StringRef const & classOrQualifiedMethodName)13703 std::string extractClassName( StringRef const& classOrQualifiedMethodName ) {
13704 std::string className = classOrQualifiedMethodName;
13705 if( startsWith( className, '&' ) )
13706 {
13707 std::size_t lastColons = className.rfind( "::" );
13708 std::size_t penultimateColons = className.rfind( "::", lastColons-1 );
13709 if( penultimateColons == std::string::npos )
13710 penultimateColons = 1;
13711 className = className.substr( penultimateColons, lastColons-penultimateColons );
13712 }
13713 return className;
13714 }
13715
13716 } // end namespace Catch
13717 // end catch_test_case_registry_impl.cpp
13718 // start catch_test_case_tracker.cpp
13719
13720 #include <algorithm>
13721 #include <cassert>
13722 #include <stdexcept>
13723 #include <memory>
13724 #include <sstream>
13725
13726 #if defined(__clang__)
13727 # pragma clang diagnostic push
13728 # pragma clang diagnostic ignored "-Wexit-time-destructors"
13729 #endif
13730
13731 namespace Catch {
13732 namespace TestCaseTracking {
13733
NameAndLocation(std::string const & _name,SourceLineInfo const & _location)13734 NameAndLocation::NameAndLocation( std::string const& _name, SourceLineInfo const& _location )
13735 : name( _name ),
13736 location( _location )
13737 {}
13738
13739 ITracker::~ITracker() = default;
13740
startRun()13741 ITracker& TrackerContext::startRun() {
13742 m_rootTracker = std::make_shared<SectionTracker>( NameAndLocation( "{root}", CATCH_INTERNAL_LINEINFO ), *this, nullptr );
13743 m_currentTracker = nullptr;
13744 m_runState = Executing;
13745 return *m_rootTracker;
13746 }
13747
endRun()13748 void TrackerContext::endRun() {
13749 m_rootTracker.reset();
13750 m_currentTracker = nullptr;
13751 m_runState = NotStarted;
13752 }
13753
startCycle()13754 void TrackerContext::startCycle() {
13755 m_currentTracker = m_rootTracker.get();
13756 m_runState = Executing;
13757 }
completeCycle()13758 void TrackerContext::completeCycle() {
13759 m_runState = CompletedCycle;
13760 }
13761
completedCycle() const13762 bool TrackerContext::completedCycle() const {
13763 return m_runState == CompletedCycle;
13764 }
currentTracker()13765 ITracker& TrackerContext::currentTracker() {
13766 return *m_currentTracker;
13767 }
setCurrentTracker(ITracker * tracker)13768 void TrackerContext::setCurrentTracker( ITracker* tracker ) {
13769 m_currentTracker = tracker;
13770 }
13771
TrackerBase(NameAndLocation const & nameAndLocation,TrackerContext & ctx,ITracker * parent)13772 TrackerBase::TrackerBase( NameAndLocation const& nameAndLocation, TrackerContext& ctx, ITracker* parent )
13773 : m_nameAndLocation( nameAndLocation ),
13774 m_ctx( ctx ),
13775 m_parent( parent )
13776 {}
13777
nameAndLocation() const13778 NameAndLocation const& TrackerBase::nameAndLocation() const {
13779 return m_nameAndLocation;
13780 }
isComplete() const13781 bool TrackerBase::isComplete() const {
13782 return m_runState == CompletedSuccessfully || m_runState == Failed;
13783 }
isSuccessfullyCompleted() const13784 bool TrackerBase::isSuccessfullyCompleted() const {
13785 return m_runState == CompletedSuccessfully;
13786 }
isOpen() const13787 bool TrackerBase::isOpen() const {
13788 return m_runState != NotStarted && !isComplete();
13789 }
hasChildren() const13790 bool TrackerBase::hasChildren() const {
13791 return !m_children.empty();
13792 }
13793
addChild(ITrackerPtr const & child)13794 void TrackerBase::addChild( ITrackerPtr const& child ) {
13795 m_children.push_back( child );
13796 }
13797
findChild(NameAndLocation const & nameAndLocation)13798 ITrackerPtr TrackerBase::findChild( NameAndLocation const& nameAndLocation ) {
13799 auto it = std::find_if( m_children.begin(), m_children.end(),
13800 [&nameAndLocation]( ITrackerPtr const& tracker ){
13801 return
13802 tracker->nameAndLocation().location == nameAndLocation.location &&
13803 tracker->nameAndLocation().name == nameAndLocation.name;
13804 } );
13805 return( it != m_children.end() )
13806 ? *it
13807 : nullptr;
13808 }
parent()13809 ITracker& TrackerBase::parent() {
13810 assert( m_parent ); // Should always be non-null except for root
13811 return *m_parent;
13812 }
13813
openChild()13814 void TrackerBase::openChild() {
13815 if( m_runState != ExecutingChildren ) {
13816 m_runState = ExecutingChildren;
13817 if( m_parent )
13818 m_parent->openChild();
13819 }
13820 }
13821
isSectionTracker() const13822 bool TrackerBase::isSectionTracker() const { return false; }
isGeneratorTracker() const13823 bool TrackerBase::isGeneratorTracker() const { return false; }
13824
open()13825 void TrackerBase::open() {
13826 m_runState = Executing;
13827 moveToThis();
13828 if( m_parent )
13829 m_parent->openChild();
13830 }
13831
close()13832 void TrackerBase::close() {
13833
13834 // Close any still open children (e.g. generators)
13835 while( &m_ctx.currentTracker() != this )
13836 m_ctx.currentTracker().close();
13837
13838 switch( m_runState ) {
13839 case NeedsAnotherRun:
13840 break;
13841
13842 case Executing:
13843 m_runState = CompletedSuccessfully;
13844 break;
13845 case ExecutingChildren:
13846 if( std::all_of(m_children.begin(), m_children.end(), [](ITrackerPtr const& t){ return t->isComplete(); }) )
13847 m_runState = CompletedSuccessfully;
13848 break;
13849
13850 case NotStarted:
13851 case CompletedSuccessfully:
13852 case Failed:
13853 CATCH_INTERNAL_ERROR( "Illogical state: " << m_runState );
13854
13855 default:
13856 CATCH_INTERNAL_ERROR( "Unknown state: " << m_runState );
13857 }
13858 moveToParent();
13859 m_ctx.completeCycle();
13860 }
fail()13861 void TrackerBase::fail() {
13862 m_runState = Failed;
13863 if( m_parent )
13864 m_parent->markAsNeedingAnotherRun();
13865 moveToParent();
13866 m_ctx.completeCycle();
13867 }
markAsNeedingAnotherRun()13868 void TrackerBase::markAsNeedingAnotherRun() {
13869 m_runState = NeedsAnotherRun;
13870 }
13871
moveToParent()13872 void TrackerBase::moveToParent() {
13873 assert( m_parent );
13874 m_ctx.setCurrentTracker( m_parent );
13875 }
moveToThis()13876 void TrackerBase::moveToThis() {
13877 m_ctx.setCurrentTracker( this );
13878 }
13879
SectionTracker(NameAndLocation const & nameAndLocation,TrackerContext & ctx,ITracker * parent)13880 SectionTracker::SectionTracker( NameAndLocation const& nameAndLocation, TrackerContext& ctx, ITracker* parent )
13881 : TrackerBase( nameAndLocation, ctx, parent )
13882 {
13883 if( parent ) {
13884 while( !parent->isSectionTracker() )
13885 parent = &parent->parent();
13886
13887 SectionTracker& parentSection = static_cast<SectionTracker&>( *parent );
13888 addNextFilters( parentSection.m_filters );
13889 }
13890 }
13891
isComplete() const13892 bool SectionTracker::isComplete() const {
13893 bool complete = true;
13894
13895 if ((m_filters.empty() || m_filters[0] == "") ||
13896 std::find(m_filters.begin(), m_filters.end(),
13897 m_nameAndLocation.name) != m_filters.end())
13898 complete = TrackerBase::isComplete();
13899 return complete;
13900
13901 }
13902
isSectionTracker() const13903 bool SectionTracker::isSectionTracker() const { return true; }
13904
acquire(TrackerContext & ctx,NameAndLocation const & nameAndLocation)13905 SectionTracker& SectionTracker::acquire( TrackerContext& ctx, NameAndLocation const& nameAndLocation ) {
13906 std::shared_ptr<SectionTracker> section;
13907
13908 ITracker& currentTracker = ctx.currentTracker();
13909 if( ITrackerPtr childTracker = currentTracker.findChild( nameAndLocation ) ) {
13910 assert( childTracker );
13911 assert( childTracker->isSectionTracker() );
13912 section = std::static_pointer_cast<SectionTracker>( childTracker );
13913 }
13914 else {
13915 section = std::make_shared<SectionTracker>( nameAndLocation, ctx, ¤tTracker );
13916 currentTracker.addChild( section );
13917 }
13918 if( !ctx.completedCycle() )
13919 section->tryOpen();
13920 return *section;
13921 }
13922
tryOpen()13923 void SectionTracker::tryOpen() {
13924 if( !isComplete() && (m_filters.empty() || m_filters[0].empty() || m_filters[0] == m_nameAndLocation.name ) )
13925 open();
13926 }
13927
addInitialFilters(std::vector<std::string> const & filters)13928 void SectionTracker::addInitialFilters( std::vector<std::string> const& filters ) {
13929 if( !filters.empty() ) {
13930 m_filters.push_back(""); // Root - should never be consulted
13931 m_filters.push_back(""); // Test Case - not a section filter
13932 m_filters.insert( m_filters.end(), filters.begin(), filters.end() );
13933 }
13934 }
addNextFilters(std::vector<std::string> const & filters)13935 void SectionTracker::addNextFilters( std::vector<std::string> const& filters ) {
13936 if( filters.size() > 1 )
13937 m_filters.insert( m_filters.end(), ++filters.begin(), filters.end() );
13938 }
13939
13940 } // namespace TestCaseTracking
13941
13942 using TestCaseTracking::ITracker;
13943 using TestCaseTracking::TrackerContext;
13944 using TestCaseTracking::SectionTracker;
13945
13946 } // namespace Catch
13947
13948 #if defined(__clang__)
13949 # pragma clang diagnostic pop
13950 #endif
13951 // end catch_test_case_tracker.cpp
13952 // start catch_test_registry.cpp
13953
13954 namespace Catch {
13955
makeTestInvoker(void (* testAsFunction)())13956 auto makeTestInvoker( void(*testAsFunction)() ) noexcept -> ITestInvoker* {
13957 return new(std::nothrow) TestInvokerAsFunction( testAsFunction );
13958 }
13959
NameAndTags(StringRef const & name_,StringRef const & tags_)13960 NameAndTags::NameAndTags( StringRef const& name_ , StringRef const& tags_ ) noexcept : name( name_ ), tags( tags_ ) {}
13961
AutoReg(ITestInvoker * invoker,SourceLineInfo const & lineInfo,StringRef const & classOrMethod,NameAndTags const & nameAndTags)13962 AutoReg::AutoReg( ITestInvoker* invoker, SourceLineInfo const& lineInfo, StringRef const& classOrMethod, NameAndTags const& nameAndTags ) noexcept {
13963 CATCH_TRY {
13964 getMutableRegistryHub()
13965 .registerTest(
13966 makeTestCase(
13967 invoker,
13968 extractClassName( classOrMethod ),
13969 nameAndTags,
13970 lineInfo));
13971 } CATCH_CATCH_ALL {
13972 // Do not throw when constructing global objects, instead register the exception to be processed later
13973 getMutableRegistryHub().registerStartupException();
13974 }
13975 }
13976
13977 AutoReg::~AutoReg() = default;
13978 }
13979 // end catch_test_registry.cpp
13980 // start catch_test_spec.cpp
13981
13982 #include <algorithm>
13983 #include <string>
13984 #include <vector>
13985 #include <memory>
13986
13987 namespace Catch {
13988
Pattern(std::string const & name)13989 TestSpec::Pattern::Pattern( std::string const& name )
13990 : m_name( name )
13991 {}
13992
13993 TestSpec::Pattern::~Pattern() = default;
13994
name() const13995 std::string const& TestSpec::Pattern::name() const {
13996 return m_name;
13997 }
13998
NamePattern(std::string const & name,std::string const & filterString)13999 TestSpec::NamePattern::NamePattern( std::string const& name, std::string const& filterString )
14000 : Pattern( filterString )
14001 , m_wildcardPattern( toLower( name ), CaseSensitive::No )
14002 {}
14003
matches(TestCaseInfo const & testCase) const14004 bool TestSpec::NamePattern::matches( TestCaseInfo const& testCase ) const {
14005 return m_wildcardPattern.matches( toLower( testCase.name ) );
14006 }
14007
TagPattern(std::string const & tag,std::string const & filterString)14008 TestSpec::TagPattern::TagPattern( std::string const& tag, std::string const& filterString )
14009 : Pattern( filterString )
14010 , m_tag( toLower( tag ) )
14011 {}
14012
matches(TestCaseInfo const & testCase) const14013 bool TestSpec::TagPattern::matches( TestCaseInfo const& testCase ) const {
14014 return std::find(begin(testCase.lcaseTags),
14015 end(testCase.lcaseTags),
14016 m_tag) != end(testCase.lcaseTags);
14017 }
14018
ExcludedPattern(PatternPtr const & underlyingPattern)14019 TestSpec::ExcludedPattern::ExcludedPattern( PatternPtr const& underlyingPattern )
14020 : Pattern( underlyingPattern->name() )
14021 , m_underlyingPattern( underlyingPattern )
14022 {}
14023
matches(TestCaseInfo const & testCase) const14024 bool TestSpec::ExcludedPattern::matches( TestCaseInfo const& testCase ) const {
14025 return !m_underlyingPattern->matches( testCase );
14026 }
14027
matches(TestCaseInfo const & testCase) const14028 bool TestSpec::Filter::matches( TestCaseInfo const& testCase ) const {
14029 return std::all_of( m_patterns.begin(), m_patterns.end(), [&]( PatternPtr const& p ){ return p->matches( testCase ); } );
14030 }
14031
name() const14032 std::string TestSpec::Filter::name() const {
14033 std::string name;
14034 for( auto const& p : m_patterns )
14035 name += p->name();
14036 return name;
14037 }
14038
hasFilters() const14039 bool TestSpec::hasFilters() const {
14040 return !m_filters.empty();
14041 }
14042
matches(TestCaseInfo const & testCase) const14043 bool TestSpec::matches( TestCaseInfo const& testCase ) const {
14044 return std::any_of( m_filters.begin(), m_filters.end(), [&]( Filter const& f ){ return f.matches( testCase ); } );
14045 }
14046
matchesByFilter(std::vector<TestCase> const & testCases,IConfig const & config) const14047 TestSpec::Matches TestSpec::matchesByFilter( std::vector<TestCase> const& testCases, IConfig const& config ) const
14048 {
14049 Matches matches( m_filters.size() );
14050 std::transform( m_filters.begin(), m_filters.end(), matches.begin(), [&]( Filter const& filter ){
14051 std::vector<TestCase const*> currentMatches;
14052 for( auto const& test : testCases )
14053 if( isThrowSafe( test, config ) && filter.matches( test ) )
14054 currentMatches.emplace_back( &test );
14055 return FilterMatch{ filter.name(), currentMatches };
14056 } );
14057 return matches;
14058 }
14059
14060 }
14061 // end catch_test_spec.cpp
14062 // start catch_test_spec_parser.cpp
14063
14064 namespace Catch {
14065
TestSpecParser(ITagAliasRegistry const & tagAliases)14066 TestSpecParser::TestSpecParser( ITagAliasRegistry const& tagAliases ) : m_tagAliases( &tagAliases ) {}
14067
parse(std::string const & arg)14068 TestSpecParser& TestSpecParser::parse( std::string const& arg ) {
14069 m_mode = None;
14070 m_exclusion = false;
14071 m_arg = m_tagAliases->expandAliases( arg );
14072 m_escapeChars.clear();
14073 m_substring.reserve(m_arg.size());
14074 m_patternName.reserve(m_arg.size());
14075 for( m_pos = 0; m_pos < m_arg.size(); ++m_pos )
14076 visitChar( m_arg[m_pos] );
14077 endMode();
14078 return *this;
14079 }
testSpec()14080 TestSpec TestSpecParser::testSpec() {
14081 addFilter();
14082 return m_testSpec;
14083 }
visitChar(char c)14084 void TestSpecParser::visitChar( char c ) {
14085 if( c == ',' ) {
14086 endMode();
14087 addFilter();
14088 return;
14089 }
14090
14091 switch( m_mode ) {
14092 case None:
14093 if( processNoneChar( c ) )
14094 return;
14095 break;
14096 case Name:
14097 processNameChar( c );
14098 break;
14099 case EscapedName:
14100 endMode();
14101 break;
14102 default:
14103 case Tag:
14104 case QuotedName:
14105 if( processOtherChar( c ) )
14106 return;
14107 break;
14108 }
14109
14110 m_substring += c;
14111 if( !isControlChar( c ) )
14112 m_patternName += c;
14113 }
14114 // Two of the processing methods return true to signal the caller to return
14115 // without adding the given character to the current pattern strings
processNoneChar(char c)14116 bool TestSpecParser::processNoneChar( char c ) {
14117 switch( c ) {
14118 case ' ':
14119 return true;
14120 case '~':
14121 m_exclusion = true;
14122 return false;
14123 case '[':
14124 startNewMode( Tag );
14125 return false;
14126 case '"':
14127 startNewMode( QuotedName );
14128 return false;
14129 case '\\':
14130 escape();
14131 return true;
14132 default:
14133 startNewMode( Name );
14134 return false;
14135 }
14136 }
processNameChar(char c)14137 void TestSpecParser::processNameChar( char c ) {
14138 if( c == '[' ) {
14139 if( m_substring == "exclude:" )
14140 m_exclusion = true;
14141 else
14142 endMode();
14143 startNewMode( Tag );
14144 }
14145 }
processOtherChar(char c)14146 bool TestSpecParser::processOtherChar( char c ) {
14147 if( !isControlChar( c ) )
14148 return false;
14149 m_substring += c;
14150 endMode();
14151 return true;
14152 }
startNewMode(Mode mode)14153 void TestSpecParser::startNewMode( Mode mode ) {
14154 m_mode = mode;
14155 }
endMode()14156 void TestSpecParser::endMode() {
14157 switch( m_mode ) {
14158 case Name:
14159 case QuotedName:
14160 return addPattern<TestSpec::NamePattern>();
14161 case Tag:
14162 return addPattern<TestSpec::TagPattern>();
14163 case EscapedName:
14164 return startNewMode( Name );
14165 case None:
14166 default:
14167 return startNewMode( None );
14168 }
14169 }
escape()14170 void TestSpecParser::escape() {
14171 m_mode = EscapedName;
14172 m_escapeChars.push_back( m_pos );
14173 }
isControlChar(char c) const14174 bool TestSpecParser::isControlChar( char c ) const {
14175 switch( m_mode ) {
14176 default:
14177 return false;
14178 case None:
14179 return c == '~';
14180 case Name:
14181 return c == '[';
14182 case EscapedName:
14183 return true;
14184 case QuotedName:
14185 return c == '"';
14186 case Tag:
14187 return c == '[' || c == ']';
14188 }
14189 }
14190
addFilter()14191 void TestSpecParser::addFilter() {
14192 if( !m_currentFilter.m_patterns.empty() ) {
14193 m_testSpec.m_filters.push_back( m_currentFilter );
14194 m_currentFilter = TestSpec::Filter();
14195 }
14196 }
14197
parseTestSpec(std::string const & arg)14198 TestSpec parseTestSpec( std::string const& arg ) {
14199 return TestSpecParser( ITagAliasRegistry::get() ).parse( arg ).testSpec();
14200 }
14201
14202 } // namespace Catch
14203 // end catch_test_spec_parser.cpp
14204 // start catch_timer.cpp
14205
14206 #include <chrono>
14207
14208 static const uint64_t nanosecondsInSecond = 1000000000;
14209
14210 namespace Catch {
14211
getCurrentNanosecondsSinceEpoch()14212 auto getCurrentNanosecondsSinceEpoch() -> uint64_t {
14213 return std::chrono::duration_cast<std::chrono::nanoseconds>( std::chrono::high_resolution_clock::now().time_since_epoch() ).count();
14214 }
14215
14216 namespace {
estimateClockResolution()14217 auto estimateClockResolution() -> uint64_t {
14218 uint64_t sum = 0;
14219 static const uint64_t iterations = 1000000;
14220
14221 auto startTime = getCurrentNanosecondsSinceEpoch();
14222
14223 for( std::size_t i = 0; i < iterations; ++i ) {
14224
14225 uint64_t ticks;
14226 uint64_t baseTicks = getCurrentNanosecondsSinceEpoch();
14227 do {
14228 ticks = getCurrentNanosecondsSinceEpoch();
14229 } while( ticks == baseTicks );
14230
14231 auto delta = ticks - baseTicks;
14232 sum += delta;
14233
14234 // If we have been calibrating for over 3 seconds -- the clock
14235 // is terrible and we should move on.
14236 // TBD: How to signal that the measured resolution is probably wrong?
14237 if (ticks > startTime + 3 * nanosecondsInSecond) {
14238 return sum / ( i + 1u );
14239 }
14240 }
14241
14242 // We're just taking the mean, here. To do better we could take the std. dev and exclude outliers
14243 // - and potentially do more iterations if there's a high variance.
14244 return sum/iterations;
14245 }
14246 }
getEstimatedClockResolution()14247 auto getEstimatedClockResolution() -> uint64_t {
14248 static auto s_resolution = estimateClockResolution();
14249 return s_resolution;
14250 }
14251
start()14252 void Timer::start() {
14253 m_nanoseconds = getCurrentNanosecondsSinceEpoch();
14254 }
getElapsedNanoseconds() const14255 auto Timer::getElapsedNanoseconds() const -> uint64_t {
14256 return getCurrentNanosecondsSinceEpoch() - m_nanoseconds;
14257 }
getElapsedMicroseconds() const14258 auto Timer::getElapsedMicroseconds() const -> uint64_t {
14259 return getElapsedNanoseconds()/1000;
14260 }
getElapsedMilliseconds() const14261 auto Timer::getElapsedMilliseconds() const -> unsigned int {
14262 return static_cast<unsigned int>(getElapsedMicroseconds()/1000);
14263 }
getElapsedSeconds() const14264 auto Timer::getElapsedSeconds() const -> double {
14265 return getElapsedMicroseconds()/1000000.0;
14266 }
14267
14268 } // namespace Catch
14269 // end catch_timer.cpp
14270 // start catch_tostring.cpp
14271
14272 #if defined(__clang__)
14273 # pragma clang diagnostic push
14274 # pragma clang diagnostic ignored "-Wexit-time-destructors"
14275 # pragma clang diagnostic ignored "-Wglobal-constructors"
14276 #endif
14277
14278 // Enable specific decls locally
14279 #if !defined(CATCH_CONFIG_ENABLE_CHRONO_STRINGMAKER)
14280 #define CATCH_CONFIG_ENABLE_CHRONO_STRINGMAKER
14281 #endif
14282
14283 #include <cmath>
14284 #include <iomanip>
14285
14286 namespace Catch {
14287
14288 namespace Detail {
14289
14290 const std::string unprintableString = "{?}";
14291
14292 namespace {
14293 const int hexThreshold = 255;
14294
14295 struct Endianness {
14296 enum Arch { Big, Little };
14297
whichCatch::Detail::__anon73d2dbed4111::Endianness14298 static Arch which() {
14299 union _{
14300 int asInt;
14301 char asChar[sizeof (int)];
14302 } u;
14303
14304 u.asInt = 1;
14305 return ( u.asChar[sizeof(int)-1] == 1 ) ? Big : Little;
14306 }
14307 };
14308 }
14309
rawMemoryToString(const void * object,std::size_t size)14310 std::string rawMemoryToString( const void *object, std::size_t size ) {
14311 // Reverse order for little endian architectures
14312 int i = 0, end = static_cast<int>( size ), inc = 1;
14313 if( Endianness::which() == Endianness::Little ) {
14314 i = end-1;
14315 end = inc = -1;
14316 }
14317
14318 unsigned char const *bytes = static_cast<unsigned char const *>(object);
14319 ReusableStringStream rss;
14320 rss << "0x" << std::setfill('0') << std::hex;
14321 for( ; i != end; i += inc )
14322 rss << std::setw(2) << static_cast<unsigned>(bytes[i]);
14323 return rss.str();
14324 }
14325 }
14326
14327 template<typename T>
fpToString(T value,int precision)14328 std::string fpToString( T value, int precision ) {
14329 if (Catch::isnan(value)) {
14330 return "nan";
14331 }
14332
14333 ReusableStringStream rss;
14334 rss << std::setprecision( precision )
14335 << std::fixed
14336 << value;
14337 std::string d = rss.str();
14338 std::size_t i = d.find_last_not_of( '0' );
14339 if( i != std::string::npos && i != d.size()-1 ) {
14340 if( d[i] == '.' )
14341 i++;
14342 d = d.substr( 0, i+1 );
14343 }
14344 return d;
14345 }
14346
14347 //// ======================================================= ////
14348 //
14349 // Out-of-line defs for full specialization of StringMaker
14350 //
14351 //// ======================================================= ////
14352
convert(const std::string & str)14353 std::string StringMaker<std::string>::convert(const std::string& str) {
14354 if (!getCurrentContext().getConfig()->showInvisibles()) {
14355 return '"' + str + '"';
14356 }
14357
14358 std::string s("\"");
14359 for (char c : str) {
14360 switch (c) {
14361 case '\n':
14362 s.append("\\n");
14363 break;
14364 case '\t':
14365 s.append("\\t");
14366 break;
14367 default:
14368 s.push_back(c);
14369 break;
14370 }
14371 }
14372 s.append("\"");
14373 return s;
14374 }
14375
14376 #ifdef CATCH_CONFIG_CPP17_STRING_VIEW
convert(std::string_view str)14377 std::string StringMaker<std::string_view>::convert(std::string_view str) {
14378 return ::Catch::Detail::stringify(std::string{ str });
14379 }
14380 #endif
14381
convert(char const * str)14382 std::string StringMaker<char const*>::convert(char const* str) {
14383 if (str) {
14384 return ::Catch::Detail::stringify(std::string{ str });
14385 } else {
14386 return{ "{null string}" };
14387 }
14388 }
convert(char * str)14389 std::string StringMaker<char*>::convert(char* str) {
14390 if (str) {
14391 return ::Catch::Detail::stringify(std::string{ str });
14392 } else {
14393 return{ "{null string}" };
14394 }
14395 }
14396
14397 #ifdef CATCH_CONFIG_WCHAR
convert(const std::wstring & wstr)14398 std::string StringMaker<std::wstring>::convert(const std::wstring& wstr) {
14399 std::string s;
14400 s.reserve(wstr.size());
14401 for (auto c : wstr) {
14402 s += (c <= 0xff) ? static_cast<char>(c) : '?';
14403 }
14404 return ::Catch::Detail::stringify(s);
14405 }
14406
14407 # ifdef CATCH_CONFIG_CPP17_STRING_VIEW
convert(std::wstring_view str)14408 std::string StringMaker<std::wstring_view>::convert(std::wstring_view str) {
14409 return StringMaker<std::wstring>::convert(std::wstring(str));
14410 }
14411 # endif
14412
convert(wchar_t const * str)14413 std::string StringMaker<wchar_t const*>::convert(wchar_t const * str) {
14414 if (str) {
14415 return ::Catch::Detail::stringify(std::wstring{ str });
14416 } else {
14417 return{ "{null string}" };
14418 }
14419 }
convert(wchar_t * str)14420 std::string StringMaker<wchar_t *>::convert(wchar_t * str) {
14421 if (str) {
14422 return ::Catch::Detail::stringify(std::wstring{ str });
14423 } else {
14424 return{ "{null string}" };
14425 }
14426 }
14427 #endif
14428
14429 #if defined(CATCH_CONFIG_CPP17_BYTE)
14430 #include <cstddef>
convert(std::byte value)14431 std::string StringMaker<std::byte>::convert(std::byte value) {
14432 return ::Catch::Detail::stringify(std::to_integer<unsigned long long>(value));
14433 }
14434 #endif // defined(CATCH_CONFIG_CPP17_BYTE)
14435
convert(int value)14436 std::string StringMaker<int>::convert(int value) {
14437 return ::Catch::Detail::stringify(static_cast<long long>(value));
14438 }
convert(long value)14439 std::string StringMaker<long>::convert(long value) {
14440 return ::Catch::Detail::stringify(static_cast<long long>(value));
14441 }
convert(long long value)14442 std::string StringMaker<long long>::convert(long long value) {
14443 ReusableStringStream rss;
14444 rss << value;
14445 if (value > Detail::hexThreshold) {
14446 rss << " (0x" << std::hex << value << ')';
14447 }
14448 return rss.str();
14449 }
14450
convert(unsigned int value)14451 std::string StringMaker<unsigned int>::convert(unsigned int value) {
14452 return ::Catch::Detail::stringify(static_cast<unsigned long long>(value));
14453 }
convert(unsigned long value)14454 std::string StringMaker<unsigned long>::convert(unsigned long value) {
14455 return ::Catch::Detail::stringify(static_cast<unsigned long long>(value));
14456 }
convert(unsigned long long value)14457 std::string StringMaker<unsigned long long>::convert(unsigned long long value) {
14458 ReusableStringStream rss;
14459 rss << value;
14460 if (value > Detail::hexThreshold) {
14461 rss << " (0x" << std::hex << value << ')';
14462 }
14463 return rss.str();
14464 }
14465
convert(bool b)14466 std::string StringMaker<bool>::convert(bool b) {
14467 return b ? "true" : "false";
14468 }
14469
convert(signed char value)14470 std::string StringMaker<signed char>::convert(signed char value) {
14471 if (value == '\r') {
14472 return "'\\r'";
14473 } else if (value == '\f') {
14474 return "'\\f'";
14475 } else if (value == '\n') {
14476 return "'\\n'";
14477 } else if (value == '\t') {
14478 return "'\\t'";
14479 } else if ('\0' <= value && value < ' ') {
14480 return ::Catch::Detail::stringify(static_cast<unsigned int>(value));
14481 } else {
14482 char chstr[] = "' '";
14483 chstr[1] = value;
14484 return chstr;
14485 }
14486 }
convert(char c)14487 std::string StringMaker<char>::convert(char c) {
14488 return ::Catch::Detail::stringify(static_cast<signed char>(c));
14489 }
convert(unsigned char c)14490 std::string StringMaker<unsigned char>::convert(unsigned char c) {
14491 return ::Catch::Detail::stringify(static_cast<char>(c));
14492 }
14493
convert(std::nullptr_t)14494 std::string StringMaker<std::nullptr_t>::convert(std::nullptr_t) {
14495 return "nullptr";
14496 }
14497
14498 int StringMaker<float>::precision = 5;
14499
convert(float value)14500 std::string StringMaker<float>::convert(float value) {
14501 return fpToString(value, precision) + 'f';
14502 }
14503
14504 int StringMaker<double>::precision = 10;
14505
convert(double value)14506 std::string StringMaker<double>::convert(double value) {
14507 return fpToString(value, precision);
14508 }
14509
symbol()14510 std::string ratio_string<std::atto>::symbol() { return "a"; }
symbol()14511 std::string ratio_string<std::femto>::symbol() { return "f"; }
symbol()14512 std::string ratio_string<std::pico>::symbol() { return "p"; }
symbol()14513 std::string ratio_string<std::nano>::symbol() { return "n"; }
symbol()14514 std::string ratio_string<std::micro>::symbol() { return "u"; }
symbol()14515 std::string ratio_string<std::milli>::symbol() { return "m"; }
14516
14517 } // end namespace Catch
14518
14519 #if defined(__clang__)
14520 # pragma clang diagnostic pop
14521 #endif
14522
14523 // end catch_tostring.cpp
14524 // start catch_totals.cpp
14525
14526 namespace Catch {
14527
operator -(Counts const & other) const14528 Counts Counts::operator - ( Counts const& other ) const {
14529 Counts diff;
14530 diff.passed = passed - other.passed;
14531 diff.failed = failed - other.failed;
14532 diff.failedButOk = failedButOk - other.failedButOk;
14533 return diff;
14534 }
14535
operator +=(Counts const & other)14536 Counts& Counts::operator += ( Counts const& other ) {
14537 passed += other.passed;
14538 failed += other.failed;
14539 failedButOk += other.failedButOk;
14540 return *this;
14541 }
14542
total() const14543 std::size_t Counts::total() const {
14544 return passed + failed + failedButOk;
14545 }
allPassed() const14546 bool Counts::allPassed() const {
14547 return failed == 0 && failedButOk == 0;
14548 }
allOk() const14549 bool Counts::allOk() const {
14550 return failed == 0;
14551 }
14552
operator -(Totals const & other) const14553 Totals Totals::operator - ( Totals const& other ) const {
14554 Totals diff;
14555 diff.assertions = assertions - other.assertions;
14556 diff.testCases = testCases - other.testCases;
14557 return diff;
14558 }
14559
operator +=(Totals const & other)14560 Totals& Totals::operator += ( Totals const& other ) {
14561 assertions += other.assertions;
14562 testCases += other.testCases;
14563 return *this;
14564 }
14565
delta(Totals const & prevTotals) const14566 Totals Totals::delta( Totals const& prevTotals ) const {
14567 Totals diff = *this - prevTotals;
14568 if( diff.assertions.failed > 0 )
14569 ++diff.testCases.failed;
14570 else if( diff.assertions.failedButOk > 0 )
14571 ++diff.testCases.failedButOk;
14572 else
14573 ++diff.testCases.passed;
14574 return diff;
14575 }
14576
14577 }
14578 // end catch_totals.cpp
14579 // start catch_uncaught_exceptions.cpp
14580
14581 #include <exception>
14582
14583 namespace Catch {
uncaught_exceptions()14584 bool uncaught_exceptions() {
14585 #if defined(CATCH_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS)
14586 return std::uncaught_exceptions() > 0;
14587 #else
14588 return std::uncaught_exception();
14589 #endif
14590 }
14591 } // end namespace Catch
14592 // end catch_uncaught_exceptions.cpp
14593 // start catch_version.cpp
14594
14595 #include <ostream>
14596
14597 namespace Catch {
14598
Version(unsigned int _majorVersion,unsigned int _minorVersion,unsigned int _patchNumber,char const * const _branchName,unsigned int _buildNumber)14599 Version::Version
14600 ( unsigned int _majorVersion,
14601 unsigned int _minorVersion,
14602 unsigned int _patchNumber,
14603 char const * const _branchName,
14604 unsigned int _buildNumber )
14605 : majorVersion( _majorVersion ),
14606 minorVersion( _minorVersion ),
14607 patchNumber( _patchNumber ),
14608 branchName( _branchName ),
14609 buildNumber( _buildNumber )
14610 {}
14611
operator <<(std::ostream & os,Version const & version)14612 std::ostream& operator << ( std::ostream& os, Version const& version ) {
14613 os << version.majorVersion << '.'
14614 << version.minorVersion << '.'
14615 << version.patchNumber;
14616 // branchName is never null -> 0th char is \0 if it is empty
14617 if (version.branchName[0]) {
14618 os << '-' << version.branchName
14619 << '.' << version.buildNumber;
14620 }
14621 return os;
14622 }
14623
libraryVersion()14624 Version const& libraryVersion() {
14625 static Version version( 2, 9, 2, "", 0 );
14626 return version;
14627 }
14628
14629 }
14630 // end catch_version.cpp
14631 // start catch_wildcard_pattern.cpp
14632
14633 #include <sstream>
14634
14635 namespace Catch {
14636
WildcardPattern(std::string const & pattern,CaseSensitive::Choice caseSensitivity)14637 WildcardPattern::WildcardPattern( std::string const& pattern,
14638 CaseSensitive::Choice caseSensitivity )
14639 : m_caseSensitivity( caseSensitivity ),
14640 m_pattern( adjustCase( pattern ) )
14641 {
14642 if( startsWith( m_pattern, '*' ) ) {
14643 m_pattern = m_pattern.substr( 1 );
14644 m_wildcard = WildcardAtStart;
14645 }
14646 if( endsWith( m_pattern, '*' ) ) {
14647 m_pattern = m_pattern.substr( 0, m_pattern.size()-1 );
14648 m_wildcard = static_cast<WildcardPosition>( m_wildcard | WildcardAtEnd );
14649 }
14650 }
14651
matches(std::string const & str) const14652 bool WildcardPattern::matches( std::string const& str ) const {
14653 switch( m_wildcard ) {
14654 case NoWildcard:
14655 return m_pattern == adjustCase( str );
14656 case WildcardAtStart:
14657 return endsWith( adjustCase( str ), m_pattern );
14658 case WildcardAtEnd:
14659 return startsWith( adjustCase( str ), m_pattern );
14660 case WildcardAtBothEnds:
14661 return contains( adjustCase( str ), m_pattern );
14662 default:
14663 CATCH_INTERNAL_ERROR( "Unknown enum" );
14664 }
14665 }
14666
adjustCase(std::string const & str) const14667 std::string WildcardPattern::adjustCase( std::string const& str ) const {
14668 return m_caseSensitivity == CaseSensitive::No ? toLower( str ) : str;
14669 }
14670 }
14671 // end catch_wildcard_pattern.cpp
14672 // start catch_xmlwriter.cpp
14673
14674 #include <iomanip>
14675
14676 using uchar = unsigned char;
14677
14678 namespace Catch {
14679
14680 namespace {
14681
trailingBytes(unsigned char c)14682 size_t trailingBytes(unsigned char c) {
14683 if ((c & 0xE0) == 0xC0) {
14684 return 2;
14685 }
14686 if ((c & 0xF0) == 0xE0) {
14687 return 3;
14688 }
14689 if ((c & 0xF8) == 0xF0) {
14690 return 4;
14691 }
14692 CATCH_INTERNAL_ERROR("Invalid multibyte utf-8 start byte encountered");
14693 }
14694
headerValue(unsigned char c)14695 uint32_t headerValue(unsigned char c) {
14696 if ((c & 0xE0) == 0xC0) {
14697 return c & 0x1F;
14698 }
14699 if ((c & 0xF0) == 0xE0) {
14700 return c & 0x0F;
14701 }
14702 if ((c & 0xF8) == 0xF0) {
14703 return c & 0x07;
14704 }
14705 CATCH_INTERNAL_ERROR("Invalid multibyte utf-8 start byte encountered");
14706 }
14707
hexEscapeChar(std::ostream & os,unsigned char c)14708 void hexEscapeChar(std::ostream& os, unsigned char c) {
14709 std::ios_base::fmtflags f(os.flags());
14710 os << "\\x"
14711 << std::uppercase << std::hex << std::setfill('0') << std::setw(2)
14712 << static_cast<int>(c);
14713 os.flags(f);
14714 }
14715
14716 } // anonymous namespace
14717
XmlEncode(std::string const & str,ForWhat forWhat)14718 XmlEncode::XmlEncode( std::string const& str, ForWhat forWhat )
14719 : m_str( str ),
14720 m_forWhat( forWhat )
14721 {}
14722
encodeTo(std::ostream & os) const14723 void XmlEncode::encodeTo( std::ostream& os ) const {
14724 // Apostrophe escaping not necessary if we always use " to write attributes
14725 // (see: http://www.w3.org/TR/xml/#syntax)
14726
14727 for( std::size_t idx = 0; idx < m_str.size(); ++ idx ) {
14728 uchar c = m_str[idx];
14729 switch (c) {
14730 case '<': os << "<"; break;
14731 case '&': os << "&"; break;
14732
14733 case '>':
14734 // See: http://www.w3.org/TR/xml/#syntax
14735 if (idx > 2 && m_str[idx - 1] == ']' && m_str[idx - 2] == ']')
14736 os << ">";
14737 else
14738 os << c;
14739 break;
14740
14741 case '\"':
14742 if (m_forWhat == ForAttributes)
14743 os << """;
14744 else
14745 os << c;
14746 break;
14747
14748 default:
14749 // Check for control characters and invalid utf-8
14750
14751 // Escape control characters in standard ascii
14752 // see http://stackoverflow.com/questions/404107/why-are-control-characters-illegal-in-xml-1-0
14753 if (c < 0x09 || (c > 0x0D && c < 0x20) || c == 0x7F) {
14754 hexEscapeChar(os, c);
14755 break;
14756 }
14757
14758 // Plain ASCII: Write it to stream
14759 if (c < 0x7F) {
14760 os << c;
14761 break;
14762 }
14763
14764 // UTF-8 territory
14765 // Check if the encoding is valid and if it is not, hex escape bytes.
14766 // Important: We do not check the exact decoded values for validity, only the encoding format
14767 // First check that this bytes is a valid lead byte:
14768 // This means that it is not encoded as 1111 1XXX
14769 // Or as 10XX XXXX
14770 if (c < 0xC0 ||
14771 c >= 0xF8) {
14772 hexEscapeChar(os, c);
14773 break;
14774 }
14775
14776 auto encBytes = trailingBytes(c);
14777 // Are there enough bytes left to avoid accessing out-of-bounds memory?
14778 if (idx + encBytes - 1 >= m_str.size()) {
14779 hexEscapeChar(os, c);
14780 break;
14781 }
14782 // The header is valid, check data
14783 // The next encBytes bytes must together be a valid utf-8
14784 // This means: bitpattern 10XX XXXX and the extracted value is sane (ish)
14785 bool valid = true;
14786 uint32_t value = headerValue(c);
14787 for (std::size_t n = 1; n < encBytes; ++n) {
14788 uchar nc = m_str[idx + n];
14789 valid &= ((nc & 0xC0) == 0x80);
14790 value = (value << 6) | (nc & 0x3F);
14791 }
14792
14793 if (
14794 // Wrong bit pattern of following bytes
14795 (!valid) ||
14796 // Overlong encodings
14797 (value < 0x80) ||
14798 (0x80 <= value && value < 0x800 && encBytes > 2) ||
14799 (0x800 < value && value < 0x10000 && encBytes > 3) ||
14800 // Encoded value out of range
14801 (value >= 0x110000)
14802 ) {
14803 hexEscapeChar(os, c);
14804 break;
14805 }
14806
14807 // If we got here, this is in fact a valid(ish) utf-8 sequence
14808 for (std::size_t n = 0; n < encBytes; ++n) {
14809 os << m_str[idx + n];
14810 }
14811 idx += encBytes - 1;
14812 break;
14813 }
14814 }
14815 }
14816
operator <<(std::ostream & os,XmlEncode const & xmlEncode)14817 std::ostream& operator << ( std::ostream& os, XmlEncode const& xmlEncode ) {
14818 xmlEncode.encodeTo( os );
14819 return os;
14820 }
14821
ScopedElement(XmlWriter * writer)14822 XmlWriter::ScopedElement::ScopedElement( XmlWriter* writer )
14823 : m_writer( writer )
14824 {}
14825
ScopedElement(ScopedElement && other)14826 XmlWriter::ScopedElement::ScopedElement( ScopedElement&& other ) noexcept
14827 : m_writer( other.m_writer ){
14828 other.m_writer = nullptr;
14829 }
operator =(ScopedElement && other)14830 XmlWriter::ScopedElement& XmlWriter::ScopedElement::operator=( ScopedElement&& other ) noexcept {
14831 if ( m_writer ) {
14832 m_writer->endElement();
14833 }
14834 m_writer = other.m_writer;
14835 other.m_writer = nullptr;
14836 return *this;
14837 }
14838
~ScopedElement()14839 XmlWriter::ScopedElement::~ScopedElement() {
14840 if( m_writer )
14841 m_writer->endElement();
14842 }
14843
writeText(std::string const & text,bool indent)14844 XmlWriter::ScopedElement& XmlWriter::ScopedElement::writeText( std::string const& text, bool indent ) {
14845 m_writer->writeText( text, indent );
14846 return *this;
14847 }
14848
XmlWriter(std::ostream & os)14849 XmlWriter::XmlWriter( std::ostream& os ) : m_os( os )
14850 {
14851 writeDeclaration();
14852 }
14853
~XmlWriter()14854 XmlWriter::~XmlWriter() {
14855 while( !m_tags.empty() )
14856 endElement();
14857 }
14858
startElement(std::string const & name)14859 XmlWriter& XmlWriter::startElement( std::string const& name ) {
14860 ensureTagClosed();
14861 newlineIfNecessary();
14862 m_os << m_indent << '<' << name;
14863 m_tags.push_back( name );
14864 m_indent += " ";
14865 m_tagIsOpen = true;
14866 return *this;
14867 }
14868
scopedElement(std::string const & name)14869 XmlWriter::ScopedElement XmlWriter::scopedElement( std::string const& name ) {
14870 ScopedElement scoped( this );
14871 startElement( name );
14872 return scoped;
14873 }
14874
endElement()14875 XmlWriter& XmlWriter::endElement() {
14876 newlineIfNecessary();
14877 m_indent = m_indent.substr( 0, m_indent.size()-2 );
14878 if( m_tagIsOpen ) {
14879 m_os << "/>";
14880 m_tagIsOpen = false;
14881 }
14882 else {
14883 m_os << m_indent << "</" << m_tags.back() << ">";
14884 }
14885 m_os << std::endl;
14886 m_tags.pop_back();
14887 return *this;
14888 }
14889
writeAttribute(std::string const & name,std::string const & attribute)14890 XmlWriter& XmlWriter::writeAttribute( std::string const& name, std::string const& attribute ) {
14891 if( !name.empty() && !attribute.empty() )
14892 m_os << ' ' << name << "=\"" << XmlEncode( attribute, XmlEncode::ForAttributes ) << '"';
14893 return *this;
14894 }
14895
writeAttribute(std::string const & name,bool attribute)14896 XmlWriter& XmlWriter::writeAttribute( std::string const& name, bool attribute ) {
14897 m_os << ' ' << name << "=\"" << ( attribute ? "true" : "false" ) << '"';
14898 return *this;
14899 }
14900
writeText(std::string const & text,bool indent)14901 XmlWriter& XmlWriter::writeText( std::string const& text, bool indent ) {
14902 if( !text.empty() ){
14903 bool tagWasOpen = m_tagIsOpen;
14904 ensureTagClosed();
14905 if( tagWasOpen && indent )
14906 m_os << m_indent;
14907 m_os << XmlEncode( text );
14908 m_needsNewline = true;
14909 }
14910 return *this;
14911 }
14912
writeComment(std::string const & text)14913 XmlWriter& XmlWriter::writeComment( std::string const& text ) {
14914 ensureTagClosed();
14915 m_os << m_indent << "<!--" << text << "-->";
14916 m_needsNewline = true;
14917 return *this;
14918 }
14919
writeStylesheetRef(std::string const & url)14920 void XmlWriter::writeStylesheetRef( std::string const& url ) {
14921 m_os << "<?xml-stylesheet type=\"text/xsl\" href=\"" << url << "\"?>\n";
14922 }
14923
writeBlankLine()14924 XmlWriter& XmlWriter::writeBlankLine() {
14925 ensureTagClosed();
14926 m_os << '\n';
14927 return *this;
14928 }
14929
ensureTagClosed()14930 void XmlWriter::ensureTagClosed() {
14931 if( m_tagIsOpen ) {
14932 m_os << ">" << std::endl;
14933 m_tagIsOpen = false;
14934 }
14935 }
14936
writeDeclaration()14937 void XmlWriter::writeDeclaration() {
14938 m_os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
14939 }
14940
newlineIfNecessary()14941 void XmlWriter::newlineIfNecessary() {
14942 if( m_needsNewline ) {
14943 m_os << std::endl;
14944 m_needsNewline = false;
14945 }
14946 }
14947 }
14948 // end catch_xmlwriter.cpp
14949 // start catch_reporter_bases.cpp
14950
14951 #include <cstring>
14952 #include <cfloat>
14953 #include <cstdio>
14954 #include <cassert>
14955 #include <memory>
14956
14957 namespace Catch {
prepareExpandedExpression(AssertionResult & result)14958 void prepareExpandedExpression(AssertionResult& result) {
14959 result.getExpandedExpression();
14960 }
14961
14962 // Because formatting using c++ streams is stateful, drop down to C is required
14963 // Alternatively we could use stringstream, but its performance is... not good.
getFormattedDuration(double duration)14964 std::string getFormattedDuration( double duration ) {
14965 // Max exponent + 1 is required to represent the whole part
14966 // + 1 for decimal point
14967 // + 3 for the 3 decimal places
14968 // + 1 for null terminator
14969 const std::size_t maxDoubleSize = DBL_MAX_10_EXP + 1 + 1 + 3 + 1;
14970 char buffer[maxDoubleSize];
14971
14972 // Save previous errno, to prevent sprintf from overwriting it
14973 ErrnoGuard guard;
14974 #ifdef _MSC_VER
14975 sprintf_s(buffer, "%.3f", duration);
14976 #else
14977 std::sprintf(buffer, "%.3f", duration);
14978 #endif
14979 return std::string(buffer);
14980 }
14981
serializeFilters(std::vector<std::string> const & container)14982 std::string serializeFilters( std::vector<std::string> const& container ) {
14983 ReusableStringStream oss;
14984 bool first = true;
14985 for (auto&& filter : container)
14986 {
14987 if (!first)
14988 oss << ' ';
14989 else
14990 first = false;
14991
14992 oss << filter;
14993 }
14994 return oss.str();
14995 }
14996
TestEventListenerBase(ReporterConfig const & _config)14997 TestEventListenerBase::TestEventListenerBase(ReporterConfig const & _config)
14998 :StreamingReporterBase(_config) {}
14999
getSupportedVerbosities()15000 std::set<Verbosity> TestEventListenerBase::getSupportedVerbosities() {
15001 return { Verbosity::Quiet, Verbosity::Normal, Verbosity::High };
15002 }
15003
assertionStarting(AssertionInfo const &)15004 void TestEventListenerBase::assertionStarting(AssertionInfo const &) {}
15005
assertionEnded(AssertionStats const &)15006 bool TestEventListenerBase::assertionEnded(AssertionStats const &) {
15007 return false;
15008 }
15009
15010 } // end namespace Catch
15011 // end catch_reporter_bases.cpp
15012 // start catch_reporter_compact.cpp
15013
15014 namespace {
15015
15016 #ifdef CATCH_PLATFORM_MAC
failedString()15017 const char* failedString() { return "FAILED"; }
passedString()15018 const char* passedString() { return "PASSED"; }
15019 #else
15020 const char* failedString() { return "failed"; }
15021 const char* passedString() { return "passed"; }
15022 #endif
15023
15024 // Colour::LightGrey
dimColour()15025 Catch::Colour::Code dimColour() { return Catch::Colour::FileName; }
15026
bothOrAll(std::size_t count)15027 std::string bothOrAll( std::size_t count ) {
15028 return count == 1 ? std::string() :
15029 count == 2 ? "both " : "all " ;
15030 }
15031
15032 } // anon namespace
15033
15034 namespace Catch {
15035 namespace {
15036 // Colour, message variants:
15037 // - white: No tests ran.
15038 // - red: Failed [both/all] N test cases, failed [both/all] M assertions.
15039 // - white: Passed [both/all] N test cases (no assertions).
15040 // - red: Failed N tests cases, failed M assertions.
15041 // - green: Passed [both/all] N tests cases with M assertions.
printTotals(std::ostream & out,const Totals & totals)15042 void printTotals(std::ostream& out, const Totals& totals) {
15043 if (totals.testCases.total() == 0) {
15044 out << "No tests ran.";
15045 } else if (totals.testCases.failed == totals.testCases.total()) {
15046 Colour colour(Colour::ResultError);
15047 const std::string qualify_assertions_failed =
15048 totals.assertions.failed == totals.assertions.total() ?
15049 bothOrAll(totals.assertions.failed) : std::string();
15050 out <<
15051 "Failed " << bothOrAll(totals.testCases.failed)
15052 << pluralise(totals.testCases.failed, "test case") << ", "
15053 "failed " << qualify_assertions_failed <<
15054 pluralise(totals.assertions.failed, "assertion") << '.';
15055 } else if (totals.assertions.total() == 0) {
15056 out <<
15057 "Passed " << bothOrAll(totals.testCases.total())
15058 << pluralise(totals.testCases.total(), "test case")
15059 << " (no assertions).";
15060 } else if (totals.assertions.failed) {
15061 Colour colour(Colour::ResultError);
15062 out <<
15063 "Failed " << pluralise(totals.testCases.failed, "test case") << ", "
15064 "failed " << pluralise(totals.assertions.failed, "assertion") << '.';
15065 } else {
15066 Colour colour(Colour::ResultSuccess);
15067 out <<
15068 "Passed " << bothOrAll(totals.testCases.passed)
15069 << pluralise(totals.testCases.passed, "test case") <<
15070 " with " << pluralise(totals.assertions.passed, "assertion") << '.';
15071 }
15072 }
15073
15074 // Implementation of CompactReporter formatting
15075 class AssertionPrinter {
15076 public:
15077 AssertionPrinter& operator= (AssertionPrinter const&) = delete;
15078 AssertionPrinter(AssertionPrinter const&) = delete;
AssertionPrinter(std::ostream & _stream,AssertionStats const & _stats,bool _printInfoMessages)15079 AssertionPrinter(std::ostream& _stream, AssertionStats const& _stats, bool _printInfoMessages)
15080 : stream(_stream)
15081 , result(_stats.assertionResult)
15082 , messages(_stats.infoMessages)
15083 , itMessage(_stats.infoMessages.begin())
15084 , printInfoMessages(_printInfoMessages) {}
15085
print()15086 void print() {
15087 printSourceInfo();
15088
15089 itMessage = messages.begin();
15090
15091 switch (result.getResultType()) {
15092 case ResultWas::Ok:
15093 printResultType(Colour::ResultSuccess, passedString());
15094 printOriginalExpression();
15095 printReconstructedExpression();
15096 if (!result.hasExpression())
15097 printRemainingMessages(Colour::None);
15098 else
15099 printRemainingMessages();
15100 break;
15101 case ResultWas::ExpressionFailed:
15102 if (result.isOk())
15103 printResultType(Colour::ResultSuccess, failedString() + std::string(" - but was ok"));
15104 else
15105 printResultType(Colour::Error, failedString());
15106 printOriginalExpression();
15107 printReconstructedExpression();
15108 printRemainingMessages();
15109 break;
15110 case ResultWas::ThrewException:
15111 printResultType(Colour::Error, failedString());
15112 printIssue("unexpected exception with message:");
15113 printMessage();
15114 printExpressionWas();
15115 printRemainingMessages();
15116 break;
15117 case ResultWas::FatalErrorCondition:
15118 printResultType(Colour::Error, failedString());
15119 printIssue("fatal error condition with message:");
15120 printMessage();
15121 printExpressionWas();
15122 printRemainingMessages();
15123 break;
15124 case ResultWas::DidntThrowException:
15125 printResultType(Colour::Error, failedString());
15126 printIssue("expected exception, got none");
15127 printExpressionWas();
15128 printRemainingMessages();
15129 break;
15130 case ResultWas::Info:
15131 printResultType(Colour::None, "info");
15132 printMessage();
15133 printRemainingMessages();
15134 break;
15135 case ResultWas::Warning:
15136 printResultType(Colour::None, "warning");
15137 printMessage();
15138 printRemainingMessages();
15139 break;
15140 case ResultWas::ExplicitFailure:
15141 printResultType(Colour::Error, failedString());
15142 printIssue("explicitly");
15143 printRemainingMessages(Colour::None);
15144 break;
15145 // These cases are here to prevent compiler warnings
15146 case ResultWas::Unknown:
15147 case ResultWas::FailureBit:
15148 case ResultWas::Exception:
15149 printResultType(Colour::Error, "** internal error **");
15150 break;
15151 }
15152 }
15153
15154 private:
printSourceInfo() const15155 void printSourceInfo() const {
15156 Colour colourGuard(Colour::FileName);
15157 stream << result.getSourceInfo() << ':';
15158 }
15159
printResultType(Colour::Code colour,std::string const & passOrFail) const15160 void printResultType(Colour::Code colour, std::string const& passOrFail) const {
15161 if (!passOrFail.empty()) {
15162 {
15163 Colour colourGuard(colour);
15164 stream << ' ' << passOrFail;
15165 }
15166 stream << ':';
15167 }
15168 }
15169
printIssue(std::string const & issue) const15170 void printIssue(std::string const& issue) const {
15171 stream << ' ' << issue;
15172 }
15173
printExpressionWas()15174 void printExpressionWas() {
15175 if (result.hasExpression()) {
15176 stream << ';';
15177 {
15178 Colour colour(dimColour());
15179 stream << " expression was:";
15180 }
15181 printOriginalExpression();
15182 }
15183 }
15184
printOriginalExpression() const15185 void printOriginalExpression() const {
15186 if (result.hasExpression()) {
15187 stream << ' ' << result.getExpression();
15188 }
15189 }
15190
printReconstructedExpression() const15191 void printReconstructedExpression() const {
15192 if (result.hasExpandedExpression()) {
15193 {
15194 Colour colour(dimColour());
15195 stream << " for: ";
15196 }
15197 stream << result.getExpandedExpression();
15198 }
15199 }
15200
printMessage()15201 void printMessage() {
15202 if (itMessage != messages.end()) {
15203 stream << " '" << itMessage->message << '\'';
15204 ++itMessage;
15205 }
15206 }
15207
printRemainingMessages(Colour::Code colour=dimColour ())15208 void printRemainingMessages(Colour::Code colour = dimColour()) {
15209 if (itMessage == messages.end())
15210 return;
15211
15212 const auto itEnd = messages.cend();
15213 const auto N = static_cast<std::size_t>(std::distance(itMessage, itEnd));
15214
15215 {
15216 Colour colourGuard(colour);
15217 stream << " with " << pluralise(N, "message") << ':';
15218 }
15219
15220 while (itMessage != itEnd) {
15221 // If this assertion is a warning ignore any INFO messages
15222 if (printInfoMessages || itMessage->type != ResultWas::Info) {
15223 printMessage();
15224 if (itMessage != itEnd) {
15225 Colour colourGuard(dimColour());
15226 stream << " and";
15227 }
15228 continue;
15229 }
15230 ++itMessage;
15231 }
15232 }
15233
15234 private:
15235 std::ostream& stream;
15236 AssertionResult const& result;
15237 std::vector<MessageInfo> messages;
15238 std::vector<MessageInfo>::const_iterator itMessage;
15239 bool printInfoMessages;
15240 };
15241
15242 } // anon namespace
15243
getDescription()15244 std::string CompactReporter::getDescription() {
15245 return "Reports test results on a single line, suitable for IDEs";
15246 }
15247
getPreferences() const15248 ReporterPreferences CompactReporter::getPreferences() const {
15249 return m_reporterPrefs;
15250 }
15251
noMatchingTestCases(std::string const & spec)15252 void CompactReporter::noMatchingTestCases( std::string const& spec ) {
15253 stream << "No test cases matched '" << spec << '\'' << std::endl;
15254 }
15255
assertionStarting(AssertionInfo const &)15256 void CompactReporter::assertionStarting( AssertionInfo const& ) {}
15257
assertionEnded(AssertionStats const & _assertionStats)15258 bool CompactReporter::assertionEnded( AssertionStats const& _assertionStats ) {
15259 AssertionResult const& result = _assertionStats.assertionResult;
15260
15261 bool printInfoMessages = true;
15262
15263 // Drop out if result was successful and we're not printing those
15264 if( !m_config->includeSuccessfulResults() && result.isOk() ) {
15265 if( result.getResultType() != ResultWas::Warning )
15266 return false;
15267 printInfoMessages = false;
15268 }
15269
15270 AssertionPrinter printer( stream, _assertionStats, printInfoMessages );
15271 printer.print();
15272
15273 stream << std::endl;
15274 return true;
15275 }
15276
sectionEnded(SectionStats const & _sectionStats)15277 void CompactReporter::sectionEnded(SectionStats const& _sectionStats) {
15278 if (m_config->showDurations() == ShowDurations::Always) {
15279 stream << getFormattedDuration(_sectionStats.durationInSeconds) << " s: " << _sectionStats.sectionInfo.name << std::endl;
15280 }
15281 }
15282
testRunEnded(TestRunStats const & _testRunStats)15283 void CompactReporter::testRunEnded( TestRunStats const& _testRunStats ) {
15284 printTotals( stream, _testRunStats.totals );
15285 stream << '\n' << std::endl;
15286 StreamingReporterBase::testRunEnded( _testRunStats );
15287 }
15288
~CompactReporter()15289 CompactReporter::~CompactReporter() {}
15290
15291 CATCH_REGISTER_REPORTER( "compact", CompactReporter )
15292
15293 } // end namespace Catch
15294 // end catch_reporter_compact.cpp
15295 // start catch_reporter_console.cpp
15296
15297 #include <cfloat>
15298 #include <cstdio>
15299
15300 #if defined(_MSC_VER)
15301 #pragma warning(push)
15302 #pragma warning(disable:4061) // Not all labels are EXPLICITLY handled in switch
15303 // Note that 4062 (not all labels are handled and default is missing) is enabled
15304 #endif
15305
15306 #if defined(__clang__)
15307 # pragma clang diagnostic push
15308 // For simplicity, benchmarking-only helpers are always enabled
15309 # pragma clang diagnostic ignored "-Wunused-function"
15310 #endif
15311
15312 namespace Catch {
15313
15314 namespace {
15315
15316 // Formatter impl for ConsoleReporter
15317 class ConsoleAssertionPrinter {
15318 public:
15319 ConsoleAssertionPrinter& operator= (ConsoleAssertionPrinter const&) = delete;
15320 ConsoleAssertionPrinter(ConsoleAssertionPrinter const&) = delete;
ConsoleAssertionPrinter(std::ostream & _stream,AssertionStats const & _stats,bool _printInfoMessages)15321 ConsoleAssertionPrinter(std::ostream& _stream, AssertionStats const& _stats, bool _printInfoMessages)
15322 : stream(_stream),
15323 stats(_stats),
15324 result(_stats.assertionResult),
15325 colour(Colour::None),
15326 message(result.getMessage()),
15327 messages(_stats.infoMessages),
15328 printInfoMessages(_printInfoMessages) {
15329 switch (result.getResultType()) {
15330 case ResultWas::Ok:
15331 colour = Colour::Success;
15332 passOrFail = "PASSED";
15333 //if( result.hasMessage() )
15334 if (_stats.infoMessages.size() == 1)
15335 messageLabel = "with message";
15336 if (_stats.infoMessages.size() > 1)
15337 messageLabel = "with messages";
15338 break;
15339 case ResultWas::ExpressionFailed:
15340 if (result.isOk()) {
15341 colour = Colour::Success;
15342 passOrFail = "FAILED - but was ok";
15343 } else {
15344 colour = Colour::Error;
15345 passOrFail = "FAILED";
15346 }
15347 if (_stats.infoMessages.size() == 1)
15348 messageLabel = "with message";
15349 if (_stats.infoMessages.size() > 1)
15350 messageLabel = "with messages";
15351 break;
15352 case ResultWas::ThrewException:
15353 colour = Colour::Error;
15354 passOrFail = "FAILED";
15355 messageLabel = "due to unexpected exception with ";
15356 if (_stats.infoMessages.size() == 1)
15357 messageLabel += "message";
15358 if (_stats.infoMessages.size() > 1)
15359 messageLabel += "messages";
15360 break;
15361 case ResultWas::FatalErrorCondition:
15362 colour = Colour::Error;
15363 passOrFail = "FAILED";
15364 messageLabel = "due to a fatal error condition";
15365 break;
15366 case ResultWas::DidntThrowException:
15367 colour = Colour::Error;
15368 passOrFail = "FAILED";
15369 messageLabel = "because no exception was thrown where one was expected";
15370 break;
15371 case ResultWas::Info:
15372 messageLabel = "info";
15373 break;
15374 case ResultWas::Warning:
15375 messageLabel = "warning";
15376 break;
15377 case ResultWas::ExplicitFailure:
15378 passOrFail = "FAILED";
15379 colour = Colour::Error;
15380 if (_stats.infoMessages.size() == 1)
15381 messageLabel = "explicitly with message";
15382 if (_stats.infoMessages.size() > 1)
15383 messageLabel = "explicitly with messages";
15384 break;
15385 // These cases are here to prevent compiler warnings
15386 case ResultWas::Unknown:
15387 case ResultWas::FailureBit:
15388 case ResultWas::Exception:
15389 passOrFail = "** internal error **";
15390 colour = Colour::Error;
15391 break;
15392 }
15393 }
15394
print() const15395 void print() const {
15396 printSourceInfo();
15397 if (stats.totals.assertions.total() > 0) {
15398 printResultType();
15399 printOriginalExpression();
15400 printReconstructedExpression();
15401 } else {
15402 stream << '\n';
15403 }
15404 printMessage();
15405 }
15406
15407 private:
printResultType() const15408 void printResultType() const {
15409 if (!passOrFail.empty()) {
15410 Colour colourGuard(colour);
15411 stream << passOrFail << ":\n";
15412 }
15413 }
printOriginalExpression() const15414 void printOriginalExpression() const {
15415 if (result.hasExpression()) {
15416 Colour colourGuard(Colour::OriginalExpression);
15417 stream << " ";
15418 stream << result.getExpressionInMacro();
15419 stream << '\n';
15420 }
15421 }
printReconstructedExpression() const15422 void printReconstructedExpression() const {
15423 if (result.hasExpandedExpression()) {
15424 stream << "with expansion:\n";
15425 Colour colourGuard(Colour::ReconstructedExpression);
15426 stream << Column(result.getExpandedExpression()).indent(2) << '\n';
15427 }
15428 }
printMessage() const15429 void printMessage() const {
15430 if (!messageLabel.empty())
15431 stream << messageLabel << ':' << '\n';
15432 for (auto const& msg : messages) {
15433 // If this assertion is a warning ignore any INFO messages
15434 if (printInfoMessages || msg.type != ResultWas::Info)
15435 stream << Column(msg.message).indent(2) << '\n';
15436 }
15437 }
printSourceInfo() const15438 void printSourceInfo() const {
15439 Colour colourGuard(Colour::FileName);
15440 stream << result.getSourceInfo() << ": ";
15441 }
15442
15443 std::ostream& stream;
15444 AssertionStats const& stats;
15445 AssertionResult const& result;
15446 Colour::Code colour;
15447 std::string passOrFail;
15448 std::string messageLabel;
15449 std::string message;
15450 std::vector<MessageInfo> messages;
15451 bool printInfoMessages;
15452 };
15453
makeRatio(std::size_t number,std::size_t total)15454 std::size_t makeRatio(std::size_t number, std::size_t total) {
15455 std::size_t ratio = total > 0 ? CATCH_CONFIG_CONSOLE_WIDTH * number / total : 0;
15456 return (ratio == 0 && number > 0) ? 1 : ratio;
15457 }
15458
findMax(std::size_t & i,std::size_t & j,std::size_t & k)15459 std::size_t& findMax(std::size_t& i, std::size_t& j, std::size_t& k) {
15460 if (i > j && i > k)
15461 return i;
15462 else if (j > k)
15463 return j;
15464 else
15465 return k;
15466 }
15467
15468 struct ColumnInfo {
15469 enum Justification { Left, Right };
15470 std::string name;
15471 int width;
15472 Justification justification;
15473 };
15474 struct ColumnBreak {};
15475 struct RowBreak {};
15476
15477 class Duration {
15478 enum class Unit {
15479 Auto,
15480 Nanoseconds,
15481 Microseconds,
15482 Milliseconds,
15483 Seconds,
15484 Minutes
15485 };
15486 static const uint64_t s_nanosecondsInAMicrosecond = 1000;
15487 static const uint64_t s_nanosecondsInAMillisecond = 1000 * s_nanosecondsInAMicrosecond;
15488 static const uint64_t s_nanosecondsInASecond = 1000 * s_nanosecondsInAMillisecond;
15489 static const uint64_t s_nanosecondsInAMinute = 60 * s_nanosecondsInASecond;
15490
15491 uint64_t m_inNanoseconds;
15492 Unit m_units;
15493
15494 public:
Duration(double inNanoseconds,Unit units=Unit::Auto)15495 explicit Duration(double inNanoseconds, Unit units = Unit::Auto)
15496 : Duration(static_cast<uint64_t>(inNanoseconds), units) {
15497 }
15498
Duration(uint64_t inNanoseconds,Unit units=Unit::Auto)15499 explicit Duration(uint64_t inNanoseconds, Unit units = Unit::Auto)
15500 : m_inNanoseconds(inNanoseconds),
15501 m_units(units) {
15502 if (m_units == Unit::Auto) {
15503 if (m_inNanoseconds < s_nanosecondsInAMicrosecond)
15504 m_units = Unit::Nanoseconds;
15505 else if (m_inNanoseconds < s_nanosecondsInAMillisecond)
15506 m_units = Unit::Microseconds;
15507 else if (m_inNanoseconds < s_nanosecondsInASecond)
15508 m_units = Unit::Milliseconds;
15509 else if (m_inNanoseconds < s_nanosecondsInAMinute)
15510 m_units = Unit::Seconds;
15511 else
15512 m_units = Unit::Minutes;
15513 }
15514
15515 }
15516
value() const15517 auto value() const -> double {
15518 switch (m_units) {
15519 case Unit::Microseconds:
15520 return m_inNanoseconds / static_cast<double>(s_nanosecondsInAMicrosecond);
15521 case Unit::Milliseconds:
15522 return m_inNanoseconds / static_cast<double>(s_nanosecondsInAMillisecond);
15523 case Unit::Seconds:
15524 return m_inNanoseconds / static_cast<double>(s_nanosecondsInASecond);
15525 case Unit::Minutes:
15526 return m_inNanoseconds / static_cast<double>(s_nanosecondsInAMinute);
15527 default:
15528 return static_cast<double>(m_inNanoseconds);
15529 }
15530 }
unitsAsString() const15531 auto unitsAsString() const -> std::string {
15532 switch (m_units) {
15533 case Unit::Nanoseconds:
15534 return "ns";
15535 case Unit::Microseconds:
15536 return "us";
15537 case Unit::Milliseconds:
15538 return "ms";
15539 case Unit::Seconds:
15540 return "s";
15541 case Unit::Minutes:
15542 return "m";
15543 default:
15544 return "** internal error **";
15545 }
15546
15547 }
operator <<(std::ostream & os,Duration const & duration)15548 friend auto operator << (std::ostream& os, Duration const& duration) -> std::ostream& {
15549 return os << duration.value() << " " << duration.unitsAsString();
15550 }
15551 };
15552 } // end anon namespace
15553
15554 class TablePrinter {
15555 std::ostream& m_os;
15556 std::vector<ColumnInfo> m_columnInfos;
15557 std::ostringstream m_oss;
15558 int m_currentColumn = -1;
15559 bool m_isOpen = false;
15560
15561 public:
TablePrinter(std::ostream & os,std::vector<ColumnInfo> columnInfos)15562 TablePrinter( std::ostream& os, std::vector<ColumnInfo> columnInfos )
15563 : m_os( os ),
15564 m_columnInfos( std::move( columnInfos ) ) {}
15565
columnInfos() const15566 auto columnInfos() const -> std::vector<ColumnInfo> const& {
15567 return m_columnInfos;
15568 }
15569
open()15570 void open() {
15571 if (!m_isOpen) {
15572 m_isOpen = true;
15573 *this << RowBreak();
15574
15575 Columns headerCols;
15576 Spacer spacer(2);
15577 for (auto const& info : m_columnInfos) {
15578 headerCols += Column(info.name).width(static_cast<std::size_t>(info.width - 2));
15579 headerCols += spacer;
15580 }
15581 m_os << headerCols << "\n";
15582
15583 m_os << Catch::getLineOfChars<'-'>() << "\n";
15584 }
15585 }
close()15586 void close() {
15587 if (m_isOpen) {
15588 *this << RowBreak();
15589 m_os << std::endl;
15590 m_isOpen = false;
15591 }
15592 }
15593
15594 template<typename T>
operator <<(TablePrinter & tp,T const & value)15595 friend TablePrinter& operator << (TablePrinter& tp, T const& value) {
15596 tp.m_oss << value;
15597 return tp;
15598 }
15599
operator <<(TablePrinter & tp,ColumnBreak)15600 friend TablePrinter& operator << (TablePrinter& tp, ColumnBreak) {
15601 auto colStr = tp.m_oss.str();
15602 // This takes account of utf8 encodings
15603 auto strSize = Catch::StringRef(colStr).numberOfCharacters();
15604 tp.m_oss.str("");
15605 tp.open();
15606 if (tp.m_currentColumn == static_cast<int>(tp.m_columnInfos.size() - 1)) {
15607 tp.m_currentColumn = -1;
15608 tp.m_os << "\n";
15609 }
15610 tp.m_currentColumn++;
15611
15612 auto colInfo = tp.m_columnInfos[tp.m_currentColumn];
15613 auto padding = (strSize + 2 < static_cast<std::size_t>(colInfo.width))
15614 ? std::string(colInfo.width - (strSize + 2), ' ')
15615 : std::string();
15616 if (colInfo.justification == ColumnInfo::Left)
15617 tp.m_os << colStr << padding << " ";
15618 else
15619 tp.m_os << padding << colStr << " ";
15620 return tp;
15621 }
15622
operator <<(TablePrinter & tp,RowBreak)15623 friend TablePrinter& operator << (TablePrinter& tp, RowBreak) {
15624 if (tp.m_currentColumn > 0) {
15625 tp.m_os << "\n";
15626 tp.m_currentColumn = -1;
15627 }
15628 return tp;
15629 }
15630 };
15631
ConsoleReporter(ReporterConfig const & config)15632 ConsoleReporter::ConsoleReporter(ReporterConfig const& config)
15633 : StreamingReporterBase(config),
15634 m_tablePrinter(new TablePrinter(config.stream(),
15635 {
15636 { "benchmark name", CATCH_CONFIG_CONSOLE_WIDTH - 32, ColumnInfo::Left },
15637 { "samples mean std dev", 14, ColumnInfo::Right },
15638 { "iterations low mean low std dev", 14, ColumnInfo::Right },
15639 { "estimated high mean high std dev", 14, ColumnInfo::Right }
15640 })) {}
15641 ConsoleReporter::~ConsoleReporter() = default;
15642
getDescription()15643 std::string ConsoleReporter::getDescription() {
15644 return "Reports test results as plain lines of text";
15645 }
15646
noMatchingTestCases(std::string const & spec)15647 void ConsoleReporter::noMatchingTestCases(std::string const& spec) {
15648 stream << "No test cases matched '" << spec << '\'' << std::endl;
15649 }
15650
assertionStarting(AssertionInfo const &)15651 void ConsoleReporter::assertionStarting(AssertionInfo const&) {}
15652
assertionEnded(AssertionStats const & _assertionStats)15653 bool ConsoleReporter::assertionEnded(AssertionStats const& _assertionStats) {
15654 AssertionResult const& result = _assertionStats.assertionResult;
15655
15656 bool includeResults = m_config->includeSuccessfulResults() || !result.isOk();
15657
15658 // Drop out if result was successful but we're not printing them.
15659 if (!includeResults && result.getResultType() != ResultWas::Warning)
15660 return false;
15661
15662 lazyPrint();
15663
15664 ConsoleAssertionPrinter printer(stream, _assertionStats, includeResults);
15665 printer.print();
15666 stream << std::endl;
15667 return true;
15668 }
15669
sectionStarting(SectionInfo const & _sectionInfo)15670 void ConsoleReporter::sectionStarting(SectionInfo const& _sectionInfo) {
15671 m_tablePrinter->close();
15672 m_headerPrinted = false;
15673 StreamingReporterBase::sectionStarting(_sectionInfo);
15674 }
sectionEnded(SectionStats const & _sectionStats)15675 void ConsoleReporter::sectionEnded(SectionStats const& _sectionStats) {
15676 m_tablePrinter->close();
15677 if (_sectionStats.missingAssertions) {
15678 lazyPrint();
15679 Colour colour(Colour::ResultError);
15680 if (m_sectionStack.size() > 1)
15681 stream << "\nNo assertions in section";
15682 else
15683 stream << "\nNo assertions in test case";
15684 stream << " '" << _sectionStats.sectionInfo.name << "'\n" << std::endl;
15685 }
15686 if (m_config->showDurations() == ShowDurations::Always) {
15687 stream << getFormattedDuration(_sectionStats.durationInSeconds) << " s: " << _sectionStats.sectionInfo.name << std::endl;
15688 }
15689 if (m_headerPrinted) {
15690 m_headerPrinted = false;
15691 }
15692 StreamingReporterBase::sectionEnded(_sectionStats);
15693 }
15694
15695 #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
benchmarkPreparing(std::string const & name)15696 void ConsoleReporter::benchmarkPreparing(std::string const& name) {
15697 lazyPrintWithoutClosingBenchmarkTable();
15698
15699 auto nameCol = Column(name).width(static_cast<std::size_t>(m_tablePrinter->columnInfos()[0].width - 2));
15700
15701 bool firstLine = true;
15702 for (auto line : nameCol) {
15703 if (!firstLine)
15704 (*m_tablePrinter) << ColumnBreak() << ColumnBreak() << ColumnBreak();
15705 else
15706 firstLine = false;
15707
15708 (*m_tablePrinter) << line << ColumnBreak();
15709 }
15710 }
15711
benchmarkStarting(BenchmarkInfo const & info)15712 void ConsoleReporter::benchmarkStarting(BenchmarkInfo const& info) {
15713 (*m_tablePrinter) << info.samples << ColumnBreak()
15714 << info.iterations << ColumnBreak()
15715 << Duration(info.estimatedDuration) << ColumnBreak();
15716 }
benchmarkEnded(BenchmarkStats<> const & stats)15717 void ConsoleReporter::benchmarkEnded(BenchmarkStats<> const& stats) {
15718 (*m_tablePrinter) << ColumnBreak()
15719 << Duration(stats.mean.point.count()) << ColumnBreak()
15720 << Duration(stats.mean.lower_bound.count()) << ColumnBreak()
15721 << Duration(stats.mean.upper_bound.count()) << ColumnBreak() << ColumnBreak()
15722 << Duration(stats.standardDeviation.point.count()) << ColumnBreak()
15723 << Duration(stats.standardDeviation.lower_bound.count()) << ColumnBreak()
15724 << Duration(stats.standardDeviation.upper_bound.count()) << ColumnBreak() << ColumnBreak() << ColumnBreak() << ColumnBreak() << ColumnBreak();
15725 }
15726
benchmarkFailed(std::string const & error)15727 void ConsoleReporter::benchmarkFailed(std::string const& error) {
15728 Colour colour(Colour::Red);
15729 (*m_tablePrinter)
15730 << "Benchmark failed (" << error << ")"
15731 << ColumnBreak() << RowBreak();
15732 }
15733 #endif // CATCH_CONFIG_ENABLE_BENCHMARKING
15734
testCaseEnded(TestCaseStats const & _testCaseStats)15735 void ConsoleReporter::testCaseEnded(TestCaseStats const& _testCaseStats) {
15736 m_tablePrinter->close();
15737 StreamingReporterBase::testCaseEnded(_testCaseStats);
15738 m_headerPrinted = false;
15739 }
testGroupEnded(TestGroupStats const & _testGroupStats)15740 void ConsoleReporter::testGroupEnded(TestGroupStats const& _testGroupStats) {
15741 if (currentGroupInfo.used) {
15742 printSummaryDivider();
15743 stream << "Summary for group '" << _testGroupStats.groupInfo.name << "':\n";
15744 printTotals(_testGroupStats.totals);
15745 stream << '\n' << std::endl;
15746 }
15747 StreamingReporterBase::testGroupEnded(_testGroupStats);
15748 }
testRunEnded(TestRunStats const & _testRunStats)15749 void ConsoleReporter::testRunEnded(TestRunStats const& _testRunStats) {
15750 printTotalsDivider(_testRunStats.totals);
15751 printTotals(_testRunStats.totals);
15752 stream << std::endl;
15753 StreamingReporterBase::testRunEnded(_testRunStats);
15754 }
testRunStarting(TestRunInfo const & _testInfo)15755 void ConsoleReporter::testRunStarting(TestRunInfo const& _testInfo) {
15756 StreamingReporterBase::testRunStarting(_testInfo);
15757 printTestFilters();
15758 }
15759
lazyPrint()15760 void ConsoleReporter::lazyPrint() {
15761
15762 m_tablePrinter->close();
15763 lazyPrintWithoutClosingBenchmarkTable();
15764 }
15765
lazyPrintWithoutClosingBenchmarkTable()15766 void ConsoleReporter::lazyPrintWithoutClosingBenchmarkTable() {
15767
15768 if (!currentTestRunInfo.used)
15769 lazyPrintRunInfo();
15770 if (!currentGroupInfo.used)
15771 lazyPrintGroupInfo();
15772
15773 if (!m_headerPrinted) {
15774 printTestCaseAndSectionHeader();
15775 m_headerPrinted = true;
15776 }
15777 }
lazyPrintRunInfo()15778 void ConsoleReporter::lazyPrintRunInfo() {
15779 stream << '\n' << getLineOfChars<'~'>() << '\n';
15780 Colour colour(Colour::SecondaryText);
15781 stream << currentTestRunInfo->name
15782 << " is a Catch v" << libraryVersion() << " host application.\n"
15783 << "Run with -? for options\n\n";
15784
15785 if (m_config->rngSeed() != 0)
15786 stream << "Randomness seeded to: " << m_config->rngSeed() << "\n\n";
15787
15788 currentTestRunInfo.used = true;
15789 }
lazyPrintGroupInfo()15790 void ConsoleReporter::lazyPrintGroupInfo() {
15791 if (!currentGroupInfo->name.empty() && currentGroupInfo->groupsCounts > 1) {
15792 printClosedHeader("Group: " + currentGroupInfo->name);
15793 currentGroupInfo.used = true;
15794 }
15795 }
printTestCaseAndSectionHeader()15796 void ConsoleReporter::printTestCaseAndSectionHeader() {
15797 assert(!m_sectionStack.empty());
15798 printOpenHeader(currentTestCaseInfo->name);
15799
15800 if (m_sectionStack.size() > 1) {
15801 Colour colourGuard(Colour::Headers);
15802
15803 auto
15804 it = m_sectionStack.begin() + 1, // Skip first section (test case)
15805 itEnd = m_sectionStack.end();
15806 for (; it != itEnd; ++it)
15807 printHeaderString(it->name, 2);
15808 }
15809
15810 SourceLineInfo lineInfo = m_sectionStack.back().lineInfo;
15811
15812 if (!lineInfo.empty()) {
15813 stream << getLineOfChars<'-'>() << '\n';
15814 Colour colourGuard(Colour::FileName);
15815 stream << lineInfo << '\n';
15816 }
15817 stream << getLineOfChars<'.'>() << '\n' << std::endl;
15818 }
15819
printClosedHeader(std::string const & _name)15820 void ConsoleReporter::printClosedHeader(std::string const& _name) {
15821 printOpenHeader(_name);
15822 stream << getLineOfChars<'.'>() << '\n';
15823 }
printOpenHeader(std::string const & _name)15824 void ConsoleReporter::printOpenHeader(std::string const& _name) {
15825 stream << getLineOfChars<'-'>() << '\n';
15826 {
15827 Colour colourGuard(Colour::Headers);
15828 printHeaderString(_name);
15829 }
15830 }
15831
15832 // if string has a : in first line will set indent to follow it on
15833 // subsequent lines
printHeaderString(std::string const & _string,std::size_t indent)15834 void ConsoleReporter::printHeaderString(std::string const& _string, std::size_t indent) {
15835 std::size_t i = _string.find(": ");
15836 if (i != std::string::npos)
15837 i += 2;
15838 else
15839 i = 0;
15840 stream << Column(_string).indent(indent + i).initialIndent(indent) << '\n';
15841 }
15842
15843 struct SummaryColumn {
15844
SummaryColumnCatch::SummaryColumn15845 SummaryColumn( std::string _label, Colour::Code _colour )
15846 : label( std::move( _label ) ),
15847 colour( _colour ) {}
addRowCatch::SummaryColumn15848 SummaryColumn addRow( std::size_t count ) {
15849 ReusableStringStream rss;
15850 rss << count;
15851 std::string row = rss.str();
15852 for (auto& oldRow : rows) {
15853 while (oldRow.size() < row.size())
15854 oldRow = ' ' + oldRow;
15855 while (oldRow.size() > row.size())
15856 row = ' ' + row;
15857 }
15858 rows.push_back(row);
15859 return *this;
15860 }
15861
15862 std::string label;
15863 Colour::Code colour;
15864 std::vector<std::string> rows;
15865
15866 };
15867
printTotals(Totals const & totals)15868 void ConsoleReporter::printTotals( Totals const& totals ) {
15869 if (totals.testCases.total() == 0) {
15870 stream << Colour(Colour::Warning) << "No tests ran\n";
15871 } else if (totals.assertions.total() > 0 && totals.testCases.allPassed()) {
15872 stream << Colour(Colour::ResultSuccess) << "All tests passed";
15873 stream << " ("
15874 << pluralise(totals.assertions.passed, "assertion") << " in "
15875 << pluralise(totals.testCases.passed, "test case") << ')'
15876 << '\n';
15877 } else {
15878
15879 std::vector<SummaryColumn> columns;
15880 columns.push_back(SummaryColumn("", Colour::None)
15881 .addRow(totals.testCases.total())
15882 .addRow(totals.assertions.total()));
15883 columns.push_back(SummaryColumn("passed", Colour::Success)
15884 .addRow(totals.testCases.passed)
15885 .addRow(totals.assertions.passed));
15886 columns.push_back(SummaryColumn("failed", Colour::ResultError)
15887 .addRow(totals.testCases.failed)
15888 .addRow(totals.assertions.failed));
15889 columns.push_back(SummaryColumn("failed as expected", Colour::ResultExpectedFailure)
15890 .addRow(totals.testCases.failedButOk)
15891 .addRow(totals.assertions.failedButOk));
15892
15893 printSummaryRow("test cases", columns, 0);
15894 printSummaryRow("assertions", columns, 1);
15895 }
15896 }
printSummaryRow(std::string const & label,std::vector<SummaryColumn> const & cols,std::size_t row)15897