1 // SPDX-License-Identifier: BSL-1.0
2 /*
3 * Catch v2.13.9
4 * Generated: 2022-04-12 22:37:23.260201
5 * ----------------------------------------------------------
6 * This file has been merged from multiple headers. Please don't edit it directly
7 * Copyright (c) 2022 Two Blue Cubes Ltd. All rights reserved.
8 *
9 * Distributed under the Boost Software License, Version 1.0. (See accompanying
10 * file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
11 */
12 #ifndef TWOBLUECUBES_SINGLE_INCLUDE_CATCH_HPP_INCLUDED
13 #define TWOBLUECUBES_SINGLE_INCLUDE_CATCH_HPP_INCLUDED
14 // start catch.hpp
15
16
17 #define CATCH_VERSION_MAJOR 2
18 #define CATCH_VERSION_MINOR 13
19 #define CATCH_VERSION_PATCH 9
20
21 #ifdef __clang__
22 # pragma clang system_header
23 #elif defined __GNUC__
24 # pragma GCC system_header
25 #endif
26
27 // start catch_suppress_warnings.h
28
29 #ifdef __clang__
30 # ifdef __ICC // icpc defines the __clang__ macro
31 # pragma warning(push)
32 # pragma warning(disable: 161 1682)
33 # else // __ICC
34 # pragma clang diagnostic push
35 # pragma clang diagnostic ignored "-Wpadded"
36 # pragma clang diagnostic ignored "-Wswitch-enum"
37 # pragma clang diagnostic ignored "-Wcovered-switch-default"
38 # endif
39 #elif defined __GNUC__
40 // Because REQUIREs trigger GCC's -Wparentheses, and because still
41 // supported version of g++ have only buggy support for _Pragmas,
42 // Wparentheses have to be suppressed globally.
43 # pragma GCC diagnostic ignored "-Wparentheses" // See #674 for details
44
45 # pragma GCC diagnostic push
46 # pragma GCC diagnostic ignored "-Wunused-variable"
47 # pragma GCC diagnostic ignored "-Wpadded"
48 #endif
49 // end catch_suppress_warnings.h
50 #if defined(CATCH_CONFIG_MAIN) || defined(CATCH_CONFIG_RUNNER)
51 # define CATCH_IMPL
52 # define CATCH_CONFIG_ALL_PARTS
53 #endif
54
55 // In the impl file, we want to have access to all parts of the headers
56 // Can also be used to sanely support PCHs
57 #if defined(CATCH_CONFIG_ALL_PARTS)
58 # define CATCH_CONFIG_EXTERNAL_INTERFACES
59 # if defined(CATCH_CONFIG_DISABLE_MATCHERS)
60 # undef CATCH_CONFIG_DISABLE_MATCHERS
61 # endif
62 # if !defined(CATCH_CONFIG_ENABLE_CHRONO_STRINGMAKER)
63 # define CATCH_CONFIG_ENABLE_CHRONO_STRINGMAKER
64 # endif
65 #endif
66
67 #if !defined(CATCH_CONFIG_IMPL_ONLY)
68 // start catch_platform.h
69
70 // See e.g.:
71 // https://opensource.apple.com/source/CarbonHeaders/CarbonHeaders-18.1/TargetConditionals.h.auto.html
72 #ifdef __APPLE__
73 # include <TargetConditionals.h>
74 # if (defined(TARGET_OS_OSX) && TARGET_OS_OSX == 1) || \
75 (defined(TARGET_OS_MAC) && TARGET_OS_MAC == 1)
76 # define CATCH_PLATFORM_MAC
77 # elif (defined(TARGET_OS_IPHONE) && TARGET_OS_IPHONE == 1)
78 # define CATCH_PLATFORM_IPHONE
79 # endif
80
81 #elif defined(linux) || defined(__linux) || defined(__linux__)
82 # define CATCH_PLATFORM_LINUX
83
84 #elif defined(WIN32) || defined(__WIN32__) || defined(_WIN32) || defined(_MSC_VER) || defined(__MINGW32__)
85 # define CATCH_PLATFORM_WINDOWS
86 #endif
87
88 // end catch_platform.h
89
90 #ifdef CATCH_IMPL
91 # ifndef CLARA_CONFIG_MAIN
92 # define CLARA_CONFIG_MAIN_NOT_DEFINED
93 # define CLARA_CONFIG_MAIN
94 # endif
95 #endif
96
97 // start catch_user_interfaces.h
98
99 namespace Catch {
100 unsigned int rngSeed();
101 }
102
103 // end catch_user_interfaces.h
104 // start catch_tag_alias_autoregistrar.h
105
106 // start catch_common.h
107
108 // start catch_compiler_capabilities.h
109
110 // Detect a number of compiler features - by compiler
111 // The following features are defined:
112 //
113 // CATCH_CONFIG_COUNTER : is the __COUNTER__ macro supported?
114 // CATCH_CONFIG_WINDOWS_SEH : is Windows SEH supported?
115 // CATCH_CONFIG_POSIX_SIGNALS : are POSIX signals supported?
116 // CATCH_CONFIG_DISABLE_EXCEPTIONS : Are exceptions enabled?
117 // ****************
118 // Note to maintainers: if new toggles are added please document them
119 // in configuration.md, too
120 // ****************
121
122 // In general each macro has a _NO_<feature name> form
123 // (e.g. CATCH_CONFIG_NO_POSIX_SIGNALS) which disables the feature.
124 // Many features, at point of detection, define an _INTERNAL_ macro, so they
125 // can be combined, en-mass, with the _NO_ forms later.
126
127 #ifdef __cplusplus
128
129 # if (__cplusplus >= 201402L) || (defined(_MSVC_LANG) && _MSVC_LANG >= 201402L)
130 # define CATCH_CPP14_OR_GREATER
131 # endif
132
133 # if (__cplusplus >= 201703L) || (defined(_MSVC_LANG) && _MSVC_LANG >= 201703L)
134 # define CATCH_CPP17_OR_GREATER
135 # endif
136
137 #endif
138
139 // Only GCC compiler should be used in this block, so other compilers trying to
140 // mask themselves as GCC should be ignored.
141 #if defined(__GNUC__) && !defined(__clang__) && !defined(__ICC) && !defined(__CUDACC__) && !defined(__LCC__)
142 # define CATCH_INTERNAL_START_WARNINGS_SUPPRESSION _Pragma( "GCC diagnostic push" )
143 # define CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION _Pragma( "GCC diagnostic pop" )
144
145 # define CATCH_INTERNAL_IGNORE_BUT_WARN(...) (void)__builtin_constant_p(__VA_ARGS__)
146
147 #endif
148
149 #if defined(__clang__)
150
151 # define CATCH_INTERNAL_START_WARNINGS_SUPPRESSION _Pragma( "clang diagnostic push" )
152 # define CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION _Pragma( "clang diagnostic pop" )
153
154 // As of this writing, IBM XL's implementation of __builtin_constant_p has a bug
155 // which results in calls to destructors being emitted for each temporary,
156 // without a matching initialization. In practice, this can result in something
157 // like `std::string::~string` being called on an uninitialized value.
158 //
159 // For example, this code will likely segfault under IBM XL:
160 // ```
161 // REQUIRE(std::string("12") + "34" == "1234")
162 // ```
163 //
164 // Therefore, `CATCH_INTERNAL_IGNORE_BUT_WARN` is not implemented.
165 # if !defined(__ibmxl__) && !defined(__CUDACC__)
166 # define CATCH_INTERNAL_IGNORE_BUT_WARN(...) (void)__builtin_constant_p(__VA_ARGS__) /* NOLINT(cppcoreguidelines-pro-type-vararg, hicpp-vararg) */
167 # endif
168
169 # define CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
170 _Pragma( "clang diagnostic ignored \"-Wexit-time-destructors\"" ) \
171 _Pragma( "clang diagnostic ignored \"-Wglobal-constructors\"")
172
173 # define CATCH_INTERNAL_SUPPRESS_PARENTHESES_WARNINGS \
174 _Pragma( "clang diagnostic ignored \"-Wparentheses\"" )
175
176 # define CATCH_INTERNAL_SUPPRESS_UNUSED_WARNINGS \
177 _Pragma( "clang diagnostic ignored \"-Wunused-variable\"" )
178
179 # define CATCH_INTERNAL_SUPPRESS_ZERO_VARIADIC_WARNINGS \
180 _Pragma( "clang diagnostic ignored \"-Wgnu-zero-variadic-macro-arguments\"" )
181
182 # define CATCH_INTERNAL_SUPPRESS_UNUSED_TEMPLATE_WARNINGS \
183 _Pragma( "clang diagnostic ignored \"-Wunused-template\"" )
184
185 #endif // __clang__
186
187 ////////////////////////////////////////////////////////////////////////////////
188 // Assume that non-Windows platforms support posix signals by default
189 #if !defined(CATCH_PLATFORM_WINDOWS)
190 #define CATCH_INTERNAL_CONFIG_POSIX_SIGNALS
191 #endif
192
193 ////////////////////////////////////////////////////////////////////////////////
194 // We know some environments not to support full POSIX signals
195 #if defined(__CYGWIN__) || defined(__QNX__) || defined(__EMSCRIPTEN__) || defined(__DJGPP__)
196 #define CATCH_INTERNAL_CONFIG_NO_POSIX_SIGNALS
197 #endif
198
199 #ifdef __OS400__
200 # define CATCH_INTERNAL_CONFIG_NO_POSIX_SIGNALS
201 # define CATCH_CONFIG_COLOUR_NONE
202 #endif
203
204 ////////////////////////////////////////////////////////////////////////////////
205 // Android somehow still does not support std::to_string
206 #if defined(__ANDROID__)
207 # define CATCH_INTERNAL_CONFIG_NO_CPP11_TO_STRING
208 # define CATCH_INTERNAL_CONFIG_ANDROID_LOGWRITE
209 #endif
210
211 ////////////////////////////////////////////////////////////////////////////////
212 // Not all Windows environments support SEH properly
213 #if defined(__MINGW32__)
214 # define CATCH_INTERNAL_CONFIG_NO_WINDOWS_SEH
215 #endif
216
217 ////////////////////////////////////////////////////////////////////////////////
218 // PS4
219 #if defined(__ORBIS__)
220 # define CATCH_INTERNAL_CONFIG_NO_NEW_CAPTURE
221 #endif
222
223 ////////////////////////////////////////////////////////////////////////////////
224 // Cygwin
225 #ifdef __CYGWIN__
226
227 // Required for some versions of Cygwin to declare gettimeofday
228 // see: http://stackoverflow.com/questions/36901803/gettimeofday-not-declared-in-this-scope-cygwin
229 # define _BSD_SOURCE
230 // some versions of cygwin (most) do not support std::to_string. Use the libstd check.
231 // https://gcc.gnu.org/onlinedocs/gcc-4.8.2/libstdc++/api/a01053_source.html line 2812-2813
232 # if !((__cplusplus >= 201103L) && defined(_GLIBCXX_USE_C99) \
233 && !defined(_GLIBCXX_HAVE_BROKEN_VSWPRINTF))
234
235 # define CATCH_INTERNAL_CONFIG_NO_CPP11_TO_STRING
236
237 # endif
238 #endif // __CYGWIN__
239
240 ////////////////////////////////////////////////////////////////////////////////
241 // Visual C++
242 #if defined(_MSC_VER)
243
244 // Universal Windows platform does not support SEH
245 // Or console colours (or console at all...)
246 # if defined(WINAPI_FAMILY) && (WINAPI_FAMILY == WINAPI_FAMILY_APP)
247 # define CATCH_CONFIG_COLOUR_NONE
248 # else
249 # define CATCH_INTERNAL_CONFIG_WINDOWS_SEH
250 # endif
251
252 # if !defined(__clang__) // Handle Clang masquerading for msvc
253
254 // MSVC traditional preprocessor needs some workaround for __VA_ARGS__
255 // _MSVC_TRADITIONAL == 0 means new conformant preprocessor
256 // _MSVC_TRADITIONAL == 1 means old traditional non-conformant preprocessor
257 # if !defined(_MSVC_TRADITIONAL) || (defined(_MSVC_TRADITIONAL) && _MSVC_TRADITIONAL)
258 # define CATCH_INTERNAL_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
259 # endif // MSVC_TRADITIONAL
260
261 // Only do this if we're not using clang on Windows, which uses `diagnostic push` & `diagnostic pop`
262 # define CATCH_INTERNAL_START_WARNINGS_SUPPRESSION __pragma( warning(push) )
263 # define CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION __pragma( warning(pop) )
264 # endif // __clang__
265
266 #endif // _MSC_VER
267
268 #if defined(_REENTRANT) || defined(_MSC_VER)
269 // Enable async processing, as -pthread is specified or no additional linking is required
270 # define CATCH_INTERNAL_CONFIG_USE_ASYNC
271 #endif // _MSC_VER
272
273 ////////////////////////////////////////////////////////////////////////////////
274 // Check if we are compiled with -fno-exceptions or equivalent
275 #if defined(__EXCEPTIONS) || defined(__cpp_exceptions) || defined(_CPPUNWIND)
276 # define CATCH_INTERNAL_CONFIG_EXCEPTIONS_ENABLED
277 #endif
278
279 ////////////////////////////////////////////////////////////////////////////////
280 // DJGPP
281 #ifdef __DJGPP__
282 # define CATCH_INTERNAL_CONFIG_NO_WCHAR
283 #endif // __DJGPP__
284
285 ////////////////////////////////////////////////////////////////////////////////
286 // Embarcadero C++Build
287 #if defined(__BORLANDC__)
288 #define CATCH_INTERNAL_CONFIG_POLYFILL_ISNAN
289 #endif
290
291 ////////////////////////////////////////////////////////////////////////////////
292
293 // Use of __COUNTER__ is suppressed during code analysis in
294 // CLion/AppCode 2017.2.x and former, because __COUNTER__ is not properly
295 // handled by it.
296 // Otherwise all supported compilers support COUNTER macro,
297 // but user still might want to turn it off
298 #if ( !defined(__JETBRAINS_IDE__) || __JETBRAINS_IDE__ >= 20170300L )
299 #define CATCH_INTERNAL_CONFIG_COUNTER
300 #endif
301
302 ////////////////////////////////////////////////////////////////////////////////
303
304 // RTX is a special version of Windows that is real time.
305 // This means that it is detected as Windows, but does not provide
306 // the same set of capabilities as real Windows does.
307 #if defined(UNDER_RTSS) || defined(RTX64_BUILD)
308 #define CATCH_INTERNAL_CONFIG_NO_WINDOWS_SEH
309 #define CATCH_INTERNAL_CONFIG_NO_ASYNC
310 #define CATCH_CONFIG_COLOUR_NONE
311 #endif
312
313 #if !defined(_GLIBCXX_USE_C99_MATH_TR1)
314 #define CATCH_INTERNAL_CONFIG_GLOBAL_NEXTAFTER
315 #endif
316
317 // Various stdlib support checks that require __has_include
318 #if defined(__has_include)
319 // Check if string_view is available and usable
320 #if __has_include(<string_view>) && defined(CATCH_CPP17_OR_GREATER)
321 # define CATCH_INTERNAL_CONFIG_CPP17_STRING_VIEW
322 #endif
323
324 // Check if optional is available and usable
325 # if __has_include(<optional>) && defined(CATCH_CPP17_OR_GREATER)
326 # define CATCH_INTERNAL_CONFIG_CPP17_OPTIONAL
327 # endif // __has_include(<optional>) && defined(CATCH_CPP17_OR_GREATER)
328
329 // Check if byte is available and usable
330 # if __has_include(<cstddef>) && defined(CATCH_CPP17_OR_GREATER)
331 # include <cstddef>
332 # if defined(__cpp_lib_byte) && (__cpp_lib_byte > 0)
333 # define CATCH_INTERNAL_CONFIG_CPP17_BYTE
334 # endif
335 # endif // __has_include(<cstddef>) && defined(CATCH_CPP17_OR_GREATER)
336
337 // Check if variant is available and usable
338 # if __has_include(<variant>) && defined(CATCH_CPP17_OR_GREATER)
339 # if defined(__clang__) && (__clang_major__ < 8)
340 // work around clang bug with libstdc++ https://bugs.llvm.org/show_bug.cgi?id=31852
341 // fix should be in clang 8, workaround in libstdc++ 8.2
342 # include <ciso646>
343 # if defined(__GLIBCXX__) && defined(_GLIBCXX_RELEASE) && (_GLIBCXX_RELEASE < 9)
344 # define CATCH_CONFIG_NO_CPP17_VARIANT
345 # else
346 # define CATCH_INTERNAL_CONFIG_CPP17_VARIANT
347 # endif // defined(__GLIBCXX__) && defined(_GLIBCXX_RELEASE) && (_GLIBCXX_RELEASE < 9)
348 # else
349 # define CATCH_INTERNAL_CONFIG_CPP17_VARIANT
350 # endif // defined(__clang__) && (__clang_major__ < 8)
351 # endif // __has_include(<variant>) && defined(CATCH_CPP17_OR_GREATER)
352 #endif // defined(__has_include)
353
354 #if defined(CATCH_INTERNAL_CONFIG_COUNTER) && !defined(CATCH_CONFIG_NO_COUNTER) && !defined(CATCH_CONFIG_COUNTER)
355 # define CATCH_CONFIG_COUNTER
356 #endif
357 #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)
358 # define CATCH_CONFIG_WINDOWS_SEH
359 #endif
360 // This is set by default, because we assume that unix compilers are posix-signal-compatible by default.
361 #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)
362 # define CATCH_CONFIG_POSIX_SIGNALS
363 #endif
364 // This is set by default, because we assume that compilers with no wchar_t support are just rare exceptions.
365 #if !defined(CATCH_INTERNAL_CONFIG_NO_WCHAR) && !defined(CATCH_CONFIG_NO_WCHAR) && !defined(CATCH_CONFIG_WCHAR)
366 # define CATCH_CONFIG_WCHAR
367 #endif
368
369 #if !defined(CATCH_INTERNAL_CONFIG_NO_CPP11_TO_STRING) && !defined(CATCH_CONFIG_NO_CPP11_TO_STRING) && !defined(CATCH_CONFIG_CPP11_TO_STRING)
370 # define CATCH_CONFIG_CPP11_TO_STRING
371 #endif
372
373 #if defined(CATCH_INTERNAL_CONFIG_CPP17_OPTIONAL) && !defined(CATCH_CONFIG_NO_CPP17_OPTIONAL) && !defined(CATCH_CONFIG_CPP17_OPTIONAL)
374 # define CATCH_CONFIG_CPP17_OPTIONAL
375 #endif
376
377 #if defined(CATCH_INTERNAL_CONFIG_CPP17_STRING_VIEW) && !defined(CATCH_CONFIG_NO_CPP17_STRING_VIEW) && !defined(CATCH_CONFIG_CPP17_STRING_VIEW)
378 # define CATCH_CONFIG_CPP17_STRING_VIEW
379 #endif
380
381 #if defined(CATCH_INTERNAL_CONFIG_CPP17_VARIANT) && !defined(CATCH_CONFIG_NO_CPP17_VARIANT) && !defined(CATCH_CONFIG_CPP17_VARIANT)
382 # define CATCH_CONFIG_CPP17_VARIANT
383 #endif
384
385 #if defined(CATCH_INTERNAL_CONFIG_CPP17_BYTE) && !defined(CATCH_CONFIG_NO_CPP17_BYTE) && !defined(CATCH_CONFIG_CPP17_BYTE)
386 # define CATCH_CONFIG_CPP17_BYTE
387 #endif
388
389 #if defined(CATCH_CONFIG_EXPERIMENTAL_REDIRECT)
390 # define CATCH_INTERNAL_CONFIG_NEW_CAPTURE
391 #endif
392
393 #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)
394 # define CATCH_CONFIG_NEW_CAPTURE
395 #endif
396
397 #if !defined(CATCH_INTERNAL_CONFIG_EXCEPTIONS_ENABLED) && !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
398 # define CATCH_CONFIG_DISABLE_EXCEPTIONS
399 #endif
400
401 #if defined(CATCH_INTERNAL_CONFIG_POLYFILL_ISNAN) && !defined(CATCH_CONFIG_NO_POLYFILL_ISNAN) && !defined(CATCH_CONFIG_POLYFILL_ISNAN)
402 # define CATCH_CONFIG_POLYFILL_ISNAN
403 #endif
404
405 #if defined(CATCH_INTERNAL_CONFIG_USE_ASYNC) && !defined(CATCH_INTERNAL_CONFIG_NO_ASYNC) && !defined(CATCH_CONFIG_NO_USE_ASYNC) && !defined(CATCH_CONFIG_USE_ASYNC)
406 # define CATCH_CONFIG_USE_ASYNC
407 #endif
408
409 #if defined(CATCH_INTERNAL_CONFIG_ANDROID_LOGWRITE) && !defined(CATCH_CONFIG_NO_ANDROID_LOGWRITE) && !defined(CATCH_CONFIG_ANDROID_LOGWRITE)
410 # define CATCH_CONFIG_ANDROID_LOGWRITE
411 #endif
412
413 #if defined(CATCH_INTERNAL_CONFIG_GLOBAL_NEXTAFTER) && !defined(CATCH_CONFIG_NO_GLOBAL_NEXTAFTER) && !defined(CATCH_CONFIG_GLOBAL_NEXTAFTER)
414 # define CATCH_CONFIG_GLOBAL_NEXTAFTER
415 #endif
416
417 // Even if we do not think the compiler has that warning, we still have
418 // to provide a macro that can be used by the code.
419 #if !defined(CATCH_INTERNAL_START_WARNINGS_SUPPRESSION)
420 # define CATCH_INTERNAL_START_WARNINGS_SUPPRESSION
421 #endif
422 #if !defined(CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION)
423 # define CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION
424 #endif
425 #if !defined(CATCH_INTERNAL_SUPPRESS_PARENTHESES_WARNINGS)
426 # define CATCH_INTERNAL_SUPPRESS_PARENTHESES_WARNINGS
427 #endif
428 #if !defined(CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS)
429 # define CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS
430 #endif
431 #if !defined(CATCH_INTERNAL_SUPPRESS_UNUSED_WARNINGS)
432 # define CATCH_INTERNAL_SUPPRESS_UNUSED_WARNINGS
433 #endif
434 #if !defined(CATCH_INTERNAL_SUPPRESS_ZERO_VARIADIC_WARNINGS)
435 # define CATCH_INTERNAL_SUPPRESS_ZERO_VARIADIC_WARNINGS
436 #endif
437
438 // The goal of this macro is to avoid evaluation of the arguments, but
439 // still have the compiler warn on problems inside...
440 #if !defined(CATCH_INTERNAL_IGNORE_BUT_WARN)
441 # define CATCH_INTERNAL_IGNORE_BUT_WARN(...)
442 #endif
443
444 #if defined(__APPLE__) && defined(__apple_build_version__) && (__clang_major__ < 10)
445 # undef CATCH_INTERNAL_SUPPRESS_UNUSED_TEMPLATE_WARNINGS
446 #elif defined(__clang__) && (__clang_major__ < 5)
447 # undef CATCH_INTERNAL_SUPPRESS_UNUSED_TEMPLATE_WARNINGS
448 #endif
449
450 #if !defined(CATCH_INTERNAL_SUPPRESS_UNUSED_TEMPLATE_WARNINGS)
451 # define CATCH_INTERNAL_SUPPRESS_UNUSED_TEMPLATE_WARNINGS
452 #endif
453
454 #if defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
455 #define CATCH_TRY if ((true))
456 #define CATCH_CATCH_ALL if ((false))
457 #define CATCH_CATCH_ANON(type) if ((false))
458 #else
459 #define CATCH_TRY try
460 #define CATCH_CATCH_ALL catch (...)
461 #define CATCH_CATCH_ANON(type) catch (type)
462 #endif
463
464 #if defined(CATCH_INTERNAL_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR) && !defined(CATCH_CONFIG_NO_TRADITIONAL_MSVC_PREPROCESSOR) && !defined(CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR)
465 #define CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
466 #endif
467
468 // end catch_compiler_capabilities.h
469 #define INTERNAL_CATCH_UNIQUE_NAME_LINE2( name, line ) name##line
470 #define INTERNAL_CATCH_UNIQUE_NAME_LINE( name, line ) INTERNAL_CATCH_UNIQUE_NAME_LINE2( name, line )
471 #ifdef CATCH_CONFIG_COUNTER
472 # define INTERNAL_CATCH_UNIQUE_NAME( name ) INTERNAL_CATCH_UNIQUE_NAME_LINE( name, __COUNTER__ )
473 #else
474 # define INTERNAL_CATCH_UNIQUE_NAME( name ) INTERNAL_CATCH_UNIQUE_NAME_LINE( name, __LINE__ )
475 #endif
476
477 #include <iosfwd>
478 #include <string>
479 #include <cstdint>
480
481 // We need a dummy global operator<< so we can bring it into Catch namespace later
482 struct Catch_global_namespace_dummy {};
483 std::ostream& operator<<(std::ostream&, Catch_global_namespace_dummy);
484
485 namespace Catch {
486
487 struct CaseSensitive { enum Choice {
488 Yes,
489 No
490 }; };
491
492 class NonCopyable {
493 NonCopyable( NonCopyable const& ) = delete;
494 NonCopyable( NonCopyable && ) = delete;
495 NonCopyable& operator = ( NonCopyable const& ) = delete;
496 NonCopyable& operator = ( NonCopyable && ) = delete;
497
498 protected:
499 NonCopyable();
500 virtual ~NonCopyable();
501 };
502
503 struct SourceLineInfo {
504
505 SourceLineInfo() = delete;
SourceLineInfoCatch::SourceLineInfo506 SourceLineInfo( char const* _file, std::size_t _line ) noexcept
507 : file( _file ),
508 line( _line )
509 {}
510
511 SourceLineInfo( SourceLineInfo const& other ) = default;
512 SourceLineInfo& operator = ( SourceLineInfo const& ) = default;
513 SourceLineInfo( SourceLineInfo&& ) noexcept = default;
514 SourceLineInfo& operator = ( SourceLineInfo&& ) noexcept = default;
515
emptyCatch::SourceLineInfo516 bool empty() const noexcept { return file[0] == '\0'; }
517 bool operator == ( SourceLineInfo const& other ) const noexcept;
518 bool operator < ( SourceLineInfo const& other ) const noexcept;
519
520 char const* file;
521 std::size_t line;
522 };
523
524 std::ostream& operator << ( std::ostream& os, SourceLineInfo const& info );
525
526 // Bring in operator<< from global namespace into Catch namespace
527 // This is necessary because the overload of operator<< above makes
528 // lookup stop at namespace Catch
529 using ::operator<<;
530
531 // Use this in variadic streaming macros to allow
532 // >> +StreamEndStop
533 // as well as
534 // >> stuff +StreamEndStop
535 struct StreamEndStop {
536 std::string operator+() const;
537 };
538 template<typename T>
operator +(T const & value,StreamEndStop)539 T const& operator + ( T const& value, StreamEndStop ) {
540 return value;
541 }
542 }
543
544 #define CATCH_INTERNAL_LINEINFO \
545 ::Catch::SourceLineInfo( __FILE__, static_cast<std::size_t>( __LINE__ ) )
546
547 // end catch_common.h
548 namespace Catch {
549
550 struct RegistrarForTagAliases {
551 RegistrarForTagAliases( char const* alias, char const* tag, SourceLineInfo const& lineInfo );
552 };
553
554 } // end namespace Catch
555
556 #define CATCH_REGISTER_TAG_ALIAS( alias, spec ) \
557 CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \
558 CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
559 namespace{ Catch::RegistrarForTagAliases INTERNAL_CATCH_UNIQUE_NAME( AutoRegisterTagAlias )( alias, spec, CATCH_INTERNAL_LINEINFO ); } \
560 CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION
561
562 // end catch_tag_alias_autoregistrar.h
563 // start catch_test_registry.h
564
565 // start catch_interfaces_testcase.h
566
567 #include <vector>
568
569 namespace Catch {
570
571 class TestSpec;
572
573 struct ITestInvoker {
574 virtual void invoke () const = 0;
575 virtual ~ITestInvoker();
576 };
577
578 class TestCase;
579 struct IConfig;
580
581 struct ITestCaseRegistry {
582 virtual ~ITestCaseRegistry();
583 virtual std::vector<TestCase> const& getAllTests() const = 0;
584 virtual std::vector<TestCase> const& getAllTestsSorted( IConfig const& config ) const = 0;
585 };
586
587 bool isThrowSafe( TestCase const& testCase, IConfig const& config );
588 bool matchTest( TestCase const& testCase, TestSpec const& testSpec, IConfig const& config );
589 std::vector<TestCase> filterTests( std::vector<TestCase> const& testCases, TestSpec const& testSpec, IConfig const& config );
590 std::vector<TestCase> const& getAllTestCasesSorted( IConfig const& config );
591
592 }
593
594 // end catch_interfaces_testcase.h
595 // start catch_stringref.h
596
597 #include <cstddef>
598 #include <string>
599 #include <iosfwd>
600 #include <cassert>
601
602 namespace Catch {
603
604 /// A non-owning string class (similar to the forthcoming std::string_view)
605 /// Note that, because a StringRef may be a substring of another string,
606 /// it may not be null terminated.
607 class StringRef {
608 public:
609 using size_type = std::size_t;
610 using const_iterator = const char*;
611
612 private:
613 static constexpr char const* const s_empty = "";
614
615 char const* m_start = s_empty;
616 size_type m_size = 0;
617
618 public: // construction
619 constexpr StringRef() noexcept = default;
620
621 StringRef( char const* rawChars ) noexcept;
622
StringRef(char const * rawChars,size_type size)623 constexpr StringRef( char const* rawChars, size_type size ) noexcept
624 : m_start( rawChars ),
625 m_size( size )
626 {}
627
StringRef(std::string const & stdString)628 StringRef( std::string const& stdString ) noexcept
629 : m_start( stdString.c_str() ),
630 m_size( stdString.size() )
631 {}
632
operator std::string() const633 explicit operator std::string() const {
634 return std::string(m_start, m_size);
635 }
636
637 public: // operators
638 auto operator == ( StringRef const& other ) const noexcept -> bool;
operator !=(StringRef const & other) const639 auto operator != (StringRef const& other) const noexcept -> bool {
640 return !(*this == other);
641 }
642
operator [](size_type index) const643 auto operator[] ( size_type index ) const noexcept -> char {
644 assert(index < m_size);
645 return m_start[index];
646 }
647
648 public: // named queries
empty() const649 constexpr auto empty() const noexcept -> bool {
650 return m_size == 0;
651 }
size() const652 constexpr auto size() const noexcept -> size_type {
653 return m_size;
654 }
655
656 // Returns the current start pointer. If the StringRef is not
657 // null-terminated, throws std::domain_exception
658 auto c_str() const -> char const*;
659
660 public: // substrings and searches
661 // Returns a substring of [start, start + length).
662 // If start + length > size(), then the substring is [start, size()).
663 // If start > size(), then the substring is empty.
664 auto substr( size_type start, size_type length ) const noexcept -> StringRef;
665
666 // Returns the current start pointer. May not be null-terminated.
667 auto data() const noexcept -> char const*;
668
isNullTerminated() const669 constexpr auto isNullTerminated() const noexcept -> bool {
670 return m_start[m_size] == '\0';
671 }
672
673 public: // iterators
begin() const674 constexpr const_iterator begin() const { return m_start; }
end() const675 constexpr const_iterator end() const { return m_start + m_size; }
676 };
677
678 auto operator += ( std::string& lhs, StringRef const& sr ) -> std::string&;
679 auto operator << ( std::ostream& os, StringRef const& sr ) -> std::ostream&;
680
operator ""_sr(char const * rawChars,std::size_t size)681 constexpr auto operator "" _sr( char const* rawChars, std::size_t size ) noexcept -> StringRef {
682 return StringRef( rawChars, size );
683 }
684 } // namespace Catch
685
operator ""_catch_sr(char const * rawChars,std::size_t size)686 constexpr auto operator "" _catch_sr( char const* rawChars, std::size_t size ) noexcept -> Catch::StringRef {
687 return Catch::StringRef( rawChars, size );
688 }
689
690 // end catch_stringref.h
691 // start catch_preprocessor.hpp
692
693
694 #define CATCH_RECURSION_LEVEL0(...) __VA_ARGS__
695 #define CATCH_RECURSION_LEVEL1(...) CATCH_RECURSION_LEVEL0(CATCH_RECURSION_LEVEL0(CATCH_RECURSION_LEVEL0(__VA_ARGS__)))
696 #define CATCH_RECURSION_LEVEL2(...) CATCH_RECURSION_LEVEL1(CATCH_RECURSION_LEVEL1(CATCH_RECURSION_LEVEL1(__VA_ARGS__)))
697 #define CATCH_RECURSION_LEVEL3(...) CATCH_RECURSION_LEVEL2(CATCH_RECURSION_LEVEL2(CATCH_RECURSION_LEVEL2(__VA_ARGS__)))
698 #define CATCH_RECURSION_LEVEL4(...) CATCH_RECURSION_LEVEL3(CATCH_RECURSION_LEVEL3(CATCH_RECURSION_LEVEL3(__VA_ARGS__)))
699 #define CATCH_RECURSION_LEVEL5(...) CATCH_RECURSION_LEVEL4(CATCH_RECURSION_LEVEL4(CATCH_RECURSION_LEVEL4(__VA_ARGS__)))
700
701 #ifdef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
702 #define INTERNAL_CATCH_EXPAND_VARGS(...) __VA_ARGS__
703 // MSVC needs more evaluations
704 #define CATCH_RECURSION_LEVEL6(...) CATCH_RECURSION_LEVEL5(CATCH_RECURSION_LEVEL5(CATCH_RECURSION_LEVEL5(__VA_ARGS__)))
705 #define CATCH_RECURSE(...) CATCH_RECURSION_LEVEL6(CATCH_RECURSION_LEVEL6(__VA_ARGS__))
706 #else
707 #define CATCH_RECURSE(...) CATCH_RECURSION_LEVEL5(__VA_ARGS__)
708 #endif
709
710 #define CATCH_REC_END(...)
711 #define CATCH_REC_OUT
712
713 #define CATCH_EMPTY()
714 #define CATCH_DEFER(id) id CATCH_EMPTY()
715
716 #define CATCH_REC_GET_END2() 0, CATCH_REC_END
717 #define CATCH_REC_GET_END1(...) CATCH_REC_GET_END2
718 #define CATCH_REC_GET_END(...) CATCH_REC_GET_END1
719 #define CATCH_REC_NEXT0(test, next, ...) next CATCH_REC_OUT
720 #define CATCH_REC_NEXT1(test, next) CATCH_DEFER ( CATCH_REC_NEXT0 ) ( test, next, 0)
721 #define CATCH_REC_NEXT(test, next) CATCH_REC_NEXT1(CATCH_REC_GET_END test, next)
722
723 #define CATCH_REC_LIST0(f, x, peek, ...) , f(x) CATCH_DEFER ( CATCH_REC_NEXT(peek, CATCH_REC_LIST1) ) ( f, peek, __VA_ARGS__ )
724 #define CATCH_REC_LIST1(f, x, peek, ...) , f(x) CATCH_DEFER ( CATCH_REC_NEXT(peek, CATCH_REC_LIST0) ) ( f, peek, __VA_ARGS__ )
725 #define CATCH_REC_LIST2(f, x, peek, ...) f(x) CATCH_DEFER ( CATCH_REC_NEXT(peek, CATCH_REC_LIST1) ) ( f, peek, __VA_ARGS__ )
726
727 #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__ )
728 #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__ )
729 #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__ )
730
731 // Applies the function macro `f` to each of the remaining parameters, inserts commas between the results,
732 // and passes userdata as the first parameter to each invocation,
733 // e.g. CATCH_REC_LIST_UD(f, x, a, b, c) evaluates to f(x, a), f(x, b), f(x, c)
734 #define CATCH_REC_LIST_UD(f, userdata, ...) CATCH_RECURSE(CATCH_REC_LIST2_UD(f, userdata, __VA_ARGS__, ()()(), ()()(), ()()(), 0))
735
736 #define CATCH_REC_LIST(f, ...) CATCH_RECURSE(CATCH_REC_LIST2(f, __VA_ARGS__, ()()(), ()()(), ()()(), 0))
737
738 #define INTERNAL_CATCH_EXPAND1(param) INTERNAL_CATCH_EXPAND2(param)
739 #define INTERNAL_CATCH_EXPAND2(...) INTERNAL_CATCH_NO## __VA_ARGS__
740 #define INTERNAL_CATCH_DEF(...) INTERNAL_CATCH_DEF __VA_ARGS__
741 #define INTERNAL_CATCH_NOINTERNAL_CATCH_DEF
742 #define INTERNAL_CATCH_STRINGIZE(...) INTERNAL_CATCH_STRINGIZE2(__VA_ARGS__)
743 #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
744 #define INTERNAL_CATCH_STRINGIZE2(...) #__VA_ARGS__
745 #define INTERNAL_CATCH_STRINGIZE_WITHOUT_PARENS(param) INTERNAL_CATCH_STRINGIZE(INTERNAL_CATCH_REMOVE_PARENS(param))
746 #else
747 // MSVC is adding extra space and needs another indirection to expand INTERNAL_CATCH_NOINTERNAL_CATCH_DEF
748 #define INTERNAL_CATCH_STRINGIZE2(...) INTERNAL_CATCH_STRINGIZE3(__VA_ARGS__)
749 #define INTERNAL_CATCH_STRINGIZE3(...) #__VA_ARGS__
750 #define INTERNAL_CATCH_STRINGIZE_WITHOUT_PARENS(param) (INTERNAL_CATCH_STRINGIZE(INTERNAL_CATCH_REMOVE_PARENS(param)) + 1)
751 #endif
752
753 #define INTERNAL_CATCH_MAKE_NAMESPACE2(...) ns_##__VA_ARGS__
754 #define INTERNAL_CATCH_MAKE_NAMESPACE(name) INTERNAL_CATCH_MAKE_NAMESPACE2(name)
755
756 #define INTERNAL_CATCH_REMOVE_PARENS(...) INTERNAL_CATCH_EXPAND1(INTERNAL_CATCH_DEF __VA_ARGS__)
757
758 #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
759 #define INTERNAL_CATCH_MAKE_TYPE_LIST2(...) decltype(get_wrapper<INTERNAL_CATCH_REMOVE_PARENS_GEN(__VA_ARGS__)>())
760 #define INTERNAL_CATCH_MAKE_TYPE_LIST(...) INTERNAL_CATCH_MAKE_TYPE_LIST2(INTERNAL_CATCH_REMOVE_PARENS(__VA_ARGS__))
761 #else
762 #define INTERNAL_CATCH_MAKE_TYPE_LIST2(...) INTERNAL_CATCH_EXPAND_VARGS(decltype(get_wrapper<INTERNAL_CATCH_REMOVE_PARENS_GEN(__VA_ARGS__)>()))
763 #define INTERNAL_CATCH_MAKE_TYPE_LIST(...) INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_MAKE_TYPE_LIST2(INTERNAL_CATCH_REMOVE_PARENS(__VA_ARGS__)))
764 #endif
765
766 #define INTERNAL_CATCH_MAKE_TYPE_LISTS_FROM_TYPES(...)\
767 CATCH_REC_LIST(INTERNAL_CATCH_MAKE_TYPE_LIST,__VA_ARGS__)
768
769 #define INTERNAL_CATCH_REMOVE_PARENS_1_ARG(_0) INTERNAL_CATCH_REMOVE_PARENS(_0)
770 #define INTERNAL_CATCH_REMOVE_PARENS_2_ARG(_0, _1) INTERNAL_CATCH_REMOVE_PARENS(_0), INTERNAL_CATCH_REMOVE_PARENS_1_ARG(_1)
771 #define INTERNAL_CATCH_REMOVE_PARENS_3_ARG(_0, _1, _2) INTERNAL_CATCH_REMOVE_PARENS(_0), INTERNAL_CATCH_REMOVE_PARENS_2_ARG(_1, _2)
772 #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)
773 #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)
774 #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)
775 #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, _3, _4, _5, _6)
776 #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)
777 #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)
778 #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)
779 #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)
780
781 #define INTERNAL_CATCH_VA_NARGS_IMPL(_0, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, N, ...) N
782
783 #define INTERNAL_CATCH_TYPE_GEN\
784 template<typename...> struct TypeList {};\
785 template<typename...Ts>\
786 constexpr auto get_wrapper() noexcept -> TypeList<Ts...> { return {}; }\
787 template<template<typename...> class...> struct TemplateTypeList{};\
788 template<template<typename...> class...Cs>\
789 constexpr auto get_wrapper() noexcept -> TemplateTypeList<Cs...> { return {}; }\
790 template<typename...>\
791 struct append;\
792 template<typename...>\
793 struct rewrap;\
794 template<template<typename...> class, typename...>\
795 struct create;\
796 template<template<typename...> class, typename>\
797 struct convert;\
798 \
799 template<typename T> \
800 struct append<T> { using type = T; };\
801 template< template<typename...> class L1, typename...E1, template<typename...> class L2, typename...E2, typename...Rest>\
802 struct append<L1<E1...>, L2<E2...>, Rest...> { using type = typename append<L1<E1...,E2...>, Rest...>::type; };\
803 template< template<typename...> class L1, typename...E1, typename...Rest>\
804 struct append<L1<E1...>, TypeList<mpl_::na>, Rest...> { using type = L1<E1...>; };\
805 \
806 template< template<typename...> class Container, template<typename...> class List, typename...elems>\
807 struct rewrap<TemplateTypeList<Container>, List<elems...>> { using type = TypeList<Container<elems...>>; };\
808 template< template<typename...> class Container, template<typename...> class List, class...Elems, typename...Elements>\
809 struct rewrap<TemplateTypeList<Container>, List<Elems...>, Elements...> { using type = typename append<TypeList<Container<Elems...>>, typename rewrap<TemplateTypeList<Container>, Elements...>::type>::type; };\
810 \
811 template<template <typename...> class Final, template< typename...> class...Containers, typename...Types>\
812 struct create<Final, TemplateTypeList<Containers...>, TypeList<Types...>> { using type = typename append<Final<>, typename rewrap<TemplateTypeList<Containers>, Types...>::type...>::type; };\
813 template<template <typename...> class Final, template <typename...> class List, typename...Ts>\
814 struct convert<Final, List<Ts...>> { using type = typename append<Final<>,TypeList<Ts>...>::type; };
815
816 #define INTERNAL_CATCH_NTTP_1(signature, ...)\
817 template<INTERNAL_CATCH_REMOVE_PARENS(signature)> struct Nttp{};\
818 template<INTERNAL_CATCH_REMOVE_PARENS(signature)>\
819 constexpr auto get_wrapper() noexcept -> Nttp<__VA_ARGS__> { return {}; } \
820 template<template<INTERNAL_CATCH_REMOVE_PARENS(signature)> class...> struct NttpTemplateTypeList{};\
821 template<template<INTERNAL_CATCH_REMOVE_PARENS(signature)> class...Cs>\
822 constexpr auto get_wrapper() noexcept -> NttpTemplateTypeList<Cs...> { return {}; } \
823 \
824 template< template<INTERNAL_CATCH_REMOVE_PARENS(signature)> class Container, template<INTERNAL_CATCH_REMOVE_PARENS(signature)> class List, INTERNAL_CATCH_REMOVE_PARENS(signature)>\
825 struct rewrap<NttpTemplateTypeList<Container>, List<__VA_ARGS__>> { using type = TypeList<Container<__VA_ARGS__>>; };\
826 template< template<INTERNAL_CATCH_REMOVE_PARENS(signature)> class Container, template<INTERNAL_CATCH_REMOVE_PARENS(signature)> class List, INTERNAL_CATCH_REMOVE_PARENS(signature), typename...Elements>\
827 struct rewrap<NttpTemplateTypeList<Container>, List<__VA_ARGS__>, Elements...> { using type = typename append<TypeList<Container<__VA_ARGS__>>, typename rewrap<NttpTemplateTypeList<Container>, Elements...>::type>::type; };\
828 template<template <typename...> class Final, template<INTERNAL_CATCH_REMOVE_PARENS(signature)> class...Containers, typename...Types>\
829 struct create<Final, NttpTemplateTypeList<Containers...>, TypeList<Types...>> { using type = typename append<Final<>, typename rewrap<NttpTemplateTypeList<Containers>, Types...>::type...>::type; };
830
831 #define INTERNAL_CATCH_DECLARE_SIG_TEST0(TestName)
832 #define INTERNAL_CATCH_DECLARE_SIG_TEST1(TestName, signature)\
833 template<INTERNAL_CATCH_REMOVE_PARENS(signature)>\
834 static void TestName()
835 #define INTERNAL_CATCH_DECLARE_SIG_TEST_X(TestName, signature, ...)\
836 template<INTERNAL_CATCH_REMOVE_PARENS(signature)>\
837 static void TestName()
838
839 #define INTERNAL_CATCH_DEFINE_SIG_TEST0(TestName)
840 #define INTERNAL_CATCH_DEFINE_SIG_TEST1(TestName, signature)\
841 template<INTERNAL_CATCH_REMOVE_PARENS(signature)>\
842 static void TestName()
843 #define INTERNAL_CATCH_DEFINE_SIG_TEST_X(TestName, signature,...)\
844 template<INTERNAL_CATCH_REMOVE_PARENS(signature)>\
845 static void TestName()
846
847 #define INTERNAL_CATCH_NTTP_REGISTER0(TestFunc, signature)\
848 template<typename Type>\
849 void reg_test(TypeList<Type>, Catch::NameAndTags nameAndTags)\
850 {\
851 Catch::AutoReg( Catch::makeTestInvoker(&TestFunc<Type>), CATCH_INTERNAL_LINEINFO, Catch::StringRef(), nameAndTags);\
852 }
853
854 #define INTERNAL_CATCH_NTTP_REGISTER(TestFunc, signature, ...)\
855 template<INTERNAL_CATCH_REMOVE_PARENS(signature)>\
856 void reg_test(Nttp<__VA_ARGS__>, Catch::NameAndTags nameAndTags)\
857 {\
858 Catch::AutoReg( Catch::makeTestInvoker(&TestFunc<__VA_ARGS__>), CATCH_INTERNAL_LINEINFO, Catch::StringRef(), nameAndTags);\
859 }
860
861 #define INTERNAL_CATCH_NTTP_REGISTER_METHOD0(TestName, signature, ...)\
862 template<typename Type>\
863 void reg_test(TypeList<Type>, Catch::StringRef className, Catch::NameAndTags nameAndTags)\
864 {\
865 Catch::AutoReg( Catch::makeTestInvoker(&TestName<Type>::test), CATCH_INTERNAL_LINEINFO, className, nameAndTags);\
866 }
867
868 #define INTERNAL_CATCH_NTTP_REGISTER_METHOD(TestName, signature, ...)\
869 template<INTERNAL_CATCH_REMOVE_PARENS(signature)>\
870 void reg_test(Nttp<__VA_ARGS__>, Catch::StringRef className, Catch::NameAndTags nameAndTags)\
871 {\
872 Catch::AutoReg( Catch::makeTestInvoker(&TestName<__VA_ARGS__>::test), CATCH_INTERNAL_LINEINFO, className, nameAndTags);\
873 }
874
875 #define INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD0(TestName, ClassName)
876 #define INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD1(TestName, ClassName, signature)\
877 template<typename TestType> \
878 struct TestName : INTERNAL_CATCH_REMOVE_PARENS(ClassName)<TestType> { \
879 void test();\
880 }
881
882 #define INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X(TestName, ClassName, signature, ...)\
883 template<INTERNAL_CATCH_REMOVE_PARENS(signature)> \
884 struct TestName : INTERNAL_CATCH_REMOVE_PARENS(ClassName)<__VA_ARGS__> { \
885 void test();\
886 }
887
888 #define INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD0(TestName)
889 #define INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD1(TestName, signature)\
890 template<typename TestType> \
891 void INTERNAL_CATCH_MAKE_NAMESPACE(TestName)::TestName<TestType>::test()
892 #define INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X(TestName, signature, ...)\
893 template<INTERNAL_CATCH_REMOVE_PARENS(signature)> \
894 void INTERNAL_CATCH_MAKE_NAMESPACE(TestName)::TestName<__VA_ARGS__>::test()
895
896 #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
897 #define INTERNAL_CATCH_NTTP_0
898 #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)
899 #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__)
900 #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__)
901 #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__)
902 #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__)
903 #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__)
904 #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__)
905 #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__)
906 #else
907 #define INTERNAL_CATCH_NTTP_0(signature)
908 #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__))
909 #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__))
910 #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__))
911 #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__))
912 #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__))
913 #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__))
914 #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__))
915 #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__))
916 #endif
917
918 // end catch_preprocessor.hpp
919 // start catch_meta.hpp
920
921
922 #include <type_traits>
923
924 namespace Catch {
925 template<typename T>
926 struct always_false : std::false_type {};
927
928 template <typename> struct true_given : std::true_type {};
929 struct is_callable_tester {
930 template <typename Fun, typename... Args>
931 true_given<decltype(std::declval<Fun>()(std::declval<Args>()...))> static test(int);
932 template <typename...>
933 std::false_type static test(...);
934 };
935
936 template <typename T>
937 struct is_callable;
938
939 template <typename Fun, typename... Args>
940 struct is_callable<Fun(Args...)> : decltype(is_callable_tester::test<Fun, Args...>(0)) {};
941
942 #if defined(__cpp_lib_is_invocable) && __cpp_lib_is_invocable >= 201703
943 // std::result_of is deprecated in C++17 and removed in C++20. Hence, it is
944 // replaced with std::invoke_result here.
945 template <typename Func, typename... U>
946 using FunctionReturnType = std::remove_reference_t<std::remove_cv_t<std::invoke_result_t<Func, U...>>>;
947 #else
948 // Keep ::type here because we still support C++11
949 template <typename Func, typename... U>
950 using FunctionReturnType = typename std::remove_reference<typename std::remove_cv<typename std::result_of<Func(U...)>::type>::type>::type;
951 #endif
952
953 } // namespace Catch
954
955 namespace mpl_{
956 struct na;
957 }
958
959 // end catch_meta.hpp
960 namespace Catch {
961
962 template<typename C>
963 class TestInvokerAsMethod : public ITestInvoker {
964 void (C::*m_testAsMethod)();
965 public:
TestInvokerAsMethod(void (C::* testAsMethod)())966 TestInvokerAsMethod( void (C::*testAsMethod)() ) noexcept : m_testAsMethod( testAsMethod ) {}
967
invoke() const968 void invoke() const override {
969 C obj;
970 (obj.*m_testAsMethod)();
971 }
972 };
973
974 auto makeTestInvoker( void(*testAsFunction)() ) noexcept -> ITestInvoker*;
975
976 template<typename C>
makeTestInvoker(void (C::* testAsMethod)())977 auto makeTestInvoker( void (C::*testAsMethod)() ) noexcept -> ITestInvoker* {
978 return new(std::nothrow) TestInvokerAsMethod<C>( testAsMethod );
979 }
980
981 struct NameAndTags {
982 NameAndTags( StringRef const& name_ = StringRef(), StringRef const& tags_ = StringRef() ) noexcept;
983 StringRef name;
984 StringRef tags;
985 };
986
987 struct AutoReg : NonCopyable {
988 AutoReg( ITestInvoker* invoker, SourceLineInfo const& lineInfo, StringRef const& classOrMethod, NameAndTags const& nameAndTags ) noexcept;
989 ~AutoReg();
990 };
991
992 } // end namespace Catch
993
994 #if defined(CATCH_CONFIG_DISABLE)
995 #define INTERNAL_CATCH_TESTCASE_NO_REGISTRATION( TestName, ... ) \
996 static void TestName()
997 #define INTERNAL_CATCH_TESTCASE_METHOD_NO_REGISTRATION( TestName, ClassName, ... ) \
998 namespace{ \
999 struct TestName : INTERNAL_CATCH_REMOVE_PARENS(ClassName) { \
1000 void test(); \
1001 }; \
1002 } \
1003 void TestName::test()
1004 #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION_2( TestName, TestFunc, Name, Tags, Signature, ... ) \
1005 INTERNAL_CATCH_DEFINE_SIG_TEST(TestFunc, INTERNAL_CATCH_REMOVE_PARENS(Signature))
1006 #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION_2( TestNameClass, TestName, ClassName, Name, Tags, Signature, ... ) \
1007 namespace{ \
1008 namespace INTERNAL_CATCH_MAKE_NAMESPACE(TestName) { \
1009 INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD(TestName, ClassName, INTERNAL_CATCH_REMOVE_PARENS(Signature));\
1010 } \
1011 } \
1012 INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD(TestName, INTERNAL_CATCH_REMOVE_PARENS(Signature))
1013
1014 #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
1015 #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION(Name, Tags, ...) \
1016 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__ )
1017 #else
1018 #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION(Name, Tags, ...) \
1019 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__ ) )
1020 #endif
1021
1022 #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
1023 #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG_NO_REGISTRATION(Name, Tags, Signature, ...) \
1024 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__ )
1025 #else
1026 #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG_NO_REGISTRATION(Name, Tags, Signature, ...) \
1027 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__ ) )
1028 #endif
1029
1030 #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
1031 #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION( ClassName, Name, Tags,... ) \
1032 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__ )
1033 #else
1034 #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION( ClassName, Name, Tags,... ) \
1035 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__ ) )
1036 #endif
1037
1038 #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
1039 #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG_NO_REGISTRATION( ClassName, Name, Tags, Signature, ... ) \
1040 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__ )
1041 #else
1042 #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG_NO_REGISTRATION( ClassName, Name, Tags, Signature, ... ) \
1043 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__ ) )
1044 #endif
1045 #endif
1046
1047 ///////////////////////////////////////////////////////////////////////////////
1048 #define INTERNAL_CATCH_TESTCASE2( TestName, ... ) \
1049 static void TestName(); \
1050 CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \
1051 CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
1052 namespace{ Catch::AutoReg INTERNAL_CATCH_UNIQUE_NAME( autoRegistrar )( Catch::makeTestInvoker( &TestName ), CATCH_INTERNAL_LINEINFO, Catch::StringRef(), Catch::NameAndTags{ __VA_ARGS__ } ); } /* NOLINT */ \
1053 CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION \
1054 static void TestName()
1055 #define INTERNAL_CATCH_TESTCASE( ... ) \
1056 INTERNAL_CATCH_TESTCASE2( INTERNAL_CATCH_UNIQUE_NAME( C_A_T_C_H_T_E_S_T_ ), __VA_ARGS__ )
1057
1058 ///////////////////////////////////////////////////////////////////////////////
1059 #define INTERNAL_CATCH_METHOD_AS_TEST_CASE( QualifiedMethod, ... ) \
1060 CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \
1061 CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
1062 namespace{ Catch::AutoReg INTERNAL_CATCH_UNIQUE_NAME( autoRegistrar )( Catch::makeTestInvoker( &QualifiedMethod ), CATCH_INTERNAL_LINEINFO, "&" #QualifiedMethod, Catch::NameAndTags{ __VA_ARGS__ } ); } /* NOLINT */ \
1063 CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION
1064
1065 ///////////////////////////////////////////////////////////////////////////////
1066 #define INTERNAL_CATCH_TEST_CASE_METHOD2( TestName, ClassName, ... )\
1067 CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \
1068 CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
1069 namespace{ \
1070 struct TestName : INTERNAL_CATCH_REMOVE_PARENS(ClassName) { \
1071 void test(); \
1072 }; \
1073 Catch::AutoReg INTERNAL_CATCH_UNIQUE_NAME( autoRegistrar ) ( Catch::makeTestInvoker( &TestName::test ), CATCH_INTERNAL_LINEINFO, #ClassName, Catch::NameAndTags{ __VA_ARGS__ } ); /* NOLINT */ \
1074 } \
1075 CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION \
1076 void TestName::test()
1077 #define INTERNAL_CATCH_TEST_CASE_METHOD( ClassName, ... ) \
1078 INTERNAL_CATCH_TEST_CASE_METHOD2( INTERNAL_CATCH_UNIQUE_NAME( C_A_T_C_H_T_E_S_T_ ), ClassName, __VA_ARGS__ )
1079
1080 ///////////////////////////////////////////////////////////////////////////////
1081 #define INTERNAL_CATCH_REGISTER_TESTCASE( Function, ... ) \
1082 CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \
1083 CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
1084 Catch::AutoReg INTERNAL_CATCH_UNIQUE_NAME( autoRegistrar )( Catch::makeTestInvoker( Function ), CATCH_INTERNAL_LINEINFO, Catch::StringRef(), Catch::NameAndTags{ __VA_ARGS__ } ); /* NOLINT */ \
1085 CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION
1086
1087 ///////////////////////////////////////////////////////////////////////////////
1088 #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_2(TestName, TestFunc, Name, Tags, Signature, ... )\
1089 CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \
1090 CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
1091 CATCH_INTERNAL_SUPPRESS_ZERO_VARIADIC_WARNINGS \
1092 CATCH_INTERNAL_SUPPRESS_UNUSED_TEMPLATE_WARNINGS \
1093 INTERNAL_CATCH_DECLARE_SIG_TEST(TestFunc, INTERNAL_CATCH_REMOVE_PARENS(Signature));\
1094 namespace {\
1095 namespace INTERNAL_CATCH_MAKE_NAMESPACE(TestName){\
1096 INTERNAL_CATCH_TYPE_GEN\
1097 INTERNAL_CATCH_NTTP_GEN(INTERNAL_CATCH_REMOVE_PARENS(Signature))\
1098 INTERNAL_CATCH_NTTP_REG_GEN(TestFunc,INTERNAL_CATCH_REMOVE_PARENS(Signature))\
1099 template<typename...Types> \
1100 struct TestName{\
1101 TestName(){\
1102 int index = 0; \
1103 constexpr char const* tmpl_types[] = {CATCH_REC_LIST(INTERNAL_CATCH_STRINGIZE_WITHOUT_PARENS, __VA_ARGS__)};\
1104 using expander = int[];\
1105 (void)expander{(reg_test(Types{}, Catch::NameAndTags{ Name " - " + std::string(tmpl_types[index]), Tags } ), index++)... };/* NOLINT */ \
1106 }\
1107 };\
1108 static int INTERNAL_CATCH_UNIQUE_NAME( globalRegistrar ) = [](){\
1109 TestName<INTERNAL_CATCH_MAKE_TYPE_LISTS_FROM_TYPES(__VA_ARGS__)>();\
1110 return 0;\
1111 }();\
1112 }\
1113 }\
1114 CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION \
1115 INTERNAL_CATCH_DEFINE_SIG_TEST(TestFunc,INTERNAL_CATCH_REMOVE_PARENS(Signature))
1116
1117 #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
1118 #define INTERNAL_CATCH_TEMPLATE_TEST_CASE(Name, Tags, ...) \
1119 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__ )
1120 #else
1121 #define INTERNAL_CATCH_TEMPLATE_TEST_CASE(Name, Tags, ...) \
1122 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__ ) )
1123 #endif
1124
1125 #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
1126 #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG(Name, Tags, Signature, ...) \
1127 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__ )
1128 #else
1129 #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG(Name, Tags, Signature, ...) \
1130 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__ ) )
1131 #endif
1132
1133 #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE2(TestName, TestFuncName, Name, Tags, Signature, TmplTypes, TypesList) \
1134 CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \
1135 CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
1136 CATCH_INTERNAL_SUPPRESS_ZERO_VARIADIC_WARNINGS \
1137 CATCH_INTERNAL_SUPPRESS_UNUSED_TEMPLATE_WARNINGS \
1138 template<typename TestType> static void TestFuncName(); \
1139 namespace {\
1140 namespace INTERNAL_CATCH_MAKE_NAMESPACE(TestName) { \
1141 INTERNAL_CATCH_TYPE_GEN \
1142 INTERNAL_CATCH_NTTP_GEN(INTERNAL_CATCH_REMOVE_PARENS(Signature)) \
1143 template<typename... Types> \
1144 struct TestName { \
1145 void reg_tests() { \
1146 int index = 0; \
1147 using expander = int[]; \
1148 constexpr char const* tmpl_types[] = {CATCH_REC_LIST(INTERNAL_CATCH_STRINGIZE_WITHOUT_PARENS, INTERNAL_CATCH_REMOVE_PARENS(TmplTypes))};\
1149 constexpr char const* types_list[] = {CATCH_REC_LIST(INTERNAL_CATCH_STRINGIZE_WITHOUT_PARENS, INTERNAL_CATCH_REMOVE_PARENS(TypesList))};\
1150 constexpr auto num_types = sizeof(types_list) / sizeof(types_list[0]);\
1151 (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++)... };/* NOLINT */\
1152 } \
1153 }; \
1154 static int INTERNAL_CATCH_UNIQUE_NAME( globalRegistrar ) = [](){ \
1155 using TestInit = typename create<TestName, decltype(get_wrapper<INTERNAL_CATCH_REMOVE_PARENS(TmplTypes)>()), TypeList<INTERNAL_CATCH_MAKE_TYPE_LISTS_FROM_TYPES(INTERNAL_CATCH_REMOVE_PARENS(TypesList))>>::type; \
1156 TestInit t; \
1157 t.reg_tests(); \
1158 return 0; \
1159 }(); \
1160 } \
1161 } \
1162 CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION \
1163 template<typename TestType> \
1164 static void TestFuncName()
1165
1166 #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
1167 #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE(Name, Tags, ...)\
1168 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__)
1169 #else
1170 #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE(Name, Tags, ...)\
1171 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__ ) )
1172 #endif
1173
1174 #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
1175 #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG(Name, Tags, Signature, ...)\
1176 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__)
1177 #else
1178 #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG(Name, Tags, Signature, ...)\
1179 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__ ) )
1180 #endif
1181
1182 #define INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE_2(TestName, TestFunc, Name, Tags, TmplList)\
1183 CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \
1184 CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
1185 CATCH_INTERNAL_SUPPRESS_UNUSED_TEMPLATE_WARNINGS \
1186 template<typename TestType> static void TestFunc(); \
1187 namespace {\
1188 namespace INTERNAL_CATCH_MAKE_NAMESPACE(TestName){\
1189 INTERNAL_CATCH_TYPE_GEN\
1190 template<typename... Types> \
1191 struct TestName { \
1192 void reg_tests() { \
1193 int index = 0; \
1194 using expander = int[]; \
1195 (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++)... };/* NOLINT */\
1196 } \
1197 };\
1198 static int INTERNAL_CATCH_UNIQUE_NAME( globalRegistrar ) = [](){ \
1199 using TestInit = typename convert<TestName, TmplList>::type; \
1200 TestInit t; \
1201 t.reg_tests(); \
1202 return 0; \
1203 }(); \
1204 }}\
1205 CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION \
1206 template<typename TestType> \
1207 static void TestFunc()
1208
1209 #define INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE(Name, Tags, TmplList) \
1210 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 )
1211
1212 #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_2( TestNameClass, TestName, ClassName, Name, Tags, Signature, ... ) \
1213 CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \
1214 CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
1215 CATCH_INTERNAL_SUPPRESS_ZERO_VARIADIC_WARNINGS \
1216 CATCH_INTERNAL_SUPPRESS_UNUSED_TEMPLATE_WARNINGS \
1217 namespace {\
1218 namespace INTERNAL_CATCH_MAKE_NAMESPACE(TestName){ \
1219 INTERNAL_CATCH_TYPE_GEN\
1220 INTERNAL_CATCH_NTTP_GEN(INTERNAL_CATCH_REMOVE_PARENS(Signature))\
1221 INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD(TestName, ClassName, INTERNAL_CATCH_REMOVE_PARENS(Signature));\
1222 INTERNAL_CATCH_NTTP_REG_METHOD_GEN(TestName, INTERNAL_CATCH_REMOVE_PARENS(Signature))\
1223 template<typename...Types> \
1224 struct TestNameClass{\
1225 TestNameClass(){\
1226 int index = 0; \
1227 constexpr char const* tmpl_types[] = {CATCH_REC_LIST(INTERNAL_CATCH_STRINGIZE_WITHOUT_PARENS, __VA_ARGS__)};\
1228 using expander = int[];\
1229 (void)expander{(reg_test(Types{}, #ClassName, Catch::NameAndTags{ Name " - " + std::string(tmpl_types[index]), Tags } ), index++)... };/* NOLINT */ \
1230 }\
1231 };\
1232 static int INTERNAL_CATCH_UNIQUE_NAME( globalRegistrar ) = [](){\
1233 TestNameClass<INTERNAL_CATCH_MAKE_TYPE_LISTS_FROM_TYPES(__VA_ARGS__)>();\
1234 return 0;\
1235 }();\
1236 }\
1237 }\
1238 CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION \
1239 INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD(TestName, INTERNAL_CATCH_REMOVE_PARENS(Signature))
1240
1241 #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
1242 #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD( ClassName, Name, Tags,... ) \
1243 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__ )
1244 #else
1245 #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD( ClassName, Name, Tags,... ) \
1246 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__ ) )
1247 #endif
1248
1249 #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
1250 #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG( ClassName, Name, Tags, Signature, ... ) \
1251 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__ )
1252 #else
1253 #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG( ClassName, Name, Tags, Signature, ... ) \
1254 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__ ) )
1255 #endif
1256
1257 #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_2(TestNameClass, TestName, ClassName, Name, Tags, Signature, TmplTypes, TypesList)\
1258 CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \
1259 CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
1260 CATCH_INTERNAL_SUPPRESS_ZERO_VARIADIC_WARNINGS \
1261 CATCH_INTERNAL_SUPPRESS_UNUSED_TEMPLATE_WARNINGS \
1262 template<typename TestType> \
1263 struct TestName : INTERNAL_CATCH_REMOVE_PARENS(ClassName <TestType>) { \
1264 void test();\
1265 };\
1266 namespace {\
1267 namespace INTERNAL_CATCH_MAKE_NAMESPACE(TestNameClass) {\
1268 INTERNAL_CATCH_TYPE_GEN \
1269 INTERNAL_CATCH_NTTP_GEN(INTERNAL_CATCH_REMOVE_PARENS(Signature))\
1270 template<typename...Types>\
1271 struct TestNameClass{\
1272 void reg_tests(){\
1273 int index = 0;\
1274 using expander = int[];\
1275 constexpr char const* tmpl_types[] = {CATCH_REC_LIST(INTERNAL_CATCH_STRINGIZE_WITHOUT_PARENS, INTERNAL_CATCH_REMOVE_PARENS(TmplTypes))};\
1276 constexpr char const* types_list[] = {CATCH_REC_LIST(INTERNAL_CATCH_STRINGIZE_WITHOUT_PARENS, INTERNAL_CATCH_REMOVE_PARENS(TypesList))};\
1277 constexpr auto num_types = sizeof(types_list) / sizeof(types_list[0]);\
1278 (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++)... };/* NOLINT */ \
1279 }\
1280 };\
1281 static int INTERNAL_CATCH_UNIQUE_NAME( globalRegistrar ) = [](){\
1282 using TestInit = typename create<TestNameClass, decltype(get_wrapper<INTERNAL_CATCH_REMOVE_PARENS(TmplTypes)>()), TypeList<INTERNAL_CATCH_MAKE_TYPE_LISTS_FROM_TYPES(INTERNAL_CATCH_REMOVE_PARENS(TypesList))>>::type;\
1283 TestInit t;\
1284 t.reg_tests();\
1285 return 0;\
1286 }(); \
1287 }\
1288 }\
1289 CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION \
1290 template<typename TestType> \
1291 void TestName<TestType>::test()
1292
1293 #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
1294 #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( ClassName, Name, Tags, ... )\
1295 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__ )
1296 #else
1297 #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( ClassName, Name, Tags, ... )\
1298 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__ ) )
1299 #endif
1300
1301 #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
1302 #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( ClassName, Name, Tags, Signature, ... )\
1303 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__ )
1304 #else
1305 #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( ClassName, Name, Tags, Signature, ... )\
1306 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__ ) )
1307 #endif
1308
1309 #define INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE_METHOD_2( TestNameClass, TestName, ClassName, Name, Tags, TmplList) \
1310 CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \
1311 CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
1312 CATCH_INTERNAL_SUPPRESS_UNUSED_TEMPLATE_WARNINGS \
1313 template<typename TestType> \
1314 struct TestName : INTERNAL_CATCH_REMOVE_PARENS(ClassName <TestType>) { \
1315 void test();\
1316 };\
1317 namespace {\
1318 namespace INTERNAL_CATCH_MAKE_NAMESPACE(TestName){ \
1319 INTERNAL_CATCH_TYPE_GEN\
1320 template<typename...Types>\
1321 struct TestNameClass{\
1322 void reg_tests(){\
1323 int index = 0;\
1324 using expander = int[];\
1325 (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++)... };/* NOLINT */ \
1326 }\
1327 };\
1328 static int INTERNAL_CATCH_UNIQUE_NAME( globalRegistrar ) = [](){\
1329 using TestInit = typename convert<TestNameClass, TmplList>::type;\
1330 TestInit t;\
1331 t.reg_tests();\
1332 return 0;\
1333 }(); \
1334 }}\
1335 CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION \
1336 template<typename TestType> \
1337 void TestName<TestType>::test()
1338
1339 #define INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE_METHOD(ClassName, Name, Tags, TmplList) \
1340 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 )
1341
1342 // end catch_test_registry.h
1343 // start catch_capture.hpp
1344
1345 // start catch_assertionhandler.h
1346
1347 // start catch_assertioninfo.h
1348
1349 // start catch_result_type.h
1350
1351 namespace Catch {
1352
1353 // ResultWas::OfType enum
1354 struct ResultWas { enum OfType {
1355 Unknown = -1,
1356 Ok = 0,
1357 Info = 1,
1358 Warning = 2,
1359
1360 FailureBit = 0x10,
1361
1362 ExpressionFailed = FailureBit | 1,
1363 ExplicitFailure = FailureBit | 2,
1364
1365 Exception = 0x100 | FailureBit,
1366
1367 ThrewException = Exception | 1,
1368 DidntThrowException = Exception | 2,
1369
1370 FatalErrorCondition = 0x200 | FailureBit
1371
1372 }; };
1373
1374 bool isOk( ResultWas::OfType resultType );
1375 bool isJustInfo( int flags );
1376
1377 // ResultDisposition::Flags enum
1378 struct ResultDisposition { enum Flags {
1379 Normal = 0x01,
1380
1381 ContinueOnFailure = 0x02, // Failures fail test, but execution continues
1382 FalseTest = 0x04, // Prefix expression with !
1383 SuppressFail = 0x08 // Failures are reported but do not fail the test
1384 }; };
1385
1386 ResultDisposition::Flags operator | ( ResultDisposition::Flags lhs, ResultDisposition::Flags rhs );
1387
1388 bool shouldContinueOnFailure( int flags );
isFalseTest(int flags)1389 inline bool isFalseTest( int flags ) { return ( flags & ResultDisposition::FalseTest ) != 0; }
1390 bool shouldSuppressFailure( int flags );
1391
1392 } // end namespace Catch
1393
1394 // end catch_result_type.h
1395 namespace Catch {
1396
1397 struct AssertionInfo
1398 {
1399 StringRef macroName;
1400 SourceLineInfo lineInfo;
1401 StringRef capturedExpression;
1402 ResultDisposition::Flags resultDisposition;
1403
1404 // We want to delete this constructor but a compiler bug in 4.8 means
1405 // the struct is then treated as non-aggregate
1406 //AssertionInfo() = delete;
1407 };
1408
1409 } // end namespace Catch
1410
1411 // end catch_assertioninfo.h
1412 // start catch_decomposer.h
1413
1414 // start catch_tostring.h
1415
1416 #include <vector>
1417 #include <cstddef>
1418 #include <type_traits>
1419 #include <string>
1420 // start catch_stream.h
1421
1422 #include <iosfwd>
1423 #include <cstddef>
1424 #include <ostream>
1425
1426 namespace Catch {
1427
1428 std::ostream& cout();
1429 std::ostream& cerr();
1430 std::ostream& clog();
1431
1432 class StringRef;
1433
1434 struct IStream {
1435 virtual ~IStream();
1436 virtual std::ostream& stream() const = 0;
1437 };
1438
1439 auto makeStream( StringRef const &filename ) -> IStream const*;
1440
1441 class ReusableStringStream : NonCopyable {
1442 std::size_t m_index;
1443 std::ostream* m_oss;
1444 public:
1445 ReusableStringStream();
1446 ~ReusableStringStream();
1447
1448 auto str() const -> std::string;
1449
1450 template<typename T>
operator <<(T const & value)1451 auto operator << ( T const& value ) -> ReusableStringStream& {
1452 *m_oss << value;
1453 return *this;
1454 }
get()1455 auto get() -> std::ostream& { return *m_oss; }
1456 };
1457 }
1458
1459 // end catch_stream.h
1460 // start catch_interfaces_enum_values_registry.h
1461
1462 #include <vector>
1463
1464 namespace Catch {
1465
1466 namespace Detail {
1467 struct EnumInfo {
1468 StringRef m_name;
1469 std::vector<std::pair<int, StringRef>> m_values;
1470
1471 ~EnumInfo();
1472
1473 StringRef lookup( int value ) const;
1474 };
1475 } // namespace Detail
1476
1477 struct IMutableEnumValuesRegistry {
1478 virtual ~IMutableEnumValuesRegistry();
1479
1480 virtual Detail::EnumInfo const& registerEnum( StringRef enumName, StringRef allEnums, std::vector<int> const& values ) = 0;
1481
1482 template<typename E>
registerEnumCatch::IMutableEnumValuesRegistry1483 Detail::EnumInfo const& registerEnum( StringRef enumName, StringRef allEnums, std::initializer_list<E> values ) {
1484 static_assert(sizeof(int) >= sizeof(E), "Cannot serialize enum to int");
1485 std::vector<int> intValues;
1486 intValues.reserve( values.size() );
1487 for( auto enumValue : values )
1488 intValues.push_back( static_cast<int>( enumValue ) );
1489 return registerEnum( enumName, allEnums, intValues );
1490 }
1491 };
1492
1493 } // Catch
1494
1495 // end catch_interfaces_enum_values_registry.h
1496
1497 #ifdef CATCH_CONFIG_CPP17_STRING_VIEW
1498 #include <string_view>
1499 #endif
1500
1501 #ifdef __OBJC__
1502 // start catch_objc_arc.hpp
1503
1504 #import <Foundation/Foundation.h>
1505
1506 #ifdef __has_feature
1507 #define CATCH_ARC_ENABLED __has_feature(objc_arc)
1508 #else
1509 #define CATCH_ARC_ENABLED 0
1510 #endif
1511
1512 void arcSafeRelease( NSObject* obj );
1513 id performOptionalSelector( id obj, SEL sel );
1514
1515 #if !CATCH_ARC_ENABLED
arcSafeRelease(NSObject * obj)1516 inline void arcSafeRelease( NSObject* obj ) {
1517 [obj release];
1518 }
performOptionalSelector(id obj,SEL sel)1519 inline id performOptionalSelector( id obj, SEL sel ) {
1520 if( [obj respondsToSelector: sel] )
1521 return [obj performSelector: sel];
1522 return nil;
1523 }
1524 #define CATCH_UNSAFE_UNRETAINED
1525 #define CATCH_ARC_STRONG
1526 #else
arcSafeRelease(NSObject *)1527 inline void arcSafeRelease( NSObject* ){}
performOptionalSelector(id obj,SEL sel)1528 inline id performOptionalSelector( id obj, SEL sel ) {
1529 #ifdef __clang__
1530 #pragma clang diagnostic push
1531 #pragma clang diagnostic ignored "-Warc-performSelector-leaks"
1532 #endif
1533 if( [obj respondsToSelector: sel] )
1534 return [obj performSelector: sel];
1535 #ifdef __clang__
1536 #pragma clang diagnostic pop
1537 #endif
1538 return nil;
1539 }
1540 #define CATCH_UNSAFE_UNRETAINED __unsafe_unretained
1541 #define CATCH_ARC_STRONG __strong
1542 #endif
1543
1544 // end catch_objc_arc.hpp
1545 #endif
1546
1547 #ifdef _MSC_VER
1548 #pragma warning(push)
1549 #pragma warning(disable:4180) // We attempt to stream a function (address) by const&, which MSVC complains about but is harmless
1550 #endif
1551
1552 namespace Catch {
1553 namespace Detail {
1554
1555 extern const std::string unprintableString;
1556
1557 std::string rawMemoryToString( const void *object, std::size_t size );
1558
1559 template<typename T>
rawMemoryToString(const T & object)1560 std::string rawMemoryToString( const T& object ) {
1561 return rawMemoryToString( &object, sizeof(object) );
1562 }
1563
1564 template<typename T>
1565 class IsStreamInsertable {
1566 template<typename Stream, typename U>
1567 static auto test(int)
1568 -> decltype(std::declval<Stream&>() << std::declval<U>(), std::true_type());
1569
1570 template<typename, typename>
1571 static auto test(...)->std::false_type;
1572
1573 public:
1574 static const bool value = decltype(test<std::ostream, const T&>(0))::value;
1575 };
1576
1577 template<typename E>
1578 std::string convertUnknownEnumToString( E e );
1579
1580 template<typename T>
1581 typename std::enable_if<
1582 !std::is_enum<T>::value && !std::is_base_of<std::exception, T>::value,
convertUnstreamable(T const &)1583 std::string>::type convertUnstreamable( T const& ) {
1584 return Detail::unprintableString;
1585 }
1586 template<typename T>
1587 typename std::enable_if<
1588 !std::is_enum<T>::value && std::is_base_of<std::exception, T>::value,
convertUnstreamable(T const & ex)1589 std::string>::type convertUnstreamable(T const& ex) {
1590 return ex.what();
1591 }
1592
1593 template<typename T>
1594 typename std::enable_if<
1595 std::is_enum<T>::value
convertUnstreamable(T const & value)1596 , std::string>::type convertUnstreamable( T const& value ) {
1597 return convertUnknownEnumToString( value );
1598 }
1599
1600 #if defined(_MANAGED)
1601 //! Convert a CLR string to a utf8 std::string
1602 template<typename T>
1603 std::string clrReferenceToString( T^ ref ) {
1604 if (ref == nullptr)
1605 return std::string("null");
1606 auto bytes = System::Text::Encoding::UTF8->GetBytes(ref->ToString());
1607 cli::pin_ptr<System::Byte> p = &bytes[0];
1608 return std::string(reinterpret_cast<char const *>(p), bytes->Length);
1609 }
1610 #endif
1611
1612 } // namespace Detail
1613
1614 // If we decide for C++14, change these to enable_if_ts
1615 template <typename T, typename = void>
1616 struct StringMaker {
1617 template <typename Fake = T>
1618 static
1619 typename std::enable_if<::Catch::Detail::IsStreamInsertable<Fake>::value, std::string>::type
convertCatch::StringMaker1620 convert(const Fake& value) {
1621 ReusableStringStream rss;
1622 // NB: call using the function-like syntax to avoid ambiguity with
1623 // user-defined templated operator<< under clang.
1624 rss.operator<<(value);
1625 return rss.str();
1626 }
1627
1628 template <typename Fake = T>
1629 static
1630 typename std::enable_if<!::Catch::Detail::IsStreamInsertable<Fake>::value, std::string>::type
convertCatch::StringMaker1631 convert( const Fake& value ) {
1632 #if !defined(CATCH_CONFIG_FALLBACK_STRINGIFIER)
1633 return Detail::convertUnstreamable(value);
1634 #else
1635 return CATCH_CONFIG_FALLBACK_STRINGIFIER(value);
1636 #endif
1637 }
1638 };
1639
1640 namespace Detail {
1641
1642 // This function dispatches all stringification requests inside of Catch.
1643 // Should be preferably called fully qualified, like ::Catch::Detail::stringify
1644 template <typename T>
stringify(const T & e)1645 std::string stringify(const T& e) {
1646 return ::Catch::StringMaker<typename std::remove_cv<typename std::remove_reference<T>::type>::type>::convert(e);
1647 }
1648
1649 template<typename E>
convertUnknownEnumToString(E e)1650 std::string convertUnknownEnumToString( E e ) {
1651 return ::Catch::Detail::stringify(static_cast<typename std::underlying_type<E>::type>(e));
1652 }
1653
1654 #if defined(_MANAGED)
1655 template <typename T>
1656 std::string stringify( T^ e ) {
1657 return ::Catch::StringMaker<T^>::convert(e);
1658 }
1659 #endif
1660
1661 } // namespace Detail
1662
1663 // Some predefined specializations
1664
1665 template<>
1666 struct StringMaker<std::string> {
1667 static std::string convert(const std::string& str);
1668 };
1669
1670 #ifdef CATCH_CONFIG_CPP17_STRING_VIEW
1671 template<>
1672 struct StringMaker<std::string_view> {
1673 static std::string convert(std::string_view str);
1674 };
1675 #endif
1676
1677 template<>
1678 struct StringMaker<char const *> {
1679 static std::string convert(char const * str);
1680 };
1681 template<>
1682 struct StringMaker<char *> {
1683 static std::string convert(char * str);
1684 };
1685
1686 #ifdef CATCH_CONFIG_WCHAR
1687 template<>
1688 struct StringMaker<std::wstring> {
1689 static std::string convert(const std::wstring& wstr);
1690 };
1691
1692 # ifdef CATCH_CONFIG_CPP17_STRING_VIEW
1693 template<>
1694 struct StringMaker<std::wstring_view> {
1695 static std::string convert(std::wstring_view str);
1696 };
1697 # endif
1698
1699 template<>
1700 struct StringMaker<wchar_t const *> {
1701 static std::string convert(wchar_t const * str);
1702 };
1703 template<>
1704 struct StringMaker<wchar_t *> {
1705 static std::string convert(wchar_t * str);
1706 };
1707 #endif
1708
1709 // TBD: Should we use `strnlen` to ensure that we don't go out of the buffer,
1710 // while keeping string semantics?
1711 template<int SZ>
1712 struct StringMaker<char[SZ]> {
convertCatch::StringMaker1713 static std::string convert(char const* str) {
1714 return ::Catch::Detail::stringify(std::string{ str });
1715 }
1716 };
1717 template<int SZ>
1718 struct StringMaker<signed char[SZ]> {
convertCatch::StringMaker1719 static std::string convert(signed char const* str) {
1720 return ::Catch::Detail::stringify(std::string{ reinterpret_cast<char const *>(str) });
1721 }
1722 };
1723 template<int SZ>
1724 struct StringMaker<unsigned char[SZ]> {
convertCatch::StringMaker1725 static std::string convert(unsigned char const* str) {
1726 return ::Catch::Detail::stringify(std::string{ reinterpret_cast<char const *>(str) });
1727 }
1728 };
1729
1730 #if defined(CATCH_CONFIG_CPP17_BYTE)
1731 template<>
1732 struct StringMaker<std::byte> {
1733 static std::string convert(std::byte value);
1734 };
1735 #endif // defined(CATCH_CONFIG_CPP17_BYTE)
1736 template<>
1737 struct StringMaker<int> {
1738 static std::string convert(int value);
1739 };
1740 template<>
1741 struct StringMaker<long> {
1742 static std::string convert(long value);
1743 };
1744 template<>
1745 struct StringMaker<long long> {
1746 static std::string convert(long long value);
1747 };
1748 template<>
1749 struct StringMaker<unsigned int> {
1750 static std::string convert(unsigned int value);
1751 };
1752 template<>
1753 struct StringMaker<unsigned long> {
1754 static std::string convert(unsigned long value);
1755 };
1756 template<>
1757 struct StringMaker<unsigned long long> {
1758 static std::string convert(unsigned long long value);
1759 };
1760
1761 template<>
1762 struct StringMaker<bool> {
1763 static std::string convert(bool b);
1764 };
1765
1766 template<>
1767 struct StringMaker<char> {
1768 static std::string convert(char c);
1769 };
1770 template<>
1771 struct StringMaker<signed char> {
1772 static std::string convert(signed char c);
1773 };
1774 template<>
1775 struct StringMaker<unsigned char> {
1776 static std::string convert(unsigned char c);
1777 };
1778
1779 template<>
1780 struct StringMaker<std::nullptr_t> {
1781 static std::string convert(std::nullptr_t);
1782 };
1783
1784 template<>
1785 struct StringMaker<float> {
1786 static std::string convert(float value);
1787 static int precision;
1788 };
1789
1790 template<>
1791 struct StringMaker<double> {
1792 static std::string convert(double value);
1793 static int precision;
1794 };
1795
1796 template <typename T>
1797 struct StringMaker<T*> {
1798 template <typename U>
convertCatch::StringMaker1799 static std::string convert(U* p) {
1800 if (p) {
1801 return ::Catch::Detail::rawMemoryToString(p);
1802 } else {
1803 return "nullptr";
1804 }
1805 }
1806 };
1807
1808 template <typename R, typename C>
1809 struct StringMaker<R C::*> {
convertCatch::StringMaker1810 static std::string convert(R C::* p) {
1811 if (p) {
1812 return ::Catch::Detail::rawMemoryToString(p);
1813 } else {
1814 return "nullptr";
1815 }
1816 }
1817 };
1818
1819 #if defined(_MANAGED)
1820 template <typename T>
1821 struct StringMaker<T^> {
1822 static std::string convert( T^ ref ) {
1823 return ::Catch::Detail::clrReferenceToString(ref);
1824 }
1825 };
1826 #endif
1827
1828 namespace Detail {
1829 template<typename InputIterator, typename Sentinel = InputIterator>
rangeToString(InputIterator first,Sentinel last)1830 std::string rangeToString(InputIterator first, Sentinel last) {
1831 ReusableStringStream rss;
1832 rss << "{ ";
1833 if (first != last) {
1834 rss << ::Catch::Detail::stringify(*first);
1835 for (++first; first != last; ++first)
1836 rss << ", " << ::Catch::Detail::stringify(*first);
1837 }
1838 rss << " }";
1839 return rss.str();
1840 }
1841 }
1842
1843 #ifdef __OBJC__
1844 template<>
1845 struct StringMaker<NSString*> {
convertCatch::StringMaker1846 static std::string convert(NSString * nsstring) {
1847 if (!nsstring)
1848 return "nil";
1849 return std::string("@") + [nsstring UTF8String];
1850 }
1851 };
1852 template<>
1853 struct StringMaker<NSObject*> {
convertCatch::StringMaker1854 static std::string convert(NSObject* nsObject) {
1855 return ::Catch::Detail::stringify([nsObject description]);
1856 }
1857
1858 };
1859 namespace Detail {
stringify(NSString * nsstring)1860 inline std::string stringify( NSString* nsstring ) {
1861 return StringMaker<NSString*>::convert( nsstring );
1862 }
1863
1864 } // namespace Detail
1865 #endif // __OBJC__
1866
1867 } // namespace Catch
1868
1869 //////////////////////////////////////////////////////
1870 // Separate std-lib types stringification, so it can be selectively enabled
1871 // This means that we do not bring in
1872
1873 #if defined(CATCH_CONFIG_ENABLE_ALL_STRINGMAKERS)
1874 # define CATCH_CONFIG_ENABLE_PAIR_STRINGMAKER
1875 # define CATCH_CONFIG_ENABLE_TUPLE_STRINGMAKER
1876 # define CATCH_CONFIG_ENABLE_VARIANT_STRINGMAKER
1877 # define CATCH_CONFIG_ENABLE_CHRONO_STRINGMAKER
1878 # define CATCH_CONFIG_ENABLE_OPTIONAL_STRINGMAKER
1879 #endif
1880
1881 // Separate std::pair specialization
1882 #if defined(CATCH_CONFIG_ENABLE_PAIR_STRINGMAKER)
1883 #include <utility>
1884 namespace Catch {
1885 template<typename T1, typename T2>
1886 struct StringMaker<std::pair<T1, T2> > {
convertCatch::StringMaker1887 static std::string convert(const std::pair<T1, T2>& pair) {
1888 ReusableStringStream rss;
1889 rss << "{ "
1890 << ::Catch::Detail::stringify(pair.first)
1891 << ", "
1892 << ::Catch::Detail::stringify(pair.second)
1893 << " }";
1894 return rss.str();
1895 }
1896 };
1897 }
1898 #endif // CATCH_CONFIG_ENABLE_PAIR_STRINGMAKER
1899
1900 #if defined(CATCH_CONFIG_ENABLE_OPTIONAL_STRINGMAKER) && defined(CATCH_CONFIG_CPP17_OPTIONAL)
1901 #include <optional>
1902 namespace Catch {
1903 template<typename T>
1904 struct StringMaker<std::optional<T> > {
convertCatch::StringMaker1905 static std::string convert(const std::optional<T>& optional) {
1906 ReusableStringStream rss;
1907 if (optional.has_value()) {
1908 rss << ::Catch::Detail::stringify(*optional);
1909 } else {
1910 rss << "{ }";
1911 }
1912 return rss.str();
1913 }
1914 };
1915 }
1916 #endif // CATCH_CONFIG_ENABLE_OPTIONAL_STRINGMAKER
1917
1918 // Separate std::tuple specialization
1919 #if defined(CATCH_CONFIG_ENABLE_TUPLE_STRINGMAKER)
1920 #include <tuple>
1921 namespace Catch {
1922 namespace Detail {
1923 template<
1924 typename Tuple,
1925 std::size_t N = 0,
1926 bool = (N < std::tuple_size<Tuple>::value)
1927 >
1928 struct TupleElementPrinter {
printCatch::Detail::TupleElementPrinter1929 static void print(const Tuple& tuple, std::ostream& os) {
1930 os << (N ? ", " : " ")
1931 << ::Catch::Detail::stringify(std::get<N>(tuple));
1932 TupleElementPrinter<Tuple, N + 1>::print(tuple, os);
1933 }
1934 };
1935
1936 template<
1937 typename Tuple,
1938 std::size_t N
1939 >
1940 struct TupleElementPrinter<Tuple, N, false> {
printCatch::Detail::TupleElementPrinter1941 static void print(const Tuple&, std::ostream&) {}
1942 };
1943
1944 }
1945
1946 template<typename ...Types>
1947 struct StringMaker<std::tuple<Types...>> {
convertCatch::StringMaker1948 static std::string convert(const std::tuple<Types...>& tuple) {
1949 ReusableStringStream rss;
1950 rss << '{';
1951 Detail::TupleElementPrinter<std::tuple<Types...>>::print(tuple, rss.get());
1952 rss << " }";
1953 return rss.str();
1954 }
1955 };
1956 }
1957 #endif // CATCH_CONFIG_ENABLE_TUPLE_STRINGMAKER
1958
1959 #if defined(CATCH_CONFIG_ENABLE_VARIANT_STRINGMAKER) && defined(CATCH_CONFIG_CPP17_VARIANT)
1960 #include <variant>
1961 namespace Catch {
1962 template<>
1963 struct StringMaker<std::monostate> {
convertCatch::StringMaker1964 static std::string convert(const std::monostate&) {
1965 return "{ }";
1966 }
1967 };
1968
1969 template<typename... Elements>
1970 struct StringMaker<std::variant<Elements...>> {
convertCatch::StringMaker1971 static std::string convert(const std::variant<Elements...>& variant) {
1972 if (variant.valueless_by_exception()) {
1973 return "{valueless variant}";
1974 } else {
1975 return std::visit(
1976 [](const auto& value) {
1977 return ::Catch::Detail::stringify(value);
1978 },
1979 variant
1980 );
1981 }
1982 }
1983 };
1984 }
1985 #endif // CATCH_CONFIG_ENABLE_VARIANT_STRINGMAKER
1986
1987 namespace Catch {
1988 // Import begin/ end from std here
1989 using std::begin;
1990 using std::end;
1991
1992 namespace detail {
1993 template <typename...>
1994 struct void_type {
1995 using type = void;
1996 };
1997
1998 template <typename T, typename = void>
1999 struct is_range_impl : std::false_type {
2000 };
2001
2002 template <typename T>
2003 struct is_range_impl<T, typename void_type<decltype(begin(std::declval<T>()))>::type> : std::true_type {
2004 };
2005 } // namespace detail
2006
2007 template <typename T>
2008 struct is_range : detail::is_range_impl<T> {
2009 };
2010
2011 #if defined(_MANAGED) // Managed types are never ranges
2012 template <typename T>
2013 struct is_range<T^> {
2014 static const bool value = false;
2015 };
2016 #endif
2017
2018 template<typename Range>
rangeToString(Range const & range)2019 std::string rangeToString( Range const& range ) {
2020 return ::Catch::Detail::rangeToString( begin( range ), end( range ) );
2021 }
2022
2023 // Handle vector<bool> specially
2024 template<typename Allocator>
rangeToString(std::vector<bool,Allocator> const & v)2025 std::string rangeToString( std::vector<bool, Allocator> const& v ) {
2026 ReusableStringStream rss;
2027 rss << "{ ";
2028 bool first = true;
2029 for( bool b : v ) {
2030 if( first )
2031 first = false;
2032 else
2033 rss << ", ";
2034 rss << ::Catch::Detail::stringify( b );
2035 }
2036 rss << " }";
2037 return rss.str();
2038 }
2039
2040 template<typename R>
2041 struct StringMaker<R, typename std::enable_if<is_range<R>::value && !::Catch::Detail::IsStreamInsertable<R>::value>::type> {
convertCatch::StringMaker2042 static std::string convert( R const& range ) {
2043 return rangeToString( range );
2044 }
2045 };
2046
2047 template <typename T, int SZ>
2048 struct StringMaker<T[SZ]> {
convertCatch::StringMaker2049 static std::string convert(T const(&arr)[SZ]) {
2050 return rangeToString(arr);
2051 }
2052 };
2053
2054 } // namespace Catch
2055
2056 // Separate std::chrono::duration specialization
2057 #if defined(CATCH_CONFIG_ENABLE_CHRONO_STRINGMAKER)
2058 #include <ctime>
2059 #include <ratio>
2060 #include <chrono>
2061
2062 namespace Catch {
2063
2064 template <class Ratio>
2065 struct ratio_string {
2066 static std::string symbol();
2067 };
2068
2069 template <class Ratio>
symbol()2070 std::string ratio_string<Ratio>::symbol() {
2071 Catch::ReusableStringStream rss;
2072 rss << '[' << Ratio::num << '/'
2073 << Ratio::den << ']';
2074 return rss.str();
2075 }
2076 template <>
2077 struct ratio_string<std::atto> {
2078 static std::string symbol();
2079 };
2080 template <>
2081 struct ratio_string<std::femto> {
2082 static std::string symbol();
2083 };
2084 template <>
2085 struct ratio_string<std::pico> {
2086 static std::string symbol();
2087 };
2088 template <>
2089 struct ratio_string<std::nano> {
2090 static std::string symbol();
2091 };
2092 template <>
2093 struct ratio_string<std::micro> {
2094 static std::string symbol();
2095 };
2096 template <>
2097 struct ratio_string<std::milli> {
2098 static std::string symbol();
2099 };
2100
2101 ////////////
2102 // std::chrono::duration specializations
2103 template<typename Value, typename Ratio>
2104 struct StringMaker<std::chrono::duration<Value, Ratio>> {
convertCatch::StringMaker2105 static std::string convert(std::chrono::duration<Value, Ratio> const& duration) {
2106 ReusableStringStream rss;
2107 rss << duration.count() << ' ' << ratio_string<Ratio>::symbol() << 's';
2108 return rss.str();
2109 }
2110 };
2111 template<typename Value>
2112 struct StringMaker<std::chrono::duration<Value, std::ratio<1>>> {
convertCatch::StringMaker2113 static std::string convert(std::chrono::duration<Value, std::ratio<1>> const& duration) {
2114 ReusableStringStream rss;
2115 rss << duration.count() << " s";
2116 return rss.str();
2117 }
2118 };
2119 template<typename Value>
2120 struct StringMaker<std::chrono::duration<Value, std::ratio<60>>> {
convertCatch::StringMaker2121 static std::string convert(std::chrono::duration<Value, std::ratio<60>> const& duration) {
2122 ReusableStringStream rss;
2123 rss << duration.count() << " m";
2124 return rss.str();
2125 }
2126 };
2127 template<typename Value>
2128 struct StringMaker<std::chrono::duration<Value, std::ratio<3600>>> {
convertCatch::StringMaker2129 static std::string convert(std::chrono::duration<Value, std::ratio<3600>> const& duration) {
2130 ReusableStringStream rss;
2131 rss << duration.count() << " h";
2132 return rss.str();
2133 }
2134 };
2135
2136 ////////////
2137 // std::chrono::time_point specialization
2138 // Generic time_point cannot be specialized, only std::chrono::time_point<system_clock>
2139 template<typename Clock, typename Duration>
2140 struct StringMaker<std::chrono::time_point<Clock, Duration>> {
convertCatch::StringMaker2141 static std::string convert(std::chrono::time_point<Clock, Duration> const& time_point) {
2142 return ::Catch::Detail::stringify(time_point.time_since_epoch()) + " since epoch";
2143 }
2144 };
2145 // std::chrono::time_point<system_clock> specialization
2146 template<typename Duration>
2147 struct StringMaker<std::chrono::time_point<std::chrono::system_clock, Duration>> {
convertCatch::StringMaker2148 static std::string convert(std::chrono::time_point<std::chrono::system_clock, Duration> const& time_point) {
2149 auto converted = std::chrono::system_clock::to_time_t(time_point);
2150
2151 #ifdef _MSC_VER
2152 std::tm timeInfo = {};
2153 gmtime_s(&timeInfo, &converted);
2154 #else
2155 std::tm* timeInfo = std::gmtime(&converted);
2156 #endif
2157
2158 auto const timeStampSize = sizeof("2017-01-16T17:06:45Z");
2159 char timeStamp[timeStampSize];
2160 const char * const fmt = "%Y-%m-%dT%H:%M:%SZ";
2161
2162 #ifdef _MSC_VER
2163 std::strftime(timeStamp, timeStampSize, fmt, &timeInfo);
2164 #else
2165 std::strftime(timeStamp, timeStampSize, fmt, timeInfo);
2166 #endif
2167 return std::string(timeStamp);
2168 }
2169 };
2170 }
2171 #endif // CATCH_CONFIG_ENABLE_CHRONO_STRINGMAKER
2172
2173 #define INTERNAL_CATCH_REGISTER_ENUM( enumName, ... ) \
2174 namespace Catch { \
2175 template<> struct StringMaker<enumName> { \
2176 static std::string convert( enumName value ) { \
2177 static const auto& enumInfo = ::Catch::getMutableRegistryHub().getMutableEnumValuesRegistry().registerEnum( #enumName, #__VA_ARGS__, { __VA_ARGS__ } ); \
2178 return static_cast<std::string>(enumInfo.lookup( static_cast<int>( value ) )); \
2179 } \
2180 }; \
2181 }
2182
2183 #define CATCH_REGISTER_ENUM( enumName, ... ) INTERNAL_CATCH_REGISTER_ENUM( enumName, __VA_ARGS__ )
2184
2185 #ifdef _MSC_VER
2186 #pragma warning(pop)
2187 #endif
2188
2189 // end catch_tostring.h
2190 #include <iosfwd>
2191
2192 #ifdef _MSC_VER
2193 #pragma warning(push)
2194 #pragma warning(disable:4389) // '==' : signed/unsigned mismatch
2195 #pragma warning(disable:4018) // more "signed/unsigned mismatch"
2196 #pragma warning(disable:4312) // Converting int to T* using reinterpret_cast (issue on x64 platform)
2197 #pragma warning(disable:4180) // qualifier applied to function type has no meaning
2198 #pragma warning(disable:4800) // Forcing result to true or false
2199 #endif
2200
2201 namespace Catch {
2202
2203 struct ITransientExpression {
isBinaryExpressionCatch::ITransientExpression2204 auto isBinaryExpression() const -> bool { return m_isBinaryExpression; }
getResultCatch::ITransientExpression2205 auto getResult() const -> bool { return m_result; }
2206 virtual void streamReconstructedExpression( std::ostream &os ) const = 0;
2207
ITransientExpressionCatch::ITransientExpression2208 ITransientExpression( bool isBinaryExpression, bool result )
2209 : m_isBinaryExpression( isBinaryExpression ),
2210 m_result( result )
2211 {}
2212
2213 // We don't actually need a virtual destructor, but many static analysers
2214 // complain if it's not here :-(
2215 virtual ~ITransientExpression();
2216
2217 bool m_isBinaryExpression;
2218 bool m_result;
2219
2220 };
2221
2222 void formatReconstructedExpression( std::ostream &os, std::string const& lhs, StringRef op, std::string const& rhs );
2223
2224 template<typename LhsT, typename RhsT>
2225 class BinaryExpr : public ITransientExpression {
2226 LhsT m_lhs;
2227 StringRef m_op;
2228 RhsT m_rhs;
2229
streamReconstructedExpression(std::ostream & os) const2230 void streamReconstructedExpression( std::ostream &os ) const override {
2231 formatReconstructedExpression
2232 ( os, Catch::Detail::stringify( m_lhs ), m_op, Catch::Detail::stringify( m_rhs ) );
2233 }
2234
2235 public:
BinaryExpr(bool comparisonResult,LhsT lhs,StringRef op,RhsT rhs)2236 BinaryExpr( bool comparisonResult, LhsT lhs, StringRef op, RhsT rhs )
2237 : ITransientExpression{ true, comparisonResult },
2238 m_lhs( lhs ),
2239 m_op( op ),
2240 m_rhs( rhs )
2241 {}
2242
2243 template<typename T>
operator &&(T) const2244 auto operator && ( T ) const -> BinaryExpr<LhsT, RhsT const&> const {
2245 static_assert(always_false<T>::value,
2246 "chained comparisons are not supported inside assertions, "
2247 "wrap the expression inside parentheses, or decompose it");
2248 }
2249
2250 template<typename T>
operator ||(T) const2251 auto operator || ( T ) const -> BinaryExpr<LhsT, RhsT const&> const {
2252 static_assert(always_false<T>::value,
2253 "chained comparisons are not supported inside assertions, "
2254 "wrap the expression inside parentheses, or decompose it");
2255 }
2256
2257 template<typename T>
operator ==(T) const2258 auto operator == ( T ) const -> BinaryExpr<LhsT, RhsT const&> const {
2259 static_assert(always_false<T>::value,
2260 "chained comparisons are not supported inside assertions, "
2261 "wrap the expression inside parentheses, or decompose it");
2262 }
2263
2264 template<typename T>
operator !=(T) const2265 auto operator != ( T ) const -> BinaryExpr<LhsT, RhsT const&> const {
2266 static_assert(always_false<T>::value,
2267 "chained comparisons are not supported inside assertions, "
2268 "wrap the expression inside parentheses, or decompose it");
2269 }
2270
2271 template<typename T>
operator >(T) const2272 auto operator > ( T ) const -> BinaryExpr<LhsT, RhsT const&> const {
2273 static_assert(always_false<T>::value,
2274 "chained comparisons are not supported inside assertions, "
2275 "wrap the expression inside parentheses, or decompose it");
2276 }
2277
2278 template<typename T>
operator <(T) const2279 auto operator < ( T ) const -> BinaryExpr<LhsT, RhsT const&> const {
2280 static_assert(always_false<T>::value,
2281 "chained comparisons are not supported inside assertions, "
2282 "wrap the expression inside parentheses, or decompose it");
2283 }
2284
2285 template<typename T>
operator >=(T) const2286 auto operator >= ( T ) const -> BinaryExpr<LhsT, RhsT const&> const {
2287 static_assert(always_false<T>::value,
2288 "chained comparisons are not supported inside assertions, "
2289 "wrap the expression inside parentheses, or decompose it");
2290 }
2291
2292 template<typename T>
operator <=(T) const2293 auto operator <= ( T ) const -> BinaryExpr<LhsT, RhsT const&> const {
2294 static_assert(always_false<T>::value,
2295 "chained comparisons are not supported inside assertions, "
2296 "wrap the expression inside parentheses, or decompose it");
2297 }
2298 };
2299
2300 template<typename LhsT>
2301 class UnaryExpr : public ITransientExpression {
2302 LhsT m_lhs;
2303
streamReconstructedExpression(std::ostream & os) const2304 void streamReconstructedExpression( std::ostream &os ) const override {
2305 os << Catch::Detail::stringify( m_lhs );
2306 }
2307
2308 public:
UnaryExpr(LhsT lhs)2309 explicit UnaryExpr( LhsT lhs )
2310 : ITransientExpression{ false, static_cast<bool>(lhs) },
2311 m_lhs( lhs )
2312 {}
2313 };
2314
2315 // Specialised comparison functions to handle equality comparisons between ints and pointers (NULL deduces as an int)
2316 template<typename LhsT, typename RhsT>
compareEqual(LhsT const & lhs,RhsT const & rhs)2317 auto compareEqual( LhsT const& lhs, RhsT const& rhs ) -> bool { return static_cast<bool>(lhs == rhs); }
2318 template<typename T>
compareEqual(T * const & lhs,int rhs)2319 auto compareEqual( T* const& lhs, int rhs ) -> bool { return lhs == reinterpret_cast<void const*>( rhs ); }
2320 template<typename T>
compareEqual(T * const & lhs,long rhs)2321 auto compareEqual( T* const& lhs, long rhs ) -> bool { return lhs == reinterpret_cast<void const*>( rhs ); }
2322 template<typename T>
compareEqual(int lhs,T * const & rhs)2323 auto compareEqual( int lhs, T* const& rhs ) -> bool { return reinterpret_cast<void const*>( lhs ) == rhs; }
2324 template<typename T>
compareEqual(long lhs,T * const & rhs)2325 auto compareEqual( long lhs, T* const& rhs ) -> bool { return reinterpret_cast<void const*>( lhs ) == rhs; }
2326
2327 template<typename LhsT, typename RhsT>
compareNotEqual(LhsT const & lhs,RhsT && rhs)2328 auto compareNotEqual( LhsT const& lhs, RhsT&& rhs ) -> bool { return static_cast<bool>(lhs != rhs); }
2329 template<typename T>
compareNotEqual(T * const & lhs,int rhs)2330 auto compareNotEqual( T* const& lhs, int rhs ) -> bool { return lhs != reinterpret_cast<void const*>( rhs ); }
2331 template<typename T>
compareNotEqual(T * const & lhs,long rhs)2332 auto compareNotEqual( T* const& lhs, long rhs ) -> bool { return lhs != reinterpret_cast<void const*>( rhs ); }
2333 template<typename T>
compareNotEqual(int lhs,T * const & rhs)2334 auto compareNotEqual( int lhs, T* const& rhs ) -> bool { return reinterpret_cast<void const*>( lhs ) != rhs; }
2335 template<typename T>
compareNotEqual(long lhs,T * const & rhs)2336 auto compareNotEqual( long lhs, T* const& rhs ) -> bool { return reinterpret_cast<void const*>( lhs ) != rhs; }
2337
2338 template<typename LhsT>
2339 class ExprLhs {
2340 LhsT m_lhs;
2341 public:
ExprLhs(LhsT lhs)2342 explicit ExprLhs( LhsT lhs ) : m_lhs( lhs ) {}
2343
2344 template<typename RhsT>
operator ==(RhsT const & rhs)2345 auto operator == ( RhsT const& rhs ) -> BinaryExpr<LhsT, RhsT const&> const {
2346 return { compareEqual( m_lhs, rhs ), m_lhs, "==", rhs };
2347 }
operator ==(bool rhs)2348 auto operator == ( bool rhs ) -> BinaryExpr<LhsT, bool> const {
2349 return { m_lhs == rhs, m_lhs, "==", rhs };
2350 }
2351
2352 template<typename RhsT>
operator !=(RhsT const & rhs)2353 auto operator != ( RhsT const& rhs ) -> BinaryExpr<LhsT, RhsT const&> const {
2354 return { compareNotEqual( m_lhs, rhs ), m_lhs, "!=", rhs };
2355 }
operator !=(bool rhs)2356 auto operator != ( bool rhs ) -> BinaryExpr<LhsT, bool> const {
2357 return { m_lhs != rhs, m_lhs, "!=", rhs };
2358 }
2359
2360 template<typename RhsT>
operator >(RhsT const & rhs)2361 auto operator > ( RhsT const& rhs ) -> BinaryExpr<LhsT, RhsT const&> const {
2362 return { static_cast<bool>(m_lhs > rhs), m_lhs, ">", rhs };
2363 }
2364 template<typename RhsT>
operator <(RhsT const & rhs)2365 auto operator < ( RhsT const& rhs ) -> BinaryExpr<LhsT, RhsT const&> const {
2366 return { static_cast<bool>(m_lhs < rhs), m_lhs, "<", rhs };
2367 }
2368 template<typename RhsT>
operator >=(RhsT const & rhs)2369 auto operator >= ( RhsT const& rhs ) -> BinaryExpr<LhsT, RhsT const&> const {
2370 return { static_cast<bool>(m_lhs >= rhs), m_lhs, ">=", rhs };
2371 }
2372 template<typename RhsT>
operator <=(RhsT const & rhs)2373 auto operator <= ( RhsT const& rhs ) -> BinaryExpr<LhsT, RhsT const&> const {
2374 return { static_cast<bool>(m_lhs <= rhs), m_lhs, "<=", rhs };
2375 }
2376 template <typename RhsT>
operator |(RhsT const & rhs)2377 auto operator | (RhsT const& rhs) -> BinaryExpr<LhsT, RhsT const&> const {
2378 return { static_cast<bool>(m_lhs | rhs), m_lhs, "|", rhs };
2379 }
2380 template <typename RhsT>
operator &(RhsT const & rhs)2381 auto operator & (RhsT const& rhs) -> BinaryExpr<LhsT, RhsT const&> const {
2382 return { static_cast<bool>(m_lhs & rhs), m_lhs, "&", rhs };
2383 }
2384 template <typename RhsT>
operator ^(RhsT const & rhs)2385 auto operator ^ (RhsT const& rhs) -> BinaryExpr<LhsT, RhsT const&> const {
2386 return { static_cast<bool>(m_lhs ^ rhs), m_lhs, "^", rhs };
2387 }
2388
2389 template<typename RhsT>
operator &&(RhsT const &)2390 auto operator && ( RhsT const& ) -> BinaryExpr<LhsT, RhsT const&> const {
2391 static_assert(always_false<RhsT>::value,
2392 "operator&& is not supported inside assertions, "
2393 "wrap the expression inside parentheses, or decompose it");
2394 }
2395
2396 template<typename RhsT>
operator ||(RhsT const &)2397 auto operator || ( RhsT const& ) -> BinaryExpr<LhsT, RhsT const&> const {
2398 static_assert(always_false<RhsT>::value,
2399 "operator|| is not supported inside assertions, "
2400 "wrap the expression inside parentheses, or decompose it");
2401 }
2402
makeUnaryExpr() const2403 auto makeUnaryExpr() const -> UnaryExpr<LhsT> {
2404 return UnaryExpr<LhsT>{ m_lhs };
2405 }
2406 };
2407
2408 void handleExpression( ITransientExpression const& expr );
2409
2410 template<typename T>
handleExpression(ExprLhs<T> const & expr)2411 void handleExpression( ExprLhs<T> const& expr ) {
2412 handleExpression( expr.makeUnaryExpr() );
2413 }
2414
2415 struct Decomposer {
2416 template<typename T>
operator <=Catch::Decomposer2417 auto operator <= ( T const& lhs ) -> ExprLhs<T const&> {
2418 return ExprLhs<T const&>{ lhs };
2419 }
2420
operator <=Catch::Decomposer2421 auto operator <=( bool value ) -> ExprLhs<bool> {
2422 return ExprLhs<bool>{ value };
2423 }
2424 };
2425
2426 } // end namespace Catch
2427
2428 #ifdef _MSC_VER
2429 #pragma warning(pop)
2430 #endif
2431
2432 // end catch_decomposer.h
2433 // start catch_interfaces_capture.h
2434
2435 #include <string>
2436 #include <chrono>
2437
2438 namespace Catch {
2439
2440 class AssertionResult;
2441 struct AssertionInfo;
2442 struct SectionInfo;
2443 struct SectionEndInfo;
2444 struct MessageInfo;
2445 struct MessageBuilder;
2446 struct Counts;
2447 struct AssertionReaction;
2448 struct SourceLineInfo;
2449
2450 struct ITransientExpression;
2451 struct IGeneratorTracker;
2452
2453 #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
2454 struct BenchmarkInfo;
2455 template <typename Duration = std::chrono::duration<double, std::nano>>
2456 struct BenchmarkStats;
2457 #endif // CATCH_CONFIG_ENABLE_BENCHMARKING
2458
2459 struct IResultCapture {
2460
2461 virtual ~IResultCapture();
2462
2463 virtual bool sectionStarted( SectionInfo const& sectionInfo,
2464 Counts& assertions ) = 0;
2465 virtual void sectionEnded( SectionEndInfo const& endInfo ) = 0;
2466 virtual void sectionEndedEarly( SectionEndInfo const& endInfo ) = 0;
2467
2468 virtual auto acquireGeneratorTracker( StringRef generatorName, SourceLineInfo const& lineInfo ) -> IGeneratorTracker& = 0;
2469
2470 #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
2471 virtual void benchmarkPreparing( std::string const& name ) = 0;
2472 virtual void benchmarkStarting( BenchmarkInfo const& info ) = 0;
2473 virtual void benchmarkEnded( BenchmarkStats<> const& stats ) = 0;
2474 virtual void benchmarkFailed( std::string const& error ) = 0;
2475 #endif // CATCH_CONFIG_ENABLE_BENCHMARKING
2476
2477 virtual void pushScopedMessage( MessageInfo const& message ) = 0;
2478 virtual void popScopedMessage( MessageInfo const& message ) = 0;
2479
2480 virtual void emplaceUnscopedMessage( MessageBuilder const& builder ) = 0;
2481
2482 virtual void handleFatalErrorCondition( StringRef message ) = 0;
2483
2484 virtual void handleExpr
2485 ( AssertionInfo const& info,
2486 ITransientExpression const& expr,
2487 AssertionReaction& reaction ) = 0;
2488 virtual void handleMessage
2489 ( AssertionInfo const& info,
2490 ResultWas::OfType resultType,
2491 StringRef const& message,
2492 AssertionReaction& reaction ) = 0;
2493 virtual void handleUnexpectedExceptionNotThrown
2494 ( AssertionInfo const& info,
2495 AssertionReaction& reaction ) = 0;
2496 virtual void handleUnexpectedInflightException
2497 ( AssertionInfo const& info,
2498 std::string const& message,
2499 AssertionReaction& reaction ) = 0;
2500 virtual void handleIncomplete
2501 ( AssertionInfo const& info ) = 0;
2502 virtual void handleNonExpr
2503 ( AssertionInfo const &info,
2504 ResultWas::OfType resultType,
2505 AssertionReaction &reaction ) = 0;
2506
2507 virtual bool lastAssertionPassed() = 0;
2508 virtual void assertionPassed() = 0;
2509
2510 // Deprecated, do not use:
2511 virtual std::string getCurrentTestName() const = 0;
2512 virtual const AssertionResult* getLastResult() const = 0;
2513 virtual void exceptionEarlyReported() = 0;
2514 };
2515
2516 IResultCapture& getResultCapture();
2517 }
2518
2519 // end catch_interfaces_capture.h
2520 namespace Catch {
2521
2522 struct TestFailureException{};
2523 struct AssertionResultData;
2524 struct IResultCapture;
2525 class RunContext;
2526
2527 class LazyExpression {
2528 friend class AssertionHandler;
2529 friend struct AssertionStats;
2530 friend class RunContext;
2531
2532 ITransientExpression const* m_transientExpression = nullptr;
2533 bool m_isNegated;
2534 public:
2535 LazyExpression( bool isNegated );
2536 LazyExpression( LazyExpression const& other );
2537 LazyExpression& operator = ( LazyExpression const& ) = delete;
2538
2539 explicit operator bool() const;
2540
2541 friend auto operator << ( std::ostream& os, LazyExpression const& lazyExpr ) -> std::ostream&;
2542 };
2543
2544 struct AssertionReaction {
2545 bool shouldDebugBreak = false;
2546 bool shouldThrow = false;
2547 };
2548
2549 class AssertionHandler {
2550 AssertionInfo m_assertionInfo;
2551 AssertionReaction m_reaction;
2552 bool m_completed = false;
2553 IResultCapture& m_resultCapture;
2554
2555 public:
2556 AssertionHandler
2557 ( StringRef const& macroName,
2558 SourceLineInfo const& lineInfo,
2559 StringRef capturedExpression,
2560 ResultDisposition::Flags resultDisposition );
~AssertionHandler()2561 ~AssertionHandler() {
2562 if ( !m_completed ) {
2563 m_resultCapture.handleIncomplete( m_assertionInfo );
2564 }
2565 }
2566
2567 template<typename T>
handleExpr(ExprLhs<T> const & expr)2568 void handleExpr( ExprLhs<T> const& expr ) {
2569 handleExpr( expr.makeUnaryExpr() );
2570 }
2571 void handleExpr( ITransientExpression const& expr );
2572
2573 void handleMessage(ResultWas::OfType resultType, StringRef const& message);
2574
2575 void handleExceptionThrownAsExpected();
2576 void handleUnexpectedExceptionNotThrown();
2577 void handleExceptionNotThrownAsExpected();
2578 void handleThrowingCallSkipped();
2579 void handleUnexpectedInflightException();
2580
2581 void complete();
2582 void setCompleted();
2583
2584 // query
2585 auto allowThrows() const -> bool;
2586 };
2587
2588 void handleExceptionMatchExpr( AssertionHandler& handler, std::string const& str, StringRef const& matcherString );
2589
2590 } // namespace Catch
2591
2592 // end catch_assertionhandler.h
2593 // start catch_message.h
2594
2595 #include <string>
2596 #include <vector>
2597
2598 namespace Catch {
2599
2600 struct MessageInfo {
2601 MessageInfo( StringRef const& _macroName,
2602 SourceLineInfo const& _lineInfo,
2603 ResultWas::OfType _type );
2604
2605 StringRef macroName;
2606 std::string message;
2607 SourceLineInfo lineInfo;
2608 ResultWas::OfType type;
2609 unsigned int sequence;
2610
2611 bool operator == ( MessageInfo const& other ) const;
2612 bool operator < ( MessageInfo const& other ) const;
2613 private:
2614 static unsigned int globalCount;
2615 };
2616
2617 struct MessageStream {
2618
2619 template<typename T>
operator <<Catch::MessageStream2620 MessageStream& operator << ( T const& value ) {
2621 m_stream << value;
2622 return *this;
2623 }
2624
2625 ReusableStringStream m_stream;
2626 };
2627
2628 struct MessageBuilder : MessageStream {
2629 MessageBuilder( StringRef const& macroName,
2630 SourceLineInfo const& lineInfo,
2631 ResultWas::OfType type );
2632
2633 template<typename T>
operator <<Catch::MessageBuilder2634 MessageBuilder& operator << ( T const& value ) {
2635 m_stream << value;
2636 return *this;
2637 }
2638
2639 MessageInfo m_info;
2640 };
2641
2642 class ScopedMessage {
2643 public:
2644 explicit ScopedMessage( MessageBuilder const& builder );
2645 ScopedMessage( ScopedMessage& duplicate ) = delete;
2646 ScopedMessage( ScopedMessage&& old );
2647 ~ScopedMessage();
2648
2649 MessageInfo m_info;
2650 bool m_moved;
2651 };
2652
2653 class Capturer {
2654 std::vector<MessageInfo> m_messages;
2655 IResultCapture& m_resultCapture = getResultCapture();
2656 size_t m_captured = 0;
2657 public:
2658 Capturer( StringRef macroName, SourceLineInfo const& lineInfo, ResultWas::OfType resultType, StringRef names );
2659 ~Capturer();
2660
2661 void captureValue( size_t index, std::string const& value );
2662
2663 template<typename T>
captureValues(size_t index,T const & value)2664 void captureValues( size_t index, T const& value ) {
2665 captureValue( index, Catch::Detail::stringify( value ) );
2666 }
2667
2668 template<typename T, typename... Ts>
captureValues(size_t index,T const & value,Ts const &...values)2669 void captureValues( size_t index, T const& value, Ts const&... values ) {
2670 captureValue( index, Catch::Detail::stringify(value) );
2671 captureValues( index+1, values... );
2672 }
2673 };
2674
2675 } // end namespace Catch
2676
2677 // end catch_message.h
2678 #if !defined(CATCH_CONFIG_DISABLE)
2679
2680 #if !defined(CATCH_CONFIG_DISABLE_STRINGIFICATION)
2681 #define CATCH_INTERNAL_STRINGIFY(...) #__VA_ARGS__
2682 #else
2683 #define CATCH_INTERNAL_STRINGIFY(...) "Disabled by CATCH_CONFIG_DISABLE_STRINGIFICATION"
2684 #endif
2685
2686 #if defined(CATCH_CONFIG_FAST_COMPILE) || defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
2687
2688 ///////////////////////////////////////////////////////////////////////////////
2689 // Another way to speed-up compilation is to omit local try-catch for REQUIRE*
2690 // macros.
2691 #define INTERNAL_CATCH_TRY
2692 #define INTERNAL_CATCH_CATCH( capturer )
2693
2694 #else // CATCH_CONFIG_FAST_COMPILE
2695
2696 #define INTERNAL_CATCH_TRY try
2697 #define INTERNAL_CATCH_CATCH( handler ) catch(...) { handler.handleUnexpectedInflightException(); }
2698
2699 #endif
2700
2701 #define INTERNAL_CATCH_REACT( handler ) handler.complete();
2702
2703 ///////////////////////////////////////////////////////////////////////////////
2704 #define INTERNAL_CATCH_TEST( macroName, resultDisposition, ... ) \
2705 do { \
2706 CATCH_INTERNAL_IGNORE_BUT_WARN(__VA_ARGS__); \
2707 Catch::AssertionHandler catchAssertionHandler( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(__VA_ARGS__), resultDisposition ); \
2708 INTERNAL_CATCH_TRY { \
2709 CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \
2710 CATCH_INTERNAL_SUPPRESS_PARENTHESES_WARNINGS \
2711 catchAssertionHandler.handleExpr( Catch::Decomposer() <= __VA_ARGS__ ); \
2712 CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION \
2713 } INTERNAL_CATCH_CATCH( catchAssertionHandler ) \
2714 INTERNAL_CATCH_REACT( catchAssertionHandler ) \
2715 } while( (void)0, (false) && static_cast<bool>( !!(__VA_ARGS__) ) )
2716
2717 ///////////////////////////////////////////////////////////////////////////////
2718 #define INTERNAL_CATCH_IF( macroName, resultDisposition, ... ) \
2719 INTERNAL_CATCH_TEST( macroName, resultDisposition, __VA_ARGS__ ); \
2720 if( Catch::getResultCapture().lastAssertionPassed() )
2721
2722 ///////////////////////////////////////////////////////////////////////////////
2723 #define INTERNAL_CATCH_ELSE( macroName, resultDisposition, ... ) \
2724 INTERNAL_CATCH_TEST( macroName, resultDisposition, __VA_ARGS__ ); \
2725 if( !Catch::getResultCapture().lastAssertionPassed() )
2726
2727 ///////////////////////////////////////////////////////////////////////////////
2728 #define INTERNAL_CATCH_NO_THROW( macroName, resultDisposition, ... ) \
2729 do { \
2730 Catch::AssertionHandler catchAssertionHandler( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(__VA_ARGS__), resultDisposition ); \
2731 try { \
2732 static_cast<void>(__VA_ARGS__); \
2733 catchAssertionHandler.handleExceptionNotThrownAsExpected(); \
2734 } \
2735 catch( ... ) { \
2736 catchAssertionHandler.handleUnexpectedInflightException(); \
2737 } \
2738 INTERNAL_CATCH_REACT( catchAssertionHandler ) \
2739 } while( false )
2740
2741 ///////////////////////////////////////////////////////////////////////////////
2742 #define INTERNAL_CATCH_THROWS( macroName, resultDisposition, ... ) \
2743 do { \
2744 Catch::AssertionHandler catchAssertionHandler( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(__VA_ARGS__), resultDisposition); \
2745 if( catchAssertionHandler.allowThrows() ) \
2746 try { \
2747 static_cast<void>(__VA_ARGS__); \
2748 catchAssertionHandler.handleUnexpectedExceptionNotThrown(); \
2749 } \
2750 catch( ... ) { \
2751 catchAssertionHandler.handleExceptionThrownAsExpected(); \
2752 } \
2753 else \
2754 catchAssertionHandler.handleThrowingCallSkipped(); \
2755 INTERNAL_CATCH_REACT( catchAssertionHandler ) \
2756 } while( false )
2757
2758 ///////////////////////////////////////////////////////////////////////////////
2759 #define INTERNAL_CATCH_THROWS_AS( macroName, exceptionType, resultDisposition, expr ) \
2760 do { \
2761 Catch::AssertionHandler catchAssertionHandler( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(expr) ", " CATCH_INTERNAL_STRINGIFY(exceptionType), resultDisposition ); \
2762 if( catchAssertionHandler.allowThrows() ) \
2763 try { \
2764 static_cast<void>(expr); \
2765 catchAssertionHandler.handleUnexpectedExceptionNotThrown(); \
2766 } \
2767 catch( exceptionType const& ) { \
2768 catchAssertionHandler.handleExceptionThrownAsExpected(); \
2769 } \
2770 catch( ... ) { \
2771 catchAssertionHandler.handleUnexpectedInflightException(); \
2772 } \
2773 else \
2774 catchAssertionHandler.handleThrowingCallSkipped(); \
2775 INTERNAL_CATCH_REACT( catchAssertionHandler ) \
2776 } while( false )
2777
2778 ///////////////////////////////////////////////////////////////////////////////
2779 #define INTERNAL_CATCH_MSG( macroName, messageType, resultDisposition, ... ) \
2780 do { \
2781 Catch::AssertionHandler catchAssertionHandler( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, Catch::StringRef(), resultDisposition ); \
2782 catchAssertionHandler.handleMessage( messageType, ( Catch::MessageStream() << __VA_ARGS__ + ::Catch::StreamEndStop() ).m_stream.str() ); \
2783 INTERNAL_CATCH_REACT( catchAssertionHandler ) \
2784 } while( false )
2785
2786 ///////////////////////////////////////////////////////////////////////////////
2787 #define INTERNAL_CATCH_CAPTURE( varName, macroName, ... ) \
2788 auto varName = Catch::Capturer( macroName, CATCH_INTERNAL_LINEINFO, Catch::ResultWas::Info, #__VA_ARGS__ ); \
2789 varName.captureValues( 0, __VA_ARGS__ )
2790
2791 ///////////////////////////////////////////////////////////////////////////////
2792 #define INTERNAL_CATCH_INFO( macroName, log ) \
2793 Catch::ScopedMessage INTERNAL_CATCH_UNIQUE_NAME( scopedMessage )( Catch::MessageBuilder( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, Catch::ResultWas::Info ) << log );
2794
2795 ///////////////////////////////////////////////////////////////////////////////
2796 #define INTERNAL_CATCH_UNSCOPED_INFO( macroName, log ) \
2797 Catch::getResultCapture().emplaceUnscopedMessage( Catch::MessageBuilder( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, Catch::ResultWas::Info ) << log )
2798
2799 ///////////////////////////////////////////////////////////////////////////////
2800 // Although this is matcher-based, it can be used with just a string
2801 #define INTERNAL_CATCH_THROWS_STR_MATCHES( macroName, resultDisposition, matcher, ... ) \
2802 do { \
2803 Catch::AssertionHandler catchAssertionHandler( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(__VA_ARGS__) ", " CATCH_INTERNAL_STRINGIFY(matcher), resultDisposition ); \
2804 if( catchAssertionHandler.allowThrows() ) \
2805 try { \
2806 static_cast<void>(__VA_ARGS__); \
2807 catchAssertionHandler.handleUnexpectedExceptionNotThrown(); \
2808 } \
2809 catch( ... ) { \
2810 Catch::handleExceptionMatchExpr( catchAssertionHandler, matcher, #matcher##_catch_sr ); \
2811 } \
2812 else \
2813 catchAssertionHandler.handleThrowingCallSkipped(); \
2814 INTERNAL_CATCH_REACT( catchAssertionHandler ) \
2815 } while( false )
2816
2817 #endif // CATCH_CONFIG_DISABLE
2818
2819 // end catch_capture.hpp
2820 // start catch_section.h
2821
2822 // start catch_section_info.h
2823
2824 // start catch_totals.h
2825
2826 #include <cstddef>
2827
2828 namespace Catch {
2829
2830 struct Counts {
2831 Counts operator - ( Counts const& other ) const;
2832 Counts& operator += ( Counts const& other );
2833
2834 std::size_t total() const;
2835 bool allPassed() const;
2836 bool allOk() const;
2837
2838 std::size_t passed = 0;
2839 std::size_t failed = 0;
2840 std::size_t failedButOk = 0;
2841 };
2842
2843 struct Totals {
2844
2845 Totals operator - ( Totals const& other ) const;
2846 Totals& operator += ( Totals const& other );
2847
2848 Totals delta( Totals const& prevTotals ) const;
2849
2850 int error = 0;
2851 Counts assertions;
2852 Counts testCases;
2853 };
2854 }
2855
2856 // end catch_totals.h
2857 #include <string>
2858
2859 namespace Catch {
2860
2861 struct SectionInfo {
2862 SectionInfo
2863 ( SourceLineInfo const& _lineInfo,
2864 std::string const& _name );
2865
2866 // Deprecated
SectionInfoCatch::SectionInfo2867 SectionInfo
2868 ( SourceLineInfo const& _lineInfo,
2869 std::string const& _name,
2870 std::string const& ) : SectionInfo( _lineInfo, _name ) {}
2871
2872 std::string name;
2873 std::string description; // !Deprecated: this will always be empty
2874 SourceLineInfo lineInfo;
2875 };
2876
2877 struct SectionEndInfo {
2878 SectionInfo sectionInfo;
2879 Counts prevAssertions;
2880 double durationInSeconds;
2881 };
2882
2883 } // end namespace Catch
2884
2885 // end catch_section_info.h
2886 // start catch_timer.h
2887
2888 #include <cstdint>
2889
2890 namespace Catch {
2891
2892 auto getCurrentNanosecondsSinceEpoch() -> uint64_t;
2893 auto getEstimatedClockResolution() -> uint64_t;
2894
2895 class Timer {
2896 uint64_t m_nanoseconds = 0;
2897 public:
2898 void start();
2899 auto getElapsedNanoseconds() const -> uint64_t;
2900 auto getElapsedMicroseconds() const -> uint64_t;
2901 auto getElapsedMilliseconds() const -> unsigned int;
2902 auto getElapsedSeconds() const -> double;
2903 };
2904
2905 } // namespace Catch
2906
2907 // end catch_timer.h
2908 #include <string>
2909
2910 namespace Catch {
2911
2912 class Section : NonCopyable {
2913 public:
2914 Section( SectionInfo const& info );
2915 ~Section();
2916
2917 // This indicates whether the section should be executed or not
2918 explicit operator bool() const;
2919
2920 private:
2921 SectionInfo m_info;
2922
2923 std::string m_name;
2924 Counts m_assertions;
2925 bool m_sectionIncluded;
2926 Timer m_timer;
2927 };
2928
2929 } // end namespace Catch
2930
2931 #define INTERNAL_CATCH_SECTION( ... ) \
2932 CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \
2933 CATCH_INTERNAL_SUPPRESS_UNUSED_WARNINGS \
2934 if( Catch::Section const& INTERNAL_CATCH_UNIQUE_NAME( catch_internal_Section ) = Catch::SectionInfo( CATCH_INTERNAL_LINEINFO, __VA_ARGS__ ) ) \
2935 CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION
2936
2937 #define INTERNAL_CATCH_DYNAMIC_SECTION( ... ) \
2938 CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \
2939 CATCH_INTERNAL_SUPPRESS_UNUSED_WARNINGS \
2940 if( Catch::Section const& INTERNAL_CATCH_UNIQUE_NAME( catch_internal_Section ) = Catch::SectionInfo( CATCH_INTERNAL_LINEINFO, (Catch::ReusableStringStream() << __VA_ARGS__).str() ) ) \
2941 CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION
2942
2943 // end catch_section.h
2944 // start catch_interfaces_exception.h
2945
2946 // start catch_interfaces_registry_hub.h
2947
2948 #include <string>
2949 #include <memory>
2950
2951 namespace Catch {
2952
2953 class TestCase;
2954 struct ITestCaseRegistry;
2955 struct IExceptionTranslatorRegistry;
2956 struct IExceptionTranslator;
2957 struct IReporterRegistry;
2958 struct IReporterFactory;
2959 struct ITagAliasRegistry;
2960 struct IMutableEnumValuesRegistry;
2961
2962 class StartupExceptionRegistry;
2963
2964 using IReporterFactoryPtr = std::shared_ptr<IReporterFactory>;
2965
2966 struct IRegistryHub {
2967 virtual ~IRegistryHub();
2968
2969 virtual IReporterRegistry const& getReporterRegistry() const = 0;
2970 virtual ITestCaseRegistry const& getTestCaseRegistry() const = 0;
2971 virtual ITagAliasRegistry const& getTagAliasRegistry() const = 0;
2972 virtual IExceptionTranslatorRegistry const& getExceptionTranslatorRegistry() const = 0;
2973
2974 virtual StartupExceptionRegistry const& getStartupExceptionRegistry() const = 0;
2975 };
2976
2977 struct IMutableRegistryHub {
2978 virtual ~IMutableRegistryHub();
2979 virtual void registerReporter( std::string const& name, IReporterFactoryPtr const& factory ) = 0;
2980 virtual void registerListener( IReporterFactoryPtr const& factory ) = 0;
2981 virtual void registerTest( TestCase const& testInfo ) = 0;
2982 virtual void registerTranslator( const IExceptionTranslator* translator ) = 0;
2983 virtual void registerTagAlias( std::string const& alias, std::string const& tag, SourceLineInfo const& lineInfo ) = 0;
2984 virtual void registerStartupException() noexcept = 0;
2985 virtual IMutableEnumValuesRegistry& getMutableEnumValuesRegistry() = 0;
2986 };
2987
2988 IRegistryHub const& getRegistryHub();
2989 IMutableRegistryHub& getMutableRegistryHub();
2990 void cleanUp();
2991 std::string translateActiveException();
2992
2993 }
2994
2995 // end catch_interfaces_registry_hub.h
2996 #if defined(CATCH_CONFIG_DISABLE)
2997 #define INTERNAL_CATCH_TRANSLATE_EXCEPTION_NO_REG( translatorName, signature) \
2998 static std::string translatorName( signature )
2999 #endif
3000
3001 #include <exception>
3002 #include <string>
3003 #include <vector>
3004
3005 namespace Catch {
3006 using exceptionTranslateFunction = std::string(*)();
3007
3008 struct IExceptionTranslator;
3009 using ExceptionTranslators = std::vector<std::unique_ptr<IExceptionTranslator const>>;
3010
3011 struct IExceptionTranslator {
3012 virtual ~IExceptionTranslator();
3013 virtual std::string translate( ExceptionTranslators::const_iterator it, ExceptionTranslators::const_iterator itEnd ) const = 0;
3014 };
3015
3016 struct IExceptionTranslatorRegistry {
3017 virtual ~IExceptionTranslatorRegistry();
3018
3019 virtual std::string translateActiveException() const = 0;
3020 };
3021
3022 class ExceptionTranslatorRegistrar {
3023 template<typename T>
3024 class ExceptionTranslator : public IExceptionTranslator {
3025 public:
3026
ExceptionTranslator(std::string (* translateFunction)(T &))3027 ExceptionTranslator( std::string(*translateFunction)( T& ) )
3028 : m_translateFunction( translateFunction )
3029 {}
3030
translate(ExceptionTranslators::const_iterator it,ExceptionTranslators::const_iterator itEnd) const3031 std::string translate( ExceptionTranslators::const_iterator it, ExceptionTranslators::const_iterator itEnd ) const override {
3032 #if defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
3033 return "";
3034 #else
3035 try {
3036 if( it == itEnd )
3037 std::rethrow_exception(std::current_exception());
3038 else
3039 return (*it)->translate( it+1, itEnd );
3040 }
3041 catch( T& ex ) {
3042 return m_translateFunction( ex );
3043 }
3044 #endif
3045 }
3046
3047 protected:
3048 std::string(*m_translateFunction)( T& );
3049 };
3050
3051 public:
3052 template<typename T>
ExceptionTranslatorRegistrar(std::string (* translateFunction)(T &))3053 ExceptionTranslatorRegistrar( std::string(*translateFunction)( T& ) ) {
3054 getMutableRegistryHub().registerTranslator
3055 ( new ExceptionTranslator<T>( translateFunction ) );
3056 }
3057 };
3058 }
3059
3060 ///////////////////////////////////////////////////////////////////////////////
3061 #define INTERNAL_CATCH_TRANSLATE_EXCEPTION2( translatorName, signature ) \
3062 static std::string translatorName( signature ); \
3063 CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \
3064 CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
3065 namespace{ Catch::ExceptionTranslatorRegistrar INTERNAL_CATCH_UNIQUE_NAME( catch_internal_ExceptionRegistrar )( &translatorName ); } \
3066 CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION \
3067 static std::string translatorName( signature )
3068
3069 #define INTERNAL_CATCH_TRANSLATE_EXCEPTION( signature ) INTERNAL_CATCH_TRANSLATE_EXCEPTION2( INTERNAL_CATCH_UNIQUE_NAME( catch_internal_ExceptionTranslator ), signature )
3070
3071 // end catch_interfaces_exception.h
3072 // start catch_approx.h
3073
3074 #include <type_traits>
3075
3076 namespace Catch {
3077 namespace Detail {
3078
3079 class Approx {
3080 private:
3081 bool equalityComparisonImpl(double other) const;
3082 // Validates the new margin (margin >= 0)
3083 // out-of-line to avoid including stdexcept in the header
3084 void setMargin(double margin);
3085 // Validates the new epsilon (0 < epsilon < 1)
3086 // out-of-line to avoid including stdexcept in the header
3087 void setEpsilon(double epsilon);
3088
3089 public:
3090 explicit Approx ( double value );
3091
3092 static Approx custom();
3093
3094 Approx operator-() const;
3095
3096 template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
operator ()(T const & value) const3097 Approx operator()( T const& value ) const {
3098 Approx approx( static_cast<double>(value) );
3099 approx.m_epsilon = m_epsilon;
3100 approx.m_margin = m_margin;
3101 approx.m_scale = m_scale;
3102 return approx;
3103 }
3104
3105 template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
Approx(T const & value)3106 explicit Approx( T const& value ): Approx(static_cast<double>(value))
3107 {}
3108
3109 template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
operator ==(const T & lhs,Approx const & rhs)3110 friend bool operator == ( const T& lhs, Approx const& rhs ) {
3111 auto lhs_v = static_cast<double>(lhs);
3112 return rhs.equalityComparisonImpl(lhs_v);
3113 }
3114
3115 template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
operator ==(Approx const & lhs,const T & rhs)3116 friend bool operator == ( Approx const& lhs, const T& rhs ) {
3117 return operator==( rhs, lhs );
3118 }
3119
3120 template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
operator !=(T const & lhs,Approx const & rhs)3121 friend bool operator != ( T const& lhs, Approx const& rhs ) {
3122 return !operator==( lhs, rhs );
3123 }
3124
3125 template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
operator !=(Approx const & lhs,T const & rhs)3126 friend bool operator != ( Approx const& lhs, T const& rhs ) {
3127 return !operator==( rhs, lhs );
3128 }
3129
3130 template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
operator <=(T const & lhs,Approx const & rhs)3131 friend bool operator <= ( T const& lhs, Approx const& rhs ) {
3132 return static_cast<double>(lhs) < rhs.m_value || lhs == rhs;
3133 }
3134
3135 template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
operator <=(Approx const & lhs,T const & rhs)3136 friend bool operator <= ( Approx const& lhs, T const& rhs ) {
3137 return lhs.m_value < static_cast<double>(rhs) || lhs == rhs;
3138 }
3139
3140 template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
operator >=(T const & lhs,Approx const & rhs)3141 friend bool operator >= ( T const& lhs, Approx const& rhs ) {
3142 return static_cast<double>(lhs) > rhs.m_value || lhs == rhs;
3143 }
3144
3145 template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
operator >=(Approx const & lhs,T const & rhs)3146 friend bool operator >= ( Approx const& lhs, T const& rhs ) {
3147 return lhs.m_value > static_cast<double>(rhs) || lhs == rhs;
3148 }
3149
3150 template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
epsilon(T const & newEpsilon)3151 Approx& epsilon( T const& newEpsilon ) {
3152 double epsilonAsDouble = static_cast<double>(newEpsilon);
3153 setEpsilon(epsilonAsDouble);
3154 return *this;
3155 }
3156
3157 template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
margin(T const & newMargin)3158 Approx& margin( T const& newMargin ) {
3159 double marginAsDouble = static_cast<double>(newMargin);
3160 setMargin(marginAsDouble);
3161 return *this;
3162 }
3163
3164 template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
scale(T const & newScale)3165 Approx& scale( T const& newScale ) {
3166 m_scale = static_cast<double>(newScale);
3167 return *this;
3168 }
3169
3170 std::string toString() const;
3171
3172 private:
3173 double m_epsilon;
3174 double m_margin;
3175 double m_scale;
3176 double m_value;
3177 };
3178 } // end namespace Detail
3179
3180 namespace literals {
3181 Detail::Approx operator "" _a(long double val);
3182 Detail::Approx operator "" _a(unsigned long long val);
3183 } // end namespace literals
3184
3185 template<>
3186 struct StringMaker<Catch::Detail::Approx> {
3187 static std::string convert(Catch::Detail::Approx const& value);
3188 };
3189
3190 } // end namespace Catch
3191
3192 // end catch_approx.h
3193 // start catch_string_manip.h
3194
3195 #include <string>
3196 #include <iosfwd>
3197 #include <vector>
3198
3199 namespace Catch {
3200
3201 bool startsWith( std::string const& s, std::string const& prefix );
3202 bool startsWith( std::string const& s, char prefix );
3203 bool endsWith( std::string const& s, std::string const& suffix );
3204 bool endsWith( std::string const& s, char suffix );
3205 bool contains( std::string const& s, std::string const& infix );
3206 void toLowerInPlace( std::string& s );
3207 std::string toLower( std::string const& s );
3208 //! Returns a new string without whitespace at the start/end
3209 std::string trim( std::string const& str );
3210 //! Returns a substring of the original ref without whitespace. Beware lifetimes!
3211 StringRef trim(StringRef ref);
3212
3213 // !!! Be aware, returns refs into original string - make sure original string outlives them
3214 std::vector<StringRef> splitStringRef( StringRef str, char delimiter );
3215 bool replaceInPlace( std::string& str, std::string const& replaceThis, std::string const& withThis );
3216
3217 struct pluralise {
3218 pluralise( std::size_t count, std::string const& label );
3219
3220 friend std::ostream& operator << ( std::ostream& os, pluralise const& pluraliser );
3221
3222 std::size_t m_count;
3223 std::string m_label;
3224 };
3225 }
3226
3227 // end catch_string_manip.h
3228 #ifndef CATCH_CONFIG_DISABLE_MATCHERS
3229 // start catch_capture_matchers.h
3230
3231 // start catch_matchers.h
3232
3233 #include <string>
3234 #include <vector>
3235
3236 namespace Catch {
3237 namespace Matchers {
3238 namespace Impl {
3239
3240 template<typename ArgT> struct MatchAllOf;
3241 template<typename ArgT> struct MatchAnyOf;
3242 template<typename ArgT> struct MatchNotOf;
3243
3244 class MatcherUntypedBase {
3245 public:
3246 MatcherUntypedBase() = default;
3247 MatcherUntypedBase ( MatcherUntypedBase const& ) = default;
3248 MatcherUntypedBase& operator = ( MatcherUntypedBase const& ) = delete;
3249 std::string toString() const;
3250
3251 protected:
3252 virtual ~MatcherUntypedBase();
3253 virtual std::string describe() const = 0;
3254 mutable std::string m_cachedToString;
3255 };
3256
3257 #ifdef __clang__
3258 # pragma clang diagnostic push
3259 # pragma clang diagnostic ignored "-Wnon-virtual-dtor"
3260 #endif
3261
3262 template<typename ObjectT>
3263 struct MatcherMethod {
3264 virtual bool match( ObjectT const& arg ) const = 0;
3265 };
3266
3267 #if defined(__OBJC__)
3268 // Hack to fix Catch GH issue #1661. Could use id for generic Object support.
3269 // use of const for Object pointers is very uncommon and under ARC it causes some kind of signature mismatch that breaks compilation
3270 template<>
3271 struct MatcherMethod<NSString*> {
3272 virtual bool match( NSString* arg ) const = 0;
3273 };
3274 #endif
3275
3276 #ifdef __clang__
3277 # pragma clang diagnostic pop
3278 #endif
3279
3280 template<typename T>
3281 struct MatcherBase : MatcherUntypedBase, MatcherMethod<T> {
3282
3283 MatchAllOf<T> operator && ( MatcherBase const& other ) const;
3284 MatchAnyOf<T> operator || ( MatcherBase const& other ) const;
3285 MatchNotOf<T> operator ! () const;
3286 };
3287
3288 template<typename ArgT>
3289 struct MatchAllOf : MatcherBase<ArgT> {
matchCatch::Matchers::Impl::MatchAllOf3290 bool match( ArgT const& arg ) const override {
3291 for( auto matcher : m_matchers ) {
3292 if (!matcher->match(arg))
3293 return false;
3294 }
3295 return true;
3296 }
describeCatch::Matchers::Impl::MatchAllOf3297 std::string describe() const override {
3298 std::string description;
3299 description.reserve( 4 + m_matchers.size()*32 );
3300 description += "( ";
3301 bool first = true;
3302 for( auto matcher : m_matchers ) {
3303 if( first )
3304 first = false;
3305 else
3306 description += " and ";
3307 description += matcher->toString();
3308 }
3309 description += " )";
3310 return description;
3311 }
3312
operator &&Catch::Matchers::Impl::MatchAllOf3313 MatchAllOf<ArgT> operator && ( MatcherBase<ArgT> const& other ) {
3314 auto copy(*this);
3315 copy.m_matchers.push_back( &other );
3316 return copy;
3317 }
3318
3319 std::vector<MatcherBase<ArgT> const*> m_matchers;
3320 };
3321 template<typename ArgT>
3322 struct MatchAnyOf : MatcherBase<ArgT> {
3323
matchCatch::Matchers::Impl::MatchAnyOf3324 bool match( ArgT const& arg ) const override {
3325 for( auto matcher : m_matchers ) {
3326 if (matcher->match(arg))
3327 return true;
3328 }
3329 return false;
3330 }
describeCatch::Matchers::Impl::MatchAnyOf3331 std::string describe() const override {
3332 std::string description;
3333 description.reserve( 4 + m_matchers.size()*32 );
3334 description += "( ";
3335 bool first = true;
3336 for( auto matcher : m_matchers ) {
3337 if( first )
3338 first = false;
3339 else
3340 description += " or ";
3341 description += matcher->toString();
3342 }
3343 description += " )";
3344 return description;
3345 }
3346
operator ||Catch::Matchers::Impl::MatchAnyOf3347 MatchAnyOf<ArgT> operator || ( MatcherBase<ArgT> const& other ) {
3348 auto copy(*this);
3349 copy.m_matchers.push_back( &other );
3350 return copy;
3351 }
3352
3353 std::vector<MatcherBase<ArgT> const*> m_matchers;
3354 };
3355
3356 template<typename ArgT>
3357 struct MatchNotOf : MatcherBase<ArgT> {
3358
MatchNotOfCatch::Matchers::Impl::MatchNotOf3359 MatchNotOf( MatcherBase<ArgT> const& underlyingMatcher ) : m_underlyingMatcher( underlyingMatcher ) {}
3360
matchCatch::Matchers::Impl::MatchNotOf3361 bool match( ArgT const& arg ) const override {
3362 return !m_underlyingMatcher.match( arg );
3363 }
3364
describeCatch::Matchers::Impl::MatchNotOf3365 std::string describe() const override {
3366 return "not " + m_underlyingMatcher.toString();
3367 }
3368 MatcherBase<ArgT> const& m_underlyingMatcher;
3369 };
3370
3371 template<typename T>
operator &&(MatcherBase const & other) const3372 MatchAllOf<T> MatcherBase<T>::operator && ( MatcherBase const& other ) const {
3373 return MatchAllOf<T>() && *this && other;
3374 }
3375 template<typename T>
operator ||(MatcherBase const & other) const3376 MatchAnyOf<T> MatcherBase<T>::operator || ( MatcherBase const& other ) const {
3377 return MatchAnyOf<T>() || *this || other;
3378 }
3379 template<typename T>
operator !() const3380 MatchNotOf<T> MatcherBase<T>::operator ! () const {
3381 return MatchNotOf<T>( *this );
3382 }
3383
3384 } // namespace Impl
3385
3386 } // namespace Matchers
3387
3388 using namespace Matchers;
3389 using Matchers::Impl::MatcherBase;
3390
3391 } // namespace Catch
3392
3393 // end catch_matchers.h
3394 // start catch_matchers_exception.hpp
3395
3396 namespace Catch {
3397 namespace Matchers {
3398 namespace Exception {
3399
3400 class ExceptionMessageMatcher : public MatcherBase<std::exception> {
3401 std::string m_message;
3402 public:
3403
ExceptionMessageMatcher(std::string const & message)3404 ExceptionMessageMatcher(std::string const& message):
3405 m_message(message)
3406 {}
3407
3408 bool match(std::exception const& ex) const override;
3409
3410 std::string describe() const override;
3411 };
3412
3413 } // namespace Exception
3414
3415 Exception::ExceptionMessageMatcher Message(std::string const& message);
3416
3417 } // namespace Matchers
3418 } // namespace Catch
3419
3420 // end catch_matchers_exception.hpp
3421 // start catch_matchers_floating.h
3422
3423 namespace Catch {
3424 namespace Matchers {
3425
3426 namespace Floating {
3427
3428 enum class FloatingPointKind : uint8_t;
3429
3430 struct WithinAbsMatcher : MatcherBase<double> {
3431 WithinAbsMatcher(double target, double margin);
3432 bool match(double const& matchee) const override;
3433 std::string describe() const override;
3434 private:
3435 double m_target;
3436 double m_margin;
3437 };
3438
3439 struct WithinUlpsMatcher : MatcherBase<double> {
3440 WithinUlpsMatcher(double target, uint64_t ulps, FloatingPointKind baseType);
3441 bool match(double const& matchee) const override;
3442 std::string describe() const override;
3443 private:
3444 double m_target;
3445 uint64_t m_ulps;
3446 FloatingPointKind m_type;
3447 };
3448
3449 // Given IEEE-754 format for floats and doubles, we can assume
3450 // that float -> double promotion is lossless. Given this, we can
3451 // assume that if we do the standard relative comparison of
3452 // |lhs - rhs| <= epsilon * max(fabs(lhs), fabs(rhs)), then we get
3453 // the same result if we do this for floats, as if we do this for
3454 // doubles that were promoted from floats.
3455 struct WithinRelMatcher : MatcherBase<double> {
3456 WithinRelMatcher(double target, double epsilon);
3457 bool match(double const& matchee) const override;
3458 std::string describe() const override;
3459 private:
3460 double m_target;
3461 double m_epsilon;
3462 };
3463
3464 } // namespace Floating
3465
3466 // The following functions create the actual matcher objects.
3467 // This allows the types to be inferred
3468 Floating::WithinUlpsMatcher WithinULP(double target, uint64_t maxUlpDiff);
3469 Floating::WithinUlpsMatcher WithinULP(float target, uint64_t maxUlpDiff);
3470 Floating::WithinAbsMatcher WithinAbs(double target, double margin);
3471 Floating::WithinRelMatcher WithinRel(double target, double eps);
3472 // defaults epsilon to 100*numeric_limits<double>::epsilon()
3473 Floating::WithinRelMatcher WithinRel(double target);
3474 Floating::WithinRelMatcher WithinRel(float target, float eps);
3475 // defaults epsilon to 100*numeric_limits<float>::epsilon()
3476 Floating::WithinRelMatcher WithinRel(float target);
3477
3478 } // namespace Matchers
3479 } // namespace Catch
3480
3481 // end catch_matchers_floating.h
3482 // start catch_matchers_generic.hpp
3483
3484 #include <functional>
3485 #include <string>
3486
3487 namespace Catch {
3488 namespace Matchers {
3489 namespace Generic {
3490
3491 namespace Detail {
3492 std::string finalizeDescription(const std::string& desc);
3493 }
3494
3495 template <typename T>
3496 class PredicateMatcher : public MatcherBase<T> {
3497 std::function<bool(T const&)> m_predicate;
3498 std::string m_description;
3499 public:
3500
PredicateMatcher(std::function<bool (T const &)> const & elem,std::string const & descr)3501 PredicateMatcher(std::function<bool(T const&)> const& elem, std::string const& descr)
3502 :m_predicate(std::move(elem)),
3503 m_description(Detail::finalizeDescription(descr))
3504 {}
3505
match(T const & item) const3506 bool match( T const& item ) const override {
3507 return m_predicate(item);
3508 }
3509
describe() const3510 std::string describe() const override {
3511 return m_description;
3512 }
3513 };
3514
3515 } // namespace Generic
3516
3517 // The following functions create the actual matcher objects.
3518 // The user has to explicitly specify type to the function, because
3519 // inferring std::function<bool(T const&)> is hard (but possible) and
3520 // requires a lot of TMP.
3521 template<typename T>
Predicate(std::function<bool (T const &)> const & predicate,std::string const & description="")3522 Generic::PredicateMatcher<T> Predicate(std::function<bool(T const&)> const& predicate, std::string const& description = "") {
3523 return Generic::PredicateMatcher<T>(predicate, description);
3524 }
3525
3526 } // namespace Matchers
3527 } // namespace Catch
3528
3529 // end catch_matchers_generic.hpp
3530 // start catch_matchers_string.h
3531
3532 #include <string>
3533
3534 namespace Catch {
3535 namespace Matchers {
3536
3537 namespace StdString {
3538
3539 struct CasedString
3540 {
3541 CasedString( std::string const& str, CaseSensitive::Choice caseSensitivity );
3542 std::string adjustString( std::string const& str ) const;
3543 std::string caseSensitivitySuffix() const;
3544
3545 CaseSensitive::Choice m_caseSensitivity;
3546 std::string m_str;
3547 };
3548
3549 struct StringMatcherBase : MatcherBase<std::string> {
3550 StringMatcherBase( std::string const& operation, CasedString const& comparator );
3551 std::string describe() const override;
3552
3553 CasedString m_comparator;
3554 std::string m_operation;
3555 };
3556
3557 struct EqualsMatcher : StringMatcherBase {
3558 EqualsMatcher( CasedString const& comparator );
3559 bool match( std::string const& source ) const override;
3560 };
3561 struct ContainsMatcher : StringMatcherBase {
3562 ContainsMatcher( CasedString const& comparator );
3563 bool match( std::string const& source ) const override;
3564 };
3565 struct StartsWithMatcher : StringMatcherBase {
3566 StartsWithMatcher( CasedString const& comparator );
3567 bool match( std::string const& source ) const override;
3568 };
3569 struct EndsWithMatcher : StringMatcherBase {
3570 EndsWithMatcher( CasedString const& comparator );
3571 bool match( std::string const& source ) const override;
3572 };
3573
3574 struct RegexMatcher : MatcherBase<std::string> {
3575 RegexMatcher( std::string regex, CaseSensitive::Choice caseSensitivity );
3576 bool match( std::string const& matchee ) const override;
3577 std::string describe() const override;
3578
3579 private:
3580 std::string m_regex;
3581 CaseSensitive::Choice m_caseSensitivity;
3582 };
3583
3584 } // namespace StdString
3585
3586 // The following functions create the actual matcher objects.
3587 // This allows the types to be inferred
3588
3589 StdString::EqualsMatcher Equals( std::string const& str, CaseSensitive::Choice caseSensitivity = CaseSensitive::Yes );
3590 StdString::ContainsMatcher Contains( std::string const& str, CaseSensitive::Choice caseSensitivity = CaseSensitive::Yes );
3591 StdString::EndsWithMatcher EndsWith( std::string const& str, CaseSensitive::Choice caseSensitivity = CaseSensitive::Yes );
3592 StdString::StartsWithMatcher StartsWith( std::string const& str, CaseSensitive::Choice caseSensitivity = CaseSensitive::Yes );
3593 StdString::RegexMatcher Matches( std::string const& regex, CaseSensitive::Choice caseSensitivity = CaseSensitive::Yes );
3594
3595 } // namespace Matchers
3596 } // namespace Catch
3597
3598 // end catch_matchers_string.h
3599 // start catch_matchers_vector.h
3600
3601 #include <algorithm>
3602
3603 namespace Catch {
3604 namespace Matchers {
3605
3606 namespace Vector {
3607 template<typename T, typename Alloc>
3608 struct ContainsElementMatcher : MatcherBase<std::vector<T, Alloc>> {
3609
ContainsElementMatcherCatch::Matchers::Vector::ContainsElementMatcher3610 ContainsElementMatcher(T const &comparator) : m_comparator( comparator) {}
3611
matchCatch::Matchers::Vector::ContainsElementMatcher3612 bool match(std::vector<T, Alloc> const &v) const override {
3613 for (auto const& el : v) {
3614 if (el == m_comparator) {
3615 return true;
3616 }
3617 }
3618 return false;
3619 }
3620
describeCatch::Matchers::Vector::ContainsElementMatcher3621 std::string describe() const override {
3622 return "Contains: " + ::Catch::Detail::stringify( m_comparator );
3623 }
3624
3625 T const& m_comparator;
3626 };
3627
3628 template<typename T, typename AllocComp, typename AllocMatch>
3629 struct ContainsMatcher : MatcherBase<std::vector<T, AllocMatch>> {
3630
ContainsMatcherCatch::Matchers::Vector::ContainsMatcher3631 ContainsMatcher(std::vector<T, AllocComp> const &comparator) : m_comparator( comparator ) {}
3632
matchCatch::Matchers::Vector::ContainsMatcher3633 bool match(std::vector<T, AllocMatch> const &v) const override {
3634 // !TBD: see note in EqualsMatcher
3635 if (m_comparator.size() > v.size())
3636 return false;
3637 for (auto const& comparator : m_comparator) {
3638 auto present = false;
3639 for (const auto& el : v) {
3640 if (el == comparator) {
3641 present = true;
3642 break;
3643 }
3644 }
3645 if (!present) {
3646 return false;
3647 }
3648 }
3649 return true;
3650 }
describeCatch::Matchers::Vector::ContainsMatcher3651 std::string describe() const override {
3652 return "Contains: " + ::Catch::Detail::stringify( m_comparator );
3653 }
3654
3655 std::vector<T, AllocComp> const& m_comparator;
3656 };
3657
3658 template<typename T, typename AllocComp, typename AllocMatch>
3659 struct EqualsMatcher : MatcherBase<std::vector<T, AllocMatch>> {
3660
EqualsMatcherCatch::Matchers::Vector::EqualsMatcher3661 EqualsMatcher(std::vector<T, AllocComp> const &comparator) : m_comparator( comparator ) {}
3662
matchCatch::Matchers::Vector::EqualsMatcher3663 bool match(std::vector<T, AllocMatch> const &v) const override {
3664 // !TBD: This currently works if all elements can be compared using !=
3665 // - a more general approach would be via a compare template that defaults
3666 // to using !=. but could be specialised for, e.g. std::vector<T, Alloc> etc
3667 // - then just call that directly
3668 if (m_comparator.size() != v.size())
3669 return false;
3670 for (std::size_t i = 0; i < v.size(); ++i)
3671 if (m_comparator[i] != v[i])
3672 return false;
3673 return true;
3674 }
describeCatch::Matchers::Vector::EqualsMatcher3675 std::string describe() const override {
3676 return "Equals: " + ::Catch::Detail::stringify( m_comparator );
3677 }
3678 std::vector<T, AllocComp> const& m_comparator;
3679 };
3680
3681 template<typename T, typename AllocComp, typename AllocMatch>
3682 struct ApproxMatcher : MatcherBase<std::vector<T, AllocMatch>> {
3683
ApproxMatcherCatch::Matchers::Vector::ApproxMatcher3684 ApproxMatcher(std::vector<T, AllocComp> const& comparator) : m_comparator( comparator ) {}
3685
matchCatch::Matchers::Vector::ApproxMatcher3686 bool match(std::vector<T, AllocMatch> const &v) const override {
3687 if (m_comparator.size() != v.size())
3688 return false;
3689 for (std::size_t i = 0; i < v.size(); ++i)
3690 if (m_comparator[i] != approx(v[i]))
3691 return false;
3692 return true;
3693 }
describeCatch::Matchers::Vector::ApproxMatcher3694 std::string describe() const override {
3695 return "is approx: " + ::Catch::Detail::stringify( m_comparator );
3696 }
3697 template <typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
epsilonCatch::Matchers::Vector::ApproxMatcher3698 ApproxMatcher& epsilon( T const& newEpsilon ) {
3699 approx.epsilon(newEpsilon);
3700 return *this;
3701 }
3702 template <typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
marginCatch::Matchers::Vector::ApproxMatcher3703 ApproxMatcher& margin( T const& newMargin ) {
3704 approx.margin(newMargin);
3705 return *this;
3706 }
3707 template <typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
scaleCatch::Matchers::Vector::ApproxMatcher3708 ApproxMatcher& scale( T const& newScale ) {
3709 approx.scale(newScale);
3710 return *this;
3711 }
3712
3713 std::vector<T, AllocComp> const& m_comparator;
3714 mutable Catch::Detail::Approx approx = Catch::Detail::Approx::custom();
3715 };
3716
3717 template<typename T, typename AllocComp, typename AllocMatch>
3718 struct UnorderedEqualsMatcher : MatcherBase<std::vector<T, AllocMatch>> {
UnorderedEqualsMatcherCatch::Matchers::Vector::UnorderedEqualsMatcher3719 UnorderedEqualsMatcher(std::vector<T, AllocComp> const& target) : m_target(target) {}
matchCatch::Matchers::Vector::UnorderedEqualsMatcher3720 bool match(std::vector<T, AllocMatch> const& vec) const override {
3721 if (m_target.size() != vec.size()) {
3722 return false;
3723 }
3724 return std::is_permutation(m_target.begin(), m_target.end(), vec.begin());
3725 }
3726
describeCatch::Matchers::Vector::UnorderedEqualsMatcher3727 std::string describe() const override {
3728 return "UnorderedEquals: " + ::Catch::Detail::stringify(m_target);
3729 }
3730 private:
3731 std::vector<T, AllocComp> const& m_target;
3732 };
3733
3734 } // namespace Vector
3735
3736 // The following functions create the actual matcher objects.
3737 // This allows the types to be inferred
3738
3739 template<typename T, typename AllocComp = std::allocator<T>, typename AllocMatch = AllocComp>
Contains(std::vector<T,AllocComp> const & comparator)3740 Vector::ContainsMatcher<T, AllocComp, AllocMatch> Contains( std::vector<T, AllocComp> const& comparator ) {
3741 return Vector::ContainsMatcher<T, AllocComp, AllocMatch>( comparator );
3742 }
3743
3744 template<typename T, typename Alloc = std::allocator<T>>
VectorContains(T const & comparator)3745 Vector::ContainsElementMatcher<T, Alloc> VectorContains( T const& comparator ) {
3746 return Vector::ContainsElementMatcher<T, Alloc>( comparator );
3747 }
3748
3749 template<typename T, typename AllocComp = std::allocator<T>, typename AllocMatch = AllocComp>
Equals(std::vector<T,AllocComp> const & comparator)3750 Vector::EqualsMatcher<T, AllocComp, AllocMatch> Equals( std::vector<T, AllocComp> const& comparator ) {
3751 return Vector::EqualsMatcher<T, AllocComp, AllocMatch>( comparator );
3752 }
3753
3754 template<typename T, typename AllocComp = std::allocator<T>, typename AllocMatch = AllocComp>
Approx(std::vector<T,AllocComp> const & comparator)3755 Vector::ApproxMatcher<T, AllocComp, AllocMatch> Approx( std::vector<T, AllocComp> const& comparator ) {
3756 return Vector::ApproxMatcher<T, AllocComp, AllocMatch>( comparator );
3757 }
3758
3759 template<typename T, typename AllocComp = std::allocator<T>, typename AllocMatch = AllocComp>
UnorderedEquals(std::vector<T,AllocComp> const & target)3760 Vector::UnorderedEqualsMatcher<T, AllocComp, AllocMatch> UnorderedEquals(std::vector<T, AllocComp> const& target) {
3761 return Vector::UnorderedEqualsMatcher<T, AllocComp, AllocMatch>( target );
3762 }
3763
3764 } // namespace Matchers
3765 } // namespace Catch
3766
3767 // end catch_matchers_vector.h
3768 namespace Catch {
3769
3770 template<typename ArgT, typename MatcherT>
3771 class MatchExpr : public ITransientExpression {
3772 ArgT const& m_arg;
3773 MatcherT m_matcher;
3774 StringRef m_matcherString;
3775 public:
MatchExpr(ArgT const & arg,MatcherT const & matcher,StringRef const & matcherString)3776 MatchExpr( ArgT const& arg, MatcherT const& matcher, StringRef const& matcherString )
3777 : ITransientExpression{ true, matcher.match( arg ) },
3778 m_arg( arg ),
3779 m_matcher( matcher ),
3780 m_matcherString( matcherString )
3781 {}
3782
streamReconstructedExpression(std::ostream & os) const3783 void streamReconstructedExpression( std::ostream &os ) const override {
3784 auto matcherAsString = m_matcher.toString();
3785 os << Catch::Detail::stringify( m_arg ) << ' ';
3786 if( matcherAsString == Detail::unprintableString )
3787 os << m_matcherString;
3788 else
3789 os << matcherAsString;
3790 }
3791 };
3792
3793 using StringMatcher = Matchers::Impl::MatcherBase<std::string>;
3794
3795 void handleExceptionMatchExpr( AssertionHandler& handler, StringMatcher const& matcher, StringRef const& matcherString );
3796
3797 template<typename ArgT, typename MatcherT>
makeMatchExpr(ArgT const & arg,MatcherT const & matcher,StringRef const & matcherString)3798 auto makeMatchExpr( ArgT const& arg, MatcherT const& matcher, StringRef const& matcherString ) -> MatchExpr<ArgT, MatcherT> {
3799 return MatchExpr<ArgT, MatcherT>( arg, matcher, matcherString );
3800 }
3801
3802 } // namespace Catch
3803
3804 ///////////////////////////////////////////////////////////////////////////////
3805 #define INTERNAL_CHECK_THAT( macroName, matcher, resultDisposition, arg ) \
3806 do { \
3807 Catch::AssertionHandler catchAssertionHandler( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(arg) ", " CATCH_INTERNAL_STRINGIFY(matcher), resultDisposition ); \
3808 INTERNAL_CATCH_TRY { \
3809 catchAssertionHandler.handleExpr( Catch::makeMatchExpr( arg, matcher, #matcher##_catch_sr ) ); \
3810 } INTERNAL_CATCH_CATCH( catchAssertionHandler ) \
3811 INTERNAL_CATCH_REACT( catchAssertionHandler ) \
3812 } while( false )
3813
3814 ///////////////////////////////////////////////////////////////////////////////
3815 #define INTERNAL_CATCH_THROWS_MATCHES( macroName, exceptionType, resultDisposition, matcher, ... ) \
3816 do { \
3817 Catch::AssertionHandler catchAssertionHandler( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(__VA_ARGS__) ", " CATCH_INTERNAL_STRINGIFY(exceptionType) ", " CATCH_INTERNAL_STRINGIFY(matcher), resultDisposition ); \
3818 if( catchAssertionHandler.allowThrows() ) \
3819 try { \
3820 static_cast<void>(__VA_ARGS__ ); \
3821 catchAssertionHandler.handleUnexpectedExceptionNotThrown(); \
3822 } \
3823 catch( exceptionType const& ex ) { \
3824 catchAssertionHandler.handleExpr( Catch::makeMatchExpr( ex, matcher, #matcher##_catch_sr ) ); \
3825 } \
3826 catch( ... ) { \
3827 catchAssertionHandler.handleUnexpectedInflightException(); \
3828 } \
3829 else \
3830 catchAssertionHandler.handleThrowingCallSkipped(); \
3831 INTERNAL_CATCH_REACT( catchAssertionHandler ) \
3832 } while( false )
3833
3834 // end catch_capture_matchers.h
3835 #endif
3836 // start catch_generators.hpp
3837
3838 // start catch_interfaces_generatortracker.h
3839
3840
3841 #include <memory>
3842
3843 namespace Catch {
3844
3845 namespace Generators {
3846 class GeneratorUntypedBase {
3847 public:
3848 GeneratorUntypedBase() = default;
3849 virtual ~GeneratorUntypedBase();
3850 // Attempts to move the generator to the next element
3851 //
3852 // Returns true iff the move succeeded (and a valid element
3853 // can be retrieved).
3854 virtual bool next() = 0;
3855 };
3856 using GeneratorBasePtr = std::unique_ptr<GeneratorUntypedBase>;
3857
3858 } // namespace Generators
3859
3860 struct IGeneratorTracker {
3861 virtual ~IGeneratorTracker();
3862 virtual auto hasGenerator() const -> bool = 0;
3863 virtual auto getGenerator() const -> Generators::GeneratorBasePtr const& = 0;
3864 virtual void setGenerator( Generators::GeneratorBasePtr&& generator ) = 0;
3865 };
3866
3867 } // namespace Catch
3868
3869 // end catch_interfaces_generatortracker.h
3870 // start catch_enforce.h
3871
3872 #include <exception>
3873
3874 namespace Catch {
3875 #if !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
3876 template <typename Ex>
3877 [[noreturn]]
throw_exception(Ex const & e)3878 void throw_exception(Ex const& e) {
3879 throw e;
3880 }
3881 #else // ^^ Exceptions are enabled // Exceptions are disabled vv
3882 [[noreturn]]
3883 void throw_exception(std::exception const& e);
3884 #endif
3885
3886 [[noreturn]]
3887 void throw_logic_error(std::string const& msg);
3888 [[noreturn]]
3889 void throw_domain_error(std::string const& msg);
3890 [[noreturn]]
3891 void throw_runtime_error(std::string const& msg);
3892
3893 } // namespace Catch;
3894
3895 #define CATCH_MAKE_MSG(...) \
3896 (Catch::ReusableStringStream() << __VA_ARGS__).str()
3897
3898 #define CATCH_INTERNAL_ERROR(...) \
3899 Catch::throw_logic_error(CATCH_MAKE_MSG( CATCH_INTERNAL_LINEINFO << ": Internal Catch2 error: " << __VA_ARGS__))
3900
3901 #define CATCH_ERROR(...) \
3902 Catch::throw_domain_error(CATCH_MAKE_MSG( __VA_ARGS__ ))
3903
3904 #define CATCH_RUNTIME_ERROR(...) \
3905 Catch::throw_runtime_error(CATCH_MAKE_MSG( __VA_ARGS__ ))
3906
3907 #define CATCH_ENFORCE( condition, ... ) \
3908 do{ if( !(condition) ) CATCH_ERROR( __VA_ARGS__ ); } while(false)
3909
3910 // end catch_enforce.h
3911 #include <memory>
3912 #include <vector>
3913 #include <cassert>
3914
3915 #include <utility>
3916 #include <exception>
3917
3918 namespace Catch {
3919
3920 class GeneratorException : public std::exception {
3921 const char* const m_msg = "";
3922
3923 public:
GeneratorException(const char * msg)3924 GeneratorException(const char* msg):
3925 m_msg(msg)
3926 {}
3927
3928 const char* what() const noexcept override final;
3929 };
3930
3931 namespace Generators {
3932
3933 // !TBD move this into its own location?
3934 namespace pf{
3935 template<typename T, typename... Args>
make_unique(Args &&...args)3936 std::unique_ptr<T> make_unique( Args&&... args ) {
3937 return std::unique_ptr<T>(new T(std::forward<Args>(args)...));
3938 }
3939 }
3940
3941 template<typename T>
3942 struct IGenerator : GeneratorUntypedBase {
3943 virtual ~IGenerator() = default;
3944
3945 // Returns the current element of the generator
3946 //
3947 // \Precondition The generator is either freshly constructed,
3948 // or the last call to `next()` returned true
3949 virtual T const& get() const = 0;
3950 using type = T;
3951 };
3952
3953 template<typename T>
3954 class SingleValueGenerator final : public IGenerator<T> {
3955 T m_value;
3956 public:
SingleValueGenerator(T && value)3957 SingleValueGenerator(T&& value) : m_value(std::move(value)) {}
3958
get() const3959 T const& get() const override {
3960 return m_value;
3961 }
next()3962 bool next() override {
3963 return false;
3964 }
3965 };
3966
3967 template<typename T>
3968 class FixedValuesGenerator final : public IGenerator<T> {
3969 static_assert(!std::is_same<T, bool>::value,
3970 "FixedValuesGenerator does not support bools because of std::vector<bool>"
3971 "specialization, use SingleValue Generator instead.");
3972 std::vector<T> m_values;
3973 size_t m_idx = 0;
3974 public:
FixedValuesGenerator(std::initializer_list<T> values)3975 FixedValuesGenerator( std::initializer_list<T> values ) : m_values( values ) {}
3976
get() const3977 T const& get() const override {
3978 return m_values[m_idx];
3979 }
next()3980 bool next() override {
3981 ++m_idx;
3982 return m_idx < m_values.size();
3983 }
3984 };
3985
3986 template <typename T>
3987 class GeneratorWrapper final {
3988 std::unique_ptr<IGenerator<T>> m_generator;
3989 public:
GeneratorWrapper(std::unique_ptr<IGenerator<T>> generator)3990 GeneratorWrapper(std::unique_ptr<IGenerator<T>> generator):
3991 m_generator(std::move(generator))
3992 {}
get() const3993 T const& get() const {
3994 return m_generator->get();
3995 }
next()3996 bool next() {
3997 return m_generator->next();
3998 }
3999 };
4000
4001 template <typename T>
value(T && value)4002 GeneratorWrapper<T> value(T&& value) {
4003 return GeneratorWrapper<T>(pf::make_unique<SingleValueGenerator<T>>(std::forward<T>(value)));
4004 }
4005 template <typename T>
values(std::initializer_list<T> values)4006 GeneratorWrapper<T> values(std::initializer_list<T> values) {
4007 return GeneratorWrapper<T>(pf::make_unique<FixedValuesGenerator<T>>(values));
4008 }
4009
4010 template<typename T>
4011 class Generators : public IGenerator<T> {
4012 std::vector<GeneratorWrapper<T>> m_generators;
4013 size_t m_current = 0;
4014
populate(GeneratorWrapper<T> && generator)4015 void populate(GeneratorWrapper<T>&& generator) {
4016 m_generators.emplace_back(std::move(generator));
4017 }
populate(T && val)4018 void populate(T&& val) {
4019 m_generators.emplace_back(value(std::forward<T>(val)));
4020 }
4021 template<typename U>
populate(U && val)4022 void populate(U&& val) {
4023 populate(T(std::forward<U>(val)));
4024 }
4025 template<typename U, typename... Gs>
populate(U && valueOrGenerator,Gs &&...moreGenerators)4026 void populate(U&& valueOrGenerator, Gs &&... moreGenerators) {
4027 populate(std::forward<U>(valueOrGenerator));
4028 populate(std::forward<Gs>(moreGenerators)...);
4029 }
4030
4031 public:
4032 template <typename... Gs>
Generators(Gs &&...moreGenerators)4033 Generators(Gs &&... moreGenerators) {
4034 m_generators.reserve(sizeof...(Gs));
4035 populate(std::forward<Gs>(moreGenerators)...);
4036 }
4037
get() const4038 T const& get() const override {
4039 return m_generators[m_current].get();
4040 }
4041
next()4042 bool next() override {
4043 if (m_current >= m_generators.size()) {
4044 return false;
4045 }
4046 const bool current_status = m_generators[m_current].next();
4047 if (!current_status) {
4048 ++m_current;
4049 }
4050 return m_current < m_generators.size();
4051 }
4052 };
4053
4054 template<typename... Ts>
table(std::initializer_list<std::tuple<typename std::decay<Ts>::type...>> tuples)4055 GeneratorWrapper<std::tuple<Ts...>> table( std::initializer_list<std::tuple<typename std::decay<Ts>::type...>> tuples ) {
4056 return values<std::tuple<Ts...>>( tuples );
4057 }
4058
4059 // Tag type to signal that a generator sequence should convert arguments to a specific type
4060 template <typename T>
4061 struct as {};
4062
4063 template<typename T, typename... Gs>
makeGenerators(GeneratorWrapper<T> && generator,Gs &&...moreGenerators)4064 auto makeGenerators( GeneratorWrapper<T>&& generator, Gs &&... moreGenerators ) -> Generators<T> {
4065 return Generators<T>(std::move(generator), std::forward<Gs>(moreGenerators)...);
4066 }
4067 template<typename T>
makeGenerators(GeneratorWrapper<T> && generator)4068 auto makeGenerators( GeneratorWrapper<T>&& generator ) -> Generators<T> {
4069 return Generators<T>(std::move(generator));
4070 }
4071 template<typename T, typename... Gs>
makeGenerators(T && val,Gs &&...moreGenerators)4072 auto makeGenerators( T&& val, Gs &&... moreGenerators ) -> Generators<T> {
4073 return makeGenerators( value( std::forward<T>( val ) ), std::forward<Gs>( moreGenerators )... );
4074 }
4075 template<typename T, typename U, typename... Gs>
makeGenerators(as<T>,U && val,Gs &&...moreGenerators)4076 auto makeGenerators( as<T>, U&& val, Gs &&... moreGenerators ) -> Generators<T> {
4077 return makeGenerators( value( T( std::forward<U>( val ) ) ), std::forward<Gs>( moreGenerators )... );
4078 }
4079
4080 auto acquireGeneratorTracker( StringRef generatorName, SourceLineInfo const& lineInfo ) -> IGeneratorTracker&;
4081
4082 template<typename L>
4083 // Note: The type after -> is weird, because VS2015 cannot parse
4084 // the expression used in the typedef inside, when it is in
4085 // return type. Yeah.
generate(StringRef generatorName,SourceLineInfo const & lineInfo,L const & generatorExpression)4086 auto generate( StringRef generatorName, SourceLineInfo const& lineInfo, L const& generatorExpression ) -> decltype(std::declval<decltype(generatorExpression())>().get()) {
4087 using UnderlyingType = typename decltype(generatorExpression())::type;
4088
4089 IGeneratorTracker& tracker = acquireGeneratorTracker( generatorName, lineInfo );
4090 if (!tracker.hasGenerator()) {
4091 tracker.setGenerator(pf::make_unique<Generators<UnderlyingType>>(generatorExpression()));
4092 }
4093
4094 auto const& generator = static_cast<IGenerator<UnderlyingType> const&>( *tracker.getGenerator() );
4095 return generator.get();
4096 }
4097
4098 } // namespace Generators
4099 } // namespace Catch
4100
4101 #define GENERATE( ... ) \
4102 Catch::Generators::generate( INTERNAL_CATCH_STRINGIZE(INTERNAL_CATCH_UNIQUE_NAME(generator)), \
4103 CATCH_INTERNAL_LINEINFO, \
4104 [ ]{ using namespace Catch::Generators; return makeGenerators( __VA_ARGS__ ); } ) //NOLINT(google-build-using-namespace)
4105 #define GENERATE_COPY( ... ) \
4106 Catch::Generators::generate( INTERNAL_CATCH_STRINGIZE(INTERNAL_CATCH_UNIQUE_NAME(generator)), \
4107 CATCH_INTERNAL_LINEINFO, \
4108 [=]{ using namespace Catch::Generators; return makeGenerators( __VA_ARGS__ ); } ) //NOLINT(google-build-using-namespace)
4109 #define GENERATE_REF( ... ) \
4110 Catch::Generators::generate( INTERNAL_CATCH_STRINGIZE(INTERNAL_CATCH_UNIQUE_NAME(generator)), \
4111 CATCH_INTERNAL_LINEINFO, \
4112 [&]{ using namespace Catch::Generators; return makeGenerators( __VA_ARGS__ ); } ) //NOLINT(google-build-using-namespace)
4113
4114 // end catch_generators.hpp
4115 // start catch_generators_generic.hpp
4116
4117 namespace Catch {
4118 namespace Generators {
4119
4120 template <typename T>
4121 class TakeGenerator : public IGenerator<T> {
4122 GeneratorWrapper<T> m_generator;
4123 size_t m_returned = 0;
4124 size_t m_target;
4125 public:
TakeGenerator(size_t target,GeneratorWrapper<T> && generator)4126 TakeGenerator(size_t target, GeneratorWrapper<T>&& generator):
4127 m_generator(std::move(generator)),
4128 m_target(target)
4129 {
4130 assert(target != 0 && "Empty generators are not allowed");
4131 }
get() const4132 T const& get() const override {
4133 return m_generator.get();
4134 }
next()4135 bool next() override {
4136 ++m_returned;
4137 if (m_returned >= m_target) {
4138 return false;
4139 }
4140
4141 const auto success = m_generator.next();
4142 // If the underlying generator does not contain enough values
4143 // then we cut short as well
4144 if (!success) {
4145 m_returned = m_target;
4146 }
4147 return success;
4148 }
4149 };
4150
4151 template <typename T>
take(size_t target,GeneratorWrapper<T> && generator)4152 GeneratorWrapper<T> take(size_t target, GeneratorWrapper<T>&& generator) {
4153 return GeneratorWrapper<T>(pf::make_unique<TakeGenerator<T>>(target, std::move(generator)));
4154 }
4155
4156 template <typename T, typename Predicate>
4157 class FilterGenerator : public IGenerator<T> {
4158 GeneratorWrapper<T> m_generator;
4159 Predicate m_predicate;
4160 public:
4161 template <typename P = Predicate>
FilterGenerator(P && pred,GeneratorWrapper<T> && generator)4162 FilterGenerator(P&& pred, GeneratorWrapper<T>&& generator):
4163 m_generator(std::move(generator)),
4164 m_predicate(std::forward<P>(pred))
4165 {
4166 if (!m_predicate(m_generator.get())) {
4167 // It might happen that there are no values that pass the
4168 // filter. In that case we throw an exception.
4169 auto has_initial_value = nextImpl();
4170 if (!has_initial_value) {
4171 Catch::throw_exception(GeneratorException("No valid value found in filtered generator"));
4172 }
4173 }
4174 }
4175
get() const4176 T const& get() const override {
4177 return m_generator.get();
4178 }
4179
next()4180 bool next() override {
4181 return nextImpl();
4182 }
4183
4184 private:
nextImpl()4185 bool nextImpl() {
4186 bool success = m_generator.next();
4187 if (!success) {
4188 return false;
4189 }
4190 while (!m_predicate(m_generator.get()) && (success = m_generator.next()) == true);
4191 return success;
4192 }
4193 };
4194
4195 template <typename T, typename Predicate>
filter(Predicate && pred,GeneratorWrapper<T> && generator)4196 GeneratorWrapper<T> filter(Predicate&& pred, GeneratorWrapper<T>&& generator) {
4197 return GeneratorWrapper<T>(std::unique_ptr<IGenerator<T>>(pf::make_unique<FilterGenerator<T, Predicate>>(std::forward<Predicate>(pred), std::move(generator))));
4198 }
4199
4200 template <typename T>
4201 class RepeatGenerator : public IGenerator<T> {
4202 static_assert(!std::is_same<T, bool>::value,
4203 "RepeatGenerator currently does not support bools"
4204 "because of std::vector<bool> specialization");
4205 GeneratorWrapper<T> m_generator;
4206 mutable std::vector<T> m_returned;
4207 size_t m_target_repeats;
4208 size_t m_current_repeat = 0;
4209 size_t m_repeat_index = 0;
4210 public:
RepeatGenerator(size_t repeats,GeneratorWrapper<T> && generator)4211 RepeatGenerator(size_t repeats, GeneratorWrapper<T>&& generator):
4212 m_generator(std::move(generator)),
4213 m_target_repeats(repeats)
4214 {
4215 assert(m_target_repeats > 0 && "Repeat generator must repeat at least once");
4216 }
4217
get() const4218 T const& get() const override {
4219 if (m_current_repeat == 0) {
4220 m_returned.push_back(m_generator.get());
4221 return m_returned.back();
4222 }
4223 return m_returned[m_repeat_index];
4224 }
4225
next()4226 bool next() override {
4227 // There are 2 basic cases:
4228 // 1) We are still reading the generator
4229 // 2) We are reading our own cache
4230
4231 // In the first case, we need to poke the underlying generator.
4232 // If it happily moves, we are left in that state, otherwise it is time to start reading from our cache
4233 if (m_current_repeat == 0) {
4234 const auto success = m_generator.next();
4235 if (!success) {
4236 ++m_current_repeat;
4237 }
4238 return m_current_repeat < m_target_repeats;
4239 }
4240
4241 // In the second case, we need to move indices forward and check that we haven't run up against the end
4242 ++m_repeat_index;
4243 if (m_repeat_index == m_returned.size()) {
4244 m_repeat_index = 0;
4245 ++m_current_repeat;
4246 }
4247 return m_current_repeat < m_target_repeats;
4248 }
4249 };
4250
4251 template <typename T>
repeat(size_t repeats,GeneratorWrapper<T> && generator)4252 GeneratorWrapper<T> repeat(size_t repeats, GeneratorWrapper<T>&& generator) {
4253 return GeneratorWrapper<T>(pf::make_unique<RepeatGenerator<T>>(repeats, std::move(generator)));
4254 }
4255
4256 template <typename T, typename U, typename Func>
4257 class MapGenerator : public IGenerator<T> {
4258 // TBD: provide static assert for mapping function, for friendly error message
4259 GeneratorWrapper<U> m_generator;
4260 Func m_function;
4261 // To avoid returning dangling reference, we have to save the values
4262 T m_cache;
4263 public:
4264 template <typename F2 = Func>
MapGenerator(F2 && function,GeneratorWrapper<U> && generator)4265 MapGenerator(F2&& function, GeneratorWrapper<U>&& generator) :
4266 m_generator(std::move(generator)),
4267 m_function(std::forward<F2>(function)),
4268 m_cache(m_function(m_generator.get()))
4269 {}
4270
get() const4271 T const& get() const override {
4272 return m_cache;
4273 }
next()4274 bool next() override {
4275 const auto success = m_generator.next();
4276 if (success) {
4277 m_cache = m_function(m_generator.get());
4278 }
4279 return success;
4280 }
4281 };
4282
4283 template <typename Func, typename U, typename T = FunctionReturnType<Func, U>>
map(Func && function,GeneratorWrapper<U> && generator)4284 GeneratorWrapper<T> map(Func&& function, GeneratorWrapper<U>&& generator) {
4285 return GeneratorWrapper<T>(
4286 pf::make_unique<MapGenerator<T, U, Func>>(std::forward<Func>(function), std::move(generator))
4287 );
4288 }
4289
4290 template <typename T, typename U, typename Func>
map(Func && function,GeneratorWrapper<U> && generator)4291 GeneratorWrapper<T> map(Func&& function, GeneratorWrapper<U>&& generator) {
4292 return GeneratorWrapper<T>(
4293 pf::make_unique<MapGenerator<T, U, Func>>(std::forward<Func>(function), std::move(generator))
4294 );
4295 }
4296
4297 template <typename T>
4298 class ChunkGenerator final : public IGenerator<std::vector<T>> {
4299 std::vector<T> m_chunk;
4300 size_t m_chunk_size;
4301 GeneratorWrapper<T> m_generator;
4302 bool m_used_up = false;
4303 public:
ChunkGenerator(size_t size,GeneratorWrapper<T> generator)4304 ChunkGenerator(size_t size, GeneratorWrapper<T> generator) :
4305 m_chunk_size(size), m_generator(std::move(generator))
4306 {
4307 m_chunk.reserve(m_chunk_size);
4308 if (m_chunk_size != 0) {
4309 m_chunk.push_back(m_generator.get());
4310 for (size_t i = 1; i < m_chunk_size; ++i) {
4311 if (!m_generator.next()) {
4312 Catch::throw_exception(GeneratorException("Not enough values to initialize the first chunk"));
4313 }
4314 m_chunk.push_back(m_generator.get());
4315 }
4316 }
4317 }
get() const4318 std::vector<T> const& get() const override {
4319 return m_chunk;
4320 }
next()4321 bool next() override {
4322 m_chunk.clear();
4323 for (size_t idx = 0; idx < m_chunk_size; ++idx) {
4324 if (!m_generator.next()) {
4325 return false;
4326 }
4327 m_chunk.push_back(m_generator.get());
4328 }
4329 return true;
4330 }
4331 };
4332
4333 template <typename T>
chunk(size_t size,GeneratorWrapper<T> && generator)4334 GeneratorWrapper<std::vector<T>> chunk(size_t size, GeneratorWrapper<T>&& generator) {
4335 return GeneratorWrapper<std::vector<T>>(
4336 pf::make_unique<ChunkGenerator<T>>(size, std::move(generator))
4337 );
4338 }
4339
4340 } // namespace Generators
4341 } // namespace Catch
4342
4343 // end catch_generators_generic.hpp
4344 // start catch_generators_specific.hpp
4345
4346 // start catch_context.h
4347
4348 #include <memory>
4349
4350 namespace Catch {
4351
4352 struct IResultCapture;
4353 struct IRunner;
4354 struct IConfig;
4355 struct IMutableContext;
4356
4357 using IConfigPtr = std::shared_ptr<IConfig const>;
4358
4359 struct IContext
4360 {
4361 virtual ~IContext();
4362
4363 virtual IResultCapture* getResultCapture() = 0;
4364 virtual IRunner* getRunner() = 0;
4365 virtual IConfigPtr const& getConfig() const = 0;
4366 };
4367
4368 struct IMutableContext : IContext
4369 {
4370 virtual ~IMutableContext();
4371 virtual void setResultCapture( IResultCapture* resultCapture ) = 0;
4372 virtual void setRunner( IRunner* runner ) = 0;
4373 virtual void setConfig( IConfigPtr const& config ) = 0;
4374
4375 private:
4376 static IMutableContext *currentContext;
4377 friend IMutableContext& getCurrentMutableContext();
4378 friend void cleanUpContext();
4379 static void createContext();
4380 };
4381
getCurrentMutableContext()4382 inline IMutableContext& getCurrentMutableContext()
4383 {
4384 if( !IMutableContext::currentContext )
4385 IMutableContext::createContext();
4386 // NOLINTNEXTLINE(clang-analyzer-core.uninitialized.UndefReturn)
4387 return *IMutableContext::currentContext;
4388 }
4389
getCurrentContext()4390 inline IContext& getCurrentContext()
4391 {
4392 return getCurrentMutableContext();
4393 }
4394
4395 void cleanUpContext();
4396
4397 class SimplePcg32;
4398 SimplePcg32& rng();
4399 }
4400
4401 // end catch_context.h
4402 // start catch_interfaces_config.h
4403
4404 // start catch_option.hpp
4405
4406 namespace Catch {
4407
4408 // An optional type
4409 template<typename T>
4410 class Option {
4411 public:
Option()4412 Option() : nullableValue( nullptr ) {}
Option(T const & _value)4413 Option( T const& _value )
4414 : nullableValue( new( storage ) T( _value ) )
4415 {}
Option(Option const & _other)4416 Option( Option const& _other )
4417 : nullableValue( _other ? new( storage ) T( *_other ) : nullptr )
4418 {}
4419
~Option()4420 ~Option() {
4421 reset();
4422 }
4423
operator =(Option const & _other)4424 Option& operator= ( Option const& _other ) {
4425 if( &_other != this ) {
4426 reset();
4427 if( _other )
4428 nullableValue = new( storage ) T( *_other );
4429 }
4430 return *this;
4431 }
operator =(T const & _value)4432 Option& operator = ( T const& _value ) {
4433 reset();
4434 nullableValue = new( storage ) T( _value );
4435 return *this;
4436 }
4437
reset()4438 void reset() {
4439 if( nullableValue )
4440 nullableValue->~T();
4441 nullableValue = nullptr;
4442 }
4443
operator *()4444 T& operator*() { return *nullableValue; }
operator *() const4445 T const& operator*() const { return *nullableValue; }
operator ->()4446 T* operator->() { return nullableValue; }
operator ->() const4447 const T* operator->() const { return nullableValue; }
4448
valueOr(T const & defaultValue) const4449 T valueOr( T const& defaultValue ) const {
4450 return nullableValue ? *nullableValue : defaultValue;
4451 }
4452
some() const4453 bool some() const { return nullableValue != nullptr; }
none() const4454 bool none() const { return nullableValue == nullptr; }
4455
operator !() const4456 bool operator !() const { return nullableValue == nullptr; }
operator bool() const4457 explicit operator bool() const {
4458 return some();
4459 }
4460
4461 private:
4462 T *nullableValue;
4463 alignas(alignof(T)) char storage[sizeof(T)];
4464 };
4465
4466 } // end namespace Catch
4467
4468 // end catch_option.hpp
4469 #include <chrono>
4470 #include <iosfwd>
4471 #include <string>
4472 #include <vector>
4473 #include <memory>
4474
4475 namespace Catch {
4476
4477 enum class Verbosity {
4478 Quiet = 0,
4479 Normal,
4480 High
4481 };
4482
4483 struct WarnAbout { enum What {
4484 Nothing = 0x00,
4485 NoAssertions = 0x01,
4486 NoTests = 0x02
4487 }; };
4488
4489 struct ShowDurations { enum OrNot {
4490 DefaultForReporter,
4491 Always,
4492 Never
4493 }; };
4494 struct RunTests { enum InWhatOrder {
4495 InDeclarationOrder,
4496 InLexicographicalOrder,
4497 InRandomOrder
4498 }; };
4499 struct UseColour { enum YesOrNo {
4500 Auto,
4501 Yes,
4502 No
4503 }; };
4504 struct WaitForKeypress { enum When {
4505 Never,
4506 BeforeStart = 1,
4507 BeforeExit = 2,
4508 BeforeStartAndExit = BeforeStart | BeforeExit
4509 }; };
4510
4511 class TestSpec;
4512
4513 struct IConfig : NonCopyable {
4514
4515 virtual ~IConfig();
4516
4517 virtual bool allowThrows() const = 0;
4518 virtual std::ostream& stream() const = 0;
4519 virtual std::string name() const = 0;
4520 virtual bool includeSuccessfulResults() const = 0;
4521 virtual bool shouldDebugBreak() const = 0;
4522 virtual bool warnAboutMissingAssertions() const = 0;
4523 virtual bool warnAboutNoTests() const = 0;
4524 virtual int abortAfter() const = 0;
4525 virtual bool showInvisibles() const = 0;
4526 virtual ShowDurations::OrNot showDurations() const = 0;
4527 virtual double minDuration() const = 0;
4528 virtual TestSpec const& testSpec() const = 0;
4529 virtual bool hasTestFilters() const = 0;
4530 virtual std::vector<std::string> const& getTestsOrTags() const = 0;
4531 virtual RunTests::InWhatOrder runOrder() const = 0;
4532 virtual unsigned int rngSeed() const = 0;
4533 virtual UseColour::YesOrNo useColour() const = 0;
4534 virtual std::vector<std::string> const& getSectionsToRun() const = 0;
4535 virtual Verbosity verbosity() const = 0;
4536
4537 virtual bool benchmarkNoAnalysis() const = 0;
4538 virtual int benchmarkSamples() const = 0;
4539 virtual double benchmarkConfidenceInterval() const = 0;
4540 virtual unsigned int benchmarkResamples() const = 0;
4541 virtual std::chrono::milliseconds benchmarkWarmupTime() const = 0;
4542 };
4543
4544 using IConfigPtr = std::shared_ptr<IConfig const>;
4545 }
4546
4547 // end catch_interfaces_config.h
4548 // start catch_random_number_generator.h
4549
4550 #include <cstdint>
4551
4552 namespace Catch {
4553
4554 // This is a simple implementation of C++11 Uniform Random Number
4555 // Generator. It does not provide all operators, because Catch2
4556 // does not use it, but it should behave as expected inside stdlib's
4557 // distributions.
4558 // The implementation is based on the PCG family (http://pcg-random.org)
4559 class SimplePcg32 {
4560 using state_type = std::uint64_t;
4561 public:
4562 using result_type = std::uint32_t;
result_type(min)4563 static constexpr result_type (min)() {
4564 return 0;
4565 }
result_type(max)4566 static constexpr result_type (max)() {
4567 return static_cast<result_type>(-1);
4568 }
4569
4570 // Provide some default initial state for the default constructor
SimplePcg32()4571 SimplePcg32():SimplePcg32(0xed743cc4U) {}
4572
4573 explicit SimplePcg32(result_type seed_);
4574
4575 void seed(result_type seed_);
4576 void discard(uint64_t skip);
4577
4578 result_type operator()();
4579
4580 private:
4581 friend bool operator==(SimplePcg32 const& lhs, SimplePcg32 const& rhs);
4582 friend bool operator!=(SimplePcg32 const& lhs, SimplePcg32 const& rhs);
4583
4584 // In theory we also need operator<< and operator>>
4585 // In practice we do not use them, so we will skip them for now
4586
4587 std::uint64_t m_state;
4588 // This part of the state determines which "stream" of the numbers
4589 // is chosen -- we take it as a constant for Catch2, so we only
4590 // need to deal with seeding the main state.
4591 // Picked by reading 8 bytes from `/dev/random` :-)
4592 static const std::uint64_t s_inc = (0x13ed0cc53f939476ULL << 1ULL) | 1ULL;
4593 };
4594
4595 } // end namespace Catch
4596
4597 // end catch_random_number_generator.h
4598 #include <random>
4599
4600 namespace Catch {
4601 namespace Generators {
4602
4603 template <typename Float>
4604 class RandomFloatingGenerator final : public IGenerator<Float> {
4605 Catch::SimplePcg32& m_rng;
4606 std::uniform_real_distribution<Float> m_dist;
4607 Float m_current_number;
4608 public:
4609
RandomFloatingGenerator(Float a,Float b)4610 RandomFloatingGenerator(Float a, Float b):
4611 m_rng(rng()),
4612 m_dist(a, b) {
4613 static_cast<void>(next());
4614 }
4615
get() const4616 Float const& get() const override {
4617 return m_current_number;
4618 }
next()4619 bool next() override {
4620 m_current_number = m_dist(m_rng);
4621 return true;
4622 }
4623 };
4624
4625 template <typename Integer>
4626 class RandomIntegerGenerator final : public IGenerator<Integer> {
4627 Catch::SimplePcg32& m_rng;
4628 std::uniform_int_distribution<Integer> m_dist;
4629 Integer m_current_number;
4630 public:
4631
RandomIntegerGenerator(Integer a,Integer b)4632 RandomIntegerGenerator(Integer a, Integer b):
4633 m_rng(rng()),
4634 m_dist(a, b) {
4635 static_cast<void>(next());
4636 }
4637
get() const4638 Integer const& get() const override {
4639 return m_current_number;
4640 }
next()4641 bool next() override {
4642 m_current_number = m_dist(m_rng);
4643 return true;
4644 }
4645 };
4646
4647 // TODO: Ideally this would be also constrained against the various char types,
4648 // but I don't expect users to run into that in practice.
4649 template <typename T>
4650 typename std::enable_if<std::is_integral<T>::value && !std::is_same<T, bool>::value,
4651 GeneratorWrapper<T>>::type
random(T a,T b)4652 random(T a, T b) {
4653 return GeneratorWrapper<T>(
4654 pf::make_unique<RandomIntegerGenerator<T>>(a, b)
4655 );
4656 }
4657
4658 template <typename T>
4659 typename std::enable_if<std::is_floating_point<T>::value,
4660 GeneratorWrapper<T>>::type
random(T a,T b)4661 random(T a, T b) {
4662 return GeneratorWrapper<T>(
4663 pf::make_unique<RandomFloatingGenerator<T>>(a, b)
4664 );
4665 }
4666
4667 template <typename T>
4668 class RangeGenerator final : public IGenerator<T> {
4669 T m_current;
4670 T m_end;
4671 T m_step;
4672 bool m_positive;
4673
4674 public:
RangeGenerator(T const & start,T const & end,T const & step)4675 RangeGenerator(T const& start, T const& end, T const& step):
4676 m_current(start),
4677 m_end(end),
4678 m_step(step),
4679 m_positive(m_step > T(0))
4680 {
4681 assert(m_current != m_end && "Range start and end cannot be equal");
4682 assert(m_step != T(0) && "Step size cannot be zero");
4683 assert(((m_positive && m_current <= m_end) || (!m_positive && m_current >= m_end)) && "Step moves away from end");
4684 }
4685
RangeGenerator(T const & start,T const & end)4686 RangeGenerator(T const& start, T const& end):
4687 RangeGenerator(start, end, (start < end) ? T(1) : T(-1))
4688 {}
4689
get() const4690 T const& get() const override {
4691 return m_current;
4692 }
4693
next()4694 bool next() override {
4695 m_current += m_step;
4696 return (m_positive) ? (m_current < m_end) : (m_current > m_end);
4697 }
4698 };
4699
4700 template <typename T>
range(T const & start,T const & end,T const & step)4701 GeneratorWrapper<T> range(T const& start, T const& end, T const& step) {
4702 static_assert(std::is_arithmetic<T>::value && !std::is_same<T, bool>::value, "Type must be numeric");
4703 return GeneratorWrapper<T>(pf::make_unique<RangeGenerator<T>>(start, end, step));
4704 }
4705
4706 template <typename T>
range(T const & start,T const & end)4707 GeneratorWrapper<T> range(T const& start, T const& end) {
4708 static_assert(std::is_integral<T>::value && !std::is_same<T, bool>::value, "Type must be an integer");
4709 return GeneratorWrapper<T>(pf::make_unique<RangeGenerator<T>>(start, end));
4710 }
4711
4712 template <typename T>
4713 class IteratorGenerator final : public IGenerator<T> {
4714 static_assert(!std::is_same<T, bool>::value,
4715 "IteratorGenerator currently does not support bools"
4716 "because of std::vector<bool> specialization");
4717
4718 std::vector<T> m_elems;
4719 size_t m_current = 0;
4720 public:
4721 template <typename InputIterator, typename InputSentinel>
IteratorGenerator(InputIterator first,InputSentinel last)4722 IteratorGenerator(InputIterator first, InputSentinel last):m_elems(first, last) {
4723 if (m_elems.empty()) {
4724 Catch::throw_exception(GeneratorException("IteratorGenerator received no valid values"));
4725 }
4726 }
4727
get() const4728 T const& get() const override {
4729 return m_elems[m_current];
4730 }
4731
next()4732 bool next() override {
4733 ++m_current;
4734 return m_current != m_elems.size();
4735 }
4736 };
4737
4738 template <typename InputIterator,
4739 typename InputSentinel,
4740 typename ResultType = typename std::iterator_traits<InputIterator>::value_type>
from_range(InputIterator from,InputSentinel to)4741 GeneratorWrapper<ResultType> from_range(InputIterator from, InputSentinel to) {
4742 return GeneratorWrapper<ResultType>(pf::make_unique<IteratorGenerator<ResultType>>(from, to));
4743 }
4744
4745 template <typename Container,
4746 typename ResultType = typename Container::value_type>
from_range(Container const & cnt)4747 GeneratorWrapper<ResultType> from_range(Container const& cnt) {
4748 return GeneratorWrapper<ResultType>(pf::make_unique<IteratorGenerator<ResultType>>(cnt.begin(), cnt.end()));
4749 }
4750
4751 } // namespace Generators
4752 } // namespace Catch
4753
4754 // end catch_generators_specific.hpp
4755
4756 // These files are included here so the single_include script doesn't put them
4757 // in the conditionally compiled sections
4758 // start catch_test_case_info.h
4759
4760 #include <string>
4761 #include <vector>
4762 #include <memory>
4763
4764 #ifdef __clang__
4765 #pragma clang diagnostic push
4766 #pragma clang diagnostic ignored "-Wpadded"
4767 #endif
4768
4769 namespace Catch {
4770
4771 struct ITestInvoker;
4772
4773 struct TestCaseInfo {
4774 enum SpecialProperties{
4775 None = 0,
4776 IsHidden = 1 << 1,
4777 ShouldFail = 1 << 2,
4778 MayFail = 1 << 3,
4779 Throws = 1 << 4,
4780 NonPortable = 1 << 5,
4781 Benchmark = 1 << 6
4782 };
4783
4784 TestCaseInfo( std::string const& _name,
4785 std::string const& _className,
4786 std::string const& _description,
4787 std::vector<std::string> const& _tags,
4788 SourceLineInfo const& _lineInfo );
4789
4790 friend void setTags( TestCaseInfo& testCaseInfo, std::vector<std::string> tags );
4791
4792 bool isHidden() const;
4793 bool throws() const;
4794 bool okToFail() const;
4795 bool expectedToFail() const;
4796
4797 std::string tagsAsString() const;
4798
4799 std::string name;
4800 std::string className;
4801 std::string description;
4802 std::vector<std::string> tags;
4803 std::vector<std::string> lcaseTags;
4804 SourceLineInfo lineInfo;
4805 SpecialProperties properties;
4806 };
4807
4808 class TestCase : public TestCaseInfo {
4809 public:
4810
4811 TestCase( ITestInvoker* testCase, TestCaseInfo&& info );
4812
4813 TestCase withName( std::string const& _newName ) const;
4814
4815 void invoke() const;
4816
4817 TestCaseInfo const& getTestCaseInfo() const;
4818
4819 bool operator == ( TestCase const& other ) const;
4820 bool operator < ( TestCase const& other ) const;
4821
4822 private:
4823 std::shared_ptr<ITestInvoker> test;
4824 };
4825
4826 TestCase makeTestCase( ITestInvoker* testCase,
4827 std::string const& className,
4828 NameAndTags const& nameAndTags,
4829 SourceLineInfo const& lineInfo );
4830 }
4831
4832 #ifdef __clang__
4833 #pragma clang diagnostic pop
4834 #endif
4835
4836 // end catch_test_case_info.h
4837 // start catch_interfaces_runner.h
4838
4839 namespace Catch {
4840
4841 struct IRunner {
4842 virtual ~IRunner();
4843 virtual bool aborting() const = 0;
4844 };
4845 }
4846
4847 // end catch_interfaces_runner.h
4848
4849 #ifdef __OBJC__
4850 // start catch_objc.hpp
4851
4852 #import <objc/runtime.h>
4853
4854 #include <string>
4855
4856 // NB. Any general catch headers included here must be included
4857 // in catch.hpp first to make sure they are included by the single
4858 // header for non obj-usage
4859
4860 ///////////////////////////////////////////////////////////////////////////////
4861 // This protocol is really only here for (self) documenting purposes, since
4862 // all its methods are optional.
4863 @protocol OcFixture
4864
4865 @optional
4866
4867 -(void) setUp;
4868 -(void) tearDown;
4869
4870 @end
4871
4872 namespace Catch {
4873
4874 class OcMethod : public ITestInvoker {
4875
4876 public:
OcMethod(Class cls,SEL sel)4877 OcMethod( Class cls, SEL sel ) : m_cls( cls ), m_sel( sel ) {}
4878
invoke() const4879 virtual void invoke() const {
4880 id obj = [[m_cls alloc] init];
4881
4882 performOptionalSelector( obj, @selector(setUp) );
4883 performOptionalSelector( obj, m_sel );
4884 performOptionalSelector( obj, @selector(tearDown) );
4885
4886 arcSafeRelease( obj );
4887 }
4888 private:
~OcMethod()4889 virtual ~OcMethod() {}
4890
4891 Class m_cls;
4892 SEL m_sel;
4893 };
4894
4895 namespace Detail{
4896
getAnnotation(Class cls,std::string const & annotationName,std::string const & testCaseName)4897 inline std::string getAnnotation( Class cls,
4898 std::string const& annotationName,
4899 std::string const& testCaseName ) {
4900 NSString* selStr = [[NSString alloc] initWithFormat:@"Catch_%s_%s", annotationName.c_str(), testCaseName.c_str()];
4901 SEL sel = NSSelectorFromString( selStr );
4902 arcSafeRelease( selStr );
4903 id value = performOptionalSelector( cls, sel );
4904 if( value )
4905 return [(NSString*)value UTF8String];
4906 return "";
4907 }
4908 }
4909
registerTestMethods()4910 inline std::size_t registerTestMethods() {
4911 std::size_t noTestMethods = 0;
4912 int noClasses = objc_getClassList( nullptr, 0 );
4913
4914 Class* classes = (CATCH_UNSAFE_UNRETAINED Class *)malloc( sizeof(Class) * noClasses);
4915 objc_getClassList( classes, noClasses );
4916
4917 for( int c = 0; c < noClasses; c++ ) {
4918 Class cls = classes[c];
4919 {
4920 u_int count;
4921 Method* methods = class_copyMethodList( cls, &count );
4922 for( u_int m = 0; m < count ; m++ ) {
4923 SEL selector = method_getName(methods[m]);
4924 std::string methodName = sel_getName(selector);
4925 if( startsWith( methodName, "Catch_TestCase_" ) ) {
4926 std::string testCaseName = methodName.substr( 15 );
4927 std::string name = Detail::getAnnotation( cls, "Name", testCaseName );
4928 std::string desc = Detail::getAnnotation( cls, "Description", testCaseName );
4929 const char* className = class_getName( cls );
4930
4931 getMutableRegistryHub().registerTest( makeTestCase( new OcMethod( cls, selector ), className, NameAndTags( name.c_str(), desc.c_str() ), SourceLineInfo("",0) ) );
4932 noTestMethods++;
4933 }
4934 }
4935 free(methods);
4936 }
4937 }
4938 return noTestMethods;
4939 }
4940
4941 #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
4942
4943 namespace Matchers {
4944 namespace Impl {
4945 namespace NSStringMatchers {
4946
4947 struct StringHolder : MatcherBase<NSString*>{
StringHolderCatch::Matchers::Impl::NSStringMatchers::StringHolder4948 StringHolder( NSString* substr ) : m_substr( [substr copy] ){}
StringHolderCatch::Matchers::Impl::NSStringMatchers::StringHolder4949 StringHolder( StringHolder const& other ) : m_substr( [other.m_substr copy] ){}
StringHolderCatch::Matchers::Impl::NSStringMatchers::StringHolder4950 StringHolder() {
4951 arcSafeRelease( m_substr );
4952 }
4953
matchCatch::Matchers::Impl::NSStringMatchers::StringHolder4954 bool match( NSString* str ) const override {
4955 return false;
4956 }
4957
4958 NSString* CATCH_ARC_STRONG m_substr;
4959 };
4960
4961 struct Equals : StringHolder {
EqualsCatch::Matchers::Impl::NSStringMatchers::Equals4962 Equals( NSString* substr ) : StringHolder( substr ){}
4963
matchCatch::Matchers::Impl::NSStringMatchers::Equals4964 bool match( NSString* str ) const override {
4965 return (str != nil || m_substr == nil ) &&
4966 [str isEqualToString:m_substr];
4967 }
4968
describeCatch::Matchers::Impl::NSStringMatchers::Equals4969 std::string describe() const override {
4970 return "equals string: " + Catch::Detail::stringify( m_substr );
4971 }
4972 };
4973
4974 struct Contains : StringHolder {
ContainsCatch::Matchers::Impl::NSStringMatchers::Contains4975 Contains( NSString* substr ) : StringHolder( substr ){}
4976
matchCatch::Matchers::Impl::NSStringMatchers::Contains4977 bool match( NSString* str ) const override {
4978 return (str != nil || m_substr == nil ) &&
4979 [str rangeOfString:m_substr].location != NSNotFound;
4980 }
4981
describeCatch::Matchers::Impl::NSStringMatchers::Contains4982 std::string describe() const override {
4983 return "contains string: " + Catch::Detail::stringify( m_substr );
4984 }
4985 };
4986
4987 struct StartsWith : StringHolder {
StartsWithCatch::Matchers::Impl::NSStringMatchers::StartsWith4988 StartsWith( NSString* substr ) : StringHolder( substr ){}
4989
matchCatch::Matchers::Impl::NSStringMatchers::StartsWith4990 bool match( NSString* str ) const override {
4991 return (str != nil || m_substr == nil ) &&
4992 [str rangeOfString:m_substr].location == 0;
4993 }
4994
describeCatch::Matchers::Impl::NSStringMatchers::StartsWith4995 std::string describe() const override {
4996 return "starts with: " + Catch::Detail::stringify( m_substr );
4997 }
4998 };
4999 struct EndsWith : StringHolder {
EndsWithCatch::Matchers::Impl::NSStringMatchers::EndsWith5000 EndsWith( NSString* substr ) : StringHolder( substr ){}
5001
matchCatch::Matchers::Impl::NSStringMatchers::EndsWith5002 bool match( NSString* str ) const override {
5003 return (str != nil || m_substr == nil ) &&
5004 [str rangeOfString:m_substr].location == [str length] - [m_substr length];
5005 }
5006
describeCatch::Matchers::Impl::NSStringMatchers::EndsWith5007 std::string describe() const override {
5008 return "ends with: " + Catch::Detail::stringify( m_substr );
5009 }
5010 };
5011
5012 } // namespace NSStringMatchers
5013 } // namespace Impl
5014
5015 inline Impl::NSStringMatchers::Equals
Equals(NSString * substr)5016 Equals( NSString* substr ){ return Impl::NSStringMatchers::Equals( substr ); }
5017
5018 inline Impl::NSStringMatchers::Contains
Contains(NSString * substr)5019 Contains( NSString* substr ){ return Impl::NSStringMatchers::Contains( substr ); }
5020
5021 inline Impl::NSStringMatchers::StartsWith
StartsWith(NSString * substr)5022 StartsWith( NSString* substr ){ return Impl::NSStringMatchers::StartsWith( substr ); }
5023
5024 inline Impl::NSStringMatchers::EndsWith
EndsWith(NSString * substr)5025 EndsWith( NSString* substr ){ return Impl::NSStringMatchers::EndsWith( substr ); }
5026
5027 } // namespace Matchers
5028
5029 using namespace Matchers;
5030
5031 #endif // CATCH_CONFIG_DISABLE_MATCHERS
5032
5033 } // namespace Catch
5034
5035 ///////////////////////////////////////////////////////////////////////////////
5036 #define OC_MAKE_UNIQUE_NAME( root, uniqueSuffix ) root##uniqueSuffix
5037 #define OC_TEST_CASE2( name, desc, uniqueSuffix ) \
5038 +(NSString*) OC_MAKE_UNIQUE_NAME( Catch_Name_test_, uniqueSuffix ) \
5039 { \
5040 return @ name; \
5041 } \
5042 +(NSString*) OC_MAKE_UNIQUE_NAME( Catch_Description_test_, uniqueSuffix ) \
5043 { \
5044 return @ desc; \
5045 } \
5046 -(void) OC_MAKE_UNIQUE_NAME( Catch_TestCase_test_, uniqueSuffix )
5047
5048 #define OC_TEST_CASE( name, desc ) OC_TEST_CASE2( name, desc, __LINE__ )
5049
5050 // end catch_objc.hpp
5051 #endif
5052
5053 // Benchmarking needs the externally-facing parts of reporters to work
5054 #if defined(CATCH_CONFIG_EXTERNAL_INTERFACES) || defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
5055 // start catch_external_interfaces.h
5056
5057 // start catch_reporter_bases.hpp
5058
5059 // start catch_interfaces_reporter.h
5060
5061 // start catch_config.hpp
5062
5063 // start catch_test_spec_parser.h
5064
5065 #ifdef __clang__
5066 #pragma clang diagnostic push
5067 #pragma clang diagnostic ignored "-Wpadded"
5068 #endif
5069
5070 // start catch_test_spec.h
5071
5072 #ifdef __clang__
5073 #pragma clang diagnostic push
5074 #pragma clang diagnostic ignored "-Wpadded"
5075 #endif
5076
5077 // start catch_wildcard_pattern.h
5078
5079 namespace Catch
5080 {
5081 class WildcardPattern {
5082 enum WildcardPosition {
5083 NoWildcard = 0,
5084 WildcardAtStart = 1,
5085 WildcardAtEnd = 2,
5086 WildcardAtBothEnds = WildcardAtStart | WildcardAtEnd
5087 };
5088
5089 public:
5090
5091 WildcardPattern( std::string const& pattern, CaseSensitive::Choice caseSensitivity );
5092 virtual ~WildcardPattern() = default;
5093 virtual bool matches( std::string const& str ) const;
5094
5095 private:
5096 std::string normaliseString( std::string const& str ) const;
5097 CaseSensitive::Choice m_caseSensitivity;
5098 WildcardPosition m_wildcard = NoWildcard;
5099 std::string m_pattern;
5100 };
5101 }
5102
5103 // end catch_wildcard_pattern.h
5104 #include <string>
5105 #include <vector>
5106 #include <memory>
5107
5108 namespace Catch {
5109
5110 struct IConfig;
5111
5112 class TestSpec {
5113 class Pattern {
5114 public:
5115 explicit Pattern( std::string const& name );
5116 virtual ~Pattern();
5117 virtual bool matches( TestCaseInfo const& testCase ) const = 0;
5118 std::string const& name() const;
5119 private:
5120 std::string const m_name;
5121 };
5122 using PatternPtr = std::shared_ptr<Pattern>;
5123
5124 class NamePattern : public Pattern {
5125 public:
5126 explicit NamePattern( std::string const& name, std::string const& filterString );
5127 bool matches( TestCaseInfo const& testCase ) const override;
5128 private:
5129 WildcardPattern m_wildcardPattern;
5130 };
5131
5132 class TagPattern : public Pattern {
5133 public:
5134 explicit TagPattern( std::string const& tag, std::string const& filterString );
5135 bool matches( TestCaseInfo const& testCase ) const override;
5136 private:
5137 std::string m_tag;
5138 };
5139
5140 class ExcludedPattern : public Pattern {
5141 public:
5142 explicit ExcludedPattern( PatternPtr const& underlyingPattern );
5143 bool matches( TestCaseInfo const& testCase ) const override;
5144 private:
5145 PatternPtr m_underlyingPattern;
5146 };
5147
5148 struct Filter {
5149 std::vector<PatternPtr> m_patterns;
5150
5151 bool matches( TestCaseInfo const& testCase ) const;
5152 std::string name() const;
5153 };
5154
5155 public:
5156 struct FilterMatch {
5157 std::string name;
5158 std::vector<TestCase const*> tests;
5159 };
5160 using Matches = std::vector<FilterMatch>;
5161 using vectorStrings = std::vector<std::string>;
5162
5163 bool hasFilters() const;
5164 bool matches( TestCaseInfo const& testCase ) const;
5165 Matches matchesByFilter( std::vector<TestCase> const& testCases, IConfig const& config ) const;
5166 const vectorStrings & getInvalidArgs() const;
5167
5168 private:
5169 std::vector<Filter> m_filters;
5170 std::vector<std::string> m_invalidArgs;
5171 friend class TestSpecParser;
5172 };
5173 }
5174
5175 #ifdef __clang__
5176 #pragma clang diagnostic pop
5177 #endif
5178
5179 // end catch_test_spec.h
5180 // start catch_interfaces_tag_alias_registry.h
5181
5182 #include <string>
5183
5184 namespace Catch {
5185
5186 struct TagAlias;
5187
5188 struct ITagAliasRegistry {
5189 virtual ~ITagAliasRegistry();
5190 // Nullptr if not present
5191 virtual TagAlias const* find( std::string const& alias ) const = 0;
5192 virtual std::string expandAliases( std::string const& unexpandedTestSpec ) const = 0;
5193
5194 static ITagAliasRegistry const& get();
5195 };
5196
5197 } // end namespace Catch
5198
5199 // end catch_interfaces_tag_alias_registry.h
5200 namespace Catch {
5201
5202 class TestSpecParser {
5203 enum Mode{ None, Name, QuotedName, Tag, EscapedName };
5204 Mode m_mode = None;
5205 Mode lastMode = None;
5206 bool m_exclusion = false;
5207 std::size_t m_pos = 0;
5208 std::size_t m_realPatternPos = 0;
5209 std::string m_arg;
5210 std::string m_substring;
5211 std::string m_patternName;
5212 std::vector<std::size_t> m_escapeChars;
5213 TestSpec::Filter m_currentFilter;
5214 TestSpec m_testSpec;
5215 ITagAliasRegistry const* m_tagAliases = nullptr;
5216
5217 public:
5218 TestSpecParser( ITagAliasRegistry const& tagAliases );
5219
5220 TestSpecParser& parse( std::string const& arg );
5221 TestSpec testSpec();
5222
5223 private:
5224 bool visitChar( char c );
5225 void startNewMode( Mode mode );
5226 bool processNoneChar( char c );
5227 void processNameChar( char c );
5228 bool processOtherChar( char c );
5229 void endMode();
5230 void escape();
5231 bool isControlChar( char c ) const;
5232 void saveLastMode();
5233 void revertBackToLastMode();
5234 void addFilter();
5235 bool separate();
5236
5237 // Handles common preprocessing of the pattern for name/tag patterns
5238 std::string preprocessPattern();
5239 // Adds the current pattern as a test name
5240 void addNamePattern();
5241 // Adds the current pattern as a tag
5242 void addTagPattern();
5243
addCharToPattern(char c)5244 inline void addCharToPattern(char c) {
5245 m_substring += c;
5246 m_patternName += c;
5247 m_realPatternPos++;
5248 }
5249
5250 };
5251 TestSpec parseTestSpec( std::string const& arg );
5252
5253 } // namespace Catch
5254
5255 #ifdef __clang__
5256 #pragma clang diagnostic pop
5257 #endif
5258
5259 // end catch_test_spec_parser.h
5260 // Libstdc++ doesn't like incomplete classes for unique_ptr
5261
5262 #include <memory>
5263 #include <vector>
5264 #include <string>
5265
5266 #ifndef CATCH_CONFIG_CONSOLE_WIDTH
5267 #define CATCH_CONFIG_CONSOLE_WIDTH 80
5268 #endif
5269
5270 namespace Catch {
5271
5272 struct IStream;
5273
5274 struct ConfigData {
5275 bool listTests = false;
5276 bool listTags = false;
5277 bool listReporters = false;
5278 bool listTestNamesOnly = false;
5279
5280 bool showSuccessfulTests = false;
5281 bool shouldDebugBreak = false;
5282 bool noThrow = false;
5283 bool showHelp = false;
5284 bool showInvisibles = false;
5285 bool filenamesAsTags = false;
5286 bool libIdentify = false;
5287
5288 int abortAfter = -1;
5289 unsigned int rngSeed = 0;
5290
5291 bool benchmarkNoAnalysis = false;
5292 unsigned int benchmarkSamples = 100;
5293 double benchmarkConfidenceInterval = 0.95;
5294 unsigned int benchmarkResamples = 100000;
5295 std::chrono::milliseconds::rep benchmarkWarmupTime = 100;
5296
5297 Verbosity verbosity = Verbosity::Normal;
5298 WarnAbout::What warnings = WarnAbout::Nothing;
5299 ShowDurations::OrNot showDurations = ShowDurations::DefaultForReporter;
5300 double minDuration = -1;
5301 RunTests::InWhatOrder runOrder = RunTests::InDeclarationOrder;
5302 UseColour::YesOrNo useColour = UseColour::Auto;
5303 WaitForKeypress::When waitForKeypress = WaitForKeypress::Never;
5304
5305 std::string outputFilename;
5306 std::string name;
5307 std::string processName;
5308 #ifndef CATCH_CONFIG_DEFAULT_REPORTER
5309 #define CATCH_CONFIG_DEFAULT_REPORTER "console"
5310 #endif
5311 std::string reporterName = CATCH_CONFIG_DEFAULT_REPORTER;
5312 #undef CATCH_CONFIG_DEFAULT_REPORTER
5313
5314 std::vector<std::string> testsOrTags;
5315 std::vector<std::string> sectionsToRun;
5316 };
5317
5318 class Config : public IConfig {
5319 public:
5320
5321 Config() = default;
5322 Config( ConfigData const& data );
5323 virtual ~Config() = default;
5324
5325 std::string const& getFilename() const;
5326
5327 bool listTests() const;
5328 bool listTestNamesOnly() const;
5329 bool listTags() const;
5330 bool listReporters() const;
5331
5332 std::string getProcessName() const;
5333 std::string const& getReporterName() const;
5334
5335 std::vector<std::string> const& getTestsOrTags() const override;
5336 std::vector<std::string> const& getSectionsToRun() const override;
5337
5338 TestSpec const& testSpec() const override;
5339 bool hasTestFilters() const override;
5340
5341 bool showHelp() const;
5342
5343 // IConfig interface
5344 bool allowThrows() const override;
5345 std::ostream& stream() const override;
5346 std::string name() const override;
5347 bool includeSuccessfulResults() const override;
5348 bool warnAboutMissingAssertions() const override;
5349 bool warnAboutNoTests() const override;
5350 ShowDurations::OrNot showDurations() const override;
5351 double minDuration() const override;
5352 RunTests::InWhatOrder runOrder() const override;
5353 unsigned int rngSeed() const override;
5354 UseColour::YesOrNo useColour() const override;
5355 bool shouldDebugBreak() const override;
5356 int abortAfter() const override;
5357 bool showInvisibles() const override;
5358 Verbosity verbosity() const override;
5359 bool benchmarkNoAnalysis() const override;
5360 int benchmarkSamples() const override;
5361 double benchmarkConfidenceInterval() const override;
5362 unsigned int benchmarkResamples() const override;
5363 std::chrono::milliseconds benchmarkWarmupTime() const override;
5364
5365 private:
5366
5367 IStream const* openStream();
5368 ConfigData m_data;
5369
5370 std::unique_ptr<IStream const> m_stream;
5371 TestSpec m_testSpec;
5372 bool m_hasTestFilters = false;
5373 };
5374
5375 } // end namespace Catch
5376
5377 // end catch_config.hpp
5378 // start catch_assertionresult.h
5379
5380 #include <string>
5381
5382 namespace Catch {
5383
5384 struct AssertionResultData
5385 {
5386 AssertionResultData() = delete;
5387
5388 AssertionResultData( ResultWas::OfType _resultType, LazyExpression const& _lazyExpression );
5389
5390 std::string message;
5391 mutable std::string reconstructedExpression;
5392 LazyExpression lazyExpression;
5393 ResultWas::OfType resultType;
5394
5395 std::string reconstructExpression() const;
5396 };
5397
5398 class AssertionResult {
5399 public:
5400 AssertionResult() = delete;
5401 AssertionResult( AssertionInfo const& info, AssertionResultData const& data );
5402
5403 bool isOk() const;
5404 bool succeeded() const;
5405 ResultWas::OfType getResultType() const;
5406 bool hasExpression() const;
5407 bool hasMessage() const;
5408 std::string getExpression() const;
5409 std::string getExpressionInMacro() const;
5410 bool hasExpandedExpression() const;
5411 std::string getExpandedExpression() const;
5412 std::string getMessage() const;
5413 SourceLineInfo getSourceInfo() const;
5414 StringRef getTestMacroName() const;
5415
5416 //protected:
5417 AssertionInfo m_info;
5418 AssertionResultData m_resultData;
5419 };
5420
5421 } // end namespace Catch
5422
5423 // end catch_assertionresult.h
5424 #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
5425 // start catch_estimate.hpp
5426
5427 // Statistics estimates
5428
5429
5430 namespace Catch {
5431 namespace Benchmark {
5432 template <typename Duration>
5433 struct Estimate {
5434 Duration point;
5435 Duration lower_bound;
5436 Duration upper_bound;
5437 double confidence_interval;
5438
5439 template <typename Duration2>
operator Estimate<Duration2>Catch::Benchmark::Estimate5440 operator Estimate<Duration2>() const {
5441 return { point, lower_bound, upper_bound, confidence_interval };
5442 }
5443 };
5444 } // namespace Benchmark
5445 } // namespace Catch
5446
5447 // end catch_estimate.hpp
5448 // start catch_outlier_classification.hpp
5449
5450 // Outlier information
5451
5452 namespace Catch {
5453 namespace Benchmark {
5454 struct OutlierClassification {
5455 int samples_seen = 0;
5456 int low_severe = 0; // more than 3 times IQR below Q1
5457 int low_mild = 0; // 1.5 to 3 times IQR below Q1
5458 int high_mild = 0; // 1.5 to 3 times IQR above Q3
5459 int high_severe = 0; // more than 3 times IQR above Q3
5460
totalCatch::Benchmark::OutlierClassification5461 int total() const {
5462 return low_severe + low_mild + high_mild + high_severe;
5463 }
5464 };
5465 } // namespace Benchmark
5466 } // namespace Catch
5467
5468 // end catch_outlier_classification.hpp
5469
5470 #include <iterator>
5471 #endif // CATCH_CONFIG_ENABLE_BENCHMARKING
5472
5473 #include <string>
5474 #include <iosfwd>
5475 #include <map>
5476 #include <set>
5477 #include <memory>
5478 #include <algorithm>
5479
5480 namespace Catch {
5481
5482 struct ReporterConfig {
5483 explicit ReporterConfig( IConfigPtr const& _fullConfig );
5484
5485 ReporterConfig( IConfigPtr const& _fullConfig, std::ostream& _stream );
5486
5487 std::ostream& stream() const;
5488 IConfigPtr fullConfig() const;
5489
5490 private:
5491 std::ostream* m_stream;
5492 IConfigPtr m_fullConfig;
5493 };
5494
5495 struct ReporterPreferences {
5496 bool shouldRedirectStdOut = false;
5497 bool shouldReportAllAssertions = false;
5498 };
5499
5500 template<typename T>
5501 struct LazyStat : Option<T> {
operator =Catch::LazyStat5502 LazyStat& operator=( T const& _value ) {
5503 Option<T>::operator=( _value );
5504 used = false;
5505 return *this;
5506 }
resetCatch::LazyStat5507 void reset() {
5508 Option<T>::reset();
5509 used = false;
5510 }
5511 bool used = false;
5512 };
5513
5514 struct TestRunInfo {
5515 TestRunInfo( std::string const& _name );
5516 std::string name;
5517 };
5518 struct GroupInfo {
5519 GroupInfo( std::string const& _name,
5520 std::size_t _groupIndex,
5521 std::size_t _groupsCount );
5522
5523 std::string name;
5524 std::size_t groupIndex;
5525 std::size_t groupsCounts;
5526 };
5527
5528 struct AssertionStats {
5529 AssertionStats( AssertionResult const& _assertionResult,
5530 std::vector<MessageInfo> const& _infoMessages,
5531 Totals const& _totals );
5532
5533 AssertionStats( AssertionStats const& ) = default;
5534 AssertionStats( AssertionStats && ) = default;
5535 AssertionStats& operator = ( AssertionStats const& ) = delete;
5536 AssertionStats& operator = ( AssertionStats && ) = delete;
5537 virtual ~AssertionStats();
5538
5539 AssertionResult assertionResult;
5540 std::vector<MessageInfo> infoMessages;
5541 Totals totals;
5542 };
5543
5544 struct SectionStats {
5545 SectionStats( SectionInfo const& _sectionInfo,
5546 Counts const& _assertions,
5547 double _durationInSeconds,
5548 bool _missingAssertions );
5549 SectionStats( SectionStats const& ) = default;
5550 SectionStats( SectionStats && ) = default;
5551 SectionStats& operator = ( SectionStats const& ) = default;
5552 SectionStats& operator = ( SectionStats && ) = default;
5553 virtual ~SectionStats();
5554
5555 SectionInfo sectionInfo;
5556 Counts assertions;
5557 double durationInSeconds;
5558 bool missingAssertions;
5559 };
5560
5561 struct TestCaseStats {
5562 TestCaseStats( TestCaseInfo const& _testInfo,
5563 Totals const& _totals,
5564 std::string const& _stdOut,
5565 std::string const& _stdErr,
5566 bool _aborting );
5567
5568 TestCaseStats( TestCaseStats const& ) = default;
5569 TestCaseStats( TestCaseStats && ) = default;
5570 TestCaseStats& operator = ( TestCaseStats const& ) = default;
5571 TestCaseStats& operator = ( TestCaseStats && ) = default;
5572 virtual ~TestCaseStats();
5573
5574 TestCaseInfo testInfo;
5575 Totals totals;
5576 std::string stdOut;
5577 std::string stdErr;
5578 bool aborting;
5579 };
5580
5581 struct TestGroupStats {
5582 TestGroupStats( GroupInfo const& _groupInfo,
5583 Totals const& _totals,
5584 bool _aborting );
5585 TestGroupStats( GroupInfo const& _groupInfo );
5586
5587 TestGroupStats( TestGroupStats const& ) = default;
5588 TestGroupStats( TestGroupStats && ) = default;
5589 TestGroupStats& operator = ( TestGroupStats const& ) = default;
5590 TestGroupStats& operator = ( TestGroupStats && ) = default;
5591 virtual ~TestGroupStats();
5592
5593 GroupInfo groupInfo;
5594 Totals totals;
5595 bool aborting;
5596 };
5597
5598 struct TestRunStats {
5599 TestRunStats( TestRunInfo const& _runInfo,
5600 Totals const& _totals,
5601 bool _aborting );
5602
5603 TestRunStats( TestRunStats const& ) = default;
5604 TestRunStats( TestRunStats && ) = default;
5605 TestRunStats& operator = ( TestRunStats const& ) = default;
5606 TestRunStats& operator = ( TestRunStats && ) = default;
5607 virtual ~TestRunStats();
5608
5609 TestRunInfo runInfo;
5610 Totals totals;
5611 bool aborting;
5612 };
5613
5614 #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
5615 struct BenchmarkInfo {
5616 std::string name;
5617 double estimatedDuration;
5618 int iterations;
5619 int samples;
5620 unsigned int resamples;
5621 double clockResolution;
5622 double clockCost;
5623 };
5624
5625 template <class Duration>
5626 struct BenchmarkStats {
5627 BenchmarkInfo info;
5628
5629 std::vector<Duration> samples;
5630 Benchmark::Estimate<Duration> mean;
5631 Benchmark::Estimate<Duration> standardDeviation;
5632 Benchmark::OutlierClassification outliers;
5633 double outlierVariance;
5634
5635 template <typename Duration2>
operator BenchmarkStats<Duration2>Catch::BenchmarkStats5636 operator BenchmarkStats<Duration2>() const {
5637 std::vector<Duration2> samples2;
5638 samples2.reserve(samples.size());
5639 std::transform(samples.begin(), samples.end(), std::back_inserter(samples2), [](Duration d) { return Duration2(d); });
5640 return {
5641 info,
5642 std::move(samples2),
5643 mean,
5644 standardDeviation,
5645 outliers,
5646 outlierVariance,
5647 };
5648 }
5649 };
5650 #endif // CATCH_CONFIG_ENABLE_BENCHMARKING
5651
5652 struct IStreamingReporter {
5653 virtual ~IStreamingReporter() = default;
5654
5655 // Implementing class must also provide the following static methods:
5656 // static std::string getDescription();
5657 // static std::set<Verbosity> getSupportedVerbosities()
5658
5659 virtual ReporterPreferences getPreferences() const = 0;
5660
5661 virtual void noMatchingTestCases( std::string const& spec ) = 0;
5662
reportInvalidArgumentsCatch::IStreamingReporter5663 virtual void reportInvalidArguments(std::string const&) {}
5664
5665 virtual void testRunStarting( TestRunInfo const& testRunInfo ) = 0;
5666 virtual void testGroupStarting( GroupInfo const& groupInfo ) = 0;
5667
5668 virtual void testCaseStarting( TestCaseInfo const& testInfo ) = 0;
5669 virtual void sectionStarting( SectionInfo const& sectionInfo ) = 0;
5670
5671 #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
benchmarkPreparingCatch::IStreamingReporter5672 virtual void benchmarkPreparing( std::string const& ) {}
benchmarkStartingCatch::IStreamingReporter5673 virtual void benchmarkStarting( BenchmarkInfo const& ) {}
benchmarkEndedCatch::IStreamingReporter5674 virtual void benchmarkEnded( BenchmarkStats<> const& ) {}
benchmarkFailedCatch::IStreamingReporter5675 virtual void benchmarkFailed( std::string const& ) {}
5676 #endif // CATCH_CONFIG_ENABLE_BENCHMARKING
5677
5678 virtual void assertionStarting( AssertionInfo const& assertionInfo ) = 0;
5679
5680 // The return value indicates if the messages buffer should be cleared:
5681 virtual bool assertionEnded( AssertionStats const& assertionStats ) = 0;
5682
5683 virtual void sectionEnded( SectionStats const& sectionStats ) = 0;
5684 virtual void testCaseEnded( TestCaseStats const& testCaseStats ) = 0;
5685 virtual void testGroupEnded( TestGroupStats const& testGroupStats ) = 0;
5686 virtual void testRunEnded( TestRunStats const& testRunStats ) = 0;
5687
5688 virtual void skipTest( TestCaseInfo const& testInfo ) = 0;
5689
5690 // Default empty implementation provided
5691 virtual void fatalErrorEncountered( StringRef name );
5692
5693 virtual bool isMulti() const;
5694 };
5695 using IStreamingReporterPtr = std::unique_ptr<IStreamingReporter>;
5696
5697 struct IReporterFactory {
5698 virtual ~IReporterFactory();
5699 virtual IStreamingReporterPtr create( ReporterConfig const& config ) const = 0;
5700 virtual std::string getDescription() const = 0;
5701 };
5702 using IReporterFactoryPtr = std::shared_ptr<IReporterFactory>;
5703
5704 struct IReporterRegistry {
5705 using FactoryMap = std::map<std::string, IReporterFactoryPtr>;
5706 using Listeners = std::vector<IReporterFactoryPtr>;
5707
5708 virtual ~IReporterRegistry();
5709 virtual IStreamingReporterPtr create( std::string const& name, IConfigPtr const& config ) const = 0;
5710 virtual FactoryMap const& getFactories() const = 0;
5711 virtual Listeners const& getListeners() const = 0;
5712 };
5713
5714 } // end namespace Catch
5715
5716 // end catch_interfaces_reporter.h
5717 #include <algorithm>
5718 #include <cstring>
5719 #include <cfloat>
5720 #include <cstdio>
5721 #include <cassert>
5722 #include <memory>
5723 #include <ostream>
5724
5725 namespace Catch {
5726 void prepareExpandedExpression(AssertionResult& result);
5727
5728 // Returns double formatted as %.3f (format expected on output)
5729 std::string getFormattedDuration( double duration );
5730
5731 //! Should the reporter show
5732 bool shouldShowDuration( IConfig const& config, double duration );
5733
5734 std::string serializeFilters( std::vector<std::string> const& container );
5735
5736 template<typename DerivedT>
5737 struct StreamingReporterBase : IStreamingReporter {
5738
StreamingReporterBaseCatch::StreamingReporterBase5739 StreamingReporterBase( ReporterConfig const& _config )
5740 : m_config( _config.fullConfig() ),
5741 stream( _config.stream() )
5742 {
5743 m_reporterPrefs.shouldRedirectStdOut = false;
5744 if( !DerivedT::getSupportedVerbosities().count( m_config->verbosity() ) )
5745 CATCH_ERROR( "Verbosity level not supported by this reporter" );
5746 }
5747
getPreferencesCatch::StreamingReporterBase5748 ReporterPreferences getPreferences() const override {
5749 return m_reporterPrefs;
5750 }
5751
getSupportedVerbositiesCatch::StreamingReporterBase5752 static std::set<Verbosity> getSupportedVerbosities() {
5753 return { Verbosity::Normal };
5754 }
5755
5756 ~StreamingReporterBase() override = default;
5757
noMatchingTestCasesCatch::StreamingReporterBase5758 void noMatchingTestCases(std::string const&) override {}
5759
reportInvalidArgumentsCatch::StreamingReporterBase5760 void reportInvalidArguments(std::string const&) override {}
5761
testRunStartingCatch::StreamingReporterBase5762 void testRunStarting(TestRunInfo const& _testRunInfo) override {
5763 currentTestRunInfo = _testRunInfo;
5764 }
5765
testGroupStartingCatch::StreamingReporterBase5766 void testGroupStarting(GroupInfo const& _groupInfo) override {
5767 currentGroupInfo = _groupInfo;
5768 }
5769
testCaseStartingCatch::StreamingReporterBase5770 void testCaseStarting(TestCaseInfo const& _testInfo) override {
5771 currentTestCaseInfo = _testInfo;
5772 }
sectionStartingCatch::StreamingReporterBase5773 void sectionStarting(SectionInfo const& _sectionInfo) override {
5774 m_sectionStack.push_back(_sectionInfo);
5775 }
5776
sectionEndedCatch::StreamingReporterBase5777 void sectionEnded(SectionStats const& /* _sectionStats */) override {
5778 m_sectionStack.pop_back();
5779 }
testCaseEndedCatch::StreamingReporterBase5780 void testCaseEnded(TestCaseStats const& /* _testCaseStats */) override {
5781 currentTestCaseInfo.reset();
5782 }
testGroupEndedCatch::StreamingReporterBase5783 void testGroupEnded(TestGroupStats const& /* _testGroupStats */) override {
5784 currentGroupInfo.reset();
5785 }
testRunEndedCatch::StreamingReporterBase5786 void testRunEnded(TestRunStats const& /* _testRunStats */) override {
5787 currentTestCaseInfo.reset();
5788 currentGroupInfo.reset();
5789 currentTestRunInfo.reset();
5790 }
5791
skipTestCatch::StreamingReporterBase5792 void skipTest(TestCaseInfo const&) override {
5793 // Don't do anything with this by default.
5794 // It can optionally be overridden in the derived class.
5795 }
5796
5797 IConfigPtr m_config;
5798 std::ostream& stream;
5799
5800 LazyStat<TestRunInfo> currentTestRunInfo;
5801 LazyStat<GroupInfo> currentGroupInfo;
5802 LazyStat<TestCaseInfo> currentTestCaseInfo;
5803
5804 std::vector<SectionInfo> m_sectionStack;
5805 ReporterPreferences m_reporterPrefs;
5806 };
5807
5808 template<typename DerivedT>
5809 struct CumulativeReporterBase : IStreamingReporter {
5810 template<typename T, typename ChildNodeT>
5811 struct Node {
NodeCatch::CumulativeReporterBase::Node5812 explicit Node( T const& _value ) : value( _value ) {}
~NodeCatch::CumulativeReporterBase::Node5813 virtual ~Node() {}
5814
5815 using ChildNodes = std::vector<std::shared_ptr<ChildNodeT>>;
5816 T value;
5817 ChildNodes children;
5818 };
5819 struct SectionNode {
SectionNodeCatch::CumulativeReporterBase::SectionNode5820 explicit SectionNode(SectionStats const& _stats) : stats(_stats) {}
5821 virtual ~SectionNode() = default;
5822
operator ==Catch::CumulativeReporterBase::SectionNode5823 bool operator == (SectionNode const& other) const {
5824 return stats.sectionInfo.lineInfo == other.stats.sectionInfo.lineInfo;
5825 }
operator ==Catch::CumulativeReporterBase::SectionNode5826 bool operator == (std::shared_ptr<SectionNode> const& other) const {
5827 return operator==(*other);
5828 }
5829
5830 SectionStats stats;
5831 using ChildSections = std::vector<std::shared_ptr<SectionNode>>;
5832 using Assertions = std::vector<AssertionStats>;
5833 ChildSections childSections;
5834 Assertions assertions;
5835 std::string stdOut;
5836 std::string stdErr;
5837 };
5838
5839 struct BySectionInfo {
BySectionInfoCatch::CumulativeReporterBase::BySectionInfo5840 BySectionInfo( SectionInfo const& other ) : m_other( other ) {}
BySectionInfoCatch::CumulativeReporterBase::BySectionInfo5841 BySectionInfo( BySectionInfo const& other ) : m_other( other.m_other ) {}
operator ()Catch::CumulativeReporterBase::BySectionInfo5842 bool operator() (std::shared_ptr<SectionNode> const& node) const {
5843 return ((node->stats.sectionInfo.name == m_other.name) &&
5844 (node->stats.sectionInfo.lineInfo == m_other.lineInfo));
5845 }
5846 void operator=(BySectionInfo const&) = delete;
5847
5848 private:
5849 SectionInfo const& m_other;
5850 };
5851
5852 using TestCaseNode = Node<TestCaseStats, SectionNode>;
5853 using TestGroupNode = Node<TestGroupStats, TestCaseNode>;
5854 using TestRunNode = Node<TestRunStats, TestGroupNode>;
5855
CumulativeReporterBaseCatch::CumulativeReporterBase5856 CumulativeReporterBase( ReporterConfig const& _config )
5857 : m_config( _config.fullConfig() ),
5858 stream( _config.stream() )
5859 {
5860 m_reporterPrefs.shouldRedirectStdOut = false;
5861 if( !DerivedT::getSupportedVerbosities().count( m_config->verbosity() ) )
5862 CATCH_ERROR( "Verbosity level not supported by this reporter" );
5863 }
5864 ~CumulativeReporterBase() override = default;
5865
getPreferencesCatch::CumulativeReporterBase5866 ReporterPreferences getPreferences() const override {
5867 return m_reporterPrefs;
5868 }
5869
getSupportedVerbositiesCatch::CumulativeReporterBase5870 static std::set<Verbosity> getSupportedVerbosities() {
5871 return { Verbosity::Normal };
5872 }
5873
testRunStartingCatch::CumulativeReporterBase5874 void testRunStarting( TestRunInfo const& ) override {}
testGroupStartingCatch::CumulativeReporterBase5875 void testGroupStarting( GroupInfo const& ) override {}
5876
testCaseStartingCatch::CumulativeReporterBase5877 void testCaseStarting( TestCaseInfo const& ) override {}
5878
sectionStartingCatch::CumulativeReporterBase5879 void sectionStarting( SectionInfo const& sectionInfo ) override {
5880 SectionStats incompleteStats( sectionInfo, Counts(), 0, false );
5881 std::shared_ptr<SectionNode> node;
5882 if( m_sectionStack.empty() ) {
5883 if( !m_rootSection )
5884 m_rootSection = std::make_shared<SectionNode>( incompleteStats );
5885 node = m_rootSection;
5886 }
5887 else {
5888 SectionNode& parentNode = *m_sectionStack.back();
5889 auto it =
5890 std::find_if( parentNode.childSections.begin(),
5891 parentNode.childSections.end(),
5892 BySectionInfo( sectionInfo ) );
5893 if( it == parentNode.childSections.end() ) {
5894 node = std::make_shared<SectionNode>( incompleteStats );
5895 parentNode.childSections.push_back( node );
5896 }
5897 else
5898 node = *it;
5899 }
5900 m_sectionStack.push_back( node );
5901 m_deepestSection = std::move(node);
5902 }
5903
assertionStartingCatch::CumulativeReporterBase5904 void assertionStarting(AssertionInfo const&) override {}
5905
assertionEndedCatch::CumulativeReporterBase5906 bool assertionEnded(AssertionStats const& assertionStats) override {
5907 assert(!m_sectionStack.empty());
5908 // AssertionResult holds a pointer to a temporary DecomposedExpression,
5909 // which getExpandedExpression() calls to build the expression string.
5910 // Our section stack copy of the assertionResult will likely outlive the
5911 // temporary, so it must be expanded or discarded now to avoid calling
5912 // a destroyed object later.
5913 prepareExpandedExpression(const_cast<AssertionResult&>( assertionStats.assertionResult ) );
5914 SectionNode& sectionNode = *m_sectionStack.back();
5915 sectionNode.assertions.push_back(assertionStats);
5916 return true;
5917 }
sectionEndedCatch::CumulativeReporterBase5918 void sectionEnded(SectionStats const& sectionStats) override {
5919 assert(!m_sectionStack.empty());
5920 SectionNode& node = *m_sectionStack.back();
5921 node.stats = sectionStats;
5922 m_sectionStack.pop_back();
5923 }
testCaseEndedCatch::CumulativeReporterBase5924 void testCaseEnded(TestCaseStats const& testCaseStats) override {
5925 auto node = std::make_shared<TestCaseNode>(testCaseStats);
5926 assert(m_sectionStack.size() == 0);
5927 node->children.push_back(m_rootSection);
5928 m_testCases.push_back(node);
5929 m_rootSection.reset();
5930
5931 assert(m_deepestSection);
5932 m_deepestSection->stdOut = testCaseStats.stdOut;
5933 m_deepestSection->stdErr = testCaseStats.stdErr;
5934 }
testGroupEndedCatch::CumulativeReporterBase5935 void testGroupEnded(TestGroupStats const& testGroupStats) override {
5936 auto node = std::make_shared<TestGroupNode>(testGroupStats);
5937 node->children.swap(m_testCases);
5938 m_testGroups.push_back(node);
5939 }
testRunEndedCatch::CumulativeReporterBase5940 void testRunEnded(TestRunStats const& testRunStats) override {
5941 auto node = std::make_shared<TestRunNode>(testRunStats);
5942 node->children.swap(m_testGroups);
5943 m_testRuns.push_back(node);
5944 testRunEndedCumulative();
5945 }
5946 virtual void testRunEndedCumulative() = 0;
5947
skipTestCatch::CumulativeReporterBase5948 void skipTest(TestCaseInfo const&) override {}
5949
5950 IConfigPtr m_config;
5951 std::ostream& stream;
5952 std::vector<AssertionStats> m_assertions;
5953 std::vector<std::vector<std::shared_ptr<SectionNode>>> m_sections;
5954 std::vector<std::shared_ptr<TestCaseNode>> m_testCases;
5955 std::vector<std::shared_ptr<TestGroupNode>> m_testGroups;
5956
5957 std::vector<std::shared_ptr<TestRunNode>> m_testRuns;
5958
5959 std::shared_ptr<SectionNode> m_rootSection;
5960 std::shared_ptr<SectionNode> m_deepestSection;
5961 std::vector<std::shared_ptr<SectionNode>> m_sectionStack;
5962 ReporterPreferences m_reporterPrefs;
5963 };
5964
5965 template<char C>
getLineOfChars()5966 char const* getLineOfChars() {
5967 static char line[CATCH_CONFIG_CONSOLE_WIDTH] = {0};
5968 if( !*line ) {
5969 std::memset( line, C, CATCH_CONFIG_CONSOLE_WIDTH-1 );
5970 line[CATCH_CONFIG_CONSOLE_WIDTH-1] = 0;
5971 }
5972 return line;
5973 }
5974
5975 struct TestEventListenerBase : StreamingReporterBase<TestEventListenerBase> {
5976 TestEventListenerBase( ReporterConfig const& _config );
5977
5978 static std::set<Verbosity> getSupportedVerbosities();
5979
5980 void assertionStarting(AssertionInfo const&) override;
5981 bool assertionEnded(AssertionStats const&) override;
5982 };
5983
5984 } // end namespace Catch
5985
5986 // end catch_reporter_bases.hpp
5987 // start catch_console_colour.h
5988
5989 namespace Catch {
5990
5991 struct Colour {
5992 enum Code {
5993 None = 0,
5994
5995 White,
5996 Red,
5997 Green,
5998 Blue,
5999 Cyan,
6000 Yellow,
6001 Grey,
6002
6003 Bright = 0x10,
6004
6005 BrightRed = Bright | Red,
6006 BrightGreen = Bright | Green,
6007 LightGrey = Bright | Grey,
6008 BrightWhite = Bright | White,
6009 BrightYellow = Bright | Yellow,
6010
6011 // By intention
6012 FileName = LightGrey,
6013 Warning = BrightYellow,
6014 ResultError = BrightRed,
6015 ResultSuccess = BrightGreen,
6016 ResultExpectedFailure = Warning,
6017
6018 Error = BrightRed,
6019 Success = Green,
6020
6021 OriginalExpression = Cyan,
6022 ReconstructedExpression = BrightYellow,
6023
6024 SecondaryText = LightGrey,
6025 Headers = White
6026 };
6027
6028 // Use constructed object for RAII guard
6029 Colour( Code _colourCode );
6030 Colour( Colour&& other ) noexcept;
6031 Colour& operator=( Colour&& other ) noexcept;
6032 ~Colour();
6033
6034 // Use static method for one-shot changes
6035 static void use( Code _colourCode );
6036
6037 private:
6038 bool m_moved = false;
6039 };
6040
6041 std::ostream& operator << ( std::ostream& os, Colour const& );
6042
6043 } // end namespace Catch
6044
6045 // end catch_console_colour.h
6046 // start catch_reporter_registrars.hpp
6047
6048
6049 namespace Catch {
6050
6051 template<typename T>
6052 class ReporterRegistrar {
6053
6054 class ReporterFactory : public IReporterFactory {
6055
create(ReporterConfig const & config) const6056 IStreamingReporterPtr create( ReporterConfig const& config ) const override {
6057 return std::unique_ptr<T>( new T( config ) );
6058 }
6059
getDescription() const6060 std::string getDescription() const override {
6061 return T::getDescription();
6062 }
6063 };
6064
6065 public:
6066
ReporterRegistrar(std::string const & name)6067 explicit ReporterRegistrar( std::string const& name ) {
6068 getMutableRegistryHub().registerReporter( name, std::make_shared<ReporterFactory>() );
6069 }
6070 };
6071
6072 template<typename T>
6073 class ListenerRegistrar {
6074
6075 class ListenerFactory : public IReporterFactory {
6076
create(ReporterConfig const & config) const6077 IStreamingReporterPtr create( ReporterConfig const& config ) const override {
6078 return std::unique_ptr<T>( new T( config ) );
6079 }
getDescription() const6080 std::string getDescription() const override {
6081 return std::string();
6082 }
6083 };
6084
6085 public:
6086
ListenerRegistrar()6087 ListenerRegistrar() {
6088 getMutableRegistryHub().registerListener( std::make_shared<ListenerFactory>() );
6089 }
6090 };
6091 }
6092
6093 #if !defined(CATCH_CONFIG_DISABLE)
6094
6095 #define CATCH_REGISTER_REPORTER( name, reporterType ) \
6096 CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \
6097 CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
6098 namespace{ Catch::ReporterRegistrar<reporterType> catch_internal_RegistrarFor##reporterType( name ); } \
6099 CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION
6100
6101 #define CATCH_REGISTER_LISTENER( listenerType ) \
6102 CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \
6103 CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
6104 namespace{ Catch::ListenerRegistrar<listenerType> catch_internal_RegistrarFor##listenerType; } \
6105 CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION
6106 #else // CATCH_CONFIG_DISABLE
6107
6108 #define CATCH_REGISTER_REPORTER(name, reporterType)
6109 #define CATCH_REGISTER_LISTENER(listenerType)
6110
6111 #endif // CATCH_CONFIG_DISABLE
6112
6113 // end catch_reporter_registrars.hpp
6114 // Allow users to base their work off existing reporters
6115 // start catch_reporter_compact.h
6116
6117 namespace Catch {
6118
6119 struct CompactReporter : StreamingReporterBase<CompactReporter> {
6120
6121 using StreamingReporterBase::StreamingReporterBase;
6122
6123 ~CompactReporter() override;
6124
6125 static std::string getDescription();
6126
6127 void noMatchingTestCases(std::string const& spec) override;
6128
6129 void assertionStarting(AssertionInfo const&) override;
6130
6131 bool assertionEnded(AssertionStats const& _assertionStats) override;
6132
6133 void sectionEnded(SectionStats const& _sectionStats) override;
6134
6135 void testRunEnded(TestRunStats const& _testRunStats) override;
6136
6137 };
6138
6139 } // end namespace Catch
6140
6141 // end catch_reporter_compact.h
6142 // start catch_reporter_console.h
6143
6144 #if defined(_MSC_VER)
6145 #pragma warning(push)
6146 #pragma warning(disable:4061) // Not all labels are EXPLICITLY handled in switch
6147 // Note that 4062 (not all labels are handled
6148 // and default is missing) is enabled
6149 #endif
6150
6151 namespace Catch {
6152 // Fwd decls
6153 struct SummaryColumn;
6154 class TablePrinter;
6155
6156 struct ConsoleReporter : StreamingReporterBase<ConsoleReporter> {
6157 std::unique_ptr<TablePrinter> m_tablePrinter;
6158
6159 ConsoleReporter(ReporterConfig const& config);
6160 ~ConsoleReporter() override;
6161 static std::string getDescription();
6162
6163 void noMatchingTestCases(std::string const& spec) override;
6164
6165 void reportInvalidArguments(std::string const&arg) override;
6166
6167 void assertionStarting(AssertionInfo const&) override;
6168
6169 bool assertionEnded(AssertionStats const& _assertionStats) override;
6170
6171 void sectionStarting(SectionInfo const& _sectionInfo) override;
6172 void sectionEnded(SectionStats const& _sectionStats) override;
6173
6174 #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
6175 void benchmarkPreparing(std::string const& name) override;
6176 void benchmarkStarting(BenchmarkInfo const& info) override;
6177 void benchmarkEnded(BenchmarkStats<> const& stats) override;
6178 void benchmarkFailed(std::string const& error) override;
6179 #endif // CATCH_CONFIG_ENABLE_BENCHMARKING
6180
6181 void testCaseEnded(TestCaseStats const& _testCaseStats) override;
6182 void testGroupEnded(TestGroupStats const& _testGroupStats) override;
6183 void testRunEnded(TestRunStats const& _testRunStats) override;
6184 void testRunStarting(TestRunInfo const& _testRunInfo) override;
6185 private:
6186
6187 void lazyPrint();
6188
6189 void lazyPrintWithoutClosingBenchmarkTable();
6190 void lazyPrintRunInfo();
6191 void lazyPrintGroupInfo();
6192 void printTestCaseAndSectionHeader();
6193
6194 void printClosedHeader(std::string const& _name);
6195 void printOpenHeader(std::string const& _name);
6196
6197 // if string has a : in first line will set indent to follow it on
6198 // subsequent lines
6199 void printHeaderString(std::string const& _string, std::size_t indent = 0);
6200
6201 void printTotals(Totals const& totals);
6202 void printSummaryRow(std::string const& label, std::vector<SummaryColumn> const& cols, std::size_t row);
6203
6204 void printTotalsDivider(Totals const& totals);
6205 void printSummaryDivider();
6206 void printTestFilters();
6207
6208 private:
6209 bool m_headerPrinted = false;
6210 };
6211
6212 } // end namespace Catch
6213
6214 #if defined(_MSC_VER)
6215 #pragma warning(pop)
6216 #endif
6217
6218 // end catch_reporter_console.h
6219 // start catch_reporter_junit.h
6220
6221 // start catch_xmlwriter.h
6222
6223 #include <vector>
6224
6225 namespace Catch {
6226 enum class XmlFormatting {
6227 None = 0x00,
6228 Indent = 0x01,
6229 Newline = 0x02,
6230 };
6231
6232 XmlFormatting operator | (XmlFormatting lhs, XmlFormatting rhs);
6233 XmlFormatting operator & (XmlFormatting lhs, XmlFormatting rhs);
6234
6235 class XmlEncode {
6236 public:
6237 enum ForWhat { ForTextNodes, ForAttributes };
6238
6239 XmlEncode( std::string const& str, ForWhat forWhat = ForTextNodes );
6240
6241 void encodeTo( std::ostream& os ) const;
6242
6243 friend std::ostream& operator << ( std::ostream& os, XmlEncode const& xmlEncode );
6244
6245 private:
6246 std::string m_str;
6247 ForWhat m_forWhat;
6248 };
6249
6250 class XmlWriter {
6251 public:
6252
6253 class ScopedElement {
6254 public:
6255 ScopedElement( XmlWriter* writer, XmlFormatting fmt );
6256
6257 ScopedElement( ScopedElement&& other ) noexcept;
6258 ScopedElement& operator=( ScopedElement&& other ) noexcept;
6259
6260 ~ScopedElement();
6261
6262 ScopedElement& writeText( std::string const& text, XmlFormatting fmt = XmlFormatting::Newline | XmlFormatting::Indent );
6263
6264 template<typename T>
writeAttribute(std::string const & name,T const & attribute)6265 ScopedElement& writeAttribute( std::string const& name, T const& attribute ) {
6266 m_writer->writeAttribute( name, attribute );
6267 return *this;
6268 }
6269
6270 private:
6271 mutable XmlWriter* m_writer = nullptr;
6272 XmlFormatting m_fmt;
6273 };
6274
6275 XmlWriter( std::ostream& os = Catch::cout() );
6276 ~XmlWriter();
6277
6278 XmlWriter( XmlWriter const& ) = delete;
6279 XmlWriter& operator=( XmlWriter const& ) = delete;
6280
6281 XmlWriter& startElement( std::string const& name, XmlFormatting fmt = XmlFormatting::Newline | XmlFormatting::Indent);
6282
6283 ScopedElement scopedElement( std::string const& name, XmlFormatting fmt = XmlFormatting::Newline | XmlFormatting::Indent);
6284
6285 XmlWriter& endElement(XmlFormatting fmt = XmlFormatting::Newline | XmlFormatting::Indent);
6286
6287 XmlWriter& writeAttribute( std::string const& name, std::string const& attribute );
6288
6289 XmlWriter& writeAttribute( std::string const& name, bool attribute );
6290
6291 template<typename T>
writeAttribute(std::string const & name,T const & attribute)6292 XmlWriter& writeAttribute( std::string const& name, T const& attribute ) {
6293 ReusableStringStream rss;
6294 rss << attribute;
6295 return writeAttribute( name, rss.str() );
6296 }
6297
6298 XmlWriter& writeText( std::string const& text, XmlFormatting fmt = XmlFormatting::Newline | XmlFormatting::Indent);
6299
6300 XmlWriter& writeComment(std::string const& text, XmlFormatting fmt = XmlFormatting::Newline | XmlFormatting::Indent);
6301
6302 void writeStylesheetRef( std::string const& url );
6303
6304 XmlWriter& writeBlankLine();
6305
6306 void ensureTagClosed();
6307
6308 private:
6309
6310 void applyFormatting(XmlFormatting fmt);
6311
6312 void writeDeclaration();
6313
6314 void newlineIfNecessary();
6315
6316 bool m_tagIsOpen = false;
6317 bool m_needsNewline = false;
6318 std::vector<std::string> m_tags;
6319 std::string m_indent;
6320 std::ostream& m_os;
6321 };
6322
6323 }
6324
6325 // end catch_xmlwriter.h
6326 namespace Catch {
6327
6328 class JunitReporter : public CumulativeReporterBase<JunitReporter> {
6329 public:
6330 JunitReporter(ReporterConfig const& _config);
6331
6332 ~JunitReporter() override;
6333
6334 static std::string getDescription();
6335
6336 void noMatchingTestCases(std::string const& /*spec*/) override;
6337
6338 void testRunStarting(TestRunInfo const& runInfo) override;
6339
6340 void testGroupStarting(GroupInfo const& groupInfo) override;
6341
6342 void testCaseStarting(TestCaseInfo const& testCaseInfo) override;
6343 bool assertionEnded(AssertionStats const& assertionStats) override;
6344
6345 void testCaseEnded(TestCaseStats const& testCaseStats) override;
6346
6347 void testGroupEnded(TestGroupStats const& testGroupStats) override;
6348
6349 void testRunEndedCumulative() override;
6350
6351 void writeGroup(TestGroupNode const& groupNode, double suiteTime);
6352
6353 void writeTestCase(TestCaseNode const& testCaseNode);
6354
6355 void writeSection( std::string const& className,
6356 std::string const& rootName,
6357 SectionNode const& sectionNode,
6358 bool testOkToFail );
6359
6360 void writeAssertions(SectionNode const& sectionNode);
6361 void writeAssertion(AssertionStats const& stats);
6362
6363 XmlWriter xml;
6364 Timer suiteTimer;
6365 std::string stdOutForSuite;
6366 std::string stdErrForSuite;
6367 unsigned int unexpectedExceptions = 0;
6368 bool m_okToFail = false;
6369 };
6370
6371 } // end namespace Catch
6372
6373 // end catch_reporter_junit.h
6374 // start catch_reporter_xml.h
6375
6376 namespace Catch {
6377 class XmlReporter : public StreamingReporterBase<XmlReporter> {
6378 public:
6379 XmlReporter(ReporterConfig const& _config);
6380
6381 ~XmlReporter() override;
6382
6383 static std::string getDescription();
6384
6385 virtual std::string getStylesheetRef() const;
6386
6387 void writeSourceInfo(SourceLineInfo const& sourceInfo);
6388
6389 public: // StreamingReporterBase
6390
6391 void noMatchingTestCases(std::string const& s) override;
6392
6393 void testRunStarting(TestRunInfo const& testInfo) override;
6394
6395 void testGroupStarting(GroupInfo const& groupInfo) override;
6396
6397 void testCaseStarting(TestCaseInfo const& testInfo) override;
6398
6399 void sectionStarting(SectionInfo const& sectionInfo) override;
6400
6401 void assertionStarting(AssertionInfo const&) override;
6402
6403 bool assertionEnded(AssertionStats const& assertionStats) override;
6404
6405 void sectionEnded(SectionStats const& sectionStats) override;
6406
6407 void testCaseEnded(TestCaseStats const& testCaseStats) override;
6408
6409 void testGroupEnded(TestGroupStats const& testGroupStats) override;
6410
6411 void testRunEnded(TestRunStats const& testRunStats) override;
6412
6413 #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
6414 void benchmarkPreparing(std::string const& name) override;
6415 void benchmarkStarting(BenchmarkInfo const&) override;
6416 void benchmarkEnded(BenchmarkStats<> const&) override;
6417 void benchmarkFailed(std::string const&) override;
6418 #endif // CATCH_CONFIG_ENABLE_BENCHMARKING
6419
6420 private:
6421 Timer m_testCaseTimer;
6422 XmlWriter m_xml;
6423 int m_sectionDepth = 0;
6424 };
6425
6426 } // end namespace Catch
6427
6428 // end catch_reporter_xml.h
6429
6430 // end catch_external_interfaces.h
6431 #endif
6432
6433 #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
6434 // start catch_benchmarking_all.hpp
6435
6436 // A proxy header that includes all of the benchmarking headers to allow
6437 // concise include of the benchmarking features. You should prefer the
6438 // individual includes in standard use.
6439
6440 // start catch_benchmark.hpp
6441
6442 // Benchmark
6443
6444 // start catch_chronometer.hpp
6445
6446 // User-facing chronometer
6447
6448
6449 // start catch_clock.hpp
6450
6451 // Clocks
6452
6453
6454 #include <chrono>
6455 #include <ratio>
6456
6457 namespace Catch {
6458 namespace Benchmark {
6459 template <typename Clock>
6460 using ClockDuration = typename Clock::duration;
6461 template <typename Clock>
6462 using FloatDuration = std::chrono::duration<double, typename Clock::period>;
6463
6464 template <typename Clock>
6465 using TimePoint = typename Clock::time_point;
6466
6467 using default_clock = std::chrono::steady_clock;
6468
6469 template <typename Clock>
6470 struct now {
operator ()Catch::Benchmark::now6471 TimePoint<Clock> operator()() const {
6472 return Clock::now();
6473 }
6474 };
6475
6476 using fp_seconds = std::chrono::duration<double, std::ratio<1>>;
6477 } // namespace Benchmark
6478 } // namespace Catch
6479
6480 // end catch_clock.hpp
6481 // start catch_optimizer.hpp
6482
6483 // Hinting the optimizer
6484
6485
6486 #if defined(_MSC_VER)
6487 # include <atomic> // atomic_thread_fence
6488 #endif
6489
6490 namespace Catch {
6491 namespace Benchmark {
6492 #if defined(__GNUC__) || defined(__clang__)
6493 template <typename T>
keep_memory(T * p)6494 inline void keep_memory(T* p) {
6495 asm volatile("" : : "g"(p) : "memory");
6496 }
keep_memory()6497 inline void keep_memory() {
6498 asm volatile("" : : : "memory");
6499 }
6500
6501 namespace Detail {
optimizer_barrier()6502 inline void optimizer_barrier() { keep_memory(); }
6503 } // namespace Detail
6504 #elif defined(_MSC_VER)
6505
6506 #pragma optimize("", off)
6507 template <typename T>
6508 inline void keep_memory(T* p) {
6509 // thanks @milleniumbug
6510 *reinterpret_cast<char volatile*>(p) = *reinterpret_cast<char const volatile*>(p);
6511 }
6512 // TODO equivalent keep_memory()
6513 #pragma optimize("", on)
6514
6515 namespace Detail {
6516 inline void optimizer_barrier() {
6517 std::atomic_thread_fence(std::memory_order_seq_cst);
6518 }
6519 } // namespace Detail
6520
6521 #endif
6522
6523 template <typename T>
deoptimize_value(T && x)6524 inline void deoptimize_value(T&& x) {
6525 keep_memory(&x);
6526 }
6527
6528 template <typename Fn, typename... Args>
invoke_deoptimized(Fn && fn,Args &&...args)6529 inline auto invoke_deoptimized(Fn&& fn, Args&&... args) -> typename std::enable_if<!std::is_same<void, decltype(fn(args...))>::value>::type {
6530 deoptimize_value(std::forward<Fn>(fn) (std::forward<Args...>(args...)));
6531 }
6532
6533 template <typename Fn, typename... Args>
invoke_deoptimized(Fn && fn,Args &&...args)6534 inline auto invoke_deoptimized(Fn&& fn, Args&&... args) -> typename std::enable_if<std::is_same<void, decltype(fn(args...))>::value>::type {
6535 std::forward<Fn>(fn) (std::forward<Args...>(args...));
6536 }
6537 } // namespace Benchmark
6538 } // namespace Catch
6539
6540 // end catch_optimizer.hpp
6541 // start catch_complete_invoke.hpp
6542
6543 // Invoke with a special case for void
6544
6545
6546 #include <type_traits>
6547 #include <utility>
6548
6549 namespace Catch {
6550 namespace Benchmark {
6551 namespace Detail {
6552 template <typename T>
6553 struct CompleteType { using type = T; };
6554 template <>
6555 struct CompleteType<void> { struct type {}; };
6556
6557 template <typename T>
6558 using CompleteType_t = typename CompleteType<T>::type;
6559
6560 template <typename Result>
6561 struct CompleteInvoker {
6562 template <typename Fun, typename... Args>
invokeCatch::Benchmark::Detail::CompleteInvoker6563 static Result invoke(Fun&& fun, Args&&... args) {
6564 return std::forward<Fun>(fun)(std::forward<Args>(args)...);
6565 }
6566 };
6567 template <>
6568 struct CompleteInvoker<void> {
6569 template <typename Fun, typename... Args>
invokeCatch::Benchmark::Detail::CompleteInvoker6570 static CompleteType_t<void> invoke(Fun&& fun, Args&&... args) {
6571 std::forward<Fun>(fun)(std::forward<Args>(args)...);
6572 return {};
6573 }
6574 };
6575
6576 // invoke and not return void :(
6577 template <typename Fun, typename... Args>
complete_invoke(Fun && fun,Args &&...args)6578 CompleteType_t<FunctionReturnType<Fun, Args...>> complete_invoke(Fun&& fun, Args&&... args) {
6579 return CompleteInvoker<FunctionReturnType<Fun, Args...>>::invoke(std::forward<Fun>(fun), std::forward<Args>(args)...);
6580 }
6581
6582 const std::string benchmarkErrorMsg = "a benchmark failed to run successfully";
6583 } // namespace Detail
6584
6585 template <typename Fun>
user_code(Fun && fun)6586 Detail::CompleteType_t<FunctionReturnType<Fun>> user_code(Fun&& fun) {
6587 CATCH_TRY{
6588 return Detail::complete_invoke(std::forward<Fun>(fun));
6589 } CATCH_CATCH_ALL{
6590 getResultCapture().benchmarkFailed(translateActiveException());
6591 CATCH_RUNTIME_ERROR(Detail::benchmarkErrorMsg);
6592 }
6593 }
6594 } // namespace Benchmark
6595 } // namespace Catch
6596
6597 // end catch_complete_invoke.hpp
6598 namespace Catch {
6599 namespace Benchmark {
6600 namespace Detail {
6601 struct ChronometerConcept {
6602 virtual void start() = 0;
6603 virtual void finish() = 0;
6604 virtual ~ChronometerConcept() = default;
6605 };
6606 template <typename Clock>
6607 struct ChronometerModel final : public ChronometerConcept {
startCatch::Benchmark::Detail::ChronometerModel6608 void start() override { started = Clock::now(); }
finishCatch::Benchmark::Detail::ChronometerModel6609 void finish() override { finished = Clock::now(); }
6610
elapsedCatch::Benchmark::Detail::ChronometerModel6611 ClockDuration<Clock> elapsed() const { return finished - started; }
6612
6613 TimePoint<Clock> started;
6614 TimePoint<Clock> finished;
6615 };
6616 } // namespace Detail
6617
6618 struct Chronometer {
6619 public:
6620 template <typename Fun>
measureCatch::Benchmark::Chronometer6621 void measure(Fun&& fun) { measure(std::forward<Fun>(fun), is_callable<Fun(int)>()); }
6622
runsCatch::Benchmark::Chronometer6623 int runs() const { return k; }
6624
ChronometerCatch::Benchmark::Chronometer6625 Chronometer(Detail::ChronometerConcept& meter, int k)
6626 : impl(&meter)
6627 , k(k) {}
6628
6629 private:
6630 template <typename Fun>
measureCatch::Benchmark::Chronometer6631 void measure(Fun&& fun, std::false_type) {
6632 measure([&fun](int) { return fun(); }, std::true_type());
6633 }
6634
6635 template <typename Fun>
measureCatch::Benchmark::Chronometer6636 void measure(Fun&& fun, std::true_type) {
6637 Detail::optimizer_barrier();
6638 impl->start();
6639 for (int i = 0; i < k; ++i) invoke_deoptimized(fun, i);
6640 impl->finish();
6641 Detail::optimizer_barrier();
6642 }
6643
6644 Detail::ChronometerConcept* impl;
6645 int k;
6646 };
6647 } // namespace Benchmark
6648 } // namespace Catch
6649
6650 // end catch_chronometer.hpp
6651 // start catch_environment.hpp
6652
6653 // Environment information
6654
6655
6656 namespace Catch {
6657 namespace Benchmark {
6658 template <typename Duration>
6659 struct EnvironmentEstimate {
6660 Duration mean;
6661 OutlierClassification outliers;
6662
6663 template <typename Duration2>
operator EnvironmentEstimate<Duration2>Catch::Benchmark::EnvironmentEstimate6664 operator EnvironmentEstimate<Duration2>() const {
6665 return { mean, outliers };
6666 }
6667 };
6668 template <typename Clock>
6669 struct Environment {
6670 using clock_type = Clock;
6671 EnvironmentEstimate<FloatDuration<Clock>> clock_resolution;
6672 EnvironmentEstimate<FloatDuration<Clock>> clock_cost;
6673 };
6674 } // namespace Benchmark
6675 } // namespace Catch
6676
6677 // end catch_environment.hpp
6678 // start catch_execution_plan.hpp
6679
6680 // Execution plan
6681
6682
6683 // start catch_benchmark_function.hpp
6684
6685 // Dumb std::function implementation for consistent call overhead
6686
6687
6688 #include <cassert>
6689 #include <type_traits>
6690 #include <utility>
6691 #include <memory>
6692
6693 namespace Catch {
6694 namespace Benchmark {
6695 namespace Detail {
6696 template <typename T>
6697 using Decay = typename std::decay<T>::type;
6698 template <typename T, typename U>
6699 struct is_related
6700 : std::is_same<Decay<T>, Decay<U>> {};
6701
6702 /// We need to reinvent std::function because every piece of code that might add overhead
6703 /// in a measurement context needs to have consistent performance characteristics so that we
6704 /// can account for it in the measurement.
6705 /// Implementations of std::function with optimizations that aren't always applicable, like
6706 /// small buffer optimizations, are not uncommon.
6707 /// This is effectively an implementation of std::function without any such optimizations;
6708 /// it may be slow, but it is consistently slow.
6709 struct BenchmarkFunction {
6710 private:
6711 struct callable {
6712 virtual void call(Chronometer meter) const = 0;
6713 virtual callable* clone() const = 0;
6714 virtual ~callable() = default;
6715 };
6716 template <typename Fun>
6717 struct model : public callable {
modelCatch::Benchmark::Detail::BenchmarkFunction::model6718 model(Fun&& fun) : fun(std::move(fun)) {}
modelCatch::Benchmark::Detail::BenchmarkFunction::model6719 model(Fun const& fun) : fun(fun) {}
6720
cloneCatch::Benchmark::Detail::BenchmarkFunction::model6721 model<Fun>* clone() const override { return new model<Fun>(*this); }
6722
callCatch::Benchmark::Detail::BenchmarkFunction::model6723 void call(Chronometer meter) const override {
6724 call(meter, is_callable<Fun(Chronometer)>());
6725 }
callCatch::Benchmark::Detail::BenchmarkFunction::model6726 void call(Chronometer meter, std::true_type) const {
6727 fun(meter);
6728 }
callCatch::Benchmark::Detail::BenchmarkFunction::model6729 void call(Chronometer meter, std::false_type) const {
6730 meter.measure(fun);
6731 }
6732
6733 Fun fun;
6734 };
6735
operator ()Catch::Benchmark::Detail::BenchmarkFunction::do_nothing6736 struct do_nothing { void operator()() const {} };
6737
6738 template <typename T>
BenchmarkFunctionCatch::Benchmark::Detail::BenchmarkFunction6739 BenchmarkFunction(model<T>* c) : f(c) {}
6740
6741 public:
BenchmarkFunctionCatch::Benchmark::Detail::BenchmarkFunction6742 BenchmarkFunction()
6743 : f(new model<do_nothing>{ {} }) {}
6744
6745 template <typename Fun,
6746 typename std::enable_if<!is_related<Fun, BenchmarkFunction>::value, int>::type = 0>
BenchmarkFunctionCatch::Benchmark::Detail::BenchmarkFunction6747 BenchmarkFunction(Fun&& fun)
6748 : f(new model<typename std::decay<Fun>::type>(std::forward<Fun>(fun))) {}
6749
BenchmarkFunctionCatch::Benchmark::Detail::BenchmarkFunction6750 BenchmarkFunction(BenchmarkFunction&& that)
6751 : f(std::move(that.f)) {}
6752
BenchmarkFunctionCatch::Benchmark::Detail::BenchmarkFunction6753 BenchmarkFunction(BenchmarkFunction const& that)
6754 : f(that.f->clone()) {}
6755
operator =Catch::Benchmark::Detail::BenchmarkFunction6756 BenchmarkFunction& operator=(BenchmarkFunction&& that) {
6757 f = std::move(that.f);
6758 return *this;
6759 }
6760
operator =Catch::Benchmark::Detail::BenchmarkFunction6761 BenchmarkFunction& operator=(BenchmarkFunction const& that) {
6762 f.reset(that.f->clone());
6763 return *this;
6764 }
6765
operator ()Catch::Benchmark::Detail::BenchmarkFunction6766 void operator()(Chronometer meter) const { f->call(meter); }
6767
6768 private:
6769 std::unique_ptr<callable> f;
6770 };
6771 } // namespace Detail
6772 } // namespace Benchmark
6773 } // namespace Catch
6774
6775 // end catch_benchmark_function.hpp
6776 // start catch_repeat.hpp
6777
6778 // repeat algorithm
6779
6780
6781 #include <type_traits>
6782 #include <utility>
6783
6784 namespace Catch {
6785 namespace Benchmark {
6786 namespace Detail {
6787 template <typename Fun>
6788 struct repeater {
operator ()Catch::Benchmark::Detail::repeater6789 void operator()(int k) const {
6790 for (int i = 0; i < k; ++i) {
6791 fun();
6792 }
6793 }
6794 Fun fun;
6795 };
6796 template <typename Fun>
repeat(Fun && fun)6797 repeater<typename std::decay<Fun>::type> repeat(Fun&& fun) {
6798 return { std::forward<Fun>(fun) };
6799 }
6800 } // namespace Detail
6801 } // namespace Benchmark
6802 } // namespace Catch
6803
6804 // end catch_repeat.hpp
6805 // start catch_run_for_at_least.hpp
6806
6807 // Run a function for a minimum amount of time
6808
6809
6810 // start catch_measure.hpp
6811
6812 // Measure
6813
6814
6815 // start catch_timing.hpp
6816
6817 // Timing
6818
6819
6820 #include <tuple>
6821 #include <type_traits>
6822
6823 namespace Catch {
6824 namespace Benchmark {
6825 template <typename Duration, typename Result>
6826 struct Timing {
6827 Duration elapsed;
6828 Result result;
6829 int iterations;
6830 };
6831 template <typename Clock, typename Func, typename... Args>
6832 using TimingOf = Timing<ClockDuration<Clock>, Detail::CompleteType_t<FunctionReturnType<Func, Args...>>>;
6833 } // namespace Benchmark
6834 } // namespace Catch
6835
6836 // end catch_timing.hpp
6837 #include <utility>
6838
6839 namespace Catch {
6840 namespace Benchmark {
6841 namespace Detail {
6842 template <typename Clock, typename Fun, typename... Args>
measure(Fun && fun,Args &&...args)6843 TimingOf<Clock, Fun, Args...> measure(Fun&& fun, Args&&... args) {
6844 auto start = Clock::now();
6845 auto&& r = Detail::complete_invoke(fun, std::forward<Args>(args)...);
6846 auto end = Clock::now();
6847 auto delta = end - start;
6848 return { delta, std::forward<decltype(r)>(r), 1 };
6849 }
6850 } // namespace Detail
6851 } // namespace Benchmark
6852 } // namespace Catch
6853
6854 // end catch_measure.hpp
6855 #include <utility>
6856 #include <type_traits>
6857
6858 namespace Catch {
6859 namespace Benchmark {
6860 namespace Detail {
6861 template <typename Clock, typename Fun>
measure_one(Fun && fun,int iters,std::false_type)6862 TimingOf<Clock, Fun, int> measure_one(Fun&& fun, int iters, std::false_type) {
6863 return Detail::measure<Clock>(fun, iters);
6864 }
6865 template <typename Clock, typename Fun>
measure_one(Fun && fun,int iters,std::true_type)6866 TimingOf<Clock, Fun, Chronometer> measure_one(Fun&& fun, int iters, std::true_type) {
6867 Detail::ChronometerModel<Clock> meter;
6868 auto&& result = Detail::complete_invoke(fun, Chronometer(meter, iters));
6869
6870 return { meter.elapsed(), std::move(result), iters };
6871 }
6872
6873 template <typename Clock, typename Fun>
6874 using run_for_at_least_argument_t = typename std::conditional<is_callable<Fun(Chronometer)>::value, Chronometer, int>::type;
6875
6876 struct optimized_away_error : std::exception {
whatCatch::Benchmark::Detail::optimized_away_error6877 const char* what() const noexcept override {
6878 return "could not measure benchmark, maybe it was optimized away";
6879 }
6880 };
6881
6882 template <typename Clock, typename Fun>
run_for_at_least(ClockDuration<Clock> how_long,int seed,Fun && fun)6883 TimingOf<Clock, Fun, run_for_at_least_argument_t<Clock, Fun>> run_for_at_least(ClockDuration<Clock> how_long, int seed, Fun&& fun) {
6884 auto iters = seed;
6885 while (iters < (1 << 30)) {
6886 auto&& Timing = measure_one<Clock>(fun, iters, is_callable<Fun(Chronometer)>());
6887
6888 if (Timing.elapsed >= how_long) {
6889 return { Timing.elapsed, std::move(Timing.result), iters };
6890 }
6891 iters *= 2;
6892 }
6893 Catch::throw_exception(optimized_away_error{});
6894 }
6895 } // namespace Detail
6896 } // namespace Benchmark
6897 } // namespace Catch
6898
6899 // end catch_run_for_at_least.hpp
6900 #include <algorithm>
6901 #include <iterator>
6902
6903 namespace Catch {
6904 namespace Benchmark {
6905 template <typename Duration>
6906 struct ExecutionPlan {
6907 int iterations_per_sample;
6908 Duration estimated_duration;
6909 Detail::BenchmarkFunction benchmark;
6910 Duration warmup_time;
6911 int warmup_iterations;
6912
6913 template <typename Duration2>
operator ExecutionPlan<Duration2>Catch::Benchmark::ExecutionPlan6914 operator ExecutionPlan<Duration2>() const {
6915 return { iterations_per_sample, estimated_duration, benchmark, warmup_time, warmup_iterations };
6916 }
6917
6918 template <typename Clock>
runCatch::Benchmark::ExecutionPlan6919 std::vector<FloatDuration<Clock>> run(const IConfig &cfg, Environment<FloatDuration<Clock>> env) const {
6920 // warmup a bit
6921 Detail::run_for_at_least<Clock>(std::chrono::duration_cast<ClockDuration<Clock>>(warmup_time), warmup_iterations, Detail::repeat(now<Clock>{}));
6922
6923 std::vector<FloatDuration<Clock>> times;
6924 times.reserve(cfg.benchmarkSamples());
6925 std::generate_n(std::back_inserter(times), cfg.benchmarkSamples(), [this, env] {
6926 Detail::ChronometerModel<Clock> model;
6927 this->benchmark(Chronometer(model, iterations_per_sample));
6928 auto sample_time = model.elapsed() - env.clock_cost.mean;
6929 if (sample_time < FloatDuration<Clock>::zero()) sample_time = FloatDuration<Clock>::zero();
6930 return sample_time / iterations_per_sample;
6931 });
6932 return times;
6933 }
6934 };
6935 } // namespace Benchmark
6936 } // namespace Catch
6937
6938 // end catch_execution_plan.hpp
6939 // start catch_estimate_clock.hpp
6940
6941 // Environment measurement
6942
6943
6944 // start catch_stats.hpp
6945
6946 // Statistical analysis tools
6947
6948
6949 #include <algorithm>
6950 #include <functional>
6951 #include <vector>
6952 #include <iterator>
6953 #include <numeric>
6954 #include <tuple>
6955 #include <cmath>
6956 #include <utility>
6957 #include <cstddef>
6958 #include <random>
6959
6960 namespace Catch {
6961 namespace Benchmark {
6962 namespace Detail {
6963 using sample = std::vector<double>;
6964
6965 double weighted_average_quantile(int k, int q, std::vector<double>::iterator first, std::vector<double>::iterator last);
6966
6967 template <typename Iterator>
classify_outliers(Iterator first,Iterator last)6968 OutlierClassification classify_outliers(Iterator first, Iterator last) {
6969 std::vector<double> copy(first, last);
6970
6971 auto q1 = weighted_average_quantile(1, 4, copy.begin(), copy.end());
6972 auto q3 = weighted_average_quantile(3, 4, copy.begin(), copy.end());
6973 auto iqr = q3 - q1;
6974 auto los = q1 - (iqr * 3.);
6975 auto lom = q1 - (iqr * 1.5);
6976 auto him = q3 + (iqr * 1.5);
6977 auto his = q3 + (iqr * 3.);
6978
6979 OutlierClassification o;
6980 for (; first != last; ++first) {
6981 auto&& t = *first;
6982 if (t < los) ++o.low_severe;
6983 else if (t < lom) ++o.low_mild;
6984 else if (t > his) ++o.high_severe;
6985 else if (t > him) ++o.high_mild;
6986 ++o.samples_seen;
6987 }
6988 return o;
6989 }
6990
6991 template <typename Iterator>
mean(Iterator first,Iterator last)6992 double mean(Iterator first, Iterator last) {
6993 auto count = last - first;
6994 double sum = std::accumulate(first, last, 0.);
6995 return sum / count;
6996 }
6997
6998 template <typename URng, typename Iterator, typename Estimator>
resample(URng & rng,int resamples,Iterator first,Iterator last,Estimator & estimator)6999 sample resample(URng& rng, int resamples, Iterator first, Iterator last, Estimator& estimator) {
7000 auto n = last - first;
7001 std::uniform_int_distribution<decltype(n)> dist(0, n - 1);
7002
7003 sample out;
7004 out.reserve(resamples);
7005 std::generate_n(std::back_inserter(out), resamples, [n, first, &estimator, &dist, &rng] {
7006 std::vector<double> resampled;
7007 resampled.reserve(n);
7008 std::generate_n(std::back_inserter(resampled), n, [first, &dist, &rng] { return first[dist(rng)]; });
7009 return estimator(resampled.begin(), resampled.end());
7010 });
7011 std::sort(out.begin(), out.end());
7012 return out;
7013 }
7014
7015 template <typename Estimator, typename Iterator>
jackknife(Estimator && estimator,Iterator first,Iterator last)7016 sample jackknife(Estimator&& estimator, Iterator first, Iterator last) {
7017 auto n = last - first;
7018 auto second = std::next(first);
7019 sample results;
7020 results.reserve(n);
7021
7022 for (auto it = first; it != last; ++it) {
7023 std::iter_swap(it, first);
7024 results.push_back(estimator(second, last));
7025 }
7026
7027 return results;
7028 }
7029
normal_cdf(double x)7030 inline double normal_cdf(double x) {
7031 return std::erfc(-x / std::sqrt(2.0)) / 2.0;
7032 }
7033
7034 double erfc_inv(double x);
7035
7036 double normal_quantile(double p);
7037
7038 template <typename Iterator, typename Estimator>
bootstrap(double confidence_level,Iterator first,Iterator last,sample const & resample,Estimator && estimator)7039 Estimate<double> bootstrap(double confidence_level, Iterator first, Iterator last, sample const& resample, Estimator&& estimator) {
7040 auto n_samples = last - first;
7041
7042 double point = estimator(first, last);
7043 // Degenerate case with a single sample
7044 if (n_samples == 1) return { point, point, point, confidence_level };
7045
7046 sample jack = jackknife(estimator, first, last);
7047 double jack_mean = mean(jack.begin(), jack.end());
7048 double sum_squares, sum_cubes;
7049 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> {
7050 auto d = jack_mean - x;
7051 auto d2 = d * d;
7052 auto d3 = d2 * d;
7053 return { sqcb.first + d2, sqcb.second + d3 };
7054 });
7055
7056 double accel = sum_cubes / (6 * std::pow(sum_squares, 1.5));
7057 int n = static_cast<int>(resample.size());
7058 double prob_n = std::count_if(resample.begin(), resample.end(), [point](double x) { return x < point; }) / (double)n;
7059 // degenerate case with uniform samples
7060 if (prob_n == 0) return { point, point, point, confidence_level };
7061
7062 double bias = normal_quantile(prob_n);
7063 double z1 = normal_quantile((1. - confidence_level) / 2.);
7064
7065 auto cumn = [n](double x) -> int {
7066 return std::lround(normal_cdf(x) * n); };
7067 auto a = [bias, accel](double b) { return bias + b / (1. - accel * b); };
7068 double b1 = bias + z1;
7069 double b2 = bias - z1;
7070 double a1 = a(b1);
7071 double a2 = a(b2);
7072 auto lo = (std::max)(cumn(a1), 0);
7073 auto hi = (std::min)(cumn(a2), n - 1);
7074
7075 return { point, resample[lo], resample[hi], confidence_level };
7076 }
7077
7078 double outlier_variance(Estimate<double> mean, Estimate<double> stddev, int n);
7079
7080 struct bootstrap_analysis {
7081 Estimate<double> mean;
7082 Estimate<double> standard_deviation;
7083 double outlier_variance;
7084 };
7085
7086 bootstrap_analysis analyse_samples(double confidence_level, int n_resamples, std::vector<double>::iterator first, std::vector<double>::iterator last);
7087 } // namespace Detail
7088 } // namespace Benchmark
7089 } // namespace Catch
7090
7091 // end catch_stats.hpp
7092 #include <algorithm>
7093 #include <iterator>
7094 #include <tuple>
7095 #include <vector>
7096 #include <cmath>
7097
7098 namespace Catch {
7099 namespace Benchmark {
7100 namespace Detail {
7101 template <typename Clock>
resolution(int k)7102 std::vector<double> resolution(int k) {
7103 std::vector<TimePoint<Clock>> times;
7104 times.reserve(k + 1);
7105 std::generate_n(std::back_inserter(times), k + 1, now<Clock>{});
7106
7107 std::vector<double> deltas;
7108 deltas.reserve(k);
7109 std::transform(std::next(times.begin()), times.end(), times.begin(),
7110 std::back_inserter(deltas),
7111 [](TimePoint<Clock> a, TimePoint<Clock> b) { return static_cast<double>((a - b).count()); });
7112
7113 return deltas;
7114 }
7115
7116 const auto warmup_iterations = 10000;
7117 const auto warmup_time = std::chrono::milliseconds(100);
7118 const auto minimum_ticks = 1000;
7119 const auto warmup_seed = 10000;
7120 const auto clock_resolution_estimation_time = std::chrono::milliseconds(500);
7121 const auto clock_cost_estimation_time_limit = std::chrono::seconds(1);
7122 const auto clock_cost_estimation_tick_limit = 100000;
7123 const auto clock_cost_estimation_time = std::chrono::milliseconds(10);
7124 const auto clock_cost_estimation_iterations = 10000;
7125
7126 template <typename Clock>
warmup()7127 int warmup() {
7128 return run_for_at_least<Clock>(std::chrono::duration_cast<ClockDuration<Clock>>(warmup_time), warmup_seed, &resolution<Clock>)
7129 .iterations;
7130 }
7131 template <typename Clock>
estimate_clock_resolution(int iterations)7132 EnvironmentEstimate<FloatDuration<Clock>> estimate_clock_resolution(int iterations) {
7133 auto r = run_for_at_least<Clock>(std::chrono::duration_cast<ClockDuration<Clock>>(clock_resolution_estimation_time), iterations, &resolution<Clock>)
7134 .result;
7135 return {
7136 FloatDuration<Clock>(mean(r.begin(), r.end())),
7137 classify_outliers(r.begin(), r.end()),
7138 };
7139 }
7140 template <typename Clock>
estimate_clock_cost(FloatDuration<Clock> resolution)7141 EnvironmentEstimate<FloatDuration<Clock>> estimate_clock_cost(FloatDuration<Clock> resolution) {
7142 auto time_limit = (std::min)(
7143 resolution * clock_cost_estimation_tick_limit,
7144 FloatDuration<Clock>(clock_cost_estimation_time_limit));
7145 auto time_clock = [](int k) {
7146 return Detail::measure<Clock>([k] {
7147 for (int i = 0; i < k; ++i) {
7148 volatile auto ignored = Clock::now();
7149 (void)ignored;
7150 }
7151 }).elapsed;
7152 };
7153 time_clock(1);
7154 int iters = clock_cost_estimation_iterations;
7155 auto&& r = run_for_at_least<Clock>(std::chrono::duration_cast<ClockDuration<Clock>>(clock_cost_estimation_time), iters, time_clock);
7156 std::vector<double> times;
7157 int nsamples = static_cast<int>(std::ceil(time_limit / r.elapsed));
7158 times.reserve(nsamples);
7159 std::generate_n(std::back_inserter(times), nsamples, [time_clock, &r] {
7160 return static_cast<double>((time_clock(r.iterations) / r.iterations).count());
7161 });
7162 return {
7163 FloatDuration<Clock>(mean(times.begin(), times.end())),
7164 classify_outliers(times.begin(), times.end()),
7165 };
7166 }
7167
7168 template <typename Clock>
measure_environment()7169 Environment<FloatDuration<Clock>> measure_environment() {
7170 static Environment<FloatDuration<Clock>>* env = nullptr;
7171 if (env) {
7172 return *env;
7173 }
7174
7175 auto iters = Detail::warmup<Clock>();
7176 auto resolution = Detail::estimate_clock_resolution<Clock>(iters);
7177 auto cost = Detail::estimate_clock_cost<Clock>(resolution.mean);
7178
7179 env = new Environment<FloatDuration<Clock>>{ resolution, cost };
7180 return *env;
7181 }
7182 } // namespace Detail
7183 } // namespace Benchmark
7184 } // namespace Catch
7185
7186 // end catch_estimate_clock.hpp
7187 // start catch_analyse.hpp
7188
7189 // Run and analyse one benchmark
7190
7191
7192 // start catch_sample_analysis.hpp
7193
7194 // Benchmark results
7195
7196
7197 #include <algorithm>
7198 #include <vector>
7199 #include <string>
7200 #include <iterator>
7201
7202 namespace Catch {
7203 namespace Benchmark {
7204 template <typename Duration>
7205 struct SampleAnalysis {
7206 std::vector<Duration> samples;
7207 Estimate<Duration> mean;
7208 Estimate<Duration> standard_deviation;
7209 OutlierClassification outliers;
7210 double outlier_variance;
7211
7212 template <typename Duration2>
operator SampleAnalysis<Duration2>Catch::Benchmark::SampleAnalysis7213 operator SampleAnalysis<Duration2>() const {
7214 std::vector<Duration2> samples2;
7215 samples2.reserve(samples.size());
7216 std::transform(samples.begin(), samples.end(), std::back_inserter(samples2), [](Duration d) { return Duration2(d); });
7217 return {
7218 std::move(samples2),
7219 mean,
7220 standard_deviation,
7221 outliers,
7222 outlier_variance,
7223 };
7224 }
7225 };
7226 } // namespace Benchmark
7227 } // namespace Catch
7228
7229 // end catch_sample_analysis.hpp
7230 #include <algorithm>
7231 #include <iterator>
7232 #include <vector>
7233
7234 namespace Catch {
7235 namespace Benchmark {
7236 namespace Detail {
7237 template <typename Duration, typename Iterator>
analyse(const IConfig & cfg,Environment<Duration>,Iterator first,Iterator last)7238 SampleAnalysis<Duration> analyse(const IConfig &cfg, Environment<Duration>, Iterator first, Iterator last) {
7239 if (!cfg.benchmarkNoAnalysis()) {
7240 std::vector<double> samples;
7241 samples.reserve(last - first);
7242 std::transform(first, last, std::back_inserter(samples), [](Duration d) { return d.count(); });
7243
7244 auto analysis = Catch::Benchmark::Detail::analyse_samples(cfg.benchmarkConfidenceInterval(), cfg.benchmarkResamples(), samples.begin(), samples.end());
7245 auto outliers = Catch::Benchmark::Detail::classify_outliers(samples.begin(), samples.end());
7246
7247 auto wrap_estimate = [](Estimate<double> e) {
7248 return Estimate<Duration> {
7249 Duration(e.point),
7250 Duration(e.lower_bound),
7251 Duration(e.upper_bound),
7252 e.confidence_interval,
7253 };
7254 };
7255 std::vector<Duration> samples2;
7256 samples2.reserve(samples.size());
7257 std::transform(samples.begin(), samples.end(), std::back_inserter(samples2), [](double d) { return Duration(d); });
7258 return {
7259 std::move(samples2),
7260 wrap_estimate(analysis.mean),
7261 wrap_estimate(analysis.standard_deviation),
7262 outliers,
7263 analysis.outlier_variance,
7264 };
7265 } else {
7266 std::vector<Duration> samples;
7267 samples.reserve(last - first);
7268
7269 Duration mean = Duration(0);
7270 int i = 0;
7271 for (auto it = first; it < last; ++it, ++i) {
7272 samples.push_back(Duration(*it));
7273 mean += Duration(*it);
7274 }
7275 mean /= i;
7276
7277 return {
7278 std::move(samples),
7279 Estimate<Duration>{mean, mean, mean, 0.0},
7280 Estimate<Duration>{Duration(0), Duration(0), Duration(0), 0.0},
7281 OutlierClassification{},
7282 0.0
7283 };
7284 }
7285 }
7286 } // namespace Detail
7287 } // namespace Benchmark
7288 } // namespace Catch
7289
7290 // end catch_analyse.hpp
7291 #include <algorithm>
7292 #include <functional>
7293 #include <string>
7294 #include <vector>
7295 #include <cmath>
7296
7297 namespace Catch {
7298 namespace Benchmark {
7299 struct Benchmark {
BenchmarkCatch::Benchmark::Benchmark7300 Benchmark(std::string &&name)
7301 : name(std::move(name)) {}
7302
7303 template <class FUN>
BenchmarkCatch::Benchmark::Benchmark7304 Benchmark(std::string &&name, FUN &&func)
7305 : fun(std::move(func)), name(std::move(name)) {}
7306
7307 template <typename Clock>
prepareCatch::Benchmark::Benchmark7308 ExecutionPlan<FloatDuration<Clock>> prepare(const IConfig &cfg, Environment<FloatDuration<Clock>> env) const {
7309 auto min_time = env.clock_resolution.mean * Detail::minimum_ticks;
7310 auto run_time = std::max(min_time, std::chrono::duration_cast<decltype(min_time)>(cfg.benchmarkWarmupTime()));
7311 auto&& test = Detail::run_for_at_least<Clock>(std::chrono::duration_cast<ClockDuration<Clock>>(run_time), 1, fun);
7312 int new_iters = static_cast<int>(std::ceil(min_time * test.iterations / test.elapsed));
7313 return { new_iters, test.elapsed / test.iterations * new_iters * cfg.benchmarkSamples(), fun, std::chrono::duration_cast<FloatDuration<Clock>>(cfg.benchmarkWarmupTime()), Detail::warmup_iterations };
7314 }
7315
7316 template <typename Clock = default_clock>
runCatch::Benchmark::Benchmark7317 void run() {
7318 IConfigPtr cfg = getCurrentContext().getConfig();
7319
7320 auto env = Detail::measure_environment<Clock>();
7321
7322 getResultCapture().benchmarkPreparing(name);
7323 CATCH_TRY{
7324 auto plan = user_code([&] {
7325 return prepare<Clock>(*cfg, env);
7326 });
7327
7328 BenchmarkInfo info {
7329 name,
7330 plan.estimated_duration.count(),
7331 plan.iterations_per_sample,
7332 cfg->benchmarkSamples(),
7333 cfg->benchmarkResamples(),
7334 env.clock_resolution.mean.count(),
7335 env.clock_cost.mean.count()
7336 };
7337
7338 getResultCapture().benchmarkStarting(info);
7339
7340 auto samples = user_code([&] {
7341 return plan.template run<Clock>(*cfg, env);
7342 });
7343
7344 auto analysis = Detail::analyse(*cfg, env, samples.begin(), samples.end());
7345 BenchmarkStats<FloatDuration<Clock>> stats{ info, analysis.samples, analysis.mean, analysis.standard_deviation, analysis.outliers, analysis.outlier_variance };
7346 getResultCapture().benchmarkEnded(stats);
7347
7348 } CATCH_CATCH_ALL{
7349 if (translateActiveException() != Detail::benchmarkErrorMsg) // benchmark errors have been reported, otherwise rethrow.
7350 std::rethrow_exception(std::current_exception());
7351 }
7352 }
7353
7354 // sets lambda to be used in fun *and* executes benchmark!
7355 template <typename Fun,
7356 typename std::enable_if<!Detail::is_related<Fun, Benchmark>::value, int>::type = 0>
operator =Catch::Benchmark::Benchmark7357 Benchmark & operator=(Fun func) {
7358 fun = Detail::BenchmarkFunction(func);
7359 run();
7360 return *this;
7361 }
7362
operator boolCatch::Benchmark::Benchmark7363 explicit operator bool() {
7364 return true;
7365 }
7366
7367 private:
7368 Detail::BenchmarkFunction fun;
7369 std::string name;
7370 };
7371 }
7372 } // namespace Catch
7373
7374 #define INTERNAL_CATCH_GET_1_ARG(arg1, arg2, ...) arg1
7375 #define INTERNAL_CATCH_GET_2_ARG(arg1, arg2, ...) arg2
7376
7377 #define INTERNAL_CATCH_BENCHMARK(BenchmarkName, name, benchmarkIndex)\
7378 if( Catch::Benchmark::Benchmark BenchmarkName{name} ) \
7379 BenchmarkName = [&](int benchmarkIndex)
7380
7381 #define INTERNAL_CATCH_BENCHMARK_ADVANCED(BenchmarkName, name)\
7382 if( Catch::Benchmark::Benchmark BenchmarkName{name} ) \
7383 BenchmarkName = [&]
7384
7385 // end catch_benchmark.hpp
7386 // start catch_constructor.hpp
7387
7388 // Constructor and destructor helpers
7389
7390
7391 #include <type_traits>
7392
7393 namespace Catch {
7394 namespace Benchmark {
7395 namespace Detail {
7396 template <typename T, bool Destruct>
7397 struct ObjectStorage
7398 {
7399 using TStorage = typename std::aligned_storage<sizeof(T), std::alignment_of<T>::value>::type;
7400
ObjectStorageCatch::Benchmark::Detail::ObjectStorage7401 ObjectStorage() : data() {}
7402
ObjectStorageCatch::Benchmark::Detail::ObjectStorage7403 ObjectStorage(const ObjectStorage& other)
7404 {
7405 new(&data) T(other.stored_object());
7406 }
7407
ObjectStorageCatch::Benchmark::Detail::ObjectStorage7408 ObjectStorage(ObjectStorage&& other)
7409 {
7410 new(&data) T(std::move(other.stored_object()));
7411 }
7412
~ObjectStorageCatch::Benchmark::Detail::ObjectStorage7413 ~ObjectStorage() { destruct_on_exit<T>(); }
7414
7415 template <typename... Args>
constructCatch::Benchmark::Detail::ObjectStorage7416 void construct(Args&&... args)
7417 {
7418 new (&data) T(std::forward<Args>(args)...);
7419 }
7420
7421 template <bool AllowManualDestruction = !Destruct>
destructCatch::Benchmark::Detail::ObjectStorage7422 typename std::enable_if<AllowManualDestruction>::type destruct()
7423 {
7424 stored_object().~T();
7425 }
7426
7427 private:
7428 // If this is a constructor benchmark, destruct the underlying object
7429 template <typename U>
destruct_on_exitCatch::Benchmark::Detail::ObjectStorage7430 void destruct_on_exit(typename std::enable_if<Destruct, U>::type* = 0) { destruct<true>(); }
7431 // Otherwise, don't
7432 template <typename U>
destruct_on_exitCatch::Benchmark::Detail::ObjectStorage7433 void destruct_on_exit(typename std::enable_if<!Destruct, U>::type* = 0) { }
7434
stored_objectCatch::Benchmark::Detail::ObjectStorage7435 T& stored_object() {
7436 return *static_cast<T*>(static_cast<void*>(&data));
7437 }
7438
stored_objectCatch::Benchmark::Detail::ObjectStorage7439 T const& stored_object() const {
7440 return *static_cast<T*>(static_cast<void*>(&data));
7441 }
7442
7443 TStorage data;
7444 };
7445 }
7446
7447 template <typename T>
7448 using storage_for = Detail::ObjectStorage<T, true>;
7449
7450 template <typename T>
7451 using destructable_object = Detail::ObjectStorage<T, false>;
7452 }
7453 }
7454
7455 // end catch_constructor.hpp
7456 // end catch_benchmarking_all.hpp
7457 #endif
7458
7459 #endif // ! CATCH_CONFIG_IMPL_ONLY
7460
7461 #ifdef CATCH_IMPL
7462 // start catch_impl.hpp
7463
7464 #ifdef __clang__
7465 #pragma clang diagnostic push
7466 #pragma clang diagnostic ignored "-Wweak-vtables"
7467 #endif
7468
7469 // Keep these here for external reporters
7470 // start catch_test_case_tracker.h
7471
7472 #include <string>
7473 #include <vector>
7474 #include <memory>
7475
7476 namespace Catch {
7477 namespace TestCaseTracking {
7478
7479 struct NameAndLocation {
7480 std::string name;
7481 SourceLineInfo location;
7482
7483 NameAndLocation( std::string const& _name, SourceLineInfo const& _location );
operator ==(NameAndLocation const & lhs,NameAndLocation const & rhs)7484 friend bool operator==(NameAndLocation const& lhs, NameAndLocation const& rhs) {
7485 return lhs.name == rhs.name
7486 && lhs.location == rhs.location;
7487 }
7488 };
7489
7490 class ITracker;
7491
7492 using ITrackerPtr = std::shared_ptr<ITracker>;
7493
7494 class ITracker {
7495 NameAndLocation m_nameAndLocation;
7496
7497 public:
ITracker(NameAndLocation const & nameAndLoc)7498 ITracker(NameAndLocation const& nameAndLoc) :
7499 m_nameAndLocation(nameAndLoc)
7500 {}
7501
7502 // static queries
nameAndLocation() const7503 NameAndLocation const& nameAndLocation() const {
7504 return m_nameAndLocation;
7505 }
7506
7507 virtual ~ITracker();
7508
7509 // dynamic queries
7510 virtual bool isComplete() const = 0; // Successfully completed or failed
7511 virtual bool isSuccessfullyCompleted() const = 0;
7512 virtual bool isOpen() const = 0; // Started but not complete
7513 virtual bool hasChildren() const = 0;
7514 virtual bool hasStarted() const = 0;
7515
7516 virtual ITracker& parent() = 0;
7517
7518 // actions
7519 virtual void close() = 0; // Successfully complete
7520 virtual void fail() = 0;
7521 virtual void markAsNeedingAnotherRun() = 0;
7522
7523 virtual void addChild( ITrackerPtr const& child ) = 0;
7524 virtual ITrackerPtr findChild( NameAndLocation const& nameAndLocation ) = 0;
7525 virtual void openChild() = 0;
7526
7527 // Debug/ checking
7528 virtual bool isSectionTracker() const = 0;
7529 virtual bool isGeneratorTracker() const = 0;
7530 };
7531
7532 class TrackerContext {
7533
7534 enum RunState {
7535 NotStarted,
7536 Executing,
7537 CompletedCycle
7538 };
7539
7540 ITrackerPtr m_rootTracker;
7541 ITracker* m_currentTracker = nullptr;
7542 RunState m_runState = NotStarted;
7543
7544 public:
7545
7546 ITracker& startRun();
7547 void endRun();
7548
7549 void startCycle();
7550 void completeCycle();
7551
7552 bool completedCycle() const;
7553 ITracker& currentTracker();
7554 void setCurrentTracker( ITracker* tracker );
7555 };
7556
7557 class TrackerBase : public ITracker {
7558 protected:
7559 enum CycleState {
7560 NotStarted,
7561 Executing,
7562 ExecutingChildren,
7563 NeedsAnotherRun,
7564 CompletedSuccessfully,
7565 Failed
7566 };
7567
7568 using Children = std::vector<ITrackerPtr>;
7569 TrackerContext& m_ctx;
7570 ITracker* m_parent;
7571 Children m_children;
7572 CycleState m_runState = NotStarted;
7573
7574 public:
7575 TrackerBase( NameAndLocation const& nameAndLocation, TrackerContext& ctx, ITracker* parent );
7576
7577 bool isComplete() const override;
7578 bool isSuccessfullyCompleted() const override;
7579 bool isOpen() const override;
7580 bool hasChildren() const override;
hasStarted() const7581 bool hasStarted() const override {
7582 return m_runState != NotStarted;
7583 }
7584
7585 void addChild( ITrackerPtr const& child ) override;
7586
7587 ITrackerPtr findChild( NameAndLocation const& nameAndLocation ) override;
7588 ITracker& parent() override;
7589
7590 void openChild() override;
7591
7592 bool isSectionTracker() const override;
7593 bool isGeneratorTracker() const override;
7594
7595 void open();
7596
7597 void close() override;
7598 void fail() override;
7599 void markAsNeedingAnotherRun() override;
7600
7601 private:
7602 void moveToParent();
7603 void moveToThis();
7604 };
7605
7606 class SectionTracker : public TrackerBase {
7607 std::vector<std::string> m_filters;
7608 std::string m_trimmed_name;
7609 public:
7610 SectionTracker( NameAndLocation const& nameAndLocation, TrackerContext& ctx, ITracker* parent );
7611
7612 bool isSectionTracker() const override;
7613
7614 bool isComplete() const override;
7615
7616 static SectionTracker& acquire( TrackerContext& ctx, NameAndLocation const& nameAndLocation );
7617
7618 void tryOpen();
7619
7620 void addInitialFilters( std::vector<std::string> const& filters );
7621 void addNextFilters( std::vector<std::string> const& filters );
7622 //! Returns filters active in this tracker
7623 std::vector<std::string> const& getFilters() const;
7624 //! Returns whitespace-trimmed name of the tracked section
7625 std::string const& trimmedName() const;
7626 };
7627
7628 } // namespace TestCaseTracking
7629
7630 using TestCaseTracking::ITracker;
7631 using TestCaseTracking::TrackerContext;
7632 using TestCaseTracking::SectionTracker;
7633
7634 } // namespace Catch
7635
7636 // end catch_test_case_tracker.h
7637
7638 // start catch_leak_detector.h
7639
7640 namespace Catch {
7641
7642 struct LeakDetector {
7643 LeakDetector();
7644 ~LeakDetector();
7645 };
7646
7647 }
7648 // end catch_leak_detector.h
7649 // Cpp files will be included in the single-header file here
7650 // start catch_stats.cpp
7651
7652 // Statistical analysis tools
7653
7654 #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
7655
7656 #include <cassert>
7657 #include <random>
7658
7659 #if defined(CATCH_CONFIG_USE_ASYNC)
7660 #include <future>
7661 #endif
7662
7663 namespace {
erf_inv(double x)7664 double erf_inv(double x) {
7665 // Code accompanying the article "Approximating the erfinv function" in GPU Computing Gems, Volume 2
7666 double w, p;
7667
7668 w = -log((1.0 - x) * (1.0 + x));
7669
7670 if (w < 6.250000) {
7671 w = w - 3.125000;
7672 p = -3.6444120640178196996e-21;
7673 p = -1.685059138182016589e-19 + p * w;
7674 p = 1.2858480715256400167e-18 + p * w;
7675 p = 1.115787767802518096e-17 + p * w;
7676 p = -1.333171662854620906e-16 + p * w;
7677 p = 2.0972767875968561637e-17 + p * w;
7678 p = 6.6376381343583238325e-15 + p * w;
7679 p = -4.0545662729752068639e-14 + p * w;
7680 p = -8.1519341976054721522e-14 + p * w;
7681 p = 2.6335093153082322977e-12 + p * w;
7682 p = -1.2975133253453532498e-11 + p * w;
7683 p = -5.4154120542946279317e-11 + p * w;
7684 p = 1.051212273321532285e-09 + p * w;
7685 p = -4.1126339803469836976e-09 + p * w;
7686 p = -2.9070369957882005086e-08 + p * w;
7687 p = 4.2347877827932403518e-07 + p * w;
7688 p = -1.3654692000834678645e-06 + p * w;
7689 p = -1.3882523362786468719e-05 + p * w;
7690 p = 0.0001867342080340571352 + p * w;
7691 p = -0.00074070253416626697512 + p * w;
7692 p = -0.0060336708714301490533 + p * w;
7693 p = 0.24015818242558961693 + p * w;
7694 p = 1.6536545626831027356 + p * w;
7695 } else if (w < 16.000000) {
7696 w = sqrt(w) - 3.250000;
7697 p = 2.2137376921775787049e-09;
7698 p = 9.0756561938885390979e-08 + p * w;
7699 p = -2.7517406297064545428e-07 + p * w;
7700 p = 1.8239629214389227755e-08 + p * w;
7701 p = 1.5027403968909827627e-06 + p * w;
7702 p = -4.013867526981545969e-06 + p * w;
7703 p = 2.9234449089955446044e-06 + p * w;
7704 p = 1.2475304481671778723e-05 + p * w;
7705 p = -4.7318229009055733981e-05 + p * w;
7706 p = 6.8284851459573175448e-05 + p * w;
7707 p = 2.4031110387097893999e-05 + p * w;
7708 p = -0.0003550375203628474796 + p * w;
7709 p = 0.00095328937973738049703 + p * w;
7710 p = -0.0016882755560235047313 + p * w;
7711 p = 0.0024914420961078508066 + p * w;
7712 p = -0.0037512085075692412107 + p * w;
7713 p = 0.005370914553590063617 + p * w;
7714 p = 1.0052589676941592334 + p * w;
7715 p = 3.0838856104922207635 + p * w;
7716 } else {
7717 w = sqrt(w) - 5.000000;
7718 p = -2.7109920616438573243e-11;
7719 p = -2.5556418169965252055e-10 + p * w;
7720 p = 1.5076572693500548083e-09 + p * w;
7721 p = -3.7894654401267369937e-09 + p * w;
7722 p = 7.6157012080783393804e-09 + p * w;
7723 p = -1.4960026627149240478e-08 + p * w;
7724 p = 2.9147953450901080826e-08 + p * w;
7725 p = -6.7711997758452339498e-08 + p * w;
7726 p = 2.2900482228026654717e-07 + p * w;
7727 p = -9.9298272942317002539e-07 + p * w;
7728 p = 4.5260625972231537039e-06 + p * w;
7729 p = -1.9681778105531670567e-05 + p * w;
7730 p = 7.5995277030017761139e-05 + p * w;
7731 p = -0.00021503011930044477347 + p * w;
7732 p = -0.00013871931833623122026 + p * w;
7733 p = 1.0103004648645343977 + p * w;
7734 p = 4.8499064014085844221 + p * w;
7735 }
7736 return p * x;
7737 }
7738
standard_deviation(std::vector<double>::iterator first,std::vector<double>::iterator last)7739 double standard_deviation(std::vector<double>::iterator first, std::vector<double>::iterator last) {
7740 auto m = Catch::Benchmark::Detail::mean(first, last);
7741 double variance = std::accumulate(first, last, 0., [m](double a, double b) {
7742 double diff = b - m;
7743 return a + diff * diff;
7744 }) / (last - first);
7745 return std::sqrt(variance);
7746 }
7747
7748 }
7749
7750 namespace Catch {
7751 namespace Benchmark {
7752 namespace Detail {
7753
weighted_average_quantile(int k,int q,std::vector<double>::iterator first,std::vector<double>::iterator last)7754 double weighted_average_quantile(int k, int q, std::vector<double>::iterator first, std::vector<double>::iterator last) {
7755 auto count = last - first;
7756 double idx = (count - 1) * k / static_cast<double>(q);
7757 int j = static_cast<int>(idx);
7758 double g = idx - j;
7759 std::nth_element(first, first + j, last);
7760 auto xj = first[j];
7761 if (g == 0) return xj;
7762
7763 auto xj1 = *std::min_element(first + (j + 1), last);
7764 return xj + g * (xj1 - xj);
7765 }
7766
erfc_inv(double x)7767 double erfc_inv(double x) {
7768 return erf_inv(1.0 - x);
7769 }
7770
normal_quantile(double p)7771 double normal_quantile(double p) {
7772 static const double ROOT_TWO = std::sqrt(2.0);
7773
7774 double result = 0.0;
7775 assert(p >= 0 && p <= 1);
7776 if (p < 0 || p > 1) {
7777 return result;
7778 }
7779
7780 result = -erfc_inv(2.0 * p);
7781 // result *= normal distribution standard deviation (1.0) * sqrt(2)
7782 result *= /*sd * */ ROOT_TWO;
7783 // result += normal disttribution mean (0)
7784 return result;
7785 }
7786
outlier_variance(Estimate<double> mean,Estimate<double> stddev,int n)7787 double outlier_variance(Estimate<double> mean, Estimate<double> stddev, int n) {
7788 double sb = stddev.point;
7789 double mn = mean.point / n;
7790 double mg_min = mn / 2.;
7791 double sg = (std::min)(mg_min / 4., sb / std::sqrt(n));
7792 double sg2 = sg * sg;
7793 double sb2 = sb * sb;
7794
7795 auto c_max = [n, mn, sb2, sg2](double x) -> double {
7796 double k = mn - x;
7797 double d = k * k;
7798 double nd = n * d;
7799 double k0 = -n * nd;
7800 double k1 = sb2 - n * sg2 + nd;
7801 double det = k1 * k1 - 4 * sg2 * k0;
7802 return (int)(-2. * k0 / (k1 + std::sqrt(det)));
7803 };
7804
7805 auto var_out = [n, sb2, sg2](double c) {
7806 double nc = n - c;
7807 return (nc / n) * (sb2 - nc * sg2);
7808 };
7809
7810 return (std::min)(var_out(1), var_out((std::min)(c_max(0.), c_max(mg_min)))) / sb2;
7811 }
7812
analyse_samples(double confidence_level,int n_resamples,std::vector<double>::iterator first,std::vector<double>::iterator last)7813 bootstrap_analysis analyse_samples(double confidence_level, int n_resamples, std::vector<double>::iterator first, std::vector<double>::iterator last) {
7814 CATCH_INTERNAL_START_WARNINGS_SUPPRESSION
7815 CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS
7816 static std::random_device entropy;
7817 CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION
7818
7819 auto n = static_cast<int>(last - first); // seriously, one can't use integral types without hell in C++
7820
7821 auto mean = &Detail::mean<std::vector<double>::iterator>;
7822 auto stddev = &standard_deviation;
7823
7824 #if defined(CATCH_CONFIG_USE_ASYNC)
7825 auto Estimate = [=](double(*f)(std::vector<double>::iterator, std::vector<double>::iterator)) {
7826 auto seed = entropy();
7827 return std::async(std::launch::async, [=] {
7828 std::mt19937 rng(seed);
7829 auto resampled = resample(rng, n_resamples, first, last, f);
7830 return bootstrap(confidence_level, first, last, resampled, f);
7831 });
7832 };
7833
7834 auto mean_future = Estimate(mean);
7835 auto stddev_future = Estimate(stddev);
7836
7837 auto mean_estimate = mean_future.get();
7838 auto stddev_estimate = stddev_future.get();
7839 #else
7840 auto Estimate = [=](double(*f)(std::vector<double>::iterator, std::vector<double>::iterator)) {
7841 auto seed = entropy();
7842 std::mt19937 rng(seed);
7843 auto resampled = resample(rng, n_resamples, first, last, f);
7844 return bootstrap(confidence_level, first, last, resampled, f);
7845 };
7846
7847 auto mean_estimate = Estimate(mean);
7848 auto stddev_estimate = Estimate(stddev);
7849 #endif // CATCH_USE_ASYNC
7850
7851 double outlier_variance = Detail::outlier_variance(mean_estimate, stddev_estimate, n);
7852
7853 return { mean_estimate, stddev_estimate, outlier_variance };
7854 }
7855 } // namespace Detail
7856 } // namespace Benchmark
7857 } // namespace Catch
7858
7859 #endif // CATCH_CONFIG_ENABLE_BENCHMARKING
7860 // end catch_stats.cpp
7861 // start catch_approx.cpp
7862
7863 #include <cmath>
7864 #include <limits>
7865
7866 namespace {
7867
7868 // Performs equivalent check of std::fabs(lhs - rhs) <= margin
7869 // But without the subtraction to allow for INFINITY in comparison
marginComparison(double lhs,double rhs,double margin)7870 bool marginComparison(double lhs, double rhs, double margin) {
7871 return (lhs + margin >= rhs) && (rhs + margin >= lhs);
7872 }
7873
7874 }
7875
7876 namespace Catch {
7877 namespace Detail {
7878
Approx(double value)7879 Approx::Approx ( double value )
7880 : m_epsilon( std::numeric_limits<float>::epsilon()*100 ),
7881 m_margin( 0.0 ),
7882 m_scale( 0.0 ),
7883 m_value( value )
7884 {}
7885
custom()7886 Approx Approx::custom() {
7887 return Approx( 0 );
7888 }
7889
operator -() const7890 Approx Approx::operator-() const {
7891 auto temp(*this);
7892 temp.m_value = -temp.m_value;
7893 return temp;
7894 }
7895
toString() const7896 std::string Approx::toString() const {
7897 ReusableStringStream rss;
7898 rss << "Approx( " << ::Catch::Detail::stringify( m_value ) << " )";
7899 return rss.str();
7900 }
7901
equalityComparisonImpl(const double other) const7902 bool Approx::equalityComparisonImpl(const double other) const {
7903 // First try with fixed margin, then compute margin based on epsilon, scale and Approx's value
7904 // Thanks to Richard Harris for his help refining the scaled margin value
7905 return marginComparison(m_value, other, m_margin)
7906 || marginComparison(m_value, other, m_epsilon * (m_scale + std::fabs(std::isinf(m_value)? 0 : m_value)));
7907 }
7908
setMargin(double newMargin)7909 void Approx::setMargin(double newMargin) {
7910 CATCH_ENFORCE(newMargin >= 0,
7911 "Invalid Approx::margin: " << newMargin << '.'
7912 << " Approx::Margin has to be non-negative.");
7913 m_margin = newMargin;
7914 }
7915
setEpsilon(double newEpsilon)7916 void Approx::setEpsilon(double newEpsilon) {
7917 CATCH_ENFORCE(newEpsilon >= 0 && newEpsilon <= 1.0,
7918 "Invalid Approx::epsilon: " << newEpsilon << '.'
7919 << " Approx::epsilon has to be in [0, 1]");
7920 m_epsilon = newEpsilon;
7921 }
7922
7923 } // end namespace Detail
7924
7925 namespace literals {
operator ""_a(long double val)7926 Detail::Approx operator "" _a(long double val) {
7927 return Detail::Approx(val);
7928 }
operator ""_a(unsigned long long val)7929 Detail::Approx operator "" _a(unsigned long long val) {
7930 return Detail::Approx(val);
7931 }
7932 } // end namespace literals
7933
convert(Catch::Detail::Approx const & value)7934 std::string StringMaker<Catch::Detail::Approx>::convert(Catch::Detail::Approx const& value) {
7935 return value.toString();
7936 }
7937
7938 } // end namespace Catch
7939 // end catch_approx.cpp
7940 // start catch_assertionhandler.cpp
7941
7942 // start catch_debugger.h
7943
7944 namespace Catch {
7945 bool isDebuggerActive();
7946 }
7947
7948 #ifdef CATCH_PLATFORM_MAC
7949
7950 #if defined(__i386__) || defined(__x86_64__)
7951 #define CATCH_TRAP() __asm__("int $3\n" : : ) /* NOLINT */
7952 #elif defined(__aarch64__)
7953 #define CATCH_TRAP() __asm__(".inst 0xd4200000")
7954 #endif
7955
7956 #elif defined(CATCH_PLATFORM_IPHONE)
7957
7958 // use inline assembler
7959 #if defined(__i386__) || defined(__x86_64__)
7960 #define CATCH_TRAP() __asm__("int $3")
7961 #elif defined(__aarch64__)
7962 #define CATCH_TRAP() __asm__(".inst 0xd4200000")
7963 #elif defined(__arm__) && !defined(__thumb__)
7964 #define CATCH_TRAP() __asm__(".inst 0xe7f001f0")
7965 #elif defined(__arm__) && defined(__thumb__)
7966 #define CATCH_TRAP() __asm__(".inst 0xde01")
7967 #endif
7968
7969 #elif defined(CATCH_PLATFORM_LINUX)
7970 // If we can use inline assembler, do it because this allows us to break
7971 // directly at the location of the failing check instead of breaking inside
7972 // raise() called from it, i.e. one stack frame below.
7973 #if defined(__GNUC__) && (defined(__i386) || defined(__x86_64))
7974 #define CATCH_TRAP() asm volatile ("int $3") /* NOLINT */
7975 #else // Fall back to the generic way.
7976 #include <signal.h>
7977
7978 #define CATCH_TRAP() raise(SIGTRAP)
7979 #endif
7980 #elif defined(_MSC_VER)
7981 #define CATCH_TRAP() __debugbreak()
7982 #elif defined(__MINGW32__)
7983 extern "C" __declspec(dllimport) void __stdcall DebugBreak();
7984 #define CATCH_TRAP() DebugBreak()
7985 #endif
7986
7987 #ifndef CATCH_BREAK_INTO_DEBUGGER
7988 #ifdef CATCH_TRAP
7989 #define CATCH_BREAK_INTO_DEBUGGER() []{ if( Catch::isDebuggerActive() ) { CATCH_TRAP(); } }()
7990 #else
7991 #define CATCH_BREAK_INTO_DEBUGGER() []{}()
7992 #endif
7993 #endif
7994
7995 // end catch_debugger.h
7996 // start catch_run_context.h
7997
7998 // start catch_fatal_condition.h
7999
8000 #include <cassert>
8001
8002 namespace Catch {
8003
8004 // Wrapper for platform-specific fatal error (signals/SEH) handlers
8005 //
8006 // Tries to be cooperative with other handlers, and not step over
8007 // other handlers. This means that unknown structured exceptions
8008 // are passed on, previous signal handlers are called, and so on.
8009 //
8010 // Can only be instantiated once, and assumes that once a signal
8011 // is caught, the binary will end up terminating. Thus, there
8012 class FatalConditionHandler {
8013 bool m_started = false;
8014
8015 // Install/disengage implementation for specific platform.
8016 // Should be if-defed to work on current platform, can assume
8017 // engage-disengage 1:1 pairing.
8018 void engage_platform();
8019 void disengage_platform();
8020 public:
8021 // Should also have platform-specific implementations as needed
8022 FatalConditionHandler();
8023 ~FatalConditionHandler();
8024
engage()8025 void engage() {
8026 assert(!m_started && "Handler cannot be installed twice.");
8027 m_started = true;
8028 engage_platform();
8029 }
8030
disengage()8031 void disengage() {
8032 assert(m_started && "Handler cannot be uninstalled without being installed first");
8033 m_started = false;
8034 disengage_platform();
8035 }
8036 };
8037
8038 //! Simple RAII guard for (dis)engaging the FatalConditionHandler
8039 class FatalConditionHandlerGuard {
8040 FatalConditionHandler* m_handler;
8041 public:
FatalConditionHandlerGuard(FatalConditionHandler * handler)8042 FatalConditionHandlerGuard(FatalConditionHandler* handler):
8043 m_handler(handler) {
8044 m_handler->engage();
8045 }
~FatalConditionHandlerGuard()8046 ~FatalConditionHandlerGuard() {
8047 m_handler->disengage();
8048 }
8049 };
8050
8051 } // end namespace Catch
8052
8053 // end catch_fatal_condition.h
8054 #include <string>
8055
8056 namespace Catch {
8057
8058 struct IMutableContext;
8059
8060 ///////////////////////////////////////////////////////////////////////////
8061
8062 class RunContext : public IResultCapture, public IRunner {
8063
8064 public:
8065 RunContext( RunContext const& ) = delete;
8066 RunContext& operator =( RunContext const& ) = delete;
8067
8068 explicit RunContext( IConfigPtr const& _config, IStreamingReporterPtr&& reporter );
8069
8070 ~RunContext() override;
8071
8072 void testGroupStarting( std::string const& testSpec, std::size_t groupIndex, std::size_t groupsCount );
8073 void testGroupEnded( std::string const& testSpec, Totals const& totals, std::size_t groupIndex, std::size_t groupsCount );
8074
8075 Totals runTest(TestCase const& testCase);
8076
8077 IConfigPtr config() const;
8078 IStreamingReporter& reporter() const;
8079
8080 public: // IResultCapture
8081
8082 // Assertion handlers
8083 void handleExpr
8084 ( AssertionInfo const& info,
8085 ITransientExpression const& expr,
8086 AssertionReaction& reaction ) override;
8087 void handleMessage
8088 ( AssertionInfo const& info,
8089 ResultWas::OfType resultType,
8090 StringRef const& message,
8091 AssertionReaction& reaction ) override;
8092 void handleUnexpectedExceptionNotThrown
8093 ( AssertionInfo const& info,
8094 AssertionReaction& reaction ) override;
8095 void handleUnexpectedInflightException
8096 ( AssertionInfo const& info,
8097 std::string const& message,
8098 AssertionReaction& reaction ) override;
8099 void handleIncomplete
8100 ( AssertionInfo const& info ) override;
8101 void handleNonExpr
8102 ( AssertionInfo const &info,
8103 ResultWas::OfType resultType,
8104 AssertionReaction &reaction ) override;
8105
8106 bool sectionStarted( SectionInfo const& sectionInfo, Counts& assertions ) override;
8107
8108 void sectionEnded( SectionEndInfo const& endInfo ) override;
8109 void sectionEndedEarly( SectionEndInfo const& endInfo ) override;
8110
8111 auto acquireGeneratorTracker( StringRef generatorName, SourceLineInfo const& lineInfo ) -> IGeneratorTracker& override;
8112
8113 #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
8114 void benchmarkPreparing( std::string const& name ) override;
8115 void benchmarkStarting( BenchmarkInfo const& info ) override;
8116 void benchmarkEnded( BenchmarkStats<> const& stats ) override;
8117 void benchmarkFailed( std::string const& error ) override;
8118 #endif // CATCH_CONFIG_ENABLE_BENCHMARKING
8119
8120 void pushScopedMessage( MessageInfo const& message ) override;
8121 void popScopedMessage( MessageInfo const& message ) override;
8122
8123 void emplaceUnscopedMessage( MessageBuilder const& builder ) override;
8124
8125 std::string getCurrentTestName() const override;
8126
8127 const AssertionResult* getLastResult() const override;
8128
8129 void exceptionEarlyReported() override;
8130
8131 void handleFatalErrorCondition( StringRef message ) override;
8132
8133 bool lastAssertionPassed() override;
8134
8135 void assertionPassed() override;
8136
8137 public:
8138 // !TBD We need to do this another way!
8139 bool aborting() const final;
8140
8141 private:
8142
8143 void runCurrentTest( std::string& redirectedCout, std::string& redirectedCerr );
8144 void invokeActiveTestCase();
8145
8146 void resetAssertionInfo();
8147 bool testForMissingAssertions( Counts& assertions );
8148
8149 void assertionEnded( AssertionResult const& result );
8150 void reportExpr
8151 ( AssertionInfo const &info,
8152 ResultWas::OfType resultType,
8153 ITransientExpression const *expr,
8154 bool negated );
8155
8156 void populateReaction( AssertionReaction& reaction );
8157
8158 private:
8159
8160 void handleUnfinishedSections();
8161
8162 TestRunInfo m_runInfo;
8163 IMutableContext& m_context;
8164 TestCase const* m_activeTestCase = nullptr;
8165 ITracker* m_testCaseTracker = nullptr;
8166 Option<AssertionResult> m_lastResult;
8167
8168 IConfigPtr m_config;
8169 Totals m_totals;
8170 IStreamingReporterPtr m_reporter;
8171 std::vector<MessageInfo> m_messages;
8172 std::vector<ScopedMessage> m_messageScopes; /* Keeps owners of so-called unscoped messages. */
8173 AssertionInfo m_lastAssertionInfo;
8174 std::vector<SectionEndInfo> m_unfinishedSections;
8175 std::vector<ITracker*> m_activeSections;
8176 TrackerContext m_trackerContext;
8177 FatalConditionHandler m_fatalConditionhandler;
8178 bool m_lastAssertionPassed = false;
8179 bool m_shouldReportUnexpected = true;
8180 bool m_includeSuccessfulResults;
8181 };
8182
8183 void seedRng(IConfig const& config);
8184 unsigned int rngSeed();
8185 } // end namespace Catch
8186
8187 // end catch_run_context.h
8188 namespace Catch {
8189
8190 namespace {
operator <<(std::ostream & os,ITransientExpression const & expr)8191 auto operator <<( std::ostream& os, ITransientExpression const& expr ) -> std::ostream& {
8192 expr.streamReconstructedExpression( os );
8193 return os;
8194 }
8195 }
8196
LazyExpression(bool isNegated)8197 LazyExpression::LazyExpression( bool isNegated )
8198 : m_isNegated( isNegated )
8199 {}
8200
LazyExpression(LazyExpression const & other)8201 LazyExpression::LazyExpression( LazyExpression const& other ) : m_isNegated( other.m_isNegated ) {}
8202
operator bool() const8203 LazyExpression::operator bool() const {
8204 return m_transientExpression != nullptr;
8205 }
8206
operator <<(std::ostream & os,LazyExpression const & lazyExpr)8207 auto operator << ( std::ostream& os, LazyExpression const& lazyExpr ) -> std::ostream& {
8208 if( lazyExpr.m_isNegated )
8209 os << "!";
8210
8211 if( lazyExpr ) {
8212 if( lazyExpr.m_isNegated && lazyExpr.m_transientExpression->isBinaryExpression() )
8213 os << "(" << *lazyExpr.m_transientExpression << ")";
8214 else
8215 os << *lazyExpr.m_transientExpression;
8216 }
8217 else {
8218 os << "{** error - unchecked empty expression requested **}";
8219 }
8220 return os;
8221 }
8222
AssertionHandler(StringRef const & macroName,SourceLineInfo const & lineInfo,StringRef capturedExpression,ResultDisposition::Flags resultDisposition)8223 AssertionHandler::AssertionHandler
8224 ( StringRef const& macroName,
8225 SourceLineInfo const& lineInfo,
8226 StringRef capturedExpression,
8227 ResultDisposition::Flags resultDisposition )
8228 : m_assertionInfo{ macroName, lineInfo, capturedExpression, resultDisposition },
8229 m_resultCapture( getResultCapture() )
8230 {}
8231
handleExpr(ITransientExpression const & expr)8232 void AssertionHandler::handleExpr( ITransientExpression const& expr ) {
8233 m_resultCapture.handleExpr( m_assertionInfo, expr, m_reaction );
8234 }
handleMessage(ResultWas::OfType resultType,StringRef const & message)8235 void AssertionHandler::handleMessage(ResultWas::OfType resultType, StringRef const& message) {
8236 m_resultCapture.handleMessage( m_assertionInfo, resultType, message, m_reaction );
8237 }
8238
allowThrows() const8239 auto AssertionHandler::allowThrows() const -> bool {
8240 return getCurrentContext().getConfig()->allowThrows();
8241 }
8242
complete()8243 void AssertionHandler::complete() {
8244 setCompleted();
8245 if( m_reaction.shouldDebugBreak ) {
8246
8247 // If you find your debugger stopping you here then go one level up on the
8248 // call-stack for the code that caused it (typically a failed assertion)
8249
8250 // (To go back to the test and change execution, jump over the throw, next)
8251 CATCH_BREAK_INTO_DEBUGGER();
8252 }
8253 if (m_reaction.shouldThrow) {
8254 #if !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
8255 throw Catch::TestFailureException();
8256 #else
8257 CATCH_ERROR( "Test failure requires aborting test!" );
8258 #endif
8259 }
8260 }
setCompleted()8261 void AssertionHandler::setCompleted() {
8262 m_completed = true;
8263 }
8264
handleUnexpectedInflightException()8265 void AssertionHandler::handleUnexpectedInflightException() {
8266 m_resultCapture.handleUnexpectedInflightException( m_assertionInfo, Catch::translateActiveException(), m_reaction );
8267 }
8268
handleExceptionThrownAsExpected()8269 void AssertionHandler::handleExceptionThrownAsExpected() {
8270 m_resultCapture.handleNonExpr(m_assertionInfo, ResultWas::Ok, m_reaction);
8271 }
handleExceptionNotThrownAsExpected()8272 void AssertionHandler::handleExceptionNotThrownAsExpected() {
8273 m_resultCapture.handleNonExpr(m_assertionInfo, ResultWas::Ok, m_reaction);
8274 }
8275
handleUnexpectedExceptionNotThrown()8276 void AssertionHandler::handleUnexpectedExceptionNotThrown() {
8277 m_resultCapture.handleUnexpectedExceptionNotThrown( m_assertionInfo, m_reaction );
8278 }
8279
handleThrowingCallSkipped()8280 void AssertionHandler::handleThrowingCallSkipped() {
8281 m_resultCapture.handleNonExpr(m_assertionInfo, ResultWas::Ok, m_reaction);
8282 }
8283
8284 // This is the overload that takes a string and infers the Equals matcher from it
8285 // 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)8286 void handleExceptionMatchExpr( AssertionHandler& handler, std::string const& str, StringRef const& matcherString ) {
8287 handleExceptionMatchExpr( handler, Matchers::Equals( str ), matcherString );
8288 }
8289
8290 } // namespace Catch
8291 // end catch_assertionhandler.cpp
8292 // start catch_assertionresult.cpp
8293
8294 namespace Catch {
AssertionResultData(ResultWas::OfType _resultType,LazyExpression const & _lazyExpression)8295 AssertionResultData::AssertionResultData(ResultWas::OfType _resultType, LazyExpression const & _lazyExpression):
8296 lazyExpression(_lazyExpression),
8297 resultType(_resultType) {}
8298
reconstructExpression() const8299 std::string AssertionResultData::reconstructExpression() const {
8300
8301 if( reconstructedExpression.empty() ) {
8302 if( lazyExpression ) {
8303 ReusableStringStream rss;
8304 rss << lazyExpression;
8305 reconstructedExpression = rss.str();
8306 }
8307 }
8308 return reconstructedExpression;
8309 }
8310
AssertionResult(AssertionInfo const & info,AssertionResultData const & data)8311 AssertionResult::AssertionResult( AssertionInfo const& info, AssertionResultData const& data )
8312 : m_info( info ),
8313 m_resultData( data )
8314 {}
8315
8316 // Result was a success
succeeded() const8317 bool AssertionResult::succeeded() const {
8318 return Catch::isOk( m_resultData.resultType );
8319 }
8320
8321 // Result was a success, or failure is suppressed
isOk() const8322 bool AssertionResult::isOk() const {
8323 return Catch::isOk( m_resultData.resultType ) || shouldSuppressFailure( m_info.resultDisposition );
8324 }
8325
getResultType() const8326 ResultWas::OfType AssertionResult::getResultType() const {
8327 return m_resultData.resultType;
8328 }
8329
hasExpression() const8330 bool AssertionResult::hasExpression() const {
8331 return !m_info.capturedExpression.empty();
8332 }
8333
hasMessage() const8334 bool AssertionResult::hasMessage() const {
8335 return !m_resultData.message.empty();
8336 }
8337
getExpression() const8338 std::string AssertionResult::getExpression() const {
8339 // Possibly overallocating by 3 characters should be basically free
8340 std::string expr; expr.reserve(m_info.capturedExpression.size() + 3);
8341 if (isFalseTest(m_info.resultDisposition)) {
8342 expr += "!(";
8343 }
8344 expr += m_info.capturedExpression;
8345 if (isFalseTest(m_info.resultDisposition)) {
8346 expr += ')';
8347 }
8348 return expr;
8349 }
8350
getExpressionInMacro() const8351 std::string AssertionResult::getExpressionInMacro() const {
8352 std::string expr;
8353 if( m_info.macroName.empty() )
8354 expr = static_cast<std::string>(m_info.capturedExpression);
8355 else {
8356 expr.reserve( m_info.macroName.size() + m_info.capturedExpression.size() + 4 );
8357 expr += m_info.macroName;
8358 expr += "( ";
8359 expr += m_info.capturedExpression;
8360 expr += " )";
8361 }
8362 return expr;
8363 }
8364
hasExpandedExpression() const8365 bool AssertionResult::hasExpandedExpression() const {
8366 return hasExpression() && getExpandedExpression() != getExpression();
8367 }
8368
getExpandedExpression() const8369 std::string AssertionResult::getExpandedExpression() const {
8370 std::string expr = m_resultData.reconstructExpression();
8371 return expr.empty()
8372 ? getExpression()
8373 : expr;
8374 }
8375
getMessage() const8376 std::string AssertionResult::getMessage() const {
8377 return m_resultData.message;
8378 }
getSourceInfo() const8379 SourceLineInfo AssertionResult::getSourceInfo() const {
8380 return m_info.lineInfo;
8381 }
8382
getTestMacroName() const8383 StringRef AssertionResult::getTestMacroName() const {
8384 return m_info.macroName;
8385 }
8386
8387 } // end namespace Catch
8388 // end catch_assertionresult.cpp
8389 // start catch_capture_matchers.cpp
8390
8391 namespace Catch {
8392
8393 using StringMatcher = Matchers::Impl::MatcherBase<std::string>;
8394
8395 // This is the general overload that takes a any string matcher
8396 // There is another overload, in catch_assertionhandler.h/.cpp, that only takes a string and infers
8397 // the Equals matcher (so the header does not mention matchers)
handleExceptionMatchExpr(AssertionHandler & handler,StringMatcher const & matcher,StringRef const & matcherString)8398 void handleExceptionMatchExpr( AssertionHandler& handler, StringMatcher const& matcher, StringRef const& matcherString ) {
8399 std::string exceptionMessage = Catch::translateActiveException();
8400 MatchExpr<std::string, StringMatcher const&> expr( exceptionMessage, matcher, matcherString );
8401 handler.handleExpr( expr );
8402 }
8403
8404 } // namespace Catch
8405 // end catch_capture_matchers.cpp
8406 // start catch_commandline.cpp
8407
8408 // start catch_commandline.h
8409
8410 // start catch_clara.h
8411
8412 // Use Catch's value for console width (store Clara's off to the side, if present)
8413 #ifdef CLARA_CONFIG_CONSOLE_WIDTH
8414 #define CATCH_TEMP_CLARA_CONFIG_CONSOLE_WIDTH CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH
8415 #undef CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH
8416 #endif
8417 #define CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH CATCH_CONFIG_CONSOLE_WIDTH-1
8418
8419 #ifdef __clang__
8420 #pragma clang diagnostic push
8421 #pragma clang diagnostic ignored "-Wweak-vtables"
8422 #pragma clang diagnostic ignored "-Wexit-time-destructors"
8423 #pragma clang diagnostic ignored "-Wshadow"
8424 #endif
8425
8426 // start clara.hpp
8427 // Copyright 2017 Two Blue Cubes Ltd. All rights reserved.
8428 //
8429 // Distributed under the Boost Software License, Version 1.0. (See accompanying
8430 // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
8431 //
8432 // See https://github.com/philsquared/Clara for more details
8433
8434 // Clara v1.1.5
8435
8436
8437 #ifndef CATCH_CLARA_CONFIG_CONSOLE_WIDTH
8438 #define CATCH_CLARA_CONFIG_CONSOLE_WIDTH 80
8439 #endif
8440
8441 #ifndef CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH
8442 #define CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH CATCH_CLARA_CONFIG_CONSOLE_WIDTH
8443 #endif
8444
8445 #ifndef CLARA_CONFIG_OPTIONAL_TYPE
8446 #ifdef __has_include
8447 #if __has_include(<optional>) && __cplusplus >= 201703L
8448 #include <optional>
8449 #define CLARA_CONFIG_OPTIONAL_TYPE std::optional
8450 #endif
8451 #endif
8452 #endif
8453
8454 // ----------- #included from clara_textflow.hpp -----------
8455
8456 // TextFlowCpp
8457 //
8458 // A single-header library for wrapping and laying out basic text, by Phil Nash
8459 //
8460 // Distributed under the Boost Software License, Version 1.0. (See accompanying
8461 // file LICENSE.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
8462 //
8463 // This project is hosted at https://github.com/philsquared/textflowcpp
8464
8465
8466 #include <cassert>
8467 #include <ostream>
8468 #include <sstream>
8469 #include <vector>
8470
8471 #ifndef CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH
8472 #define CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH 80
8473 #endif
8474
8475 namespace Catch {
8476 namespace clara {
8477 namespace TextFlow {
8478
isWhitespace(char c)8479 inline auto isWhitespace(char c) -> bool {
8480 static std::string chars = " \t\n\r";
8481 return chars.find(c) != std::string::npos;
8482 }
isBreakableBefore(char c)8483 inline auto isBreakableBefore(char c) -> bool {
8484 static std::string chars = "[({<|";
8485 return chars.find(c) != std::string::npos;
8486 }
isBreakableAfter(char c)8487 inline auto isBreakableAfter(char c) -> bool {
8488 static std::string chars = "])}>.,:;*+-=&/\\";
8489 return chars.find(c) != std::string::npos;
8490 }
8491
8492 class Columns;
8493
8494 class Column {
8495 std::vector<std::string> m_strings;
8496 size_t m_width = CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH;
8497 size_t m_indent = 0;
8498 size_t m_initialIndent = std::string::npos;
8499
8500 public:
8501 class iterator {
8502 friend Column;
8503
8504 Column const& m_column;
8505 size_t m_stringIndex = 0;
8506 size_t m_pos = 0;
8507
8508 size_t m_len = 0;
8509 size_t m_end = 0;
8510 bool m_suffix = false;
8511
iterator(Column const & column,size_t stringIndex)8512 iterator(Column const& column, size_t stringIndex)
8513 : m_column(column),
8514 m_stringIndex(stringIndex) {}
8515
line() const8516 auto line() const -> std::string const& { return m_column.m_strings[m_stringIndex]; }
8517
isBoundary(size_t at) const8518 auto isBoundary(size_t at) const -> bool {
8519 assert(at > 0);
8520 assert(at <= line().size());
8521
8522 return at == line().size() ||
8523 (isWhitespace(line()[at]) && !isWhitespace(line()[at - 1])) ||
8524 isBreakableBefore(line()[at]) ||
8525 isBreakableAfter(line()[at - 1]);
8526 }
8527
calcLength()8528 void calcLength() {
8529 assert(m_stringIndex < m_column.m_strings.size());
8530
8531 m_suffix = false;
8532 auto width = m_column.m_width - indent();
8533 m_end = m_pos;
8534 if (line()[m_pos] == '\n') {
8535 ++m_end;
8536 }
8537 while (m_end < line().size() && line()[m_end] != '\n')
8538 ++m_end;
8539
8540 if (m_end < m_pos + width) {
8541 m_len = m_end - m_pos;
8542 } else {
8543 size_t len = width;
8544 while (len > 0 && !isBoundary(m_pos + len))
8545 --len;
8546 while (len > 0 && isWhitespace(line()[m_pos + len - 1]))
8547 --len;
8548
8549 if (len > 0) {
8550 m_len = len;
8551 } else {
8552 m_suffix = true;
8553 m_len = width - 1;
8554 }
8555 }
8556 }
8557
indent() const8558 auto indent() const -> size_t {
8559 auto initial = m_pos == 0 && m_stringIndex == 0 ? m_column.m_initialIndent : std::string::npos;
8560 return initial == std::string::npos ? m_column.m_indent : initial;
8561 }
8562
addIndentAndSuffix(std::string const & plain) const8563 auto addIndentAndSuffix(std::string const &plain) const -> std::string {
8564 return std::string(indent(), ' ') + (m_suffix ? plain + "-" : plain);
8565 }
8566
8567 public:
8568 using difference_type = std::ptrdiff_t;
8569 using value_type = std::string;
8570 using pointer = value_type * ;
8571 using reference = value_type & ;
8572 using iterator_category = std::forward_iterator_tag;
8573
iterator(Column const & column)8574 explicit iterator(Column const& column) : m_column(column) {
8575 assert(m_column.m_width > m_column.m_indent);
8576 assert(m_column.m_initialIndent == std::string::npos || m_column.m_width > m_column.m_initialIndent);
8577 calcLength();
8578 if (m_len == 0)
8579 m_stringIndex++; // Empty string
8580 }
8581
operator *() const8582 auto operator *() const -> std::string {
8583 assert(m_stringIndex < m_column.m_strings.size());
8584 assert(m_pos <= m_end);
8585 return addIndentAndSuffix(line().substr(m_pos, m_len));
8586 }
8587
operator ++()8588 auto operator ++() -> iterator& {
8589 m_pos += m_len;
8590 if (m_pos < line().size() && line()[m_pos] == '\n')
8591 m_pos += 1;
8592 else
8593 while (m_pos < line().size() && isWhitespace(line()[m_pos]))
8594 ++m_pos;
8595
8596 if (m_pos == line().size()) {
8597 m_pos = 0;
8598 ++m_stringIndex;
8599 }
8600 if (m_stringIndex < m_column.m_strings.size())
8601 calcLength();
8602 return *this;
8603 }
operator ++(int)8604 auto operator ++(int) -> iterator {
8605 iterator prev(*this);
8606 operator++();
8607 return prev;
8608 }
8609
operator ==(iterator const & other) const8610 auto operator ==(iterator const& other) const -> bool {
8611 return
8612 m_pos == other.m_pos &&
8613 m_stringIndex == other.m_stringIndex &&
8614 &m_column == &other.m_column;
8615 }
operator !=(iterator const & other) const8616 auto operator !=(iterator const& other) const -> bool {
8617 return !operator==(other);
8618 }
8619 };
8620 using const_iterator = iterator;
8621
Column(std::string const & text)8622 explicit Column(std::string const& text) { m_strings.push_back(text); }
8623
width(size_t newWidth)8624 auto width(size_t newWidth) -> Column& {
8625 assert(newWidth > 0);
8626 m_width = newWidth;
8627 return *this;
8628 }
indent(size_t newIndent)8629 auto indent(size_t newIndent) -> Column& {
8630 m_indent = newIndent;
8631 return *this;
8632 }
initialIndent(size_t newIndent)8633 auto initialIndent(size_t newIndent) -> Column& {
8634 m_initialIndent = newIndent;
8635 return *this;
8636 }
8637
width() const8638 auto width() const -> size_t { return m_width; }
begin() const8639 auto begin() const -> iterator { return iterator(*this); }
end() const8640 auto end() const -> iterator { return { *this, m_strings.size() }; }
8641
operator <<(std::ostream & os,Column const & col)8642 inline friend std::ostream& operator << (std::ostream& os, Column const& col) {
8643 bool first = true;
8644 for (auto line : col) {
8645 if (first)
8646 first = false;
8647 else
8648 os << "\n";
8649 os << line;
8650 }
8651 return os;
8652 }
8653
8654 auto operator + (Column const& other)->Columns;
8655
toString() const8656 auto toString() const -> std::string {
8657 std::ostringstream oss;
8658 oss << *this;
8659 return oss.str();
8660 }
8661 };
8662
8663 class Spacer : public Column {
8664
8665 public:
Spacer(size_t spaceWidth)8666 explicit Spacer(size_t spaceWidth) : Column("") {
8667 width(spaceWidth);
8668 }
8669 };
8670
8671 class Columns {
8672 std::vector<Column> m_columns;
8673
8674 public:
8675
8676 class iterator {
8677 friend Columns;
8678 struct EndTag {};
8679
8680 std::vector<Column> const& m_columns;
8681 std::vector<Column::iterator> m_iterators;
8682 size_t m_activeIterators;
8683
iterator(Columns const & columns,EndTag)8684 iterator(Columns const& columns, EndTag)
8685 : m_columns(columns.m_columns),
8686 m_activeIterators(0) {
8687 m_iterators.reserve(m_columns.size());
8688
8689 for (auto const& col : m_columns)
8690 m_iterators.push_back(col.end());
8691 }
8692
8693 public:
8694 using difference_type = std::ptrdiff_t;
8695 using value_type = std::string;
8696 using pointer = value_type * ;
8697 using reference = value_type & ;
8698 using iterator_category = std::forward_iterator_tag;
8699
iterator(Columns const & columns)8700 explicit iterator(Columns const& columns)
8701 : m_columns(columns.m_columns),
8702 m_activeIterators(m_columns.size()) {
8703 m_iterators.reserve(m_columns.size());
8704
8705 for (auto const& col : m_columns)
8706 m_iterators.push_back(col.begin());
8707 }
8708
operator ==(iterator const & other) const8709 auto operator ==(iterator const& other) const -> bool {
8710 return m_iterators == other.m_iterators;
8711 }
operator !=(iterator const & other) const8712 auto operator !=(iterator const& other) const -> bool {
8713 return m_iterators != other.m_iterators;
8714 }
operator *() const8715 auto operator *() const -> std::string {
8716 std::string row, padding;
8717
8718 for (size_t i = 0; i < m_columns.size(); ++i) {
8719 auto width = m_columns[i].width();
8720 if (m_iterators[i] != m_columns[i].end()) {
8721 std::string col = *m_iterators[i];
8722 row += padding + col;
8723 if (col.size() < width)
8724 padding = std::string(width - col.size(), ' ');
8725 else
8726 padding = "";
8727 } else {
8728 padding += std::string(width, ' ');
8729 }
8730 }
8731 return row;
8732 }
operator ++()8733 auto operator ++() -> iterator& {
8734 for (size_t i = 0; i < m_columns.size(); ++i) {
8735 if (m_iterators[i] != m_columns[i].end())
8736 ++m_iterators[i];
8737 }
8738 return *this;
8739 }
operator ++(int)8740 auto operator ++(int) -> iterator {
8741 iterator prev(*this);
8742 operator++();
8743 return prev;
8744 }
8745 };
8746 using const_iterator = iterator;
8747
begin() const8748 auto begin() const -> iterator { return iterator(*this); }
end() const8749 auto end() const -> iterator { return { *this, iterator::EndTag() }; }
8750
operator +=(Column const & col)8751 auto operator += (Column const& col) -> Columns& {
8752 m_columns.push_back(col);
8753 return *this;
8754 }
operator +(Column const & col)8755 auto operator + (Column const& col) -> Columns {
8756 Columns combined = *this;
8757 combined += col;
8758 return combined;
8759 }
8760
operator <<(std::ostream & os,Columns const & cols)8761 inline friend std::ostream& operator << (std::ostream& os, Columns const& cols) {
8762
8763 bool first = true;
8764 for (auto line : cols) {
8765 if (first)
8766 first = false;
8767 else
8768 os << "\n";
8769 os << line;
8770 }
8771 return os;
8772 }
8773
toString() const8774 auto toString() const -> std::string {
8775 std::ostringstream oss;
8776 oss << *this;
8777 return oss.str();
8778 }
8779 };
8780
operator +(Column const & other)8781 inline auto Column::operator + (Column const& other) -> Columns {
8782 Columns cols;
8783 cols += *this;
8784 cols += other;
8785 return cols;
8786 }
8787 }
8788
8789 }
8790 }
8791
8792 // ----------- end of #include from clara_textflow.hpp -----------
8793 // ........... back in clara.hpp
8794
8795 #include <cctype>
8796 #include <string>
8797 #include <memory>
8798 #include <set>
8799 #include <algorithm>
8800
8801 #if !defined(CATCH_PLATFORM_WINDOWS) && ( defined(WIN32) || defined(__WIN32__) || defined(_WIN32) || defined(_MSC_VER) )
8802 #define CATCH_PLATFORM_WINDOWS
8803 #endif
8804
8805 namespace Catch { namespace clara {
8806 namespace detail {
8807
8808 // Traits for extracting arg and return type of lambdas (for single argument lambdas)
8809 template<typename L>
8810 struct UnaryLambdaTraits : UnaryLambdaTraits<decltype( &L::operator() )> {};
8811
8812 template<typename ClassT, typename ReturnT, typename... Args>
8813 struct UnaryLambdaTraits<ReturnT( ClassT::* )( Args... ) const> {
8814 static const bool isValid = false;
8815 };
8816
8817 template<typename ClassT, typename ReturnT, typename ArgT>
8818 struct UnaryLambdaTraits<ReturnT( ClassT::* )( ArgT ) const> {
8819 static const bool isValid = true;
8820 using ArgType = typename std::remove_const<typename std::remove_reference<ArgT>::type>::type;
8821 using ReturnType = ReturnT;
8822 };
8823
8824 class TokenStream;
8825
8826 // Transport for raw args (copied from main args, or supplied via init list for testing)
8827 class Args {
8828 friend TokenStream;
8829 std::string m_exeName;
8830 std::vector<std::string> m_args;
8831
8832 public:
Args(int argc,char const * const * argv)8833 Args( int argc, char const* const* argv )
8834 : m_exeName(argv[0]),
8835 m_args(argv + 1, argv + argc) {}
8836
Args(std::initializer_list<std::string> args)8837 Args( std::initializer_list<std::string> args )
8838 : m_exeName( *args.begin() ),
8839 m_args( args.begin()+1, args.end() )
8840 {}
8841
exeName() const8842 auto exeName() const -> std::string {
8843 return m_exeName;
8844 }
8845 };
8846
8847 // Wraps a token coming from a token stream. These may not directly correspond to strings as a single string
8848 // may encode an option + its argument if the : or = form is used
8849 enum class TokenType {
8850 Option, Argument
8851 };
8852 struct Token {
8853 TokenType type;
8854 std::string token;
8855 };
8856
isOptPrefix(char c)8857 inline auto isOptPrefix( char c ) -> bool {
8858 return c == '-'
8859 #ifdef CATCH_PLATFORM_WINDOWS
8860 || c == '/'
8861 #endif
8862 ;
8863 }
8864
8865 // Abstracts iterators into args as a stream of tokens, with option arguments uniformly handled
8866 class TokenStream {
8867 using Iterator = std::vector<std::string>::const_iterator;
8868 Iterator it;
8869 Iterator itEnd;
8870 std::vector<Token> m_tokenBuffer;
8871
loadBuffer()8872 void loadBuffer() {
8873 m_tokenBuffer.resize( 0 );
8874
8875 // Skip any empty strings
8876 while( it != itEnd && it->empty() )
8877 ++it;
8878
8879 if( it != itEnd ) {
8880 auto const &next = *it;
8881 if( isOptPrefix( next[0] ) ) {
8882 auto delimiterPos = next.find_first_of( " :=" );
8883 if( delimiterPos != std::string::npos ) {
8884 m_tokenBuffer.push_back( { TokenType::Option, next.substr( 0, delimiterPos ) } );
8885 m_tokenBuffer.push_back( { TokenType::Argument, next.substr( delimiterPos + 1 ) } );
8886 } else {
8887 if( next[1] != '-' && next.size() > 2 ) {
8888 std::string opt = "- ";
8889 for( size_t i = 1; i < next.size(); ++i ) {
8890 opt[1] = next[i];
8891 m_tokenBuffer.push_back( { TokenType::Option, opt } );
8892 }
8893 } else {
8894 m_tokenBuffer.push_back( { TokenType::Option, next } );
8895 }
8896 }
8897 } else {
8898 m_tokenBuffer.push_back( { TokenType::Argument, next } );
8899 }
8900 }
8901 }
8902
8903 public:
TokenStream(Args const & args)8904 explicit TokenStream( Args const &args ) : TokenStream( args.m_args.begin(), args.m_args.end() ) {}
8905
TokenStream(Iterator it,Iterator itEnd)8906 TokenStream( Iterator it, Iterator itEnd ) : it( it ), itEnd( itEnd ) {
8907 loadBuffer();
8908 }
8909
operator bool() const8910 explicit operator bool() const {
8911 return !m_tokenBuffer.empty() || it != itEnd;
8912 }
8913
count() const8914 auto count() const -> size_t { return m_tokenBuffer.size() + (itEnd - it); }
8915
operator *() const8916 auto operator*() const -> Token {
8917 assert( !m_tokenBuffer.empty() );
8918 return m_tokenBuffer.front();
8919 }
8920
operator ->() const8921 auto operator->() const -> Token const * {
8922 assert( !m_tokenBuffer.empty() );
8923 return &m_tokenBuffer.front();
8924 }
8925
operator ++()8926 auto operator++() -> TokenStream & {
8927 if( m_tokenBuffer.size() >= 2 ) {
8928 m_tokenBuffer.erase( m_tokenBuffer.begin() );
8929 } else {
8930 if( it != itEnd )
8931 ++it;
8932 loadBuffer();
8933 }
8934 return *this;
8935 }
8936 };
8937
8938 class ResultBase {
8939 public:
8940 enum Type {
8941 Ok, LogicError, RuntimeError
8942 };
8943
8944 protected:
ResultBase(Type type)8945 ResultBase( Type type ) : m_type( type ) {}
8946 virtual ~ResultBase() = default;
8947
8948 virtual void enforceOk() const = 0;
8949
8950 Type m_type;
8951 };
8952
8953 template<typename T>
8954 class ResultValueBase : public ResultBase {
8955 public:
value() const8956 auto value() const -> T const & {
8957 enforceOk();
8958 return m_value;
8959 }
8960
8961 protected:
ResultValueBase(Type type)8962 ResultValueBase( Type type ) : ResultBase( type ) {}
8963
ResultValueBase(ResultValueBase const & other)8964 ResultValueBase( ResultValueBase const &other ) : ResultBase( other ) {
8965 if( m_type == ResultBase::Ok )
8966 new( &m_value ) T( other.m_value );
8967 }
8968
ResultValueBase(Type,T const & value)8969 ResultValueBase( Type, T const &value ) : ResultBase( Ok ) {
8970 new( &m_value ) T( value );
8971 }
8972
operator =(ResultValueBase const & other)8973 auto operator=( ResultValueBase const &other ) -> ResultValueBase & {
8974 if( m_type == ResultBase::Ok )
8975 m_value.~T();
8976 ResultBase::operator=(other);
8977 if( m_type == ResultBase::Ok )
8978 new( &m_value ) T( other.m_value );
8979 return *this;
8980 }
8981
~ResultValueBase()8982 ~ResultValueBase() override {
8983 if( m_type == Ok )
8984 m_value.~T();
8985 }
8986
8987 union {
8988 T m_value;
8989 };
8990 };
8991
8992 template<>
8993 class ResultValueBase<void> : public ResultBase {
8994 protected:
8995 using ResultBase::ResultBase;
8996 };
8997
8998 template<typename T = void>
8999 class BasicResult : public ResultValueBase<T> {
9000 public:
9001 template<typename U>
BasicResult(BasicResult<U> const & other)9002 explicit BasicResult( BasicResult<U> const &other )
9003 : ResultValueBase<T>( other.type() ),
9004 m_errorMessage( other.errorMessage() )
9005 {
9006 assert( type() != ResultBase::Ok );
9007 }
9008
9009 template<typename U>
ok(U const & value)9010 static auto ok( U const &value ) -> BasicResult { return { ResultBase::Ok, value }; }
ok()9011 static auto ok() -> BasicResult { return { ResultBase::Ok }; }
logicError(std::string const & message)9012 static auto logicError( std::string const &message ) -> BasicResult { return { ResultBase::LogicError, message }; }
runtimeError(std::string const & message)9013 static auto runtimeError( std::string const &message ) -> BasicResult { return { ResultBase::RuntimeError, message }; }
9014
operator bool() const9015 explicit operator bool() const { return m_type == ResultBase::Ok; }
type() const9016 auto type() const -> ResultBase::Type { return m_type; }
errorMessage() const9017 auto errorMessage() const -> std::string { return m_errorMessage; }
9018
9019 protected:
enforceOk() const9020 void enforceOk() const override {
9021
9022 // Errors shouldn't reach this point, but if they do
9023 // the actual error message will be in m_errorMessage
9024 assert( m_type != ResultBase::LogicError );
9025 assert( m_type != ResultBase::RuntimeError );
9026 if( m_type != ResultBase::Ok )
9027 std::abort();
9028 }
9029
9030 std::string m_errorMessage; // Only populated if resultType is an error
9031
BasicResult(ResultBase::Type type,std::string const & message)9032 BasicResult( ResultBase::Type type, std::string const &message )
9033 : ResultValueBase<T>(type),
9034 m_errorMessage(message)
9035 {
9036 assert( m_type != ResultBase::Ok );
9037 }
9038
9039 using ResultValueBase<T>::ResultValueBase;
9040 using ResultBase::m_type;
9041 };
9042
9043 enum class ParseResultType {
9044 Matched, NoMatch, ShortCircuitAll, ShortCircuitSame
9045 };
9046
9047 class ParseState {
9048 public:
9049
ParseState(ParseResultType type,TokenStream const & remainingTokens)9050 ParseState( ParseResultType type, TokenStream const &remainingTokens )
9051 : m_type(type),
9052 m_remainingTokens( remainingTokens )
9053 {}
9054
type() const9055 auto type() const -> ParseResultType { return m_type; }
remainingTokens() const9056 auto remainingTokens() const -> TokenStream { return m_remainingTokens; }
9057
9058 private:
9059 ParseResultType m_type;
9060 TokenStream m_remainingTokens;
9061 };
9062
9063 using Result = BasicResult<void>;
9064 using ParserResult = BasicResult<ParseResultType>;
9065 using InternalParseResult = BasicResult<ParseState>;
9066
9067 struct HelpColumns {
9068 std::string left;
9069 std::string right;
9070 };
9071
9072 template<typename T>
convertInto(std::string const & source,T & target)9073 inline auto convertInto( std::string const &source, T& target ) -> ParserResult {
9074 std::stringstream ss;
9075 ss << source;
9076 ss >> target;
9077 if( ss.fail() )
9078 return ParserResult::runtimeError( "Unable to convert '" + source + "' to destination type" );
9079 else
9080 return ParserResult::ok( ParseResultType::Matched );
9081 }
convertInto(std::string const & source,std::string & target)9082 inline auto convertInto( std::string const &source, std::string& target ) -> ParserResult {
9083 target = source;
9084 return ParserResult::ok( ParseResultType::Matched );
9085 }
convertInto(std::string const & source,bool & target)9086 inline auto convertInto( std::string const &source, bool &target ) -> ParserResult {
9087 std::string srcLC = source;
9088 std::transform( srcLC.begin(), srcLC.end(), srcLC.begin(), []( unsigned char c ) { return static_cast<char>( std::tolower(c) ); } );
9089 if (srcLC == "y" || srcLC == "1" || srcLC == "true" || srcLC == "yes" || srcLC == "on")
9090 target = true;
9091 else if (srcLC == "n" || srcLC == "0" || srcLC == "false" || srcLC == "no" || srcLC == "off")
9092 target = false;
9093 else
9094 return ParserResult::runtimeError( "Expected a boolean value but did not recognise: '" + source + "'" );
9095 return ParserResult::ok( ParseResultType::Matched );
9096 }
9097 #ifdef CLARA_CONFIG_OPTIONAL_TYPE
9098 template<typename T>
convertInto(std::string const & source,CLARA_CONFIG_OPTIONAL_TYPE<T> & target)9099 inline auto convertInto( std::string const &source, CLARA_CONFIG_OPTIONAL_TYPE<T>& target ) -> ParserResult {
9100 T temp;
9101 auto result = convertInto( source, temp );
9102 if( result )
9103 target = std::move(temp);
9104 return result;
9105 }
9106 #endif // CLARA_CONFIG_OPTIONAL_TYPE
9107
9108 struct NonCopyable {
9109 NonCopyable() = default;
9110 NonCopyable( NonCopyable const & ) = delete;
9111 NonCopyable( NonCopyable && ) = delete;
9112 NonCopyable &operator=( NonCopyable const & ) = delete;
9113 NonCopyable &operator=( NonCopyable && ) = delete;
9114 };
9115
9116 struct BoundRef : NonCopyable {
9117 virtual ~BoundRef() = default;
isContainerCatch::clara::detail::BoundRef9118 virtual auto isContainer() const -> bool { return false; }
isFlagCatch::clara::detail::BoundRef9119 virtual auto isFlag() const -> bool { return false; }
9120 };
9121 struct BoundValueRefBase : BoundRef {
9122 virtual auto setValue( std::string const &arg ) -> ParserResult = 0;
9123 };
9124 struct BoundFlagRefBase : BoundRef {
9125 virtual auto setFlag( bool flag ) -> ParserResult = 0;
isFlagCatch::clara::detail::BoundFlagRefBase9126 virtual auto isFlag() const -> bool { return true; }
9127 };
9128
9129 template<typename T>
9130 struct BoundValueRef : BoundValueRefBase {
9131 T &m_ref;
9132
BoundValueRefCatch::clara::detail::BoundValueRef9133 explicit BoundValueRef( T &ref ) : m_ref( ref ) {}
9134
setValueCatch::clara::detail::BoundValueRef9135 auto setValue( std::string const &arg ) -> ParserResult override {
9136 return convertInto( arg, m_ref );
9137 }
9138 };
9139
9140 template<typename T>
9141 struct BoundValueRef<std::vector<T>> : BoundValueRefBase {
9142 std::vector<T> &m_ref;
9143
BoundValueRefCatch::clara::detail::BoundValueRef9144 explicit BoundValueRef( std::vector<T> &ref ) : m_ref( ref ) {}
9145
isContainerCatch::clara::detail::BoundValueRef9146 auto isContainer() const -> bool override { return true; }
9147
setValueCatch::clara::detail::BoundValueRef9148 auto setValue( std::string const &arg ) -> ParserResult override {
9149 T temp;
9150 auto result = convertInto( arg, temp );
9151 if( result )
9152 m_ref.push_back( temp );
9153 return result;
9154 }
9155 };
9156
9157 struct BoundFlagRef : BoundFlagRefBase {
9158 bool &m_ref;
9159
BoundFlagRefCatch::clara::detail::BoundFlagRef9160 explicit BoundFlagRef( bool &ref ) : m_ref( ref ) {}
9161
setFlagCatch::clara::detail::BoundFlagRef9162 auto setFlag( bool flag ) -> ParserResult override {
9163 m_ref = flag;
9164 return ParserResult::ok( ParseResultType::Matched );
9165 }
9166 };
9167
9168 template<typename ReturnType>
9169 struct LambdaInvoker {
9170 static_assert( std::is_same<ReturnType, ParserResult>::value, "Lambda must return void or clara::ParserResult" );
9171
9172 template<typename L, typename ArgType>
invokeCatch::clara::detail::LambdaInvoker9173 static auto invoke( L const &lambda, ArgType const &arg ) -> ParserResult {
9174 return lambda( arg );
9175 }
9176 };
9177
9178 template<>
9179 struct LambdaInvoker<void> {
9180 template<typename L, typename ArgType>
invokeCatch::clara::detail::LambdaInvoker9181 static auto invoke( L const &lambda, ArgType const &arg ) -> ParserResult {
9182 lambda( arg );
9183 return ParserResult::ok( ParseResultType::Matched );
9184 }
9185 };
9186
9187 template<typename ArgType, typename L>
invokeLambda(L const & lambda,std::string const & arg)9188 inline auto invokeLambda( L const &lambda, std::string const &arg ) -> ParserResult {
9189 ArgType temp{};
9190 auto result = convertInto( arg, temp );
9191 return !result
9192 ? result
9193 : LambdaInvoker<typename UnaryLambdaTraits<L>::ReturnType>::invoke( lambda, temp );
9194 }
9195
9196 template<typename L>
9197 struct BoundLambda : BoundValueRefBase {
9198 L m_lambda;
9199
9200 static_assert( UnaryLambdaTraits<L>::isValid, "Supplied lambda must take exactly one argument" );
BoundLambdaCatch::clara::detail::BoundLambda9201 explicit BoundLambda( L const &lambda ) : m_lambda( lambda ) {}
9202
setValueCatch::clara::detail::BoundLambda9203 auto setValue( std::string const &arg ) -> ParserResult override {
9204 return invokeLambda<typename UnaryLambdaTraits<L>::ArgType>( m_lambda, arg );
9205 }
9206 };
9207
9208 template<typename L>
9209 struct BoundFlagLambda : BoundFlagRefBase {
9210 L m_lambda;
9211
9212 static_assert( UnaryLambdaTraits<L>::isValid, "Supplied lambda must take exactly one argument" );
9213 static_assert( std::is_same<typename UnaryLambdaTraits<L>::ArgType, bool>::value, "flags must be boolean" );
9214
BoundFlagLambdaCatch::clara::detail::BoundFlagLambda9215 explicit BoundFlagLambda( L const &lambda ) : m_lambda( lambda ) {}
9216
setFlagCatch::clara::detail::BoundFlagLambda9217 auto setFlag( bool flag ) -> ParserResult override {
9218 return LambdaInvoker<typename UnaryLambdaTraits<L>::ReturnType>::invoke( m_lambda, flag );
9219 }
9220 };
9221
9222 enum class Optionality { Optional, Required };
9223
9224 struct Parser;
9225
9226 class ParserBase {
9227 public:
9228 virtual ~ParserBase() = default;
validate() const9229 virtual auto validate() const -> Result { return Result::ok(); }
9230 virtual auto parse( std::string const& exeName, TokenStream const &tokens) const -> InternalParseResult = 0;
cardinality() const9231 virtual auto cardinality() const -> size_t { return 1; }
9232
parse(Args const & args) const9233 auto parse( Args const &args ) const -> InternalParseResult {
9234 return parse( args.exeName(), TokenStream( args ) );
9235 }
9236 };
9237
9238 template<typename DerivedT>
9239 class ComposableParserImpl : public ParserBase {
9240 public:
9241 template<typename T>
9242 auto operator|( T const &other ) const -> Parser;
9243
9244 template<typename T>
9245 auto operator+( T const &other ) const -> Parser;
9246 };
9247
9248 // Common code and state for Args and Opts
9249 template<typename DerivedT>
9250 class ParserRefImpl : public ComposableParserImpl<DerivedT> {
9251 protected:
9252 Optionality m_optionality = Optionality::Optional;
9253 std::shared_ptr<BoundRef> m_ref;
9254 std::string m_hint;
9255 std::string m_description;
9256
ParserRefImpl(std::shared_ptr<BoundRef> const & ref)9257 explicit ParserRefImpl( std::shared_ptr<BoundRef> const &ref ) : m_ref( ref ) {}
9258
9259 public:
9260 template<typename T>
ParserRefImpl(T & ref,std::string const & hint)9261 ParserRefImpl( T &ref, std::string const &hint )
9262 : m_ref( std::make_shared<BoundValueRef<T>>( ref ) ),
9263 m_hint( hint )
9264 {}
9265
9266 template<typename LambdaT>
ParserRefImpl(LambdaT const & ref,std::string const & hint)9267 ParserRefImpl( LambdaT const &ref, std::string const &hint )
9268 : m_ref( std::make_shared<BoundLambda<LambdaT>>( ref ) ),
9269 m_hint(hint)
9270 {}
9271
operator ()(std::string const & description)9272 auto operator()( std::string const &description ) -> DerivedT & {
9273 m_description = description;
9274 return static_cast<DerivedT &>( *this );
9275 }
9276
optional()9277 auto optional() -> DerivedT & {
9278 m_optionality = Optionality::Optional;
9279 return static_cast<DerivedT &>( *this );
9280 };
9281
required()9282 auto required() -> DerivedT & {
9283 m_optionality = Optionality::Required;
9284 return static_cast<DerivedT &>( *this );
9285 };
9286
isOptional() const9287 auto isOptional() const -> bool {
9288 return m_optionality == Optionality::Optional;
9289 }
9290
cardinality() const9291 auto cardinality() const -> size_t override {
9292 if( m_ref->isContainer() )
9293 return 0;
9294 else
9295 return 1;
9296 }
9297
hint() const9298 auto hint() const -> std::string { return m_hint; }
9299 };
9300
9301 class ExeName : public ComposableParserImpl<ExeName> {
9302 std::shared_ptr<std::string> m_name;
9303 std::shared_ptr<BoundValueRefBase> m_ref;
9304
9305 template<typename LambdaT>
makeRef(LambdaT const & lambda)9306 static auto makeRef(LambdaT const &lambda) -> std::shared_ptr<BoundValueRefBase> {
9307 return std::make_shared<BoundLambda<LambdaT>>( lambda) ;
9308 }
9309
9310 public:
ExeName()9311 ExeName() : m_name( std::make_shared<std::string>( "<executable>" ) ) {}
9312
ExeName(std::string & ref)9313 explicit ExeName( std::string &ref ) : ExeName() {
9314 m_ref = std::make_shared<BoundValueRef<std::string>>( ref );
9315 }
9316
9317 template<typename LambdaT>
ExeName(LambdaT const & lambda)9318 explicit ExeName( LambdaT const& lambda ) : ExeName() {
9319 m_ref = std::make_shared<BoundLambda<LambdaT>>( lambda );
9320 }
9321
9322 // The exe name is not parsed out of the normal tokens, but is handled specially
parse(std::string const &,TokenStream const & tokens) const9323 auto parse( std::string const&, TokenStream const &tokens ) const -> InternalParseResult override {
9324 return InternalParseResult::ok( ParseState( ParseResultType::NoMatch, tokens ) );
9325 }
9326
name() const9327 auto name() const -> std::string { return *m_name; }
set(std::string const & newName)9328 auto set( std::string const& newName ) -> ParserResult {
9329
9330 auto lastSlash = newName.find_last_of( "\\/" );
9331 auto filename = ( lastSlash == std::string::npos )
9332 ? newName
9333 : newName.substr( lastSlash+1 );
9334
9335 *m_name = filename;
9336 if( m_ref )
9337 return m_ref->setValue( filename );
9338 else
9339 return ParserResult::ok( ParseResultType::Matched );
9340 }
9341 };
9342
9343 class Arg : public ParserRefImpl<Arg> {
9344 public:
9345 using ParserRefImpl::ParserRefImpl;
9346
parse(std::string const &,TokenStream const & tokens) const9347 auto parse( std::string const &, TokenStream const &tokens ) const -> InternalParseResult override {
9348 auto validationResult = validate();
9349 if( !validationResult )
9350 return InternalParseResult( validationResult );
9351
9352 auto remainingTokens = tokens;
9353 auto const &token = *remainingTokens;
9354 if( token.type != TokenType::Argument )
9355 return InternalParseResult::ok( ParseState( ParseResultType::NoMatch, remainingTokens ) );
9356
9357 assert( !m_ref->isFlag() );
9358 auto valueRef = static_cast<detail::BoundValueRefBase*>( m_ref.get() );
9359
9360 auto result = valueRef->setValue( remainingTokens->token );
9361 if( !result )
9362 return InternalParseResult( result );
9363 else
9364 return InternalParseResult::ok( ParseState( ParseResultType::Matched, ++remainingTokens ) );
9365 }
9366 };
9367
normaliseOpt(std::string const & optName)9368 inline auto normaliseOpt( std::string const &optName ) -> std::string {
9369 #ifdef CATCH_PLATFORM_WINDOWS
9370 if( optName[0] == '/' )
9371 return "-" + optName.substr( 1 );
9372 else
9373 #endif
9374 return optName;
9375 }
9376
9377 class Opt : public ParserRefImpl<Opt> {
9378 protected:
9379 std::vector<std::string> m_optNames;
9380
9381 public:
9382 template<typename LambdaT>
Opt(LambdaT const & ref)9383 explicit Opt( LambdaT const &ref ) : ParserRefImpl( std::make_shared<BoundFlagLambda<LambdaT>>( ref ) ) {}
9384
Opt(bool & ref)9385 explicit Opt( bool &ref ) : ParserRefImpl( std::make_shared<BoundFlagRef>( ref ) ) {}
9386
9387 template<typename LambdaT>
Opt(LambdaT const & ref,std::string const & hint)9388 Opt( LambdaT const &ref, std::string const &hint ) : ParserRefImpl( ref, hint ) {}
9389
9390 template<typename T>
Opt(T & ref,std::string const & hint)9391 Opt( T &ref, std::string const &hint ) : ParserRefImpl( ref, hint ) {}
9392
operator [](std::string const & optName)9393 auto operator[]( std::string const &optName ) -> Opt & {
9394 m_optNames.push_back( optName );
9395 return *this;
9396 }
9397
getHelpColumns() const9398 auto getHelpColumns() const -> std::vector<HelpColumns> {
9399 std::ostringstream oss;
9400 bool first = true;
9401 for( auto const &opt : m_optNames ) {
9402 if (first)
9403 first = false;
9404 else
9405 oss << ", ";
9406 oss << opt;
9407 }
9408 if( !m_hint.empty() )
9409 oss << " <" << m_hint << ">";
9410 return { { oss.str(), m_description } };
9411 }
9412
isMatch(std::string const & optToken) const9413 auto isMatch( std::string const &optToken ) const -> bool {
9414 auto normalisedToken = normaliseOpt( optToken );
9415 for( auto const &name : m_optNames ) {
9416 if( normaliseOpt( name ) == normalisedToken )
9417 return true;
9418 }
9419 return false;
9420 }
9421
9422 using ParserBase::parse;
9423
parse(std::string const &,TokenStream const & tokens) const9424 auto parse( std::string const&, TokenStream const &tokens ) const -> InternalParseResult override {
9425 auto validationResult = validate();
9426 if( !validationResult )
9427 return InternalParseResult( validationResult );
9428
9429 auto remainingTokens = tokens;
9430 if( remainingTokens && remainingTokens->type == TokenType::Option ) {
9431 auto const &token = *remainingTokens;
9432 if( isMatch(token.token ) ) {
9433 if( m_ref->isFlag() ) {
9434 auto flagRef = static_cast<detail::BoundFlagRefBase*>( m_ref.get() );
9435 auto result = flagRef->setFlag( true );
9436 if( !result )
9437 return InternalParseResult( result );
9438 if( result.value() == ParseResultType::ShortCircuitAll )
9439 return InternalParseResult::ok( ParseState( result.value(), remainingTokens ) );
9440 } else {
9441 auto valueRef = static_cast<detail::BoundValueRefBase*>( m_ref.get() );
9442 ++remainingTokens;
9443 if( !remainingTokens )
9444 return InternalParseResult::runtimeError( "Expected argument following " + token.token );
9445 auto const &argToken = *remainingTokens;
9446 if( argToken.type != TokenType::Argument )
9447 return InternalParseResult::runtimeError( "Expected argument following " + token.token );
9448 auto result = valueRef->setValue( argToken.token );
9449 if( !result )
9450 return InternalParseResult( result );
9451 if( result.value() == ParseResultType::ShortCircuitAll )
9452 return InternalParseResult::ok( ParseState( result.value(), remainingTokens ) );
9453 }
9454 return InternalParseResult::ok( ParseState( ParseResultType::Matched, ++remainingTokens ) );
9455 }
9456 }
9457 return InternalParseResult::ok( ParseState( ParseResultType::NoMatch, remainingTokens ) );
9458 }
9459
validate() const9460 auto validate() const -> Result override {
9461 if( m_optNames.empty() )
9462 return Result::logicError( "No options supplied to Opt" );
9463 for( auto const &name : m_optNames ) {
9464 if( name.empty() )
9465 return Result::logicError( "Option name cannot be empty" );
9466 #ifdef CATCH_PLATFORM_WINDOWS
9467 if( name[0] != '-' && name[0] != '/' )
9468 return Result::logicError( "Option name must begin with '-' or '/'" );
9469 #else
9470 if( name[0] != '-' )
9471 return Result::logicError( "Option name must begin with '-'" );
9472 #endif
9473 }
9474 return ParserRefImpl::validate();
9475 }
9476 };
9477
9478 struct Help : Opt {
HelpCatch::clara::detail::Help9479 Help( bool &showHelpFlag )
9480 : Opt([&]( bool flag ) {
9481 showHelpFlag = flag;
9482 return ParserResult::ok( ParseResultType::ShortCircuitAll );
9483 })
9484 {
9485 static_cast<Opt &>( *this )
9486 ("display usage information")
9487 ["-?"]["-h"]["--help"]
9488 .optional();
9489 }
9490 };
9491
9492 struct Parser : ParserBase {
9493
9494 mutable ExeName m_exeName;
9495 std::vector<Opt> m_options;
9496 std::vector<Arg> m_args;
9497
operator |=Catch::clara::detail::Parser9498 auto operator|=( ExeName const &exeName ) -> Parser & {
9499 m_exeName = exeName;
9500 return *this;
9501 }
9502
operator |=Catch::clara::detail::Parser9503 auto operator|=( Arg const &arg ) -> Parser & {
9504 m_args.push_back(arg);
9505 return *this;
9506 }
9507
operator |=Catch::clara::detail::Parser9508 auto operator|=( Opt const &opt ) -> Parser & {
9509 m_options.push_back(opt);
9510 return *this;
9511 }
9512
operator |=Catch::clara::detail::Parser9513 auto operator|=( Parser const &other ) -> Parser & {
9514 m_options.insert(m_options.end(), other.m_options.begin(), other.m_options.end());
9515 m_args.insert(m_args.end(), other.m_args.begin(), other.m_args.end());
9516 return *this;
9517 }
9518
9519 template<typename T>
operator |Catch::clara::detail::Parser9520 auto operator|( T const &other ) const -> Parser {
9521 return Parser( *this ) |= other;
9522 }
9523
9524 // Forward deprecated interface with '+' instead of '|'
9525 template<typename T>
operator +=Catch::clara::detail::Parser9526 auto operator+=( T const &other ) -> Parser & { return operator|=( other ); }
9527 template<typename T>
operator +Catch::clara::detail::Parser9528 auto operator+( T const &other ) const -> Parser { return operator|( other ); }
9529
getHelpColumnsCatch::clara::detail::Parser9530 auto getHelpColumns() const -> std::vector<HelpColumns> {
9531 std::vector<HelpColumns> cols;
9532 for (auto const &o : m_options) {
9533 auto childCols = o.getHelpColumns();
9534 cols.insert( cols.end(), childCols.begin(), childCols.end() );
9535 }
9536 return cols;
9537 }
9538
writeToStreamCatch::clara::detail::Parser9539 void writeToStream( std::ostream &os ) const {
9540 if (!m_exeName.name().empty()) {
9541 os << "usage:\n" << " " << m_exeName.name() << " ";
9542 bool required = true, first = true;
9543 for( auto const &arg : m_args ) {
9544 if (first)
9545 first = false;
9546 else
9547 os << " ";
9548 if( arg.isOptional() && required ) {
9549 os << "[";
9550 required = false;
9551 }
9552 os << "<" << arg.hint() << ">";
9553 if( arg.cardinality() == 0 )
9554 os << " ... ";
9555 }
9556 if( !required )
9557 os << "]";
9558 if( !m_options.empty() )
9559 os << " options";
9560 os << "\n\nwhere options are:" << std::endl;
9561 }
9562
9563 auto rows = getHelpColumns();
9564 size_t consoleWidth = CATCH_CLARA_CONFIG_CONSOLE_WIDTH;
9565 size_t optWidth = 0;
9566 for( auto const &cols : rows )
9567 optWidth = (std::max)(optWidth, cols.left.size() + 2);
9568
9569 optWidth = (std::min)(optWidth, consoleWidth/2);
9570
9571 for( auto const &cols : rows ) {
9572 auto row =
9573 TextFlow::Column( cols.left ).width( optWidth ).indent( 2 ) +
9574 TextFlow::Spacer(4) +
9575 TextFlow::Column( cols.right ).width( consoleWidth - 7 - optWidth );
9576 os << row << std::endl;
9577 }
9578 }
9579
operator <<(std::ostream & os,Parser const & parser)9580 friend auto operator<<( std::ostream &os, Parser const &parser ) -> std::ostream& {
9581 parser.writeToStream( os );
9582 return os;
9583 }
9584
validateCatch::clara::detail::Parser9585 auto validate() const -> Result override {
9586 for( auto const &opt : m_options ) {
9587 auto result = opt.validate();
9588 if( !result )
9589 return result;
9590 }
9591 for( auto const &arg : m_args ) {
9592 auto result = arg.validate();
9593 if( !result )
9594 return result;
9595 }
9596 return Result::ok();
9597 }
9598
9599 using ParserBase::parse;
9600
parseCatch::clara::detail::Parser9601 auto parse( std::string const& exeName, TokenStream const &tokens ) const -> InternalParseResult override {
9602
9603 struct ParserInfo {
9604 ParserBase const* parser = nullptr;
9605 size_t count = 0;
9606 };
9607 const size_t totalParsers = m_options.size() + m_args.size();
9608 assert( totalParsers < 512 );
9609 // ParserInfo parseInfos[totalParsers]; // <-- this is what we really want to do
9610 ParserInfo parseInfos[512];
9611
9612 {
9613 size_t i = 0;
9614 for (auto const &opt : m_options) parseInfos[i++].parser = &opt;
9615 for (auto const &arg : m_args) parseInfos[i++].parser = &arg;
9616 }
9617
9618 m_exeName.set( exeName );
9619
9620 auto result = InternalParseResult::ok( ParseState( ParseResultType::NoMatch, tokens ) );
9621 while( result.value().remainingTokens() ) {
9622 bool tokenParsed = false;
9623
9624 for( size_t i = 0; i < totalParsers; ++i ) {
9625 auto& parseInfo = parseInfos[i];
9626 if( parseInfo.parser->cardinality() == 0 || parseInfo.count < parseInfo.parser->cardinality() ) {
9627 result = parseInfo.parser->parse(exeName, result.value().remainingTokens());
9628 if (!result)
9629 return result;
9630 if (result.value().type() != ParseResultType::NoMatch) {
9631 tokenParsed = true;
9632 ++parseInfo.count;
9633 break;
9634 }
9635 }
9636 }
9637
9638 if( result.value().type() == ParseResultType::ShortCircuitAll )
9639 return result;
9640 if( !tokenParsed )
9641 return InternalParseResult::runtimeError( "Unrecognised token: " + result.value().remainingTokens()->token );
9642 }
9643 // !TBD Check missing required options
9644 return result;
9645 }
9646 };
9647
9648 template<typename DerivedT>
9649 template<typename T>
operator |(T const & other) const9650 auto ComposableParserImpl<DerivedT>::operator|( T const &other ) const -> Parser {
9651 return Parser() | static_cast<DerivedT const &>( *this ) | other;
9652 }
9653 } // namespace detail
9654
9655 // A Combined parser
9656 using detail::Parser;
9657
9658 // A parser for options
9659 using detail::Opt;
9660
9661 // A parser for arguments
9662 using detail::Arg;
9663
9664 // Wrapper for argc, argv from main()
9665 using detail::Args;
9666
9667 // Specifies the name of the executable
9668 using detail::ExeName;
9669
9670 // Convenience wrapper for option parser that specifies the help option
9671 using detail::Help;
9672
9673 // enum of result types from a parse
9674 using detail::ParseResultType;
9675
9676 // Result type for parser operation
9677 using detail::ParserResult;
9678
9679 }} // namespace Catch::clara
9680
9681 // end clara.hpp
9682 #ifdef __clang__
9683 #pragma clang diagnostic pop
9684 #endif
9685
9686 // Restore Clara's value for console width, if present
9687 #ifdef CATCH_TEMP_CLARA_CONFIG_CONSOLE_WIDTH
9688 #define CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH CATCH_TEMP_CLARA_CONFIG_CONSOLE_WIDTH
9689 #undef CATCH_TEMP_CLARA_CONFIG_CONSOLE_WIDTH
9690 #endif
9691
9692 // end catch_clara.h
9693 namespace Catch {
9694
9695 clara::Parser makeCommandLineParser( ConfigData& config );
9696
9697 } // end namespace Catch
9698
9699 // end catch_commandline.h
9700 #include <fstream>
9701 #include <ctime>
9702
9703 namespace Catch {
9704
makeCommandLineParser(ConfigData & config)9705 clara::Parser makeCommandLineParser( ConfigData& config ) {
9706
9707 using namespace clara;
9708
9709 auto const setWarning = [&]( std::string const& warning ) {
9710 auto warningSet = [&]() {
9711 if( warning == "NoAssertions" )
9712 return WarnAbout::NoAssertions;
9713
9714 if ( warning == "NoTests" )
9715 return WarnAbout::NoTests;
9716
9717 return WarnAbout::Nothing;
9718 }();
9719
9720 if (warningSet == WarnAbout::Nothing)
9721 return ParserResult::runtimeError( "Unrecognised warning: '" + warning + "'" );
9722 config.warnings = static_cast<WarnAbout::What>( config.warnings | warningSet );
9723 return ParserResult::ok( ParseResultType::Matched );
9724 };
9725 auto const loadTestNamesFromFile = [&]( std::string const& filename ) {
9726 std::ifstream f( filename.c_str() );
9727 if( !f.is_open() )
9728 return ParserResult::runtimeError( "Unable to load input file: '" + filename + "'" );
9729
9730 std::string line;
9731 while( std::getline( f, line ) ) {
9732 line = trim(line);
9733 if( !line.empty() && !startsWith( line, '#' ) ) {
9734 if( !startsWith( line, '"' ) )
9735 line = '"' + line + '"';
9736 config.testsOrTags.push_back( line );
9737 config.testsOrTags.emplace_back( "," );
9738 }
9739 }
9740 //Remove comma in the end
9741 if(!config.testsOrTags.empty())
9742 config.testsOrTags.erase( config.testsOrTags.end()-1 );
9743
9744 return ParserResult::ok( ParseResultType::Matched );
9745 };
9746 auto const setTestOrder = [&]( std::string const& order ) {
9747 if( startsWith( "declared", order ) )
9748 config.runOrder = RunTests::InDeclarationOrder;
9749 else if( startsWith( "lexical", order ) )
9750 config.runOrder = RunTests::InLexicographicalOrder;
9751 else if( startsWith( "random", order ) )
9752 config.runOrder = RunTests::InRandomOrder;
9753 else
9754 return clara::ParserResult::runtimeError( "Unrecognised ordering: '" + order + "'" );
9755 return ParserResult::ok( ParseResultType::Matched );
9756 };
9757 auto const setRngSeed = [&]( std::string const& seed ) {
9758 if( seed != "time" )
9759 return clara::detail::convertInto( seed, config.rngSeed );
9760 config.rngSeed = static_cast<unsigned int>( std::time(nullptr) );
9761 return ParserResult::ok( ParseResultType::Matched );
9762 };
9763 auto const setColourUsage = [&]( std::string const& useColour ) {
9764 auto mode = toLower( useColour );
9765
9766 if( mode == "yes" )
9767 config.useColour = UseColour::Yes;
9768 else if( mode == "no" )
9769 config.useColour = UseColour::No;
9770 else if( mode == "auto" )
9771 config.useColour = UseColour::Auto;
9772 else
9773 return ParserResult::runtimeError( "colour mode must be one of: auto, yes or no. '" + useColour + "' not recognised" );
9774 return ParserResult::ok( ParseResultType::Matched );
9775 };
9776 auto const setWaitForKeypress = [&]( std::string const& keypress ) {
9777 auto keypressLc = toLower( keypress );
9778 if (keypressLc == "never")
9779 config.waitForKeypress = WaitForKeypress::Never;
9780 else if( keypressLc == "start" )
9781 config.waitForKeypress = WaitForKeypress::BeforeStart;
9782 else if( keypressLc == "exit" )
9783 config.waitForKeypress = WaitForKeypress::BeforeExit;
9784 else if( keypressLc == "both" )
9785 config.waitForKeypress = WaitForKeypress::BeforeStartAndExit;
9786 else
9787 return ParserResult::runtimeError( "keypress argument must be one of: never, start, exit or both. '" + keypress + "' not recognised" );
9788 return ParserResult::ok( ParseResultType::Matched );
9789 };
9790 auto const setVerbosity = [&]( std::string const& verbosity ) {
9791 auto lcVerbosity = toLower( verbosity );
9792 if( lcVerbosity == "quiet" )
9793 config.verbosity = Verbosity::Quiet;
9794 else if( lcVerbosity == "normal" )
9795 config.verbosity = Verbosity::Normal;
9796 else if( lcVerbosity == "high" )
9797 config.verbosity = Verbosity::High;
9798 else
9799 return ParserResult::runtimeError( "Unrecognised verbosity, '" + verbosity + "'" );
9800 return ParserResult::ok( ParseResultType::Matched );
9801 };
9802 auto const setReporter = [&]( std::string const& reporter ) {
9803 IReporterRegistry::FactoryMap const& factories = getRegistryHub().getReporterRegistry().getFactories();
9804
9805 auto lcReporter = toLower( reporter );
9806 auto result = factories.find( lcReporter );
9807
9808 if( factories.end() != result )
9809 config.reporterName = lcReporter;
9810 else
9811 return ParserResult::runtimeError( "Unrecognized reporter, '" + reporter + "'. Check available with --list-reporters" );
9812 return ParserResult::ok( ParseResultType::Matched );
9813 };
9814
9815 auto cli
9816 = ExeName( config.processName )
9817 | Help( config.showHelp )
9818 | Opt( config.listTests )
9819 ["-l"]["--list-tests"]
9820 ( "list all/matching test cases" )
9821 | Opt( config.listTags )
9822 ["-t"]["--list-tags"]
9823 ( "list all/matching tags" )
9824 | Opt( config.showSuccessfulTests )
9825 ["-s"]["--success"]
9826 ( "include successful tests in output" )
9827 | Opt( config.shouldDebugBreak )
9828 ["-b"]["--break"]
9829 ( "break into debugger on failure" )
9830 | Opt( config.noThrow )
9831 ["-e"]["--nothrow"]
9832 ( "skip exception tests" )
9833 | Opt( config.showInvisibles )
9834 ["-i"]["--invisibles"]
9835 ( "show invisibles (tabs, newlines)" )
9836 | Opt( config.outputFilename, "filename" )
9837 ["-o"]["--out"]
9838 ( "output filename" )
9839 | Opt( setReporter, "name" )
9840 ["-r"]["--reporter"]
9841 ( "reporter to use (defaults to console)" )
9842 | Opt( config.name, "name" )
9843 ["-n"]["--name"]
9844 ( "suite name" )
9845 | Opt( [&]( bool ){ config.abortAfter = 1; } )
9846 ["-a"]["--abort"]
9847 ( "abort at first failure" )
9848 | Opt( [&]( int x ){ config.abortAfter = x; }, "no. failures" )
9849 ["-x"]["--abortx"]
9850 ( "abort after x failures" )
9851 | Opt( setWarning, "warning name" )
9852 ["-w"]["--warn"]
9853 ( "enable warnings" )
9854 | Opt( [&]( bool flag ) { config.showDurations = flag ? ShowDurations::Always : ShowDurations::Never; }, "yes|no" )
9855 ["-d"]["--durations"]
9856 ( "show test durations" )
9857 | Opt( config.minDuration, "seconds" )
9858 ["-D"]["--min-duration"]
9859 ( "show test durations for tests taking at least the given number of seconds" )
9860 | Opt( loadTestNamesFromFile, "filename" )
9861 ["-f"]["--input-file"]
9862 ( "load test names to run from a file" )
9863 | Opt( config.filenamesAsTags )
9864 ["-#"]["--filenames-as-tags"]
9865 ( "adds a tag for the filename" )
9866 | Opt( config.sectionsToRun, "section name" )
9867 ["-c"]["--section"]
9868 ( "specify section to run" )
9869 | Opt( setVerbosity, "quiet|normal|high" )
9870 ["-v"]["--verbosity"]
9871 ( "set output verbosity" )
9872 | Opt( config.listTestNamesOnly )
9873 ["--list-test-names-only"]
9874 ( "list all/matching test cases names only" )
9875 | Opt( config.listReporters )
9876 ["--list-reporters"]
9877 ( "list all reporters" )
9878 | Opt( setTestOrder, "decl|lex|rand" )
9879 ["--order"]
9880 ( "test case order (defaults to decl)" )
9881 | Opt( setRngSeed, "'time'|number" )
9882 ["--rng-seed"]
9883 ( "set a specific seed for random numbers" )
9884 | Opt( setColourUsage, "yes|no" )
9885 ["--use-colour"]
9886 ( "should output be colourised" )
9887 | Opt( config.libIdentify )
9888 ["--libidentify"]
9889 ( "report name and version according to libidentify standard" )
9890 | Opt( setWaitForKeypress, "never|start|exit|both" )
9891 ["--wait-for-keypress"]
9892 ( "waits for a keypress before exiting" )
9893 | Opt( config.benchmarkSamples, "samples" )
9894 ["--benchmark-samples"]
9895 ( "number of samples to collect (default: 100)" )
9896 | Opt( config.benchmarkResamples, "resamples" )
9897 ["--benchmark-resamples"]
9898 ( "number of resamples for the bootstrap (default: 100000)" )
9899 | Opt( config.benchmarkConfidenceInterval, "confidence interval" )
9900 ["--benchmark-confidence-interval"]
9901 ( "confidence interval for the bootstrap (between 0 and 1, default: 0.95)" )
9902 | Opt( config.benchmarkNoAnalysis )
9903 ["--benchmark-no-analysis"]
9904 ( "perform only measurements; do not perform any analysis" )
9905 | Opt( config.benchmarkWarmupTime, "benchmarkWarmupTime" )
9906 ["--benchmark-warmup-time"]
9907 ( "amount of time in milliseconds spent on warming up each test (default: 100)" )
9908 | Arg( config.testsOrTags, "test name|pattern|tags" )
9909 ( "which test or tests to use" );
9910
9911 return cli;
9912 }
9913
9914 } // end namespace Catch
9915 // end catch_commandline.cpp
9916 // start catch_common.cpp
9917
9918 #include <cstring>
9919 #include <ostream>
9920
9921 namespace Catch {
9922
operator ==(SourceLineInfo const & other) const9923 bool SourceLineInfo::operator == ( SourceLineInfo const& other ) const noexcept {
9924 return line == other.line && (file == other.file || std::strcmp(file, other.file) == 0);
9925 }
operator <(SourceLineInfo const & other) const9926 bool SourceLineInfo::operator < ( SourceLineInfo const& other ) const noexcept {
9927 // We can assume that the same file will usually have the same pointer.
9928 // Thus, if the pointers are the same, there is no point in calling the strcmp
9929 return line < other.line || ( line == other.line && file != other.file && (std::strcmp(file, other.file) < 0));
9930 }
9931
operator <<(std::ostream & os,SourceLineInfo const & info)9932 std::ostream& operator << ( std::ostream& os, SourceLineInfo const& info ) {
9933 #ifndef __GNUG__
9934 os << info.file << '(' << info.line << ')';
9935 #else
9936 os << info.file << ':' << info.line;
9937 #endif
9938 return os;
9939 }
9940
operator +() const9941 std::string StreamEndStop::operator+() const {
9942 return std::string();
9943 }
9944
9945 NonCopyable::NonCopyable() = default;
9946 NonCopyable::~NonCopyable() = default;
9947
9948 }
9949 // end catch_common.cpp
9950 // start catch_config.cpp
9951
9952 namespace Catch {
9953
Config(ConfigData const & data)9954 Config::Config( ConfigData const& data )
9955 : m_data( data ),
9956 m_stream( openStream() )
9957 {
9958 // We need to trim filter specs to avoid trouble with superfluous
9959 // whitespace (esp. important for bdd macros, as those are manually
9960 // aligned with whitespace).
9961
9962 for (auto& elem : m_data.testsOrTags) {
9963 elem = trim(elem);
9964 }
9965 for (auto& elem : m_data.sectionsToRun) {
9966 elem = trim(elem);
9967 }
9968
9969 TestSpecParser parser(ITagAliasRegistry::get());
9970 if (!m_data.testsOrTags.empty()) {
9971 m_hasTestFilters = true;
9972 for (auto const& testOrTags : m_data.testsOrTags) {
9973 parser.parse(testOrTags);
9974 }
9975 }
9976 m_testSpec = parser.testSpec();
9977 }
9978
getFilename() const9979 std::string const& Config::getFilename() const {
9980 return m_data.outputFilename ;
9981 }
9982
listTests() const9983 bool Config::listTests() const { return m_data.listTests; }
listTestNamesOnly() const9984 bool Config::listTestNamesOnly() const { return m_data.listTestNamesOnly; }
listTags() const9985 bool Config::listTags() const { return m_data.listTags; }
listReporters() const9986 bool Config::listReporters() const { return m_data.listReporters; }
9987
getProcessName() const9988 std::string Config::getProcessName() const { return m_data.processName; }
getReporterName() const9989 std::string const& Config::getReporterName() const { return m_data.reporterName; }
9990
getTestsOrTags() const9991 std::vector<std::string> const& Config::getTestsOrTags() const { return m_data.testsOrTags; }
getSectionsToRun() const9992 std::vector<std::string> const& Config::getSectionsToRun() const { return m_data.sectionsToRun; }
9993
testSpec() const9994 TestSpec const& Config::testSpec() const { return m_testSpec; }
hasTestFilters() const9995 bool Config::hasTestFilters() const { return m_hasTestFilters; }
9996
showHelp() const9997 bool Config::showHelp() const { return m_data.showHelp; }
9998
9999 // IConfig interface
allowThrows() const10000 bool Config::allowThrows() const { return !m_data.noThrow; }
stream() const10001 std::ostream& Config::stream() const { return m_stream->stream(); }
name() const10002 std::string Config::name() const { return m_data.name.empty() ? m_data.processName : m_data.name; }
includeSuccessfulResults() const10003 bool Config::includeSuccessfulResults() const { return m_data.showSuccessfulTests; }
warnAboutMissingAssertions() const10004 bool Config::warnAboutMissingAssertions() const { return !!(m_data.warnings & WarnAbout::NoAssertions); }
warnAboutNoTests() const10005 bool Config::warnAboutNoTests() const { return !!(m_data.warnings & WarnAbout::NoTests); }
showDurations() const10006 ShowDurations::OrNot Config::showDurations() const { return m_data.showDurations; }
minDuration() const10007 double Config::minDuration() const { return m_data.minDuration; }
runOrder() const10008 RunTests::InWhatOrder Config::runOrder() const { return m_data.runOrder; }
rngSeed() const10009 unsigned int Config::rngSeed() const { return m_data.rngSeed; }
useColour() const10010 UseColour::YesOrNo Config::useColour() const { return m_data.useColour; }
shouldDebugBreak() const10011 bool Config::shouldDebugBreak() const { return m_data.shouldDebugBreak; }
abortAfter() const10012 int Config::abortAfter() const { return m_data.abortAfter; }
showInvisibles() const10013 bool Config::showInvisibles() const { return m_data.showInvisibles; }
verbosity() const10014 Verbosity Config::verbosity() const { return m_data.verbosity; }
10015
benchmarkNoAnalysis() const10016 bool Config::benchmarkNoAnalysis() const { return m_data.benchmarkNoAnalysis; }
benchmarkSamples() const10017 int Config::benchmarkSamples() const { return m_data.benchmarkSamples; }
benchmarkConfidenceInterval() const10018 double Config::benchmarkConfidenceInterval() const { return m_data.benchmarkConfidenceInterval; }
benchmarkResamples() const10019 unsigned int Config::benchmarkResamples() const { return m_data.benchmarkResamples; }
benchmarkWarmupTime() const10020 std::chrono::milliseconds Config::benchmarkWarmupTime() const { return std::chrono::milliseconds(m_data.benchmarkWarmupTime); }
10021
openStream()10022 IStream const* Config::openStream() {
10023 return Catch::makeStream(m_data.outputFilename);
10024 }
10025
10026 } // end namespace Catch
10027 // end catch_config.cpp
10028 // start catch_console_colour.cpp
10029
10030 #if defined(__clang__)
10031 # pragma clang diagnostic push
10032 # pragma clang diagnostic ignored "-Wexit-time-destructors"
10033 #endif
10034
10035 // start catch_errno_guard.h
10036
10037 namespace Catch {
10038
10039 class ErrnoGuard {
10040 public:
10041 ErrnoGuard();
10042 ~ErrnoGuard();
10043 private:
10044 int m_oldErrno;
10045 };
10046
10047 }
10048
10049 // end catch_errno_guard.h
10050 // start catch_windows_h_proxy.h
10051
10052
10053 #if defined(CATCH_PLATFORM_WINDOWS)
10054
10055 #if !defined(NOMINMAX) && !defined(CATCH_CONFIG_NO_NOMINMAX)
10056 # define CATCH_DEFINED_NOMINMAX
10057 # define NOMINMAX
10058 #endif
10059 #if !defined(WIN32_LEAN_AND_MEAN) && !defined(CATCH_CONFIG_NO_WIN32_LEAN_AND_MEAN)
10060 # define CATCH_DEFINED_WIN32_LEAN_AND_MEAN
10061 # define WIN32_LEAN_AND_MEAN
10062 #endif
10063
10064 #ifdef __AFXDLL
10065 #include <AfxWin.h>
10066 #else
10067 #include <windows.h>
10068 #endif
10069
10070 #ifdef CATCH_DEFINED_NOMINMAX
10071 # undef NOMINMAX
10072 #endif
10073 #ifdef CATCH_DEFINED_WIN32_LEAN_AND_MEAN
10074 # undef WIN32_LEAN_AND_MEAN
10075 #endif
10076
10077 #endif // defined(CATCH_PLATFORM_WINDOWS)
10078
10079 // end catch_windows_h_proxy.h
10080 #include <sstream>
10081
10082 namespace Catch {
10083 namespace {
10084
10085 struct IColourImpl {
10086 virtual ~IColourImpl() = default;
10087 virtual void use( Colour::Code _colourCode ) = 0;
10088 };
10089
10090 struct NoColourImpl : IColourImpl {
useCatch::__anon21412a522d11::NoColourImpl10091 void use( Colour::Code ) override {}
10092
instanceCatch::__anon21412a522d11::NoColourImpl10093 static IColourImpl* instance() {
10094 static NoColourImpl s_instance;
10095 return &s_instance;
10096 }
10097 };
10098
10099 } // anon namespace
10100 } // namespace Catch
10101
10102 #if !defined( CATCH_CONFIG_COLOUR_NONE ) && !defined( CATCH_CONFIG_COLOUR_WINDOWS ) && !defined( CATCH_CONFIG_COLOUR_ANSI )
10103 # ifdef CATCH_PLATFORM_WINDOWS
10104 # define CATCH_CONFIG_COLOUR_WINDOWS
10105 # else
10106 # define CATCH_CONFIG_COLOUR_ANSI
10107 # endif
10108 #endif
10109
10110 #if defined ( CATCH_CONFIG_COLOUR_WINDOWS ) /////////////////////////////////////////
10111
10112 namespace Catch {
10113 namespace {
10114
10115 class Win32ColourImpl : public IColourImpl {
10116 public:
Win32ColourImpl()10117 Win32ColourImpl() : stdoutHandle( GetStdHandle(STD_OUTPUT_HANDLE) )
10118 {
10119 CONSOLE_SCREEN_BUFFER_INFO csbiInfo;
10120 GetConsoleScreenBufferInfo( stdoutHandle, &csbiInfo );
10121 originalForegroundAttributes = csbiInfo.wAttributes & ~( BACKGROUND_GREEN | BACKGROUND_RED | BACKGROUND_BLUE | BACKGROUND_INTENSITY );
10122 originalBackgroundAttributes = csbiInfo.wAttributes & ~( FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_BLUE | FOREGROUND_INTENSITY );
10123 }
10124
use(Colour::Code _colourCode)10125 void use( Colour::Code _colourCode ) override {
10126 switch( _colourCode ) {
10127 case Colour::None: return setTextAttribute( originalForegroundAttributes );
10128 case Colour::White: return setTextAttribute( FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_BLUE );
10129 case Colour::Red: return setTextAttribute( FOREGROUND_RED );
10130 case Colour::Green: return setTextAttribute( FOREGROUND_GREEN );
10131 case Colour::Blue: return setTextAttribute( FOREGROUND_BLUE );
10132 case Colour::Cyan: return setTextAttribute( FOREGROUND_BLUE | FOREGROUND_GREEN );
10133 case Colour::Yellow: return setTextAttribute( FOREGROUND_RED | FOREGROUND_GREEN );
10134 case Colour::Grey: return setTextAttribute( 0 );
10135
10136 case Colour::LightGrey: return setTextAttribute( FOREGROUND_INTENSITY );
10137 case Colour::BrightRed: return setTextAttribute( FOREGROUND_INTENSITY | FOREGROUND_RED );
10138 case Colour::BrightGreen: return setTextAttribute( FOREGROUND_INTENSITY | FOREGROUND_GREEN );
10139 case Colour::BrightWhite: return setTextAttribute( FOREGROUND_INTENSITY | FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_BLUE );
10140 case Colour::BrightYellow: return setTextAttribute( FOREGROUND_INTENSITY | FOREGROUND_RED | FOREGROUND_GREEN );
10141
10142 case Colour::Bright: CATCH_INTERNAL_ERROR( "not a colour" );
10143
10144 default:
10145 CATCH_ERROR( "Unknown colour requested" );
10146 }
10147 }
10148
10149 private:
setTextAttribute(WORD _textAttribute)10150 void setTextAttribute( WORD _textAttribute ) {
10151 SetConsoleTextAttribute( stdoutHandle, _textAttribute | originalBackgroundAttributes );
10152 }
10153 HANDLE stdoutHandle;
10154 WORD originalForegroundAttributes;
10155 WORD originalBackgroundAttributes;
10156 };
10157
platformColourInstance()10158 IColourImpl* platformColourInstance() {
10159 static Win32ColourImpl s_instance;
10160
10161 IConfigPtr config = getCurrentContext().getConfig();
10162 UseColour::YesOrNo colourMode = config
10163 ? config->useColour()
10164 : UseColour::Auto;
10165 if( colourMode == UseColour::Auto )
10166 colourMode = UseColour::Yes;
10167 return colourMode == UseColour::Yes
10168 ? &s_instance
10169 : NoColourImpl::instance();
10170 }
10171
10172 } // end anon namespace
10173 } // end namespace Catch
10174
10175 #elif defined( CATCH_CONFIG_COLOUR_ANSI ) //////////////////////////////////////
10176
10177 #include <unistd.h>
10178
10179 namespace Catch {
10180 namespace {
10181
10182 // use POSIX/ ANSI console terminal codes
10183 // Thanks to Adam Strzelecki for original contribution
10184 // (http://github.com/nanoant)
10185 // https://github.com/philsquared/Catch/pull/131
10186 class PosixColourImpl : public IColourImpl {
10187 public:
use(Colour::Code _colourCode)10188 void use( Colour::Code _colourCode ) override {
10189 switch( _colourCode ) {
10190 case Colour::None:
10191 case Colour::White: return setColour( "[0m" );
10192 case Colour::Red: return setColour( "[0;31m" );
10193 case Colour::Green: return setColour( "[0;32m" );
10194 case Colour::Blue: return setColour( "[0;34m" );
10195 case Colour::Cyan: return setColour( "[0;36m" );
10196 case Colour::Yellow: return setColour( "[0;33m" );
10197 case Colour::Grey: return setColour( "[1;30m" );
10198
10199 case Colour::LightGrey: return setColour( "[0;37m" );
10200 case Colour::BrightRed: return setColour( "[1;31m" );
10201 case Colour::BrightGreen: return setColour( "[1;32m" );
10202 case Colour::BrightWhite: return setColour( "[1;37m" );
10203 case Colour::BrightYellow: return setColour( "[1;33m" );
10204
10205 case Colour::Bright: CATCH_INTERNAL_ERROR( "not a colour" );
10206 default: CATCH_INTERNAL_ERROR( "Unknown colour requested" );
10207 }
10208 }
instance()10209 static IColourImpl* instance() {
10210 static PosixColourImpl s_instance;
10211 return &s_instance;
10212 }
10213
10214 private:
setColour(const char * _escapeCode)10215 void setColour( const char* _escapeCode ) {
10216 getCurrentContext().getConfig()->stream()
10217 << '\033' << _escapeCode;
10218 }
10219 };
10220
useColourOnPlatform()10221 bool useColourOnPlatform() {
10222 return
10223 #if defined(CATCH_PLATFORM_MAC) || defined(CATCH_PLATFORM_IPHONE)
10224 !isDebuggerActive() &&
10225 #endif
10226 #if !(defined(__DJGPP__) && defined(__STRICT_ANSI__))
10227 isatty(STDOUT_FILENO)
10228 #else
10229 false
10230 #endif
10231 ;
10232 }
platformColourInstance()10233 IColourImpl* platformColourInstance() {
10234 ErrnoGuard guard;
10235 IConfigPtr config = getCurrentContext().getConfig();
10236 UseColour::YesOrNo colourMode = config
10237 ? config->useColour()
10238 : UseColour::Auto;
10239 if( colourMode == UseColour::Auto )
10240 colourMode = useColourOnPlatform()
10241 ? UseColour::Yes
10242 : UseColour::No;
10243 return colourMode == UseColour::Yes
10244 ? PosixColourImpl::instance()
10245 : NoColourImpl::instance();
10246 }
10247
10248 } // end anon namespace
10249 } // end namespace Catch
10250
10251 #else // not Windows or ANSI ///////////////////////////////////////////////
10252
10253 namespace Catch {
10254
platformColourInstance()10255 static IColourImpl* platformColourInstance() { return NoColourImpl::instance(); }
10256
10257 } // end namespace Catch
10258
10259 #endif // Windows/ ANSI/ None
10260
10261 namespace Catch {
10262
Colour(Code _colourCode)10263 Colour::Colour( Code _colourCode ) { use( _colourCode ); }
Colour(Colour && other)10264 Colour::Colour( Colour&& other ) noexcept {
10265 m_moved = other.m_moved;
10266 other.m_moved = true;
10267 }
operator =(Colour && other)10268 Colour& Colour::operator=( Colour&& other ) noexcept {
10269 m_moved = other.m_moved;
10270 other.m_moved = true;
10271 return *this;
10272 }
10273
~Colour()10274 Colour::~Colour(){ if( !m_moved ) use( None ); }
10275
use(Code _colourCode)10276 void Colour::use( Code _colourCode ) {
10277 static IColourImpl* impl = platformColourInstance();
10278 // Strictly speaking, this cannot possibly happen.
10279 // However, under some conditions it does happen (see #1626),
10280 // and this change is small enough that we can let practicality
10281 // triumph over purity in this case.
10282 if (impl != nullptr) {
10283 impl->use( _colourCode );
10284 }
10285 }
10286
operator <<(std::ostream & os,Colour const &)10287 std::ostream& operator << ( std::ostream& os, Colour const& ) {
10288 return os;
10289 }
10290
10291 } // end namespace Catch
10292
10293 #if defined(__clang__)
10294 # pragma clang diagnostic pop
10295 #endif
10296
10297 // end catch_console_colour.cpp
10298 // start catch_context.cpp
10299
10300 namespace Catch {
10301
10302 class Context : public IMutableContext, NonCopyable {
10303
10304 public: // IContext
getResultCapture()10305 IResultCapture* getResultCapture() override {
10306 return m_resultCapture;
10307 }
getRunner()10308 IRunner* getRunner() override {
10309 return m_runner;
10310 }
10311
getConfig() const10312 IConfigPtr const& getConfig() const override {
10313 return m_config;
10314 }
10315
10316 ~Context() override;
10317
10318 public: // IMutableContext
setResultCapture(IResultCapture * resultCapture)10319 void setResultCapture( IResultCapture* resultCapture ) override {
10320 m_resultCapture = resultCapture;
10321 }
setRunner(IRunner * runner)10322 void setRunner( IRunner* runner ) override {
10323 m_runner = runner;
10324 }
setConfig(IConfigPtr const & config)10325 void setConfig( IConfigPtr const& config ) override {
10326 m_config = config;
10327 }
10328
10329 friend IMutableContext& getCurrentMutableContext();
10330
10331 private:
10332 IConfigPtr m_config;
10333 IRunner* m_runner = nullptr;
10334 IResultCapture* m_resultCapture = nullptr;
10335 };
10336
10337 IMutableContext *IMutableContext::currentContext = nullptr;
10338
createContext()10339 void IMutableContext::createContext()
10340 {
10341 currentContext = new Context();
10342 }
10343
cleanUpContext()10344 void cleanUpContext() {
10345 delete IMutableContext::currentContext;
10346 IMutableContext::currentContext = nullptr;
10347 }
10348 IContext::~IContext() = default;
10349 IMutableContext::~IMutableContext() = default;
10350 Context::~Context() = default;
10351
rng()10352 SimplePcg32& rng() {
10353 static SimplePcg32 s_rng;
10354 return s_rng;
10355 }
10356
10357 }
10358 // end catch_context.cpp
10359 // start catch_debug_console.cpp
10360
10361 // start catch_debug_console.h
10362
10363 #include <string>
10364
10365 namespace Catch {
10366 void writeToDebugConsole( std::string const& text );
10367 }
10368
10369 // end catch_debug_console.h
10370 #if defined(CATCH_CONFIG_ANDROID_LOGWRITE)
10371 #include <android/log.h>
10372
10373 namespace Catch {
writeToDebugConsole(std::string const & text)10374 void writeToDebugConsole( std::string const& text ) {
10375 __android_log_write( ANDROID_LOG_DEBUG, "Catch", text.c_str() );
10376 }
10377 }
10378
10379 #elif defined(CATCH_PLATFORM_WINDOWS)
10380
10381 namespace Catch {
writeToDebugConsole(std::string const & text)10382 void writeToDebugConsole( std::string const& text ) {
10383 ::OutputDebugStringA( text.c_str() );
10384 }
10385 }
10386
10387 #else
10388
10389 namespace Catch {
writeToDebugConsole(std::string const & text)10390 void writeToDebugConsole( std::string const& text ) {
10391 // !TBD: Need a version for Mac/ XCode and other IDEs
10392 Catch::cout() << text;
10393 }
10394 }
10395
10396 #endif // Platform
10397 // end catch_debug_console.cpp
10398 // start catch_debugger.cpp
10399
10400 #if defined(CATCH_PLATFORM_MAC) || defined(CATCH_PLATFORM_IPHONE)
10401
10402 # include <cassert>
10403 # include <sys/types.h>
10404 # include <unistd.h>
10405 # include <cstddef>
10406 # include <ostream>
10407
10408 #ifdef __apple_build_version__
10409 // These headers will only compile with AppleClang (XCode)
10410 // For other compilers (Clang, GCC, ... ) we need to exclude them
10411 # include <sys/sysctl.h>
10412 #endif
10413
10414 namespace Catch {
10415 #ifdef __apple_build_version__
10416 // The following function is taken directly from the following technical note:
10417 // https://developer.apple.com/library/archive/qa/qa1361/_index.html
10418
10419 // Returns true if the current process is being debugged (either
10420 // running under the debugger or has a debugger attached post facto).
isDebuggerActive()10421 bool isDebuggerActive(){
10422 int mib[4];
10423 struct kinfo_proc info;
10424 std::size_t size;
10425
10426 // Initialize the flags so that, if sysctl fails for some bizarre
10427 // reason, we get a predictable result.
10428
10429 info.kp_proc.p_flag = 0;
10430
10431 // Initialize mib, which tells sysctl the info we want, in this case
10432 // we're looking for information about a specific process ID.
10433
10434 mib[0] = CTL_KERN;
10435 mib[1] = KERN_PROC;
10436 mib[2] = KERN_PROC_PID;
10437 mib[3] = getpid();
10438
10439 // Call sysctl.
10440
10441 size = sizeof(info);
10442 if( sysctl(mib, sizeof(mib) / sizeof(*mib), &info, &size, nullptr, 0) != 0 ) {
10443 Catch::cerr() << "\n** Call to sysctl failed - unable to determine if debugger is active **\n" << std::endl;
10444 return false;
10445 }
10446
10447 // We're being debugged if the P_TRACED flag is set.
10448
10449 return ( (info.kp_proc.p_flag & P_TRACED) != 0 );
10450 }
10451 #else
10452 bool isDebuggerActive() {
10453 // We need to find another way to determine this for non-appleclang compilers on macOS
10454 return false;
10455 }
10456 #endif
10457 } // namespace Catch
10458
10459 #elif defined(CATCH_PLATFORM_LINUX)
10460 #include <fstream>
10461 #include <string>
10462
10463 namespace Catch{
10464 // The standard POSIX way of detecting a debugger is to attempt to
10465 // ptrace() the process, but this needs to be done from a child and not
10466 // this process itself to still allow attaching to this process later
10467 // if wanted, so is rather heavy. Under Linux we have the PID of the
10468 // "debugger" (which doesn't need to be gdb, of course, it could also
10469 // be strace, for example) in /proc/$PID/status, so just get it from
10470 // there instead.
isDebuggerActive()10471 bool isDebuggerActive(){
10472 // Libstdc++ has a bug, where std::ifstream sets errno to 0
10473 // This way our users can properly assert over errno values
10474 ErrnoGuard guard;
10475 std::ifstream in("/proc/self/status");
10476 for( std::string line; std::getline(in, line); ) {
10477 static const int PREFIX_LEN = 11;
10478 if( line.compare(0, PREFIX_LEN, "TracerPid:\t") == 0 ) {
10479 // We're traced if the PID is not 0 and no other PID starts
10480 // with 0 digit, so it's enough to check for just a single
10481 // character.
10482 return line.length() > PREFIX_LEN && line[PREFIX_LEN] != '0';
10483 }
10484 }
10485
10486 return false;
10487 }
10488 } // namespace Catch
10489 #elif defined(_MSC_VER)
10490 extern "C" __declspec(dllimport) int __stdcall IsDebuggerPresent();
10491 namespace Catch {
isDebuggerActive()10492 bool isDebuggerActive() {
10493 return IsDebuggerPresent() != 0;
10494 }
10495 }
10496 #elif defined(__MINGW32__)
10497 extern "C" __declspec(dllimport) int __stdcall IsDebuggerPresent();
10498 namespace Catch {
isDebuggerActive()10499 bool isDebuggerActive() {
10500 return IsDebuggerPresent() != 0;
10501 }
10502 }
10503 #else
10504 namespace Catch {
isDebuggerActive()10505 bool isDebuggerActive() { return false; }
10506 }
10507 #endif // Platform
10508 // end catch_debugger.cpp
10509 // start catch_decomposer.cpp
10510
10511 namespace Catch {
10512
10513 ITransientExpression::~ITransientExpression() = default;
10514
formatReconstructedExpression(std::ostream & os,std::string const & lhs,StringRef op,std::string const & rhs)10515 void formatReconstructedExpression( std::ostream &os, std::string const& lhs, StringRef op, std::string const& rhs ) {
10516 if( lhs.size() + rhs.size() < 40 &&
10517 lhs.find('\n') == std::string::npos &&
10518 rhs.find('\n') == std::string::npos )
10519 os << lhs << " " << op << " " << rhs;
10520 else
10521 os << lhs << "\n" << op << "\n" << rhs;
10522 }
10523 }
10524 // end catch_decomposer.cpp
10525 // start catch_enforce.cpp
10526
10527 #include <stdexcept>
10528
10529 namespace Catch {
10530 #if defined(CATCH_CONFIG_DISABLE_EXCEPTIONS) && !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS_CUSTOM_HANDLER)
10531 [[noreturn]]
throw_exception(std::exception const & e)10532 void throw_exception(std::exception const& e) {
10533 Catch::cerr() << "Catch will terminate because it needed to throw an exception.\n"
10534 << "The message was: " << e.what() << '\n';
10535 std::terminate();
10536 }
10537 #endif
10538
10539 [[noreturn]]
throw_logic_error(std::string const & msg)10540 void throw_logic_error(std::string const& msg) {
10541 throw_exception(std::logic_error(msg));
10542 }
10543
10544 [[noreturn]]
throw_domain_error(std::string const & msg)10545 void throw_domain_error(std::string const& msg) {
10546 throw_exception(std::domain_error(msg));
10547 }
10548
10549 [[noreturn]]
throw_runtime_error(std::string const & msg)10550 void throw_runtime_error(std::string const& msg) {
10551 throw_exception(std::runtime_error(msg));
10552 }
10553
10554 } // namespace Catch;
10555 // end catch_enforce.cpp
10556 // start catch_enum_values_registry.cpp
10557 // start catch_enum_values_registry.h
10558
10559 #include <vector>
10560 #include <memory>
10561
10562 namespace Catch {
10563
10564 namespace Detail {
10565
10566 std::unique_ptr<EnumInfo> makeEnumInfo( StringRef enumName, StringRef allValueNames, std::vector<int> const& values );
10567
10568 class EnumValuesRegistry : public IMutableEnumValuesRegistry {
10569
10570 std::vector<std::unique_ptr<EnumInfo>> m_enumInfos;
10571
10572 EnumInfo const& registerEnum( StringRef enumName, StringRef allEnums, std::vector<int> const& values) override;
10573 };
10574
10575 std::vector<StringRef> parseEnums( StringRef enums );
10576
10577 } // Detail
10578
10579 } // Catch
10580
10581 // end catch_enum_values_registry.h
10582
10583 #include <map>
10584 #include <cassert>
10585
10586 namespace Catch {
10587
~IMutableEnumValuesRegistry()10588 IMutableEnumValuesRegistry::~IMutableEnumValuesRegistry() {}
10589
10590 namespace Detail {
10591
10592 namespace {
10593 // Extracts the actual name part of an enum instance
10594 // In other words, it returns the Blue part of Bikeshed::Colour::Blue
extractInstanceName(StringRef enumInstance)10595 StringRef extractInstanceName(StringRef enumInstance) {
10596 // Find last occurrence of ":"
10597 size_t name_start = enumInstance.size();
10598 while (name_start > 0 && enumInstance[name_start - 1] != ':') {
10599 --name_start;
10600 }
10601 return enumInstance.substr(name_start, enumInstance.size() - name_start);
10602 }
10603 }
10604
parseEnums(StringRef enums)10605 std::vector<StringRef> parseEnums( StringRef enums ) {
10606 auto enumValues = splitStringRef( enums, ',' );
10607 std::vector<StringRef> parsed;
10608 parsed.reserve( enumValues.size() );
10609 for( auto const& enumValue : enumValues ) {
10610 parsed.push_back(trim(extractInstanceName(enumValue)));
10611 }
10612 return parsed;
10613 }
10614
~EnumInfo()10615 EnumInfo::~EnumInfo() {}
10616
lookup(int value) const10617 StringRef EnumInfo::lookup( int value ) const {
10618 for( auto const& valueToName : m_values ) {
10619 if( valueToName.first == value )
10620 return valueToName.second;
10621 }
10622 return "{** unexpected enum value **}"_sr;
10623 }
10624
makeEnumInfo(StringRef enumName,StringRef allValueNames,std::vector<int> const & values)10625 std::unique_ptr<EnumInfo> makeEnumInfo( StringRef enumName, StringRef allValueNames, std::vector<int> const& values ) {
10626 std::unique_ptr<EnumInfo> enumInfo( new EnumInfo );
10627 enumInfo->m_name = enumName;
10628 enumInfo->m_values.reserve( values.size() );
10629
10630 const auto valueNames = Catch::Detail::parseEnums( allValueNames );
10631 assert( valueNames.size() == values.size() );
10632 std::size_t i = 0;
10633 for( auto value : values )
10634 enumInfo->m_values.emplace_back(value, valueNames[i++]);
10635
10636 return enumInfo;
10637 }
10638
registerEnum(StringRef enumName,StringRef allValueNames,std::vector<int> const & values)10639 EnumInfo const& EnumValuesRegistry::registerEnum( StringRef enumName, StringRef allValueNames, std::vector<int> const& values ) {
10640 m_enumInfos.push_back(makeEnumInfo(enumName, allValueNames, values));
10641 return *m_enumInfos.back();
10642 }
10643
10644 } // Detail
10645 } // Catch
10646
10647 // end catch_enum_values_registry.cpp
10648 // start catch_errno_guard.cpp
10649
10650 #include <cerrno>
10651
10652 namespace Catch {
ErrnoGuard()10653 ErrnoGuard::ErrnoGuard():m_oldErrno(errno){}
~ErrnoGuard()10654 ErrnoGuard::~ErrnoGuard() { errno = m_oldErrno; }
10655 }
10656 // end catch_errno_guard.cpp
10657 // start catch_exception_translator_registry.cpp
10658
10659 // start catch_exception_translator_registry.h
10660
10661 #include <vector>
10662 #include <string>
10663 #include <memory>
10664
10665 namespace Catch {
10666
10667 class ExceptionTranslatorRegistry : public IExceptionTranslatorRegistry {
10668 public:
10669 ~ExceptionTranslatorRegistry();
10670 virtual void registerTranslator( const IExceptionTranslator* translator );
10671 std::string translateActiveException() const override;
10672 std::string tryTranslators() const;
10673
10674 private:
10675 std::vector<std::unique_ptr<IExceptionTranslator const>> m_translators;
10676 };
10677 }
10678
10679 // end catch_exception_translator_registry.h
10680 #ifdef __OBJC__
10681 #import "Foundation/Foundation.h"
10682 #endif
10683
10684 namespace Catch {
10685
~ExceptionTranslatorRegistry()10686 ExceptionTranslatorRegistry::~ExceptionTranslatorRegistry() {
10687 }
10688
registerTranslator(const IExceptionTranslator * translator)10689 void ExceptionTranslatorRegistry::registerTranslator( const IExceptionTranslator* translator ) {
10690 m_translators.push_back( std::unique_ptr<const IExceptionTranslator>( translator ) );
10691 }
10692
10693 #if !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
translateActiveException() const10694 std::string ExceptionTranslatorRegistry::translateActiveException() const {
10695 try {
10696 #ifdef __OBJC__
10697 // In Objective-C try objective-c exceptions first
10698 @try {
10699 return tryTranslators();
10700 }
10701 @catch (NSException *exception) {
10702 return Catch::Detail::stringify( [exception description] );
10703 }
10704 #else
10705 // Compiling a mixed mode project with MSVC means that CLR
10706 // exceptions will be caught in (...) as well. However, these
10707 // do not fill-in std::current_exception and thus lead to crash
10708 // when attempting rethrow.
10709 // /EHa switch also causes structured exceptions to be caught
10710 // here, but they fill-in current_exception properly, so
10711 // at worst the output should be a little weird, instead of
10712 // causing a crash.
10713 if (std::current_exception() == nullptr) {
10714 return "Non C++ exception. Possibly a CLR exception.";
10715 }
10716 return tryTranslators();
10717 #endif
10718 }
10719 catch( TestFailureException& ) {
10720 std::rethrow_exception(std::current_exception());
10721 }
10722 catch( std::exception& ex ) {
10723 return ex.what();
10724 }
10725 catch( std::string& msg ) {
10726 return msg;
10727 }
10728 catch( const char* msg ) {
10729 return msg;
10730 }
10731 catch(...) {
10732 return "Unknown exception";
10733 }
10734 }
10735
tryTranslators() const10736 std::string ExceptionTranslatorRegistry::tryTranslators() const {
10737 if (m_translators.empty()) {
10738 std::rethrow_exception(std::current_exception());
10739 } else {
10740 return m_translators[0]->translate(m_translators.begin() + 1, m_translators.end());
10741 }
10742 }
10743
10744 #else // ^^ Exceptions are enabled // Exceptions are disabled vv
translateActiveException() const10745 std::string ExceptionTranslatorRegistry::translateActiveException() const {
10746 CATCH_INTERNAL_ERROR("Attempted to translate active exception under CATCH_CONFIG_DISABLE_EXCEPTIONS!");
10747 }
10748
tryTranslators() const10749 std::string ExceptionTranslatorRegistry::tryTranslators() const {
10750 CATCH_INTERNAL_ERROR("Attempted to use exception translators under CATCH_CONFIG_DISABLE_EXCEPTIONS!");
10751 }
10752 #endif
10753
10754 }
10755 // end catch_exception_translator_registry.cpp
10756 // start catch_fatal_condition.cpp
10757
10758 #include <algorithm>
10759
10760 #if !defined( CATCH_CONFIG_WINDOWS_SEH ) && !defined( CATCH_CONFIG_POSIX_SIGNALS )
10761
10762 namespace Catch {
10763
10764 // If neither SEH nor signal handling is required, the handler impls
10765 // do not have to do anything, and can be empty.
engage_platform()10766 void FatalConditionHandler::engage_platform() {}
disengage_platform()10767 void FatalConditionHandler::disengage_platform() {}
10768 FatalConditionHandler::FatalConditionHandler() = default;
10769 FatalConditionHandler::~FatalConditionHandler() = default;
10770
10771 } // end namespace Catch
10772
10773 #endif // !CATCH_CONFIG_WINDOWS_SEH && !CATCH_CONFIG_POSIX_SIGNALS
10774
10775 #if defined( CATCH_CONFIG_WINDOWS_SEH ) && defined( CATCH_CONFIG_POSIX_SIGNALS )
10776 #error "Inconsistent configuration: Windows' SEH handling and POSIX signals cannot be enabled at the same time"
10777 #endif // CATCH_CONFIG_WINDOWS_SEH && CATCH_CONFIG_POSIX_SIGNALS
10778
10779 #if defined( CATCH_CONFIG_WINDOWS_SEH ) || defined( CATCH_CONFIG_POSIX_SIGNALS )
10780
10781 namespace {
10782 //! Signals fatal error message to the run context
reportFatal(char const * const message)10783 void reportFatal( char const * const message ) {
10784 Catch::getCurrentContext().getResultCapture()->handleFatalErrorCondition( message );
10785 }
10786
10787 //! Minimal size Catch2 needs for its own fatal error handling.
10788 //! Picked anecdotally, so it might not be sufficient on all
10789 //! platforms, and for all configurations.
10790 constexpr std::size_t minStackSizeForErrors = 32 * 1024;
10791 } // end unnamed namespace
10792
10793 #endif // CATCH_CONFIG_WINDOWS_SEH || CATCH_CONFIG_POSIX_SIGNALS
10794
10795 #if defined( CATCH_CONFIG_WINDOWS_SEH )
10796
10797 namespace Catch {
10798
10799 struct SignalDefs { DWORD id; const char* name; };
10800
10801 // There is no 1-1 mapping between signals and windows exceptions.
10802 // Windows can easily distinguish between SO and SigSegV,
10803 // but SigInt, SigTerm, etc are handled differently.
10804 static SignalDefs signalDefs[] = {
10805 { static_cast<DWORD>(EXCEPTION_ILLEGAL_INSTRUCTION), "SIGILL - Illegal instruction signal" },
10806 { static_cast<DWORD>(EXCEPTION_STACK_OVERFLOW), "SIGSEGV - Stack overflow" },
10807 { static_cast<DWORD>(EXCEPTION_ACCESS_VIOLATION), "SIGSEGV - Segmentation violation signal" },
10808 { static_cast<DWORD>(EXCEPTION_INT_DIVIDE_BY_ZERO), "Divide by zero error" },
10809 };
10810
handleVectoredException(PEXCEPTION_POINTERS ExceptionInfo)10811 static LONG CALLBACK handleVectoredException(PEXCEPTION_POINTERS ExceptionInfo) {
10812 for (auto const& def : signalDefs) {
10813 if (ExceptionInfo->ExceptionRecord->ExceptionCode == def.id) {
10814 reportFatal(def.name);
10815 }
10816 }
10817 // If its not an exception we care about, pass it along.
10818 // This stops us from eating debugger breaks etc.
10819 return EXCEPTION_CONTINUE_SEARCH;
10820 }
10821
10822 // Since we do not support multiple instantiations, we put these
10823 // into global variables and rely on cleaning them up in outlined
10824 // constructors/destructors
10825 static PVOID exceptionHandlerHandle = nullptr;
10826
10827 // For MSVC, we reserve part of the stack memory for handling
10828 // memory overflow structured exception.
FatalConditionHandler()10829 FatalConditionHandler::FatalConditionHandler() {
10830 ULONG guaranteeSize = static_cast<ULONG>(minStackSizeForErrors);
10831 if (!SetThreadStackGuarantee(&guaranteeSize)) {
10832 // We do not want to fully error out, because needing
10833 // the stack reserve should be rare enough anyway.
10834 Catch::cerr()
10835 << "Failed to reserve piece of stack."
10836 << " Stack overflows will not be reported successfully.";
10837 }
10838 }
10839
10840 // We do not attempt to unset the stack guarantee, because
10841 // Windows does not support lowering the stack size guarantee.
10842 FatalConditionHandler::~FatalConditionHandler() = default;
10843
engage_platform()10844 void FatalConditionHandler::engage_platform() {
10845 // Register as first handler in current chain
10846 exceptionHandlerHandle = AddVectoredExceptionHandler(1, handleVectoredException);
10847 if (!exceptionHandlerHandle) {
10848 CATCH_RUNTIME_ERROR("Could not register vectored exception handler");
10849 }
10850 }
10851
disengage_platform()10852 void FatalConditionHandler::disengage_platform() {
10853 if (!RemoveVectoredExceptionHandler(exceptionHandlerHandle)) {
10854 CATCH_RUNTIME_ERROR("Could not unregister vectored exception handler");
10855 }
10856 exceptionHandlerHandle = nullptr;
10857 }
10858
10859 } // end namespace Catch
10860
10861 #endif // CATCH_CONFIG_WINDOWS_SEH
10862
10863 #if defined( CATCH_CONFIG_POSIX_SIGNALS )
10864
10865 #include <signal.h>
10866
10867 namespace Catch {
10868
10869 struct SignalDefs {
10870 int id;
10871 const char* name;
10872 };
10873
10874 static SignalDefs signalDefs[] = {
10875 { SIGINT, "SIGINT - Terminal interrupt signal" },
10876 { SIGILL, "SIGILL - Illegal instruction signal" },
10877 { SIGFPE, "SIGFPE - Floating point error signal" },
10878 { SIGSEGV, "SIGSEGV - Segmentation violation signal" },
10879 { SIGTERM, "SIGTERM - Termination request signal" },
10880 { SIGABRT, "SIGABRT - Abort (abnormal termination) signal" }
10881 };
10882
10883 // Older GCCs trigger -Wmissing-field-initializers for T foo = {}
10884 // which is zero initialization, but not explicit. We want to avoid
10885 // that.
10886 #if defined(__GNUC__)
10887 # pragma GCC diagnostic push
10888 # pragma GCC diagnostic ignored "-Wmissing-field-initializers"
10889 #endif
10890
10891 static char* altStackMem = nullptr;
10892 static std::size_t altStackSize = 0;
10893 static stack_t oldSigStack{};
10894 static struct sigaction oldSigActions[sizeof(signalDefs) / sizeof(SignalDefs)]{};
10895
restorePreviousSignalHandlers()10896 static void restorePreviousSignalHandlers() {
10897 // We set signal handlers back to the previous ones. Hopefully
10898 // nobody overwrote them in the meantime, and doesn't expect
10899 // their signal handlers to live past ours given that they
10900 // installed them after ours..
10901 for (std::size_t i = 0; i < sizeof(signalDefs) / sizeof(SignalDefs); ++i) {
10902 sigaction(signalDefs[i].id, &oldSigActions[i], nullptr);
10903 }
10904 // Return the old stack
10905 sigaltstack(&oldSigStack, nullptr);
10906 }
10907
handleSignal(int sig)10908 static void handleSignal( int sig ) {
10909 char const * name = "<unknown signal>";
10910 for (auto const& def : signalDefs) {
10911 if (sig == def.id) {
10912 name = def.name;
10913 break;
10914 }
10915 }
10916 // We need to restore previous signal handlers and let them do
10917 // their thing, so that the users can have the debugger break
10918 // when a signal is raised, and so on.
10919 restorePreviousSignalHandlers();
10920 reportFatal( name );
10921 raise( sig );
10922 }
10923
FatalConditionHandler()10924 FatalConditionHandler::FatalConditionHandler() {
10925 assert(!altStackMem && "Cannot initialize POSIX signal handler when one already exists");
10926 if (altStackSize == 0) {
10927 altStackSize = std::max(static_cast<size_t>(SIGSTKSZ), minStackSizeForErrors);
10928 }
10929 altStackMem = new char[altStackSize]();
10930 }
10931
~FatalConditionHandler()10932 FatalConditionHandler::~FatalConditionHandler() {
10933 delete[] altStackMem;
10934 // We signal that another instance can be constructed by zeroing
10935 // out the pointer.
10936 altStackMem = nullptr;
10937 }
10938
engage_platform()10939 void FatalConditionHandler::engage_platform() {
10940 stack_t sigStack;
10941 sigStack.ss_sp = altStackMem;
10942 sigStack.ss_size = altStackSize;
10943 sigStack.ss_flags = 0;
10944 sigaltstack(&sigStack, &oldSigStack);
10945 struct sigaction sa = { };
10946
10947 sa.sa_handler = handleSignal;
10948 sa.sa_flags = SA_ONSTACK;
10949 for (std::size_t i = 0; i < sizeof(signalDefs)/sizeof(SignalDefs); ++i) {
10950 sigaction(signalDefs[i].id, &sa, &oldSigActions[i]);
10951 }
10952 }
10953
10954 #if defined(__GNUC__)
10955 # pragma GCC diagnostic pop
10956 #endif
10957
disengage_platform()10958 void FatalConditionHandler::disengage_platform() {
10959 restorePreviousSignalHandlers();
10960 }
10961
10962 } // end namespace Catch
10963
10964 #endif // CATCH_CONFIG_POSIX_SIGNALS
10965 // end catch_fatal_condition.cpp
10966 // start catch_generators.cpp
10967
10968 #include <limits>
10969 #include <set>
10970
10971 namespace Catch {
10972
~IGeneratorTracker()10973 IGeneratorTracker::~IGeneratorTracker() {}
10974
what() const10975 const char* GeneratorException::what() const noexcept {
10976 return m_msg;
10977 }
10978
10979 namespace Generators {
10980
~GeneratorUntypedBase()10981 GeneratorUntypedBase::~GeneratorUntypedBase() {}
10982
acquireGeneratorTracker(StringRef generatorName,SourceLineInfo const & lineInfo)10983 auto acquireGeneratorTracker( StringRef generatorName, SourceLineInfo const& lineInfo ) -> IGeneratorTracker& {
10984 return getResultCapture().acquireGeneratorTracker( generatorName, lineInfo );
10985 }
10986
10987 } // namespace Generators
10988 } // namespace Catch
10989 // end catch_generators.cpp
10990 // start catch_interfaces_capture.cpp
10991
10992 namespace Catch {
10993 IResultCapture::~IResultCapture() = default;
10994 }
10995 // end catch_interfaces_capture.cpp
10996 // start catch_interfaces_config.cpp
10997
10998 namespace Catch {
10999 IConfig::~IConfig() = default;
11000 }
11001 // end catch_interfaces_config.cpp
11002 // start catch_interfaces_exception.cpp
11003
11004 namespace Catch {
11005 IExceptionTranslator::~IExceptionTranslator() = default;
11006 IExceptionTranslatorRegistry::~IExceptionTranslatorRegistry() = default;
11007 }
11008 // end catch_interfaces_exception.cpp
11009 // start catch_interfaces_registry_hub.cpp
11010
11011 namespace Catch {
11012 IRegistryHub::~IRegistryHub() = default;
11013 IMutableRegistryHub::~IMutableRegistryHub() = default;
11014 }
11015 // end catch_interfaces_registry_hub.cpp
11016 // start catch_interfaces_reporter.cpp
11017
11018 // start catch_reporter_listening.h
11019
11020 namespace Catch {
11021
11022 class ListeningReporter : public IStreamingReporter {
11023 using Reporters = std::vector<IStreamingReporterPtr>;
11024 Reporters m_listeners;
11025 IStreamingReporterPtr m_reporter = nullptr;
11026 ReporterPreferences m_preferences;
11027
11028 public:
11029 ListeningReporter();
11030
11031 void addListener( IStreamingReporterPtr&& listener );
11032 void addReporter( IStreamingReporterPtr&& reporter );
11033
11034 public: // IStreamingReporter
11035
11036 ReporterPreferences getPreferences() const override;
11037
11038 void noMatchingTestCases( std::string const& spec ) override;
11039
11040 void reportInvalidArguments(std::string const&arg) override;
11041
11042 static std::set<Verbosity> getSupportedVerbosities();
11043
11044 #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
11045 void benchmarkPreparing(std::string const& name) override;
11046 void benchmarkStarting( BenchmarkInfo const& benchmarkInfo ) override;
11047 void benchmarkEnded( BenchmarkStats<> const& benchmarkStats ) override;
11048 void benchmarkFailed(std::string const&) override;
11049 #endif // CATCH_CONFIG_ENABLE_BENCHMARKING
11050
11051 void testRunStarting( TestRunInfo const& testRunInfo ) override;
11052 void testGroupStarting( GroupInfo const& groupInfo ) override;
11053 void testCaseStarting( TestCaseInfo const& testInfo ) override;
11054 void sectionStarting( SectionInfo const& sectionInfo ) override;
11055 void assertionStarting( AssertionInfo const& assertionInfo ) override;
11056
11057 // The return value indicates if the messages buffer should be cleared:
11058 bool assertionEnded( AssertionStats const& assertionStats ) override;
11059 void sectionEnded( SectionStats const& sectionStats ) override;
11060 void testCaseEnded( TestCaseStats const& testCaseStats ) override;
11061 void testGroupEnded( TestGroupStats const& testGroupStats ) override;
11062 void testRunEnded( TestRunStats const& testRunStats ) override;
11063
11064 void skipTest( TestCaseInfo const& testInfo ) override;
11065 bool isMulti() const override;
11066
11067 };
11068
11069 } // end namespace Catch
11070
11071 // end catch_reporter_listening.h
11072 namespace Catch {
11073
ReporterConfig(IConfigPtr const & _fullConfig)11074 ReporterConfig::ReporterConfig( IConfigPtr const& _fullConfig )
11075 : m_stream( &_fullConfig->stream() ), m_fullConfig( _fullConfig ) {}
11076
ReporterConfig(IConfigPtr const & _fullConfig,std::ostream & _stream)11077 ReporterConfig::ReporterConfig( IConfigPtr const& _fullConfig, std::ostream& _stream )
11078 : m_stream( &_stream ), m_fullConfig( _fullConfig ) {}
11079
stream() const11080 std::ostream& ReporterConfig::stream() const { return *m_stream; }
fullConfig() const11081 IConfigPtr ReporterConfig::fullConfig() const { return m_fullConfig; }
11082
TestRunInfo(std::string const & _name)11083 TestRunInfo::TestRunInfo( std::string const& _name ) : name( _name ) {}
11084
GroupInfo(std::string const & _name,std::size_t _groupIndex,std::size_t _groupsCount)11085 GroupInfo::GroupInfo( std::string const& _name,
11086 std::size_t _groupIndex,
11087 std::size_t _groupsCount )
11088 : name( _name ),
11089 groupIndex( _groupIndex ),
11090 groupsCounts( _groupsCount )
11091 {}
11092
AssertionStats(AssertionResult const & _assertionResult,std::vector<MessageInfo> const & _infoMessages,Totals const & _totals)11093 AssertionStats::AssertionStats( AssertionResult const& _assertionResult,
11094 std::vector<MessageInfo> const& _infoMessages,
11095 Totals const& _totals )
11096 : assertionResult( _assertionResult ),
11097 infoMessages( _infoMessages ),
11098 totals( _totals )
11099 {
11100 assertionResult.m_resultData.lazyExpression.m_transientExpression = _assertionResult.m_resultData.lazyExpression.m_transientExpression;
11101
11102 if( assertionResult.hasMessage() ) {
11103 // Copy message into messages list.
11104 // !TBD This should have been done earlier, somewhere
11105 MessageBuilder builder( assertionResult.getTestMacroName(), assertionResult.getSourceInfo(), assertionResult.getResultType() );
11106 builder << assertionResult.getMessage();
11107 builder.m_info.message = builder.m_stream.str();
11108
11109 infoMessages.push_back( builder.m_info );
11110 }
11111 }
11112
11113 AssertionStats::~AssertionStats() = default;
11114
SectionStats(SectionInfo const & _sectionInfo,Counts const & _assertions,double _durationInSeconds,bool _missingAssertions)11115 SectionStats::SectionStats( SectionInfo const& _sectionInfo,
11116 Counts const& _assertions,
11117 double _durationInSeconds,
11118 bool _missingAssertions )
11119 : sectionInfo( _sectionInfo ),
11120 assertions( _assertions ),
11121 durationInSeconds( _durationInSeconds ),
11122 missingAssertions( _missingAssertions )
11123 {}
11124
11125 SectionStats::~SectionStats() = default;
11126
TestCaseStats(TestCaseInfo const & _testInfo,Totals const & _totals,std::string const & _stdOut,std::string const & _stdErr,bool _aborting)11127 TestCaseStats::TestCaseStats( TestCaseInfo const& _testInfo,
11128 Totals const& _totals,
11129 std::string const& _stdOut,
11130 std::string const& _stdErr,
11131 bool _aborting )
11132 : testInfo( _testInfo ),
11133 totals( _totals ),
11134 stdOut( _stdOut ),
11135 stdErr( _stdErr ),
11136 aborting( _aborting )
11137 {}
11138
11139 TestCaseStats::~TestCaseStats() = default;
11140
TestGroupStats(GroupInfo const & _groupInfo,Totals const & _totals,bool _aborting)11141 TestGroupStats::TestGroupStats( GroupInfo const& _groupInfo,
11142 Totals const& _totals,
11143 bool _aborting )
11144 : groupInfo( _groupInfo ),
11145 totals( _totals ),
11146 aborting( _aborting )
11147 {}
11148
TestGroupStats(GroupInfo const & _groupInfo)11149 TestGroupStats::TestGroupStats( GroupInfo const& _groupInfo )
11150 : groupInfo( _groupInfo ),
11151 aborting( false )
11152 {}
11153
11154 TestGroupStats::~TestGroupStats() = default;
11155
TestRunStats(TestRunInfo const & _runInfo,Totals const & _totals,bool _aborting)11156 TestRunStats::TestRunStats( TestRunInfo const& _runInfo,
11157 Totals const& _totals,
11158 bool _aborting )
11159 : runInfo( _runInfo ),
11160 totals( _totals ),
11161 aborting( _aborting )
11162 {}
11163
11164 TestRunStats::~TestRunStats() = default;
11165
fatalErrorEncountered(StringRef)11166 void IStreamingReporter::fatalErrorEncountered( StringRef ) {}
isMulti() const11167 bool IStreamingReporter::isMulti() const { return false; }
11168
11169 IReporterFactory::~IReporterFactory() = default;
11170 IReporterRegistry::~IReporterRegistry() = default;
11171
11172 } // end namespace Catch
11173 // end catch_interfaces_reporter.cpp
11174 // start catch_interfaces_runner.cpp
11175
11176 namespace Catch {
11177 IRunner::~IRunner() = default;
11178 }
11179 // end catch_interfaces_runner.cpp
11180 // start catch_interfaces_testcase.cpp
11181
11182 namespace Catch {
11183 ITestInvoker::~ITestInvoker() = default;
11184 ITestCaseRegistry::~ITestCaseRegistry() = default;
11185 }
11186 // end catch_interfaces_testcase.cpp
11187 // start catch_leak_detector.cpp
11188
11189 #ifdef CATCH_CONFIG_WINDOWS_CRTDBG
11190 #include <crtdbg.h>
11191
11192 namespace Catch {
11193
LeakDetector()11194 LeakDetector::LeakDetector() {
11195 int flag = _CrtSetDbgFlag(_CRTDBG_REPORT_FLAG);
11196 flag |= _CRTDBG_LEAK_CHECK_DF;
11197 flag |= _CRTDBG_ALLOC_MEM_DF;
11198 _CrtSetDbgFlag(flag);
11199 _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE | _CRTDBG_MODE_DEBUG);
11200 _CrtSetReportFile(_CRT_WARN, _CRTDBG_FILE_STDERR);
11201 // Change this to leaking allocation's number to break there
11202 _CrtSetBreakAlloc(-1);
11203 }
11204 }
11205
11206 #else
11207
LeakDetector()11208 Catch::LeakDetector::LeakDetector() {}
11209
11210 #endif
11211
~LeakDetector()11212 Catch::LeakDetector::~LeakDetector() {
11213 Catch::cleanUp();
11214 }
11215 // end catch_leak_detector.cpp
11216 // start catch_list.cpp
11217
11218 // start catch_list.h
11219
11220 #include <set>
11221
11222 namespace Catch {
11223
11224 std::size_t listTests( Config const& config );
11225
11226 std::size_t listTestsNamesOnly( Config const& config );
11227
11228 struct TagInfo {
11229 void add( std::string const& spelling );
11230 std::string all() const;
11231
11232 std::set<std::string> spellings;
11233 std::size_t count = 0;
11234 };
11235
11236 std::size_t listTags( Config const& config );
11237
11238 std::size_t listReporters();
11239
11240 Option<std::size_t> list( std::shared_ptr<Config> const& config );
11241
11242 } // end namespace Catch
11243
11244 // end catch_list.h
11245 // start catch_text.h
11246
11247 namespace Catch {
11248 using namespace clara::TextFlow;
11249 }
11250
11251 // end catch_text.h
11252 #include <limits>
11253 #include <algorithm>
11254 #include <iomanip>
11255
11256 namespace Catch {
11257
listTests(Config const & config)11258 std::size_t listTests( Config const& config ) {
11259 TestSpec const& testSpec = config.testSpec();
11260 if( config.hasTestFilters() )
11261 Catch::cout() << "Matching test cases:\n";
11262 else {
11263 Catch::cout() << "All available test cases:\n";
11264 }
11265
11266 auto matchedTestCases = filterTests( getAllTestCasesSorted( config ), testSpec, config );
11267 for( auto const& testCaseInfo : matchedTestCases ) {
11268 Colour::Code colour = testCaseInfo.isHidden()
11269 ? Colour::SecondaryText
11270 : Colour::None;
11271 Colour colourGuard( colour );
11272
11273 Catch::cout() << Column( testCaseInfo.name ).initialIndent( 2 ).indent( 4 ) << "\n";
11274 if( config.verbosity() >= Verbosity::High ) {
11275 Catch::cout() << Column( Catch::Detail::stringify( testCaseInfo.lineInfo ) ).indent(4) << std::endl;
11276 std::string description = testCaseInfo.description;
11277 if( description.empty() )
11278 description = "(NO DESCRIPTION)";
11279 Catch::cout() << Column( description ).indent(4) << std::endl;
11280 }
11281 if( !testCaseInfo.tags.empty() )
11282 Catch::cout() << Column( testCaseInfo.tagsAsString() ).indent( 6 ) << "\n";
11283 }
11284
11285 if( !config.hasTestFilters() )
11286 Catch::cout() << pluralise( matchedTestCases.size(), "test case" ) << '\n' << std::endl;
11287 else
11288 Catch::cout() << pluralise( matchedTestCases.size(), "matching test case" ) << '\n' << std::endl;
11289 return matchedTestCases.size();
11290 }
11291
listTestsNamesOnly(Config const & config)11292 std::size_t listTestsNamesOnly( Config const& config ) {
11293 TestSpec const& testSpec = config.testSpec();
11294 std::size_t matchedTests = 0;
11295 std::vector<TestCase> matchedTestCases = filterTests( getAllTestCasesSorted( config ), testSpec, config );
11296 for( auto const& testCaseInfo : matchedTestCases ) {
11297 matchedTests++;
11298 if( startsWith( testCaseInfo.name, '#' ) )
11299 Catch::cout() << '"' << testCaseInfo.name << '"';
11300 else
11301 Catch::cout() << testCaseInfo.name;
11302 if ( config.verbosity() >= Verbosity::High )
11303 Catch::cout() << "\t@" << testCaseInfo.lineInfo;
11304 Catch::cout() << std::endl;
11305 }
11306 return matchedTests;
11307 }
11308
add(std::string const & spelling)11309 void TagInfo::add( std::string const& spelling ) {
11310 ++count;
11311 spellings.insert( spelling );
11312 }
11313
all() const11314 std::string TagInfo::all() const {
11315 size_t size = 0;
11316 for (auto const& spelling : spellings) {
11317 // Add 2 for the brackes
11318 size += spelling.size() + 2;
11319 }
11320
11321 std::string out; out.reserve(size);
11322 for (auto const& spelling : spellings) {
11323 out += '[';
11324 out += spelling;
11325 out += ']';
11326 }
11327 return out;
11328 }
11329
listTags(Config const & config)11330 std::size_t listTags( Config const& config ) {
11331 TestSpec const& testSpec = config.testSpec();
11332 if( config.hasTestFilters() )
11333 Catch::cout() << "Tags for matching test cases:\n";
11334 else {
11335 Catch::cout() << "All available tags:\n";
11336 }
11337
11338 std::map<std::string, TagInfo> tagCounts;
11339
11340 std::vector<TestCase> matchedTestCases = filterTests( getAllTestCasesSorted( config ), testSpec, config );
11341 for( auto const& testCase : matchedTestCases ) {
11342 for( auto const& tagName : testCase.getTestCaseInfo().tags ) {
11343 std::string lcaseTagName = toLower( tagName );
11344 auto countIt = tagCounts.find( lcaseTagName );
11345 if( countIt == tagCounts.end() )
11346 countIt = tagCounts.insert( std::make_pair( lcaseTagName, TagInfo() ) ).first;
11347 countIt->second.add( tagName );
11348 }
11349 }
11350
11351 for( auto const& tagCount : tagCounts ) {
11352 ReusableStringStream rss;
11353 rss << " " << std::setw(2) << tagCount.second.count << " ";
11354 auto str = rss.str();
11355 auto wrapper = Column( tagCount.second.all() )
11356 .initialIndent( 0 )
11357 .indent( str.size() )
11358 .width( CATCH_CONFIG_CONSOLE_WIDTH-10 );
11359 Catch::cout() << str << wrapper << '\n';
11360 }
11361 Catch::cout() << pluralise( tagCounts.size(), "tag" ) << '\n' << std::endl;
11362 return tagCounts.size();
11363 }
11364
listReporters()11365 std::size_t listReporters() {
11366 Catch::cout() << "Available reporters:\n";
11367 IReporterRegistry::FactoryMap const& factories = getRegistryHub().getReporterRegistry().getFactories();
11368 std::size_t maxNameLen = 0;
11369 for( auto const& factoryKvp : factories )
11370 maxNameLen = (std::max)( maxNameLen, factoryKvp.first.size() );
11371
11372 for( auto const& factoryKvp : factories ) {
11373 Catch::cout()
11374 << Column( factoryKvp.first + ":" )
11375 .indent(2)
11376 .width( 5+maxNameLen )
11377 + Column( factoryKvp.second->getDescription() )
11378 .initialIndent(0)
11379 .indent(2)
11380 .width( CATCH_CONFIG_CONSOLE_WIDTH - maxNameLen-8 )
11381 << "\n";
11382 }
11383 Catch::cout() << std::endl;
11384 return factories.size();
11385 }
11386
list(std::shared_ptr<Config> const & config)11387 Option<std::size_t> list( std::shared_ptr<Config> const& config ) {
11388 Option<std::size_t> listedCount;
11389 getCurrentMutableContext().setConfig( config );
11390 if( config->listTests() )
11391 listedCount = listedCount.valueOr(0) + listTests( *config );
11392 if( config->listTestNamesOnly() )
11393 listedCount = listedCount.valueOr(0) + listTestsNamesOnly( *config );
11394 if( config->listTags() )
11395 listedCount = listedCount.valueOr(0) + listTags( *config );
11396 if( config->listReporters() )
11397 listedCount = listedCount.valueOr(0) + listReporters();
11398 return listedCount;
11399 }
11400
11401 } // end namespace Catch
11402 // end catch_list.cpp
11403 // start catch_matchers.cpp
11404
11405 namespace Catch {
11406 namespace Matchers {
11407 namespace Impl {
11408
toString() const11409 std::string MatcherUntypedBase::toString() const {
11410 if( m_cachedToString.empty() )
11411 m_cachedToString = describe();
11412 return m_cachedToString;
11413 }
11414
11415 MatcherUntypedBase::~MatcherUntypedBase() = default;
11416
11417 } // namespace Impl
11418 } // namespace Matchers
11419
11420 using namespace Matchers;
11421 using Matchers::Impl::MatcherBase;
11422
11423 } // namespace Catch
11424 // end catch_matchers.cpp
11425 // start catch_matchers_exception.cpp
11426
11427 namespace Catch {
11428 namespace Matchers {
11429 namespace Exception {
11430
match(std::exception const & ex) const11431 bool ExceptionMessageMatcher::match(std::exception const& ex) const {
11432 return ex.what() == m_message;
11433 }
11434
describe() const11435 std::string ExceptionMessageMatcher::describe() const {
11436 return "exception message matches \"" + m_message + "\"";
11437 }
11438
11439 }
Message(std::string const & message)11440 Exception::ExceptionMessageMatcher Message(std::string const& message) {
11441 return Exception::ExceptionMessageMatcher(message);
11442 }
11443
11444 // namespace Exception
11445 } // namespace Matchers
11446 } // namespace Catch
11447 // end catch_matchers_exception.cpp
11448 // start catch_matchers_floating.cpp
11449
11450 // start catch_polyfills.hpp
11451
11452 namespace Catch {
11453 bool isnan(float f);
11454 bool isnan(double d);
11455 }
11456
11457 // end catch_polyfills.hpp
11458 // start catch_to_string.hpp
11459
11460 #include <string>
11461
11462 namespace Catch {
11463 template <typename T>
to_string(T const & t)11464 std::string to_string(T const& t) {
11465 #if defined(CATCH_CONFIG_CPP11_TO_STRING)
11466 return std::to_string(t);
11467 #else
11468 ReusableStringStream rss;
11469 rss << t;
11470 return rss.str();
11471 #endif
11472 }
11473 } // end namespace Catch
11474
11475 // end catch_to_string.hpp
11476 #include <algorithm>
11477 #include <cmath>
11478 #include <cstdlib>
11479 #include <cstdint>
11480 #include <cstring>
11481 #include <sstream>
11482 #include <type_traits>
11483 #include <iomanip>
11484 #include <limits>
11485
11486 namespace Catch {
11487 namespace {
11488
convert(float f)11489 int32_t convert(float f) {
11490 static_assert(sizeof(float) == sizeof(int32_t), "Important ULP matcher assumption violated");
11491 int32_t i;
11492 std::memcpy(&i, &f, sizeof(f));
11493 return i;
11494 }
11495
convert(double d)11496 int64_t convert(double d) {
11497 static_assert(sizeof(double) == sizeof(int64_t), "Important ULP matcher assumption violated");
11498 int64_t i;
11499 std::memcpy(&i, &d, sizeof(d));
11500 return i;
11501 }
11502
11503 template <typename FP>
almostEqualUlps(FP lhs,FP rhs,uint64_t maxUlpDiff)11504 bool almostEqualUlps(FP lhs, FP rhs, uint64_t maxUlpDiff) {
11505 // Comparison with NaN should always be false.
11506 // This way we can rule it out before getting into the ugly details
11507 if (Catch::isnan(lhs) || Catch::isnan(rhs)) {
11508 return false;
11509 }
11510
11511 auto lc = convert(lhs);
11512 auto rc = convert(rhs);
11513
11514 if ((lc < 0) != (rc < 0)) {
11515 // Potentially we can have +0 and -0
11516 return lhs == rhs;
11517 }
11518
11519 // static cast as a workaround for IBM XLC
11520 auto ulpDiff = std::abs(static_cast<FP>(lc - rc));
11521 return static_cast<uint64_t>(ulpDiff) <= maxUlpDiff;
11522 }
11523
11524 #if defined(CATCH_CONFIG_GLOBAL_NEXTAFTER)
11525
nextafter(float x,float y)11526 float nextafter(float x, float y) {
11527 return ::nextafterf(x, y);
11528 }
11529
nextafter(double x,double y)11530 double nextafter(double x, double y) {
11531 return ::nextafter(x, y);
11532 }
11533
11534 #endif // ^^^ CATCH_CONFIG_GLOBAL_NEXTAFTER ^^^
11535
11536 template <typename FP>
step(FP start,FP direction,uint64_t steps)11537 FP step(FP start, FP direction, uint64_t steps) {
11538 for (uint64_t i = 0; i < steps; ++i) {
11539 #if defined(CATCH_CONFIG_GLOBAL_NEXTAFTER)
11540 start = Catch::nextafter(start, direction);
11541 #else
11542 start = std::nextafter(start, direction);
11543 #endif
11544 }
11545 return start;
11546 }
11547
11548 // Performs equivalent check of std::fabs(lhs - rhs) <= margin
11549 // But without the subtraction to allow for INFINITY in comparison
marginComparison(double lhs,double rhs,double margin)11550 bool marginComparison(double lhs, double rhs, double margin) {
11551 return (lhs + margin >= rhs) && (rhs + margin >= lhs);
11552 }
11553
11554 template <typename FloatingPoint>
write(std::ostream & out,FloatingPoint num)11555 void write(std::ostream& out, FloatingPoint num) {
11556 out << std::scientific
11557 << std::setprecision(std::numeric_limits<FloatingPoint>::max_digits10 - 1)
11558 << num;
11559 }
11560
11561 } // end anonymous namespace
11562
11563 namespace Matchers {
11564 namespace Floating {
11565
11566 enum class FloatingPointKind : uint8_t {
11567 Float,
11568 Double
11569 };
11570
WithinAbsMatcher(double target,double margin)11571 WithinAbsMatcher::WithinAbsMatcher(double target, double margin)
11572 :m_target{ target }, m_margin{ margin } {
11573 CATCH_ENFORCE(margin >= 0, "Invalid margin: " << margin << '.'
11574 << " Margin has to be non-negative.");
11575 }
11576
11577 // Performs equivalent check of std::fabs(lhs - rhs) <= margin
11578 // But without the subtraction to allow for INFINITY in comparison
match(double const & matchee) const11579 bool WithinAbsMatcher::match(double const& matchee) const {
11580 return (matchee + m_margin >= m_target) && (m_target + m_margin >= matchee);
11581 }
11582
describe() const11583 std::string WithinAbsMatcher::describe() const {
11584 return "is within " + ::Catch::Detail::stringify(m_margin) + " of " + ::Catch::Detail::stringify(m_target);
11585 }
11586
WithinUlpsMatcher(double target,uint64_t ulps,FloatingPointKind baseType)11587 WithinUlpsMatcher::WithinUlpsMatcher(double target, uint64_t ulps, FloatingPointKind baseType)
11588 :m_target{ target }, m_ulps{ ulps }, m_type{ baseType } {
11589 CATCH_ENFORCE(m_type == FloatingPointKind::Double
11590 || m_ulps < (std::numeric_limits<uint32_t>::max)(),
11591 "Provided ULP is impossibly large for a float comparison.");
11592 }
11593
11594 #if defined(__clang__)
11595 #pragma clang diagnostic push
11596 // Clang <3.5 reports on the default branch in the switch below
11597 #pragma clang diagnostic ignored "-Wunreachable-code"
11598 #endif
11599
match(double const & matchee) const11600 bool WithinUlpsMatcher::match(double const& matchee) const {
11601 switch (m_type) {
11602 case FloatingPointKind::Float:
11603 return almostEqualUlps<float>(static_cast<float>(matchee), static_cast<float>(m_target), m_ulps);
11604 case FloatingPointKind::Double:
11605 return almostEqualUlps<double>(matchee, m_target, m_ulps);
11606 default:
11607 CATCH_INTERNAL_ERROR( "Unknown FloatingPointKind value" );
11608 }
11609 }
11610
11611 #if defined(__clang__)
11612 #pragma clang diagnostic pop
11613 #endif
11614
describe() const11615 std::string WithinUlpsMatcher::describe() const {
11616 std::stringstream ret;
11617
11618 ret << "is within " << m_ulps << " ULPs of ";
11619
11620 if (m_type == FloatingPointKind::Float) {
11621 write(ret, static_cast<float>(m_target));
11622 ret << 'f';
11623 } else {
11624 write(ret, m_target);
11625 }
11626
11627 ret << " ([";
11628 if (m_type == FloatingPointKind::Double) {
11629 write(ret, step(m_target, static_cast<double>(-INFINITY), m_ulps));
11630 ret << ", ";
11631 write(ret, step(m_target, static_cast<double>( INFINITY), m_ulps));
11632 } else {
11633 // We have to cast INFINITY to float because of MinGW, see #1782
11634 write(ret, step(static_cast<float>(m_target), static_cast<float>(-INFINITY), m_ulps));
11635 ret << ", ";
11636 write(ret, step(static_cast<float>(m_target), static_cast<float>( INFINITY), m_ulps));
11637 }
11638 ret << "])";
11639
11640 return ret.str();
11641 }
11642
WithinRelMatcher(double target,double epsilon)11643 WithinRelMatcher::WithinRelMatcher(double target, double epsilon):
11644 m_target(target),
11645 m_epsilon(epsilon){
11646 CATCH_ENFORCE(m_epsilon >= 0., "Relative comparison with epsilon < 0 does not make sense.");
11647 CATCH_ENFORCE(m_epsilon < 1., "Relative comparison with epsilon >= 1 does not make sense.");
11648 }
11649
match(double const & matchee) const11650 bool WithinRelMatcher::match(double const& matchee) const {
11651 const auto relMargin = m_epsilon * (std::max)(std::fabs(matchee), std::fabs(m_target));
11652 return marginComparison(matchee, m_target,
11653 std::isinf(relMargin)? 0 : relMargin);
11654 }
11655
describe() const11656 std::string WithinRelMatcher::describe() const {
11657 Catch::ReusableStringStream sstr;
11658 sstr << "and " << m_target << " are within " << m_epsilon * 100. << "% of each other";
11659 return sstr.str();
11660 }
11661
11662 }// namespace Floating
11663
WithinULP(double target,uint64_t maxUlpDiff)11664 Floating::WithinUlpsMatcher WithinULP(double target, uint64_t maxUlpDiff) {
11665 return Floating::WithinUlpsMatcher(target, maxUlpDiff, Floating::FloatingPointKind::Double);
11666 }
11667
WithinULP(float target,uint64_t maxUlpDiff)11668 Floating::WithinUlpsMatcher WithinULP(float target, uint64_t maxUlpDiff) {
11669 return Floating::WithinUlpsMatcher(target, maxUlpDiff, Floating::FloatingPointKind::Float);
11670 }
11671
WithinAbs(double target,double margin)11672 Floating::WithinAbsMatcher WithinAbs(double target, double margin) {
11673 return Floating::WithinAbsMatcher(target, margin);
11674 }
11675
WithinRel(double target,double eps)11676 Floating::WithinRelMatcher WithinRel(double target, double eps) {
11677 return Floating::WithinRelMatcher(target, eps);
11678 }
11679
WithinRel(double target)11680 Floating::WithinRelMatcher WithinRel(double target) {
11681 return Floating::WithinRelMatcher(target, std::numeric_limits<double>::epsilon() * 100);
11682 }
11683
WithinRel(float target,float eps)11684 Floating::WithinRelMatcher WithinRel(float target, float eps) {
11685 return Floating::WithinRelMatcher(target, eps);
11686 }
11687
WithinRel(float target)11688 Floating::WithinRelMatcher WithinRel(float target) {
11689 return Floating::WithinRelMatcher(target, std::numeric_limits<float>::epsilon() * 100);
11690 }
11691
11692 } // namespace Matchers
11693 } // namespace Catch
11694 // end catch_matchers_floating.cpp
11695 // start catch_matchers_generic.cpp
11696
finalizeDescription(const std::string & desc)11697 std::string Catch::Matchers::Generic::Detail::finalizeDescription(const std::string& desc) {
11698 if (desc.empty()) {
11699 return "matches undescribed predicate";
11700 } else {
11701 return "matches predicate: \"" + desc + '"';
11702 }
11703 }
11704 // end catch_matchers_generic.cpp
11705 // start catch_matchers_string.cpp
11706
11707 #include <regex>
11708
11709 namespace Catch {
11710 namespace Matchers {
11711
11712 namespace StdString {
11713
CasedString(std::string const & str,CaseSensitive::Choice caseSensitivity)11714 CasedString::CasedString( std::string const& str, CaseSensitive::Choice caseSensitivity )
11715 : m_caseSensitivity( caseSensitivity ),
11716 m_str( adjustString( str ) )
11717 {}
adjustString(std::string const & str) const11718 std::string CasedString::adjustString( std::string const& str ) const {
11719 return m_caseSensitivity == CaseSensitive::No
11720 ? toLower( str )
11721 : str;
11722 }
caseSensitivitySuffix() const11723 std::string CasedString::caseSensitivitySuffix() const {
11724 return m_caseSensitivity == CaseSensitive::No
11725 ? " (case insensitive)"
11726 : std::string();
11727 }
11728
StringMatcherBase(std::string const & operation,CasedString const & comparator)11729 StringMatcherBase::StringMatcherBase( std::string const& operation, CasedString const& comparator )
11730 : m_comparator( comparator ),
11731 m_operation( operation ) {
11732 }
11733
describe() const11734 std::string StringMatcherBase::describe() const {
11735 std::string description;
11736 description.reserve(5 + m_operation.size() + m_comparator.m_str.size() +
11737 m_comparator.caseSensitivitySuffix().size());
11738 description += m_operation;
11739 description += ": \"";
11740 description += m_comparator.m_str;
11741 description += "\"";
11742 description += m_comparator.caseSensitivitySuffix();
11743 return description;
11744 }
11745
EqualsMatcher(CasedString const & comparator)11746 EqualsMatcher::EqualsMatcher( CasedString const& comparator ) : StringMatcherBase( "equals", comparator ) {}
11747
match(std::string const & source) const11748 bool EqualsMatcher::match( std::string const& source ) const {
11749 return m_comparator.adjustString( source ) == m_comparator.m_str;
11750 }
11751
ContainsMatcher(CasedString const & comparator)11752 ContainsMatcher::ContainsMatcher( CasedString const& comparator ) : StringMatcherBase( "contains", comparator ) {}
11753
match(std::string const & source) const11754 bool ContainsMatcher::match( std::string const& source ) const {
11755 return contains( m_comparator.adjustString( source ), m_comparator.m_str );
11756 }
11757
StartsWithMatcher(CasedString const & comparator)11758 StartsWithMatcher::StartsWithMatcher( CasedString const& comparator ) : StringMatcherBase( "starts with", comparator ) {}
11759
match(std::string const & source) const11760 bool StartsWithMatcher::match( std::string const& source ) const {
11761 return startsWith( m_comparator.adjustString( source ), m_comparator.m_str );
11762 }
11763
EndsWithMatcher(CasedString const & comparator)11764 EndsWithMatcher::EndsWithMatcher( CasedString const& comparator ) : StringMatcherBase( "ends with", comparator ) {}
11765
match(std::string const & source) const11766 bool EndsWithMatcher::match( std::string const& source ) const {
11767 return endsWith( m_comparator.adjustString( source ), m_comparator.m_str );
11768 }
11769
RegexMatcher(std::string regex,CaseSensitive::Choice caseSensitivity)11770 RegexMatcher::RegexMatcher(std::string regex, CaseSensitive::Choice caseSensitivity): m_regex(std::move(regex)), m_caseSensitivity(caseSensitivity) {}
11771
match(std::string const & matchee) const11772 bool RegexMatcher::match(std::string const& matchee) const {
11773 auto flags = std::regex::ECMAScript; // ECMAScript is the default syntax option anyway
11774 if (m_caseSensitivity == CaseSensitive::Choice::No) {
11775 flags |= std::regex::icase;
11776 }
11777 auto reg = std::regex(m_regex, flags);
11778 return std::regex_match(matchee, reg);
11779 }
11780
describe() const11781 std::string RegexMatcher::describe() const {
11782 return "matches " + ::Catch::Detail::stringify(m_regex) + ((m_caseSensitivity == CaseSensitive::Choice::Yes)? " case sensitively" : " case insensitively");
11783 }
11784
11785 } // namespace StdString
11786
Equals(std::string const & str,CaseSensitive::Choice caseSensitivity)11787 StdString::EqualsMatcher Equals( std::string const& str, CaseSensitive::Choice caseSensitivity ) {
11788 return StdString::EqualsMatcher( StdString::CasedString( str, caseSensitivity) );
11789 }
Contains(std::string const & str,CaseSensitive::Choice caseSensitivity)11790 StdString::ContainsMatcher Contains( std::string const& str, CaseSensitive::Choice caseSensitivity ) {
11791 return StdString::ContainsMatcher( StdString::CasedString( str, caseSensitivity) );
11792 }
EndsWith(std::string const & str,CaseSensitive::Choice caseSensitivity)11793 StdString::EndsWithMatcher EndsWith( std::string const& str, CaseSensitive::Choice caseSensitivity ) {
11794 return StdString::EndsWithMatcher( StdString::CasedString( str, caseSensitivity) );
11795 }
StartsWith(std::string const & str,CaseSensitive::Choice caseSensitivity)11796 StdString::StartsWithMatcher StartsWith( std::string const& str, CaseSensitive::Choice caseSensitivity ) {
11797 return StdString::StartsWithMatcher( StdString::CasedString( str, caseSensitivity) );
11798 }
11799
Matches(std::string const & regex,CaseSensitive::Choice caseSensitivity)11800 StdString::RegexMatcher Matches(std::string const& regex, CaseSensitive::Choice caseSensitivity) {
11801 return StdString::RegexMatcher(regex, caseSensitivity);
11802 }
11803
11804 } // namespace Matchers
11805 } // namespace Catch
11806 // end catch_matchers_string.cpp
11807 // start catch_message.cpp
11808
11809 // start catch_uncaught_exceptions.h
11810
11811 namespace Catch {
11812 bool uncaught_exceptions();
11813 } // end namespace Catch
11814
11815 // end catch_uncaught_exceptions.h
11816 #include <cassert>
11817 #include <stack>
11818
11819 namespace Catch {
11820
MessageInfo(StringRef const & _macroName,SourceLineInfo const & _lineInfo,ResultWas::OfType _type)11821 MessageInfo::MessageInfo( StringRef const& _macroName,
11822 SourceLineInfo const& _lineInfo,
11823 ResultWas::OfType _type )
11824 : macroName( _macroName ),
11825 lineInfo( _lineInfo ),
11826 type( _type ),
11827 sequence( ++globalCount )
11828 {}
11829
operator ==(MessageInfo const & other) const11830 bool MessageInfo::operator==( MessageInfo const& other ) const {
11831 return sequence == other.sequence;
11832 }
11833
operator <(MessageInfo const & other) const11834 bool MessageInfo::operator<( MessageInfo const& other ) const {
11835 return sequence < other.sequence;
11836 }
11837
11838 // This may need protecting if threading support is added
11839 unsigned int MessageInfo::globalCount = 0;
11840
11841 ////////////////////////////////////////////////////////////////////////////
11842
MessageBuilder(StringRef const & macroName,SourceLineInfo const & lineInfo,ResultWas::OfType type)11843 Catch::MessageBuilder::MessageBuilder( StringRef const& macroName,
11844 SourceLineInfo const& lineInfo,
11845 ResultWas::OfType type )
11846 :m_info(macroName, lineInfo, type) {}
11847
11848 ////////////////////////////////////////////////////////////////////////////
11849
ScopedMessage(MessageBuilder const & builder)11850 ScopedMessage::ScopedMessage( MessageBuilder const& builder )
11851 : m_info( builder.m_info ), m_moved()
11852 {
11853 m_info.message = builder.m_stream.str();
11854 getResultCapture().pushScopedMessage( m_info );
11855 }
11856
ScopedMessage(ScopedMessage && old)11857 ScopedMessage::ScopedMessage( ScopedMessage&& old )
11858 : m_info( old.m_info ), m_moved()
11859 {
11860 old.m_moved = true;
11861 }
11862
~ScopedMessage()11863 ScopedMessage::~ScopedMessage() {
11864 if ( !uncaught_exceptions() && !m_moved ){
11865 getResultCapture().popScopedMessage(m_info);
11866 }
11867 }
11868
Capturer(StringRef macroName,SourceLineInfo const & lineInfo,ResultWas::OfType resultType,StringRef names)11869 Capturer::Capturer( StringRef macroName, SourceLineInfo const& lineInfo, ResultWas::OfType resultType, StringRef names ) {
11870 auto trimmed = [&] (size_t start, size_t end) {
11871 while (names[start] == ',' || isspace(static_cast<unsigned char>(names[start]))) {
11872 ++start;
11873 }
11874 while (names[end] == ',' || isspace(static_cast<unsigned char>(names[end]))) {
11875 --end;
11876 }
11877 return names.substr(start, end - start + 1);
11878 };
11879 auto skipq = [&] (size_t start, char quote) {
11880 for (auto i = start + 1; i < names.size() ; ++i) {
11881 if (names[i] == quote)
11882 return i;
11883 if (names[i] == '\\')
11884 ++i;
11885 }
11886 CATCH_INTERNAL_ERROR("CAPTURE parsing encountered unmatched quote");
11887 };
11888
11889 size_t start = 0;
11890 std::stack<char> openings;
11891 for (size_t pos = 0; pos < names.size(); ++pos) {
11892 char c = names[pos];
11893 switch (c) {
11894 case '[':
11895 case '{':
11896 case '(':
11897 // It is basically impossible to disambiguate between
11898 // comparison and start of template args in this context
11899 // case '<':
11900 openings.push(c);
11901 break;
11902 case ']':
11903 case '}':
11904 case ')':
11905 // case '>':
11906 openings.pop();
11907 break;
11908 case '"':
11909 case '\'':
11910 pos = skipq(pos, c);
11911 break;
11912 case ',':
11913 if (start != pos && openings.empty()) {
11914 m_messages.emplace_back(macroName, lineInfo, resultType);
11915 m_messages.back().message = static_cast<std::string>(trimmed(start, pos));
11916 m_messages.back().message += " := ";
11917 start = pos;
11918 }
11919 }
11920 }
11921 assert(openings.empty() && "Mismatched openings");
11922 m_messages.emplace_back(macroName, lineInfo, resultType);
11923 m_messages.back().message = static_cast<std::string>(trimmed(start, names.size() - 1));
11924 m_messages.back().message += " := ";
11925 }
~Capturer()11926 Capturer::~Capturer() {
11927 if ( !uncaught_exceptions() ){
11928 assert( m_captured == m_messages.size() );
11929 for( size_t i = 0; i < m_captured; ++i )
11930 m_resultCapture.popScopedMessage( m_messages[i] );
11931 }
11932 }
11933
captureValue(size_t index,std::string const & value)11934 void Capturer::captureValue( size_t index, std::string const& value ) {
11935 assert( index < m_messages.size() );
11936 m_messages[index].message += value;
11937 m_resultCapture.pushScopedMessage( m_messages[index] );
11938 m_captured++;
11939 }
11940
11941 } // end namespace Catch
11942 // end catch_message.cpp
11943 // start catch_output_redirect.cpp
11944
11945 // start catch_output_redirect.h
11946 #ifndef TWOBLUECUBES_CATCH_OUTPUT_REDIRECT_H
11947 #define TWOBLUECUBES_CATCH_OUTPUT_REDIRECT_H
11948
11949 #include <cstdio>
11950 #include <iosfwd>
11951 #include <string>
11952
11953 namespace Catch {
11954
11955 class RedirectedStream {
11956 std::ostream& m_originalStream;
11957 std::ostream& m_redirectionStream;
11958 std::streambuf* m_prevBuf;
11959
11960 public:
11961 RedirectedStream( std::ostream& originalStream, std::ostream& redirectionStream );
11962 ~RedirectedStream();
11963 };
11964
11965 class RedirectedStdOut {
11966 ReusableStringStream m_rss;
11967 RedirectedStream m_cout;
11968 public:
11969 RedirectedStdOut();
11970 auto str() const -> std::string;
11971 };
11972
11973 // StdErr has two constituent streams in C++, std::cerr and std::clog
11974 // This means that we need to redirect 2 streams into 1 to keep proper
11975 // order of writes
11976 class RedirectedStdErr {
11977 ReusableStringStream m_rss;
11978 RedirectedStream m_cerr;
11979 RedirectedStream m_clog;
11980 public:
11981 RedirectedStdErr();
11982 auto str() const -> std::string;
11983 };
11984
11985 class RedirectedStreams {
11986 public:
11987 RedirectedStreams(RedirectedStreams const&) = delete;
11988 RedirectedStreams& operator=(RedirectedStreams const&) = delete;
11989 RedirectedStreams(RedirectedStreams&&) = delete;
11990 RedirectedStreams& operator=(RedirectedStreams&&) = delete;
11991
11992 RedirectedStreams(std::string& redirectedCout, std::string& redirectedCerr);
11993 ~RedirectedStreams();
11994 private:
11995 std::string& m_redirectedCout;
11996 std::string& m_redirectedCerr;
11997 RedirectedStdOut m_redirectedStdOut;
11998 RedirectedStdErr m_redirectedStdErr;
11999 };
12000
12001 #if defined(CATCH_CONFIG_NEW_CAPTURE)
12002
12003 // Windows's implementation of std::tmpfile is terrible (it tries
12004 // to create a file inside system folder, thus requiring elevated
12005 // privileges for the binary), so we have to use tmpnam(_s) and
12006 // create the file ourselves there.
12007 class TempFile {
12008 public:
12009 TempFile(TempFile const&) = delete;
12010 TempFile& operator=(TempFile const&) = delete;
12011 TempFile(TempFile&&) = delete;
12012 TempFile& operator=(TempFile&&) = delete;
12013
12014 TempFile();
12015 ~TempFile();
12016
12017 std::FILE* getFile();
12018 std::string getContents();
12019
12020 private:
12021 std::FILE* m_file = nullptr;
12022 #if defined(_MSC_VER)
12023 char m_buffer[L_tmpnam] = { 0 };
12024 #endif
12025 };
12026
12027 class OutputRedirect {
12028 public:
12029 OutputRedirect(OutputRedirect const&) = delete;
12030 OutputRedirect& operator=(OutputRedirect const&) = delete;
12031 OutputRedirect(OutputRedirect&&) = delete;
12032 OutputRedirect& operator=(OutputRedirect&&) = delete;
12033
12034 OutputRedirect(std::string& stdout_dest, std::string& stderr_dest);
12035 ~OutputRedirect();
12036
12037 private:
12038 int m_originalStdout = -1;
12039 int m_originalStderr = -1;
12040 TempFile m_stdoutFile;
12041 TempFile m_stderrFile;
12042 std::string& m_stdoutDest;
12043 std::string& m_stderrDest;
12044 };
12045
12046 #endif
12047
12048 } // end namespace Catch
12049
12050 #endif // TWOBLUECUBES_CATCH_OUTPUT_REDIRECT_H
12051 // end catch_output_redirect.h
12052 #include <cstdio>
12053 #include <cstring>
12054 #include <fstream>
12055 #include <sstream>
12056 #include <stdexcept>
12057
12058 #if defined(CATCH_CONFIG_NEW_CAPTURE)
12059 #if defined(_MSC_VER)
12060 #include <io.h> //_dup and _dup2
12061 #define dup _dup
12062 #define dup2 _dup2
12063 #define fileno _fileno
12064 #else
12065 #include <unistd.h> // dup and dup2
12066 #endif
12067 #endif
12068
12069 namespace Catch {
12070
RedirectedStream(std::ostream & originalStream,std::ostream & redirectionStream)12071 RedirectedStream::RedirectedStream( std::ostream& originalStream, std::ostream& redirectionStream )
12072 : m_originalStream( originalStream ),
12073 m_redirectionStream( redirectionStream ),
12074 m_prevBuf( m_originalStream.rdbuf() )
12075 {
12076 m_originalStream.rdbuf( m_redirectionStream.rdbuf() );
12077 }
12078
~RedirectedStream()12079 RedirectedStream::~RedirectedStream() {
12080 m_originalStream.rdbuf( m_prevBuf );
12081 }
12082
RedirectedStdOut()12083 RedirectedStdOut::RedirectedStdOut() : m_cout( Catch::cout(), m_rss.get() ) {}
str() const12084 auto RedirectedStdOut::str() const -> std::string { return m_rss.str(); }
12085
RedirectedStdErr()12086 RedirectedStdErr::RedirectedStdErr()
12087 : m_cerr( Catch::cerr(), m_rss.get() ),
12088 m_clog( Catch::clog(), m_rss.get() )
12089 {}
str() const12090 auto RedirectedStdErr::str() const -> std::string { return m_rss.str(); }
12091
RedirectedStreams(std::string & redirectedCout,std::string & redirectedCerr)12092 RedirectedStreams::RedirectedStreams(std::string& redirectedCout, std::string& redirectedCerr)
12093 : m_redirectedCout(redirectedCout),
12094 m_redirectedCerr(redirectedCerr)
12095 {}
12096
~RedirectedStreams()12097 RedirectedStreams::~RedirectedStreams() {
12098 m_redirectedCout += m_redirectedStdOut.str();
12099 m_redirectedCerr += m_redirectedStdErr.str();
12100 }
12101
12102 #if defined(CATCH_CONFIG_NEW_CAPTURE)
12103
12104 #if defined(_MSC_VER)
TempFile()12105 TempFile::TempFile() {
12106 if (tmpnam_s(m_buffer)) {
12107 CATCH_RUNTIME_ERROR("Could not get a temp filename");
12108 }
12109 if (fopen_s(&m_file, m_buffer, "w+")) {
12110 char buffer[100];
12111 if (strerror_s(buffer, errno)) {
12112 CATCH_RUNTIME_ERROR("Could not translate errno to a string");
12113 }
12114 CATCH_RUNTIME_ERROR("Could not open the temp file: '" << m_buffer << "' because: " << buffer);
12115 }
12116 }
12117 #else
TempFile()12118 TempFile::TempFile() {
12119 m_file = std::tmpfile();
12120 if (!m_file) {
12121 CATCH_RUNTIME_ERROR("Could not create a temp file.");
12122 }
12123 }
12124
12125 #endif
12126
~TempFile()12127 TempFile::~TempFile() {
12128 // TBD: What to do about errors here?
12129 std::fclose(m_file);
12130 // We manually create the file on Windows only, on Linux
12131 // it will be autodeleted
12132 #if defined(_MSC_VER)
12133 std::remove(m_buffer);
12134 #endif
12135 }
12136
getFile()12137 FILE* TempFile::getFile() {
12138 return m_file;
12139 }
12140
getContents()12141 std::string TempFile::getContents() {
12142 std::stringstream sstr;
12143 char buffer[100] = {};
12144 std::rewind(m_file);
12145 while (std::fgets(buffer, sizeof(buffer), m_file)) {
12146 sstr << buffer;
12147 }
12148 return sstr.str();
12149 }
12150
OutputRedirect(std::string & stdout_dest,std::string & stderr_dest)12151 OutputRedirect::OutputRedirect(std::string& stdout_dest, std::string& stderr_dest) :
12152 m_originalStdout(dup(1)),
12153 m_originalStderr(dup(2)),
12154 m_stdoutDest(stdout_dest),
12155 m_stderrDest(stderr_dest) {
12156 dup2(fileno(m_stdoutFile.getFile()), 1);
12157 dup2(fileno(m_stderrFile.getFile()), 2);
12158 }
12159
~OutputRedirect()12160 OutputRedirect::~OutputRedirect() {
12161 Catch::cout() << std::flush;
12162 fflush(stdout);
12163 // Since we support overriding these streams, we flush cerr
12164 // even though std::cerr is unbuffered
12165 Catch::cerr() << std::flush;
12166 Catch::clog() << std::flush;
12167 fflush(stderr);
12168
12169 dup2(m_originalStdout, 1);
12170 dup2(m_originalStderr, 2);
12171
12172 m_stdoutDest += m_stdoutFile.getContents();
12173 m_stderrDest += m_stderrFile.getContents();
12174 }
12175
12176 #endif // CATCH_CONFIG_NEW_CAPTURE
12177
12178 } // namespace Catch
12179
12180 #if defined(CATCH_CONFIG_NEW_CAPTURE)
12181 #if defined(_MSC_VER)
12182 #undef dup
12183 #undef dup2
12184 #undef fileno
12185 #endif
12186 #endif
12187 // end catch_output_redirect.cpp
12188 // start catch_polyfills.cpp
12189
12190 #include <cmath>
12191
12192 namespace Catch {
12193
12194 #if !defined(CATCH_CONFIG_POLYFILL_ISNAN)
isnan(float f)12195 bool isnan(float f) {
12196 return std::isnan(f);
12197 }
isnan(double d)12198 bool isnan(double d) {
12199 return std::isnan(d);
12200 }
12201 #else
12202 // For now we only use this for embarcadero
12203 bool isnan(float f) {
12204 return std::_isnan(f);
12205 }
12206 bool isnan(double d) {
12207 return std::_isnan(d);
12208 }
12209 #endif
12210
12211 } // end namespace Catch
12212 // end catch_polyfills.cpp
12213 // start catch_random_number_generator.cpp
12214
12215 namespace Catch {
12216
12217 namespace {
12218
12219 #if defined(_MSC_VER)
12220 #pragma warning(push)
12221 #pragma warning(disable:4146) // we negate uint32 during the rotate
12222 #endif
12223 // Safe rotr implementation thanks to John Regehr
rotate_right(uint32_t val,uint32_t count)12224 uint32_t rotate_right(uint32_t val, uint32_t count) {
12225 const uint32_t mask = 31;
12226 count &= mask;
12227 return (val >> count) | (val << (-count & mask));
12228 }
12229
12230 #if defined(_MSC_VER)
12231 #pragma warning(pop)
12232 #endif
12233
12234 }
12235
SimplePcg32(result_type seed_)12236 SimplePcg32::SimplePcg32(result_type seed_) {
12237 seed(seed_);
12238 }
12239
seed(result_type seed_)12240 void SimplePcg32::seed(result_type seed_) {
12241 m_state = 0;
12242 (*this)();
12243 m_state += seed_;
12244 (*this)();
12245 }
12246
discard(uint64_t skip)12247 void SimplePcg32::discard(uint64_t skip) {
12248 // We could implement this to run in O(log n) steps, but this
12249 // should suffice for our use case.
12250 for (uint64_t s = 0; s < skip; ++s) {
12251 static_cast<void>((*this)());
12252 }
12253 }
12254
operator ()()12255 SimplePcg32::result_type SimplePcg32::operator()() {
12256 // prepare the output value
12257 const uint32_t xorshifted = static_cast<uint32_t>(((m_state >> 18u) ^ m_state) >> 27u);
12258 const auto output = rotate_right(xorshifted, m_state >> 59u);
12259
12260 // advance state
12261 m_state = m_state * 6364136223846793005ULL + s_inc;
12262
12263 return output;
12264 }
12265
operator ==(SimplePcg32 const & lhs,SimplePcg32 const & rhs)12266 bool operator==(SimplePcg32 const& lhs, SimplePcg32 const& rhs) {
12267 return lhs.m_state == rhs.m_state;
12268 }
12269
operator !=(SimplePcg32 const & lhs,SimplePcg32 const & rhs)12270 bool operator!=(SimplePcg32 const& lhs, SimplePcg32 const& rhs) {
12271 return lhs.m_state != rhs.m_state;
12272 }
12273 }
12274 // end catch_random_number_generator.cpp
12275 // start catch_registry_hub.cpp
12276
12277 // start catch_test_case_registry_impl.h
12278
12279 #include <vector>
12280 #include <set>
12281 #include <algorithm>
12282 #include <ios>
12283
12284 namespace Catch {
12285
12286 class TestCase;
12287 struct IConfig;
12288
12289 std::vector<TestCase> sortTests( IConfig const& config, std::vector<TestCase> const& unsortedTestCases );
12290
12291 bool isThrowSafe( TestCase const& testCase, IConfig const& config );
12292 bool matchTest( TestCase const& testCase, TestSpec const& testSpec, IConfig const& config );
12293
12294 void enforceNoDuplicateTestCases( std::vector<TestCase> const& functions );
12295
12296 std::vector<TestCase> filterTests( std::vector<TestCase> const& testCases, TestSpec const& testSpec, IConfig const& config );
12297 std::vector<TestCase> const& getAllTestCasesSorted( IConfig const& config );
12298
12299 class TestRegistry : public ITestCaseRegistry {
12300 public:
12301 virtual ~TestRegistry() = default;
12302
12303 virtual void registerTest( TestCase const& testCase );
12304
12305 std::vector<TestCase> const& getAllTests() const override;
12306 std::vector<TestCase> const& getAllTestsSorted( IConfig const& config ) const override;
12307
12308 private:
12309 std::vector<TestCase> m_functions;
12310 mutable RunTests::InWhatOrder m_currentSortOrder = RunTests::InDeclarationOrder;
12311 mutable std::vector<TestCase> m_sortedFunctions;
12312 std::size_t m_unnamedCount = 0;
12313 std::ios_base::Init m_ostreamInit; // Forces cout/ cerr to be initialised
12314 };
12315
12316 ///////////////////////////////////////////////////////////////////////////
12317
12318 class TestInvokerAsFunction : public ITestInvoker {
12319 void(*m_testAsFunction)();
12320 public:
12321 TestInvokerAsFunction( void(*testAsFunction)() ) noexcept;
12322
12323 void invoke() const override;
12324 };
12325
12326 std::string extractClassName( StringRef const& classOrQualifiedMethodName );
12327
12328 ///////////////////////////////////////////////////////////////////////////
12329
12330 } // end namespace Catch
12331
12332 // end catch_test_case_registry_impl.h
12333 // start catch_reporter_registry.h
12334
12335 #include <map>
12336
12337 namespace Catch {
12338
12339 class ReporterRegistry : public IReporterRegistry {
12340
12341 public:
12342
12343 ~ReporterRegistry() override;
12344
12345 IStreamingReporterPtr create( std::string const& name, IConfigPtr const& config ) const override;
12346
12347 void registerReporter( std::string const& name, IReporterFactoryPtr const& factory );
12348 void registerListener( IReporterFactoryPtr const& factory );
12349
12350 FactoryMap const& getFactories() const override;
12351 Listeners const& getListeners() const override;
12352
12353 private:
12354 FactoryMap m_factories;
12355 Listeners m_listeners;
12356 };
12357 }
12358
12359 // end catch_reporter_registry.h
12360 // start catch_tag_alias_registry.h
12361
12362 // start catch_tag_alias.h
12363
12364 #include <string>
12365
12366 namespace Catch {
12367
12368 struct TagAlias {
12369 TagAlias(std::string const& _tag, SourceLineInfo _lineInfo);
12370
12371 std::string tag;
12372 SourceLineInfo lineInfo;
12373 };
12374
12375 } // end namespace Catch
12376
12377 // end catch_tag_alias.h
12378 #include <map>
12379
12380 namespace Catch {
12381
12382 class TagAliasRegistry : public ITagAliasRegistry {
12383 public:
12384 ~TagAliasRegistry() override;
12385 TagAlias const* find( std::string const& alias ) const override;
12386 std::string expandAliases( std::string const& unexpandedTestSpec ) const override;
12387 void add( std::string const& alias, std::string const& tag, SourceLineInfo const& lineInfo );
12388
12389 private:
12390 std::map<std::string, TagAlias> m_registry;
12391 };
12392
12393 } // end namespace Catch
12394
12395 // end catch_tag_alias_registry.h
12396 // start catch_startup_exception_registry.h
12397
12398 #include <vector>
12399 #include <exception>
12400
12401 namespace Catch {
12402
12403 class StartupExceptionRegistry {
12404 #if !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
12405 public:
12406 void add(std::exception_ptr const& exception) noexcept;
12407 std::vector<std::exception_ptr> const& getExceptions() const noexcept;
12408 private:
12409 std::vector<std::exception_ptr> m_exceptions;
12410 #endif
12411 };
12412
12413 } // end namespace Catch
12414
12415 // end catch_startup_exception_registry.h
12416 // start catch_singletons.hpp
12417
12418 namespace Catch {
12419
12420 struct ISingleton {
12421 virtual ~ISingleton();
12422 };
12423
12424 void addSingleton( ISingleton* singleton );
12425 void cleanupSingletons();
12426
12427 template<typename SingletonImplT, typename InterfaceT = SingletonImplT, typename MutableInterfaceT = InterfaceT>
12428 class Singleton : SingletonImplT, public ISingleton {
12429
getInternal()12430 static auto getInternal() -> Singleton* {
12431 static Singleton* s_instance = nullptr;
12432 if( !s_instance ) {
12433 s_instance = new Singleton;
12434 addSingleton( s_instance );
12435 }
12436 return s_instance;
12437 }
12438
12439 public:
get()12440 static auto get() -> InterfaceT const& {
12441 return *getInternal();
12442 }
getMutable()12443 static auto getMutable() -> MutableInterfaceT& {
12444 return *getInternal();
12445 }
12446 };
12447
12448 } // namespace Catch
12449
12450 // end catch_singletons.hpp
12451 namespace Catch {
12452
12453 namespace {
12454
12455 class RegistryHub : public IRegistryHub, public IMutableRegistryHub,
12456 private NonCopyable {
12457
12458 public: // IRegistryHub
12459 RegistryHub() = default;
getReporterRegistry() const12460 IReporterRegistry const& getReporterRegistry() const override {
12461 return m_reporterRegistry;
12462 }
getTestCaseRegistry() const12463 ITestCaseRegistry const& getTestCaseRegistry() const override {
12464 return m_testCaseRegistry;
12465 }
getExceptionTranslatorRegistry() const12466 IExceptionTranslatorRegistry const& getExceptionTranslatorRegistry() const override {
12467 return m_exceptionTranslatorRegistry;
12468 }
getTagAliasRegistry() const12469 ITagAliasRegistry const& getTagAliasRegistry() const override {
12470 return m_tagAliasRegistry;
12471 }
getStartupExceptionRegistry() const12472 StartupExceptionRegistry const& getStartupExceptionRegistry() const override {
12473 return m_exceptionRegistry;
12474 }
12475
12476 public: // IMutableRegistryHub
registerReporter(std::string const & name,IReporterFactoryPtr const & factory)12477 void registerReporter( std::string const& name, IReporterFactoryPtr const& factory ) override {
12478 m_reporterRegistry.registerReporter( name, factory );
12479 }
registerListener(IReporterFactoryPtr const & factory)12480 void registerListener( IReporterFactoryPtr const& factory ) override {
12481 m_reporterRegistry.registerListener( factory );
12482 }
registerTest(TestCase const & testInfo)12483 void registerTest( TestCase const& testInfo ) override {
12484 m_testCaseRegistry.registerTest( testInfo );
12485 }
registerTranslator(const IExceptionTranslator * translator)12486 void registerTranslator( const IExceptionTranslator* translator ) override {
12487 m_exceptionTranslatorRegistry.registerTranslator( translator );
12488 }
registerTagAlias(std::string const & alias,std::string const & tag,SourceLineInfo const & lineInfo)12489 void registerTagAlias( std::string const& alias, std::string const& tag, SourceLineInfo const& lineInfo ) override {
12490 m_tagAliasRegistry.add( alias, tag, lineInfo );
12491 }
registerStartupException()12492 void registerStartupException() noexcept override {
12493 #if !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
12494 m_exceptionRegistry.add(std::current_exception());
12495 #else
12496 CATCH_INTERNAL_ERROR("Attempted to register active exception under CATCH_CONFIG_DISABLE_EXCEPTIONS!");
12497 #endif
12498 }
getMutableEnumValuesRegistry()12499 IMutableEnumValuesRegistry& getMutableEnumValuesRegistry() override {
12500 return m_enumValuesRegistry;
12501 }
12502
12503 private:
12504 TestRegistry m_testCaseRegistry;
12505 ReporterRegistry m_reporterRegistry;
12506 ExceptionTranslatorRegistry m_exceptionTranslatorRegistry;
12507 TagAliasRegistry m_tagAliasRegistry;
12508 StartupExceptionRegistry m_exceptionRegistry;
12509 Detail::EnumValuesRegistry m_enumValuesRegistry;
12510 };
12511 }
12512
12513 using RegistryHubSingleton = Singleton<RegistryHub, IRegistryHub, IMutableRegistryHub>;
12514
getRegistryHub()12515 IRegistryHub const& getRegistryHub() {
12516 return RegistryHubSingleton::get();
12517 }
getMutableRegistryHub()12518 IMutableRegistryHub& getMutableRegistryHub() {
12519 return RegistryHubSingleton::getMutable();
12520 }
cleanUp()12521 void cleanUp() {
12522 cleanupSingletons();
12523 cleanUpContext();
12524 }
translateActiveException()12525 std::string translateActiveException() {
12526 return getRegistryHub().getExceptionTranslatorRegistry().translateActiveException();
12527 }
12528
12529 } // end namespace Catch
12530 // end catch_registry_hub.cpp
12531 // start catch_reporter_registry.cpp
12532
12533 namespace Catch {
12534
12535 ReporterRegistry::~ReporterRegistry() = default;
12536
create(std::string const & name,IConfigPtr const & config) const12537 IStreamingReporterPtr ReporterRegistry::create( std::string const& name, IConfigPtr const& config ) const {
12538 auto it = m_factories.find( name );
12539 if( it == m_factories.end() )
12540 return nullptr;
12541 return it->second->create( ReporterConfig( config ) );
12542 }
12543
registerReporter(std::string const & name,IReporterFactoryPtr const & factory)12544 void ReporterRegistry::registerReporter( std::string const& name, IReporterFactoryPtr const& factory ) {
12545 m_factories.emplace(name, factory);
12546 }
registerListener(IReporterFactoryPtr const & factory)12547 void ReporterRegistry::registerListener( IReporterFactoryPtr const& factory ) {
12548 m_listeners.push_back( factory );
12549 }
12550
getFactories() const12551 IReporterRegistry::FactoryMap const& ReporterRegistry::getFactories() const {
12552 return m_factories;
12553 }
getListeners() const12554 IReporterRegistry::Listeners const& ReporterRegistry::getListeners() const {
12555 return m_listeners;
12556 }
12557
12558 }
12559 // end catch_reporter_registry.cpp
12560 // start catch_result_type.cpp
12561
12562 namespace Catch {
12563
isOk(ResultWas::OfType resultType)12564 bool isOk( ResultWas::OfType resultType ) {
12565 return ( resultType & ResultWas::FailureBit ) == 0;
12566 }
isJustInfo(int flags)12567 bool isJustInfo( int flags ) {
12568 return flags == ResultWas::Info;
12569 }
12570
operator |(ResultDisposition::Flags lhs,ResultDisposition::Flags rhs)12571 ResultDisposition::Flags operator | ( ResultDisposition::Flags lhs, ResultDisposition::Flags rhs ) {
12572 return static_cast<ResultDisposition::Flags>( static_cast<int>( lhs ) | static_cast<int>( rhs ) );
12573 }
12574
shouldContinueOnFailure(int flags)12575 bool shouldContinueOnFailure( int flags ) { return ( flags & ResultDisposition::ContinueOnFailure ) != 0; }
shouldSuppressFailure(int flags)12576 bool shouldSuppressFailure( int flags ) { return ( flags & ResultDisposition::SuppressFail ) != 0; }
12577
12578 } // end namespace Catch
12579 // end catch_result_type.cpp
12580 // start catch_run_context.cpp
12581
12582 #include <cassert>
12583 #include <algorithm>
12584 #include <sstream>
12585
12586 namespace Catch {
12587
12588 namespace Generators {
12589 struct GeneratorTracker : TestCaseTracking::TrackerBase, IGeneratorTracker {
12590 GeneratorBasePtr m_generator;
12591
GeneratorTrackerCatch::Generators::GeneratorTracker12592 GeneratorTracker( TestCaseTracking::NameAndLocation const& nameAndLocation, TrackerContext& ctx, ITracker* parent )
12593 : TrackerBase( nameAndLocation, ctx, parent )
12594 {}
12595 ~GeneratorTracker();
12596
acquireCatch::Generators::GeneratorTracker12597 static GeneratorTracker& acquire( TrackerContext& ctx, TestCaseTracking::NameAndLocation const& nameAndLocation ) {
12598 std::shared_ptr<GeneratorTracker> tracker;
12599
12600 ITracker& currentTracker = ctx.currentTracker();
12601 // Under specific circumstances, the generator we want
12602 // to acquire is also the current tracker. If this is
12603 // the case, we have to avoid looking through current
12604 // tracker's children, and instead return the current
12605 // tracker.
12606 // A case where this check is important is e.g.
12607 // for (int i = 0; i < 5; ++i) {
12608 // int n = GENERATE(1, 2);
12609 // }
12610 //
12611 // without it, the code above creates 5 nested generators.
12612 if (currentTracker.nameAndLocation() == nameAndLocation) {
12613 auto thisTracker = currentTracker.parent().findChild(nameAndLocation);
12614 assert(thisTracker);
12615 assert(thisTracker->isGeneratorTracker());
12616 tracker = std::static_pointer_cast<GeneratorTracker>(thisTracker);
12617 } else if ( TestCaseTracking::ITrackerPtr childTracker = currentTracker.findChild( nameAndLocation ) ) {
12618 assert( childTracker );
12619 assert( childTracker->isGeneratorTracker() );
12620 tracker = std::static_pointer_cast<GeneratorTracker>( childTracker );
12621 } else {
12622 tracker = std::make_shared<GeneratorTracker>( nameAndLocation, ctx, ¤tTracker );
12623 currentTracker.addChild( tracker );
12624 }
12625
12626 if( !tracker->isComplete() ) {
12627 tracker->open();
12628 }
12629
12630 return *tracker;
12631 }
12632
12633 // TrackerBase interface
isGeneratorTrackerCatch::Generators::GeneratorTracker12634 bool isGeneratorTracker() const override { return true; }
hasGeneratorCatch::Generators::GeneratorTracker12635 auto hasGenerator() const -> bool override {
12636 return !!m_generator;
12637 }
closeCatch::Generators::GeneratorTracker12638 void close() override {
12639 TrackerBase::close();
12640 // If a generator has a child (it is followed by a section)
12641 // and none of its children have started, then we must wait
12642 // until later to start consuming its values.
12643 // This catches cases where `GENERATE` is placed between two
12644 // `SECTION`s.
12645 // **The check for m_children.empty cannot be removed**.
12646 // doing so would break `GENERATE` _not_ followed by `SECTION`s.
12647 const bool should_wait_for_child = [&]() {
12648 // No children -> nobody to wait for
12649 if ( m_children.empty() ) {
12650 return false;
12651 }
12652 // If at least one child started executing, don't wait
12653 if ( std::find_if(
12654 m_children.begin(),
12655 m_children.end(),
12656 []( TestCaseTracking::ITrackerPtr tracker ) {
12657 return tracker->hasStarted();
12658 } ) != m_children.end() ) {
12659 return false;
12660 }
12661
12662 // No children have started. We need to check if they _can_
12663 // start, and thus we should wait for them, or they cannot
12664 // start (due to filters), and we shouldn't wait for them
12665 auto* parent = m_parent;
12666 // This is safe: there is always at least one section
12667 // tracker in a test case tracking tree
12668 while ( !parent->isSectionTracker() ) {
12669 parent = &( parent->parent() );
12670 }
12671 assert( parent &&
12672 "Missing root (test case) level section" );
12673
12674 auto const& parentSection =
12675 static_cast<SectionTracker&>( *parent );
12676 auto const& filters = parentSection.getFilters();
12677 // No filters -> no restrictions on running sections
12678 if ( filters.empty() ) {
12679 return true;
12680 }
12681
12682 for ( auto const& child : m_children ) {
12683 if ( child->isSectionTracker() &&
12684 std::find( filters.begin(),
12685 filters.end(),
12686 static_cast<SectionTracker&>( *child )
12687 .trimmedName() ) !=
12688 filters.end() ) {
12689 return true;
12690 }
12691 }
12692 return false;
12693 }();
12694
12695 // This check is a bit tricky, because m_generator->next()
12696 // has a side-effect, where it consumes generator's current
12697 // value, but we do not want to invoke the side-effect if
12698 // this generator is still waiting for any child to start.
12699 if ( should_wait_for_child ||
12700 ( m_runState == CompletedSuccessfully &&
12701 m_generator->next() ) ) {
12702 m_children.clear();
12703 m_runState = Executing;
12704 }
12705 }
12706
12707 // IGeneratorTracker interface
getGeneratorCatch::Generators::GeneratorTracker12708 auto getGenerator() const -> GeneratorBasePtr const& override {
12709 return m_generator;
12710 }
setGeneratorCatch::Generators::GeneratorTracker12711 void setGenerator( GeneratorBasePtr&& generator ) override {
12712 m_generator = std::move( generator );
12713 }
12714 };
~GeneratorTracker()12715 GeneratorTracker::~GeneratorTracker() {}
12716 }
12717
RunContext(IConfigPtr const & _config,IStreamingReporterPtr && reporter)12718 RunContext::RunContext(IConfigPtr const& _config, IStreamingReporterPtr&& reporter)
12719 : m_runInfo(_config->name()),
12720 m_context(getCurrentMutableContext()),
12721 m_config(_config),
12722 m_reporter(std::move(reporter)),
12723 m_lastAssertionInfo{ StringRef(), SourceLineInfo("",0), StringRef(), ResultDisposition::Normal },
12724 m_includeSuccessfulResults( m_config->includeSuccessfulResults() || m_reporter->getPreferences().shouldReportAllAssertions )
12725 {
12726 m_context.setRunner(this);
12727 m_context.setConfig(m_config);
12728 m_context.setResultCapture(this);
12729 m_reporter->testRunStarting(m_runInfo);
12730 }
12731
~RunContext()12732 RunContext::~RunContext() {
12733 m_reporter->testRunEnded(TestRunStats(m_runInfo, m_totals, aborting()));
12734 }
12735
testGroupStarting(std::string const & testSpec,std::size_t groupIndex,std::size_t groupsCount)12736 void RunContext::testGroupStarting(std::string const& testSpec, std::size_t groupIndex, std::size_t groupsCount) {
12737 m_reporter->testGroupStarting(GroupInfo(testSpec, groupIndex, groupsCount));
12738 }
12739
testGroupEnded(std::string const & testSpec,Totals const & totals,std::size_t groupIndex,std::size_t groupsCount)12740 void RunContext::testGroupEnded(std::string const& testSpec, Totals const& totals, std::size_t groupIndex, std::size_t groupsCount) {
12741 m_reporter->testGroupEnded(TestGroupStats(GroupInfo(testSpec, groupIndex, groupsCount), totals, aborting()));
12742 }
12743
runTest(TestCase const & testCase)12744 Totals RunContext::runTest(TestCase const& testCase) {
12745 Totals prevTotals = m_totals;
12746
12747 std::string redirectedCout;
12748 std::string redirectedCerr;
12749
12750 auto const& testInfo = testCase.getTestCaseInfo();
12751
12752 m_reporter->testCaseStarting(testInfo);
12753
12754 m_activeTestCase = &testCase;
12755
12756 ITracker& rootTracker = m_trackerContext.startRun();
12757 assert(rootTracker.isSectionTracker());
12758 static_cast<SectionTracker&>(rootTracker).addInitialFilters(m_config->getSectionsToRun());
12759 do {
12760 m_trackerContext.startCycle();
12761 m_testCaseTracker = &SectionTracker::acquire(m_trackerContext, TestCaseTracking::NameAndLocation(testInfo.name, testInfo.lineInfo));
12762 runCurrentTest(redirectedCout, redirectedCerr);
12763 } while (!m_testCaseTracker->isSuccessfullyCompleted() && !aborting());
12764
12765 Totals deltaTotals = m_totals.delta(prevTotals);
12766 if (testInfo.expectedToFail() && deltaTotals.testCases.passed > 0) {
12767 deltaTotals.assertions.failed++;
12768 deltaTotals.testCases.passed--;
12769 deltaTotals.testCases.failed++;
12770 }
12771 m_totals.testCases += deltaTotals.testCases;
12772 m_reporter->testCaseEnded(TestCaseStats(testInfo,
12773 deltaTotals,
12774 redirectedCout,
12775 redirectedCerr,
12776 aborting()));
12777
12778 m_activeTestCase = nullptr;
12779 m_testCaseTracker = nullptr;
12780
12781 return deltaTotals;
12782 }
12783
config() const12784 IConfigPtr RunContext::config() const {
12785 return m_config;
12786 }
12787
reporter() const12788 IStreamingReporter& RunContext::reporter() const {
12789 return *m_reporter;
12790 }
12791
assertionEnded(AssertionResult const & result)12792 void RunContext::assertionEnded(AssertionResult const & result) {
12793 if (result.getResultType() == ResultWas::Ok) {
12794 m_totals.assertions.passed++;
12795 m_lastAssertionPassed = true;
12796 } else if (!result.isOk()) {
12797 m_lastAssertionPassed = false;
12798 if( m_activeTestCase->getTestCaseInfo().okToFail() )
12799 m_totals.assertions.failedButOk++;
12800 else
12801 m_totals.assertions.failed++;
12802 }
12803 else {
12804 m_lastAssertionPassed = true;
12805 }
12806
12807 // We have no use for the return value (whether messages should be cleared), because messages were made scoped
12808 // and should be let to clear themselves out.
12809 static_cast<void>(m_reporter->assertionEnded(AssertionStats(result, m_messages, m_totals)));
12810
12811 if (result.getResultType() != ResultWas::Warning)
12812 m_messageScopes.clear();
12813
12814 // Reset working state
12815 resetAssertionInfo();
12816 m_lastResult = result;
12817 }
resetAssertionInfo()12818 void RunContext::resetAssertionInfo() {
12819 m_lastAssertionInfo.macroName = StringRef();
12820 m_lastAssertionInfo.capturedExpression = "{Unknown expression after the reported line}"_sr;
12821 }
12822
sectionStarted(SectionInfo const & sectionInfo,Counts & assertions)12823 bool RunContext::sectionStarted(SectionInfo const & sectionInfo, Counts & assertions) {
12824 ITracker& sectionTracker = SectionTracker::acquire(m_trackerContext, TestCaseTracking::NameAndLocation(sectionInfo.name, sectionInfo.lineInfo));
12825 if (!sectionTracker.isOpen())
12826 return false;
12827 m_activeSections.push_back(§ionTracker);
12828
12829 m_lastAssertionInfo.lineInfo = sectionInfo.lineInfo;
12830
12831 m_reporter->sectionStarting(sectionInfo);
12832
12833 assertions = m_totals.assertions;
12834
12835 return true;
12836 }
acquireGeneratorTracker(StringRef generatorName,SourceLineInfo const & lineInfo)12837 auto RunContext::acquireGeneratorTracker( StringRef generatorName, SourceLineInfo const& lineInfo ) -> IGeneratorTracker& {
12838 using namespace Generators;
12839 GeneratorTracker& tracker = GeneratorTracker::acquire(m_trackerContext,
12840 TestCaseTracking::NameAndLocation( static_cast<std::string>(generatorName), lineInfo ) );
12841 m_lastAssertionInfo.lineInfo = lineInfo;
12842 return tracker;
12843 }
12844
testForMissingAssertions(Counts & assertions)12845 bool RunContext::testForMissingAssertions(Counts& assertions) {
12846 if (assertions.total() != 0)
12847 return false;
12848 if (!m_config->warnAboutMissingAssertions())
12849 return false;
12850 if (m_trackerContext.currentTracker().hasChildren())
12851 return false;
12852 m_totals.assertions.failed++;
12853 assertions.failed++;
12854 return true;
12855 }
12856
sectionEnded(SectionEndInfo const & endInfo)12857 void RunContext::sectionEnded(SectionEndInfo const & endInfo) {
12858 Counts assertions = m_totals.assertions - endInfo.prevAssertions;
12859 bool missingAssertions = testForMissingAssertions(assertions);
12860
12861 if (!m_activeSections.empty()) {
12862 m_activeSections.back()->close();
12863 m_activeSections.pop_back();
12864 }
12865
12866 m_reporter->sectionEnded(SectionStats(endInfo.sectionInfo, assertions, endInfo.durationInSeconds, missingAssertions));
12867 m_messages.clear();
12868 m_messageScopes.clear();
12869 }
12870
sectionEndedEarly(SectionEndInfo const & endInfo)12871 void RunContext::sectionEndedEarly(SectionEndInfo const & endInfo) {
12872 if (m_unfinishedSections.empty())
12873 m_activeSections.back()->fail();
12874 else
12875 m_activeSections.back()->close();
12876 m_activeSections.pop_back();
12877
12878 m_unfinishedSections.push_back(endInfo);
12879 }
12880
12881 #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
benchmarkPreparing(std::string const & name)12882 void RunContext::benchmarkPreparing(std::string const& name) {
12883 m_reporter->benchmarkPreparing(name);
12884 }
benchmarkStarting(BenchmarkInfo const & info)12885 void RunContext::benchmarkStarting( BenchmarkInfo const& info ) {
12886 m_reporter->benchmarkStarting( info );
12887 }
benchmarkEnded(BenchmarkStats<> const & stats)12888 void RunContext::benchmarkEnded( BenchmarkStats<> const& stats ) {
12889 m_reporter->benchmarkEnded( stats );
12890 }
benchmarkFailed(std::string const & error)12891 void RunContext::benchmarkFailed(std::string const & error) {
12892 m_reporter->benchmarkFailed(error);
12893 }
12894 #endif // CATCH_CONFIG_ENABLE_BENCHMARKING
12895
pushScopedMessage(MessageInfo const & message)12896 void RunContext::pushScopedMessage(MessageInfo const & message) {
12897 m_messages.push_back(message);
12898 }
12899
popScopedMessage(MessageInfo const & message)12900 void RunContext::popScopedMessage(MessageInfo const & message) {
12901 m_messages.erase(std::remove(m_messages.begin(), m_messages.end(), message), m_messages.end());
12902 }
12903
emplaceUnscopedMessage(MessageBuilder const & builder)12904 void RunContext::emplaceUnscopedMessage( MessageBuilder const& builder ) {
12905 m_messageScopes.emplace_back( builder );
12906 }
12907
getCurrentTestName() const12908 std::string RunContext::getCurrentTestName() const {
12909 return m_activeTestCase
12910 ? m_activeTestCase->getTestCaseInfo().name
12911 : std::string();
12912 }
12913
getLastResult() const12914 const AssertionResult * RunContext::getLastResult() const {
12915 return &(*m_lastResult);
12916 }
12917
exceptionEarlyReported()12918 void RunContext::exceptionEarlyReported() {
12919 m_shouldReportUnexpected = false;
12920 }
12921
handleFatalErrorCondition(StringRef message)12922 void RunContext::handleFatalErrorCondition( StringRef message ) {
12923 // First notify reporter that bad things happened
12924 m_reporter->fatalErrorEncountered(message);
12925
12926 // Don't rebuild the result -- the stringification itself can cause more fatal errors
12927 // Instead, fake a result data.
12928 AssertionResultData tempResult( ResultWas::FatalErrorCondition, { false } );
12929 tempResult.message = static_cast<std::string>(message);
12930 AssertionResult result(m_lastAssertionInfo, tempResult);
12931
12932 assertionEnded(result);
12933
12934 handleUnfinishedSections();
12935
12936 // Recreate section for test case (as we will lose the one that was in scope)
12937 auto const& testCaseInfo = m_activeTestCase->getTestCaseInfo();
12938 SectionInfo testCaseSection(testCaseInfo.lineInfo, testCaseInfo.name);
12939
12940 Counts assertions;
12941 assertions.failed = 1;
12942 SectionStats testCaseSectionStats(testCaseSection, assertions, 0, false);
12943 m_reporter->sectionEnded(testCaseSectionStats);
12944
12945 auto const& testInfo = m_activeTestCase->getTestCaseInfo();
12946
12947 Totals deltaTotals;
12948 deltaTotals.testCases.failed = 1;
12949 deltaTotals.assertions.failed = 1;
12950 m_reporter->testCaseEnded(TestCaseStats(testInfo,
12951 deltaTotals,
12952 std::string(),
12953 std::string(),
12954 false));
12955 m_totals.testCases.failed++;
12956 testGroupEnded(std::string(), m_totals, 1, 1);
12957 m_reporter->testRunEnded(TestRunStats(m_runInfo, m_totals, false));
12958 }
12959
lastAssertionPassed()12960 bool RunContext::lastAssertionPassed() {
12961 return m_lastAssertionPassed;
12962 }
12963
assertionPassed()12964 void RunContext::assertionPassed() {
12965 m_lastAssertionPassed = true;
12966 ++m_totals.assertions.passed;
12967 resetAssertionInfo();
12968 m_messageScopes.clear();
12969 }
12970
aborting() const12971 bool RunContext::aborting() const {
12972 return m_totals.assertions.failed >= static_cast<std::size_t>(m_config->abortAfter());
12973 }
12974
runCurrentTest(std::string & redirectedCout,std::string & redirectedCerr)12975 void RunContext::runCurrentTest(std::string & redirectedCout, std::string & redirectedCerr) {
12976 auto const& testCaseInfo = m_activeTestCase->getTestCaseInfo();
12977 SectionInfo testCaseSection(testCaseInfo.lineInfo, testCaseInfo.name);
12978 m_reporter->sectionStarting(testCaseSection);
12979 Counts prevAssertions = m_totals.assertions;
12980 double duration = 0;
12981 m_shouldReportUnexpected = true;
12982 m_lastAssertionInfo = { "TEST_CASE"_sr, testCaseInfo.lineInfo, StringRef(), ResultDisposition::Normal };
12983
12984 seedRng(*m_config);
12985
12986 Timer timer;
12987 CATCH_TRY {
12988 if (m_reporter->getPreferences().shouldRedirectStdOut) {
12989 #if !defined(CATCH_CONFIG_EXPERIMENTAL_REDIRECT)
12990 RedirectedStreams redirectedStreams(redirectedCout, redirectedCerr);
12991
12992 timer.start();
12993 invokeActiveTestCase();
12994 #else
12995 OutputRedirect r(redirectedCout, redirectedCerr);
12996 timer.start();
12997 invokeActiveTestCase();
12998 #endif
12999 } else {
13000 timer.start();
13001 invokeActiveTestCase();
13002 }
13003 duration = timer.getElapsedSeconds();
13004 } CATCH_CATCH_ANON (TestFailureException&) {
13005 // This just means the test was aborted due to failure
13006 } CATCH_CATCH_ALL {
13007 // Under CATCH_CONFIG_FAST_COMPILE, unexpected exceptions under REQUIRE assertions
13008 // are reported without translation at the point of origin.
13009 if( m_shouldReportUnexpected ) {
13010 AssertionReaction dummyReaction;
13011 handleUnexpectedInflightException( m_lastAssertionInfo, translateActiveException(), dummyReaction );
13012 }
13013 }
13014 Counts assertions = m_totals.assertions - prevAssertions;
13015 bool missingAssertions = testForMissingAssertions(assertions);
13016
13017 m_testCaseTracker->close();
13018 handleUnfinishedSections();
13019 m_messages.clear();
13020 m_messageScopes.clear();
13021
13022 SectionStats testCaseSectionStats(testCaseSection, assertions, duration, missingAssertions);
13023 m_reporter->sectionEnded(testCaseSectionStats);
13024 }
13025
invokeActiveTestCase()13026 void RunContext::invokeActiveTestCase() {
13027 FatalConditionHandlerGuard _(&m_fatalConditionhandler);
13028 m_activeTestCase->invoke();
13029 }
13030
handleUnfinishedSections()13031 void RunContext::handleUnfinishedSections() {
13032 // If sections ended prematurely due to an exception we stored their
13033 // infos here so we can tear them down outside the unwind process.
13034 for (auto it = m_unfinishedSections.rbegin(),
13035 itEnd = m_unfinishedSections.rend();
13036 it != itEnd;
13037 ++it)
13038 sectionEnded(*it);
13039 m_unfinishedSections.clear();
13040 }
13041
handleExpr(AssertionInfo const & info,ITransientExpression const & expr,AssertionReaction & reaction)13042 void RunContext::handleExpr(
13043 AssertionInfo const& info,
13044 ITransientExpression const& expr,
13045 AssertionReaction& reaction
13046 ) {
13047 m_reporter->assertionStarting( info );
13048
13049 bool negated = isFalseTest( info.resultDisposition );
13050 bool result = expr.getResult() != negated;
13051
13052 if( result ) {
13053 if (!m_includeSuccessfulResults) {
13054 assertionPassed();
13055 }
13056 else {
13057 reportExpr(info, ResultWas::Ok, &expr, negated);
13058 }
13059 }
13060 else {
13061 reportExpr(info, ResultWas::ExpressionFailed, &expr, negated );
13062 populateReaction( reaction );
13063 }
13064 }
reportExpr(AssertionInfo const & info,ResultWas::OfType resultType,ITransientExpression const * expr,bool negated)13065 void RunContext::reportExpr(
13066 AssertionInfo const &info,
13067 ResultWas::OfType resultType,
13068 ITransientExpression const *expr,
13069 bool negated ) {
13070
13071 m_lastAssertionInfo = info;
13072 AssertionResultData data( resultType, LazyExpression( negated ) );
13073
13074 AssertionResult assertionResult{ info, data };
13075 assertionResult.m_resultData.lazyExpression.m_transientExpression = expr;
13076
13077 assertionEnded( assertionResult );
13078 }
13079
handleMessage(AssertionInfo const & info,ResultWas::OfType resultType,StringRef const & message,AssertionReaction & reaction)13080 void RunContext::handleMessage(
13081 AssertionInfo const& info,
13082 ResultWas::OfType resultType,
13083 StringRef const& message,
13084 AssertionReaction& reaction
13085 ) {
13086 m_reporter->assertionStarting( info );
13087
13088 m_lastAssertionInfo = info;
13089
13090 AssertionResultData data( resultType, LazyExpression( false ) );
13091 data.message = static_cast<std::string>(message);
13092 AssertionResult assertionResult{ m_lastAssertionInfo, data };
13093 assertionEnded( assertionResult );
13094 if( !assertionResult.isOk() )
13095 populateReaction( reaction );
13096 }
handleUnexpectedExceptionNotThrown(AssertionInfo const & info,AssertionReaction & reaction)13097 void RunContext::handleUnexpectedExceptionNotThrown(
13098 AssertionInfo const& info,
13099 AssertionReaction& reaction
13100 ) {
13101 handleNonExpr(info, Catch::ResultWas::DidntThrowException, reaction);
13102 }
13103
handleUnexpectedInflightException(AssertionInfo const & info,std::string const & message,AssertionReaction & reaction)13104 void RunContext::handleUnexpectedInflightException(
13105 AssertionInfo const& info,
13106 std::string const& message,
13107 AssertionReaction& reaction
13108 ) {
13109 m_lastAssertionInfo = info;
13110
13111 AssertionResultData data( ResultWas::ThrewException, LazyExpression( false ) );
13112 data.message = message;
13113 AssertionResult assertionResult{ info, data };
13114 assertionEnded( assertionResult );
13115 populateReaction( reaction );
13116 }
13117
populateReaction(AssertionReaction & reaction)13118 void RunContext::populateReaction( AssertionReaction& reaction ) {
13119 reaction.shouldDebugBreak = m_config->shouldDebugBreak();
13120 reaction.shouldThrow = aborting() || (m_lastAssertionInfo.resultDisposition & ResultDisposition::Normal);
13121 }
13122
handleIncomplete(AssertionInfo const & info)13123 void RunContext::handleIncomplete(
13124 AssertionInfo const& info
13125 ) {
13126 m_lastAssertionInfo = info;
13127
13128 AssertionResultData data( ResultWas::ThrewException, LazyExpression( false ) );
13129 data.message = "Exception translation was disabled by CATCH_CONFIG_FAST_COMPILE";
13130 AssertionResult assertionResult{ info, data };
13131 assertionEnded( assertionResult );
13132 }
handleNonExpr(AssertionInfo const & info,ResultWas::OfType resultType,AssertionReaction & reaction)13133 void RunContext::handleNonExpr(
13134 AssertionInfo const &info,
13135 ResultWas::OfType resultType,
13136 AssertionReaction &reaction
13137 ) {
13138 m_lastAssertionInfo = info;
13139
13140 AssertionResultData data( resultType, LazyExpression( false ) );
13141 AssertionResult assertionResult{ info, data };
13142 assertionEnded( assertionResult );
13143
13144 if( !assertionResult.isOk() )
13145 populateReaction( reaction );
13146 }
13147
getResultCapture()13148 IResultCapture& getResultCapture() {
13149 if (auto* capture = getCurrentContext().getResultCapture())
13150 return *capture;
13151 else
13152 CATCH_INTERNAL_ERROR("No result capture instance");
13153 }
13154
seedRng(IConfig const & config)13155 void seedRng(IConfig const& config) {
13156 if (config.rngSeed() != 0) {
13157 std::srand(config.rngSeed());
13158 rng().seed(config.rngSeed());
13159 }
13160 }
13161
rngSeed()13162 unsigned int rngSeed() {
13163 return getCurrentContext().getConfig()->rngSeed();
13164 }
13165
13166 }
13167 // end catch_run_context.cpp
13168 // start catch_section.cpp
13169
13170 namespace Catch {
13171
Section(SectionInfo const & info)13172 Section::Section( SectionInfo const& info )
13173 : m_info( info ),
13174 m_sectionIncluded( getResultCapture().sectionStarted( m_info, m_assertions ) )
13175 {
13176 m_timer.start();
13177 }
13178
~Section()13179 Section::~Section() {
13180 if( m_sectionIncluded ) {
13181 SectionEndInfo endInfo{ m_info, m_assertions, m_timer.getElapsedSeconds() };
13182 if( uncaught_exceptions() )
13183 getResultCapture().sectionEndedEarly( endInfo );
13184 else
13185 getResultCapture().sectionEnded( endInfo );
13186 }
13187 }
13188
13189 // This indicates whether the section should be executed or not
operator bool() const13190 Section::operator bool() const {
13191 return m_sectionIncluded;
13192 }
13193
13194 } // end namespace Catch
13195 // end catch_section.cpp
13196 // start catch_section_info.cpp
13197
13198 namespace Catch {
13199
SectionInfo(SourceLineInfo const & _lineInfo,std::string const & _name)13200 SectionInfo::SectionInfo
13201 ( SourceLineInfo const& _lineInfo,
13202 std::string const& _name )
13203 : name( _name ),
13204 lineInfo( _lineInfo )
13205 {}
13206
13207 } // end namespace Catch
13208 // end catch_section_info.cpp
13209 // start catch_session.cpp
13210
13211 // start catch_session.h
13212
13213 #include <memory>
13214
13215 namespace Catch {
13216
13217 class Session : NonCopyable {
13218 public:
13219
13220 Session();
13221 ~Session() override;
13222
13223 void showHelp() const;
13224 void libIdentify();
13225
13226 int applyCommandLine( int argc, char const * const * argv );
13227 #if defined(CATCH_CONFIG_WCHAR) && defined(_WIN32) && defined(UNICODE)
13228 int applyCommandLine( int argc, wchar_t const * const * argv );
13229 #endif
13230
13231 void useConfigData( ConfigData const& configData );
13232
13233 template<typename CharT>
run(int argc,CharT const * const argv[])13234 int run(int argc, CharT const * const argv[]) {
13235 if (m_startupExceptions)
13236 return 1;
13237 int returnCode = applyCommandLine(argc, argv);
13238 if (returnCode == 0)
13239 returnCode = run();
13240 return returnCode;
13241 }
13242
13243 int run();
13244
13245 clara::Parser const& cli() const;
13246 void cli( clara::Parser const& newParser );
13247 ConfigData& configData();
13248 Config& config();
13249 private:
13250 int runInternal();
13251
13252 clara::Parser m_cli;
13253 ConfigData m_configData;
13254 std::shared_ptr<Config> m_config;
13255 bool m_startupExceptions = false;
13256 };
13257
13258 } // end namespace Catch
13259
13260 // end catch_session.h
13261 // start catch_version.h
13262
13263 #include <iosfwd>
13264
13265 namespace Catch {
13266
13267 // Versioning information
13268 struct Version {
13269 Version( Version const& ) = delete;
13270 Version& operator=( Version const& ) = delete;
13271 Version( unsigned int _majorVersion,
13272 unsigned int _minorVersion,
13273 unsigned int _patchNumber,
13274 char const * const _branchName,
13275 unsigned int _buildNumber );
13276
13277 unsigned int const majorVersion;
13278 unsigned int const minorVersion;
13279 unsigned int const patchNumber;
13280
13281 // buildNumber is only used if branchName is not null
13282 char const * const branchName;
13283 unsigned int const buildNumber;
13284
13285 friend std::ostream& operator << ( std::ostream& os, Version const& version );
13286 };
13287
13288 Version const& libraryVersion();
13289 }
13290
13291 // end catch_version.h
13292 #include <cstdlib>
13293 #include <iomanip>
13294 #include <set>
13295 #include <iterator>
13296
13297 namespace Catch {
13298
13299 namespace {
13300 const int MaxExitCode = 255;
13301
createReporter(std::string const & reporterName,IConfigPtr const & config)13302 IStreamingReporterPtr createReporter(std::string const& reporterName, IConfigPtr const& config) {
13303 auto reporter = Catch::getRegistryHub().getReporterRegistry().create(reporterName, config);
13304 CATCH_ENFORCE(reporter, "No reporter registered with name: '" << reporterName << "'");
13305
13306 return reporter;
13307 }
13308
makeReporter(std::shared_ptr<Config> const & config)13309 IStreamingReporterPtr makeReporter(std::shared_ptr<Config> const& config) {
13310 if (Catch::getRegistryHub().getReporterRegistry().getListeners().empty()) {
13311 return createReporter(config->getReporterName(), config);
13312 }
13313
13314 // On older platforms, returning std::unique_ptr<ListeningReporter>
13315 // when the return type is std::unique_ptr<IStreamingReporter>
13316 // doesn't compile without a std::move call. However, this causes
13317 // a warning on newer platforms. Thus, we have to work around
13318 // it a bit and downcast the pointer manually.
13319 auto ret = std::unique_ptr<IStreamingReporter>(new ListeningReporter);
13320 auto& multi = static_cast<ListeningReporter&>(*ret);
13321 auto const& listeners = Catch::getRegistryHub().getReporterRegistry().getListeners();
13322 for (auto const& listener : listeners) {
13323 multi.addListener(listener->create(Catch::ReporterConfig(config)));
13324 }
13325 multi.addReporter(createReporter(config->getReporterName(), config));
13326 return ret;
13327 }
13328
13329 class TestGroup {
13330 public:
TestGroup(std::shared_ptr<Config> const & config)13331 explicit TestGroup(std::shared_ptr<Config> const& config)
13332 : m_config{config}
13333 , m_context{config, makeReporter(config)}
13334 {
13335 auto const& allTestCases = getAllTestCasesSorted(*m_config);
13336 m_matches = m_config->testSpec().matchesByFilter(allTestCases, *m_config);
13337 auto const& invalidArgs = m_config->testSpec().getInvalidArgs();
13338
13339 if (m_matches.empty() && invalidArgs.empty()) {
13340 for (auto const& test : allTestCases)
13341 if (!test.isHidden())
13342 m_tests.emplace(&test);
13343 } else {
13344 for (auto const& match : m_matches)
13345 m_tests.insert(match.tests.begin(), match.tests.end());
13346 }
13347 }
13348
execute()13349 Totals execute() {
13350 auto const& invalidArgs = m_config->testSpec().getInvalidArgs();
13351 Totals totals;
13352 m_context.testGroupStarting(m_config->name(), 1, 1);
13353 for (auto const& testCase : m_tests) {
13354 if (!m_context.aborting())
13355 totals += m_context.runTest(*testCase);
13356 else
13357 m_context.reporter().skipTest(*testCase);
13358 }
13359
13360 for (auto const& match : m_matches) {
13361 if (match.tests.empty()) {
13362 m_context.reporter().noMatchingTestCases(match.name);
13363 totals.error = -1;
13364 }
13365 }
13366
13367 if (!invalidArgs.empty()) {
13368 for (auto const& invalidArg: invalidArgs)
13369 m_context.reporter().reportInvalidArguments(invalidArg);
13370 }
13371
13372 m_context.testGroupEnded(m_config->name(), totals, 1, 1);
13373 return totals;
13374 }
13375
13376 private:
13377 using Tests = std::set<TestCase const*>;
13378
13379 std::shared_ptr<Config> m_config;
13380 RunContext m_context;
13381 Tests m_tests;
13382 TestSpec::Matches m_matches;
13383 };
13384
applyFilenamesAsTags(Catch::IConfig const & config)13385 void applyFilenamesAsTags(Catch::IConfig const& config) {
13386 auto& tests = const_cast<std::vector<TestCase>&>(getAllTestCasesSorted(config));
13387 for (auto& testCase : tests) {
13388 auto tags = testCase.tags;
13389
13390 std::string filename = testCase.lineInfo.file;
13391 auto lastSlash = filename.find_last_of("\\/");
13392 if (lastSlash != std::string::npos) {
13393 filename.erase(0, lastSlash);
13394 filename[0] = '#';
13395 }
13396 else
13397 {
13398 filename.insert(0, "#");
13399 }
13400
13401 auto lastDot = filename.find_last_of('.');
13402 if (lastDot != std::string::npos) {
13403 filename.erase(lastDot);
13404 }
13405
13406 tags.push_back(std::move(filename));
13407 setTags(testCase, tags);
13408 }
13409 }
13410
13411 } // anon namespace
13412
Session()13413 Session::Session() {
13414 static bool alreadyInstantiated = false;
13415 if( alreadyInstantiated ) {
13416 CATCH_TRY { CATCH_INTERNAL_ERROR( "Only one instance of Catch::Session can ever be used" ); }
13417 CATCH_CATCH_ALL { getMutableRegistryHub().registerStartupException(); }
13418 }
13419
13420 // There cannot be exceptions at startup in no-exception mode.
13421 #if !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
13422 const auto& exceptions = getRegistryHub().getStartupExceptionRegistry().getExceptions();
13423 if ( !exceptions.empty() ) {
13424 config();
13425 getCurrentMutableContext().setConfig(m_config);
13426
13427 m_startupExceptions = true;
13428 Colour colourGuard( Colour::Red );
13429 Catch::cerr() << "Errors occurred during startup!" << '\n';
13430 // iterate over all exceptions and notify user
13431 for ( const auto& ex_ptr : exceptions ) {
13432 try {
13433 std::rethrow_exception(ex_ptr);
13434 } catch ( std::exception const& ex ) {
13435 Catch::cerr() << Column( ex.what() ).indent(2) << '\n';
13436 }
13437 }
13438 }
13439 #endif
13440
13441 alreadyInstantiated = true;
13442 m_cli = makeCommandLineParser( m_configData );
13443 }
~Session()13444 Session::~Session() {
13445 Catch::cleanUp();
13446 }
13447
showHelp() const13448 void Session::showHelp() const {
13449 Catch::cout()
13450 << "\nCatch v" << libraryVersion() << "\n"
13451 << m_cli << std::endl
13452 << "For more detailed usage please see the project docs\n" << std::endl;
13453 }
libIdentify()13454 void Session::libIdentify() {
13455 Catch::cout()
13456 << std::left << std::setw(16) << "description: " << "A Catch2 test executable\n"
13457 << std::left << std::setw(16) << "category: " << "testframework\n"
13458 << std::left << std::setw(16) << "framework: " << "Catch Test\n"
13459 << std::left << std::setw(16) << "version: " << libraryVersion() << std::endl;
13460 }
13461
applyCommandLine(int argc,char const * const * argv)13462 int Session::applyCommandLine( int argc, char const * const * argv ) {
13463 if( m_startupExceptions )
13464 return 1;
13465
13466 auto result = m_cli.parse( clara::Args( argc, argv ) );
13467 if( !result ) {
13468 config();
13469 getCurrentMutableContext().setConfig(m_config);
13470 Catch::cerr()
13471 << Colour( Colour::Red )
13472 << "\nError(s) in input:\n"
13473 << Column( result.errorMessage() ).indent( 2 )
13474 << "\n\n";
13475 Catch::cerr() << "Run with -? for usage\n" << std::endl;
13476 return MaxExitCode;
13477 }
13478
13479 if( m_configData.showHelp )
13480 showHelp();
13481 if( m_configData.libIdentify )
13482 libIdentify();
13483 m_config.reset();
13484 return 0;
13485 }
13486
13487 #if defined(CATCH_CONFIG_WCHAR) && defined(_WIN32) && defined(UNICODE)
applyCommandLine(int argc,wchar_t const * const * argv)13488 int Session::applyCommandLine( int argc, wchar_t const * const * argv ) {
13489
13490 char **utf8Argv = new char *[ argc ];
13491
13492 for ( int i = 0; i < argc; ++i ) {
13493 int bufSize = WideCharToMultiByte( CP_UTF8, 0, argv[i], -1, nullptr, 0, nullptr, nullptr );
13494
13495 utf8Argv[ i ] = new char[ bufSize ];
13496
13497 WideCharToMultiByte( CP_UTF8, 0, argv[i], -1, utf8Argv[i], bufSize, nullptr, nullptr );
13498 }
13499
13500 int returnCode = applyCommandLine( argc, utf8Argv );
13501
13502 for ( int i = 0; i < argc; ++i )
13503 delete [] utf8Argv[ i ];
13504
13505 delete [] utf8Argv;
13506
13507 return returnCode;
13508 }
13509 #endif
13510
useConfigData(ConfigData const & configData)13511 void Session::useConfigData( ConfigData const& configData ) {
13512 m_configData = configData;
13513 m_config.reset();
13514 }
13515
run()13516 int Session::run() {
13517 if( ( m_configData.waitForKeypress & WaitForKeypress::BeforeStart ) != 0 ) {
13518 Catch::cout() << "...waiting for enter/ return before starting" << std::endl;
13519 static_cast<void>(std::getchar());
13520 }
13521 int exitCode = runInternal();
13522 if( ( m_configData.waitForKeypress & WaitForKeypress::BeforeExit ) != 0 ) {
13523 Catch::cout() << "...waiting for enter/ return before exiting, with code: " << exitCode << std::endl;
13524 static_cast<void>(std::getchar());
13525 }
13526 return exitCode;
13527 }
13528
cli() const13529 clara::Parser const& Session::cli() const {
13530 return m_cli;
13531 }
cli(clara::Parser const & newParser)13532 void Session::cli( clara::Parser const& newParser ) {
13533 m_cli = newParser;
13534 }
configData()13535 ConfigData& Session::configData() {
13536 return m_configData;
13537 }
config()13538 Config& Session::config() {
13539 if( !m_config )
13540 m_config = std::make_shared<Config>( m_configData );
13541 return *m_config;
13542 }
13543
runInternal()13544 int Session::runInternal() {
13545 if( m_startupExceptions )
13546 return 1;
13547
13548 if (m_configData.showHelp || m_configData.libIdentify) {
13549 return 0;
13550 }
13551
13552 CATCH_TRY {
13553 config(); // Force config to be constructed
13554
13555 seedRng( *m_config );
13556
13557 if( m_configData.filenamesAsTags )
13558 applyFilenamesAsTags( *m_config );
13559
13560 // Handle list request
13561 if( Option<std::size_t> listed = list( m_config ) )
13562 return static_cast<int>( *listed );
13563
13564 TestGroup tests { m_config };
13565 auto const totals = tests.execute();
13566
13567 if( m_config->warnAboutNoTests() && totals.error == -1 )
13568 return 2;
13569
13570 // Note that on unices only the lower 8 bits are usually used, clamping
13571 // the return value to 255 prevents false negative when some multiple
13572 // of 256 tests has failed
13573 return (std::min) (MaxExitCode, (std::max) (totals.error, static_cast<int>(totals.assertions.failed)));
13574 }
13575 #if !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
13576 catch( std::exception& ex ) {
13577 Catch::cerr() << ex.what() << std::endl;
13578 return MaxExitCode;
13579 }
13580 #endif
13581 }
13582
13583 } // end namespace Catch
13584 // end catch_session.cpp
13585 // start catch_singletons.cpp
13586
13587 #include <vector>
13588
13589 namespace Catch {
13590
13591 namespace {
getSingletons()13592 static auto getSingletons() -> std::vector<ISingleton*>*& {
13593 static std::vector<ISingleton*>* g_singletons = nullptr;
13594 if( !g_singletons )
13595 g_singletons = new std::vector<ISingleton*>();
13596 return g_singletons;
13597 }
13598 }
13599
~ISingleton()13600 ISingleton::~ISingleton() {}
13601
addSingleton(ISingleton * singleton)13602 void addSingleton(ISingleton* singleton ) {
13603 getSingletons()->push_back( singleton );
13604 }
cleanupSingletons()13605 void cleanupSingletons() {
13606 auto& singletons = getSingletons();
13607 for( auto singleton : *singletons )
13608 delete singleton;
13609 delete singletons;
13610 singletons = nullptr;
13611 }
13612
13613 } // namespace Catch
13614 // end catch_singletons.cpp
13615 // start catch_startup_exception_registry.cpp
13616
13617 #if !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
13618 namespace Catch {
add(std::exception_ptr const & exception)13619 void StartupExceptionRegistry::add( std::exception_ptr const& exception ) noexcept {
13620 CATCH_TRY {
13621 m_exceptions.push_back(exception);
13622 } CATCH_CATCH_ALL {
13623 // If we run out of memory during start-up there's really not a lot more we can do about it
13624 std::terminate();
13625 }
13626 }
13627
getExceptions() const13628 std::vector<std::exception_ptr> const& StartupExceptionRegistry::getExceptions() const noexcept {
13629 return m_exceptions;
13630 }
13631
13632 } // end namespace Catch
13633 #endif
13634 // end catch_startup_exception_registry.cpp
13635 // start catch_stream.cpp
13636
13637 #include <cstdio>
13638 #include <iostream>
13639 #include <fstream>
13640 #include <sstream>
13641 #include <vector>
13642 #include <memory>
13643
13644 namespace Catch {
13645
13646 Catch::IStream::~IStream() = default;
13647
13648 namespace Detail { namespace {
13649 template<typename WriterF, std::size_t bufferSize=256>
13650 class StreamBufImpl : public std::streambuf {
13651 char data[bufferSize];
13652 WriterF m_writer;
13653
13654 public:
StreamBufImpl()13655 StreamBufImpl() {
13656 setp( data, data + sizeof(data) );
13657 }
13658
~StreamBufImpl()13659 ~StreamBufImpl() noexcept {
13660 StreamBufImpl::sync();
13661 }
13662
13663 private:
overflow(int c)13664 int overflow( int c ) override {
13665 sync();
13666
13667 if( c != EOF ) {
13668 if( pbase() == epptr() )
13669 m_writer( std::string( 1, static_cast<char>( c ) ) );
13670 else
13671 sputc( static_cast<char>( c ) );
13672 }
13673 return 0;
13674 }
13675
sync()13676 int sync() override {
13677 if( pbase() != pptr() ) {
13678 m_writer( std::string( pbase(), static_cast<std::string::size_type>( pptr() - pbase() ) ) );
13679 setp( pbase(), epptr() );
13680 }
13681 return 0;
13682 }
13683 };
13684
13685 ///////////////////////////////////////////////////////////////////////////
13686
13687 struct OutputDebugWriter {
13688
operator ()Catch::Detail::__anon21412a523b11::OutputDebugWriter13689 void operator()( std::string const&str ) {
13690 writeToDebugConsole( str );
13691 }
13692 };
13693
13694 ///////////////////////////////////////////////////////////////////////////
13695
13696 class FileStream : public IStream {
13697 mutable std::ofstream m_ofs;
13698 public:
FileStream(StringRef filename)13699 FileStream( StringRef filename ) {
13700 m_ofs.open( filename.c_str() );
13701 CATCH_ENFORCE( !m_ofs.fail(), "Unable to open file: '" << filename << "'" );
13702 }
13703 ~FileStream() override = default;
13704 public: // IStream
stream() const13705 std::ostream& stream() const override {
13706 return m_ofs;
13707 }
13708 };
13709
13710 ///////////////////////////////////////////////////////////////////////////
13711
13712 class CoutStream : public IStream {
13713 mutable std::ostream m_os;
13714 public:
13715 // Store the streambuf from cout up-front because
13716 // cout may get redirected when running tests
CoutStream()13717 CoutStream() : m_os( Catch::cout().rdbuf() ) {}
13718 ~CoutStream() override = default;
13719
13720 public: // IStream
stream() const13721 std::ostream& stream() const override { return m_os; }
13722 };
13723
13724 ///////////////////////////////////////////////////////////////////////////
13725
13726 class DebugOutStream : public IStream {
13727 std::unique_ptr<StreamBufImpl<OutputDebugWriter>> m_streamBuf;
13728 mutable std::ostream m_os;
13729 public:
DebugOutStream()13730 DebugOutStream()
13731 : m_streamBuf( new StreamBufImpl<OutputDebugWriter>() ),
13732 m_os( m_streamBuf.get() )
13733 {}
13734
13735 ~DebugOutStream() override = default;
13736
13737 public: // IStream
stream() const13738 std::ostream& stream() const override { return m_os; }
13739 };
13740
13741 }} // namespace anon::detail
13742
13743 ///////////////////////////////////////////////////////////////////////////
13744
makeStream(StringRef const & filename)13745 auto makeStream( StringRef const &filename ) -> IStream const* {
13746 if( filename.empty() )
13747 return new Detail::CoutStream();
13748 else if( filename[0] == '%' ) {
13749 if( filename == "%debug" )
13750 return new Detail::DebugOutStream();
13751 else
13752 CATCH_ERROR( "Unrecognised stream: '" << filename << "'" );
13753 }
13754 else
13755 return new Detail::FileStream( filename );
13756 }
13757
13758 // This class encapsulates the idea of a pool of ostringstreams that can be reused.
13759 struct StringStreams {
13760 std::vector<std::unique_ptr<std::ostringstream>> m_streams;
13761 std::vector<std::size_t> m_unused;
13762 std::ostringstream m_referenceStream; // Used for copy state/ flags from
13763
addCatch::StringStreams13764 auto add() -> std::size_t {
13765 if( m_unused.empty() ) {
13766 m_streams.push_back( std::unique_ptr<std::ostringstream>( new std::ostringstream ) );
13767 return m_streams.size()-1;
13768 }
13769 else {
13770 auto index = m_unused.back();
13771 m_unused.pop_back();
13772 return index;
13773 }
13774 }
13775
releaseCatch::StringStreams13776 void release( std::size_t index ) {
13777 m_streams[index]->copyfmt( m_referenceStream ); // Restore initial flags and other state
13778 m_unused.push_back(index);
13779 }
13780 };
13781
ReusableStringStream()13782 ReusableStringStream::ReusableStringStream()
13783 : m_index( Singleton<StringStreams>::getMutable().add() ),
13784 m_oss( Singleton<StringStreams>::getMutable().m_streams[m_index].get() )
13785 {}
13786
~ReusableStringStream()13787 ReusableStringStream::~ReusableStringStream() {
13788 static_cast<std::ostringstream*>( m_oss )->str("");
13789 m_oss->clear();
13790 Singleton<StringStreams>::getMutable().release( m_index );
13791 }
13792
str() const13793 auto ReusableStringStream::str() const -> std::string {
13794 return static_cast<std::ostringstream*>( m_oss )->str();
13795 }
13796
13797 ///////////////////////////////////////////////////////////////////////////
13798
13799 #ifndef CATCH_CONFIG_NOSTDOUT // If you #define this you must implement these functions
cout()13800 std::ostream& cout() { return std::cout; }
cerr()13801 std::ostream& cerr() { return std::cerr; }
clog()13802 std::ostream& clog() { return std::clog; }
13803 #endif
13804 }
13805 // end catch_stream.cpp
13806 // start catch_string_manip.cpp
13807
13808 #include <algorithm>
13809 #include <ostream>
13810 #include <cstring>
13811 #include <cctype>
13812 #include <vector>
13813
13814 namespace Catch {
13815
13816 namespace {
toLowerCh(char c)13817 char toLowerCh(char c) {
13818 return static_cast<char>( std::tolower( static_cast<unsigned char>(c) ) );
13819 }
13820 }
13821
startsWith(std::string const & s,std::string const & prefix)13822 bool startsWith( std::string const& s, std::string const& prefix ) {
13823 return s.size() >= prefix.size() && std::equal(prefix.begin(), prefix.end(), s.begin());
13824 }
startsWith(std::string const & s,char prefix)13825 bool startsWith( std::string const& s, char prefix ) {
13826 return !s.empty() && s[0] == prefix;
13827 }
endsWith(std::string const & s,std::string const & suffix)13828 bool endsWith( std::string const& s, std::string const& suffix ) {
13829 return s.size() >= suffix.size() && std::equal(suffix.rbegin(), suffix.rend(), s.rbegin());
13830 }
endsWith(std::string const & s,char suffix)13831 bool endsWith( std::string const& s, char suffix ) {
13832 return !s.empty() && s[s.size()-1] == suffix;
13833 }
contains(std::string const & s,std::string const & infix)13834 bool contains( std::string const& s, std::string const& infix ) {
13835 return s.find( infix ) != std::string::npos;
13836 }
toLowerInPlace(std::string & s)13837 void toLowerInPlace( std::string& s ) {
13838 std::transform( s.begin(), s.end(), s.begin(), toLowerCh );
13839 }
toLower(std::string const & s)13840 std::string toLower( std::string const& s ) {
13841 std::string lc = s;
13842 toLowerInPlace( lc );
13843 return lc;
13844 }
trim(std::string const & str)13845 std::string trim( std::string const& str ) {
13846 static char const* whitespaceChars = "\n\r\t ";
13847 std::string::size_type start = str.find_first_not_of( whitespaceChars );
13848 std::string::size_type end = str.find_last_not_of( whitespaceChars );
13849
13850 return start != std::string::npos ? str.substr( start, 1+end-start ) : std::string();
13851 }
13852
trim(StringRef ref)13853 StringRef trim(StringRef ref) {
13854 const auto is_ws = [](char c) {
13855 return c == ' ' || c == '\t' || c == '\n' || c == '\r';
13856 };
13857 size_t real_begin = 0;
13858 while (real_begin < ref.size() && is_ws(ref[real_begin])) { ++real_begin; }
13859 size_t real_end = ref.size();
13860 while (real_end > real_begin && is_ws(ref[real_end - 1])) { --real_end; }
13861
13862 return ref.substr(real_begin, real_end - real_begin);
13863 }
13864
replaceInPlace(std::string & str,std::string const & replaceThis,std::string const & withThis)13865 bool replaceInPlace( std::string& str, std::string const& replaceThis, std::string const& withThis ) {
13866 bool replaced = false;
13867 std::size_t i = str.find( replaceThis );
13868 while( i != std::string::npos ) {
13869 replaced = true;
13870 str = str.substr( 0, i ) + withThis + str.substr( i+replaceThis.size() );
13871 if( i < str.size()-withThis.size() )
13872 i = str.find( replaceThis, i+withThis.size() );
13873 else
13874 i = std::string::npos;
13875 }
13876 return replaced;
13877 }
13878
splitStringRef(StringRef str,char delimiter)13879 std::vector<StringRef> splitStringRef( StringRef str, char delimiter ) {
13880 std::vector<StringRef> subStrings;
13881 std::size_t start = 0;
13882 for(std::size_t pos = 0; pos < str.size(); ++pos ) {
13883 if( str[pos] == delimiter ) {
13884 if( pos - start > 1 )
13885 subStrings.push_back( str.substr( start, pos-start ) );
13886 start = pos+1;
13887 }
13888 }
13889 if( start < str.size() )
13890 subStrings.push_back( str.substr( start, str.size()-start ) );
13891 return subStrings;
13892 }
13893
pluralise(std::size_t count,std::string const & label)13894 pluralise::pluralise( std::size_t count, std::string const& label )
13895 : m_count( count ),
13896 m_label( label )
13897 {}
13898
operator <<(std::ostream & os,pluralise const & pluraliser)13899 std::ostream& operator << ( std::ostream& os, pluralise const& pluraliser ) {
13900 os << pluraliser.m_count << ' ' << pluraliser.m_label;
13901 if( pluraliser.m_count != 1 )
13902 os << 's';
13903 return os;
13904 }
13905
13906 }
13907 // end catch_string_manip.cpp
13908 // start catch_stringref.cpp
13909
13910 #include <algorithm>
13911 #include <ostream>
13912 #include <cstring>
13913 #include <cstdint>
13914
13915 namespace Catch {
StringRef(char const * rawChars)13916 StringRef::StringRef( char const* rawChars ) noexcept
13917 : StringRef( rawChars, static_cast<StringRef::size_type>(std::strlen(rawChars) ) )
13918 {}
13919
c_str() const13920 auto StringRef::c_str() const -> char const* {
13921 CATCH_ENFORCE(isNullTerminated(), "Called StringRef::c_str() on a non-null-terminated instance");
13922 return m_start;
13923 }
data() const13924 auto StringRef::data() const noexcept -> char const* {
13925 return m_start;
13926 }
13927
substr(size_type start,size_type size) const13928 auto StringRef::substr( size_type start, size_type size ) const noexcept -> StringRef {
13929 if (start < m_size) {
13930 return StringRef(m_start + start, (std::min)(m_size - start, size));
13931 } else {
13932 return StringRef();
13933 }
13934 }
operator ==(StringRef const & other) const13935 auto StringRef::operator == ( StringRef const& other ) const noexcept -> bool {
13936 return m_size == other.m_size
13937 && (std::memcmp( m_start, other.m_start, m_size ) == 0);
13938 }
13939
operator <<(std::ostream & os,StringRef const & str)13940 auto operator << ( std::ostream& os, StringRef const& str ) -> std::ostream& {
13941 return os.write(str.data(), str.size());
13942 }
13943
operator +=(std::string & lhs,StringRef const & rhs)13944 auto operator+=( std::string& lhs, StringRef const& rhs ) -> std::string& {
13945 lhs.append(rhs.data(), rhs.size());
13946 return lhs;
13947 }
13948
13949 } // namespace Catch
13950 // end catch_stringref.cpp
13951 // start catch_tag_alias.cpp
13952
13953 namespace Catch {
TagAlias(std::string const & _tag,SourceLineInfo _lineInfo)13954 TagAlias::TagAlias(std::string const & _tag, SourceLineInfo _lineInfo): tag(_tag), lineInfo(_lineInfo) {}
13955 }
13956 // end catch_tag_alias.cpp
13957 // start catch_tag_alias_autoregistrar.cpp
13958
13959 namespace Catch {
13960
RegistrarForTagAliases(char const * alias,char const * tag,SourceLineInfo const & lineInfo)13961 RegistrarForTagAliases::RegistrarForTagAliases(char const* alias, char const* tag, SourceLineInfo const& lineInfo) {
13962 CATCH_TRY {
13963 getMutableRegistryHub().registerTagAlias(alias, tag, lineInfo);
13964 } CATCH_CATCH_ALL {
13965 // Do not throw when constructing global objects, instead register the exception to be processed later
13966 getMutableRegistryHub().registerStartupException();
13967 }
13968 }
13969
13970 }
13971 // end catch_tag_alias_autoregistrar.cpp
13972 // start catch_tag_alias_registry.cpp
13973
13974 #include <sstream>
13975
13976 namespace Catch {
13977
~TagAliasRegistry()13978 TagAliasRegistry::~TagAliasRegistry() {}
13979
find(std::string const & alias) const13980 TagAlias const* TagAliasRegistry::find( std::string const& alias ) const {
13981 auto it = m_registry.find( alias );
13982 if( it != m_registry.end() )
13983 return &(it->second);
13984 else
13985 return nullptr;
13986 }
13987
expandAliases(std::string const & unexpandedTestSpec) const13988 std::string TagAliasRegistry::expandAliases( std::string const& unexpandedTestSpec ) const {
13989 std::string expandedTestSpec = unexpandedTestSpec;
13990 for( auto const& registryKvp : m_registry ) {
13991 std::size_t pos = expandedTestSpec.find( registryKvp.first );
13992 if( pos != std::string::npos ) {
13993 expandedTestSpec = expandedTestSpec.substr( 0, pos ) +
13994 registryKvp.second.tag +
13995 expandedTestSpec.substr( pos + registryKvp.first.size() );
13996 }
13997 }
13998 return expandedTestSpec;
13999 }
14000
add(std::string const & alias,std::string const & tag,SourceLineInfo const & lineInfo)14001 void TagAliasRegistry::add( std::string const& alias, std::string const& tag, SourceLineInfo const& lineInfo ) {
14002 CATCH_ENFORCE( startsWith(alias, "[@") && endsWith(alias, ']'),
14003 "error: tag alias, '" << alias << "' is not of the form [@alias name].\n" << lineInfo );
14004
14005 CATCH_ENFORCE( m_registry.insert(std::make_pair(alias, TagAlias(tag, lineInfo))).second,
14006 "error: tag alias, '" << alias << "' already registered.\n"
14007 << "\tFirst seen at: " << find(alias)->lineInfo << "\n"
14008 << "\tRedefined at: " << lineInfo );
14009 }
14010
~ITagAliasRegistry()14011 ITagAliasRegistry::~ITagAliasRegistry() {}
14012
get()14013 ITagAliasRegistry const& ITagAliasRegistry::get() {
14014 return getRegistryHub().getTagAliasRegistry();
14015 }
14016
14017 } // end namespace Catch
14018 // end catch_tag_alias_registry.cpp
14019 // start catch_test_case_info.cpp
14020
14021 #include <cctype>
14022 #include <exception>
14023 #include <algorithm>
14024 #include <sstream>
14025
14026 namespace Catch {
14027
14028 namespace {
parseSpecialTag(std::string const & tag)14029 TestCaseInfo::SpecialProperties parseSpecialTag( std::string const& tag ) {
14030 if( startsWith( tag, '.' ) ||
14031 tag == "!hide" )
14032 return TestCaseInfo::IsHidden;
14033 else if( tag == "!throws" )
14034 return TestCaseInfo::Throws;
14035 else if( tag == "!shouldfail" )
14036 return TestCaseInfo::ShouldFail;
14037 else if( tag == "!mayfail" )
14038 return TestCaseInfo::MayFail;
14039 else if( tag == "!nonportable" )
14040 return TestCaseInfo::NonPortable;
14041 else if( tag == "!benchmark" )
14042 return static_cast<TestCaseInfo::SpecialProperties>( TestCaseInfo::Benchmark | TestCaseInfo::IsHidden );
14043 else
14044 return TestCaseInfo::None;
14045 }
isReservedTag(std::string const & tag)14046 bool isReservedTag( std::string const& tag ) {
14047 return parseSpecialTag( tag ) == TestCaseInfo::None && tag.size() > 0 && !std::isalnum( static_cast<unsigned char>(tag[0]) );
14048 }
enforceNotReservedTag(std::string const & tag,SourceLineInfo const & _lineInfo)14049 void enforceNotReservedTag( std::string const& tag, SourceLineInfo const& _lineInfo ) {
14050 CATCH_ENFORCE( !isReservedTag(tag),
14051 "Tag name: [" << tag << "] is not allowed.\n"
14052 << "Tag names starting with non alphanumeric characters are reserved\n"
14053 << _lineInfo );
14054 }
14055 }
14056
makeTestCase(ITestInvoker * _testCase,std::string const & _className,NameAndTags const & nameAndTags,SourceLineInfo const & _lineInfo)14057 TestCase makeTestCase( ITestInvoker* _testCase,
14058 std::string const& _className,
14059 NameAndTags const& nameAndTags,
14060 SourceLineInfo const& _lineInfo )
14061 {
14062 bool isHidden = false;
14063
14064 // Parse out tags
14065 std::vector<std::string> tags;
14066 std::string desc, tag;
14067 bool inTag = false;
14068 for (char c : nameAndTags.tags) {
14069 if( !inTag ) {
14070 if( c == '[' )
14071 inTag = true;
14072 else
14073 desc += c;
14074 }
14075 else {
14076 if( c == ']' ) {
14077 TestCaseInfo::SpecialProperties prop = parseSpecialTag( tag );
14078 if( ( prop & TestCaseInfo::IsHidden ) != 0 )
14079 isHidden = true;
14080 else if( prop == TestCaseInfo::None )
14081 enforceNotReservedTag( tag, _lineInfo );
14082
14083 // Merged hide tags like `[.approvals]` should be added as
14084 // `[.][approvals]`. The `[.]` is added at later point, so
14085 // we only strip the prefix
14086 if (startsWith(tag, '.') && tag.size() > 1) {
14087 tag.erase(0, 1);
14088 }
14089 tags.push_back( tag );
14090 tag.clear();
14091 inTag = false;
14092 }
14093 else
14094 tag += c;
14095 }
14096 }
14097 if( isHidden ) {
14098 // Add all "hidden" tags to make them behave identically
14099 tags.insert( tags.end(), { ".", "!hide" } );
14100 }
14101
14102 TestCaseInfo info( static_cast<std::string>(nameAndTags.name), _className, desc, tags, _lineInfo );
14103 return TestCase( _testCase, std::move(info) );
14104 }
14105
setTags(TestCaseInfo & testCaseInfo,std::vector<std::string> tags)14106 void setTags( TestCaseInfo& testCaseInfo, std::vector<std::string> tags ) {
14107 std::sort(begin(tags), end(tags));
14108 tags.erase(std::unique(begin(tags), end(tags)), end(tags));
14109 testCaseInfo.lcaseTags.clear();
14110
14111 for( auto const& tag : tags ) {
14112 std::string lcaseTag = toLower( tag );
14113 testCaseInfo.properties = static_cast<TestCaseInfo::SpecialProperties>( testCaseInfo.properties | parseSpecialTag( lcaseTag ) );
14114 testCaseInfo.lcaseTags.push_back( lcaseTag );
14115 }
14116 testCaseInfo.tags = std::move(tags);
14117 }
14118
TestCaseInfo(std::string const & _name,std::string const & _className,std::string const & _description,std::vector<std::string> const & _tags,SourceLineInfo const & _lineInfo)14119 TestCaseInfo::TestCaseInfo( std::string const& _name,
14120 std::string const& _className,
14121 std::string const& _description,
14122 std::vector<std::string> const& _tags,
14123 SourceLineInfo const& _lineInfo )
14124 : name( _name ),
14125 className( _className ),
14126 description( _description ),
14127 lineInfo( _lineInfo ),
14128 properties( None )
14129 {
14130 setTags( *this, _tags );
14131 }
14132
isHidden() const14133 bool TestCaseInfo::isHidden() const {
14134 return ( properties & IsHidden ) != 0;
14135 }
throws() const14136 bool TestCaseInfo::throws() const {
14137 return ( properties & Throws ) != 0;
14138 }
okToFail() const14139 bool TestCaseInfo::okToFail() const {
14140 return ( properties & (ShouldFail | MayFail ) ) != 0;
14141 }
expectedToFail() const14142 bool TestCaseInfo::expectedToFail() const {
14143 return ( properties & (ShouldFail ) ) != 0;
14144 }
14145
tagsAsString() const14146 std::string TestCaseInfo::tagsAsString() const {
14147 std::string ret;
14148 // '[' and ']' per tag
14149 std::size_t full_size = 2 * tags.size();
14150 for (const auto& tag : tags) {
14151 full_size += tag.size();
14152 }
14153 ret.reserve(full_size);
14154 for (const auto& tag : tags) {
14155 ret.push_back('[');
14156 ret.append(tag);
14157 ret.push_back(']');
14158 }
14159
14160 return ret;
14161 }
14162
TestCase(ITestInvoker * testCase,TestCaseInfo && info)14163 TestCase::TestCase( ITestInvoker* testCase, TestCaseInfo&& info ) : TestCaseInfo( std::move(info) ), test( testCase ) {}
14164
withName(std::string const & _newName) const14165 TestCase TestCase::withName( std::string const& _newName ) const {
14166 TestCase other( *this );
14167 other.name = _newName;
14168 return other;
14169 }
14170
invoke() const14171 void TestCase::invoke() const {
14172 test->invoke();
14173 }
14174
operator ==(TestCase const & other) const14175 bool TestCase::operator == ( TestCase const& other ) const {
14176 return test.get() == other.test.get() &&
14177 name == other.name &&
14178 className == other.className;
14179 }
14180
operator <(TestCase const & other) const14181 bool TestCase::operator < ( TestCase const& other ) const {
14182 return name < other.name;
14183 }
14184
getTestCaseInfo() const14185 TestCaseInfo const& TestCase::getTestCaseInfo() const
14186 {
14187 return *this;
14188 }
14189
14190 } // end namespace Catch
14191 // end catch_test_case_info.cpp
14192 // start catch_test_case_registry_impl.cpp
14193
14194 #include <algorithm>
14195 #include <sstream>
14196
14197 namespace Catch {
14198
14199 namespace {
14200 struct TestHasher {
14201 using hash_t = uint64_t;
14202
TestHasherCatch::__anon21412a523f11::TestHasher14203 explicit TestHasher( hash_t hashSuffix ):
14204 m_hashSuffix{ hashSuffix } {}
14205
operator ()Catch::__anon21412a523f11::TestHasher14206 uint32_t operator()( TestCase const& t ) const {
14207 // FNV-1a hash with multiplication fold.
14208 const hash_t prime = 1099511628211u;
14209 hash_t hash = 14695981039346656037u;
14210 for ( const char c : t.name ) {
14211 hash ^= c;
14212 hash *= prime;
14213 }
14214 hash ^= m_hashSuffix;
14215 hash *= prime;
14216 const uint32_t low{ static_cast<uint32_t>( hash ) };
14217 const uint32_t high{ static_cast<uint32_t>( hash >> 32 ) };
14218 return low * high;
14219 }
14220
14221 private:
14222 hash_t m_hashSuffix;
14223 };
14224 } // end unnamed namespace
14225
sortTests(IConfig const & config,std::vector<TestCase> const & unsortedTestCases)14226 std::vector<TestCase> sortTests( IConfig const& config, std::vector<TestCase> const& unsortedTestCases ) {
14227 switch( config.runOrder() ) {
14228 case RunTests::InDeclarationOrder:
14229 // already in declaration order
14230 break;
14231
14232 case RunTests::InLexicographicalOrder: {
14233 std::vector<TestCase> sorted = unsortedTestCases;
14234 std::sort( sorted.begin(), sorted.end() );
14235 return sorted;
14236 }
14237
14238 case RunTests::InRandomOrder: {
14239 seedRng( config );
14240 TestHasher h{ config.rngSeed() };
14241
14242 using hashedTest = std::pair<TestHasher::hash_t, TestCase const*>;
14243 std::vector<hashedTest> indexed_tests;
14244 indexed_tests.reserve( unsortedTestCases.size() );
14245
14246 for (auto const& testCase : unsortedTestCases) {
14247 indexed_tests.emplace_back(h(testCase), &testCase);
14248 }
14249
14250 std::sort(indexed_tests.begin(), indexed_tests.end(),
14251 [](hashedTest const& lhs, hashedTest const& rhs) {
14252 if (lhs.first == rhs.first) {
14253 return lhs.second->name < rhs.second->name;
14254 }
14255 return lhs.first < rhs.first;
14256 });
14257
14258 std::vector<TestCase> sorted;
14259 sorted.reserve( indexed_tests.size() );
14260
14261 for (auto const& hashed : indexed_tests) {
14262 sorted.emplace_back(*hashed.second);
14263 }
14264
14265 return sorted;
14266 }
14267 }
14268 return unsortedTestCases;
14269 }
14270
isThrowSafe(TestCase const & testCase,IConfig const & config)14271 bool isThrowSafe( TestCase const& testCase, IConfig const& config ) {
14272 return !testCase.throws() || config.allowThrows();
14273 }
14274
matchTest(TestCase const & testCase,TestSpec const & testSpec,IConfig const & config)14275 bool matchTest( TestCase const& testCase, TestSpec const& testSpec, IConfig const& config ) {
14276 return testSpec.matches( testCase ) && isThrowSafe( testCase, config );
14277 }
14278
enforceNoDuplicateTestCases(std::vector<TestCase> const & functions)14279 void enforceNoDuplicateTestCases( std::vector<TestCase> const& functions ) {
14280 std::set<TestCase> seenFunctions;
14281 for( auto const& function : functions ) {
14282 auto prev = seenFunctions.insert( function );
14283 CATCH_ENFORCE( prev.second,
14284 "error: TEST_CASE( \"" << function.name << "\" ) already defined.\n"
14285 << "\tFirst seen at " << prev.first->getTestCaseInfo().lineInfo << "\n"
14286 << "\tRedefined at " << function.getTestCaseInfo().lineInfo );
14287 }
14288 }
14289
filterTests(std::vector<TestCase> const & testCases,TestSpec const & testSpec,IConfig const & config)14290 std::vector<TestCase> filterTests( std::vector<TestCase> const& testCases, TestSpec const& testSpec, IConfig const& config ) {
14291 std::vector<TestCase> filtered;
14292 filtered.reserve( testCases.size() );
14293 for (auto const& testCase : testCases) {
14294 if ((!testSpec.hasFilters() && !testCase.isHidden()) ||
14295 (testSpec.hasFilters() && matchTest(testCase, testSpec, config))) {
14296 filtered.push_back(testCase);
14297 }
14298 }
14299 return filtered;
14300 }
getAllTestCasesSorted(IConfig const & config)14301 std::vector<TestCase> const& getAllTestCasesSorted( IConfig const& config ) {
14302 return getRegistryHub().getTestCaseRegistry().getAllTestsSorted( config );
14303 }
14304
registerTest(TestCase const & testCase)14305 void TestRegistry::registerTest( TestCase const& testCase ) {
14306 std::string name = testCase.getTestCaseInfo().name;
14307 if( name.empty() ) {
14308 ReusableStringStream rss;
14309 rss << "Anonymous test case " << ++m_unnamedCount;
14310 return registerTest( testCase.withName( rss.str() ) );
14311 }
14312 m_functions.push_back( testCase );
14313 }
14314
getAllTests() const14315 std::vector<TestCase> const& TestRegistry::getAllTests() const {
14316 return m_functions;
14317 }
getAllTestsSorted(IConfig const & config) const14318 std::vector<TestCase> const& TestRegistry::getAllTestsSorted( IConfig const& config ) const {
14319 if( m_sortedFunctions.empty() )
14320 enforceNoDuplicateTestCases( m_functions );
14321
14322 if( m_currentSortOrder != config.runOrder() || m_sortedFunctions.empty() ) {
14323 m_sortedFunctions = sortTests( config, m_functions );
14324 m_currentSortOrder = config.runOrder();
14325 }
14326 return m_sortedFunctions;
14327 }
14328
14329 ///////////////////////////////////////////////////////////////////////////
TestInvokerAsFunction(void (* testAsFunction)())14330 TestInvokerAsFunction::TestInvokerAsFunction( void(*testAsFunction)() ) noexcept : m_testAsFunction( testAsFunction ) {}
14331
invoke() const14332 void TestInvokerAsFunction::invoke() const {
14333 m_testAsFunction();
14334 }
14335
extractClassName(StringRef const & classOrQualifiedMethodName)14336 std::string extractClassName( StringRef const& classOrQualifiedMethodName ) {
14337 std::string className(classOrQualifiedMethodName);
14338 if( startsWith( className, '&' ) )
14339 {
14340 std::size_t lastColons = className.rfind( "::" );
14341 std::size_t penultimateColons = className.rfind( "::", lastColons-1 );
14342 if( penultimateColons == std::string::npos )
14343 penultimateColons = 1;
14344 className = className.substr( penultimateColons, lastColons-penultimateColons );
14345 }
14346 return className;
14347 }
14348
14349 } // end namespace Catch
14350 // end catch_test_case_registry_impl.cpp
14351 // start catch_test_case_tracker.cpp
14352
14353 #include <algorithm>
14354 #include <cassert>
14355 #include <stdexcept>
14356 #include <memory>
14357 #include <sstream>
14358
14359 #if defined(__clang__)
14360 # pragma clang diagnostic push
14361 # pragma clang diagnostic ignored "-Wexit-time-destructors"
14362 #endif
14363
14364 namespace Catch {
14365 namespace TestCaseTracking {
14366
NameAndLocation(std::string const & _name,SourceLineInfo const & _location)14367 NameAndLocation::NameAndLocation( std::string const& _name, SourceLineInfo const& _location )
14368 : name( _name ),
14369 location( _location )
14370 {}
14371
14372 ITracker::~ITracker() = default;
14373
startRun()14374 ITracker& TrackerContext::startRun() {
14375 m_rootTracker = std::make_shared<SectionTracker>( NameAndLocation( "{root}", CATCH_INTERNAL_LINEINFO ), *this, nullptr );
14376 m_currentTracker = nullptr;
14377 m_runState = Executing;
14378 return *m_rootTracker;
14379 }
14380
endRun()14381 void TrackerContext::endRun() {
14382 m_rootTracker.reset();
14383 m_currentTracker = nullptr;
14384 m_runState = NotStarted;
14385 }
14386
startCycle()14387 void TrackerContext::startCycle() {
14388 m_currentTracker = m_rootTracker.get();
14389 m_runState = Executing;
14390 }
completeCycle()14391 void TrackerContext::completeCycle() {
14392 m_runState = CompletedCycle;
14393 }
14394
completedCycle() const14395 bool TrackerContext::completedCycle() const {
14396 return m_runState == CompletedCycle;
14397 }
currentTracker()14398 ITracker& TrackerContext::currentTracker() {
14399 return *m_currentTracker;
14400 }
setCurrentTracker(ITracker * tracker)14401 void TrackerContext::setCurrentTracker( ITracker* tracker ) {
14402 m_currentTracker = tracker;
14403 }
14404
TrackerBase(NameAndLocation const & nameAndLocation,TrackerContext & ctx,ITracker * parent)14405 TrackerBase::TrackerBase( NameAndLocation const& nameAndLocation, TrackerContext& ctx, ITracker* parent ):
14406 ITracker(nameAndLocation),
14407 m_ctx( ctx ),
14408 m_parent( parent )
14409 {}
14410
isComplete() const14411 bool TrackerBase::isComplete() const {
14412 return m_runState == CompletedSuccessfully || m_runState == Failed;
14413 }
isSuccessfullyCompleted() const14414 bool TrackerBase::isSuccessfullyCompleted() const {
14415 return m_runState == CompletedSuccessfully;
14416 }
isOpen() const14417 bool TrackerBase::isOpen() const {
14418 return m_runState != NotStarted && !isComplete();
14419 }
hasChildren() const14420 bool TrackerBase::hasChildren() const {
14421 return !m_children.empty();
14422 }
14423
addChild(ITrackerPtr const & child)14424 void TrackerBase::addChild( ITrackerPtr const& child ) {
14425 m_children.push_back( child );
14426 }
14427
findChild(NameAndLocation const & nameAndLocation)14428 ITrackerPtr TrackerBase::findChild( NameAndLocation const& nameAndLocation ) {
14429 auto it = std::find_if( m_children.begin(), m_children.end(),
14430 [&nameAndLocation]( ITrackerPtr const& tracker ){
14431 return
14432 tracker->nameAndLocation().location == nameAndLocation.location &&
14433 tracker->nameAndLocation().name == nameAndLocation.name;
14434 } );
14435 return( it != m_children.end() )
14436 ? *it
14437 : nullptr;
14438 }
parent()14439 ITracker& TrackerBase::parent() {
14440 assert( m_parent ); // Should always be non-null except for root
14441 return *m_parent;
14442 }
14443
openChild()14444 void TrackerBase::openChild() {
14445 if( m_runState != ExecutingChildren ) {
14446 m_runState = ExecutingChildren;
14447 if( m_parent )
14448 m_parent->openChild();
14449 }
14450 }
14451
isSectionTracker() const14452 bool TrackerBase::isSectionTracker() const { return false; }
isGeneratorTracker() const14453 bool TrackerBase::isGeneratorTracker() const { return false; }
14454
open()14455 void TrackerBase::open() {
14456 m_runState = Executing;
14457 moveToThis();
14458 if( m_parent )
14459 m_parent->openChild();
14460 }
14461
close()14462 void TrackerBase::close() {
14463
14464 // Close any still open children (e.g. generators)
14465 while( &m_ctx.currentTracker() != this )
14466 m_ctx.currentTracker().close();
14467
14468 switch( m_runState ) {
14469 case NeedsAnotherRun:
14470 break;
14471
14472 case Executing:
14473 m_runState = CompletedSuccessfully;
14474 break;
14475 case ExecutingChildren:
14476 if( std::all_of(m_children.begin(), m_children.end(), [](ITrackerPtr const& t){ return t->isComplete(); }) )
14477 m_runState = CompletedSuccessfully;
14478 break;
14479
14480 case NotStarted:
14481 case CompletedSuccessfully:
14482 case Failed:
14483 CATCH_INTERNAL_ERROR( "Illogical state: " << m_runState );
14484
14485 default:
14486 CATCH_INTERNAL_ERROR( "Unknown state: " << m_runState );
14487 }
14488 moveToParent();
14489 m_ctx.completeCycle();
14490 }
fail()14491 void TrackerBase::fail() {
14492 m_runState = Failed;
14493 if( m_parent )
14494 m_parent->markAsNeedingAnotherRun();
14495 moveToParent();
14496 m_ctx.completeCycle();
14497 }
markAsNeedingAnotherRun()14498 void TrackerBase::markAsNeedingAnotherRun() {
14499 m_runState = NeedsAnotherRun;
14500 }
14501
moveToParent()14502 void TrackerBase::moveToParent() {
14503 assert( m_parent );
14504 m_ctx.setCurrentTracker( m_parent );
14505 }
moveToThis()14506 void TrackerBase::moveToThis() {
14507 m_ctx.setCurrentTracker( this );
14508 }
14509
SectionTracker(NameAndLocation const & nameAndLocation,TrackerContext & ctx,ITracker * parent)14510 SectionTracker::SectionTracker( NameAndLocation const& nameAndLocation, TrackerContext& ctx, ITracker* parent )
14511 : TrackerBase( nameAndLocation, ctx, parent ),
14512 m_trimmed_name(trim(nameAndLocation.name))
14513 {
14514 if( parent ) {
14515 while( !parent->isSectionTracker() )
14516 parent = &parent->parent();
14517
14518 SectionTracker& parentSection = static_cast<SectionTracker&>( *parent );
14519 addNextFilters( parentSection.m_filters );
14520 }
14521 }
14522
isComplete() const14523 bool SectionTracker::isComplete() const {
14524 bool complete = true;
14525
14526 if (m_filters.empty()
14527 || m_filters[0] == ""
14528 || std::find(m_filters.begin(), m_filters.end(), m_trimmed_name) != m_filters.end()) {
14529 complete = TrackerBase::isComplete();
14530 }
14531 return complete;
14532 }
14533
isSectionTracker() const14534 bool SectionTracker::isSectionTracker() const { return true; }
14535
acquire(TrackerContext & ctx,NameAndLocation const & nameAndLocation)14536 SectionTracker& SectionTracker::acquire( TrackerContext& ctx, NameAndLocation const& nameAndLocation ) {
14537 std::shared_ptr<SectionTracker> section;
14538
14539 ITracker& currentTracker = ctx.currentTracker();
14540 if( ITrackerPtr childTracker = currentTracker.findChild( nameAndLocation ) ) {
14541 assert( childTracker );
14542 assert( childTracker->isSectionTracker() );
14543 section = std::static_pointer_cast<SectionTracker>( childTracker );
14544 }
14545 else {
14546 section = std::make_shared<SectionTracker>( nameAndLocation, ctx, ¤tTracker );
14547 currentTracker.addChild( section );
14548 }
14549 if( !ctx.completedCycle() )
14550 section->tryOpen();
14551 return *section;
14552 }
14553
tryOpen()14554 void SectionTracker::tryOpen() {
14555 if( !isComplete() )
14556 open();
14557 }
14558
addInitialFilters(std::vector<std::string> const & filters)14559 void SectionTracker::addInitialFilters( std::vector<std::string> const& filters ) {
14560 if( !filters.empty() ) {
14561 m_filters.reserve( m_filters.size() + filters.size() + 2 );
14562 m_filters.emplace_back(""); // Root - should never be consulted
14563 m_filters.emplace_back(""); // Test Case - not a section filter
14564 m_filters.insert( m_filters.end(), filters.begin(), filters.end() );
14565 }
14566 }
addNextFilters(std::vector<std::string> const & filters)14567 void SectionTracker::addNextFilters( std::vector<std::string> const& filters ) {
14568 if( filters.size() > 1 )
14569 m_filters.insert( m_filters.end(), filters.begin()+1, filters.end() );
14570 }
14571
getFilters() const14572 std::vector<std::string> const& SectionTracker::getFilters() const {
14573 return m_filters;
14574 }
14575
trimmedName() const14576 std::string const& SectionTracker::trimmedName() const {
14577 return m_trimmed_name;
14578 }
14579
14580 } // namespace TestCaseTracking
14581
14582 using TestCaseTracking::ITracker;
14583 using TestCaseTracking::TrackerContext;
14584 using TestCaseTracking::SectionTracker;
14585
14586 } // namespace Catch
14587
14588 #if defined(__clang__)
14589 # pragma clang diagnostic pop
14590 #endif
14591 // end catch_test_case_tracker.cpp
14592 // start catch_test_registry.cpp
14593
14594 namespace Catch {
14595
makeTestInvoker(void (* testAsFunction)())14596 auto makeTestInvoker( void(*testAsFunction)() ) noexcept -> ITestInvoker* {
14597 return new(std::nothrow) TestInvokerAsFunction( testAsFunction );
14598 }
14599
NameAndTags(StringRef const & name_,StringRef const & tags_)14600 NameAndTags::NameAndTags( StringRef const& name_ , StringRef const& tags_ ) noexcept : name( name_ ), tags( tags_ ) {}
14601
AutoReg(ITestInvoker * invoker,SourceLineInfo const & lineInfo,StringRef const & classOrMethod,NameAndTags const & nameAndTags)14602 AutoReg::AutoReg( ITestInvoker* invoker, SourceLineInfo const& lineInfo, StringRef const& classOrMethod, NameAndTags const& nameAndTags ) noexcept {
14603 CATCH_TRY {
14604 getMutableRegistryHub()
14605 .registerTest(
14606 makeTestCase(
14607 invoker,
14608 extractClassName( classOrMethod ),
14609 nameAndTags,
14610 lineInfo));
14611 } CATCH_CATCH_ALL {
14612 // Do not throw when constructing global objects, instead register the exception to be processed later
14613 getMutableRegistryHub().registerStartupException();
14614 }
14615 }
14616
14617 AutoReg::~AutoReg() = default;
14618 }
14619 // end catch_test_registry.cpp
14620 // start catch_test_spec.cpp
14621
14622 #include <algorithm>
14623 #include <string>
14624 #include <vector>
14625 #include <memory>
14626
14627 namespace Catch {
14628
Pattern(std::string const & name)14629 TestSpec::Pattern::Pattern( std::string const& name )
14630 : m_name( name )
14631 {}
14632
14633 TestSpec::Pattern::~Pattern() = default;
14634
name() const14635 std::string const& TestSpec::Pattern::name() const {
14636 return m_name;
14637 }
14638
NamePattern(std::string const & name,std::string const & filterString)14639 TestSpec::NamePattern::NamePattern( std::string const& name, std::string const& filterString )
14640 : Pattern( filterString )
14641 , m_wildcardPattern( toLower( name ), CaseSensitive::No )
14642 {}
14643
matches(TestCaseInfo const & testCase) const14644 bool TestSpec::NamePattern::matches( TestCaseInfo const& testCase ) const {
14645 return m_wildcardPattern.matches( testCase.name );
14646 }
14647
TagPattern(std::string const & tag,std::string const & filterString)14648 TestSpec::TagPattern::TagPattern( std::string const& tag, std::string const& filterString )
14649 : Pattern( filterString )
14650 , m_tag( toLower( tag ) )
14651 {}
14652
matches(TestCaseInfo const & testCase) const14653 bool TestSpec::TagPattern::matches( TestCaseInfo const& testCase ) const {
14654 return std::find(begin(testCase.lcaseTags),
14655 end(testCase.lcaseTags),
14656 m_tag) != end(testCase.lcaseTags);
14657 }
14658
ExcludedPattern(PatternPtr const & underlyingPattern)14659 TestSpec::ExcludedPattern::ExcludedPattern( PatternPtr const& underlyingPattern )
14660 : Pattern( underlyingPattern->name() )
14661 , m_underlyingPattern( underlyingPattern )
14662 {}
14663
matches(TestCaseInfo const & testCase) const14664 bool TestSpec::ExcludedPattern::matches( TestCaseInfo const& testCase ) const {
14665 return !m_underlyingPattern->matches( testCase );
14666 }
14667
matches(TestCaseInfo const & testCase) const14668 bool TestSpec::Filter::matches( TestCaseInfo const& testCase ) const {
14669 return std::all_of( m_patterns.begin(), m_patterns.end(), [&]( PatternPtr const& p ){ return p->matches( testCase ); } );
14670 }
14671
name() const14672 std::string TestSpec::Filter::name() const {
14673 std::string name;
14674 for( auto const& p : m_patterns )
14675 name += p->name();
14676 return name;
14677 }
14678
hasFilters() const14679 bool TestSpec::hasFilters() const {
14680 return !m_filters.empty();
14681 }
14682
matches(TestCaseInfo const & testCase) const14683 bool TestSpec::matches( TestCaseInfo const& testCase ) const {
14684 return std::any_of( m_filters.begin(), m_filters.end(), [&]( Filter const& f ){ return f.matches( testCase ); } );
14685 }
14686
matchesByFilter(std::vector<TestCase> const & testCases,IConfig const & config) const14687 TestSpec::Matches TestSpec::matchesByFilter( std::vector<TestCase> const& testCases, IConfig const& config ) const
14688 {
14689 Matches matches( m_filters.size() );
14690 std::transform( m_filters.begin(), m_filters.end(), matches.begin(), [&]( Filter const& filter ){
14691 std::vector<TestCase const*> currentMatches;
14692 for( auto const& test : testCases )
14693 if( isThrowSafe( test, config ) && filter.matches( test ) )
14694 currentMatches.emplace_back( &test );
14695 return FilterMatch{ filter.name(), currentMatches };
14696 } );
14697 return matches;
14698 }
14699
getInvalidArgs() const14700 const TestSpec::vectorStrings& TestSpec::getInvalidArgs() const{
14701 return (m_invalidArgs);
14702 }
14703
14704 }
14705 // end catch_test_spec.cpp
14706 // start catch_test_spec_parser.cpp
14707
14708 namespace Catch {
14709
TestSpecParser(ITagAliasRegistry const & tagAliases)14710 TestSpecParser::TestSpecParser( ITagAliasRegistry const& tagAliases ) : m_tagAliases( &tagAliases ) {}
14711
parse(std::string const & arg)14712 TestSpecParser& TestSpecParser::parse( std::string const& arg ) {
14713 m_mode = None;
14714 m_exclusion = false;
14715 m_arg = m_tagAliases->expandAliases( arg );
14716 m_escapeChars.clear();
14717 m_substring.reserve(m_arg.size());
14718 m_patternName.reserve(m_arg.size());
14719 m_realPatternPos = 0;
14720
14721 for( m_pos = 0; m_pos < m_arg.size(); ++m_pos )
14722 //if visitChar fails
14723 if( !visitChar( m_arg[m_pos] ) ){
14724 m_testSpec.m_invalidArgs.push_back(arg);
14725 break;
14726 }
14727 endMode();
14728 return *this;
14729 }
testSpec()14730 TestSpec TestSpecParser::testSpec() {
14731 addFilter();
14732 return m_testSpec;
14733 }
visitChar(char c)14734 bool TestSpecParser::visitChar( char c ) {
14735 if( (m_mode != EscapedName) && (c == '\\') ) {
14736 escape();
14737 addCharToPattern(c);
14738 return true;
14739 }else if((m_mode != EscapedName) && (c == ',') ) {
14740 return separate();
14741 }
14742
14743 switch( m_mode ) {
14744 case None:
14745 if( processNoneChar( c ) )
14746 return true;
14747 break;
14748 case Name:
14749 processNameChar( c );
14750 break;
14751 case EscapedName:
14752 endMode();
14753 addCharToPattern(c);
14754 return true;
14755 default:
14756 case Tag:
14757 case QuotedName:
14758 if( processOtherChar( c ) )
14759 return true;
14760 break;
14761 }
14762
14763 m_substring += c;
14764 if( !isControlChar( c ) ) {
14765 m_patternName += c;
14766 m_realPatternPos++;
14767 }
14768 return true;
14769 }
14770 // Two of the processing methods return true to signal the caller to return
14771 // without adding the given character to the current pattern strings
processNoneChar(char c)14772 bool TestSpecParser::processNoneChar( char c ) {
14773 switch( c ) {
14774 case ' ':
14775 return true;
14776 case '~':
14777 m_exclusion = true;
14778 return false;
14779 case '[':
14780 startNewMode( Tag );
14781 return false;
14782 case '"':
14783 startNewMode( QuotedName );
14784 return false;
14785 default:
14786 startNewMode( Name );
14787 return false;
14788 }
14789 }
processNameChar(char c)14790 void TestSpecParser::processNameChar( char c ) {
14791 if( c == '[' ) {
14792 if( m_substring == "exclude:" )
14793 m_exclusion = true;
14794 else
14795 endMode();
14796 startNewMode( Tag );
14797 }
14798 }
processOtherChar(char c)14799 bool TestSpecParser::processOtherChar( char c ) {
14800 if( !isControlChar( c ) )
14801 return false;
14802 m_substring += c;
14803 endMode();
14804 return true;
14805 }
startNewMode(Mode mode)14806 void TestSpecParser::startNewMode( Mode mode ) {
14807 m_mode = mode;
14808 }
endMode()14809 void TestSpecParser::endMode() {
14810 switch( m_mode ) {
14811 case Name:
14812 case QuotedName:
14813 return addNamePattern();
14814 case Tag:
14815 return addTagPattern();
14816 case EscapedName:
14817 revertBackToLastMode();
14818 return;
14819 case None:
14820 default:
14821 return startNewMode( None );
14822 }
14823 }
escape()14824 void TestSpecParser::escape() {
14825 saveLastMode();
14826 m_mode = EscapedName;
14827 m_escapeChars.push_back(m_realPatternPos);
14828 }
isControlChar(char c) const14829 bool TestSpecParser::isControlChar( char c ) const {
14830 switch( m_mode ) {
14831 default:
14832 return false;
14833 case None:
14834 return c == '~';
14835 case Name:
14836 return c == '[';
14837 case EscapedName:
14838 return true;
14839 case QuotedName:
14840 return c == '"';
14841 case Tag:
14842 return c == '[' || c == ']';
14843 }
14844 }
14845
addFilter()14846 void TestSpecParser::addFilter() {
14847 if( !m_currentFilter.m_patterns.empty() ) {
14848 m_testSpec.m_filters.push_back( m_currentFilter );
14849 m_currentFilter = TestSpec::Filter();
14850 }
14851 }
14852
saveLastMode()14853 void TestSpecParser::saveLastMode() {
14854 lastMode = m_mode;
14855 }
14856
revertBackToLastMode()14857 void TestSpecParser::revertBackToLastMode() {
14858 m_mode = lastMode;
14859 }
14860
separate()14861 bool TestSpecParser::separate() {
14862 if( (m_mode==QuotedName) || (m_mode==Tag) ){
14863 //invalid argument, signal failure to previous scope.
14864 m_mode = None;
14865 m_pos = m_arg.size();
14866 m_substring.clear();
14867 m_patternName.clear();
14868 m_realPatternPos = 0;
14869 return false;
14870 }
14871 endMode();
14872 addFilter();
14873 return true; //success
14874 }
14875
preprocessPattern()14876 std::string TestSpecParser::preprocessPattern() {
14877 std::string token = m_patternName;
14878 for (std::size_t i = 0; i < m_escapeChars.size(); ++i)
14879 token = token.substr(0, m_escapeChars[i] - i) + token.substr(m_escapeChars[i] - i + 1);
14880 m_escapeChars.clear();
14881 if (startsWith(token, "exclude:")) {
14882 m_exclusion = true;
14883 token = token.substr(8);
14884 }
14885
14886 m_patternName.clear();
14887 m_realPatternPos = 0;
14888
14889 return token;
14890 }
14891
addNamePattern()14892 void TestSpecParser::addNamePattern() {
14893 auto token = preprocessPattern();
14894
14895 if (!token.empty()) {
14896 TestSpec::PatternPtr pattern = std::make_shared<TestSpec::NamePattern>(token, m_substring);
14897 if (m_exclusion)
14898 pattern = std::make_shared<TestSpec::ExcludedPattern>(pattern);
14899 m_currentFilter.m_patterns.push_back(pattern);
14900 }
14901 m_substring.clear();
14902 m_exclusion = false;
14903 m_mode = None;
14904 }
14905
addTagPattern()14906 void TestSpecParser::addTagPattern() {
14907 auto token = preprocessPattern();
14908
14909 if (!token.empty()) {
14910 // If the tag pattern is the "hide and tag" shorthand (e.g. [.foo])
14911 // we have to create a separate hide tag and shorten the real one
14912 if (token.size() > 1 && token[0] == '.') {
14913 token.erase(token.begin());
14914 TestSpec::PatternPtr pattern = std::make_shared<TestSpec::TagPattern>(".", m_substring);
14915 if (m_exclusion) {
14916 pattern = std::make_shared<TestSpec::ExcludedPattern>(pattern);
14917 }
14918 m_currentFilter.m_patterns.push_back(pattern);
14919 }
14920
14921 TestSpec::PatternPtr pattern = std::make_shared<TestSpec::TagPattern>(token, m_substring);
14922
14923 if (m_exclusion) {
14924 pattern = std::make_shared<TestSpec::ExcludedPattern>(pattern);
14925 }
14926 m_currentFilter.m_patterns.push_back(pattern);
14927 }
14928 m_substring.clear();
14929 m_exclusion = false;
14930 m_mode = None;
14931 }
14932
parseTestSpec(std::string const & arg)14933 TestSpec parseTestSpec( std::string const& arg ) {
14934 return TestSpecParser( ITagAliasRegistry::get() ).parse( arg ).testSpec();
14935 }
14936
14937 } // namespace Catch
14938 // end catch_test_spec_parser.cpp
14939 // start catch_timer.cpp
14940
14941 #include <chrono>
14942
14943 static const uint64_t nanosecondsInSecond = 1000000000;
14944
14945 namespace Catch {
14946
getCurrentNanosecondsSinceEpoch()14947 auto getCurrentNanosecondsSinceEpoch() -> uint64_t {
14948 return std::chrono::duration_cast<std::chrono::nanoseconds>( std::chrono::high_resolution_clock::now().time_since_epoch() ).count();
14949 }
14950
14951 namespace {
estimateClockResolution()14952 auto estimateClockResolution() -> uint64_t {
14953 uint64_t sum = 0;
14954 static const uint64_t iterations = 1000000;
14955
14956 auto startTime = getCurrentNanosecondsSinceEpoch();
14957
14958 for( std::size_t i = 0; i < iterations; ++i ) {
14959
14960 uint64_t ticks;
14961 uint64_t baseTicks = getCurrentNanosecondsSinceEpoch();
14962 do {
14963 ticks = getCurrentNanosecondsSinceEpoch();
14964 } while( ticks == baseTicks );
14965
14966 auto delta = ticks - baseTicks;
14967 sum += delta;
14968
14969 // If we have been calibrating for over 3 seconds -- the clock
14970 // is terrible and we should move on.
14971 // TBD: How to signal that the measured resolution is probably wrong?
14972 if (ticks > startTime + 3 * nanosecondsInSecond) {
14973 return sum / ( i + 1u );
14974 }
14975 }
14976
14977 // We're just taking the mean, here. To do better we could take the std. dev and exclude outliers
14978 // - and potentially do more iterations if there's a high variance.
14979 return sum/iterations;
14980 }
14981 }
getEstimatedClockResolution()14982 auto getEstimatedClockResolution() -> uint64_t {
14983 static auto s_resolution = estimateClockResolution();
14984 return s_resolution;
14985 }
14986
start()14987 void Timer::start() {
14988 m_nanoseconds = getCurrentNanosecondsSinceEpoch();
14989 }
getElapsedNanoseconds() const14990 auto Timer::getElapsedNanoseconds() const -> uint64_t {
14991 return getCurrentNanosecondsSinceEpoch() - m_nanoseconds;
14992 }
getElapsedMicroseconds() const14993 auto Timer::getElapsedMicroseconds() const -> uint64_t {
14994 return getElapsedNanoseconds()/1000;
14995 }
getElapsedMilliseconds() const14996 auto Timer::getElapsedMilliseconds() const -> unsigned int {
14997 return static_cast<unsigned int>(getElapsedMicroseconds()/1000);
14998 }
getElapsedSeconds() const14999 auto Timer::getElapsedSeconds() const -> double {
15000 return getElapsedMicroseconds()/1000000.0;
15001 }
15002
15003 } // namespace Catch
15004 // end catch_timer.cpp
15005 // start catch_tostring.cpp
15006
15007 #if defined(__clang__)
15008 # pragma clang diagnostic push
15009 # pragma clang diagnostic ignored "-Wexit-time-destructors"
15010 # pragma clang diagnostic ignored "-Wglobal-constructors"
15011 #endif
15012
15013 // Enable specific decls locally
15014 #if !defined(CATCH_CONFIG_ENABLE_CHRONO_STRINGMAKER)
15015 #define CATCH_CONFIG_ENABLE_CHRONO_STRINGMAKER
15016 #endif
15017
15018 #include <cmath>
15019 #include <iomanip>
15020
15021 namespace Catch {
15022
15023 namespace Detail {
15024
15025 const std::string unprintableString = "{?}";
15026
15027 namespace {
15028 const int hexThreshold = 255;
15029
15030 struct Endianness {
15031 enum Arch { Big, Little };
15032
whichCatch::Detail::__anon21412a524711::Endianness15033 static Arch which() {
15034 int one = 1;
15035 // If the lowest byte we read is non-zero, we can assume
15036 // that little endian format is used.
15037 auto value = *reinterpret_cast<char*>(&one);
15038 return value ? Little : Big;
15039 }
15040 };
15041 }
15042
rawMemoryToString(const void * object,std::size_t size)15043 std::string rawMemoryToString( const void *object, std::size_t size ) {
15044 // Reverse order for little endian architectures
15045 int i = 0, end = static_cast<int>( size ), inc = 1;
15046 if( Endianness::which() == Endianness::Little ) {
15047 i = end-1;
15048 end = inc = -1;
15049 }
15050
15051 unsigned char const *bytes = static_cast<unsigned char const *>(object);
15052 ReusableStringStream rss;
15053 rss << "0x" << std::setfill('0') << std::hex;
15054 for( ; i != end; i += inc )
15055 rss << std::setw(2) << static_cast<unsigned>(bytes[i]);
15056 return rss.str();
15057 }
15058 }
15059
15060 template<typename T>
fpToString(T value,int precision)15061 std::string fpToString( T value, int precision ) {
15062 if (Catch::isnan(value)) {
15063 return "nan";
15064 }
15065
15066 ReusableStringStream rss;
15067 rss << std::setprecision( precision )
15068 << std::fixed
15069 << value;
15070 std::string d = rss.str();
15071 std::size_t i = d.find_last_not_of( '0' );
15072 if( i != std::string::npos && i != d.size()-1 ) {
15073 if( d[i] == '.' )
15074 i++;
15075 d = d.substr( 0, i+1 );
15076 }
15077 return d;
15078 }
15079
15080 //// ======================================================= ////
15081 //
15082 // Out-of-line defs for full specialization of StringMaker
15083 //
15084 //// ======================================================= ////
15085
convert(const std::string & str)15086 std::string StringMaker<std::string>::convert(const std::string& str) {
15087 if (!getCurrentContext().getConfig()->showInvisibles()) {
15088 return '"' + str + '"';
15089 }
15090
15091 std::string s("\"");
15092 for (char c : str) {
15093 switch (c) {
15094 case '\n':
15095 s.append("\\n");
15096 break;
15097 case '\t':
15098 s.append("\\t");
15099 break;
15100 default:
15101 s.push_back(c);
15102 break;
15103 }
15104 }
15105 s.append("\"");
15106 return s;
15107 }
15108
15109 #ifdef CATCH_CONFIG_CPP17_STRING_VIEW
convert(std::string_view str)15110 std::string StringMaker<std::string_view>::convert(std::string_view str) {
15111 return ::Catch::Detail::stringify(std::string{ str });
15112 }
15113 #endif
15114
convert(char const * str)15115 std::string StringMaker<char const*>::convert(char const* str) {
15116 if (str) {
15117 return ::Catch::Detail::stringify(std::string{ str });
15118 } else {
15119 return{ "{null string}" };
15120 }
15121 }
convert(char * str)15122 std::string StringMaker<char*>::convert(char* str) {
15123 if (str) {
15124 return ::Catch::Detail::stringify(std::string{ str });
15125 } else {
15126 return{ "{null string}" };
15127 }
15128 }
15129
15130 #ifdef CATCH_CONFIG_WCHAR
convert(const std::wstring & wstr)15131 std::string StringMaker<std::wstring>::convert(const std::wstring& wstr) {
15132 std::string s;
15133 s.reserve(wstr.size());
15134 for (auto c : wstr) {
15135 s += (c <= 0xff) ? static_cast<char>(c) : '?';
15136 }
15137 return ::Catch::Detail::stringify(s);
15138 }
15139
15140 # ifdef CATCH_CONFIG_CPP17_STRING_VIEW
convert(std::wstring_view str)15141 std::string StringMaker<std::wstring_view>::convert(std::wstring_view str) {
15142 return StringMaker<std::wstring>::convert(std::wstring(str));
15143 }
15144 # endif
15145
convert(wchar_t const * str)15146 std::string StringMaker<wchar_t const*>::convert(wchar_t const * str) {
15147 if (str) {
15148 return ::Catch::Detail::stringify(std::wstring{ str });
15149 } else {
15150 return{ "{null string}" };
15151 }
15152 }
convert(wchar_t * str)15153 std::string StringMaker<wchar_t *>::convert(wchar_t * str) {
15154 if (str) {
15155 return ::Catch::Detail::stringify(std::wstring{ str });
15156 } else {
15157 return{ "{null string}" };
15158 }
15159 }
15160 #endif
15161
15162 #if defined(CATCH_CONFIG_CPP17_BYTE)
15163 #include <cstddef>
convert(std::byte value)15164 std::string StringMaker<std::byte>::convert(std::byte value) {
15165 return ::Catch::Detail::stringify(std::to_integer<unsigned long long>(value));
15166 }
15167 #endif // defined(CATCH_CONFIG_CPP17_BYTE)
15168
convert(int value)15169 std::string StringMaker<int>::convert(int value) {
15170 return ::Catch::Detail::stringify(static_cast<long long>(value));
15171 }
convert(long value)15172 std::string StringMaker<long>::convert(long value) {
15173 return ::Catch::Detail::stringify(static_cast<long long>(value));
15174 }
convert(long long value)15175 std::string StringMaker<long long>::convert(long long value) {
15176 ReusableStringStream rss;
15177 rss << value;
15178 if (value > Detail::hexThreshold) {
15179 rss << " (0x" << std::hex << value << ')';
15180 }
15181 return rss.str();
15182 }
15183
convert(unsigned int value)15184 std::string StringMaker<unsigned int>::convert(unsigned int value) {
15185 return ::Catch::Detail::stringify(static_cast<unsigned long long>(value));
15186 }
convert(unsigned long value)15187 std::string StringMaker<unsigned long>::convert(unsigned long value) {
15188 return ::Catch::Detail::stringify(static_cast<unsigned long long>(value));
15189 }
convert(unsigned long long value)15190 std::string StringMaker<unsigned long long>::convert(unsigned long long value) {
15191 ReusableStringStream rss;
15192 rss << value;
15193 if (value > Detail::hexThreshold) {
15194 rss << " (0x" << std::hex << value << ')';
15195 }
15196 return rss.str();
15197 }
15198
convert(bool b)15199 std::string StringMaker<bool>::convert(bool b) {
15200 return b ? "true" : "false";
15201 }
15202
convert(signed char value)15203 std::string StringMaker<signed char>::convert(signed char value) {
15204 if (value == '\r') {
15205 return "'\\r'";
15206 } else if (value == '\f') {
15207 return "'\\f'";
15208 } else if (value == '\n') {
15209 return "'\\n'";
15210 } else if (value == '\t') {
15211 return "'\\t'";
15212 } else if ('\0' <= value && value < ' ') {
15213 return ::Catch::Detail::stringify(static_cast<unsigned int>(value));
15214 } else {
15215 char chstr[] = "' '";
15216 chstr[1] = value;
15217 return chstr;
15218 }
15219 }
convert(char c)15220 std::string StringMaker<char>::convert(char c) {
15221 return ::Catch::Detail::stringify(static_cast<signed char>(c));
15222 }
convert(unsigned char c)15223 std::string StringMaker<unsigned char>::convert(unsigned char c) {
15224 return ::Catch::Detail::stringify(static_cast<char>(c));
15225 }
15226
convert(std::nullptr_t)15227 std::string StringMaker<std::nullptr_t>::convert(std::nullptr_t) {
15228 return "nullptr";
15229 }
15230
15231 int StringMaker<float>::precision = 5;
15232
convert(float value)15233 std::string StringMaker<float>::convert(float value) {
15234 return fpToString(value, precision) + 'f';
15235 }
15236
15237 int StringMaker<double>::precision = 10;
15238
convert(double value)15239 std::string StringMaker<double>::convert(double value) {
15240 return fpToString(value, precision);
15241 }
15242
symbol()15243 std::string ratio_string<std::atto>::symbol() { return "a"; }
symbol()15244 std::string ratio_string<std::femto>::symbol() { return "f"; }
symbol()15245 std::string ratio_string<std::pico>::symbol() { return "p"; }
symbol()15246 std::string ratio_string<std::nano>::symbol() { return "n"; }
symbol()15247 std::string ratio_string<std::micro>::symbol() { return "u"; }
symbol()15248 std::string ratio_string<std::milli>::symbol() { return "m"; }
15249
15250 } // end namespace Catch
15251
15252 #if defined(__clang__)
15253 # pragma clang diagnostic pop
15254 #endif
15255
15256 // end catch_tostring.cpp
15257 // start catch_totals.cpp
15258
15259 namespace Catch {
15260
operator -(Counts const & other) const15261 Counts Counts::operator - ( Counts const& other ) const {
15262 Counts diff;
15263 diff.passed = passed - other.passed;
15264 diff.failed = failed - other.failed;
15265 diff.failedButOk = failedButOk - other.failedButOk;
15266 return diff;
15267 }
15268
operator +=(Counts const & other)15269 Counts& Counts::operator += ( Counts const& other ) {
15270 passed += other.passed;
15271 failed += other.failed;
15272 failedButOk += other.failedButOk;
15273 return *this;
15274 }
15275
total() const15276 std::size_t Counts::total() const {
15277 return passed + failed + failedButOk;
15278 }
allPassed() const15279 bool Counts::allPassed() const {
15280 return failed == 0 && failedButOk == 0;
15281 }
allOk() const15282 bool Counts::allOk() const {
15283 return failed == 0;
15284 }
15285
operator -(Totals const & other) const15286 Totals Totals::operator - ( Totals const& other ) const {
15287 Totals diff;
15288 diff.assertions = assertions - other.assertions;
15289 diff.testCases = testCases - other.testCases;
15290 return diff;
15291 }
15292
operator +=(Totals const & other)15293 Totals& Totals::operator += ( Totals const& other ) {
15294 assertions += other.assertions;
15295 testCases += other.testCases;
15296 return *this;
15297 }
15298
delta(Totals const & prevTotals) const15299 Totals Totals::delta( Totals const& prevTotals ) const {
15300 Totals diff = *this - prevTotals;
15301 if( diff.assertions.failed > 0 )
15302 ++diff.testCases.failed;
15303 else if( diff.assertions.failedButOk > 0 )
15304 ++diff.testCases.failedButOk;
15305 else
15306 ++diff.testCases.passed;
15307 return diff;
15308 }
15309
15310 }
15311 // end catch_totals.cpp
15312 // start catch_uncaught_exceptions.cpp
15313
15314 // start catch_config_uncaught_exceptions.hpp
15315
15316 // Copyright Catch2 Authors
15317 // Distributed under the Boost Software License, Version 1.0.
15318 // (See accompanying file LICENSE_1_0.txt or copy at
15319 // https://www.boost.org/LICENSE_1_0.txt)
15320
15321 // SPDX-License-Identifier: BSL-1.0
15322
15323 #ifndef CATCH_CONFIG_UNCAUGHT_EXCEPTIONS_HPP
15324 #define CATCH_CONFIG_UNCAUGHT_EXCEPTIONS_HPP
15325
15326 #if defined(_MSC_VER)
15327 # if _MSC_VER >= 1900 // Visual Studio 2015 or newer
15328 # define CATCH_INTERNAL_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS
15329 # endif
15330 #endif
15331
15332 #include <exception>
15333
15334 #if defined(__cpp_lib_uncaught_exceptions) \
15335 && !defined(CATCH_INTERNAL_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS)
15336
15337 # define CATCH_INTERNAL_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS
15338 #endif // __cpp_lib_uncaught_exceptions
15339
15340 #if defined(CATCH_INTERNAL_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS) \
15341 && !defined(CATCH_CONFIG_NO_CPP17_UNCAUGHT_EXCEPTIONS) \
15342 && !defined(CATCH_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS)
15343
15344 # define CATCH_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS
15345 #endif
15346
15347 #endif // CATCH_CONFIG_UNCAUGHT_EXCEPTIONS_HPP
15348 // end catch_config_uncaught_exceptions.hpp
15349 #include <exception>
15350
15351 namespace Catch {
uncaught_exceptions()15352 bool uncaught_exceptions() {
15353 #if defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
15354 return false;
15355 #elif defined(CATCH_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS)
15356 return std::uncaught_exceptions() > 0;
15357 #else
15358 return std::uncaught_exception();
15359 #endif
15360 }
15361 } // end namespace Catch
15362 // end catch_uncaught_exceptions.cpp
15363 // start catch_version.cpp
15364
15365 #include <ostream>
15366
15367 namespace Catch {
15368
Version(unsigned int _majorVersion,unsigned int _minorVersion,unsigned int _patchNumber,char const * const _branchName,unsigned int _buildNumber)15369 Version::Version
15370 ( unsigned int _majorVersion,
15371 unsigned int _minorVersion,
15372 unsigned int _patchNumber,
15373 char const * const _branchName,
15374 unsigned int _buildNumber )
15375 : majorVersion( _majorVersion ),
15376 minorVersion( _minorVersion ),
15377 patchNumber( _patchNumber ),
15378 branchName( _branchName ),
15379 buildNumber( _buildNumber )
15380 {}
15381
operator <<(std::ostream & os,Version const & version)15382 std::ostream& operator << ( std::ostream& os, Version const& version ) {
15383 os << version.majorVersion << '.'
15384 << version.minorVersion << '.'
15385 << version.patchNumber;
15386 // branchName is never null -> 0th char is \0 if it is empty
15387 if (version.branchName[0]) {
15388 os << '-' << version.branchName
15389 << '.' << version.buildNumber;
15390 }
15391 return os;
15392 }
15393
libraryVersion()15394 Version const& libraryVersion() {
15395 static Version version( 2, 13, 9, "", 0 );
15396 return version;
15397 }
15398
15399 }
15400 // end catch_version.cpp
15401 // start catch_wildcard_pattern.cpp
15402
15403 namespace Catch {
15404
WildcardPattern(std::string const & pattern,CaseSensitive::Choice caseSensitivity)15405 WildcardPattern::WildcardPattern( std::string const& pattern,
15406 CaseSensitive::Choice caseSensitivity )
15407 : m_caseSensitivity( caseSensitivity ),
15408 m_pattern( normaliseString( pattern ) )
15409 {
15410 if( startsWith( m_pattern, '*' ) ) {
15411 m_pattern = m_pattern.substr( 1 );
15412 m_wildcard = WildcardAtStart;
15413 }
15414 if( endsWith( m_pattern, '*' ) ) {
15415 m_pattern = m_pattern.substr( 0, m_pattern.size()-1 );
15416 m_wildcard = static_cast<WildcardPosition>( m_wildcard | WildcardAtEnd );
15417 }
15418 }
15419
matches(std::string const & str) const15420 bool WildcardPattern::matches( std::string const& str ) const {
15421 switch( m_wildcard ) {
15422 case NoWildcard:
15423 return m_pattern == normaliseString( str );
15424 case WildcardAtStart:
15425 return endsWith( normaliseString( str ), m_pattern );
15426 case WildcardAtEnd:
15427 return startsWith( normaliseString( str ), m_pattern );
15428 case WildcardAtBothEnds:
15429 return contains( normaliseString( str ), m_pattern );
15430 default:
15431 CATCH_INTERNAL_ERROR( "Unknown enum" );
15432 }
15433 }
15434
normaliseString(std::string const & str) const15435 std::string WildcardPattern::normaliseString( std::string const& str ) const {
15436 return trim( m_caseSensitivity == CaseSensitive::No ? toLower( str ) : str );
15437 }
15438 }
15439 // end catch_wildcard_pattern.cpp
15440 // start catch_xmlwriter.cpp
15441
15442 #include <iomanip>
15443 #include <type_traits>
15444
15445 namespace Catch {
15446
15447 namespace {
15448
trailingBytes(unsigned char c)15449 size_t trailingBytes(unsigned char c) {
15450 if ((c & 0xE0) == 0xC0) {
15451 return 2;
15452 }
15453 if ((c & 0xF0) == 0xE0) {
15454 return 3;
15455 }
15456 if ((c & 0xF8) == 0xF0) {
15457 return 4;
15458 }
15459 CATCH_INTERNAL_ERROR("Invalid multibyte utf-8 start byte encountered");
15460 }
15461
headerValue(unsigned char c)15462 uint32_t headerValue(unsigned char c) {
15463 if ((c & 0xE0) == 0xC0) {
15464 return c & 0x1F;
15465 }
15466 if ((c & 0xF0) == 0xE0) {
15467 return c & 0x0F;
15468 }
15469 if ((c & 0xF8) == 0xF0) {
15470 return c & 0x07;
15471 }
15472 CATCH_INTERNAL_ERROR("Invalid multibyte utf-8 start byte encountered");
15473 }
15474
hexEscapeChar(std::ostream & os,unsigned char c)15475 void hexEscapeChar(std::ostream& os, unsigned char c) {
15476 std::ios_base::fmtflags f(os.flags());
15477 os << "\\x"
15478 << std::uppercase << std::hex << std::setfill('0') << std::setw(2)
15479 << static_cast<int>(c);
15480 os.flags(f);
15481 }
15482
shouldNewline(XmlFormatting fmt)15483 bool shouldNewline(XmlFormatting fmt) {
15484 return !!(static_cast<std::underlying_type<XmlFormatting>::type>(fmt & XmlFormatting::Newline));
15485 }
15486
shouldIndent(XmlFormatting fmt)15487 bool shouldIndent(XmlFormatting fmt) {
15488 return !!(static_cast<std::underlying_type<XmlFormatting>::type>(fmt & XmlFormatting::Indent));
15489 }
15490
15491 } // anonymous namespace
15492
operator |(XmlFormatting lhs,XmlFormatting rhs)15493 XmlFormatting operator | (XmlFormatting lhs, XmlFormatting rhs) {
15494 return static_cast<XmlFormatting>(
15495 static_cast<std::underlying_type<XmlFormatting>::type>(lhs) |
15496 static_cast<std::underlying_type<XmlFormatting>::type>(rhs)
15497 );
15498 }
15499
operator &(XmlFormatting lhs,XmlFormatting rhs)15500 XmlFormatting operator & (XmlFormatting lhs, XmlFormatting rhs) {
15501 return static_cast<XmlFormatting>(
15502 static_cast<std::underlying_type<XmlFormatting>::type>(lhs) &
15503 static_cast<std::underlying_type<XmlFormatting>::type>(rhs)
15504 );
15505 }
15506
XmlEncode(std::string const & str,ForWhat forWhat)15507 XmlEncode::XmlEncode( std::string const& str, ForWhat forWhat )
15508 : m_str( str ),
15509 m_forWhat( forWhat )
15510 {}
15511
encodeTo(std::ostream & os) const15512 void XmlEncode::encodeTo( std::ostream& os ) const {
15513 // Apostrophe escaping not necessary if we always use " to write attributes
15514 // (see: http://www.w3.org/TR/xml/#syntax)
15515
15516 for( std::size_t idx = 0; idx < m_str.size(); ++ idx ) {
15517 unsigned char c = m_str[idx];
15518 switch (c) {
15519 case '<': os << "<"; break;
15520 case '&': os << "&"; break;
15521
15522 case '>':
15523 // See: http://www.w3.org/TR/xml/#syntax
15524 if (idx > 2 && m_str[idx - 1] == ']' && m_str[idx - 2] == ']')
15525 os << ">";
15526 else
15527 os << c;
15528 break;
15529
15530 case '\"':
15531 if (m_forWhat == ForAttributes)
15532 os << """;
15533 else
15534 os << c;
15535 break;
15536
15537 default:
15538 // Check for control characters and invalid utf-8
15539
15540 // Escape control characters in standard ascii
15541 // see http://stackoverflow.com/questions/404107/why-are-control-characters-illegal-in-xml-1-0
15542 if (c < 0x09 || (c > 0x0D && c < 0x20) || c == 0x7F) {
15543 hexEscapeChar(os, c);
15544 break;
15545 }
15546
15547 // Plain ASCII: Write it to stream
15548 if (c < 0x7F) {
15549 os << c;
15550 break;
15551 }
15552
15553 // UTF-8 territory
15554 // Check if the encoding is valid and if it is not, hex escape bytes.
15555 // Important: We do not check the exact decoded values for validity, only the encoding format
15556 // First check that this bytes is a valid lead byte:
15557 // This means that it is not encoded as 1111 1XXX
15558 // Or as 10XX XXXX
15559 if (c < 0xC0 ||
15560 c >= 0xF8) {
15561 hexEscapeChar(os, c);
15562 break;
15563 }
15564
15565 auto encBytes = trailingBytes(c);
15566 // Are there enough bytes left to avoid accessing out-of-bounds memory?
15567 if (idx + encBytes - 1 >= m_str.size()) {
15568 hexEscapeChar(os, c);
15569 break;
15570 }
15571 // The header is valid, check data
15572 // The next encBytes bytes must together be a valid utf-8
15573 // This means: bitpattern 10XX XXXX and the extracted value is sane (ish)
15574 bool valid = true;
15575 uint32_t value = headerValue(c);
15576 for (std::size_t n = 1; n < encBytes; ++n) {
15577 unsigned char nc = m_str[idx + n];
15578 valid &= ((nc & 0xC0) == 0x80);
15579 value = (value << 6) | (nc & 0x3F);
15580 }
15581
15582 if (
15583 // Wrong bit pattern of following bytes
15584 (!valid) ||
15585 // Overlong encodings
15586 (value < 0x80) ||
15587 (0x80 <= value && value < 0x800 && encBytes > 2) ||
15588 (0x800 < value && value < 0x10000 && encBytes > 3) ||
15589 // Encoded value out of range
15590 (value >= 0x110000)
15591 ) {
15592 hexEscapeChar(os, c);
15593 break;
15594 }
15595
15596 // If we got here, this is in fact a valid(ish) utf-8 sequence
15597 for (std::size_t n = 0; n < encBytes; ++n) {
15598 os << m_str[idx + n];
15599 }
15600 idx += encBytes - 1;
15601 break;
15602 }
15603 }
15604 }
15605
operator <<(std::ostream & os,XmlEncode const & xmlEncode)15606 std::ostream& operator << ( std::ostream& os, XmlEncode const& xmlEncode ) {
15607 xmlEncode.encodeTo( os );
15608 return os;
15609 }
15610
ScopedElement(XmlWriter * writer,XmlFormatting fmt)15611 XmlWriter::ScopedElement::ScopedElement( XmlWriter* writer, XmlFormatting fmt )
15612 : m_writer( writer ),
15613 m_fmt(fmt)
15614 {}
15615
ScopedElement(ScopedElement && other)15616 XmlWriter::ScopedElement::ScopedElement( ScopedElement&& other ) noexcept
15617 : m_writer( other.m_writer ),
15618 m_fmt(other.m_fmt)
15619 {
15620 other.m_writer = nullptr;
15621 other.m_fmt = XmlFormatting::None;
15622 }
operator =(ScopedElement && other)15623 XmlWriter::ScopedElement& XmlWriter::ScopedElement::operator=( ScopedElement&& other ) noexcept {
15624 if ( m_writer ) {
15625 m_writer->endElement();
15626 }
15627 m_writer = other.m_writer;
15628 other.m_writer = nullptr;
15629 m_fmt = other.m_fmt;
15630 other.m_fmt = XmlFormatting::None;
15631 return *this;
15632 }
15633
~ScopedElement()15634 XmlWriter::ScopedElement::~ScopedElement() {
15635 if (m_writer) {
15636 m_writer->endElement(m_fmt);
15637 }
15638 }
15639
writeText(std::string const & text,XmlFormatting fmt)15640 XmlWriter::ScopedElement& XmlWriter::ScopedElement::writeText( std::string const& text, XmlFormatting fmt ) {
15641 m_writer->writeText( text, fmt );
15642 return *this;
15643 }
15644
XmlWriter(std::ostream & os)15645 XmlWriter::XmlWriter( std::ostream& os ) : m_os( os )
15646 {
15647 writeDeclaration();
15648 }
15649
~XmlWriter()15650 XmlWriter::~XmlWriter() {
15651 while (!m_tags.empty()) {
15652 endElement();
15653 }
15654 newlineIfNecessary();
15655 }
15656
startElement(std::string const & name,XmlFormatting fmt)15657 XmlWriter& XmlWriter::startElement( std::string const& name, XmlFormatting fmt ) {
15658 ensureTagClosed();
15659 newlineIfNecessary();
15660 if (shouldIndent(fmt)) {
15661 m_os << m_indent;
15662 m_indent += " ";
15663 }
15664 m_os << '<' << name;
15665 m_tags.push_back( name );
15666 m_tagIsOpen = true;
15667 applyFormatting(fmt);
15668 return *this;
15669 }
15670
scopedElement(std::string const & name,XmlFormatting fmt)15671 XmlWriter::ScopedElement XmlWriter::scopedElement( std::string const& name, XmlFormatting fmt ) {
15672 ScopedElement scoped( this, fmt );
15673 startElement( name, fmt );
15674 return scoped;
15675 }
15676
endElement(XmlFormatting fmt)15677 XmlWriter& XmlWriter::endElement(XmlFormatting fmt) {
15678 m_indent = m_indent.substr(0, m_indent.size() - 2);
15679
15680 if( m_tagIsOpen ) {
15681 m_os << "/>";
15682 m_tagIsOpen = false;
15683 } else {
15684 newlineIfNecessary();
15685 if (shouldIndent(fmt)) {
15686 m_os << m_indent;
15687 }
15688 m_os << "</" << m_tags.back() << ">";
15689 }
15690 m_os << std::flush;
15691 applyFormatting(fmt);
15692 m_tags.pop_back();
15693 return *this;
15694 }
15695
writeAttribute(std::string const & name,std::string const & attribute)15696 XmlWriter& XmlWriter::writeAttribute( std::string const& name, std::string const& attribute ) {
15697 if( !name.empty() && !attribute.empty() )
15698 m_os << ' ' << name << "=\"" << XmlEncode( attribute, XmlEncode::ForAttributes ) << '"';
15699 return *this;
15700 }
15701
writeAttribute(std::string const & name,bool attribute)15702 XmlWriter& XmlWriter::writeAttribute( std::string const& name, bool attribute ) {
15703 m_os << ' ' << name << "=\"" << ( attribute ? "true" : "false" ) << '"';
15704 return *this;
15705 }
15706
writeText(std::string const & text,XmlFormatting fmt)15707 XmlWriter& XmlWriter::writeText( std::string const& text, XmlFormatting fmt) {
15708 if( !text.empty() ){
15709 bool tagWasOpen = m_tagIsOpen;
15710 ensureTagClosed();
15711 if (tagWasOpen && shouldIndent(fmt)) {
15712 m_os << m_indent;
15713 }
15714 m_os << XmlEncode( text );
15715 applyFormatting(fmt);
15716 }
15717 return *this;
15718 }
15719
writeComment(std::string const & text,XmlFormatting fmt)15720 XmlWriter& XmlWriter::writeComment( std::string const& text, XmlFormatting fmt) {
15721 ensureTagClosed();
15722 if (shouldIndent(fmt)) {
15723 m_os << m_indent;
15724 }
15725 m_os << "<!--" << text << "-->";
15726 applyFormatting(fmt);
15727 return *this;
15728 }
15729
writeStylesheetRef(std::string const & url)15730 void XmlWriter::writeStylesheetRef( std::string const& url ) {
15731 m_os << "<?xml-stylesheet type=\"text/xsl\" href=\"" << url << "\"?>\n";
15732 }
15733
writeBlankLine()15734 XmlWriter& XmlWriter::writeBlankLine() {
15735 ensureTagClosed();
15736 m_os << '\n';
15737 return *this;
15738 }
15739
ensureTagClosed()15740 void XmlWriter::ensureTagClosed() {
15741 if( m_tagIsOpen ) {
15742 m_os << '>' << std::flush;
15743 newlineIfNecessary();
15744 m_tagIsOpen = false;
15745 }
15746 }
15747
applyFormatting(XmlFormatting fmt)15748 void XmlWriter::applyFormatting(XmlFormatting fmt) {
15749 m_needsNewline = shouldNewline(fmt);
15750 }
15751
writeDeclaration()15752 void XmlWriter::writeDeclaration() {
15753 m_os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
15754 }
15755
newlineIfNecessary()15756 void XmlWriter::newlineIfNecessary() {
15757 if( m_needsNewline ) {
15758 m_os << std::endl;
15759 m_needsNewline = false;
15760 }
15761 }
15762 }
15763 // end catch_xmlwriter.cpp
15764 // start catch_reporter_bases.cpp
15765
15766 #include <cstring>
15767 #include <cfloat>
15768 #include <cstdio>
15769 #include <cassert>
15770 #include <memory>
15771
15772 namespace Catch {
prepareExpandedExpression(AssertionResult & result)15773 void prepareExpandedExpression(AssertionResult& result) {
15774 result.getExpandedExpression();
15775 }
15776
15777 // Because formatting using c++ streams is stateful, drop down to C is required
15778 // Alternatively we could use stringstream, but its performance is... not good.
getFormattedDuration(double duration)15779 std::string getFormattedDuration( double duration ) {
15780 // Max exponent + 1 is required to represent the whole part
15781 // + 1 for decimal point
15782 // + 3 for the 3 decimal places
15783 // + 1 for null terminator
15784 const std::size_t maxDoubleSize = DBL_MAX_10_EXP + 1 + 1 + 3 + 1;
15785 char buffer[maxDoubleSize];
15786
15787 // Save previous errno, to prevent sprintf from overwriting it
15788 ErrnoGuard guard;
15789 #ifdef _MSC_VER
15790 sprintf_s(buffer, "%.3f", duration);
15791 #else
15792 std::sprintf(buffer, "%.3f", duration);
15793 #endif
15794 return std::string(buffer);
15795 }
15796
shouldShowDuration(IConfig const & config,double duration)15797 bool shouldShowDuration( IConfig const& config, double duration ) {
15798 if ( config.showDurations() == ShowDurations::Always ) {
15799 return true;
15800 }
15801 if ( config.showDurations() == ShowDurations::Never ) {
15802 return false;
15803 }
15804 const double min = config.minDuration();
15805 return min >= 0 && duration >= min;
15806 }
15807
serializeFilters(std::vector<std::string> const & container)15808 std::string serializeFilters( std::vector<std::string> const& container ) {
15809 ReusableStringStream oss;
15810 bool first = true;
15811 for (auto&& filter : container)
15812 {
15813 if (!first)
15814 oss << ' ';
15815 else
15816 first = false;
15817
15818 oss << filter;
15819 }
15820 return oss.str();
15821 }
15822
TestEventListenerBase(ReporterConfig const & _config)15823 TestEventListenerBase::TestEventListenerBase(ReporterConfig const & _config)
15824 :StreamingReporterBase(_config) {}
15825
getSupportedVerbosities()15826 std::set<Verbosity> TestEventListenerBase::getSupportedVerbosities() {
15827 return { Verbosity::Quiet, Verbosity::Normal, Verbosity::High };
15828 }
15829
assertionStarting(AssertionInfo const &)15830 void TestEventListenerBase::assertionStarting(AssertionInfo const &) {}
15831
assertionEnded(AssertionStats const &)15832 bool TestEventListenerBase::assertionEnded(AssertionStats const &) {
15833 return false;
15834 }
15835
15836 } // end namespace Catch
15837 // end catch_reporter_bases.cpp
15838 // start catch_reporter_compact.cpp
15839
15840 namespace {
15841
15842 #ifdef CATCH_PLATFORM_MAC
failedString()15843 const char* failedString() { return "FAILED"; }
passedString()15844 const char* passedString() { return "PASSED"; }
15845 #else
15846 const char* failedString() { return "failed"; }
15847 const char* passedString() { return "passed"; }
15848 #endif
15849
15850 // Colour::LightGrey
dimColour()15851 Catch::Colour::Code dimColour() { return Catch::Colour::FileName; }
15852
bothOrAll(std::size_t count)15853 std::string bothOrAll( std::size_t count ) {
15854 return count == 1 ? std::string() :
15855 count == 2 ? "both " : "all " ;
15856 }
15857
15858 } // anon namespace
15859
15860 namespace Catch {
15861 namespace {
15862 // Colour, message variants:
15863 // - white: No tests ran.
15864 // - red: Failed [both/all] N test cases, failed [both/all] M assertions.
15865 // - white: Passed [both/all] N test cases (no assertions).
15866 // - red: Failed N tests cases, failed M assertions.
15867 // - green: Passed [both/all] N tests cases with M assertions.
printTotals(std::ostream & out,const Totals & totals)15868 void printTotals(std::ostream& out, const Totals& totals) {
15869 if (totals.testCases.total() == 0) {
15870 out << "No tests ran.";
15871 } else if (totals.testCases.failed == totals.testCases.total()) {
15872 Colour colour(Colour::ResultError);
15873 const std::string qualify_assertions_failed =
15874 totals.assertions.failed == totals.assertions.total() ?
15875 bothOrAll(totals.assertions.failed) : std::string();
15876 out <<
15877 "Failed " << bothOrAll(totals.testCases.failed)
15878 << pluralise(totals.testCases.failed, "test case") << ", "
15879 "failed " << qualify_assertions_failed <<
15880 pluralise(totals.assertions.failed, "assertion") << '.';
15881 } else if (totals.assertions.total() == 0) {
15882 out <<
15883 "Passed " << bothOrAll(totals.testCases.total())
15884 << pluralise(totals.testCases.total(), "test case")
15885 << " (no assertions).";
15886 } else if (totals.assertions.failed) {
15887 Colour colour(Colour::ResultError);
15888 out <<
15889 "Failed " << pluralise(totals.testCases.failed, "test case") << ", "
15890 "failed " << pluralise(totals.assertions.failed, "assertion") << '.';
15891 } else {
15892 Colour colour(Colour::ResultSuccess);
15893 out <<
15894 "Passed " << bothOrAll(totals.testCases.passed)
15895 << pluralise(totals.testCases.passed, "test case") <<
15896 " with " << pluralise(totals.assertions.passed, "assertion") << '.';
15897 }
15898 }
15899
15900 // Implementation of CompactReporter formatting
15901 class AssertionPrinter {
15902 public:
15903 AssertionPrinter& operator= (AssertionPrinter const&) = delete;
15904 AssertionPrinter(AssertionPrinter const&) = delete;
AssertionPrinter(std::ostream & _stream,AssertionStats const & _stats,bool _printInfoMessages)15905 AssertionPrinter(std::ostream& _stream, AssertionStats const& _stats, bool _printInfoMessages)
15906 : stream(_stream)
15907 , result(_stats.assertionResult)
15908 , messages(_stats.infoMessages)
15909 , itMessage(_stats.infoMessages.begin())
15910 , printInfoMessages(_printInfoMessages) {}
15911
print()15912 void print() {
15913 printSourceInfo();
15914
15915 itMessage = messages.begin();
15916
15917 switch (result.getResultType()) {
15918 case ResultWas::Ok:
15919 printResultType(Colour::ResultSuccess, passedString());
15920 printOriginalExpression();
15921 printReconstructedExpression();
15922 if (!result.hasExpression())
15923 printRemainingMessages(Colour::None);
15924 else
15925 printRemainingMessages();
15926 break;
15927 case ResultWas::ExpressionFailed:
15928 if (result.isOk())
15929 printResultType(Colour::ResultSuccess, failedString() + std::string(" - but was ok"));
15930 else
15931 printResultType(Colour::Error, failedString());
15932 printOriginalExpression();
15933 printReconstructedExpression();
15934 printRemainingMessages();
15935 break;
15936 case ResultWas::ThrewException:
15937 printResultType(Colour::Error, failedString());
15938 printIssue("unexpected exception with message:");
15939 printMessage();
15940 printExpressionWas();
15941 printRemainingMessages();
15942 break;
15943 case ResultWas::FatalErrorCondition:
15944 printResultType(Colour::Error, failedString());
15945 printIssue("fatal error condition with message:");
15946 printMessage();
15947 printExpressionWas();
15948 printRemainingMessages();
15949 break;
15950 case ResultWas::DidntThrowException:
15951 printResultType(Colour::Error, failedString());
15952 printIssue("expected exception, got none");
15953 printExpressionWas();
15954 printRemainingMessages();
15955 break;
15956 case ResultWas::Info:
15957 printResultType(Colour::None, "info");
15958 printMessage();
15959 printRemainingMessages();
15960 break;
15961 case ResultWas::Warning:
15962 printResultType(Colour::None, "warning");
15963 printMessage();
15964 printRemainingMessages();
15965 break;
15966 case ResultWas::ExplicitFailure:
15967 printResultType(Colour::Error, failedString());
15968 printIssue("explicitly");
15969 printRemainingMessages(Colour::None);
15970 break;
15971 // These cases are here to prevent compiler warnings
15972 case ResultWas::Unknown:
15973 case ResultWas::FailureBit:
15974 case ResultWas::Exception:
15975 printResultType(Colour::Error, "** internal error **");
15976 break;
15977 }
15978 }
15979
15980 private:
printSourceInfo() const15981 void printSourceInfo() const {
15982 Colour colourGuard(Colour::FileName);
15983 stream << result.getSourceInfo() << ':';
15984 }
15985
printResultType(Colour::Code colour,std::string const & passOrFail) const15986 void printResultType(Colour::Code colour, std::string const& passOrFail) const {
15987 if (!passOrFail.empty()) {
15988 {
15989 Colour colourGuard(colour);
15990 stream << ' ' << passOrFail;
15991 }
15992 stream << ':';
15993 }
15994 }
15995
printIssue(std::string const & issue) const15996 void printIssue(std::string const& issue) const {
15997 stream << ' ' << issue;
15998 }
15999
printExpressionWas()16000 void printExpressionWas() {
16001 if (result.hasExpression()) {
16002 stream << ';';
16003 {
16004 Colour colour(dimColour());
16005 stream << " expression was:";
16006 }
16007 printOriginalExpression();
16008 }
16009 }
16010
printOriginalExpression() const16011 void printOriginalExpression() const {
16012 if (result.hasExpression()) {
16013 stream << ' ' << result.getExpression();
16014 }
16015 }
16016
printReconstructedExpression() const16017 void printReconstructedExpression() const {
16018 if (result.hasExpandedExpression()) {
16019 {
16020 Colour colour(dimColour());
16021 stream << " for: ";
16022 }
16023 stream << result.getExpandedExpression();
16024 }
16025 }
16026
printMessage()16027 void printMessage() {
16028 if (itMessage != messages.end()) {
16029 stream << " '" << itMessage->message << '\'';
16030 ++itMessage;
16031 }
16032 }
16033
printRemainingMessages(Colour::Code colour=dimColour ())16034 void printRemainingMessages(Colour::Code colour = dimColour()) {
16035 if (itMessage == messages.end())
16036 return;
16037
16038 const auto itEnd = messages.cend();
16039 const auto N = static_cast<std::size_t>(std::distance(itMessage, itEnd));
16040
16041 {
16042 Colour colourGuard(colour);
16043 stream << " with " << pluralise(N, "message") << ':';
16044 }
16045
16046 while (itMessage != itEnd) {
16047 // If this assertion is a warning ignore any INFO messages
16048 if (printInfoMessages || itMessage->type != ResultWas::Info) {
16049 printMessage();
16050 if (itMessage != itEnd) {
16051 Colour colourGuard(dimColour());
16052 stream << " and";
16053 }
16054 continue;
16055 }
16056 ++itMessage;
16057 }
16058 }
16059
16060 private:
16061 std::ostream& stream;
16062 AssertionResult const& result;
16063 std::vector<MessageInfo> messages;
16064 std::vector<MessageInfo>::const_iterator itMessage;
16065 bool printInfoMessages;
16066 };
16067
16068 } // anon namespace
16069
getDescription()16070 std::string CompactReporter::getDescription() {
16071 return "Reports test results on a single line, suitable for IDEs";
16072 }
16073
noMatchingTestCases(std::string const & spec)16074 void CompactReporter::noMatchingTestCases( std::string const& spec ) {
16075 stream << "No test cases matched '" << spec << '\'' << std::endl;
16076 }
16077
assertionStarting(AssertionInfo const &)16078 void CompactReporter::assertionStarting( AssertionInfo const& ) {}
16079
assertionEnded(AssertionStats const & _assertionStats)16080 bool CompactReporter::assertionEnded( AssertionStats const& _assertionStats ) {
16081 AssertionResult const& result = _assertionStats.assertionResult;
16082
16083 bool printInfoMessages = true;
16084
16085 // Drop out if result was successful and we're not printing those
16086 if( !m_config->includeSuccessfulResults() && result.isOk() ) {
16087 if( result.getResultType() != ResultWas::Warning )
16088 return false;
16089 printInfoMessages = false;
16090 }
16091
16092 AssertionPrinter printer( stream, _assertionStats, printInfoMessages );
16093 printer.print();
16094
16095 stream << std::endl;
16096 return true;
16097 }
16098
sectionEnded(SectionStats const & _sectionStats)16099 void CompactReporter::sectionEnded(SectionStats const& _sectionStats) {
16100 double dur = _sectionStats.durationInSeconds;
16101 if ( shouldShowDuration( *m_config, dur ) ) {
16102 stream << getFormattedDuration( dur ) << " s: " << _sectionStats.sectionInfo.name << std::endl;
16103 }
16104 }
16105
testRunEnded(TestRunStats const & _testRunStats)16106 void CompactReporter::testRunEnded( TestRunStats const& _testRunStats ) {
16107 printTotals( stream, _testRunStats.totals );
16108 stream << '\n' << std::endl;
16109 StreamingReporterBase::testRunEnded( _testRunStats );
16110 }
16111
~CompactReporter()16112 CompactReporter::~CompactReporter() {}
16113
16114 CATCH_REGISTER_REPORTER( "compact", CompactReporter )
16115
16116 } // end namespace Catch
16117 // end catch_reporter_compact.cpp
16118 // start catch_reporter_console.cpp
16119
16120 #include <cfloat>
16121 #include <cstdio>
16122
16123 #if defined(_MSC_VER)
16124 #pragma warning(push)
16125 #pragma warning(disable:4061) // Not all labels are EXPLICITLY handled in switch
16126 // Note that 4062 (not all labels are handled and default is missing) is enabled
16127 #endif
16128
16129 #if defined(__clang__)
16130 # pragma clang diagnostic push
16131 // For simplicity, benchmarking-only helpers are always enabled
16132 # pragma clang diagnostic ignored "-Wunused-function"
16133 #endif
16134
16135 namespace Catch {
16136
16137 namespace {
16138
16139 // Formatter impl for ConsoleReporter
16140 class ConsoleAssertionPrinter {
16141 public:
16142 ConsoleAssertionPrinter& operator= (ConsoleAssertionPrinter const&) = delete;
16143 ConsoleAssertionPrinter(ConsoleAssertionPrinter const&) = delete;
ConsoleAssertionPrinter(std::ostream & _stream,AssertionStats const & _stats,bool _printInfoMessages)16144 ConsoleAssertionPrinter(std::ostream& _stream, AssertionStats const& _stats, bool _printInfoMessages)
16145 : stream(_stream),
16146 stats(_stats),
16147 result(_stats.assertionResult),
16148 colour(Colour::None),
16149 message(result.getMessage()),
16150 messages(_stats.infoMessages),
16151 printInfoMessages(_printInfoMessages) {
16152 switch (result.getResultType()) {
16153 case ResultWas::Ok:
16154 colour = Colour::Success;
16155 passOrFail = "PASSED";
16156 //if( result.hasMessage() )
16157 if (_stats.infoMessages.size() == 1)
16158 messageLabel = "with message";
16159 if (_stats.infoMessages.size() > 1)
16160 messageLabel = "with messages";
16161 break;
16162 case ResultWas::ExpressionFailed:
16163 if (result.isOk()) {
16164 colour = Colour::Success;
16165 passOrFail = "FAILED - but was ok";
16166 } else {
16167 colour = Colour::Error;
16168 passOrFail = "FAILED";
16169 }
16170 if (_stats.infoMessages.size() == 1)
16171 messageLabel = "with message";
16172 if (_stats.infoMessages.size() > 1)
16173 messageLabel = "with messages";
16174 break;
16175 case ResultWas::ThrewException:
16176 colour = Colour::Error;
16177 passOrFail = "FAILED";
16178 messageLabel = "due to unexpected exception with ";
16179 if (_stats.infoMessages.size() == 1)
16180 messageLabel += "message";
16181 if (_stats.infoMessages.size() > 1)
16182 messageLabel += "messages";
16183 break;
16184 case ResultWas::FatalErrorCondition:
16185 colour = Colour::Error;
16186 passOrFail = "FAILED";
16187 messageLabel = "due to a fatal error condition";
16188 break;
16189 case ResultWas::DidntThrowException:
16190 colour = Colour::Error;
16191 passOrFail = "FAILED";
16192 messageLabel = "because no exception was thrown where one was expected";
16193 break;
16194 case ResultWas::Info:
16195 messageLabel = "info";
16196 break;
16197 case ResultWas::Warning:
16198 messageLabel = "warning";
16199 break;
16200 case ResultWas::ExplicitFailure:
16201 passOrFail = "FAILED";
16202 colour = Colour::Error;
16203 if (_stats.infoMessages.size() == 1)
16204 messageLabel = "explicitly with message";
16205 if (_stats.infoMessages.size() > 1)
16206 messageLabel = "explicitly with messages";
16207 break;
16208 // These cases are here to prevent compiler warnings
16209 case ResultWas::Unknown:
16210 case ResultWas::FailureBit:
16211 case ResultWas::Exception:
16212 passOrFail = "** internal error **";
16213 colour = Colour::Error;
16214 break;
16215 }
16216 }
16217
print() const16218 void print() const {
16219 printSourceInfo();
16220 if (stats.totals.assertions.total() > 0) {
16221 printResultType();
16222 printOriginalExpression();
16223 printReconstructedExpression();
16224 } else {
16225 stream << '\n';
16226 }
16227 printMessage();
16228 }
16229
16230 private:
printResultType() const16231 void printResultType() const {
16232 if (!passOrFail.empty()) {
16233 Colour colourGuard(colour);
16234 stream << passOrFail << ":\n";
16235 }
16236 }
printOriginalExpression() const16237 void printOriginalExpression() const {
16238 if (result.hasExpression()) {
16239 Colour colourGuard(Colour::OriginalExpression);
16240 stream << " ";
16241 stream << result.getExpressionInMacro();
16242 stream << '\n';
16243 }
16244 }
printReconstructedExpression() const16245 void printReconstructedExpression() const {
16246 if (result.hasExpandedExpression()) {
16247 stream << "with expansion:\n";
16248 Colour colourGuard(Colour::ReconstructedExpression);
16249 stream << Column(result.getExpandedExpression()).indent(2) << '\n';
16250 }
16251 }
printMessage() const16252 void printMessage() const {
16253 if (!messageLabel.empty())
16254 stream << messageLabel << ':' << '\n';
16255 for (auto const& msg : messages) {
16256 // If this assertion is a warning ignore any INFO messages
16257 if (printInfoMessages || msg.type != ResultWas::Info)
16258 stream << Column(msg.message).indent(2) << '\n';
16259 }
16260 }
printSourceInfo() const16261 void printSourceInfo() const {
16262 Colour colourGuard(Colour::FileName);
16263 stream << result.getSourceInfo() << ": ";
16264 }
16265
16266 std::ostream& stream;
16267 AssertionStats const& stats;
16268 AssertionResult const& result;
16269 Colour::Code colour;
16270 std::string passOrFail;
16271 std::string messageLabel;
16272 std::string message;
16273 std::vector<MessageInfo> messages;
16274 bool printInfoMessages;
16275 };
16276
makeRatio(std::size_t number,std::size_t total)16277 std::size_t makeRatio(std::size_t number, std::size_t total) {
16278 std::size_t ratio = total > 0 ? CATCH_CONFIG_CONSOLE_WIDTH * number / total : 0;
16279 return (ratio == 0 && number > 0) ? 1 : ratio;
16280 }
16281
findMax(std::size_t & i,std::size_t & j,std::size_t & k)16282 std::size_t& findMax(std::size_t& i, std::size_t& j, std::size_t& k) {
16283 if (i > j && i > k)
16284 return i;
16285 else if (j > k)
16286 return j;
16287 else
16288 return k;
16289 }
16290
16291 struct ColumnInfo {
16292 enum Justification { Left, Right };
16293 std::string name;
16294 int width;
16295 Justification justification;
16296 };
16297 struct ColumnBreak {};
16298 struct RowBreak {};
16299
16300 class Duration {
16301 enum class Unit {
16302 Auto,
16303 Nanoseconds,
16304 Microseconds,
16305 Milliseconds,
16306 Seconds,
16307 Minutes
16308 };
16309 static const uint64_t s_nanosecondsInAMicrosecond = 1000;
16310 static const uint64_t s_nanosecondsInAMillisecond = 1000 * s_nanosecondsInAMicrosecond;
16311 static const uint64_t s_nanosecondsInASecond = 1000 * s_nanosecondsInAMillisecond;
16312 static const uint64_t s_nanosecondsInAMinute = 60 * s_nanosecondsInASecond;
16313
16314 double m_inNanoseconds;
16315 Unit m_units;
16316
16317 public:
Duration(double inNanoseconds,Unit units=Unit::Auto)16318 explicit Duration(double inNanoseconds, Unit units = Unit::Auto)
16319 : m_inNanoseconds(inNanoseconds),
16320 m_units(units) {
16321 if (m_units == Unit::Auto) {
16322 if (m_inNanoseconds < s_nanosecondsInAMicrosecond)
16323 m_units = Unit::Nanoseconds;
16324 else if (m_inNanoseconds < s_nanosecondsInAMillisecond)
16325 m_units = Unit::Microseconds;
16326 else if (m_inNanoseconds < s_nanosecondsInASecond)
16327 m_units = Unit::Milliseconds;
16328 else if (m_inNanoseconds < s_nanosecondsInAMinute)
16329 m_units = Unit::Seconds;
16330 else
16331 m_units = Unit::Minutes;
16332 }
16333
16334 }
16335
value() const16336 auto value() const -> double {
16337 switch (m_units) {
16338 case Unit::Microseconds:
16339 return m_inNanoseconds / static_cast<double>(s_nanosecondsInAMicrosecond);
16340 case Unit::Milliseconds:
16341 return m_inNanoseconds / static_cast<double>(s_nanosecondsInAMillisecond);
16342 case Unit::Seconds:
16343 return m_inNanoseconds / static_cast<double>(s_nanosecondsInASecond);
16344 case Unit::Minutes:
16345 return m_inNanoseconds / static_cast<double>(s_nanosecondsInAMinute);
16346 default:
16347 return m_inNanoseconds;
16348 }
16349 }
unitsAsString() const16350 auto unitsAsString() const -> std::string {
16351 switch (m_units) {
16352 case Unit::Nanoseconds:
16353 return "ns";
16354 case Unit::Microseconds:
16355 return "us";
16356 case Unit::Milliseconds:
16357 return "ms";
16358 case Unit::Seconds:
16359 return "s";
16360 case Unit::Minutes:
16361 return "m";
16362 default:
16363 return "** internal error **";
16364 }
16365
16366 }
operator <<(std::ostream & os,Duration const & duration)16367 friend auto operator << (std::ostream& os, Duration const& duration) -> std::ostream& {
16368 return os << duration.value() << ' ' << duration.unitsAsString();
16369 }
16370 };
16371 } // end anon namespace
16372
16373 class TablePrinter {
16374 std::ostream& m_os;
16375 std::vector<ColumnInfo> m_columnInfos;
16376 std::ostringstream m_oss;
16377 int m_currentColumn = -1;
16378 bool m_isOpen = false;
16379
16380 public:
TablePrinter(std::ostream & os,std::vector<ColumnInfo> columnInfos)16381 TablePrinter( std::ostream& os, std::vector<ColumnInfo> columnInfos )
16382 : m_os( os ),
16383 m_columnInfos( std::move( columnInfos ) ) {}
16384
columnInfos() const16385 auto columnInfos() const -> std::vector<ColumnInfo> const& {
16386 return m_columnInfos;
16387 }
16388
open()16389 void open() {
16390 if (!m_isOpen) {
16391 m_isOpen = true;
16392 *this << RowBreak();
16393
16394 Columns headerCols;
16395 Spacer spacer(2);
16396 for (auto const& info : m_columnInfos) {
16397 headerCols += Column(info.name).width(static_cast<std::size_t>(info.width - 2));
16398 headerCols += spacer;
16399 }
16400 m_os << headerCols << '\n';
16401
16402 m_os << Catch::getLineOfChars<'-'>() << '\n';
16403 }
16404 }
close()16405 void close() {
16406 if (m_isOpen) {
16407 *this << RowBreak();
16408 m_os << std::endl;
16409 m_isOpen = false;
16410 }
16411 }
16412
16413 template<typename T>
operator <<(TablePrinter & tp,T const & value)16414 friend TablePrinter& operator << (TablePrinter& tp, T const& value) {
16415 tp.m_oss << value;
16416 return tp;
16417 }
16418
operator <<(TablePrinter & tp,ColumnBreak)16419 friend TablePrinter& operator << (TablePrinter& tp, ColumnBreak) {
16420 auto colStr = tp.m_oss.str();
16421 const auto strSize = colStr.size();
16422 tp.m_oss.str("");
16423 tp.open();
16424 if (tp.m_currentColumn == static_cast<int>(tp.m_columnInfos.size() - 1)) {
16425 tp.m_currentColumn = -1;
16426 tp.m_os << '\n';
16427 }
16428 tp.m_currentColumn++;
16429
16430 auto colInfo = tp.m_columnInfos[tp.m_currentColumn];
16431 auto padding = (strSize + 1 < static_cast<std::size_t>(colInfo.width))
16432 ? std::string(colInfo.width - (strSize + 1), ' ')
16433 : std::string();
16434 if (colInfo.justification == ColumnInfo::Left)
16435 tp.m_os << colStr << padding << ' ';
16436 else
16437 tp.m_os << padding << colStr << ' ';
16438 return tp;
16439 }
16440
operator <<(TablePrinter & tp,RowBreak)16441 friend TablePrinter& operator << (TablePrinter& tp, RowBreak) {
16442 if (tp.m_currentColumn > 0) {
16443 tp.m_os << '\n';
16444 tp.m_currentColumn = -1;
16445 }
16446 return tp;
16447 }
16448 };
16449
ConsoleReporter(ReporterConfig const & config)16450 ConsoleReporter::ConsoleReporter(ReporterConfig const& config)
16451 : StreamingReporterBase(config),
16452 m_tablePrinter(new TablePrinter(config.stream(),
16453 [&config]() -> std::vector<ColumnInfo> {
16454 if (config.fullConfig()->benchmarkNoAnalysis())
16455 {
16456 return{
16457 { "benchmark name", CATCH_CONFIG_CONSOLE_WIDTH - 43, ColumnInfo::Left },
16458 { " samples", 14, ColumnInfo::Right },
16459 { " iterations", 14, ColumnInfo::Right },
16460 { " mean", 14, ColumnInfo::Right }
16461 };
16462 }
16463 else
16464 {
16465 return{
16466 { "benchmark name", CATCH_CONFIG_CONSOLE_WIDTH - 43, ColumnInfo::Left },
16467 { "samples mean std dev", 14, ColumnInfo::Right },
16468 { "iterations low mean low std dev", 14, ColumnInfo::Right },
16469 { "estimated high mean high std dev", 14, ColumnInfo::Right }
16470 };
16471 }
16472 }())) {}
16473 ConsoleReporter::~ConsoleReporter() = default;
16474
getDescription()16475 std::string ConsoleReporter::getDescription() {
16476 return "Reports test results as plain lines of text";
16477 }
16478
noMatchingTestCases(std::string const & spec)16479 void ConsoleReporter::noMatchingTestCases(std::string const& spec) {
16480 stream << "No test cases matched '" << spec << '\'' << std::endl;
16481 }
16482
reportInvalidArguments(std::string const & arg)16483 void ConsoleReporter::reportInvalidArguments(std::string const&arg){
16484 stream << "Invalid Filter: " << arg << std::endl;
16485 }
16486
assertionStarting(AssertionInfo const &)16487 void ConsoleReporter::assertionStarting(AssertionInfo const&) {}
16488
assertionEnded(AssertionStats const & _assertionStats)16489 bool ConsoleReporter::assertionEnded(AssertionStats const& _assertionStats) {
16490 AssertionResult const& result = _assertionStats.assertionResult;
16491
16492 bool includeResults = m_config->includeSuccessfulResults() || !result.isOk();
16493
16494 // Drop out if result was successful but we're not printing them.
16495 if (!includeResults && result.getResultType() != ResultWas::Warning)
16496 return false;
16497
16498 lazyPrint();
16499
16500 ConsoleAssertionPrinter printer(stream, _assertionStats, includeResults);
16501 printer.print();
16502 stream << std::endl;
16503 return true;
16504 }
16505
sectionStarting(SectionInfo const & _sectionInfo)16506 void ConsoleReporter::sectionStarting(SectionInfo const& _sectionInfo) {
16507 m_tablePrinter->close();
16508 m_headerPrinted = false;
16509 StreamingReporterBase::sectionStarting(_sectionInfo);
16510 }
sectionEnded(SectionStats const & _sectionStats)16511 void ConsoleReporter::sectionEnded(SectionStats const& _sectionStats) {
16512 m_tablePrinter->close();
16513 if (_sectionStats.missingAssertions) {
16514 lazyPrint();
16515 Colour colour(Colour::ResultError);
16516 if (m_sectionStack.size() > 1)
16517 stream << "\nNo assertions in section";
16518 else
16519 stream << "\nNo assertions in test case";
16520 stream << " '" << _sectionStats.sectionInfo.name << "'\n" << std::endl;
16521 }
16522 double dur = _sectionStats.durationInSeconds;
16523 if (shouldShowDuration(*m_config, dur)) {
16524 stream << getFormattedDuration(dur) << " s: " << _sectionStats.sectionInfo.name << std::endl;
16525 }
16526 if (m_headerPrinted) {
16527 m_headerPrinted = false;
16528 }
16529 StreamingReporterBase::sectionEnded(_sectionStats);
16530 }
16531
16532 #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
benchmarkPreparing(std::string const & name)16533 void ConsoleReporter::benchmarkPreparing(std::string const& name) {
16534 lazyPrintWithoutClosingBenchmarkTable();
16535
16536 auto nameCol = Column(name).width(static_cast<std::size_t>(m_tablePrinter->columnInfos()[0].width - 2));
16537
16538 bool firstLine = true;
16539 for (auto line : nameCol) {
16540 if (!firstLine)
16541 (*m_tablePrinter) << ColumnBreak() << ColumnBreak() << ColumnBreak();
16542 else
16543 firstLine = false;
16544
16545 (*m_tablePrinter) << line << ColumnBreak();
16546 }
16547 }
16548
benchmarkStarting(BenchmarkInfo const & info)16549 void ConsoleReporter::benchmarkStarting(BenchmarkInfo const& info) {
16550 (*m_tablePrinter) << info.samples << ColumnBreak()
16551 << info.iterations << ColumnBreak();
16552 if (!m_config->benchmarkNoAnalysis())
16553 (*m_tablePrinter) << Duration(info.estimatedDuration) << ColumnBreak();
16554 }
benchmarkEnded(BenchmarkStats<> const & stats)16555 void ConsoleReporter::benchmarkEnded(BenchmarkStats<> const& stats) {
16556 if (m_config->benchmarkNoAnalysis())
16557 {
16558 (*m_tablePrinter) << Duration(stats.mean.point.count()) << ColumnBreak();
16559 }
16560 else
16561 {
16562 (*m_tablePrinter) << ColumnBreak()
16563 << Duration(stats.mean.point.count()) << ColumnBreak()
16564 << Duration(stats.mean.lower_bound.count()) << ColumnBreak()
16565 << Duration(stats.mean.upper_bound.count()) << ColumnBreak() << ColumnBreak()
16566 << Duration(stats.standardDeviation.point.count()) << ColumnBreak()
16567 << Duration(stats.standardDeviation.lower_bound.count()) << ColumnBreak()
16568 << Duration(stats.standardDeviation.upper_bound.count()) << ColumnBreak() << ColumnBreak() << ColumnBreak() << ColumnBreak() << ColumnBreak();
16569 }
16570 }
16571
benchmarkFailed(std::string const & error)16572 void ConsoleReporter::benchmarkFailed(std::string const& error) {
16573 Colour colour(Colour::Red);
16574 (*m_tablePrinter)
16575 << "Benchmark failed (" << error << ')'
16576 << ColumnBreak() << RowBreak();
16577 }
16578 #endif // CATCH_CONFIG_ENABLE_BENCHMARKING
16579
testCaseEnded(TestCaseStats const & _testCaseStats)16580 void ConsoleReporter::testCaseEnded(TestCaseStats const& _testCaseStats) {
16581 m_tablePrinter->close();
16582 StreamingReporterBase::testCaseEnded(_testCaseStats);
16583 m_headerPrinted = false;
16584 }
testGroupEnded(TestGroupStats const & _testGroupStats)16585 void ConsoleReporter::testGroupEnded(TestGroupStats const& _testGroupStats) {
16586 if (currentGroupInfo.used) {
16587 printSummaryDivider();
16588 stream << "Summary for group '" << _testGroupStats.groupInfo.name << "':\n";
16589 printTotals(_testGroupStats.totals);
16590 stream << '\n' << std::endl;
16591 }
16592 StreamingReporterBase::testGroupEnded(_testGroupStats);
16593 }
testRunEnded(TestRunStats const & _testRunStats)16594 void ConsoleReporter::testRunEnded(TestRunStats const& _testRunStats) {
16595 printTotalsDivider(_testRunStats.totals);
16596 printTotals(_testRunStats.totals);
16597 stream << std::endl;
16598 StreamingReporterBase::testRunEnded(_testRunStats);
16599 }
testRunStarting(TestRunInfo const & _testInfo)16600 void ConsoleReporter::testRunStarting(TestRunInfo const& _testInfo) {
16601 StreamingReporterBase::testRunStarting(_testInfo);
16602 printTestFilters();
16603 }
16604
lazyPrint()16605 void ConsoleReporter::lazyPrint() {
16606
16607 m_tablePrinter->close();
16608 lazyPrintWithoutClosingBenchmarkTable();
16609 }
16610
lazyPrintWithoutClosingBenchmarkTable()16611 void ConsoleReporter::lazyPrintWithoutClosingBenchmarkTable() {
16612
16613 if (!currentTestRunInfo.used)
16614 lazyPrintRunInfo();
16615 if (!currentGroupInfo.used)
16616 lazyPrintGroupInfo();
16617
16618 if (!m_headerPrinted) {
16619 printTestCaseAndSectionHeader();
16620 m_headerPrinted = true;
16621 }
16622 }
lazyPrintRunInfo()16623 void ConsoleReporter::lazyPrintRunInfo() {
16624 stream << '\n' << getLineOfChars<'~'>() << '\n';
16625 Colour colour(Colour::SecondaryText);
16626 stream << currentTestRunInfo->name
16627 << " is a Catch v" << libraryVersion() << " host application.\n"
16628 << "Run with -? for options\n\n";
16629
16630 if (m_config->rngSeed() != 0)
16631 stream << "Randomness seeded to: " << m_config->rngSeed() << "\n\n";
16632
16633 currentTestRunInfo.used = true;
16634 }
lazyPrintGroupInfo()16635 void ConsoleReporter::lazyPrintGroupInfo() {
16636 if (!currentGroupInfo->name.empty() && currentGroupInfo->groupsCounts > 1) {
16637 printClosedHeader("Group: " + currentGroupInfo->name);
16638 currentGroupInfo.used = true;
16639 }
16640 }
printTestCaseAndSectionHeader()16641 void ConsoleReporter::printTestCaseAndSectionHeader() {
16642 assert(!m_sectionStack.empty());
16643 printOpenHeader(currentTestCaseInfo->name);
16644
16645 if (m_sectionStack.size() > 1) {
16646 Colour colourGuard(Colour::Headers);
16647
16648 auto
16649 it = m_sectionStack.begin() + 1, // Skip first section (test case)
16650 itEnd = m_sectionStack.end();
16651 for (; it != itEnd; ++it)
16652 printHeaderString(it->name, 2);
16653 }
16654
16655 SourceLineInfo lineInfo = m_sectionStack.back().lineInfo;
16656
16657 stream << getLineOfChars<'-'>() << '\n';
16658 Colour colourGuard(Colour::FileName);
16659 stream << lineInfo << '\n';
16660 stream << getLineOfChars<'.'>() << '\n' << std::endl;
16661 }
16662
printClosedHeader(std::string const & _name)16663 void ConsoleReporter::printClosedHeader(std::string const& _name) {
16664 printOpenHeader(_name);
16665 stream << getLineOfChars<'.'>() << '\n';
16666 }
printOpenHeader(std::string const & _name)16667 void ConsoleReporter::printOpenHeader(std::string const& _name) {
16668 stream << getLineOfChars<'-'>() << '\n';
16669 {
16670 Colour colourGuard(Colour::Headers);
16671 printHeaderString(_name);
16672 }
16673 }
16674
16675 // if string has a : in first line will set indent to follow it on
16676 // subsequent lines
printHeaderString(std::string const & _string,std::size_t indent)16677 void ConsoleReporter::printHeaderString(std::string const& _string, std::size_t indent) {
16678 std::size_t i = _string.find(": ");
16679 if (i != std::string::npos)
16680 i += 2;
16681 else
16682 i = 0;
16683 stream << Column(_string).indent(indent + i).initialIndent(indent) << '\n';
16684 }
16685
16686 struct SummaryColumn {
16687
SummaryColumnCatch::SummaryColumn16688 SummaryColumn( std::string _label, Colour::Code _colour )
16689 : label( std::move( _label ) ),
16690 colour( _colour ) {}
addRowCatch::SummaryColumn16691 SummaryColumn addRow( std::size_t count ) {
16692 ReusableStringStream rss;
16693 rss << count;
16694 std::string row = rss.str();
16695 for (auto& oldRow : rows) {
16696 while (oldRow.size() < row.size())
16697 oldRow = ' ' + oldRow;
16698 while (oldRow.size() > row.size())
16699 row = ' ' + row;
16700 }
16701 rows.push_back(row);
16702 return *this;
16703 }
16704
16705 std::string label;
16706 Colour::Code colour;
16707 std::vector<std::string> rows;
16708
16709 };
16710
printTotals(Totals const & totals)16711 void ConsoleReporter::printTotals( Totals const& totals ) {
16712 if (totals.testCases.total() == 0) {
16713 stream << Colour(Colour::Warning) << "No tests ran\n";
16714 } else if (totals.assertions.total() > 0 && totals.testCases.allPassed()) {
16715 stream << Colour(Colour::ResultSuccess) << "All tests passed";
16716 stream << " ("
16717 << pluralise(totals.assertions.passed, "assertion") << " in "
16718 << pluralise(totals.testCases.passed, "test case") << ')'
16719 << '\n';
16720 } else {
16721
16722 std::vector<SummaryColumn> columns;
16723 columns.push_back(SummaryColumn("", Colour::None)
16724 .addRow(totals.testCases.total())
16725 .addRow(totals.assertions.total()));
16726 columns.push_back(SummaryColumn("passed", Colour::Success)
16727 .addRow(totals.testCases.passed)
16728 .addRow(totals.assertions.passed));
16729 columns.push_back(SummaryColumn("failed", Colour::ResultError)
16730 .addRow(totals.testCases.failed)
16731 .addRow(totals.assertions.failed));
16732 columns.push_back(SummaryColumn("failed as expected", Colour::ResultExpectedFailure)
16733 .addRow(totals.testCases.failedButOk)
16734 .addRow(totals.assertions.failedButOk));
16735
16736 printSummaryRow("test cases", columns, 0);
16737 printSummaryRow("assertions", columns, 1);
16738 }
16739 }
printSummaryRow(std::string const & label,std::vector<SummaryColumn> const & cols,std::size_t row)16740 void ConsoleReporter::printSummaryRow(std::string const& label, std::vector<SummaryColumn> const& cols, std::size_t row) {
16741 for (auto col : cols) {
16742 std::string value = col.rows[row];
16743 if (col.label.empty()) {
16744 stream << label << ": ";
16745 if (value != "0")
16746 stream << value;
16747 else
16748 stream << Colour(Colour::Warning) << "- none -";
16749 } else if (value != "0") {
16750 stream << Colour(Colour::LightGrey) << " | ";
16751 stream << Colour(col.colour)
16752 << value << ' ' << col.label;
16753 }
16754 }
16755 stream << '\n';
16756 }
16757
printTotalsDivider(Totals const & totals)16758 void ConsoleReporter::printTotalsDivider(Totals const& totals) {
16759 if (totals.testCases.total() > 0) {
16760 std::size_t failedRatio = makeRatio(totals.testCases.failed, totals.testCases.total());
16761 std::size_t failedButOkRatio = makeRatio(totals.testCases.failedButOk, totals.testCases.total());
16762 std::size_t passedRatio = makeRatio(totals.testCases.passed, totals.testCases.total());
16763 while (failedRatio + failedButOkRatio + passedRatio < CATCH_CONFIG_CONSOLE_WIDTH - 1)
16764 findMax(failedRatio, failedButOkRatio, passedRatio)++;
16765 while (failedRatio + failedButOkRatio + passedRatio > CATCH_CONFIG_CONSOLE_WIDTH - 1)
16766 findMax(failedRatio, failedButOkRatio, passedRatio)--;
16767
16768 stream << Colour(Colour::Error) << std::string(failedRatio, '=');
16769 stream << Colour(Colour::ResultExpectedFailure) << std::string(failedButOkRatio, '=');
16770 if (totals.testCases.allPassed())
16771 stream << Colour(Colour::ResultSuccess) << std::string(passedRatio, '=');
16772 else
16773 stream << Colour(Colour::Success) << std::string(passedRatio, '=');
16774 } else {
16775 stream << Colour(Colour::Warning) << std::string(CATCH_CONFIG_CONSOLE_WIDTH - 1, '=');
16776 }
16777 stream << '\n';
16778 }
printSummaryDivider()16779 void ConsoleReporter::printSummaryDivider() {
16780 stream << getLineOfChars<'-'>() << '\n';
16781 }
16782
printTestFilters()16783 void ConsoleReporter::printTestFilters() {
16784 if (m_config->testSpec().hasFilters()) {
16785 Colour guard(Colour::BrightYellow);
16786 stream << "Filters: " << serializeFilters(m_config->getTestsOrTags()) << '\n';
16787 }
16788 }
16789
16790 CATCH_REGISTER_REPORTER("console", ConsoleReporter)
16791
16792 } // end namespace Catch
16793
16794 #if defined(_MSC_VER)
16795 #pragma warning(pop)
16796 #endif
16797
16798 #if defined(__clang__)
16799 # pragma clang diagnostic pop
16800 #endif
16801 // end catch_reporter_console.cpp
16802 // start catch_reporter_junit.cpp
16803
16804 #include <cassert>
16805 #include <sstream>
16806 #include <ctime>
16807 #include <algorithm>
16808 #include <iomanip>
16809
16810 namespace Catch {
16811
16812 namespace {
getCurrentTimestamp()16813 std::string getCurrentTimestamp() {
16814 // Beware, this is not reentrant because of backward compatibility issues
16815 // Also, UTC only, again because of backward compatibility (%z is C++11)
16816 time_t rawtime;
16817 std::time(&rawtime);
16818 auto const timeStampSize = sizeof("2017-01-16T17:06:45Z");
16819
16820 #ifdef _MSC_VER
16821 std::tm timeInfo = {};
16822 gmtime_s(&timeInfo, &rawtime);
16823 #else
16824 std::tm* timeInfo;
16825 timeInfo = std::gmtime(&rawtime);
16826 #endif
16827
16828 char timeStamp[timeStampSize];
16829 const char * const fmt = "%Y-%m-%dT%H:%M:%SZ";
16830
16831 #ifdef _MSC_VER
16832 std::strftime(timeStamp, timeStampSize, fmt, &timeInfo);
16833 #else
16834 std::strftime(timeStamp, timeStampSize, fmt, timeInfo);
16835 #endif
16836 return std::string(timeStamp, timeStampSize-1);
16837 }
16838
fileNameTag(const std::vector<std::string> & tags)16839 std::string fileNameTag(const std::vector<std::string> &tags) {
16840 auto it = std::find_if(begin(tags),
16841 end(tags),
16842 [] (std::string const& tag) {return tag.front() == '#'; });
16843 if (it != tags.end())
16844 return it->substr(1);
16845 return std::string();
16846 }
16847
16848 // Formats the duration in seconds to 3 decimal places.
16849 // This is done because some genius defined Maven Surefire schema
16850 // in a way that only accepts 3 decimal places, and tools like
16851 // Jenkins use that schema for validation JUnit reporter output.
formatDuration(double seconds)16852 std::string formatDuration( double seconds ) {
16853 ReusableStringStream rss;
16854 rss << std::fixed << std::setprecision( 3 ) << seconds;
16855 return rss.str();
16856 }
16857
16858 } // anonymous namespace
16859
JunitReporter(ReporterConfig const & _config)16860 JunitReporter::JunitReporter( ReporterConfig const& _config )
16861 : CumulativeReporterBase( _config ),
16862 xml( _config.stream() )
16863 {
16864 m_reporterPrefs.shouldRedirectStdOut = true;
16865 m_reporterPrefs.shouldReportAllAssertions = true;
16866 }
16867
~JunitReporter()16868 JunitReporter::~JunitReporter() {}
16869
getDescription()16870 std::string JunitReporter::getDescription() {
16871 return "Reports test results in an XML format that looks like Ant's junitreport target";
16872 }
16873
noMatchingTestCases(std::string const &)16874 void JunitReporter::noMatchingTestCases( std::string const& /*spec*/ ) {}
16875
testRunStarting(TestRunInfo const & runInfo)16876 void JunitReporter::testRunStarting( TestRunInfo const& runInfo ) {
16877 CumulativeReporterBase::testRunStarting( runInfo );
16878 xml.startElement( "testsuites" );
16879 }
16880
testGroupStarting(GroupInfo const & groupInfo)16881 void JunitReporter::testGroupStarting( GroupInfo const& groupInfo ) {
16882 suiteTimer.start();
16883 stdOutForSuite.clear();
16884 stdErrForSuite.clear();
16885 unexpectedExceptions = 0;
16886 CumulativeReporterBase::testGroupStarting( groupInfo );
16887 }
16888
testCaseStarting(TestCaseInfo const & testCaseInfo)16889 void JunitReporter::testCaseStarting( TestCaseInfo const& testCaseInfo ) {
16890 m_okToFail = testCaseInfo.okToFail();
16891 }
16892
assertionEnded(AssertionStats const & assertionStats)16893 bool JunitReporter::assertionEnded( AssertionStats const& assertionStats ) {
16894 if( assertionStats.assertionResult.getResultType() == ResultWas::ThrewException && !m_okToFail )
16895 unexpectedExceptions++;
16896 return CumulativeReporterBase::assertionEnded( assertionStats );
16897 }
16898
testCaseEnded(TestCaseStats const & testCaseStats)16899 void JunitReporter::testCaseEnded( TestCaseStats const& testCaseStats ) {
16900 stdOutForSuite += testCaseStats.stdOut;
16901 stdErrForSuite += testCaseStats.stdErr;
16902 CumulativeReporterBase::testCaseEnded( testCaseStats );
16903 }
16904
testGroupEnded(TestGroupStats const & testGroupStats)16905 void JunitReporter::testGroupEnded( TestGroupStats const& testGroupStats ) {
16906 double suiteTime = suiteTimer.getElapsedSeconds();
16907 CumulativeReporterBase::testGroupEnded( testGroupStats );
16908 writeGroup( *m_testGroups.back(), suiteTime );
16909 }
16910
testRunEndedCumulative()16911 void JunitReporter::testRunEndedCumulative() {
16912 xml.endElement();
16913 }
16914
writeGroup(TestGroupNode const & groupNode,double suiteTime)16915 void JunitReporter::writeGroup( TestGroupNode const& groupNode, double suiteTime ) {
16916 XmlWriter::ScopedElement e = xml.scopedElement( "testsuite" );
16917
16918 TestGroupStats const& stats = groupNode.value;
16919 xml.writeAttribute( "name", stats.groupInfo.name );
16920 xml.writeAttribute( "errors", unexpectedExceptions );
16921 xml.writeAttribute( "failures", stats.totals.assertions.failed-unexpectedExceptions );
16922 xml.writeAttribute( "tests", stats.totals.assertions.total() );
16923 xml.writeAttribute( "hostname", "tbd" ); // !TBD
16924 if( m_config->showDurations() == ShowDurations::Never )
16925 xml.writeAttribute( "time", "" );
16926 else
16927 xml.writeAttribute( "time", formatDuration( suiteTime ) );
16928 xml.writeAttribute( "timestamp", getCurrentTimestamp() );
16929
16930 // Write properties if there are any
16931 if (m_config->hasTestFilters() || m_config->rngSeed() != 0) {
16932 auto properties = xml.scopedElement("properties");
16933 if (m_config->hasTestFilters()) {
16934 xml.scopedElement("property")
16935 .writeAttribute("name", "filters")
16936 .writeAttribute("value", serializeFilters(m_config->getTestsOrTags()));
16937 }
16938 if (m_config->rngSeed() != 0) {
16939 xml.scopedElement("property")
16940 .writeAttribute("name", "random-seed")
16941 .writeAttribute("value", m_config->rngSeed());
16942 }
16943 }
16944
16945 // Write test cases
16946 for( auto const& child : groupNode.children )
16947 writeTestCase( *child );
16948
16949 xml.scopedElement( "system-out" ).writeText( trim( stdOutForSuite ), XmlFormatting::Newline );
16950 xml.scopedElement( "system-err" ).writeText( trim( stdErrForSuite ), XmlFormatting::Newline );
16951 }
16952
writeTestCase(TestCaseNode const & testCaseNode)16953 void JunitReporter::writeTestCase( TestCaseNode const& testCaseNode ) {
16954 TestCaseStats const& stats = testCaseNode.value;
16955
16956 // All test cases have exactly one section - which represents the
16957 // test case itself. That section may have 0-n nested sections
16958 assert( testCaseNode.children.size() == 1 );
16959 SectionNode const& rootSection = *testCaseNode.children.front();
16960
16961 std::string className = stats.testInfo.className;
16962
16963 if( className.empty() ) {
16964 className = fileNameTag(stats.testInfo.tags);
16965 if ( className.empty() )
16966 className = "global";
16967 }
16968
16969 if ( !m_config->name().empty() )
16970 className = m_config->name() + "." + className;
16971
16972 writeSection( className, "", rootSection, stats.testInfo.okToFail() );
16973 }
16974
writeSection(std::string const & className,std::string const & rootName,SectionNode const & sectionNode,bool testOkToFail)16975 void JunitReporter::writeSection( std::string const& className,
16976 std::string const& rootName,
16977 SectionNode const& sectionNode,
16978 bool testOkToFail) {
16979 std::string name = trim( sectionNode.stats.sectionInfo.name );
16980 if( !rootName.empty() )
16981 name = rootName + '/' + name;
16982
16983 if( !sectionNode.assertions.empty() ||
16984 !sectionNode.stdOut.empty() ||
16985 !sectionNode.stdErr.empty() ) {
16986 XmlWriter::ScopedElement e = xml.scopedElement( "testcase" );
16987 if( className.empty() ) {
16988 xml.writeAttribute( "classname", name );
16989 xml.writeAttribute( "name", "root" );
16990 }
16991 else {
16992 xml.writeAttribute( "classname", className );
16993 xml.writeAttribute( "name", name );
16994 }
16995 xml.writeAttribute( "time", formatDuration( sectionNode.stats.durationInSeconds ) );
16996 // This is not ideal, but it should be enough to mimic gtest's
16997 // junit output.
16998 // Ideally the JUnit reporter would also handle `skipTest`
16999 // events and write those out appropriately.
17000 xml.writeAttribute( "status", "run" );
17001
17002 if (sectionNode.stats.assertions.failedButOk) {
17003 xml.scopedElement("skipped")
17004 .writeAttribute("message", "TEST_CASE tagged with !mayfail");
17005 }
17006
17007 writeAssertions( sectionNode );
17008
17009 if( !sectionNode.stdOut.empty() )
17010 xml.scopedElement( "system-out" ).writeText( trim( sectionNode.stdOut ), XmlFormatting::Newline );
17011 if( !sectionNode.stdErr.empty() )
17012 xml.scopedElement( "system-err" ).writeText( trim( sectionNode.stdErr ), XmlFormatting::Newline );
17013 }
17014 for( auto const& childNode : sectionNode.childSections )
17015 if( className.empty() )
17016 writeSection( name, "", *childNode, testOkToFail );
17017 else
17018 writeSection( className, name, *childNode, testOkToFail );
17019 }
17020
writeAssertions(SectionNode const & sectionNode)17021 void JunitReporter::writeAssertions( SectionNode const& sectionNode ) {
17022 for( auto const& assertion : sectionNode.assertions )
17023 writeAssertion( assertion );
17024 }
17025
writeAssertion(AssertionStats const & stats)17026 void JunitReporter::writeAssertion( AssertionStats const& stats ) {
17027 AssertionResult const& result = stats.assertionResult;
17028 if( !result.isOk() ) {
17029 std::string elementName;
17030 switch( result.getResultType() ) {
17031 case ResultWas::ThrewException:
17032 case ResultWas::FatalErrorCondition:
17033 elementName = "error";
17034 break;
17035 case ResultWas::ExplicitFailure:
17036 case ResultWas::ExpressionFailed:
17037 case ResultWas::DidntThrowException:
17038 elementName = "failure";
17039 break;
17040
17041 // We should never see these here:
17042 case ResultWas::Info:
17043 case ResultWas::Warning:
17044 case ResultWas::Ok:
17045 case ResultWas::Unknown:
17046 case ResultWas::FailureBit:
17047 case ResultWas::Exception:
17048 elementName = "internalError";
17049 break;
17050 }
17051
17052 XmlWriter::ScopedElement e = xml.scopedElement( elementName );
17053
17054 xml.writeAttribute( "message", result.getExpression() );
17055 xml.writeAttribute( "type", result.getTestMacroName() );
17056
17057 ReusableStringStream rss;
17058 if (stats.totals.assertions.total() > 0) {
17059 rss << "FAILED" << ":\n";
17060 if (result.hasExpression()) {
17061 rss << " ";
17062 rss << result.getExpressionInMacro();
17063 rss << '\n';
17064 }
17065 if (result.hasExpandedExpression()) {
17066 rss << "with expansion:\n";
17067 rss << Column(result.getExpandedExpression()).indent(2) << '\n';
17068 }
17069 } else {
17070 rss << '\n';
17071 }
17072
17073 if( !result.getMessage().empty() )
17074 rss << result.getMessage() << '\n';
17075 for( auto const& msg : stats.infoMessages )
17076 if( msg.type == ResultWas::Info )
17077 rss << msg.message << '\n';
17078
17079 rss << "at " << result.getSourceInfo();
17080 xml.writeText( rss.str(), XmlFormatting::Newline );
17081 }
17082 }
17083
17084 CATCH_REGISTER_REPORTER( "junit", JunitReporter )
17085
17086 } // end namespace Catch
17087 // end catch_reporter_junit.cpp
17088 // start catch_reporter_listening.cpp
17089
17090 #include <cassert>
17091
17092 namespace Catch {
17093
ListeningReporter()17094 ListeningReporter::ListeningReporter() {
17095 // We will assume that listeners will always want all assertions
17096 m_preferences.shouldReportAllAssertions = true;
17097 }
17098
addListener(IStreamingReporterPtr && listener)17099 void ListeningReporter::addListener( IStreamingReporterPtr&& listener ) {
17100 m_listeners.push_back( std::move( listener ) );
17101 }
17102
addReporter(IStreamingReporterPtr && reporter)17103 void ListeningReporter::addReporter(IStreamingReporterPtr&& reporter) {
17104 assert(!m_reporter && "Listening reporter can wrap only 1 real reporter");
17105 m_reporter = std::move( reporter );
17106 m_preferences.shouldRedirectStdOut = m_reporter->getPreferences().shouldRedirectStdOut;
17107 }
17108
getPreferences() const17109 ReporterPreferences ListeningReporter::getPreferences() const {
17110 return m_preferences;
17111 }
17112
getSupportedVerbosities()17113 std::set<Verbosity> ListeningReporter::getSupportedVerbosities() {
17114 return std::set<Verbosity>{ };
17115 }
17116
noMatchingTestCases(std::string const & spec)17117 void ListeningReporter::noMatchingTestCases( std::string const& spec ) {
17118 for ( auto const& listener : m_listeners ) {
17119 listener->noMatchingTestCases( spec );
17120 }
17121 m_reporter->noMatchingTestCases( spec );
17122 }
17123
reportInvalidArguments(std::string const & arg)17124 void ListeningReporter::reportInvalidArguments(std::string const&arg){
17125 for ( auto const& listener : m_listeners ) {
17126 listener->reportInvalidArguments( arg );
17127 }
17128 m_reporter->reportInvalidArguments( arg );
17129 }
17130
17131 #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
benchmarkPreparing(std::string const & name)17132 void ListeningReporter::benchmarkPreparing( std::string const& name ) {
17133 for (auto const& listener : m_listeners) {
17134 listener->benchmarkPreparing(name);
17135 }
17136 m_reporter->benchmarkPreparing(name);
17137 }
benchmarkStarting(BenchmarkInfo const & benchmarkInfo)17138