Debian Codegraph @

packages/seacas/libraries/ioss/src/visualization/catalyst/test/Catch2/catch.hpp

raw
1 /*
2 * Catch v2.13.4
3 * Generated: 2020-12-29 14:48:00.116107
4 * ----------------------------------------------------------
5 * This file has been merged from multiple headers. Please don't edit it directly
6 * Copyright (c) 2020 Two Blue Cubes Ltd. All rights reserved.
7 *
8 * Distributed under the Boost Software License, Version 1.0. (See accompanying
9 * file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
10 */
11 #ifndef TWOBLUECUBES_SINGLE_INCLUDE_CATCH_HPP_INCLUDED
12 #define TWOBLUECUBES_SINGLE_INCLUDE_CATCH_HPP_INCLUDED
13 // start catch.hpp
14
15 #define CATCH_VERSION_MAJOR 2
16 #define CATCH_VERSION_MINOR 13
17 #define CATCH_VERSION_PATCH 4
18
19 #ifdef __clang__
20 #pragma clang system_header
21 #elif defined __GNUC__
22 #pragma GCC system_header
23 #endif
24
25 // start catch_suppress_warnings.h
26
27 #ifdef __clang__
28 #ifdef __ICC // icpc defines the __clang__ macro
29 #pragma warning(push)
30 #pragma warning(disable : 161 1682)
31 #else // __ICC
32 #pragma clang diagnostic push
33 #pragma clang diagnostic ignored "-Wpadded"
34 #pragma clang diagnostic ignored "-Wswitch-enum"
35 #pragma clang diagnostic ignored "-Wcovered-switch-default"
36 #endif
37 #elif defined __GNUC__
38 // Because REQUIREs trigger GCC's -Wparentheses, and because still
39 // supported version of g++ have only buggy support for _Pragmas,
40 // Wparentheses have to be suppressed globally.
41 #pragma GCC diagnostic ignored "-Wparentheses" // See #674 for details
42
43 #pragma GCC diagnostic push
44 #pragma GCC diagnostic ignored "-Wunused-variable"
45 #pragma GCC diagnostic ignored "-Wpadded"
46 #endif
47 // end catch_suppress_warnings.h
48 #if defined(CATCH_CONFIG_MAIN) || defined(CATCH_CONFIG_RUNNER)
49 #define CATCH_IMPL
50 #define CATCH_CONFIG_ALL_PARTS
51 #endif
52
53 // In the impl file, we want to have access to all parts of the headers
54 // Can also be used to sanely support PCHs
55 #if defined(CATCH_CONFIG_ALL_PARTS)
56 #define CATCH_CONFIG_EXTERNAL_INTERFACES
57 #if defined(CATCH_CONFIG_DISABLE_MATCHERS)
58 #undef CATCH_CONFIG_DISABLE_MATCHERS
59 #endif
60 #if !defined(CATCH_CONFIG_ENABLE_CHRONO_STRINGMAKER)
61 #define CATCH_CONFIG_ENABLE_CHRONO_STRINGMAKER
62 #endif
63 #endif
64
65 #if !defined(CATCH_CONFIG_IMPL_ONLY)
66 // start catch_platform.h
67
68 #ifdef __APPLE__
69 #include <TargetConditionals.h>
70 #if TARGET_OS_OSX == 1
71 #define CATCH_PLATFORM_MAC
72 #elif TARGET_OS_IPHONE == 1
73 #define CATCH_PLATFORM_IPHONE
74 #endif
75
76 #elif defined(linux) || defined(__linux) || defined(__linux__)
77 #define CATCH_PLATFORM_LINUX
78
79 #elif defined(WIN32) || defined(__WIN32__) || defined(_WIN32) || defined(_MSC_VER) || \
80 defined(__MINGW32__)
81 #define CATCH_PLATFORM_WINDOWS
82 #endif
83
84 // end catch_platform.h
85
86 #ifdef CATCH_IMPL
87 #ifndef CLARA_CONFIG_MAIN
88 #define CLARA_CONFIG_MAIN_NOT_DEFINED
89 #define CLARA_CONFIG_MAIN
90 #endif
91 #endif
92
93 // start catch_user_interfaces.h
94
95 namespace Catch {
96 unsigned int rngSeed();
97 }
98
99 // end catch_user_interfaces.h
100 // start catch_tag_alias_autoregistrar.h
101
102 // start catch_common.h
103
104 // start catch_compiler_capabilities.h
105
106 // Detect a number of compiler features - by compiler
107 // The following features are defined:
108 //
109 // CATCH_CONFIG_COUNTER : is the __COUNTER__ macro supported?
110 // CATCH_CONFIG_WINDOWS_SEH : is Windows SEH supported?
111 // CATCH_CONFIG_POSIX_SIGNALS : are POSIX signals supported?
112 // CATCH_CONFIG_DISABLE_EXCEPTIONS : Are exceptions enabled?
113 // ****************
114 // Note to maintainers: if new toggles are added please document them
115 // in configuration.md, too
116 // ****************
117
118 // In general each macro has a _NO_<feature name> form
119 // (e.g. CATCH_CONFIG_NO_POSIX_SIGNALS) which disables the feature.
120 // Many features, at point of detection, define an _INTERNAL_ macro, so they
121 // can be combined, en-mass, with the _NO_ forms later.
122
123 #ifdef __cplusplus
124
125 #if (__cplusplus >= 201402L) || (defined(_MSVC_LANG) && _MSVC_LANG >= 201402L)
126 #define CATCH_CPP14_OR_GREATER
127 #endif
128
129 #if (__cplusplus >= 201703L) || (defined(_MSVC_LANG) && _MSVC_LANG >= 201703L)
130 #define CATCH_CPP17_OR_GREATER
131 #endif
132
133 #endif
134
135 // We have to avoid both ICC and Clang, because they try to mask themselves
136 // as gcc, and we want only GCC in this block
137 #if defined(__GNUC__) && !defined(__clang__) && !defined(__ICC) && !defined(__CUDACC__)
138 #define CATCH_INTERNAL_START_WARNINGS_SUPPRESSION _Pragma("GCC diagnostic push")
139 #define CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION _Pragma("GCC diagnostic pop")
140
141 #define CATCH_INTERNAL_IGNORE_BUT_WARN(...) (void)__builtin_constant_p(__VA_ARGS__)
142
143 #endif
144
145 #if defined(__clang__)
146
147 #define CATCH_INTERNAL_START_WARNINGS_SUPPRESSION _Pragma("clang diagnostic push")
148 #define CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION _Pragma("clang diagnostic pop")
149
150 // As of this writing, IBM XL's implementation of __builtin_constant_p has a bug
151 // which results in calls to destructors being emitted for each temporary,
152 // without a matching initialization. In practice, this can result in something
153 // like `std::string::~string` being called on an uninitialized value.
154 //
155 // For example, this code will likely segfault under IBM XL:
156 // ```
157 // REQUIRE(std::string("12") + "34" == "1234")
158 // ```
159 //
160 // Therefore, `CATCH_INTERNAL_IGNORE_BUT_WARN` is not implemented.
161 #if !defined(__ibmxl__) && !defined(__CUDACC__)
162 #define CATCH_INTERNAL_IGNORE_BUT_WARN(...) \
163 (void)__builtin_constant_p( \
164 __VA_ARGS__) /* NOLINT(cppcoreguidelines-pro-type-vararg, hicpp-vararg) */
165 #endif
166
167 #define CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
168 _Pragma("clang diagnostic ignored \"-Wexit-time-destructors\"") \
169 _Pragma("clang diagnostic ignored \"-Wglobal-constructors\"")
170
171 #define CATCH_INTERNAL_SUPPRESS_PARENTHESES_WARNINGS \
172 _Pragma("clang diagnostic ignored \"-Wparentheses\"")
173
174 #define CATCH_INTERNAL_SUPPRESS_UNUSED_WARNINGS \
175 _Pragma("clang diagnostic ignored \"-Wunused-variable\"")
176
177 #define CATCH_INTERNAL_SUPPRESS_ZERO_VARIADIC_WARNINGS \
178 _Pragma("clang diagnostic ignored \"-Wgnu-zero-variadic-macro-arguments\"")
179
180 #define CATCH_INTERNAL_SUPPRESS_UNUSED_TEMPLATE_WARNINGS \
181 _Pragma("clang diagnostic ignored \"-Wunused-template\"")
182
183 #endif // __clang__
184
185 ////////////////////////////////////////////////////////////////////////////////
186 // Assume that non-Windows platforms support posix signals by default
187 #if !defined(CATCH_PLATFORM_WINDOWS)
188 #define CATCH_INTERNAL_CONFIG_POSIX_SIGNALS
189 #endif
190
191 ////////////////////////////////////////////////////////////////////////////////
192 // We know some environments not to support full POSIX signals
193 #if defined(__CYGWIN__) || defined(__QNX__) || defined(__EMSCRIPTEN__) || defined(__DJGPP__)
194 #define CATCH_INTERNAL_CONFIG_NO_POSIX_SIGNALS
195 #endif
196
197 #ifdef __OS400__
198 #define CATCH_INTERNAL_CONFIG_NO_POSIX_SIGNALS
199 #define CATCH_CONFIG_COLOUR_NONE
200 #endif
201
202 ////////////////////////////////////////////////////////////////////////////////
203 // Android somehow still does not support std::to_string
204 #if defined(__ANDROID__)
205 #define CATCH_INTERNAL_CONFIG_NO_CPP11_TO_STRING
206 #define CATCH_INTERNAL_CONFIG_ANDROID_LOGWRITE
207 #endif
208
209 ////////////////////////////////////////////////////////////////////////////////
210 // Not all Windows environments support SEH properly
211 #if defined(__MINGW32__)
212 #define CATCH_INTERNAL_CONFIG_NO_WINDOWS_SEH
213 #endif
214
215 ////////////////////////////////////////////////////////////////////////////////
216 // PS4
217 #if defined(__ORBIS__)
218 #define CATCH_INTERNAL_CONFIG_NO_NEW_CAPTURE
219 #endif
220
221 ////////////////////////////////////////////////////////////////////////////////
222 // Cygwin
223 #ifdef __CYGWIN__
224
225 // Required for some versions of Cygwin to declare gettimeofday
226 // see: http://stackoverflow.com/questions/36901803/gettimeofday-not-declared-in-this-scope-cygwin
227 #define _BSD_SOURCE
228 // some versions of cygwin (most) do not support std::to_string. Use the libstd check.
229 // https://gcc.gnu.org/onlinedocs/gcc-4.8.2/libstdc++/api/a01053_source.html line 2812-2813
230 #if !((__cplusplus >= 201103L) && defined(_GLIBCXX_USE_C99) && \
231 !defined(_GLIBCXX_HAVE_BROKEN_VSWPRINTF))
232
233 #define CATCH_INTERNAL_CONFIG_NO_CPP11_TO_STRING
234
235 #endif
236 #endif // __CYGWIN__
237
238 ////////////////////////////////////////////////////////////////////////////////
239 // Visual C++
240 #if defined(_MSC_VER)
241
242 #define CATCH_INTERNAL_START_WARNINGS_SUPPRESSION __pragma(warning(push))
243 #define CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION __pragma(warning(pop))
244
245 // Universal Windows platform does not support SEH
246 // Or console colours (or console at all...)
247 #if defined(WINAPI_FAMILY) && (WINAPI_FAMILY == WINAPI_FAMILY_APP)
248 #define CATCH_CONFIG_COLOUR_NONE
249 #else
250 #define CATCH_INTERNAL_CONFIG_WINDOWS_SEH
251 #endif
252
253 // MSVC traditional preprocessor needs some workaround for __VA_ARGS__
254 // _MSVC_TRADITIONAL == 0 means new conformant preprocessor
255 // _MSVC_TRADITIONAL == 1 means old traditional non-conformant preprocessor
256 #if !defined(__clang__) // Handle Clang masquerading for msvc
257 #if !defined(_MSVC_TRADITIONAL) || (defined(_MSVC_TRADITIONAL) && _MSVC_TRADITIONAL)
258 #define CATCH_INTERNAL_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
259 #endif // MSVC_TRADITIONAL
260 #endif // __clang__
261
262 #endif // _MSC_VER
263
264 #if defined(_REENTRANT) || defined(_MSC_VER)
265 // Enable async processing, as -pthread is specified or no additional linking is required
266 #define CATCH_INTERNAL_CONFIG_USE_ASYNC
267 #endif // _MSC_VER
268
269 ////////////////////////////////////////////////////////////////////////////////
270 // Check if we are compiled with -fno-exceptions or equivalent
271 #if defined(__EXCEPTIONS) || defined(__cpp_exceptions) || defined(_CPPUNWIND)
272 #define CATCH_INTERNAL_CONFIG_EXCEPTIONS_ENABLED
273 #endif
274
275 ////////////////////////////////////////////////////////////////////////////////
276 // DJGPP
277 #ifdef __DJGPP__
278 #define CATCH_INTERNAL_CONFIG_NO_WCHAR
279 #endif // __DJGPP__
280
281 ////////////////////////////////////////////////////////////////////////////////
282 // Embarcadero C++Build
283 #if defined(__BORLANDC__)
284 #define CATCH_INTERNAL_CONFIG_POLYFILL_ISNAN
285 #endif
286
287 ////////////////////////////////////////////////////////////////////////////////
288
289 // Use of __COUNTER__ is suppressed during code analysis in
290 // CLion/AppCode 2017.2.x and former, because __COUNTER__ is not properly
291 // handled by it.
292 // Otherwise all supported compilers support COUNTER macro,
293 // but user still might want to turn it off
294 #if (!defined(__JETBRAINS_IDE__) || __JETBRAINS_IDE__ >= 20170300L)
295 #define CATCH_INTERNAL_CONFIG_COUNTER
296 #endif
297
298 ////////////////////////////////////////////////////////////////////////////////
299
300 // RTX is a special version of Windows that is real time.
301 // This means that it is detected as Windows, but does not provide
302 // the same set of capabilities as real Windows does.
303 #if defined(UNDER_RTSS) || defined(RTX64_BUILD)
304 #define CATCH_INTERNAL_CONFIG_NO_WINDOWS_SEH
305 #define CATCH_INTERNAL_CONFIG_NO_ASYNC
306 #define CATCH_CONFIG_COLOUR_NONE
307 #endif
308
309 #if !defined(_GLIBCXX_USE_C99_MATH_TR1)
310 #define CATCH_INTERNAL_CONFIG_GLOBAL_NEXTAFTER
311 #endif
312
313 // Various stdlib support checks that require __has_include
314 #if defined(__has_include)
315 // Check if string_view is available and usable
316 #if __has_include(<string_view>) && defined(CATCH_CPP17_OR_GREATER)
317 #define CATCH_INTERNAL_CONFIG_CPP17_STRING_VIEW
318 #endif
319
320 // Check if optional is available and usable
321 #if __has_include(<optional>) && defined(CATCH_CPP17_OR_GREATER)
322 #define CATCH_INTERNAL_CONFIG_CPP17_OPTIONAL
323 #endif // __has_include(<optional>) && defined(CATCH_CPP17_OR_GREATER)
324
325 // Check if byte is available and usable
326 #if __has_include(<cstddef>) && defined(CATCH_CPP17_OR_GREATER)
327 #include <cstddef>
328 #if __cpp_lib_byte > 0
329 #define CATCH_INTERNAL_CONFIG_CPP17_BYTE
330 #endif
331 #endif // __has_include(<cstddef>) && defined(CATCH_CPP17_OR_GREATER)
332
333 // Check if variant is available and usable
334 #if __has_include(<variant>) && defined(CATCH_CPP17_OR_GREATER)
335 #if defined(__clang__) && (__clang_major__ < 8)
336 // work around clang bug with libstdc++ https://bugs.llvm.org/show_bug.cgi?id=31852
337 // fix should be in clang 8, workaround in libstdc++ 8.2
338 #include <ciso646>
339 #if defined(__GLIBCXX__) && defined(_GLIBCXX_RELEASE) && (_GLIBCXX_RELEASE < 9)
340 #define CATCH_CONFIG_NO_CPP17_VARIANT
341 #else
342 #define CATCH_INTERNAL_CONFIG_CPP17_VARIANT
343 #endif // defined(__GLIBCXX__) && defined(_GLIBCXX_RELEASE) && (_GLIBCXX_RELEASE < 9)
344 #else
345 #define CATCH_INTERNAL_CONFIG_CPP17_VARIANT
346 #endif // defined(__clang__) && (__clang_major__ < 8)
347 #endif // __has_include(<variant>) && defined(CATCH_CPP17_OR_GREATER)
348 #endif // defined(__has_include)
349
350 #if defined(CATCH_INTERNAL_CONFIG_COUNTER) && !defined(CATCH_CONFIG_NO_COUNTER) && \
351 !defined(CATCH_CONFIG_COUNTER)
352 #define CATCH_CONFIG_COUNTER
353 #endif
354 #if defined(CATCH_INTERNAL_CONFIG_WINDOWS_SEH) && !defined(CATCH_CONFIG_NO_WINDOWS_SEH) && \
355 !defined(CATCH_CONFIG_WINDOWS_SEH) && !defined(CATCH_INTERNAL_CONFIG_NO_WINDOWS_SEH)
356 #define CATCH_CONFIG_WINDOWS_SEH
357 #endif
358 // This is set by default, because we assume that unix compilers are posix-signal-compatible by
359 // default.
360 #if defined(CATCH_INTERNAL_CONFIG_POSIX_SIGNALS) && \
361 !defined(CATCH_INTERNAL_CONFIG_NO_POSIX_SIGNALS) && !defined(CATCH_CONFIG_NO_POSIX_SIGNALS) && \
362 !defined(CATCH_CONFIG_POSIX_SIGNALS)
363 #define CATCH_CONFIG_POSIX_SIGNALS
364 #endif
365 // This is set by default, because we assume that compilers with no wchar_t support are just rare
366 // exceptions.
367 #if !defined(CATCH_INTERNAL_CONFIG_NO_WCHAR) && !defined(CATCH_CONFIG_NO_WCHAR) && \
368 !defined(CATCH_CONFIG_WCHAR)
369 #define CATCH_CONFIG_WCHAR
370 #endif
371
372 #if !defined(CATCH_INTERNAL_CONFIG_NO_CPP11_TO_STRING) && \
373 !defined(CATCH_CONFIG_NO_CPP11_TO_STRING) && !defined(CATCH_CONFIG_CPP11_TO_STRING)
374 #define CATCH_CONFIG_CPP11_TO_STRING
375 #endif
376
377 #if defined(CATCH_INTERNAL_CONFIG_CPP17_OPTIONAL) && !defined(CATCH_CONFIG_NO_CPP17_OPTIONAL) && \
378 !defined(CATCH_CONFIG_CPP17_OPTIONAL)
379 #define CATCH_CONFIG_CPP17_OPTIONAL
380 #endif
381
382 #if defined(CATCH_INTERNAL_CONFIG_CPP17_STRING_VIEW) && \
383 !defined(CATCH_CONFIG_NO_CPP17_STRING_VIEW) && !defined(CATCH_CONFIG_CPP17_STRING_VIEW)
384 #define CATCH_CONFIG_CPP17_STRING_VIEW
385 #endif
386
387 #if defined(CATCH_INTERNAL_CONFIG_CPP17_VARIANT) && !defined(CATCH_CONFIG_NO_CPP17_VARIANT) && \
388 !defined(CATCH_CONFIG_CPP17_VARIANT)
389 #define CATCH_CONFIG_CPP17_VARIANT
390 #endif
391
392 #if defined(CATCH_INTERNAL_CONFIG_CPP17_BYTE) && !defined(CATCH_CONFIG_NO_CPP17_BYTE) && \
393 !defined(CATCH_CONFIG_CPP17_BYTE)
394 #define CATCH_CONFIG_CPP17_BYTE
395 #endif
396
397 #if defined(CATCH_CONFIG_EXPERIMENTAL_REDIRECT)
398 #define CATCH_INTERNAL_CONFIG_NEW_CAPTURE
399 #endif
400
401 #if defined(CATCH_INTERNAL_CONFIG_NEW_CAPTURE) && \
402 !defined(CATCH_INTERNAL_CONFIG_NO_NEW_CAPTURE) && !defined(CATCH_CONFIG_NO_NEW_CAPTURE) && \
403 !defined(CATCH_CONFIG_NEW_CAPTURE)
404 #define CATCH_CONFIG_NEW_CAPTURE
405 #endif
406
407 #if !defined(CATCH_INTERNAL_CONFIG_EXCEPTIONS_ENABLED) && !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
408 #define CATCH_CONFIG_DISABLE_EXCEPTIONS
409 #endif
410
411 #if defined(CATCH_INTERNAL_CONFIG_POLYFILL_ISNAN) && !defined(CATCH_CONFIG_NO_POLYFILL_ISNAN) && \
412 !defined(CATCH_CONFIG_POLYFILL_ISNAN)
413 #define CATCH_CONFIG_POLYFILL_ISNAN
414 #endif
415
416 #if defined(CATCH_INTERNAL_CONFIG_USE_ASYNC) && !defined(CATCH_INTERNAL_CONFIG_NO_ASYNC) && \
417 !defined(CATCH_CONFIG_NO_USE_ASYNC) && !defined(CATCH_CONFIG_USE_ASYNC)
418 #define CATCH_CONFIG_USE_ASYNC
419 #endif
420
421 #if defined(CATCH_INTERNAL_CONFIG_ANDROID_LOGWRITE) && \
422 !defined(CATCH_CONFIG_NO_ANDROID_LOGWRITE) && !defined(CATCH_CONFIG_ANDROID_LOGWRITE)
423 #define CATCH_CONFIG_ANDROID_LOGWRITE
424 #endif
425
426 #if defined(CATCH_INTERNAL_CONFIG_GLOBAL_NEXTAFTER) && \
427 !defined(CATCH_CONFIG_NO_GLOBAL_NEXTAFTER) && !defined(CATCH_CONFIG_GLOBAL_NEXTAFTER)
428 #define CATCH_CONFIG_GLOBAL_NEXTAFTER
429 #endif
430
431 // Even if we do not think the compiler has that warning, we still have
432 // to provide a macro that can be used by the code.
433 #if !defined(CATCH_INTERNAL_START_WARNINGS_SUPPRESSION)
434 #define CATCH_INTERNAL_START_WARNINGS_SUPPRESSION
435 #endif
436 #if !defined(CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION)
437 #define CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION
438 #endif
439 #if !defined(CATCH_INTERNAL_SUPPRESS_PARENTHESES_WARNINGS)
440 #define CATCH_INTERNAL_SUPPRESS_PARENTHESES_WARNINGS
441 #endif
442 #if !defined(CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS)
443 #define CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS
444 #endif
445 #if !defined(CATCH_INTERNAL_SUPPRESS_UNUSED_WARNINGS)
446 #define CATCH_INTERNAL_SUPPRESS_UNUSED_WARNINGS
447 #endif
448 #if !defined(CATCH_INTERNAL_SUPPRESS_ZERO_VARIADIC_WARNINGS)
449 #define CATCH_INTERNAL_SUPPRESS_ZERO_VARIADIC_WARNINGS
450 #endif
451
452 // The goal of this macro is to avoid evaluation of the arguments, but
453 // still have the compiler warn on problems inside...
454 #if !defined(CATCH_INTERNAL_IGNORE_BUT_WARN)
455 #define CATCH_INTERNAL_IGNORE_BUT_WARN(...)
456 #endif
457
458 #if defined(__APPLE__) && defined(__apple_build_version__) && (__clang_major__ < 10)
459 #undef CATCH_INTERNAL_SUPPRESS_UNUSED_TEMPLATE_WARNINGS
460 #elif defined(__clang__) && (__clang_major__ < 5)
461 #undef CATCH_INTERNAL_SUPPRESS_UNUSED_TEMPLATE_WARNINGS
462 #endif
463
464 #if !defined(CATCH_INTERNAL_SUPPRESS_UNUSED_TEMPLATE_WARNINGS)
465 #define CATCH_INTERNAL_SUPPRESS_UNUSED_TEMPLATE_WARNINGS
466 #endif
467
468 #if defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
469 #define CATCH_TRY if ((true))
470 #define CATCH_CATCH_ALL if ((false))
471 #define CATCH_CATCH_ANON(type) if ((false))
472 #else
473 #define CATCH_TRY try
474 #define CATCH_CATCH_ALL catch (...)
475 #define CATCH_CATCH_ANON(type) catch (type)
476 #endif
477
478 #if defined(CATCH_INTERNAL_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR) && \
479 !defined(CATCH_CONFIG_NO_TRADITIONAL_MSVC_PREPROCESSOR) && \
480 !defined(CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR)
481 #define CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
482 #endif
483
484 // end catch_compiler_capabilities.h
485 #define INTERNAL_CATCH_UNIQUE_NAME_LINE2(name, line) name##line
486 #define INTERNAL_CATCH_UNIQUE_NAME_LINE(name, line) INTERNAL_CATCH_UNIQUE_NAME_LINE2(name, line)
487 #ifdef CATCH_CONFIG_COUNTER
488 #define INTERNAL_CATCH_UNIQUE_NAME(name) INTERNAL_CATCH_UNIQUE_NAME_LINE(name, __COUNTER__)
489 #else
490 #define INTERNAL_CATCH_UNIQUE_NAME(name) INTERNAL_CATCH_UNIQUE_NAME_LINE(name, __LINE__)
491 #endif
492
493 #include <cstdint>
494 #include <iosfwd>
495 #include <string>
496
497 // We need a dummy global operator<< so we can bring it into Catch namespace later
498 struct Catch_global_namespace_dummy
499 {
500 };
501 std::ostream &operator<<(std::ostream &, Catch_global_namespace_dummy);
502
503 namespace Catch {
504
505 struct CaseSensitive
506 {
507 enum Choice { Yes, No };
508 };
509
510 class NonCopyable
511 {
512 NonCopyable(NonCopyable const &) = delete;
513 NonCopyable(NonCopyable &&) = delete;
514 NonCopyable &operator=(NonCopyable const &) = delete;
515 NonCopyable &operator=(NonCopyable &&) = delete;
516
517 protected:
518 NonCopyable();
519 virtual ~NonCopyable();
520 };
521
522 struct SourceLineInfo
523 {
524
525 SourceLineInfo() = delete;
526 SourceLineInfo(char const *_file, std::size_t _line) noexcept : file(_file), line(_line) {}
527
528 SourceLineInfo(SourceLineInfo const &other) = default;
529 SourceLineInfo &operator=(SourceLineInfo const &) = default;
530 SourceLineInfo(SourceLineInfo &&) noexcept = default;
531 SourceLineInfo &operator=(SourceLineInfo &&) noexcept = default;
532
533 bool empty() const noexcept { return file[0] == '\0'; }
534 bool operator==(SourceLineInfo const &other) const noexcept;
535 bool operator<(SourceLineInfo const &other) const noexcept;
536
537 char const *file;
538 std::size_t line;
539 };
540
541 std::ostream &operator<<(std::ostream &os, SourceLineInfo const &info);
542
543 // Bring in operator<< from global namespace into Catch namespace
544 // This is necessary because the overload of operator<< above makes
545 // lookup stop at namespace Catch
546 using ::operator<<;
547
548 // Use this in variadic streaming macros to allow
549 // >> +StreamEndStop
550 // as well as
551 // >> stuff +StreamEndStop
552 struct StreamEndStop
553 {
554 std::string operator+() const;
555 };
556 template <typename T> T const &operator+(T const &value, StreamEndStop) { return value; }
557 } // namespace Catch
558
559 #define CATCH_INTERNAL_LINEINFO \
560 ::Catch::SourceLineInfo(__FILE__, static_cast<std::size_t>(__LINE__))
561
562 // end catch_common.h
563 namespace Catch {
564
565 struct RegistrarForTagAliases
566 {
567 RegistrarForTagAliases(char const *alias, char const *tag, SourceLineInfo const &lineInfo);
568 };
569
570 } // end namespace Catch
571
572 #define CATCH_REGISTER_TAG_ALIAS(alias, spec) \
573 CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \
574 CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
575 namespace { \
576 Catch::RegistrarForTagAliases \
577 INTERNAL_CATCH_UNIQUE_NAME(AutoRegisterTagAlias)(alias, spec, CATCH_INTERNAL_LINEINFO); \
578 } \
579 CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION
580
581 // end catch_tag_alias_autoregistrar.h
582 // start catch_test_registry.h
583
584 // start catch_interfaces_testcase.h
585
586 #include <vector>
587
588 namespace Catch {
589
590 class TestSpec;
591
592 struct ITestInvoker
593 {
594 virtual void invoke() const = 0;
595 virtual ~ITestInvoker();
596 };
597
598 class TestCase;
599 struct IConfig;
600
601 struct ITestCaseRegistry
602 {
603 virtual ~ITestCaseRegistry();
604 virtual std::vector<TestCase> const &getAllTests() const = 0;
605 virtual std::vector<TestCase> const &getAllTestsSorted(IConfig const &config) const = 0;
606 };
607
608 bool isThrowSafe(TestCase const &testCase, IConfig const &config);
609 bool matchTest(TestCase const &testCase, TestSpec const &testSpec, IConfig const &config);
610 std::vector<TestCase> filterTests(std::vector<TestCase> const &testCases,
611 TestSpec const &testSpec, IConfig const &config);
612 std::vector<TestCase> const &getAllTestCasesSorted(IConfig const &config);
613
614 } // namespace Catch
615
616 // end catch_interfaces_testcase.h
617 // start catch_stringref.h
618
619 #include <cassert>
620 #include <cstddef>
621 #include <iosfwd>
622 #include <string>
623
624 namespace Catch {
625
626 /// A non-owning string class (similar to the forthcoming std::string_view)
627 /// Note that, because a StringRef may be a substring of another string,
628 /// it may not be null terminated.
629 class StringRef
630 {
631 public:
632 using size_type = std::size_t;
633 using const_iterator = const char *;
634
635 private:
636 static constexpr char const *const s_empty = "";
637
638 char const *m_start = s_empty;
639 size_type m_size = 0;
640
641 public: // construction
642 constexpr StringRef() noexcept = default;
643
644 StringRef(char const *rawChars) noexcept;
645
646 constexpr StringRef(char const *rawChars, size_type size) noexcept
647 : m_start(rawChars), m_size(size)
648 {
649 }
650
651 StringRef(std::string const &stdString) noexcept
652 : m_start(stdString.c_str()), m_size(stdString.size())
653 {
654 }
655
656 explicit operator std::string() const { return std::string(m_start, m_size); }
657
658 public: // operators
659 auto operator==(StringRef const &other) const noexcept -> bool;
660 auto operator!=(StringRef const &other) const noexcept -> bool { return !(*this == other); }
661
662 auto operator[](size_type index) const noexcept -> char
663 {
664 assert(index < m_size);
665 return m_start[index];
666 }
667
668 public: // named queries
669 constexpr auto empty() const noexcept -> bool { return m_size == 0; }
670 constexpr auto size() const noexcept -> size_type { return m_size; }
671
672 // Returns the current start pointer. If the StringRef is not
673 // null-terminated, throws std::domain_exception
674 auto c_str() const -> char const *;
675
676 public: // substrings and searches
677 // Returns a substring of [start, start + length).
678 // If start + length > size(), then the substring is [start, size()).
679 // If start > size(), then the substring is empty.
680 auto substr(size_type start, size_type length) const noexcept -> StringRef;
681
682 // Returns the current start pointer. May not be null-terminated.
683 auto data() const noexcept -> char const *;
684
685 constexpr auto isNullTerminated() const noexcept -> bool { return m_start[m_size] == '\0'; }
686
687 public: // iterators
688 constexpr const_iterator begin() const { return m_start; }
689 constexpr const_iterator end() const { return m_start + m_size; }
690 };
691
692 auto operator+=(std::string &lhs, StringRef const &sr) -> std::string &;
693 auto operator<<(std::ostream &os, StringRef const &sr) -> std::ostream &;
694
695 constexpr auto operator"" _sr(char const *rawChars, std::size_t size) noexcept -> StringRef
696 {
697 return StringRef(rawChars, size);
698 }
699 } // namespace Catch
700
701 constexpr auto operator"" _catch_sr(char const *rawChars,
702 std::size_t size) noexcept -> Catch::StringRef
703 {
704 return Catch::StringRef(rawChars, size);
705 }
706
707 // end catch_stringref.h
708 // start catch_preprocessor.hpp
709
710 #define CATCH_RECURSION_LEVEL0(...) __VA_ARGS__
711 #define CATCH_RECURSION_LEVEL1(...) \
712 CATCH_RECURSION_LEVEL0(CATCH_RECURSION_LEVEL0(CATCH_RECURSION_LEVEL0(__VA_ARGS__)))
713 #define CATCH_RECURSION_LEVEL2(...) \
714 CATCH_RECURSION_LEVEL1(CATCH_RECURSION_LEVEL1(CATCH_RECURSION_LEVEL1(__VA_ARGS__)))
715 #define CATCH_RECURSION_LEVEL3(...) \
716 CATCH_RECURSION_LEVEL2(CATCH_RECURSION_LEVEL2(CATCH_RECURSION_LEVEL2(__VA_ARGS__)))
717 #define CATCH_RECURSION_LEVEL4(...) \
718 CATCH_RECURSION_LEVEL3(CATCH_RECURSION_LEVEL3(CATCH_RECURSION_LEVEL3(__VA_ARGS__)))
719 #define CATCH_RECURSION_LEVEL5(...) \
720 CATCH_RECURSION_LEVEL4(CATCH_RECURSION_LEVEL4(CATCH_RECURSION_LEVEL4(__VA_ARGS__)))
721
722 #ifdef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
723 #define INTERNAL_CATCH_EXPAND_VARGS(...) __VA_ARGS__
724 // MSVC needs more evaluations
725 #define CATCH_RECURSION_LEVEL6(...) \
726 CATCH_RECURSION_LEVEL5(CATCH_RECURSION_LEVEL5(CATCH_RECURSION_LEVEL5(__VA_ARGS__)))
727 #define CATCH_RECURSE(...) CATCH_RECURSION_LEVEL6(CATCH_RECURSION_LEVEL6(__VA_ARGS__))
728 #else
729 #define CATCH_RECURSE(...) CATCH_RECURSION_LEVEL5(__VA_ARGS__)
730 #endif
731
732 #define CATCH_REC_END(...)
733 #define CATCH_REC_OUT
734
735 #define CATCH_EMPTY()
736 #define CATCH_DEFER(id) id CATCH_EMPTY()
737
738 #define CATCH_REC_GET_END2() 0, CATCH_REC_END
739 #define CATCH_REC_GET_END1(...) CATCH_REC_GET_END2
740 #define CATCH_REC_GET_END(...) CATCH_REC_GET_END1
741 #define CATCH_REC_NEXT0(test, next, ...) next CATCH_REC_OUT
742 #define CATCH_REC_NEXT1(test, next) CATCH_DEFER(CATCH_REC_NEXT0)(test, next, 0)
743 #define CATCH_REC_NEXT(test, next) CATCH_REC_NEXT1(CATCH_REC_GET_END test, next)
744
745 #define CATCH_REC_LIST0(f, x, peek, ...) \
746 , f(x) CATCH_DEFER(CATCH_REC_NEXT(peek, CATCH_REC_LIST1))(f, peek, __VA_ARGS__)
747 #define CATCH_REC_LIST1(f, x, peek, ...) \
748 , f(x) CATCH_DEFER(CATCH_REC_NEXT(peek, CATCH_REC_LIST0))(f, peek, __VA_ARGS__)
749 #define CATCH_REC_LIST2(f, x, peek, ...) \
750 f(x) CATCH_DEFER(CATCH_REC_NEXT(peek, CATCH_REC_LIST1))(f, peek, __VA_ARGS__)
751
752 #define CATCH_REC_LIST0_UD(f, userdata, x, peek, ...) \
753 , f(userdata, x) \
754 CATCH_DEFER(CATCH_REC_NEXT(peek, CATCH_REC_LIST1_UD))(f, userdata, peek, __VA_ARGS__)
755 #define CATCH_REC_LIST1_UD(f, userdata, x, peek, ...) \
756 , f(userdata, x) \
757 CATCH_DEFER(CATCH_REC_NEXT(peek, CATCH_REC_LIST0_UD))(f, userdata, peek, __VA_ARGS__)
758 #define CATCH_REC_LIST2_UD(f, userdata, x, peek, ...) \
759 f(userdata, x) \
760 CATCH_DEFER(CATCH_REC_NEXT(peek, CATCH_REC_LIST1_UD))(f, userdata, peek, __VA_ARGS__)
761
762 // Applies the function macro `f` to each of the remaining parameters, inserts commas between the
763 // results, and passes userdata as the first parameter to each invocation, e.g. CATCH_REC_LIST_UD(f,
764 // x, a, b, c) evaluates to f(x, a), f(x, b), f(x, c)
765 #define CATCH_REC_LIST_UD(f, userdata, ...) \
766 CATCH_RECURSE(CATCH_REC_LIST2_UD(f, userdata, __VA_ARGS__, ()()(), ()()(), ()()(), 0))
767
768 #define CATCH_REC_LIST(f, ...) \
769 CATCH_RECURSE(CATCH_REC_LIST2(f, __VA_ARGS__, ()()(), ()()(), ()()(), 0))
770
771 #define INTERNAL_CATCH_EXPAND1(param) INTERNAL_CATCH_EXPAND2(param)
772 #define INTERNAL_CATCH_EXPAND2(...) INTERNAL_CATCH_NO##__VA_ARGS__
773 #define INTERNAL_CATCH_DEF(...) INTERNAL_CATCH_DEF __VA_ARGS__
774 #define INTERNAL_CATCH_NOINTERNAL_CATCH_DEF
775 #define INTERNAL_CATCH_STRINGIZE(...) INTERNAL_CATCH_STRINGIZE2(__VA_ARGS__)
776 #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
777 #define INTERNAL_CATCH_STRINGIZE2(...) #__VA_ARGS__
778 #define INTERNAL_CATCH_STRINGIZE_WITHOUT_PARENS(param) \
779 INTERNAL_CATCH_STRINGIZE(INTERNAL_CATCH_REMOVE_PARENS(param))
780 #else
781 // MSVC is adding extra space and needs another indirection to expand
782 // INTERNAL_CATCH_NOINTERNAL_CATCH_DEF
783 #define INTERNAL_CATCH_STRINGIZE2(...) INTERNAL_CATCH_STRINGIZE3(__VA_ARGS__)
784 #define INTERNAL_CATCH_STRINGIZE3(...) #__VA_ARGS__
785 #define INTERNAL_CATCH_STRINGIZE_WITHOUT_PARENS(param) \
786 (INTERNAL_CATCH_STRINGIZE(INTERNAL_CATCH_REMOVE_PARENS(param)) + 1)
787 #endif
788
789 #define INTERNAL_CATCH_MAKE_NAMESPACE2(...) ns_##__VA_ARGS__
790 #define INTERNAL_CATCH_MAKE_NAMESPACE(name) INTERNAL_CATCH_MAKE_NAMESPACE2(name)
791
792 #define INTERNAL_CATCH_REMOVE_PARENS(...) INTERNAL_CATCH_EXPAND1(INTERNAL_CATCH_DEF __VA_ARGS__)
793
794 #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
795 #define INTERNAL_CATCH_MAKE_TYPE_LIST2(...) \
796 decltype(get_wrapper<INTERNAL_CATCH_REMOVE_PARENS_GEN(__VA_ARGS__)>())
797 #define INTERNAL_CATCH_MAKE_TYPE_LIST(...) \
798 INTERNAL_CATCH_MAKE_TYPE_LIST2(INTERNAL_CATCH_REMOVE_PARENS(__VA_ARGS__))
799 #else
800 #define INTERNAL_CATCH_MAKE_TYPE_LIST2(...) \
801 INTERNAL_CATCH_EXPAND_VARGS( \
802 decltype(get_wrapper<INTERNAL_CATCH_REMOVE_PARENS_GEN(__VA_ARGS__)>()))
803 #define INTERNAL_CATCH_MAKE_TYPE_LIST(...) \
804 INTERNAL_CATCH_EXPAND_VARGS( \
805 INTERNAL_CATCH_MAKE_TYPE_LIST2(INTERNAL_CATCH_REMOVE_PARENS(__VA_ARGS__)))
806 #endif
807
808 #define INTERNAL_CATCH_MAKE_TYPE_LISTS_FROM_TYPES(...) \
809 CATCH_REC_LIST(INTERNAL_CATCH_MAKE_TYPE_LIST, __VA_ARGS__)
810
811 #define INTERNAL_CATCH_REMOVE_PARENS_1_ARG(_0) INTERNAL_CATCH_REMOVE_PARENS(_0)
812 #define INTERNAL_CATCH_REMOVE_PARENS_2_ARG(_0, _1) \
813 INTERNAL_CATCH_REMOVE_PARENS(_0), INTERNAL_CATCH_REMOVE_PARENS_1_ARG(_1)
814 #define INTERNAL_CATCH_REMOVE_PARENS_3_ARG(_0, _1, _2) \
815 INTERNAL_CATCH_REMOVE_PARENS(_0), INTERNAL_CATCH_REMOVE_PARENS_2_ARG(_1, _2)
816 #define INTERNAL_CATCH_REMOVE_PARENS_4_ARG(_0, _1, _2, _3) \
817 INTERNAL_CATCH_REMOVE_PARENS(_0), INTERNAL_CATCH_REMOVE_PARENS_3_ARG(_1, _2, _3)
818 #define INTERNAL_CATCH_REMOVE_PARENS_5_ARG(_0, _1, _2, _3, _4) \
819 INTERNAL_CATCH_REMOVE_PARENS(_0), INTERNAL_CATCH_REMOVE_PARENS_4_ARG(_1, _2, _3, _4)
820 #define INTERNAL_CATCH_REMOVE_PARENS_6_ARG(_0, _1, _2, _3, _4, _5) \
821 INTERNAL_CATCH_REMOVE_PARENS(_0), INTERNAL_CATCH_REMOVE_PARENS_5_ARG(_1, _2, _3, _4, _5)
822 #define INTERNAL_CATCH_REMOVE_PARENS_7_ARG(_0, _1, _2, _3, _4, _5, _6) \
823 INTERNAL_CATCH_REMOVE_PARENS(_0), INTERNAL_CATCH_REMOVE_PARENS_6_ARG(_1, _2, _3, _4, _5, _6)
824 #define INTERNAL_CATCH_REMOVE_PARENS_8_ARG(_0, _1, _2, _3, _4, _5, _6, _7) \
825 INTERNAL_CATCH_REMOVE_PARENS(_0), INTERNAL_CATCH_REMOVE_PARENS_7_ARG(_1, _2, _3, _4, _5, _6, _7)
826 #define INTERNAL_CATCH_REMOVE_PARENS_9_ARG(_0, _1, _2, _3, _4, _5, _6, _7, _8) \
827 INTERNAL_CATCH_REMOVE_PARENS(_0), \
828 INTERNAL_CATCH_REMOVE_PARENS_8_ARG(_1, _2, _3, _4, _5, _6, _7, _8)
829 #define INTERNAL_CATCH_REMOVE_PARENS_10_ARG(_0, _1, _2, _3, _4, _5, _6, _7, _8, _9) \
830 INTERNAL_CATCH_REMOVE_PARENS(_0), \
831 INTERNAL_CATCH_REMOVE_PARENS_9_ARG(_1, _2, _3, _4, _5, _6, _7, _8, _9)
832 #define INTERNAL_CATCH_REMOVE_PARENS_11_ARG(_0, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10) \
833 INTERNAL_CATCH_REMOVE_PARENS(_0), \
834 INTERNAL_CATCH_REMOVE_PARENS_10_ARG(_1, _2, _3, _4, _5, _6, _7, _8, _9, _10)
835
836 #define INTERNAL_CATCH_VA_NARGS_IMPL(_0, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, N, ...) N
837
838 #define INTERNAL_CATCH_TYPE_GEN \
839 template <typename...> struct TypeList \
840 { \
841 }; \
842 template <typename... Ts> constexpr auto get_wrapper() noexcept -> TypeList<Ts...> \
843 { \
844 return {}; \
845 } \
846 template <template <typename...> class...> struct TemplateTypeList \
847 { \
848 }; \
849 template <template <typename...> class... Cs> \
850 constexpr auto get_wrapper() noexcept -> TemplateTypeList<Cs...> \
851 { \
852 return {}; \
853 } \
854 template <typename...> struct append; \
855 template <typename...> struct rewrap; \
856 template <template <typename...> class, typename...> struct create; \
857 template <template <typename...> class, typename> struct convert; \
858 \
859 template <typename T> struct append<T> \
860 { \
861 using type = T; \
862 }; \
863 template <template <typename...> class L1, typename... E1, template <typename...> class L2, \
864 typename... E2, typename... Rest> \
865 struct append<L1<E1...>, L2<E2...>, Rest...> \
866 { \
867 using type = typename append<L1<E1..., E2...>, Rest...>::type; \
868 }; \
869 template <template <typename...> class L1, typename... E1, typename... Rest> \
870 struct append<L1<E1...>, TypeList<mpl_::na>, Rest...> \
871 { \
872 using type = L1<E1...>; \
873 }; \
874 \
875 template <template <typename...> class Container, template <typename...> class List, \
876 typename... elems> \
877 struct rewrap<TemplateTypeList<Container>, List<elems...>> \
878 { \
879 using type = TypeList<Container<elems...>>; \
880 }; \
881 template <template <typename...> class Container, template <typename...> class List, \
882 class... Elems, typename... Elements> \
883 struct rewrap<TemplateTypeList<Container>, List<Elems...>, Elements...> \
884 { \
885 using type = \
886 typename append<TypeList<Container<Elems...>>, \
887 typename rewrap<TemplateTypeList<Container>, Elements...>::type>::type; \
888 }; \
889 \
890 template <template <typename...> class Final, template <typename...> class... Containers, \
891 typename... Types> \
892 struct create<Final, TemplateTypeList<Containers...>, TypeList<Types...>> \
893 { \
894 using type = \
895 typename append<Final<>, \
896 typename rewrap<TemplateTypeList<Containers>, Types...>::type...>::type; \
897 }; \
898 template <template <typename...> class Final, template <typename...> class List, typename... Ts> \
899 struct convert<Final, List<Ts...>> \
900 { \
901 using type = typename append<Final<>, TypeList<Ts>...>::type; \
902 };
903
904 #define INTERNAL_CATCH_NTTP_1(signature, ...) \
905 template <INTERNAL_CATCH_REMOVE_PARENS(signature)> struct Nttp \
906 { \
907 }; \
908 template <INTERNAL_CATCH_REMOVE_PARENS(signature)> \
909 constexpr auto get_wrapper() noexcept -> Nttp<__VA_ARGS__> \
910 { \
911 return {}; \
912 } \
913 template <template <INTERNAL_CATCH_REMOVE_PARENS(signature)> class...> \
914 struct NttpTemplateTypeList \
915 { \
916 }; \
917 template <template <INTERNAL_CATCH_REMOVE_PARENS(signature)> class... Cs> \
918 constexpr auto get_wrapper() noexcept -> NttpTemplateTypeList<Cs...> \
919 { \
920 return {}; \
921 } \
922 \
923 template <template <INTERNAL_CATCH_REMOVE_PARENS(signature)> class Container, \
924 template <INTERNAL_CATCH_REMOVE_PARENS(signature)> class List, \
925 INTERNAL_CATCH_REMOVE_PARENS(signature)> \
926 struct rewrap<NttpTemplateTypeList<Container>, List<__VA_ARGS__>> \
927 { \
928 using type = TypeList<Container<__VA_ARGS__>>; \
929 }; \
930 template <template <INTERNAL_CATCH_REMOVE_PARENS(signature)> class Container, \
931 template <INTERNAL_CATCH_REMOVE_PARENS(signature)> class List, \
932 INTERNAL_CATCH_REMOVE_PARENS(signature), typename... Elements> \
933 struct rewrap<NttpTemplateTypeList<Container>, List<__VA_ARGS__>, Elements...> \
934 { \
935 using type = typename append< \
936 TypeList<Container<__VA_ARGS__>>, \
937 typename rewrap<NttpTemplateTypeList<Container>, Elements...>::type>::type; \
938 }; \
939 template <template <typename...> class Final, \
940 template <INTERNAL_CATCH_REMOVE_PARENS(signature)> class... Containers, \
941 typename... Types> \
942 struct create<Final, NttpTemplateTypeList<Containers...>, TypeList<Types...>> \
943 { \
944 using type = typename append< \
945 Final<>, typename rewrap<NttpTemplateTypeList<Containers>, Types...>::type...>::type; \
946 };
947
948 #define INTERNAL_CATCH_DECLARE_SIG_TEST0(TestName)
949 #define INTERNAL_CATCH_DECLARE_SIG_TEST1(TestName, signature) \
950 template <INTERNAL_CATCH_REMOVE_PARENS(signature)> static void TestName()
951 #define INTERNAL_CATCH_DECLARE_SIG_TEST_X(TestName, signature, ...) \
952 template <INTERNAL_CATCH_REMOVE_PARENS(signature)> static void TestName()
953
954 #define INTERNAL_CATCH_DEFINE_SIG_TEST0(TestName)
955 #define INTERNAL_CATCH_DEFINE_SIG_TEST1(TestName, signature) \
956 template <INTERNAL_CATCH_REMOVE_PARENS(signature)> static void TestName()
957 #define INTERNAL_CATCH_DEFINE_SIG_TEST_X(TestName, signature, ...) \
958 template <INTERNAL_CATCH_REMOVE_PARENS(signature)> static void TestName()
959
960 #define INTERNAL_CATCH_NTTP_REGISTER0(TestFunc, signature) \
961 template <typename Type> void reg_test(TypeList<Type>, Catch::NameAndTags nameAndTags) \
962 { \
963 Catch::AutoReg(Catch::makeTestInvoker(&TestFunc<Type>), CATCH_INTERNAL_LINEINFO, \
964 Catch::StringRef(), nameAndTags); \
965 }
966
967 #define INTERNAL_CATCH_NTTP_REGISTER(TestFunc, signature, ...) \
968 template <INTERNAL_CATCH_REMOVE_PARENS(signature)> \
969 void reg_test(Nttp<__VA_ARGS__>, Catch::NameAndTags nameAndTags) \
970 { \
971 Catch::AutoReg(Catch::makeTestInvoker(&TestFunc<__VA_ARGS__>), CATCH_INTERNAL_LINEINFO, \
972 Catch::StringRef(), nameAndTags); \
973 }
974
975 #define INTERNAL_CATCH_NTTP_REGISTER_METHOD0(TestName, signature, ...) \
976 template <typename Type> \
977 void reg_test(TypeList<Type>, Catch::StringRef className, Catch::NameAndTags nameAndTags) \
978 { \
979 Catch::AutoReg(Catch::makeTestInvoker(&TestName<Type>::test), CATCH_INTERNAL_LINEINFO, \
980 className, nameAndTags); \
981 }
982
983 #define INTERNAL_CATCH_NTTP_REGISTER_METHOD(TestName, signature, ...) \
984 template <INTERNAL_CATCH_REMOVE_PARENS(signature)> \
985 void reg_test(Nttp<__VA_ARGS__>, Catch::StringRef className, Catch::NameAndTags nameAndTags) \
986 { \
987 Catch::AutoReg(Catch::makeTestInvoker(&TestName<__VA_ARGS__>::test), CATCH_INTERNAL_LINEINFO, \
988 className, nameAndTags); \
989 }
990
991 #define INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD0(TestName, ClassName)
992 #define INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD1(TestName, ClassName, signature) \
993 template <typename TestType> struct TestName : INTERNAL_CATCH_REMOVE_PARENS(ClassName)<TestType> \
994 { \
995 void test(); \
996 }
997
998 #define INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X(TestName, ClassName, signature, ...) \
999 template <INTERNAL_CATCH_REMOVE_PARENS(signature)> \
1000 struct TestName : INTERNAL_CATCH_REMOVE_PARENS(ClassName)<__VA_ARGS__> \
1001 { \
1002 void test(); \
1003 }
1004
1005 #define INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD0(TestName)
1006 #define INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD1(TestName, signature) \
1007 template <typename TestType> \
1008 void INTERNAL_CATCH_MAKE_NAMESPACE(TestName)::TestName<TestType>::test()
1009 #define INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X(TestName, signature, ...) \
1010 template <INTERNAL_CATCH_REMOVE_PARENS(signature)> \
1011 void INTERNAL_CATCH_MAKE_NAMESPACE(TestName)::TestName<__VA_ARGS__>::test()
1012
1013 #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
1014 #define INTERNAL_CATCH_NTTP_0
1015 #define INTERNAL_CATCH_NTTP_GEN(...) \
1016 INTERNAL_CATCH_VA_NARGS_IMPL( \
1017 __VA_ARGS__, INTERNAL_CATCH_NTTP_1(__VA_ARGS__), INTERNAL_CATCH_NTTP_1(__VA_ARGS__), \
1018 INTERNAL_CATCH_NTTP_1(__VA_ARGS__), INTERNAL_CATCH_NTTP_1(__VA_ARGS__), \
1019 INTERNAL_CATCH_NTTP_1(__VA_ARGS__), INTERNAL_CATCH_NTTP_1(__VA_ARGS__), \
1020 INTERNAL_CATCH_NTTP_1(__VA_ARGS__), INTERNAL_CATCH_NTTP_1(__VA_ARGS__), \
1021 INTERNAL_CATCH_NTTP_1(__VA_ARGS__), INTERNAL_CATCH_NTTP_1(__VA_ARGS__), \
1022 INTERNAL_CATCH_NTTP_0)
1023 #define INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD(TestName, ...) \
1024 INTERNAL_CATCH_VA_NARGS_IMPL( \
1025 "dummy", __VA_ARGS__, INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X, \
1026 INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X, \
1027 INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X, \
1028 INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X, \
1029 INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X, \
1030 INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD1, INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD0) \
1031 (TestName, __VA_ARGS__)
1032 #define INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD(TestName, ClassName, ...) \
1033 INTERNAL_CATCH_VA_NARGS_IMPL( \
1034 "dummy", __VA_ARGS__, INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X, \
1035 INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X, \
1036 INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X, \
1037 INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X, \
1038 INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X, \
1039 INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD1, INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD0) \
1040 (TestName, ClassName, __VA_ARGS__)
1041 #define INTERNAL_CATCH_NTTP_REG_METHOD_GEN(TestName, ...) \
1042 INTERNAL_CATCH_VA_NARGS_IMPL( \
1043 "dummy", __VA_ARGS__, INTERNAL_CATCH_NTTP_REGISTER_METHOD, \
1044 INTERNAL_CATCH_NTTP_REGISTER_METHOD, INTERNAL_CATCH_NTTP_REGISTER_METHOD, \
1045 INTERNAL_CATCH_NTTP_REGISTER_METHOD, INTERNAL_CATCH_NTTP_REGISTER_METHOD, \
1046 INTERNAL_CATCH_NTTP_REGISTER_METHOD, INTERNAL_CATCH_NTTP_REGISTER_METHOD, \
1047 INTERNAL_CATCH_NTTP_REGISTER_METHOD, INTERNAL_CATCH_NTTP_REGISTER_METHOD, \
1048 INTERNAL_CATCH_NTTP_REGISTER_METHOD0, INTERNAL_CATCH_NTTP_REGISTER_METHOD0) \
1049 (TestName, __VA_ARGS__)
1050 #define INTERNAL_CATCH_NTTP_REG_GEN(TestFunc, ...) \
1051 INTERNAL_CATCH_VA_NARGS_IMPL( \
1052 "dummy", __VA_ARGS__, INTERNAL_CATCH_NTTP_REGISTER, INTERNAL_CATCH_NTTP_REGISTER, \
1053 INTERNAL_CATCH_NTTP_REGISTER, INTERNAL_CATCH_NTTP_REGISTER, INTERNAL_CATCH_NTTP_REGISTER, \
1054 INTERNAL_CATCH_NTTP_REGISTER, INTERNAL_CATCH_NTTP_REGISTER, INTERNAL_CATCH_NTTP_REGISTER, \
1055 INTERNAL_CATCH_NTTP_REGISTER, INTERNAL_CATCH_NTTP_REGISTER0, INTERNAL_CATCH_NTTP_REGISTER0) \
1056 (TestFunc, __VA_ARGS__)
1057 #define INTERNAL_CATCH_DEFINE_SIG_TEST(TestName, ...) \
1058 INTERNAL_CATCH_VA_NARGS_IMPL("dummy", __VA_ARGS__, INTERNAL_CATCH_DEFINE_SIG_TEST_X, \
1059 INTERNAL_CATCH_DEFINE_SIG_TEST_X, INTERNAL_CATCH_DEFINE_SIG_TEST_X, \
1060 INTERNAL_CATCH_DEFINE_SIG_TEST_X, INTERNAL_CATCH_DEFINE_SIG_TEST_X, \
1061 INTERNAL_CATCH_DEFINE_SIG_TEST_X, INTERNAL_CATCH_DEFINE_SIG_TEST_X, \
1062 INTERNAL_CATCH_DEFINE_SIG_TEST_X, INTERNAL_CATCH_DEFINE_SIG_TEST_X, \
1063 INTERNAL_CATCH_DEFINE_SIG_TEST1, INTERNAL_CATCH_DEFINE_SIG_TEST0) \
1064 (TestName, __VA_ARGS__)
1065 #define INTERNAL_CATCH_DECLARE_SIG_TEST(TestName, ...) \
1066 INTERNAL_CATCH_VA_NARGS_IMPL( \
1067 "dummy", __VA_ARGS__, INTERNAL_CATCH_DECLARE_SIG_TEST_X, INTERNAL_CATCH_DECLARE_SIG_TEST_X, \
1068 INTERNAL_CATCH_DECLARE_SIG_TEST_X, INTERNAL_CATCH_DECLARE_SIG_TEST_X, \
1069 INTERNAL_CATCH_DECLARE_SIG_TEST_X, INTERNAL_CATCH_DECLARE_SIG_TEST_X, \
1070 INTERNAL_CATCH_DEFINE_SIG_TEST_X, INTERNAL_CATCH_DECLARE_SIG_TEST_X, \
1071 INTERNAL_CATCH_DECLARE_SIG_TEST_X, INTERNAL_CATCH_DECLARE_SIG_TEST1, \
1072 INTERNAL_CATCH_DECLARE_SIG_TEST0) \
1073 (TestName, __VA_ARGS__)
1074 #define INTERNAL_CATCH_REMOVE_PARENS_GEN(...) \
1075 INTERNAL_CATCH_VA_NARGS_IMPL( \
1076 __VA_ARGS__, INTERNAL_CATCH_REMOVE_PARENS_11_ARG, INTERNAL_CATCH_REMOVE_PARENS_10_ARG, \
1077 INTERNAL_CATCH_REMOVE_PARENS_9_ARG, INTERNAL_CATCH_REMOVE_PARENS_8_ARG, \
1078 INTERNAL_CATCH_REMOVE_PARENS_7_ARG, INTERNAL_CATCH_REMOVE_PARENS_6_ARG, \
1079 INTERNAL_CATCH_REMOVE_PARENS_5_ARG, INTERNAL_CATCH_REMOVE_PARENS_4_ARG, \
1080 INTERNAL_CATCH_REMOVE_PARENS_3_ARG, INTERNAL_CATCH_REMOVE_PARENS_2_ARG, \
1081 INTERNAL_CATCH_REMOVE_PARENS_1_ARG) \
1082 (__VA_ARGS__)
1083 #else
1084 #define INTERNAL_CATCH_NTTP_0(signature)
1085 #define INTERNAL_CATCH_NTTP_GEN(...) \
1086 INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_VA_NARGS_IMPL( \
1087 __VA_ARGS__, INTERNAL_CATCH_NTTP_1, INTERNAL_CATCH_NTTP_1, INTERNAL_CATCH_NTTP_1, \
1088 INTERNAL_CATCH_NTTP_1, INTERNAL_CATCH_NTTP_1, INTERNAL_CATCH_NTTP_1, INTERNAL_CATCH_NTTP_1, \
1089 INTERNAL_CATCH_NTTP_1, INTERNAL_CATCH_NTTP_1, INTERNAL_CATCH_NTTP_1, \
1090 INTERNAL_CATCH_NTTP_0)(__VA_ARGS__))
1091 #define INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD(TestName, ...) \
1092 INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_VA_NARGS_IMPL( \
1093 "dummy", __VA_ARGS__, INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X, \
1094 INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X, \
1095 INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X, \
1096 INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X, \
1097 INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X, \
1098 INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD1, \
1099 INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD0)(TestName, __VA_ARGS__))
1100 #define INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD(TestName, ClassName, ...) \
1101 INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_VA_NARGS_IMPL( \
1102 "dummy", __VA_ARGS__, INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X, \
1103 INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X, \
1104 INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X, \
1105 INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X, \
1106 INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X, \
1107 INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD1, \
1108 INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD0)(TestName, ClassName, __VA_ARGS__))
1109 #define INTERNAL_CATCH_NTTP_REG_METHOD_GEN(TestName, ...) \
1110 INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_VA_NARGS_IMPL( \
1111 "dummy", __VA_ARGS__, INTERNAL_CATCH_NTTP_REGISTER_METHOD, \
1112 INTERNAL_CATCH_NTTP_REGISTER_METHOD, INTERNAL_CATCH_NTTP_REGISTER_METHOD, \
1113 INTERNAL_CATCH_NTTP_REGISTER_METHOD, INTERNAL_CATCH_NTTP_REGISTER_METHOD, \
1114 INTERNAL_CATCH_NTTP_REGISTER_METHOD, INTERNAL_CATCH_NTTP_REGISTER_METHOD, \
1115 INTERNAL_CATCH_NTTP_REGISTER_METHOD, INTERNAL_CATCH_NTTP_REGISTER_METHOD, \
1116 INTERNAL_CATCH_NTTP_REGISTER_METHOD0, \
1117 INTERNAL_CATCH_NTTP_REGISTER_METHOD0)(TestName, __VA_ARGS__))
1118 #define INTERNAL_CATCH_NTTP_REG_GEN(TestFunc, ...) \
1119 INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_VA_NARGS_IMPL( \
1120 "dummy", __VA_ARGS__, INTERNAL_CATCH_NTTP_REGISTER, INTERNAL_CATCH_NTTP_REGISTER, \
1121 INTERNAL_CATCH_NTTP_REGISTER, INTERNAL_CATCH_NTTP_REGISTER, INTERNAL_CATCH_NTTP_REGISTER, \
1122 INTERNAL_CATCH_NTTP_REGISTER, INTERNAL_CATCH_NTTP_REGISTER, INTERNAL_CATCH_NTTP_REGISTER, \
1123 INTERNAL_CATCH_NTTP_REGISTER, INTERNAL_CATCH_NTTP_REGISTER0, \
1124 INTERNAL_CATCH_NTTP_REGISTER0)(TestFunc, __VA_ARGS__))
1125 #define INTERNAL_CATCH_DEFINE_SIG_TEST(TestName, ...) \
1126 INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_VA_NARGS_IMPL( \
1127 "dummy", __VA_ARGS__, INTERNAL_CATCH_DEFINE_SIG_TEST_X, INTERNAL_CATCH_DEFINE_SIG_TEST_X, \
1128 INTERNAL_CATCH_DEFINE_SIG_TEST_X, INTERNAL_CATCH_DEFINE_SIG_TEST_X, \
1129 INTERNAL_CATCH_DEFINE_SIG_TEST_X, INTERNAL_CATCH_DEFINE_SIG_TEST_X, \
1130 INTERNAL_CATCH_DEFINE_SIG_TEST_X, INTERNAL_CATCH_DEFINE_SIG_TEST_X, \
1131 INTERNAL_CATCH_DEFINE_SIG_TEST_X, INTERNAL_CATCH_DEFINE_SIG_TEST1, \
1132 INTERNAL_CATCH_DEFINE_SIG_TEST0)(TestName, __VA_ARGS__))
1133 #define INTERNAL_CATCH_DECLARE_SIG_TEST(TestName, ...) \
1134 INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_VA_NARGS_IMPL( \
1135 "dummy", __VA_ARGS__, INTERNAL_CATCH_DECLARE_SIG_TEST_X, INTERNAL_CATCH_DECLARE_SIG_TEST_X, \
1136 INTERNAL_CATCH_DECLARE_SIG_TEST_X, INTERNAL_CATCH_DECLARE_SIG_TEST_X, \
1137 INTERNAL_CATCH_DECLARE_SIG_TEST_X, INTERNAL_CATCH_DECLARE_SIG_TEST_X, \
1138 INTERNAL_CATCH_DEFINE_SIG_TEST_X, INTERNAL_CATCH_DECLARE_SIG_TEST_X, \
1139 INTERNAL_CATCH_DECLARE_SIG_TEST_X, INTERNAL_CATCH_DECLARE_SIG_TEST1, \
1140 INTERNAL_CATCH_DECLARE_SIG_TEST0)(TestName, __VA_ARGS__))
1141 #define INTERNAL_CATCH_REMOVE_PARENS_GEN(...) \
1142 INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_VA_NARGS_IMPL( \
1143 __VA_ARGS__, INTERNAL_CATCH_REMOVE_PARENS_11_ARG, INTERNAL_CATCH_REMOVE_PARENS_10_ARG, \
1144 INTERNAL_CATCH_REMOVE_PARENS_9_ARG, INTERNAL_CATCH_REMOVE_PARENS_8_ARG, \
1145 INTERNAL_CATCH_REMOVE_PARENS_7_ARG, INTERNAL_CATCH_REMOVE_PARENS_6_ARG, \
1146 INTERNAL_CATCH_REMOVE_PARENS_5_ARG, INTERNAL_CATCH_REMOVE_PARENS_4_ARG, \
1147 INTERNAL_CATCH_REMOVE_PARENS_3_ARG, INTERNAL_CATCH_REMOVE_PARENS_2_ARG, \
1148 INTERNAL_CATCH_REMOVE_PARENS_1_ARG)(__VA_ARGS__))
1149 #endif
1150
1151 // end catch_preprocessor.hpp
1152 // start catch_meta.hpp
1153
1154 #include <type_traits>
1155
1156 namespace Catch {
1157 template <typename T> struct always_false : std::false_type
1158 {
1159 };
1160
1161 template <typename> struct true_given : std::true_type
1162 {
1163 };
1164 struct is_callable_tester
1165 {
1166 template <typename Fun, typename... Args>
1167 true_given<decltype(std::declval<Fun>()(std::declval<Args>()...))> static test(int);
1168 template <typename...> std::false_type static test(...);
1169 };
1170
1171 template <typename T> struct is_callable;
1172
1173 template <typename Fun, typename... Args>
1174 struct is_callable<Fun(Args...)> : decltype(is_callable_tester::test<Fun, Args...>(0))
1175 {
1176 };
1177
1178 #if defined(__cpp_lib_is_invocable) && __cpp_lib_is_invocable >= 201703
1179 // std::result_of is deprecated in C++17 and removed in C++20. Hence, it is
1180 // replaced with std::invoke_result here.
1181 template <typename Func, typename... U>
1182 using FunctionReturnType =
1183 std::remove_reference_t<std::remove_cv_t<std::invoke_result_t<Func, U...>>>;
1184 #else
1185 // Keep ::type here because we still support C++11
1186 template <typename Func, typename... U>
1187 using FunctionReturnType = typename std::remove_reference<
1188 typename std::remove_cv<typename std::result_of<Func(U...)>::type>::type>::type;
1189 #endif
1190
1191 } // namespace Catch
1192
1193 namespace mpl_ {
1194 struct na;
1195 }
1196
1197 // end catch_meta.hpp
1198 namespace Catch {
1199
1200 template <typename C> class TestInvokerAsMethod : public ITestInvoker
1201 {
1202 void (C::*m_testAsMethod)();
1203
1204 public:
1205 TestInvokerAsMethod(void (C::*testAsMethod)()) noexcept : m_testAsMethod(testAsMethod) {}
1206
1207 void invoke() const override
1208 {
1209 C obj;
1210 (obj.*m_testAsMethod)();
1211 }
1212 };
1213
1214 auto makeTestInvoker(void (*testAsFunction)()) noexcept -> ITestInvoker *;
1215
1216 template <typename C> auto makeTestInvoker(void (C::*testAsMethod)()) noexcept -> ITestInvoker *
1217 {
1218 return new (std::nothrow) TestInvokerAsMethod<C>(testAsMethod);
1219 }
1220
1221 struct NameAndTags
1222 {
1223 NameAndTags(StringRef const &name_ = StringRef(),
1224 StringRef const &tags_ = StringRef()) noexcept;
1225 StringRef name;
1226 StringRef tags;
1227 };
1228
1229 struct AutoReg : NonCopyable
1230 {
1231 AutoReg(ITestInvoker *invoker, SourceLineInfo const &lineInfo, StringRef const &classOrMethod,
1232 NameAndTags const &nameAndTags) noexcept;
1233 ~AutoReg();
1234 };
1235
1236 } // end namespace Catch
1237
1238 #if defined(CATCH_CONFIG_DISABLE)
1239 #define INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(TestName, ...) static void TestName()
1240 #define INTERNAL_CATCH_TESTCASE_METHOD_NO_REGISTRATION(TestName, ClassName, ...) \
1241 namespace { \
1242 struct TestName : INTERNAL_CATCH_REMOVE_PARENS(ClassName) \
1243 { \
1244 void test(); \
1245 }; \
1246 } \
1247 void TestName::test()
1248 #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION_2(TestName, TestFunc, Name, Tags, \
1249 Signature, ...) \
1250 INTERNAL_CATCH_DEFINE_SIG_TEST(TestFunc, INTERNAL_CATCH_REMOVE_PARENS(Signature))
1251 #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION_2( \
1252 TestNameClass, TestName, ClassName, Name, Tags, Signature, ...) \
1253 namespace { \
1254 namespace INTERNAL_CATCH_MAKE_NAMESPACE(TestName) { \
1255 INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD(TestName, ClassName, \
1256 INTERNAL_CATCH_REMOVE_PARENS(Signature)); \
1257 } \
1258 } \
1259 INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD(TestName, INTERNAL_CATCH_REMOVE_PARENS(Signature))
1260
1261 #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
1262 #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION(Name, Tags, ...) \
1263 INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION_2( \
1264 INTERNAL_CATCH_UNIQUE_NAME(____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____), \
1265 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____), \
1266 Name, Tags, typename TestType, __VA_ARGS__)
1267 #else
1268 #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION(Name, Tags, ...) \
1269 INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION_2( \
1270 INTERNAL_CATCH_UNIQUE_NAME(____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____), \
1271 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____), \
1272 Name, Tags, typename TestType, __VA_ARGS__))
1273 #endif
1274
1275 #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
1276 #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG_NO_REGISTRATION(Name, Tags, Signature, ...) \
1277 INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION_2( \
1278 INTERNAL_CATCH_UNIQUE_NAME(____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____), \
1279 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____), \
1280 Name, Tags, Signature, __VA_ARGS__)
1281 #else
1282 #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG_NO_REGISTRATION(Name, Tags, Signature, ...) \
1283 INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION_2( \
1284 INTERNAL_CATCH_UNIQUE_NAME(____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____), \
1285 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____), \
1286 Name, Tags, Signature, __VA_ARGS__))
1287 #endif
1288
1289 #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
1290 #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION(ClassName, Name, Tags, ...) \
1291 INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION_2( \
1292 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____), \
1293 INTERNAL_CATCH_UNIQUE_NAME(____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____), ClassName, \
1294 Name, Tags, typename T, __VA_ARGS__)
1295 #else
1296 #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION(ClassName, Name, Tags, ...) \
1297 INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION_2( \
1298 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____), \
1299 INTERNAL_CATCH_UNIQUE_NAME(____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____), ClassName, \
1300 Name, Tags, typename T, __VA_ARGS__))
1301 #endif
1302
1303 #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
1304 #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG_NO_REGISTRATION(ClassName, Name, Tags, \
1305 Signature, ...) \
1306 INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION_2( \
1307 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____), \
1308 INTERNAL_CATCH_UNIQUE_NAME(____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____), ClassName, \
1309 Name, Tags, Signature, __VA_ARGS__)
1310 #else
1311 #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG_NO_REGISTRATION(ClassName, Name, Tags, \
1312 Signature, ...) \
1313 INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION_2( \
1314 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____), \
1315 INTERNAL_CATCH_UNIQUE_NAME(____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____), ClassName, \
1316 Name, Tags, Signature, __VA_ARGS__))
1317 #endif
1318 #endif
1319
1320 ///////////////////////////////////////////////////////////////////////////////
1321 #define INTERNAL_CATCH_TESTCASE2(TestName, ...) \
1322 static void TestName(); \
1323 CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \
1324 CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
1325 namespace { \
1326 Catch::AutoReg INTERNAL_CATCH_UNIQUE_NAME(autoRegistrar)(Catch::makeTestInvoker(&TestName), \
1327 CATCH_INTERNAL_LINEINFO, \
1328 Catch::StringRef(), \
1329 Catch::NameAndTags{__VA_ARGS__}); \
1330 } /* NOLINT */ \
1331 CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION \
1332 static void TestName()
1333 #define INTERNAL_CATCH_TESTCASE(...) \
1334 INTERNAL_CATCH_TESTCASE2(INTERNAL_CATCH_UNIQUE_NAME(____C_A_T_C_H____T_E_S_T____), __VA_ARGS__)
1335
1336 ///////////////////////////////////////////////////////////////////////////////
1337 #define INTERNAL_CATCH_METHOD_AS_TEST_CASE(QualifiedMethod, ...) \
1338 CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \
1339 CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
1340 namespace { \
1341 Catch::AutoReg \
1342 INTERNAL_CATCH_UNIQUE_NAME(autoRegistrar)(Catch::makeTestInvoker(&QualifiedMethod), \
1343 CATCH_INTERNAL_LINEINFO, "&" #QualifiedMethod, \
1344 Catch::NameAndTags{__VA_ARGS__}); \
1345 } /* NOLINT */ \
1346 CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION
1347
1348 ///////////////////////////////////////////////////////////////////////////////
1349 #define INTERNAL_CATCH_TEST_CASE_METHOD2(TestName, ClassName, ...) \
1350 CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \
1351 CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
1352 namespace { \
1353 struct TestName : INTERNAL_CATCH_REMOVE_PARENS(ClassName) \
1354 { \
1355 void test(); \
1356 }; \
1357 Catch::AutoReg \
1358 INTERNAL_CATCH_UNIQUE_NAME(autoRegistrar)(Catch::makeTestInvoker(&TestName::test), \
1359 CATCH_INTERNAL_LINEINFO, #ClassName, \
1360 Catch::NameAndTags{__VA_ARGS__}); /* NOLINT */ \
1361 } \
1362 CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION \
1363 void TestName::test()
1364 #define INTERNAL_CATCH_TEST_CASE_METHOD(ClassName, ...) \
1365 INTERNAL_CATCH_TEST_CASE_METHOD2(INTERNAL_CATCH_UNIQUE_NAME(____C_A_T_C_H____T_E_S_T____), \
1366 ClassName, __VA_ARGS__)
1367
1368 ///////////////////////////////////////////////////////////////////////////////
1369 #define INTERNAL_CATCH_REGISTER_TESTCASE(Function, ...) \
1370 CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \
1371 CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
1372 Catch::AutoReg INTERNAL_CATCH_UNIQUE_NAME(autoRegistrar)( \
1373 Catch::makeTestInvoker(Function), CATCH_INTERNAL_LINEINFO, Catch::StringRef(), \
1374 Catch::NameAndTags{__VA_ARGS__}); /* NOLINT */ \
1375 CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION
1376
1377 ///////////////////////////////////////////////////////////////////////////////
1378 #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_2(TestName, TestFunc, Name, Tags, Signature, ...) \
1379 CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \
1380 CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
1381 CATCH_INTERNAL_SUPPRESS_ZERO_VARIADIC_WARNINGS \
1382 CATCH_INTERNAL_SUPPRESS_UNUSED_TEMPLATE_WARNINGS \
1383 INTERNAL_CATCH_DECLARE_SIG_TEST(TestFunc, INTERNAL_CATCH_REMOVE_PARENS(Signature)); \
1384 namespace { \
1385 namespace INTERNAL_CATCH_MAKE_NAMESPACE(TestName) { \
1386 INTERNAL_CATCH_TYPE_GEN \
1387 INTERNAL_CATCH_NTTP_GEN(INTERNAL_CATCH_REMOVE_PARENS(Signature)) \
1388 INTERNAL_CATCH_NTTP_REG_GEN(TestFunc, INTERNAL_CATCH_REMOVE_PARENS(Signature)) \
1389 template <typename... Types> struct TestName \
1390 { \
1391 TestName() \
1392 { \
1393 int index = 0; \
1394 constexpr char const *tmpl_types[] = { \
1395 CATCH_REC_LIST(INTERNAL_CATCH_STRINGIZE_WITHOUT_PARENS, __VA_ARGS__)}; \
1396 using expander = int[]; \
1397 (void)expander{ \
1398 (reg_test(Types{}, \
1399 Catch::NameAndTags{Name " - " + std::string(tmpl_types[index]), Tags}), \
1400 index++)...}; /* NOLINT */ \
1401 } \
1402 }; \
1403 static int INTERNAL_CATCH_UNIQUE_NAME(globalRegistrar) = []() { \
1404 TestName<INTERNAL_CATCH_MAKE_TYPE_LISTS_FROM_TYPES(__VA_ARGS__)>(); \
1405 return 0; \
1406 }(); \
1407 } \
1408 } \
1409 CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION \
1410 INTERNAL_CATCH_DEFINE_SIG_TEST(TestFunc, INTERNAL_CATCH_REMOVE_PARENS(Signature))
1411
1412 #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
1413 #define INTERNAL_CATCH_TEMPLATE_TEST_CASE(Name, Tags, ...) \
1414 INTERNAL_CATCH_TEMPLATE_TEST_CASE_2( \
1415 INTERNAL_CATCH_UNIQUE_NAME(____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____), \
1416 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____), \
1417 Name, Tags, typename TestType, __VA_ARGS__)
1418 #else
1419 #define INTERNAL_CATCH_TEMPLATE_TEST_CASE(Name, Tags, ...) \
1420 INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_TEMPLATE_TEST_CASE_2( \
1421 INTERNAL_CATCH_UNIQUE_NAME(____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____), \
1422 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____), \
1423 Name, Tags, typename TestType, __VA_ARGS__))
1424 #endif
1425
1426 #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
1427 #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG(Name, Tags, Signature, ...) \
1428 INTERNAL_CATCH_TEMPLATE_TEST_CASE_2( \
1429 INTERNAL_CATCH_UNIQUE_NAME(____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____), \
1430 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____), \
1431 Name, Tags, Signature, __VA_ARGS__)
1432 #else
1433 #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG(Name, Tags, Signature, ...) \
1434 INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_TEMPLATE_TEST_CASE_2( \
1435 INTERNAL_CATCH_UNIQUE_NAME(____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____), \
1436 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____), \
1437 Name, Tags, Signature, __VA_ARGS__))
1438 #endif
1439
1440 #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE2(TestName, TestFuncName, Name, Tags, Signature, \
1441 TmplTypes, TypesList) \
1442 CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \
1443 CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
1444 CATCH_INTERNAL_SUPPRESS_ZERO_VARIADIC_WARNINGS \
1445 CATCH_INTERNAL_SUPPRESS_UNUSED_TEMPLATE_WARNINGS \
1446 template <typename TestType> static void TestFuncName(); \
1447 namespace { \
1448 namespace INTERNAL_CATCH_MAKE_NAMESPACE(TestName) { \
1449 INTERNAL_CATCH_TYPE_GEN \
1450 INTERNAL_CATCH_NTTP_GEN(INTERNAL_CATCH_REMOVE_PARENS(Signature)) \
1451 template <typename... Types> struct TestName \
1452 { \
1453 void reg_tests() \
1454 { \
1455 int index = 0; \
1456 using expander = int[]; \
1457 constexpr char const *tmpl_types[] = {CATCH_REC_LIST( \
1458 INTERNAL_CATCH_STRINGIZE_WITHOUT_PARENS, INTERNAL_CATCH_REMOVE_PARENS(TmplTypes))}; \
1459 constexpr char const *types_list[] = {CATCH_REC_LIST( \
1460 INTERNAL_CATCH_STRINGIZE_WITHOUT_PARENS, INTERNAL_CATCH_REMOVE_PARENS(TypesList))}; \
1461 constexpr auto num_types = sizeof(types_list) / sizeof(types_list[0]); \
1462 (void)expander{ \
1463 (Catch::AutoReg( \
1464 Catch::makeTestInvoker(&TestFuncName<Types>), CATCH_INTERNAL_LINEINFO, \
1465 Catch::StringRef(), \
1466 Catch::NameAndTags{Name " - " + std::string(tmpl_types[index / num_types]) + \
1467 "<" + std::string(types_list[index % num_types]) + ">", \
1468 Tags}), \
1469 index++)...}; /* NOLINT */ \
1470 } \
1471 }; \
1472 static int INTERNAL_CATCH_UNIQUE_NAME(globalRegistrar) = []() { \
1473 using TestInit = \
1474 typename create<TestName, \
1475 decltype(get_wrapper<INTERNAL_CATCH_REMOVE_PARENS(TmplTypes)>()), \
1476 TypeList<INTERNAL_CATCH_MAKE_TYPE_LISTS_FROM_TYPES( \
1477 INTERNAL_CATCH_REMOVE_PARENS(TypesList))>>::type; \
1478 TestInit t; \
1479 t.reg_tests(); \
1480 return 0; \
1481 }(); \
1482 } \
1483 } \
1484 CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION \
1485 template <typename TestType> static void TestFuncName()
1486
1487 #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
1488 #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE(Name, Tags, ...) \
1489 INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE2( \
1490 INTERNAL_CATCH_UNIQUE_NAME(____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____), \
1491 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____), \
1492 Name, Tags, typename T, __VA_ARGS__)
1493 #else
1494 #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE(Name, Tags, ...) \
1495 INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE2( \
1496 INTERNAL_CATCH_UNIQUE_NAME(____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____), \
1497 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____), \
1498 Name, Tags, typename T, __VA_ARGS__))
1499 #endif
1500
1501 #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
1502 #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG(Name, Tags, Signature, ...) \
1503 INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE2( \
1504 INTERNAL_CATCH_UNIQUE_NAME(____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____), \
1505 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____), \
1506 Name, Tags, Signature, __VA_ARGS__)
1507 #else
1508 #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG(Name, Tags, Signature, ...) \
1509 INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE2( \
1510 INTERNAL_CATCH_UNIQUE_NAME(____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____), \
1511 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____), \
1512 Name, Tags, Signature, __VA_ARGS__))
1513 #endif
1514
1515 #define INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE_2(TestName, TestFunc, Name, Tags, TmplList) \
1516 CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \
1517 CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
1518 CATCH_INTERNAL_SUPPRESS_UNUSED_TEMPLATE_WARNINGS \
1519 template <typename TestType> static void TestFunc(); \
1520 namespace { \
1521 namespace INTERNAL_CATCH_MAKE_NAMESPACE(TestName) { \
1522 INTERNAL_CATCH_TYPE_GEN \
1523 template <typename... Types> struct TestName \
1524 { \
1525 void reg_tests() \
1526 { \
1527 int index = 0; \
1528 using expander = int[]; \
1529 (void)expander{ \
1530 (Catch::AutoReg(Catch::makeTestInvoker(&TestFunc<Types>), CATCH_INTERNAL_LINEINFO, \
1531 Catch::StringRef(), \
1532 Catch::NameAndTags{ \
1533 Name " - " + std::string(INTERNAL_CATCH_STRINGIZE(TmplList)) + \
1534 " - " + std::to_string(index), \
1535 Tags}), \
1536 index++)...}; /* NOLINT */ \
1537 } \
1538 }; \
1539 static int INTERNAL_CATCH_UNIQUE_NAME(globalRegistrar) = []() { \
1540 using TestInit = typename convert<TestName, TmplList>::type; \
1541 TestInit t; \
1542 t.reg_tests(); \
1543 return 0; \
1544 }(); \
1545 } \
1546 } \
1547 CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION \
1548 template <typename TestType> static void TestFunc()
1549
1550 #define INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE(Name, Tags, TmplList) \
1551 INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE_2( \
1552 INTERNAL_CATCH_UNIQUE_NAME(____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____), \
1553 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____), \
1554 Name, Tags, TmplList)
1555
1556 #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_2(TestNameClass, TestName, ClassName, Name, Tags, \
1557 Signature, ...) \
1558 CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \
1559 CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
1560 CATCH_INTERNAL_SUPPRESS_ZERO_VARIADIC_WARNINGS \
1561 CATCH_INTERNAL_SUPPRESS_UNUSED_TEMPLATE_WARNINGS \
1562 namespace { \
1563 namespace INTERNAL_CATCH_MAKE_NAMESPACE(TestName) { \
1564 INTERNAL_CATCH_TYPE_GEN \
1565 INTERNAL_CATCH_NTTP_GEN(INTERNAL_CATCH_REMOVE_PARENS(Signature)) \
1566 INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD(TestName, ClassName, \
1567 INTERNAL_CATCH_REMOVE_PARENS(Signature)); \
1568 INTERNAL_CATCH_NTTP_REG_METHOD_GEN(TestName, INTERNAL_CATCH_REMOVE_PARENS(Signature)) \
1569 template <typename... Types> struct TestNameClass \
1570 { \
1571 TestNameClass() \
1572 { \
1573 int index = 0; \
1574 constexpr char const *tmpl_types[] = { \
1575 CATCH_REC_LIST(INTERNAL_CATCH_STRINGIZE_WITHOUT_PARENS, __VA_ARGS__)}; \
1576 using expander = int[]; \
1577 (void)expander{ \
1578 (reg_test(Types{}, #ClassName, \
1579 Catch::NameAndTags{Name " - " + std::string(tmpl_types[index]), Tags}), \
1580 index++)...}; /* NOLINT */ \
1581 } \
1582 }; \
1583 static int INTERNAL_CATCH_UNIQUE_NAME(globalRegistrar) = []() { \
1584 TestNameClass<INTERNAL_CATCH_MAKE_TYPE_LISTS_FROM_TYPES(__VA_ARGS__)>(); \
1585 return 0; \
1586 }(); \
1587 } \
1588 } \
1589 CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION \
1590 INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD(TestName, INTERNAL_CATCH_REMOVE_PARENS(Signature))
1591
1592 #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
1593 #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD(ClassName, Name, Tags, ...) \
1594 INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_2( \
1595 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____), \
1596 INTERNAL_CATCH_UNIQUE_NAME(____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____), ClassName, \
1597 Name, Tags, typename T, __VA_ARGS__)
1598 #else
1599 #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD(ClassName, Name, Tags, ...) \
1600 INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_2( \
1601 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____), \
1602 INTERNAL_CATCH_UNIQUE_NAME(____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____), ClassName, \
1603 Name, Tags, typename T, __VA_ARGS__))
1604 #endif
1605
1606 #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
1607 #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG(ClassName, Name, Tags, Signature, ...) \
1608 INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_2( \
1609 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____), \
1610 INTERNAL_CATCH_UNIQUE_NAME(____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____), ClassName, \
1611 Name, Tags, Signature, __VA_ARGS__)
1612 #else
1613 #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG(ClassName, Name, Tags, Signature, ...) \
1614 INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_2( \
1615 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____), \
1616 INTERNAL_CATCH_UNIQUE_NAME(____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____), ClassName, \
1617 Name, Tags, Signature, __VA_ARGS__))
1618 #endif
1619
1620 #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_2( \
1621 TestNameClass, TestName, ClassName, Name, Tags, Signature, TmplTypes, TypesList) \
1622 CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \
1623 CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
1624 CATCH_INTERNAL_SUPPRESS_ZERO_VARIADIC_WARNINGS \
1625 CATCH_INTERNAL_SUPPRESS_UNUSED_TEMPLATE_WARNINGS \
1626 template <typename TestType> struct TestName : INTERNAL_CATCH_REMOVE_PARENS(ClassName<TestType>) \
1627 { \
1628 void test(); \
1629 }; \
1630 namespace { \
1631 namespace INTERNAL_CATCH_MAKE_NAMESPACE(TestNameClass) { \
1632 INTERNAL_CATCH_TYPE_GEN \
1633 INTERNAL_CATCH_NTTP_GEN(INTERNAL_CATCH_REMOVE_PARENS(Signature)) \
1634 template <typename... Types> struct TestNameClass \
1635 { \
1636 void reg_tests() \
1637 { \
1638 int index = 0; \
1639 using expander = int[]; \
1640 constexpr char const *tmpl_types[] = {CATCH_REC_LIST( \
1641 INTERNAL_CATCH_STRINGIZE_WITHOUT_PARENS, INTERNAL_CATCH_REMOVE_PARENS(TmplTypes))}; \
1642 constexpr char const *types_list[] = {CATCH_REC_LIST( \
1643 INTERNAL_CATCH_STRINGIZE_WITHOUT_PARENS, INTERNAL_CATCH_REMOVE_PARENS(TypesList))}; \
1644 constexpr auto num_types = sizeof(types_list) / sizeof(types_list[0]); \
1645 (void)expander{ \
1646 (Catch::AutoReg( \
1647 Catch::makeTestInvoker(&TestName<Types>::test), CATCH_INTERNAL_LINEINFO, \
1648 #ClassName, \
1649 Catch::NameAndTags{Name " - " + std::string(tmpl_types[index / num_types]) + \
1650 "<" + std::string(types_list[index % num_types]) + ">", \
1651 Tags}), \
1652 index++)...}; /* NOLINT */ \
1653 } \
1654 }; \
1655 static int INTERNAL_CATCH_UNIQUE_NAME(globalRegistrar) = []() { \
1656 using TestInit = \
1657 typename create<TestNameClass, \
1658 decltype(get_wrapper<INTERNAL_CATCH_REMOVE_PARENS(TmplTypes)>()), \
1659 TypeList<INTERNAL_CATCH_MAKE_TYPE_LISTS_FROM_TYPES( \
1660 INTERNAL_CATCH_REMOVE_PARENS(TypesList))>>::type; \
1661 TestInit t; \
1662 t.reg_tests(); \
1663 return 0; \
1664 }(); \
1665 } \
1666 } \
1667 CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION \
1668 template <typename TestType> void TestName<TestType>::test()
1669
1670 #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
1671 #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD(ClassName, Name, Tags, ...) \
1672 INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_2( \
1673 INTERNAL_CATCH_UNIQUE_NAME(____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____), \
1674 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____), \
1675 ClassName, Name, Tags, typename T, __VA_ARGS__)
1676 #else
1677 #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD(ClassName, Name, Tags, ...) \
1678 INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_2( \
1679 INTERNAL_CATCH_UNIQUE_NAME(____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____), \
1680 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____), \
1681 ClassName, Name, Tags, typename T, __VA_ARGS__))
1682 #endif
1683
1684 #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
1685 #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG(ClassName, Name, Tags, Signature, \
1686 ...) \
1687 INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_2( \
1688 INTERNAL_CATCH_UNIQUE_NAME(____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____), \
1689 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____), \
1690 ClassName, Name, Tags, Signature, __VA_ARGS__)
1691 #else
1692 #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG(ClassName, Name, Tags, Signature, \
1693 ...) \
1694 INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_2( \
1695 INTERNAL_CATCH_UNIQUE_NAME(____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____), \
1696 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____), \
1697 ClassName, Name, Tags, Signature, __VA_ARGS__))
1698 #endif
1699
1700 #define INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE_METHOD_2(TestNameClass, TestName, ClassName, Name, \
1701 Tags, TmplList) \
1702 CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \
1703 CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
1704 CATCH_INTERNAL_SUPPRESS_UNUSED_TEMPLATE_WARNINGS \
1705 template <typename TestType> struct TestName : INTERNAL_CATCH_REMOVE_PARENS(ClassName<TestType>) \
1706 { \
1707 void test(); \
1708 }; \
1709 namespace { \
1710 namespace INTERNAL_CATCH_MAKE_NAMESPACE(TestName) { \
1711 INTERNAL_CATCH_TYPE_GEN \
1712 template <typename... Types> struct TestNameClass \
1713 { \
1714 void reg_tests() \
1715 { \
1716 int index = 0; \
1717 using expander = int[]; \
1718 (void)expander{ \
1719 (Catch::AutoReg(Catch::makeTestInvoker(&TestName<Types>::test), \
1720 CATCH_INTERNAL_LINEINFO, #ClassName, \
1721 Catch::NameAndTags{ \
1722 Name " - " + std::string(INTERNAL_CATCH_STRINGIZE(TmplList)) + \
1723 " - " + std::to_string(index), \
1724 Tags}), \
1725 index++)...}; /* NOLINT */ \
1726 } \
1727 }; \
1728 static int INTERNAL_CATCH_UNIQUE_NAME(globalRegistrar) = []() { \
1729 using TestInit = typename convert<TestNameClass, TmplList>::type; \
1730 TestInit t; \
1731 t.reg_tests(); \
1732 return 0; \
1733 }(); \
1734 } \
1735 } \
1736 CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION \
1737 template <typename TestType> void TestName<TestType>::test()
1738
1739 #define INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE_METHOD(ClassName, Name, Tags, TmplList) \
1740 INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE_METHOD_2( \
1741 INTERNAL_CATCH_UNIQUE_NAME(____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____), \
1742 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____), \
1743 ClassName, Name, Tags, TmplList)
1744
1745 // end catch_test_registry.h
1746 // start catch_capture.hpp
1747
1748 // start catch_assertionhandler.h
1749
1750 // start catch_assertioninfo.h
1751
1752 // start catch_result_type.h
1753
1754 namespace Catch {
1755
1756 // ResultWas::OfType enum
1757 struct ResultWas
1758 {
1759 enum OfType {
1760 Unknown = -1,
1761 Ok = 0,
1762 Info = 1,
1763 Warning = 2,
1764
1765 FailureBit = 0x10,
1766
1767 ExpressionFailed = FailureBit | 1,
1768 ExplicitFailure = FailureBit | 2,
1769
1770 Exception = 0x100 | FailureBit,
1771
1772 ThrewException = Exception | 1,
1773 DidntThrowException = Exception | 2,
1774
1775 FatalErrorCondition = 0x200 | FailureBit
1776
1777 };
1778 };
1779
1780 bool isOk(ResultWas::OfType resultType);
1781 bool isJustInfo(int flags);
1782
1783 // ResultDisposition::Flags enum
1784 struct ResultDisposition
1785 {
1786 enum Flags {
1787 Normal = 0x01,
1788
1789 ContinueOnFailure = 0x02, // Failures fail test, but execution continues
1790 FalseTest = 0x04, // Prefix expression with !
1791 SuppressFail = 0x08 // Failures are reported but do not fail the test
1792 };
1793 };
1794
1795 ResultDisposition::Flags operator|(ResultDisposition::Flags lhs, ResultDisposition::Flags rhs);
1796
1797 bool shouldContinueOnFailure(int flags);
1798 inline bool isFalseTest(int flags) { return (flags & ResultDisposition::FalseTest) != 0; }
1799 bool shouldSuppressFailure(int flags);
1800
1801 } // end namespace Catch
1802
1803 // end catch_result_type.h
1804 namespace Catch {
1805
1806 struct AssertionInfo
1807 {
1808 StringRef macroName;
1809 SourceLineInfo lineInfo;
1810 StringRef capturedExpression;
1811 ResultDisposition::Flags resultDisposition;
1812
1813 // We want to delete this constructor but a compiler bug in 4.8 means
1814 // the struct is then treated as non-aggregate
1815 // AssertionInfo() = delete;
1816 };
1817
1818 } // end namespace Catch
1819
1820 // end catch_assertioninfo.h
1821 // start catch_decomposer.h
1822
1823 // start catch_tostring.h
1824
1825 #include <cstddef>
1826 #include <string>
1827 #include <type_traits>
1828 #include <vector>
1829 // start catch_stream.h
1830
1831 #include <cstddef>
1832 #include <iosfwd>
1833 #include <ostream>
1834
1835 namespace Catch {
1836
1837 std::ostream &cout();
1838 std::ostream &cerr();
1839 std::ostream &clog();
1840
1841 class StringRef;
1842
1843 struct IStream
1844 {
1845 virtual ~IStream();
1846 virtual std::ostream &stream() const = 0;
1847 };
1848
1849 auto makeStream(StringRef const &filename) -> IStream const *;
1850
1851 class ReusableStringStream : NonCopyable
1852 {
1853 std::size_t m_index;
1854 std::ostream *m_oss;
1855
1856 public:
1857 ReusableStringStream();
1858 ~ReusableStringStream();
1859
1860 auto str() const -> std::string;
1861
1862 template <typename T> auto operator<<(T const &value) -> ReusableStringStream &
1863 {
1864 *m_oss << value;
1865 return *this;
1866 }
1867 auto get() -> std::ostream & { return *m_oss; }
1868 };
1869 } // namespace Catch
1870
1871 // end catch_stream.h
1872 // start catch_interfaces_enum_values_registry.h
1873
1874 #include <vector>
1875
1876 namespace Catch {
1877
1878 namespace Detail {
1879 struct EnumInfo
1880 {
1881 StringRef m_name;
1882 std::vector<std::pair<int, StringRef>> m_values;
1883
1884 ~EnumInfo();
1885
1886 StringRef lookup(int value) const;
1887 };
1888 } // namespace Detail
1889
1890 struct IMutableEnumValuesRegistry
1891 {
1892 virtual ~IMutableEnumValuesRegistry();
1893
1894 virtual Detail::EnumInfo const &registerEnum(StringRef enumName, StringRef allEnums,
1895 std::vector<int> const &values) = 0;
1896
1897 template <typename E>
1898 Detail::EnumInfo const &registerEnum(StringRef enumName, StringRef allEnums,
1899 std::initializer_list<E> values)
1900 {
1901 static_assert(sizeof(int) >= sizeof(E), "Cannot serialize enum to int");
1902 std::vector<int> intValues;
1903 intValues.reserve(values.size());
1904 for (auto enumValue : values)
1905 intValues.push_back(static_cast<int>(enumValue));
1906 return registerEnum(enumName, allEnums, intValues);
1907 }
1908 };
1909
1910 } // namespace Catch
1911
1912 // end catch_interfaces_enum_values_registry.h
1913
1914 #ifdef CATCH_CONFIG_CPP17_STRING_VIEW
1915 #include <string_view>
1916 #endif
1917
1918 #ifdef __OBJC__
1919 // start catch_objc_arc.hpp
1920
1921 #import <Foundation/Foundation.h>
1922
1923 #ifdef __has_feature
1924 #define CATCH_ARC_ENABLED __has_feature(objc_arc)
1925 #else
1926 #define CATCH_ARC_ENABLED 0
1927 #endif
1928
1929 void arcSafeRelease(NSObject *obj);
1930 id performOptionalSelector(id obj, SEL sel);
1931
1932 #if !CATCH_ARC_ENABLED
1933 inline void arcSafeRelease(NSObject *obj) { [obj release]; }
1934 inline id performOptionalSelector(id obj, SEL sel)
1935 {
1936 if ([obj respondsToSelector:sel])
1937 return [obj performSelector:sel];
1938 return nil;
1939 }
1940 #define CATCH_UNSAFE_UNRETAINED
1941 #define CATCH_ARC_STRONG
1942 #else
1943 inline void arcSafeRelease(NSObject *) {}
1944 inline id performOptionalSelector(id obj, SEL sel)
1945 {
1946 #ifdef __clang__
1947 #pragma clang diagnostic push
1948 #pragma clang diagnostic ignored "-Warc-performSelector-leaks"
1949 #endif
1950 if ([obj respondsToSelector:sel])
1951 return [obj performSelector:sel];
1952 #ifdef __clang__
1953 #pragma clang diagnostic pop
1954 #endif
1955 return nil;
1956 }
1957 #define CATCH_UNSAFE_UNRETAINED __unsafe_unretained
1958 #define CATCH_ARC_STRONG __strong
1959 #endif
1960
1961 // end catch_objc_arc.hpp
1962 #endif
1963
1964 #ifdef _MSC_VER
1965 #pragma warning(push)
1966 #pragma warning(disable : 4180) // We attempt to stream a function (address) by const&, which MSVC
1967 // complains about but is harmless
1968 #endif
1969
1970 namespace Catch {
1971 namespace Detail {
1972
1973 extern const std::string unprintableString;
1974
1975 std::string rawMemoryToString(const void *object, std::size_t size);
1976
1977 template <typename T> std::string rawMemoryToString(const T &object)
1978 {
1979 return rawMemoryToString(&object, sizeof(object));
1980 }
1981
1982 template <typename T> class IsStreamInsertable
1983 {
1984 template <typename Stream, typename U>
1985 static auto test(int) -> decltype(std::declval<Stream &>() << std::declval<U>(),
1986 std::true_type());
1987
1988 template <typename, typename> static auto test(...) -> std::false_type;
1989
1990 public:
1991 static const bool value = decltype(test<std::ostream, const T &>(0))::value;
1992 };
1993
1994 template <typename E> std::string convertUnknownEnumToString(E e);
1995
1996 template <typename T>
1997 typename std::enable_if<!std::is_enum<T>::value && !std::is_base_of<std::exception, T>::value,
1998 std::string>::type
1999 convertUnstreamable(T const &)
2000 {
2001 return Detail::unprintableString;
2002 }
2003 template <typename T>
2004 typename std::enable_if<!std::is_enum<T>::value && std::is_base_of<std::exception, T>::value,
2005 std::string>::type
2006 convertUnstreamable(T const &ex)
2007 {
2008 return ex.what();
2009 }
2010
2011 template <typename T>
2012 typename std::enable_if<std::is_enum<T>::value, std::string>::type
2013 convertUnstreamable(T const &value)
2014 {
2015 return convertUnknownEnumToString(value);
2016 }
2017
2018 #if defined(_MANAGED)
2019 //! Convert a CLR string to a utf8 std::string
2020 template <typename T> std::string clrReferenceToString(T ^ ref)
2021 {
2022 if (ref == nullptr)
2023 return std::string("null");
2024 auto bytes = System::Text::Encoding::UTF8->GetBytes(ref->ToString());
2025 cli::pin_ptr<System::Byte> p = &bytes[0];
2026 return std::string(reinterpret_cast<char const *>(p), bytes->Length);
2027 }
2028 #endif
2029
2030 } // namespace Detail
2031
2032 // If we decide for C++14, change these to enable_if_ts
2033 template <typename T, typename = void> struct StringMaker
2034 {
2035 template <typename Fake = T>
2036 static
2037 typename std::enable_if<::Catch::Detail::IsStreamInsertable<Fake>::value, std::string>::type
2038 convert(const Fake &value)
2039 {
2040 ReusableStringStream rss;
2041 // NB: call using the function-like syntax to avoid ambiguity with
2042 // user-defined templated operator<< under clang.
2043 rss.operator<<(value);
2044 return rss.str();
2045 }
2046
2047 template <typename Fake = T>
2048 static typename std::enable_if<!::Catch::Detail::IsStreamInsertable<Fake>::value,
2049 std::string>::type
2050 convert(const Fake &value)
2051 {
2052 #if !defined(CATCH_CONFIG_FALLBACK_STRINGIFIER)
2053 return Detail::convertUnstreamable(value);
2054 #else
2055 return CATCH_CONFIG_FALLBACK_STRINGIFIER(value);
2056 #endif
2057 }
2058 };
2059
2060 namespace Detail {
2061
2062 // This function dispatches all stringification requests inside of Catch.
2063 // Should be preferably called fully qualified, like ::Catch::Detail::stringify
2064 template <typename T> std::string stringify(const T &e)
2065 {
2066 return ::Catch::StringMaker<
2067 typename std::remove_cv<typename std::remove_reference<T>::type>::type>::convert(e);
2068 }
2069
2070 template <typename E> std::string convertUnknownEnumToString(E e)
2071 {
2072 return ::Catch::Detail::stringify(static_cast<typename std::underlying_type<E>::type>(e));
2073 }
2074
2075 #if defined(_MANAGED)
2076 template <typename T> std::string stringify(T ^ e)
2077 {
2078 return ::Catch::StringMaker<T ^>::convert(e);
2079 }
2080 #endif
2081
2082 } // namespace Detail
2083
2084 // Some predefined specializations
2085
2086 template <> struct StringMaker<std::string>
2087 {
2088 static std::string convert(const std::string &str);
2089 };
2090
2091 #ifdef CATCH_CONFIG_CPP17_STRING_VIEW
2092 template <> struct StringMaker<std::string_view>
2093 {
2094 static std::string convert(std::string_view str);
2095 };
2096 #endif
2097
2098 template <> struct StringMaker<char const *>
2099 {
2100 static std::string convert(char const *str);
2101 };
2102 template <> struct StringMaker<char *>
2103 {
2104 static std::string convert(char *str);
2105 };
2106
2107 #ifdef CATCH_CONFIG_WCHAR
2108 template <> struct StringMaker<std::wstring>
2109 {
2110 static std::string convert(const std::wstring &wstr);
2111 };
2112
2113 #ifdef CATCH_CONFIG_CPP17_STRING_VIEW
2114 template <> struct StringMaker<std::wstring_view>
2115 {
2116 static std::string convert(std::wstring_view str);
2117 };
2118 #endif
2119
2120 template <> struct StringMaker<wchar_t const *>
2121 {
2122 static std::string convert(wchar_t const *str);
2123 };
2124 template <> struct StringMaker<wchar_t *>
2125 {
2126 static std::string convert(wchar_t *str);
2127 };
2128 #endif
2129
2130 // TBD: Should we use `strnlen` to ensure that we don't go out of the buffer,
2131 // while keeping string semantics?
2132 template <int SZ> struct StringMaker<char[SZ]>
2133 {
2134 static std::string convert(char const *str)
2135 {
2136 return ::Catch::Detail::stringify(std::string{str});
2137 }
2138 };
2139 template <int SZ> struct StringMaker<signed char[SZ]>
2140 {
2141 static std::string convert(signed char const *str)
2142 {
2143 return ::Catch::Detail::stringify(std::string{reinterpret_cast<char const *>(str)});
2144 }
2145 };
2146 template <int SZ> struct StringMaker<unsigned char[SZ]>
2147 {
2148 static std::string convert(unsigned char const *str)
2149 {
2150 return ::Catch::Detail::stringify(std::string{reinterpret_cast<char const *>(str)});
2151 }
2152 };
2153
2154 #if defined(CATCH_CONFIG_CPP17_BYTE)
2155 template <> struct StringMaker<std::byte>
2156 {
2157 static std::string convert(std::byte value);
2158 };
2159 #endif // defined(CATCH_CONFIG_CPP17_BYTE)
2160 template <> struct StringMaker<int>
2161 {
2162 static std::string convert(int value);
2163 };
2164 template <> struct StringMaker<long>
2165 {
2166 static std::string convert(long value);
2167 };
2168 template <> struct StringMaker<long long>
2169 {
2170 static std::string convert(long long value);
2171 };
2172 template <> struct StringMaker<unsigned int>
2173 {
2174 static std::string convert(unsigned int value);
2175 };
2176 template <> struct StringMaker<unsigned long>
2177 {
2178 static std::string convert(unsigned long value);
2179 };
2180 template <> struct StringMaker<unsigned long long>
2181 {
2182 static std::string convert(unsigned long long value);
2183 };
2184
2185 template <> struct StringMaker<bool>
2186 {
2187 static std::string convert(bool b);
2188 };
2189
2190 template <> struct StringMaker<char>
2191 {
2192 static std::string convert(char c);
2193 };
2194 template <> struct StringMaker<signed char>
2195 {
2196 static std::string convert(signed char c);
2197 };
2198 template <> struct StringMaker<unsigned char>
2199 {
2200 static std::string convert(unsigned char c);
2201 };
2202
2203 template <> struct StringMaker<std::nullptr_t>
2204 {
2205 static std::string convert(std::nullptr_t);
2206 };
2207
2208 template <> struct StringMaker<float>
2209 {
2210 static std::string convert(float value);
2211 static int precision;
2212 };
2213
2214 template <> struct StringMaker<double>
2215 {
2216 static std::string convert(double value);
2217 static int precision;
2218 };
2219
2220 template <typename T> struct StringMaker<T *>
2221 {
2222 template <typename U> static std::string convert(U *p)
2223 {
2224 if (p) {
2225 return ::Catch::Detail::rawMemoryToString(p);
2226 }
2227 else {
2228 return "nullptr";
2229 }
2230 }
2231 };
2232
2233 template <typename R, typename C> struct StringMaker<R C::*>
2234 {
2235 static std::string convert(R C::*p)
2236 {
2237 if (p) {
2238 return ::Catch::Detail::rawMemoryToString(p);
2239 }
2240 else {
2241 return "nullptr";
2242 }
2243 }
2244 };
2245
2246 #if defined(_MANAGED)
2247 template <typename T> struct StringMaker<T ^>
2248 {
2249 static std::string convert(T ^ ref) { return ::Catch::Detail::clrReferenceToString(ref); }
2250 };
2251 #endif
2252
2253 namespace Detail {
2254 template <typename InputIterator, typename Sentinel = InputIterator>
2255 std::string rangeToString(InputIterator first, Sentinel last)
2256 {
2257 ReusableStringStream rss;
2258 rss << "{ ";
2259 if (first != last) {
2260 rss << ::Catch::Detail::stringify(*first);
2261 for (++first; first != last; ++first)
2262 rss << ", " << ::Catch::Detail::stringify(*first);
2263 }
2264 rss << " }";
2265 return rss.str();
2266 }
2267 } // namespace Detail
2268
2269 #ifdef __OBJC__
2270 template <> struct StringMaker<NSString *>
2271 {
2272 static std::string convert(NSString *nsstring)
2273 {
2274 if (!nsstring)
2275 return "nil";
2276 return std::string("@") + [nsstring UTF8String];
2277 }
2278 };
2279 template <> struct StringMaker<NSObject *>
2280 {
2281 static std::string convert(NSObject *nsObject)
2282 {
2283 return ::Catch::Detail::stringify([nsObject description]);
2284 }
2285 };
2286 namespace Detail {
2287 inline std::string stringify(NSString *nsstring)
2288 {
2289 return StringMaker<NSString *>::convert(nsstring);
2290 }
2291
2292 } // namespace Detail
2293 #endif // __OBJC__
2294
2295 } // namespace Catch
2296
2297 //////////////////////////////////////////////////////
2298 // Separate std-lib types stringification, so it can be selectively enabled
2299 // This means that we do not bring in
2300
2301 #if defined(CATCH_CONFIG_ENABLE_ALL_STRINGMAKERS)
2302 #define CATCH_CONFIG_ENABLE_PAIR_STRINGMAKER
2303 #define CATCH_CONFIG_ENABLE_TUPLE_STRINGMAKER
2304 #define CATCH_CONFIG_ENABLE_VARIANT_STRINGMAKER
2305 #define CATCH_CONFIG_ENABLE_CHRONO_STRINGMAKER
2306 #define CATCH_CONFIG_ENABLE_OPTIONAL_STRINGMAKER
2307 #endif
2308
2309 // Separate std::pair specialization
2310 #if defined(CATCH_CONFIG_ENABLE_PAIR_STRINGMAKER)
2311 #include <utility>
2312 namespace Catch {
2313 template <typename T1, typename T2> struct StringMaker<std::pair<T1, T2>>
2314 {
2315 static std::string convert(const std::pair<T1, T2> &pair)
2316 {
2317 ReusableStringStream rss;
2318 rss << "{ " << ::Catch::Detail::stringify(pair.first) << ", "
2319 << ::Catch::Detail::stringify(pair.second) << " }";
2320 return rss.str();
2321 }
2322 };
2323 } // namespace Catch
2324 #endif // CATCH_CONFIG_ENABLE_PAIR_STRINGMAKER
2325
2326 #if defined(CATCH_CONFIG_ENABLE_OPTIONAL_STRINGMAKER) && defined(CATCH_CONFIG_CPP17_OPTIONAL)
2327 #include <optional>
2328 namespace Catch {
2329 template <typename T> struct StringMaker<std::optional<T>>
2330 {
2331 static std::string convert(const std::optional<T> &optional)
2332 {
2333 ReusableStringStream rss;
2334 if (optional.has_value()) {
2335 rss << ::Catch::Detail::stringify(*optional);
2336 }
2337 else {
2338 rss << "{ }";
2339 }
2340 return rss.str();
2341 }
2342 };
2343 } // namespace Catch
2344 #endif // CATCH_CONFIG_ENABLE_OPTIONAL_STRINGMAKER
2345
2346 // Separate std::tuple specialization
2347 #if defined(CATCH_CONFIG_ENABLE_TUPLE_STRINGMAKER)
2348 #include <tuple>
2349 namespace Catch {
2350 namespace Detail {
2351 template <typename Tuple, std::size_t N = 0, bool = (N < std::tuple_size<Tuple>::value)>
2352 struct TupleElementPrinter
2353 {
2354 static void print(const Tuple &tuple, std::ostream &os)
2355 {
2356 os << (N ? ", " : " ") << ::Catch::Detail::stringify(std::get<N>(tuple));
2357 TupleElementPrinter<Tuple, N + 1>::print(tuple, os);
2358 }
2359 };
2360
2361 template <typename Tuple, std::size_t N> struct TupleElementPrinter<Tuple, N, false>
2362 {
2363 static void print(const Tuple &, std::ostream &) {}
2364 };
2365
2366 } // namespace Detail
2367
2368 template <typename... Types> struct StringMaker<std::tuple<Types...>>
2369 {
2370 static std::string convert(const std::tuple<Types...> &tuple)
2371 {
2372 ReusableStringStream rss;
2373 rss << '{';
2374 Detail::TupleElementPrinter<std::tuple<Types...>>::print(tuple, rss.get());
2375 rss << " }";
2376 return rss.str();
2377 }
2378 };
2379 } // namespace Catch
2380 #endif // CATCH_CONFIG_ENABLE_TUPLE_STRINGMAKER
2381
2382 #if defined(CATCH_CONFIG_ENABLE_VARIANT_STRINGMAKER) && defined(CATCH_CONFIG_CPP17_VARIANT)
2383 #include <variant>
2384 namespace Catch {
2385 template <> struct StringMaker<std::monostate>
2386 {
2387 static std::string convert(const std::monostate &) { return "{ }"; }
2388 };
2389
2390 template <typename... Elements> struct StringMaker<std::variant<Elements...>>
2391 {
2392 static std::string convert(const std::variant<Elements...> &variant)
2393 {
2394 if (variant.valueless_by_exception()) {
2395 return "{valueless variant}";
2396 }
2397 else {
2398 return std::visit([](const auto &value) { return ::Catch::Detail::stringify(value); },
2399 variant);
2400 }
2401 }
2402 };
2403 } // namespace Catch
2404 #endif // CATCH_CONFIG_ENABLE_VARIANT_STRINGMAKER
2405
2406 namespace Catch {
2407 // Import begin/ end from std here
2408 using std::begin;
2409 using std::end;
2410
2411 namespace detail {
2412 template <typename...> struct void_type
2413 {
2414 using type = void;
2415 };
2416
2417 template <typename T, typename = void> struct is_range_impl : std::false_type
2418 {
2419 };
2420
2421 template <typename T>
2422 struct is_range_impl<T, typename void_type<decltype(begin(std::declval<T>()))>::type>
2423 : std::true_type
2424 {
2425 };
2426 } // namespace detail
2427
2428 template <typename T> struct is_range : detail::is_range_impl<T>
2429 {
2430 };
2431
2432 #if defined(_MANAGED) // Managed types are never ranges
2433 template <typename T> struct is_range<T ^>
2434 {
2435 static const bool value = false;
2436 };
2437 #endif
2438
2439 template <typename Range> std::string rangeToString(Range const &range)
2440 {
2441 return ::Catch::Detail::rangeToString(begin(range), end(range));
2442 }
2443
2444 // Handle vector<bool> specially
2445 template <typename Allocator> std::string rangeToString(std::vector<bool, Allocator> const &v)
2446 {
2447 ReusableStringStream rss;
2448 rss << "{ ";
2449 bool first = true;
2450 for (bool b : v) {
2451 if (first)
2452 first = false;
2453 else
2454 rss << ", ";
2455 rss << ::Catch::Detail::stringify(b);
2456 }
2457 rss << " }";
2458 return rss.str();
2459 }
2460
2461 template <typename R>
2462 struct StringMaker<R,
2463 typename std::enable_if<is_range<R>::value &&
2464 !::Catch::Detail::IsStreamInsertable<R>::value>::type>
2465 {
2466 static std::string convert(R const &range) { return rangeToString(range); }
2467 };
2468
2469 template <typename T, int SZ> struct StringMaker<T[SZ]>
2470 {
2471 static std::string convert(T const (&arr)[SZ]) { return rangeToString(arr); }
2472 };
2473
2474 } // namespace Catch
2475
2476 // Separate std::chrono::duration specialization
2477 #if defined(CATCH_CONFIG_ENABLE_CHRONO_STRINGMAKER)
2478 #include <chrono>
2479 #include <ctime>
2480 #include <ratio>
2481
2482 namespace Catch {
2483
2484 template <class Ratio> struct ratio_string
2485 {
2486 static std::string symbol();
2487 };
2488
2489 template <class Ratio> std::string ratio_string<Ratio>::symbol()
2490 {
2491 Catch::ReusableStringStream rss;
2492 rss << '[' << Ratio::num << '/' << Ratio::den << ']';
2493 return rss.str();
2494 }
2495 template <> struct ratio_string<std::atto>
2496 {
2497 static std::string symbol();
2498 };
2499 template <> struct ratio_string<std::femto>
2500 {
2501 static std::string symbol();
2502 };
2503 template <> struct ratio_string<std::pico>
2504 {
2505 static std::string symbol();
2506 };
2507 template <> struct ratio_string<std::nano>
2508 {
2509 static std::string symbol();
2510 };
2511 template <> struct ratio_string<std::micro>
2512 {
2513 static std::string symbol();
2514 };
2515 template <> struct ratio_string<std::milli>
2516 {
2517 static std::string symbol();
2518 };
2519
2520 ////////////
2521 // std::chrono::duration specializations
2522 template <typename Value, typename Ratio> struct StringMaker<std::chrono::duration<Value, Ratio>>
2523 {
2524 static std::string convert(std::chrono::duration<Value, Ratio> const &duration)
2525 {
2526 ReusableStringStream rss;
2527 rss << duration.count() << ' ' << ratio_string<Ratio>::symbol() << 's';
2528 return rss.str();
2529 }
2530 };
2531 template <typename Value> struct StringMaker<std::chrono::duration<Value, std::ratio<1>>>
2532 {
2533 static std::string convert(std::chrono::duration<Value, std::ratio<1>> const &duration)
2534 {
2535 ReusableStringStream rss;
2536 rss << duration.count() << " s";
2537 return rss.str();
2538 }
2539 };
2540 template <typename Value> struct StringMaker<std::chrono::duration<Value, std::ratio<60>>>
2541 {
2542 static std::string convert(std::chrono::duration<Value, std::ratio<60>> const &duration)
2543 {
2544 ReusableStringStream rss;
2545 rss << duration.count() << " m";
2546 return rss.str();
2547 }
2548 };
2549 template <typename Value> struct StringMaker<std::chrono::duration<Value, std::ratio<3600>>>
2550 {
2551 static std::string convert(std::chrono::duration<Value, std::ratio<3600>> const &duration)
2552 {
2553 ReusableStringStream rss;
2554 rss << duration.count() << " h";
2555 return rss.str();
2556 }
2557 };
2558
2559 ////////////
2560 // std::chrono::time_point specialization
2561 // Generic time_point cannot be specialized, only std::chrono::time_point<system_clock>
2562 template <typename Clock, typename Duration>
2563 struct StringMaker<std::chrono::time_point<Clock, Duration>>
2564 {
2565 static std::string convert(std::chrono::time_point<Clock, Duration> const &time_point)
2566 {
2567 return ::Catch::Detail::stringify(time_point.time_since_epoch()) + " since epoch";
2568 }
2569 };
2570 // std::chrono::time_point<system_clock> specialization
2571 template <typename Duration>
2572 struct StringMaker<std::chrono::time_point<std::chrono::system_clock, Duration>>
2573 {
2574 static std::string
2575 convert(std::chrono::time_point<std::chrono::system_clock, Duration> const &time_point)
2576 {
2577 auto converted = std::chrono::system_clock::to_time_t(time_point);
2578
2579 #ifdef _MSC_VER
2580 std::tm timeInfo = {};
2581 gmtime_s(&timeInfo, &converted);
2582 #else
2583 std::tm *timeInfo = std::gmtime(&converted);
2584 #endif
2585
2586 auto const timeStampSize = sizeof("2017-01-16T17:06:45Z");
2587 char timeStamp[timeStampSize];
2588 const char *const fmt = "%Y-%m-%dT%H:%M:%SZ";
2589
2590 #ifdef _MSC_VER
2591 std::strftime(timeStamp, timeStampSize, fmt, &timeInfo);
2592 #else
2593 std::strftime(timeStamp, timeStampSize, fmt, timeInfo);
2594 #endif
2595 return std::string(timeStamp);
2596 }
2597 };
2598 } // namespace Catch
2599 #endif // CATCH_CONFIG_ENABLE_CHRONO_STRINGMAKER
2600
2601 #define INTERNAL_CATCH_REGISTER_ENUM(enumName, ...) \
2602 namespace Catch { \
2603 template <> struct StringMaker<enumName> \
2604 { \
2605 static std::string convert(enumName value) \
2606 { \
2607 static const auto &enumInfo = \
2608 ::Catch::getMutableRegistryHub().getMutableEnumValuesRegistry().registerEnum( \
2609 #enumName, #__VA_ARGS__, {__VA_ARGS__}); \
2610 return static_cast<std::string>(enumInfo.lookup(static_cast<int>(value))); \
2611 } \
2612 }; \
2613 }
2614
2615 #define CATCH_REGISTER_ENUM(enumName, ...) INTERNAL_CATCH_REGISTER_ENUM(enumName, __VA_ARGS__)
2616
2617 #ifdef _MSC_VER
2618 #pragma warning(pop)
2619 #endif
2620
2621 // end catch_tostring.h
2622 #include <iosfwd>
2623
2624 #ifdef _MSC_VER
2625 #pragma warning(push)
2626 #pragma warning(disable : 4389) // '==' : signed/unsigned mismatch
2627 #pragma warning(disable : 4018) // more "signed/unsigned mismatch"
2628 #pragma warning( \
2629 disable : 4312) // Converting int to T* using reinterpret_cast (issue on x64 platform)
2630 #pragma warning(disable : 4180) // qualifier applied to function type has no meaning
2631 #pragma warning(disable : 4800) // Forcing result to true or false
2632 #endif
2633
2634 namespace Catch {
2635
2636 struct ITransientExpression
2637 {
2638 auto isBinaryExpression() const -> bool { return m_isBinaryExpression; }
2639 auto getResult() const -> bool { return m_result; }
2640 virtual void streamReconstructedExpression(std::ostream &os) const = 0;
2641
2642 ITransientExpression(bool isBinaryExpression, bool result)
2643 : m_isBinaryExpression(isBinaryExpression), m_result(result)
2644 {
2645 }
2646
2647 // We don't actually need a virtual destructor, but many static analysers
2648 // complain if it's not here :-(
2649 virtual ~ITransientExpression();
2650
2651 bool m_isBinaryExpression;
2652 bool m_result;
2653 };
2654
2655 void formatReconstructedExpression(std::ostream &os, std::string const &lhs, StringRef op,
2656 std::string const &rhs);
2657
2658 template <typename LhsT, typename RhsT> class BinaryExpr : public ITransientExpression
2659 {
2660 LhsT m_lhs;
2661 StringRef m_op;
2662 RhsT m_rhs;
2663
2664 void streamReconstructedExpression(std::ostream &os) const override
2665 {
2666 formatReconstructedExpression(os, Catch::Detail::stringify(m_lhs), m_op,
2667 Catch::Detail::stringify(m_rhs));
2668 }
2669
2670 public:
2671 BinaryExpr(bool comparisonResult, LhsT lhs, StringRef op, RhsT rhs)
2672 : ITransientExpression{true, comparisonResult}, m_lhs(lhs), m_op(op), m_rhs(rhs)
2673 {
2674 }
2675
2676 template <typename T> auto operator&&(T) const -> BinaryExpr<LhsT, RhsT const &> const
2677 {
2678 static_assert(always_false<T>::value,
2679 "chained comparisons are not supported inside assertions, "
2680 "wrap the expression inside parentheses, or decompose it");
2681 }
2682
2683 template <typename T> auto operator||(T) const -> BinaryExpr<LhsT, RhsT const &> const
2684 {
2685 static_assert(always_false<T>::value,
2686 "chained comparisons are not supported inside assertions, "
2687 "wrap the expression inside parentheses, or decompose it");
2688 }
2689
2690 template <typename T> auto operator==(T) const -> BinaryExpr<LhsT, RhsT const &> const
2691 {
2692 static_assert(always_false<T>::value,
2693 "chained comparisons are not supported inside assertions, "
2694 "wrap the expression inside parentheses, or decompose it");
2695 }
2696
2697 template <typename T> auto operator!=(T) const -> BinaryExpr<LhsT, RhsT const &> const
2698 {
2699 static_assert(always_false<T>::value,
2700 "chained comparisons are not supported inside assertions, "
2701 "wrap the expression inside parentheses, or decompose it");
2702 }
2703
2704 template <typename T> auto operator>(T) const -> BinaryExpr<LhsT, RhsT const &> const
2705 {
2706 static_assert(always_false<T>::value,
2707 "chained comparisons are not supported inside assertions, "
2708 "wrap the expression inside parentheses, or decompose it");
2709 }
2710
2711 template <typename T> auto operator<(T) const -> BinaryExpr<LhsT, RhsT const &> const
2712 {
2713 static_assert(always_false<T>::value,
2714 "chained comparisons are not supported inside assertions, "
2715 "wrap the expression inside parentheses, or decompose it");
2716 }
2717
2718 template <typename T> auto operator>=(T) const -> BinaryExpr<LhsT, RhsT const &> const
2719 {
2720 static_assert(always_false<T>::value,
2721 "chained comparisons are not supported inside assertions, "
2722 "wrap the expression inside parentheses, or decompose it");
2723 }
2724
2725 template <typename T> auto operator<=(T) const -> BinaryExpr<LhsT, RhsT const &> const
2726 {
2727 static_assert(always_false<T>::value,
2728 "chained comparisons are not supported inside assertions, "
2729 "wrap the expression inside parentheses, or decompose it");
2730 }
2731 };
2732
2733 template <typename LhsT> class UnaryExpr : public ITransientExpression
2734 {
2735 LhsT m_lhs;
2736
2737 void streamReconstructedExpression(std::ostream &os) const override
2738 {
2739 os << Catch::Detail::stringify(m_lhs);
2740 }
2741
2742 public:
2743 explicit UnaryExpr(LhsT lhs) : ITransientExpression{false, static_cast<bool>(lhs)}, m_lhs(lhs)
2744 {
2745 }
2746 };
2747
2748 // Specialised comparison functions to handle equality comparisons between ints and pointers (NULL
2749 // deduces as an int)
2750 template <typename LhsT, typename RhsT>
2751 auto compareEqual(LhsT const &lhs, RhsT const &rhs) -> bool
2752 {
2753 return static_cast<bool>(lhs == rhs);
2754 }
2755 template <typename T> auto compareEqual(T *const &lhs, int rhs) -> bool
2756 {
2757 return lhs == reinterpret_cast<void const *>(rhs);
2758 }
2759 template <typename T> auto compareEqual(T *const &lhs, long rhs) -> bool
2760 {
2761 return lhs == reinterpret_cast<void const *>(rhs);
2762 }
2763 template <typename T> auto compareEqual(int lhs, T *const &rhs) -> bool
2764 {
2765 return reinterpret_cast<void const *>(lhs) == rhs;
2766 }
2767 template <typename T> auto compareEqual(long lhs, T *const &rhs) -> bool
2768 {
2769 return reinterpret_cast<void const *>(lhs) == rhs;
2770 }
2771
2772 template <typename LhsT, typename RhsT> auto compareNotEqual(LhsT const &lhs, RhsT &&rhs) -> bool
2773 {
2774 return static_cast<bool>(lhs != rhs);
2775 }
2776 template <typename T> auto compareNotEqual(T *const &lhs, int rhs) -> bool
2777 {
2778 return lhs != reinterpret_cast<void const *>(rhs);
2779 }
2780 template <typename T> auto compareNotEqual(T *const &lhs, long rhs) -> bool
2781 {
2782 return lhs != reinterpret_cast<void const *>(rhs);
2783 }
2784 template <typename T> auto compareNotEqual(int lhs, T *const &rhs) -> bool
2785 {
2786 return reinterpret_cast<void const *>(lhs) != rhs;
2787 }
2788 template <typename T> auto compareNotEqual(long lhs, T *const &rhs) -> bool
2789 {
2790 return reinterpret_cast<void const *>(lhs) != rhs;
2791 }
2792
2793 template <typename LhsT> class ExprLhs
2794 {
2795 LhsT m_lhs;
2796
2797 public:
2798 explicit ExprLhs(LhsT lhs) : m_lhs(lhs) {}
2799
2800 template <typename RhsT>
2801 auto operator==(RhsT const &rhs) -> BinaryExpr<LhsT, RhsT const &> const
2802 {
2803 return {compareEqual(m_lhs, rhs), m_lhs, "==", rhs};
2804 }
2805 auto operator==(bool rhs) -> BinaryExpr<LhsT, bool> const
2806 {
2807 return {m_lhs == rhs, m_lhs, "==", rhs};
2808 }
2809
2810 template <typename RhsT>
2811 auto operator!=(RhsT const &rhs) -> BinaryExpr<LhsT, RhsT const &> const
2812 {
2813 return {compareNotEqual(m_lhs, rhs), m_lhs, "!=", rhs};
2814 }
2815 auto operator!=(bool rhs) -> BinaryExpr<LhsT, bool> const
2816 {
2817 return {m_lhs != rhs, m_lhs, "!=", rhs};
2818 }
2819
2820 template <typename RhsT> auto operator>(RhsT const &rhs) -> BinaryExpr<LhsT, RhsT const &> const
2821 {
2822 return {static_cast<bool>(m_lhs > rhs), m_lhs, ">", rhs};
2823 }
2824 template <typename RhsT> auto operator<(RhsT const &rhs) -> BinaryExpr<LhsT, RhsT const &> const
2825 {
2826 return {static_cast<bool>(m_lhs < rhs), m_lhs, "<", rhs};
2827 }
2828 template <typename RhsT>
2829 auto operator>=(RhsT const &rhs) -> BinaryExpr<LhsT, RhsT const &> const
2830 {
2831 return {static_cast<bool>(m_lhs >= rhs), m_lhs, ">=", rhs};
2832 }
2833 template <typename RhsT>
2834 auto operator<=(RhsT const &rhs) -> BinaryExpr<LhsT, RhsT const &> const
2835 {
2836 return {static_cast<bool>(m_lhs <= rhs), m_lhs, "<=", rhs};
2837 }
2838 template <typename RhsT> auto operator|(RhsT const &rhs) -> BinaryExpr<LhsT, RhsT const &> const
2839 {
2840 return {static_cast<bool>(m_lhs | rhs), m_lhs, "|", rhs};
2841 }
2842 template <typename RhsT> auto operator&(RhsT const &rhs) -> BinaryExpr<LhsT, RhsT const &> const
2843 {
2844 return {static_cast<bool>(m_lhs & rhs), m_lhs, "&", rhs};
2845 }
2846 template <typename RhsT> auto operator^(RhsT const &rhs) -> BinaryExpr<LhsT, RhsT const &> const
2847 {
2848 return {static_cast<bool>(m_lhs ^ rhs), m_lhs, "^", rhs};
2849 }
2850
2851 template <typename RhsT> auto operator&&(RhsT const &) -> BinaryExpr<LhsT, RhsT const &> const
2852 {
2853 static_assert(always_false<RhsT>::value,
2854 "operator&& is not supported inside assertions, "
2855 "wrap the expression inside parentheses, or decompose it");
2856 }
2857
2858 template <typename RhsT> auto operator||(RhsT const &) -> BinaryExpr<LhsT, RhsT const &> const
2859 {
2860 static_assert(always_false<RhsT>::value,
2861 "operator|| is not supported inside assertions, "
2862 "wrap the expression inside parentheses, or decompose it");
2863 }
2864
2865 auto makeUnaryExpr() const -> UnaryExpr<LhsT> { return UnaryExpr<LhsT>{m_lhs}; }
2866 };
2867
2868 void handleExpression(ITransientExpression const &expr);
2869
2870 template <typename T> void handleExpression(ExprLhs<T> const &expr)
2871 {
2872 handleExpression(expr.makeUnaryExpr());
2873 }
2874
2875 struct Decomposer
2876 {
2877 template <typename T> auto operator<=(T const &lhs) -> ExprLhs<T const &>
2878 {
2879 return ExprLhs<T const &>{lhs};
2880 }
2881
2882 auto operator<=(bool value) -> ExprLhs<bool> { return ExprLhs<bool>{value}; }
2883 };
2884
2885 } // end namespace Catch
2886
2887 #ifdef _MSC_VER
2888 #pragma warning(pop)
2889 #endif
2890
2891 // end catch_decomposer.h
2892 // start catch_interfaces_capture.h
2893
2894 #include <chrono>
2895 #include <string>
2896
2897 namespace Catch {
2898
2899 class AssertionResult;
2900 struct AssertionInfo;
2901 struct SectionInfo;
2902 struct SectionEndInfo;
2903 struct MessageInfo;
2904 struct MessageBuilder;
2905 struct Counts;
2906 struct AssertionReaction;
2907 struct SourceLineInfo;
2908
2909 struct ITransientExpression;
2910 struct IGeneratorTracker;
2911
2912 #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
2913 struct BenchmarkInfo;
2914 template <typename Duration = std::chrono::duration<double, std::nano>> struct BenchmarkStats;
2915 #endif // CATCH_CONFIG_ENABLE_BENCHMARKING
2916
2917 struct IResultCapture
2918 {
2919
2920 virtual ~IResultCapture();
2921
2922 virtual bool sectionStarted(SectionInfo const &sectionInfo, Counts &assertions) = 0;
2923 virtual void sectionEnded(SectionEndInfo const &endInfo) = 0;
2924 virtual void sectionEndedEarly(SectionEndInfo const &endInfo) = 0;
2925
2926 virtual auto acquireGeneratorTracker(StringRef generatorName,
2927 SourceLineInfo const &lineInfo) -> IGeneratorTracker & = 0;
2928
2929 #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
2930 virtual void benchmarkPreparing(std::string const &name) = 0;
2931 virtual void benchmarkStarting(BenchmarkInfo const &info) = 0;
2932 virtual void benchmarkEnded(BenchmarkStats<> const &stats) = 0;
2933 virtual void benchmarkFailed(std::string const &error) = 0;
2934 #endif // CATCH_CONFIG_ENABLE_BENCHMARKING
2935
2936 virtual void pushScopedMessage(MessageInfo const &message) = 0;
2937 virtual void popScopedMessage(MessageInfo const &message) = 0;
2938
2939 virtual void emplaceUnscopedMessage(MessageBuilder const &builder) = 0;
2940
2941 virtual void handleFatalErrorCondition(StringRef message) = 0;
2942
2943 virtual void handleExpr(AssertionInfo const &info, ITransientExpression const &expr,
2944 AssertionReaction &reaction) = 0;
2945 virtual void handleMessage(AssertionInfo const &info, ResultWas::OfType resultType,
2946 StringRef const &message, AssertionReaction &reaction) = 0;
2947 virtual void handleUnexpectedExceptionNotThrown(AssertionInfo const &info,
2948 AssertionReaction &reaction) = 0;
2949 virtual void handleUnexpectedInflightException(AssertionInfo const &info,
2950 std::string const &message,
2951 AssertionReaction &reaction) = 0;
2952 virtual void handleIncomplete(AssertionInfo const &info) = 0;
2953 virtual void handleNonExpr(AssertionInfo const &info, ResultWas::OfType resultType,
2954 AssertionReaction &reaction) = 0;
2955
2956 virtual bool lastAssertionPassed() = 0;
2957 virtual void assertionPassed() = 0;
2958
2959 // Deprecated, do not use:
2960 virtual std::string getCurrentTestName() const = 0;
2961 virtual const AssertionResult *getLastResult() const = 0;
2962 virtual void exceptionEarlyReported() = 0;
2963 };
2964
2965 IResultCapture &getResultCapture();
2966 } // namespace Catch
2967
2968 // end catch_interfaces_capture.h
2969 namespace Catch {
2970
2971 struct TestFailureException
2972 {
2973 };
2974 struct AssertionResultData;
2975 struct IResultCapture;
2976 class RunContext;
2977
2978 class LazyExpression
2979 {
2980 friend class AssertionHandler;
2981 friend struct AssertionStats;
2982 friend class RunContext;
2983
2984 ITransientExpression const *m_transientExpression = nullptr;
2985 bool m_isNegated;
2986
2987 public:
2988 LazyExpression(bool isNegated);
2989 LazyExpression(LazyExpression const &other);
2990 LazyExpression &operator=(LazyExpression const &) = delete;
2991
2992 explicit operator bool() const;
2993
2994 friend auto operator<<(std::ostream &os, LazyExpression const &lazyExpr) -> std::ostream &;
2995 };
2996
2997 struct AssertionReaction
2998 {
2999 bool shouldDebugBreak = false;
3000 bool shouldThrow = false;
3001 };
3002
3003 class AssertionHandler
3004 {
3005 AssertionInfo m_assertionInfo;
3006 AssertionReaction m_reaction;
3007 bool m_completed = false;
3008 IResultCapture &m_resultCapture;
3009
3010 public:
3011 AssertionHandler(StringRef const &macroName, SourceLineInfo const &lineInfo,
3012 StringRef capturedExpression, ResultDisposition::Flags resultDisposition);
3013 ~AssertionHandler()
3014 {
3015 if (!m_completed) {
3016 m_resultCapture.handleIncomplete(m_assertionInfo);
3017 }
3018 }
3019
3020 template <typename T> void handleExpr(ExprLhs<T> const &expr)
3021 {
3022 handleExpr(expr.makeUnaryExpr());
3023 }
3024 void handleExpr(ITransientExpression const &expr);
3025
3026 void handleMessage(ResultWas::OfType resultType, StringRef const &message);
3027
3028 void handleExceptionThrownAsExpected();
3029 void handleUnexpectedExceptionNotThrown();
3030 void handleExceptionNotThrownAsExpected();
3031 void handleThrowingCallSkipped();
3032 void handleUnexpectedInflightException();
3033
3034 void complete();
3035 void setCompleted();
3036
3037 // query
3038 auto allowThrows() const -> bool;
3039 };
3040
3041 void handleExceptionMatchExpr(AssertionHandler &handler, std::string const &str,
3042 StringRef const &matcherString);
3043
3044 } // namespace Catch
3045
3046 // end catch_assertionhandler.h
3047 // start catch_message.h
3048
3049 #include <string>
3050 #include <vector>
3051
3052 namespace Catch {
3053
3054 struct MessageInfo
3055 {
3056 MessageInfo(StringRef const &_macroName, SourceLineInfo const &_lineInfo,
3057 ResultWas::OfType _type);
3058
3059 StringRef macroName;
3060 std::string message;
3061 SourceLineInfo lineInfo;
3062 ResultWas::OfType type;
3063 unsigned int sequence;
3064
3065 bool operator==(MessageInfo const &other) const;
3066 bool operator<(MessageInfo const &other) const;
3067
3068 private:
3069 static unsigned int globalCount;
3070 };
3071
3072 struct MessageStream
3073 {
3074
3075 template <typename T> MessageStream &operator<<(T const &value)
3076 {
3077 m_stream << value;
3078 return *this;
3079 }
3080
3081 ReusableStringStream m_stream;
3082 };
3083
3084 struct MessageBuilder : MessageStream
3085 {
3086 MessageBuilder(StringRef const &macroName, SourceLineInfo const &lineInfo,
3087 ResultWas::OfType type);
3088
3089 template <typename T> MessageBuilder &operator<<(T const &value)
3090 {
3091 m_stream << value;
3092 return *this;
3093 }
3094
3095 MessageInfo m_info;
3096 };
3097
3098 class ScopedMessage
3099 {
3100 public:
3101 explicit ScopedMessage(MessageBuilder const &builder);
3102 ScopedMessage(ScopedMessage &duplicate) = delete;
3103 ScopedMessage(ScopedMessage &&old);
3104 ~ScopedMessage();
3105
3106 MessageInfo m_info;
3107 bool m_moved;
3108 };
3109
3110 class Capturer
3111 {
3112 std::vector<MessageInfo> m_messages;
3113 IResultCapture &m_resultCapture = getResultCapture();
3114 size_t m_captured = 0;
3115
3116 public:
3117 Capturer(StringRef macroName, SourceLineInfo const &lineInfo, ResultWas::OfType resultType,
3118 StringRef names);
3119 ~Capturer();
3120
3121 void captureValue(size_t index, std::string const &value);
3122
3123 template <typename T> void captureValues(size_t index, T const &value)
3124 {
3125 captureValue(index, Catch::Detail::stringify(value));
3126 }
3127
3128 template <typename T, typename... Ts>
3129 void captureValues(size_t index, T const &value, Ts const &...values)
3130 {
3131 captureValue(index, Catch::Detail::stringify(value));
3132 captureValues(index + 1, values...);
3133 }
3134 };
3135
3136 } // end namespace Catch
3137
3138 // end catch_message.h
3139 #if !defined(CATCH_CONFIG_DISABLE)
3140
3141 #if !defined(CATCH_CONFIG_DISABLE_STRINGIFICATION)
3142 #define CATCH_INTERNAL_STRINGIFY(...) #__VA_ARGS__
3143 #else
3144 #define CATCH_INTERNAL_STRINGIFY(...) "Disabled by CATCH_CONFIG_DISABLE_STRINGIFICATION"
3145 #endif
3146
3147 #if defined(CATCH_CONFIG_FAST_COMPILE) || defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
3148
3149 ///////////////////////////////////////////////////////////////////////////////
3150 // Another way to speed-up compilation is to omit local try-catch for REQUIRE*
3151 // macros.
3152 #define INTERNAL_CATCH_TRY
3153 #define INTERNAL_CATCH_CATCH(capturer)
3154
3155 #else // CATCH_CONFIG_FAST_COMPILE
3156
3157 #define INTERNAL_CATCH_TRY try
3158 #define INTERNAL_CATCH_CATCH(handler) \
3159 catch (...) { handler.handleUnexpectedInflightException(); }
3160
3161 #endif
3162
3163 #define INTERNAL_CATCH_REACT(handler) handler.complete();
3164
3165 ///////////////////////////////////////////////////////////////////////////////
3166 #define INTERNAL_CATCH_TEST(macroName, resultDisposition, ...) \
3167 do { \
3168 CATCH_INTERNAL_IGNORE_BUT_WARN(__VA_ARGS__); \
3169 Catch::AssertionHandler catchAssertionHandler(macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, \
3170 CATCH_INTERNAL_STRINGIFY(__VA_ARGS__), \
3171 resultDisposition); \
3172 INTERNAL_CATCH_TRY \
3173 { \
3174 CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \
3175 CATCH_INTERNAL_SUPPRESS_PARENTHESES_WARNINGS \
3176 catchAssertionHandler.handleExpr(Catch::Decomposer() <= __VA_ARGS__); \
3177 CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION \
3178 } \
3179 INTERNAL_CATCH_CATCH(catchAssertionHandler) \
3180 INTERNAL_CATCH_REACT(catchAssertionHandler) \
3181 } while ((void)0, (false) && static_cast<bool>(!!(__VA_ARGS__)))
3182
3183 ///////////////////////////////////////////////////////////////////////////////
3184 #define INTERNAL_CATCH_IF(macroName, resultDisposition, ...) \
3185 INTERNAL_CATCH_TEST(macroName, resultDisposition, __VA_ARGS__); \
3186 if (Catch::getResultCapture().lastAssertionPassed())
3187
3188 ///////////////////////////////////////////////////////////////////////////////
3189 #define INTERNAL_CATCH_ELSE(macroName, resultDisposition, ...) \
3190 INTERNAL_CATCH_TEST(macroName, resultDisposition, __VA_ARGS__); \
3191 if (!Catch::getResultCapture().lastAssertionPassed())
3192
3193 ///////////////////////////////////////////////////////////////////////////////
3194 #define INTERNAL_CATCH_NO_THROW(macroName, resultDisposition, ...) \
3195 do { \
3196 Catch::AssertionHandler catchAssertionHandler(macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, \
3197 CATCH_INTERNAL_STRINGIFY(__VA_ARGS__), \
3198 resultDisposition); \
3199 try { \
3200 static_cast<void>(__VA_ARGS__); \
3201 catchAssertionHandler.handleExceptionNotThrownAsExpected(); \
3202 } \
3203 catch (...) { \
3204 catchAssertionHandler.handleUnexpectedInflightException(); \
3205 } \
3206 INTERNAL_CATCH_REACT(catchAssertionHandler) \
3207 } while (false)
3208
3209 ///////////////////////////////////////////////////////////////////////////////
3210 #define INTERNAL_CATCH_THROWS(macroName, resultDisposition, ...) \
3211 do { \
3212 Catch::AssertionHandler catchAssertionHandler(macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, \
3213 CATCH_INTERNAL_STRINGIFY(__VA_ARGS__), \
3214 resultDisposition); \
3215 if (catchAssertionHandler.allowThrows()) \
3216 try { \
3217 static_cast<void>(__VA_ARGS__); \
3218 catchAssertionHandler.handleUnexpectedExceptionNotThrown(); \
3219 } \
3220 catch (...) { \
3221 catchAssertionHandler.handleExceptionThrownAsExpected(); \
3222 } \
3223 else \
3224 catchAssertionHandler.handleThrowingCallSkipped(); \
3225 INTERNAL_CATCH_REACT(catchAssertionHandler) \
3226 } while (false)
3227
3228 ///////////////////////////////////////////////////////////////////////////////
3229 #define INTERNAL_CATCH_THROWS_AS(macroName, exceptionType, resultDisposition, expr) \
3230 do { \
3231 Catch::AssertionHandler catchAssertionHandler( \
3232 macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, \
3233 CATCH_INTERNAL_STRINGIFY(expr) ", " CATCH_INTERNAL_STRINGIFY(exceptionType), \
3234 resultDisposition); \
3235 if (catchAssertionHandler.allowThrows()) \
3236 try { \
3237 static_cast<void>(expr); \
3238 catchAssertionHandler.handleUnexpectedExceptionNotThrown(); \
3239 } \
3240 catch (exceptionType const &) { \
3241 catchAssertionHandler.handleExceptionThrownAsExpected(); \
3242 } \
3243 catch (...) { \
3244 catchAssertionHandler.handleUnexpectedInflightException(); \
3245 } \
3246 else \
3247 catchAssertionHandler.handleThrowingCallSkipped(); \
3248 INTERNAL_CATCH_REACT(catchAssertionHandler) \
3249 } while (false)
3250
3251 ///////////////////////////////////////////////////////////////////////////////
3252 #define INTERNAL_CATCH_MSG(macroName, messageType, resultDisposition, ...) \
3253 do { \
3254 Catch::AssertionHandler catchAssertionHandler(macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, \
3255 Catch::StringRef(), resultDisposition); \
3256 catchAssertionHandler.handleMessage( \
3257 messageType, \
3258 (Catch::MessageStream() << __VA_ARGS__ + ::Catch::StreamEndStop()).m_stream.str()); \
3259 INTERNAL_CATCH_REACT(catchAssertionHandler) \
3260 } while (false)
3261
3262 ///////////////////////////////////////////////////////////////////////////////
3263 #define INTERNAL_CATCH_CAPTURE(varName, macroName, ...) \
3264 auto varName = \
3265 Catch::Capturer(macroName, CATCH_INTERNAL_LINEINFO, Catch::ResultWas::Info, #__VA_ARGS__); \
3266 varName.captureValues(0, __VA_ARGS__)
3267
3268 ///////////////////////////////////////////////////////////////////////////////
3269 #define INTERNAL_CATCH_INFO(macroName, log) \
3270 Catch::ScopedMessage INTERNAL_CATCH_UNIQUE_NAME(scopedMessage)( \
3271 Catch::MessageBuilder(macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, Catch::ResultWas::Info) \
3272 << log);
3273
3274 ///////////////////////////////////////////////////////////////////////////////
3275 #define INTERNAL_CATCH_UNSCOPED_INFO(macroName, log) \
3276 Catch::getResultCapture().emplaceUnscopedMessage( \
3277 Catch::MessageBuilder(macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, Catch::ResultWas::Info) \
3278 << log)
3279
3280 ///////////////////////////////////////////////////////////////////////////////
3281 // Although this is matcher-based, it can be used with just a string
3282 #define INTERNAL_CATCH_THROWS_STR_MATCHES(macroName, resultDisposition, matcher, ...) \
3283 do { \
3284 Catch::AssertionHandler catchAssertionHandler( \
3285 macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, \
3286 CATCH_INTERNAL_STRINGIFY(__VA_ARGS__) ", " CATCH_INTERNAL_STRINGIFY(matcher), \
3287 resultDisposition); \
3288 if (catchAssertionHandler.allowThrows()) \
3289 try { \
3290 static_cast<void>(__VA_ARGS__); \
3291 catchAssertionHandler.handleUnexpectedExceptionNotThrown(); \
3292 } \
3293 catch (...) { \
3294 Catch::handleExceptionMatchExpr(catchAssertionHandler, matcher, #matcher##_catch_sr); \
3295 } \
3296 else \
3297 catchAssertionHandler.handleThrowingCallSkipped(); \
3298 INTERNAL_CATCH_REACT(catchAssertionHandler) \
3299 } while (false)
3300
3301 #endif // CATCH_CONFIG_DISABLE
3302
3303 // end catch_capture.hpp
3304 // start catch_section.h
3305
3306 // start catch_section_info.h
3307
3308 // start catch_totals.h
3309
3310 #include <cstddef>
3311
3312 namespace Catch {
3313
3314 struct Counts
3315 {
3316 Counts operator-(Counts const &other) const;
3317 Counts &operator+=(Counts const &other);
3318
3319 std::size_t total() const;
3320 bool allPassed() const;
3321 bool allOk() const;
3322
3323 std::size_t passed = 0;
3324 std::size_t failed = 0;
3325 std::size_t failedButOk = 0;
3326 };
3327
3328 struct Totals
3329 {
3330
3331 Totals operator-(Totals const &other) const;
3332 Totals &operator+=(Totals const &other);
3333
3334 Totals delta(Totals const &prevTotals) const;
3335
3336 int error = 0;
3337 Counts assertions;
3338 Counts testCases;
3339 };
3340 } // namespace Catch
3341
3342 // end catch_totals.h
3343 #include <string>
3344
3345 namespace Catch {
3346
3347 struct SectionInfo
3348 {
3349 SectionInfo(SourceLineInfo const &_lineInfo, std::string const &_name);
3350
3351 // Deprecated
3352 SectionInfo(SourceLineInfo const &_lineInfo, std::string const &_name, std::string const &)
3353 : SectionInfo(_lineInfo, _name)
3354 {
3355 }
3356
3357 std::string name;
3358 std::string description; // !Deprecated: this will always be empty
3359 SourceLineInfo lineInfo;
3360 };
3361
3362 struct SectionEndInfo
3363 {
3364 SectionInfo sectionInfo;
3365 Counts prevAssertions;
3366 double durationInSeconds;
3367 };
3368
3369 } // end namespace Catch
3370
3371 // end catch_section_info.h
3372 // start catch_timer.h
3373
3374 #include <cstdint>
3375
3376 namespace Catch {
3377
3378 auto getCurrentNanosecondsSinceEpoch() -> uint64_t;
3379 auto getEstimatedClockResolution() -> uint64_t;
3380
3381 class Timer
3382 {
3383 uint64_t m_nanoseconds = 0;
3384
3385 public:
3386 void start();
3387 auto getElapsedNanoseconds() const -> uint64_t;
3388 auto getElapsedMicroseconds() const -> uint64_t;
3389 auto getElapsedMilliseconds() const -> unsigned int;
3390 auto getElapsedSeconds() const -> double;
3391 };
3392
3393 } // namespace Catch
3394
3395 // end catch_timer.h
3396 #include <string>
3397
3398 namespace Catch {
3399
3400 class Section : NonCopyable
3401 {
3402 public:
3403 Section(SectionInfo const &info);
3404 ~Section();
3405
3406 // This indicates whether the section should be executed or not
3407 explicit operator bool() const;
3408
3409 private:
3410 SectionInfo m_info;
3411
3412 std::string m_name;
3413 Counts m_assertions;
3414 bool m_sectionIncluded;
3415 Timer m_timer;
3416 };
3417
3418 } // end namespace Catch
3419
3420 #define INTERNAL_CATCH_SECTION(...) \
3421 CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \
3422 CATCH_INTERNAL_SUPPRESS_UNUSED_WARNINGS \
3423 if (Catch::Section const &INTERNAL_CATCH_UNIQUE_NAME(catch_internal_Section) = \
3424 Catch::SectionInfo(CATCH_INTERNAL_LINEINFO, __VA_ARGS__)) \
3425 CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION
3426
3427 #define INTERNAL_CATCH_DYNAMIC_SECTION(...) \
3428 CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \
3429 CATCH_INTERNAL_SUPPRESS_UNUSED_WARNINGS \
3430 if (Catch::Section const &INTERNAL_CATCH_UNIQUE_NAME(catch_internal_Section) = \
3431 Catch::SectionInfo(CATCH_INTERNAL_LINEINFO, \
3432 (Catch::ReusableStringStream() << __VA_ARGS__).str())) \
3433 CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION
3434
3435 // end catch_section.h
3436 // start catch_interfaces_exception.h
3437
3438 // start catch_interfaces_registry_hub.h
3439
3440 #include <memory>
3441 #include <string>
3442
3443 namespace Catch {
3444
3445 class TestCase;
3446 struct ITestCaseRegistry;
3447 struct IExceptionTranslatorRegistry;
3448 struct IExceptionTranslator;
3449 struct IReporterRegistry;
3450 struct IReporterFactory;
3451 struct ITagAliasRegistry;
3452 struct IMutableEnumValuesRegistry;
3453
3454 class StartupExceptionRegistry;
3455
3456 using IReporterFactoryPtr = std::shared_ptr<IReporterFactory>;
3457
3458 struct IRegistryHub
3459 {
3460 virtual ~IRegistryHub();
3461
3462 virtual IReporterRegistry const &getReporterRegistry() const = 0;
3463 virtual ITestCaseRegistry const &getTestCaseRegistry() const = 0;
3464 virtual ITagAliasRegistry const &getTagAliasRegistry() const = 0;
3465 virtual IExceptionTranslatorRegistry const &getExceptionTranslatorRegistry() const = 0;
3466
3467 virtual StartupExceptionRegistry const &getStartupExceptionRegistry() const = 0;
3468 };
3469
3470 struct IMutableRegistryHub
3471 {
3472 virtual ~IMutableRegistryHub();
3473 virtual void registerReporter(std::string const &name, IReporterFactoryPtr const &factory) = 0;
3474 virtual void registerListener(IReporterFactoryPtr const &factory) = 0;
3475 virtual void registerTest(TestCase const &testInfo) = 0;
3476 virtual void registerTranslator(const IExceptionTranslator *translator) = 0;
3477 virtual void registerTagAlias(std::string const &alias, std::string const &tag,
3478 SourceLineInfo const &lineInfo) = 0;
3479 virtual void registerStartupException() noexcept = 0;
3480 virtual IMutableEnumValuesRegistry &getMutableEnumValuesRegistry() = 0;
3481 };
3482
3483 IRegistryHub const &getRegistryHub();
3484 IMutableRegistryHub &getMutableRegistryHub();
3485 void cleanUp();
3486 std::string translateActiveException();
3487
3488 } // namespace Catch
3489
3490 // end catch_interfaces_registry_hub.h
3491 #if defined(CATCH_CONFIG_DISABLE)
3492 #define INTERNAL_CATCH_TRANSLATE_EXCEPTION_NO_REG(translatorName, signature) \
3493 static std::string translatorName(signature)
3494 #endif
3495
3496 #include <exception>
3497 #include <string>
3498 #include <vector>
3499
3500 namespace Catch {
3501 using exceptionTranslateFunction = std::string (*)();
3502
3503 struct IExceptionTranslator;
3504 using ExceptionTranslators = std::vector<std::unique_ptr<IExceptionTranslator const>>;
3505
3506 struct IExceptionTranslator
3507 {
3508 virtual ~IExceptionTranslator();
3509 virtual std::string translate(ExceptionTranslators::const_iterator it,
3510 ExceptionTranslators::const_iterator itEnd) const = 0;
3511 };
3512
3513 struct IExceptionTranslatorRegistry
3514 {
3515 virtual ~IExceptionTranslatorRegistry();
3516
3517 virtual std::string translateActiveException() const = 0;
3518 };
3519
3520 class ExceptionTranslatorRegistrar
3521 {
3522 template <typename T> class ExceptionTranslator : public IExceptionTranslator
3523 {
3524 public:
3525 ExceptionTranslator(std::string (*translateFunction)(T &))
3526 : m_translateFunction(translateFunction)
3527 {
3528 }
3529
3530 std::string translate(ExceptionTranslators::const_iterator it,
3531 ExceptionTranslators::const_iterator itEnd) const override
3532 {
3533 #if defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
3534 return "";
3535 #else
3536 try {
3537 if (it == itEnd)
3538 std::rethrow_exception(std::current_exception());
3539 else
3540 return (*it)->translate(it + 1, itEnd);
3541 }
3542 catch (T &ex) {
3543 return m_translateFunction(ex);
3544 }
3545 #endif
3546 }
3547
3548 protected:
3549 std::string (*m_translateFunction)(T &);
3550 };
3551
3552 public:
3553 template <typename T> ExceptionTranslatorRegistrar(std::string (*translateFunction)(T &))
3554 {
3555 getMutableRegistryHub().registerTranslator(new ExceptionTranslator<T>(translateFunction));
3556 }
3557 };
3558 } // namespace Catch
3559
3560 ///////////////////////////////////////////////////////////////////////////////
3561 #define INTERNAL_CATCH_TRANSLATE_EXCEPTION2(translatorName, signature) \
3562 static std::string translatorName(signature); \
3563 CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \
3564 CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
3565 namespace { \
3566 Catch::ExceptionTranslatorRegistrar \
3567 INTERNAL_CATCH_UNIQUE_NAME(catch_internal_ExceptionRegistrar)(&translatorName); \
3568 } \
3569 CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION \
3570 static std::string translatorName(signature)
3571
3572 #define INTERNAL_CATCH_TRANSLATE_EXCEPTION(signature) \
3573 INTERNAL_CATCH_TRANSLATE_EXCEPTION2( \
3574 INTERNAL_CATCH_UNIQUE_NAME(catch_internal_ExceptionTranslator), signature)
3575
3576 // end catch_interfaces_exception.h
3577 // start catch_approx.h
3578
3579 #include <type_traits>
3580
3581 namespace Catch {
3582 namespace Detail {
3583
3584 class Approx
3585 {
3586 private:
3587 bool equalityComparisonImpl(double other) const;
3588 // Validates the new margin (margin >= 0)
3589 // out-of-line to avoid including stdexcept in the header
3590 void setMargin(double margin);
3591 // Validates the new epsilon (0 < epsilon < 1)
3592 // out-of-line to avoid including stdexcept in the header
3593 void setEpsilon(double epsilon);
3594
3595 public:
3596 explicit Approx(double value);
3597
3598 static Approx custom();
3599
3600 Approx operator-() const;
3601
3602 template <typename T,
3603 typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
3604 Approx operator()(T const &value)
3605 {
3606 Approx approx(static_cast<double>(value));
3607 approx.m_epsilon = m_epsilon;
3608 approx.m_margin = m_margin;
3609 approx.m_scale = m_scale;
3610 return approx;
3611 }
3612
3613 template <typename T,
3614 typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
3615 explicit Approx(T const &value) : Approx(static_cast<double>(value))
3616 {
3617 }
3618
3619 template <typename T,
3620 typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
3621 friend bool operator==(const T &lhs, Approx const &rhs)
3622 {
3623 auto lhs_v = static_cast<double>(lhs);
3624 return rhs.equalityComparisonImpl(lhs_v);
3625 }
3626
3627 template <typename T,
3628 typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
3629 friend bool operator==(Approx const &lhs, const T &rhs)
3630 {
3631 return operator==(rhs, lhs);
3632 }
3633
3634 template <typename T,
3635 typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
3636 friend bool operator!=(T const &lhs, Approx const &rhs)
3637 {
3638 return !operator==(lhs, rhs);
3639 }
3640
3641 template <typename T,
3642 typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
3643 friend bool operator!=(Approx const &lhs, T const &rhs)
3644 {
3645 return !operator==(rhs, lhs);
3646 }
3647
3648 template <typename T,
3649 typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
3650 friend bool operator<=(T const &lhs, Approx const &rhs)
3651 {
3652 return static_cast<double>(lhs) < rhs.m_value || lhs == rhs;
3653 }
3654
3655 template <typename T,
3656 typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
3657 friend bool operator<=(Approx const &lhs, T const &rhs)
3658 {
3659 return lhs.m_value < static_cast<double>(rhs) || lhs == rhs;
3660 }
3661
3662 template <typename T,
3663 typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
3664 friend bool operator>=(T const &lhs, Approx const &rhs)
3665 {
3666 return static_cast<double>(lhs) > rhs.m_value || lhs == rhs;
3667 }
3668
3669 template <typename T,
3670 typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
3671 friend bool operator>=(Approx const &lhs, T const &rhs)
3672 {
3673 return lhs.m_value > static_cast<double>(rhs) || lhs == rhs;
3674 }
3675
3676 template <typename T,
3677 typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
3678 Approx &epsilon(T const &newEpsilon)
3679 {
3680 double epsilonAsDouble = static_cast<double>(newEpsilon);
3681 setEpsilon(epsilonAsDouble);
3682 return *this;
3683 }
3684
3685 template <typename T,
3686 typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
3687 Approx &margin(T const &newMargin)
3688 {
3689 double marginAsDouble = static_cast<double>(newMargin);
3690 setMargin(marginAsDouble);
3691 return *this;
3692 }
3693
3694 template <typename T,
3695 typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
3696 Approx &scale(T const &newScale)
3697 {
3698 m_scale = static_cast<double>(newScale);
3699 return *this;
3700 }
3701
3702 std::string toString() const;
3703
3704 private:
3705 double m_epsilon;
3706 double m_margin;
3707 double m_scale;
3708 double m_value;
3709 };
3710 } // end namespace Detail
3711
3712 namespace literals {
3713 Detail::Approx operator"" _a(long double val);
3714 Detail::Approx operator"" _a(unsigned long long val);
3715 } // end namespace literals
3716
3717 template <> struct StringMaker<Catch::Detail::Approx>
3718 {
3719 static std::string convert(Catch::Detail::Approx const &value);
3720 };
3721
3722 } // end namespace Catch
3723
3724 // end catch_approx.h
3725 // start catch_string_manip.h
3726
3727 #include <iosfwd>
3728 #include <string>
3729 #include <vector>
3730
3731 namespace Catch {
3732
3733 bool startsWith(std::string const &s, std::string const &prefix);
3734 bool startsWith(std::string const &s, char prefix);
3735 bool endsWith(std::string const &s, std::string const &suffix);
3736 bool endsWith(std::string const &s, char suffix);
3737 bool contains(std::string const &s, std::string const &infix);
3738 void toLowerInPlace(std::string &s);
3739 std::string toLower(std::string const &s);
3740 //! Returns a new string without whitespace at the start/end
3741 std::string trim(std::string const &str);
3742 //! Returns a substring of the original ref without whitespace. Beware lifetimes!
3743 StringRef trim(StringRef ref);
3744
3745 // !!! Be aware, returns refs into original string - make sure original string outlives them
3746 std::vector<StringRef> splitStringRef(StringRef str, char delimiter);
3747 bool replaceInPlace(std::string &str, std::string const &replaceThis,
3748 std::string const &withThis);
3749
3750 struct pluralise
3751 {
3752 pluralise(std::size_t count, std::string const &label);
3753
3754 friend std::ostream &operator<<(std::ostream &os, pluralise const &pluraliser);
3755
3756 std::size_t m_count;
3757 std::string m_label;
3758 };
3759 } // namespace Catch
3760
3761 // end catch_string_manip.h
3762 #ifndef CATCH_CONFIG_DISABLE_MATCHERS
3763 // start catch_capture_matchers.h
3764
3765 // start catch_matchers.h
3766
3767 #include <string>
3768 #include <vector>
3769
3770 namespace Catch {
3771 namespace Matchers {
3772 namespace Impl {
3773
3774 template <typename ArgT> struct MatchAllOf;
3775 template <typename ArgT> struct MatchAnyOf;
3776 template <typename ArgT> struct MatchNotOf;
3777
3778 class MatcherUntypedBase
3779 {
3780 public:
3781 MatcherUntypedBase() = default;
3782 MatcherUntypedBase(MatcherUntypedBase const &) = default;
3783 MatcherUntypedBase &operator=(MatcherUntypedBase const &) = delete;
3784 std::string toString() const;
3785
3786 protected:
3787 virtual ~MatcherUntypedBase();
3788 virtual std::string describe() const = 0;
3789 mutable std::string m_cachedToString;
3790 };
3791
3792 #ifdef __clang__
3793 #pragma clang diagnostic push
3794 #pragma clang diagnostic ignored "-Wnon-virtual-dtor"
3795 #endif
3796
3797 template <typename ObjectT> struct MatcherMethod
3798 {
3799 virtual bool match(ObjectT const &arg) const = 0;
3800 };
3801
3802 #if defined(__OBJC__)
3803 // Hack to fix Catch GH issue #1661. Could use id for generic Object support.
3804 // use of const for Object pointers is very uncommon and under ARC it causes some kind of
3805 // signature mismatch that breaks compilation
3806 template <> struct MatcherMethod<NSString *>
3807 {
3808 virtual bool match(NSString *arg) const = 0;
3809 };
3810 #endif
3811
3812 #ifdef __clang__
3813 #pragma clang diagnostic pop
3814 #endif
3815
3816 template <typename T> struct MatcherBase : MatcherUntypedBase, MatcherMethod<T>
3817 {
3818
3819 MatchAllOf<T> operator&&(MatcherBase const &other) const;
3820 MatchAnyOf<T> operator||(MatcherBase const &other) const;
3821 MatchNotOf<T> operator!() const;
3822 };
3823
3824 template <typename ArgT> struct MatchAllOf : MatcherBase<ArgT>
3825 {
3826 bool match(ArgT const &arg) const override
3827 {
3828 for (auto matcher : m_matchers) {
3829 if (!matcher->match(arg))
3830 return false;
3831 }
3832 return true;
3833 }
3834 std::string describe() const override
3835 {
3836 std::string description;
3837 description.reserve(4 + m_matchers.size() * 32);
3838 description += "( ";
3839 bool first = true;
3840 for (auto matcher : m_matchers) {
3841 if (first)
3842 first = false;
3843 else
3844 description += " and ";
3845 description += matcher->toString();
3846 }
3847 description += " )";
3848 return description;
3849 }
3850
3851 MatchAllOf<ArgT> operator&&(MatcherBase<ArgT> const &other)
3852 {
3853 auto copy(*this);
3854 copy.m_matchers.push_back(&other);
3855 return copy;
3856 }
3857
3858 std::vector<MatcherBase<ArgT> const *> m_matchers;
3859 };
3860 template <typename ArgT> struct MatchAnyOf : MatcherBase<ArgT>
3861 {
3862
3863 bool match(ArgT const &arg) const override
3864 {
3865 for (auto matcher : m_matchers) {
3866 if (matcher->match(arg))
3867 return true;
3868 }
3869 return false;
3870 }
3871 std::string describe() const override
3872 {
3873 std::string description;
3874 description.reserve(4 + m_matchers.size() * 32);
3875 description += "( ";
3876 bool first = true;
3877 for (auto matcher : m_matchers) {
3878 if (first)
3879 first = false;
3880 else
3881 description += " or ";
3882 description += matcher->toString();
3883 }
3884 description += " )";
3885 return description;
3886 }
3887
3888 MatchAnyOf<ArgT> operator||(MatcherBase<ArgT> const &other)
3889 {
3890 auto copy(*this);
3891 copy.m_matchers.push_back(&other);
3892 return copy;
3893 }
3894
3895 std::vector<MatcherBase<ArgT> const *> m_matchers;
3896 };
3897
3898 template <typename ArgT> struct MatchNotOf : MatcherBase<ArgT>
3899 {
3900
3901 MatchNotOf(MatcherBase<ArgT> const &underlyingMatcher)
3902 : m_underlyingMatcher(underlyingMatcher)
3903 {
3904 }
3905
3906 bool match(ArgT const &arg) const override { return !m_underlyingMatcher.match(arg); }
3907
3908 std::string describe() const override { return "not " + m_underlyingMatcher.toString(); }
3909 MatcherBase<ArgT> const &m_underlyingMatcher;
3910 };
3911
3912 template <typename T> MatchAllOf<T> MatcherBase<T>::operator&&(MatcherBase const &other) const
3913 {
3914 return MatchAllOf<T>() && *this && other;
3915 }
3916 template <typename T> MatchAnyOf<T> MatcherBase<T>::operator||(MatcherBase const &other) const
3917 {
3918 return MatchAnyOf<T>() || *this || other;
3919 }
3920 template <typename T> MatchNotOf<T> MatcherBase<T>::operator!() const
3921 {
3922 return MatchNotOf<T>(*this);
3923 }
3924
3925 } // namespace Impl
3926
3927 } // namespace Matchers
3928
3929 using namespace Matchers;
3930 using Matchers::Impl::MatcherBase;
3931
3932 } // namespace Catch
3933
3934 // end catch_matchers.h
3935 // start catch_matchers_exception.hpp
3936
3937 namespace Catch {
3938 namespace Matchers {
3939 namespace Exception {
3940
3941 class ExceptionMessageMatcher : public MatcherBase<std::exception>
3942 {
3943 std::string m_message;
3944
3945 public:
3946 ExceptionMessageMatcher(std::string const &message) : m_message(message) {}
3947
3948 bool match(std::exception const &ex) const override;
3949
3950 std::string describe() const override;
3951 };
3952
3953 } // namespace Exception
3954
3955 Exception::ExceptionMessageMatcher Message(std::string const &message);
3956
3957 } // namespace Matchers
3958 } // namespace Catch
3959
3960 // end catch_matchers_exception.hpp
3961 // start catch_matchers_floating.h
3962
3963 namespace Catch {
3964 namespace Matchers {
3965
3966 namespace Floating {
3967
3968 enum class FloatingPointKind : uint8_t;
3969
3970 struct WithinAbsMatcher : MatcherBase<double>
3971 {
3972 WithinAbsMatcher(double target, double margin);
3973 bool match(double const &matchee) const override;
3974 std::string describe() const override;
3975
3976 private:
3977 double m_target;
3978 double m_margin;
3979 };
3980
3981 struct WithinUlpsMatcher : MatcherBase<double>
3982 {
3983 WithinUlpsMatcher(double target, uint64_t ulps, FloatingPointKind baseType);
3984 bool match(double const &matchee) const override;
3985 std::string describe() const override;
3986
3987 private:
3988 double m_target;
3989 uint64_t m_ulps;
3990 FloatingPointKind m_type;
3991 };
3992
3993 // Given IEEE-754 format for floats and doubles, we can assume
3994 // that float -> double promotion is lossless. Given this, we can
3995 // assume that if we do the standard relative comparison of
3996 // |lhs - rhs| <= epsilon * max(fabs(lhs), fabs(rhs)), then we get
3997 // the same result if we do this for floats, as if we do this for
3998 // doubles that were promoted from floats.
3999 struct WithinRelMatcher : MatcherBase<double>
4000 {
4001 WithinRelMatcher(double target, double epsilon);
4002 bool match(double const &matchee) const override;
4003 std::string describe() const override;
4004
4005 private:
4006 double m_target;
4007 double m_epsilon;
4008 };
4009
4010 } // namespace Floating
4011
4012 // The following functions create the actual matcher objects.
4013 // This allows the types to be inferred
4014 Floating::WithinUlpsMatcher WithinULP(double target, uint64_t maxUlpDiff);
4015 Floating::WithinUlpsMatcher WithinULP(float target, uint64_t maxUlpDiff);
4016 Floating::WithinAbsMatcher WithinAbs(double target, double margin);
4017 Floating::WithinRelMatcher WithinRel(double target, double eps);
4018 // defaults epsilon to 100*numeric_limits<double>::epsilon()
4019 Floating::WithinRelMatcher WithinRel(double target);
4020 Floating::WithinRelMatcher WithinRel(float target, float eps);
4021 // defaults epsilon to 100*numeric_limits<float>::epsilon()
4022 Floating::WithinRelMatcher WithinRel(float target);
4023
4024 } // namespace Matchers
4025 } // namespace Catch
4026
4027 // end catch_matchers_floating.h
4028 // start catch_matchers_generic.hpp
4029
4030 #include <functional>
4031 #include <string>
4032
4033 namespace Catch {
4034 namespace Matchers {
4035 namespace Generic {
4036
4037 namespace Detail {
4038 std::string finalizeDescription(const std::string &desc);
4039 }
4040
4041 template <typename T> class PredicateMatcher : public MatcherBase<T>
4042 {
4043 std::function<bool(T const &)> m_predicate;
4044 std::string m_description;
4045
4046 public:
4047 PredicateMatcher(std::function<bool(T const &)> const &elem, std::string const &descr)
4048 : m_predicate(std::move(elem)), m_description(Detail::finalizeDescription(descr))
4049 {
4050 }
4051
4052 bool match(T const &item) const override { return m_predicate(item); }
4053
4054 std::string describe() const override { return m_description; }
4055 };
4056
4057 } // namespace Generic
4058
4059 // The following functions create the actual matcher objects.
4060 // The user has to explicitly specify type to the function, because
4061 // inferring std::function<bool(T const&)> is hard (but possible) and
4062 // requires a lot of TMP.
4063 template <typename T>
4064 Generic::PredicateMatcher<T> Predicate(std::function<bool(T const &)> const &predicate,
4065 std::string const &description = "")
4066 {
4067 return Generic::PredicateMatcher<T>(predicate, description);
4068 }
4069
4070 } // namespace Matchers
4071 } // namespace Catch
4072
4073 // end catch_matchers_generic.hpp
4074 // start catch_matchers_string.h
4075
4076 #include <string>
4077
4078 namespace Catch {
4079 namespace Matchers {
4080
4081 namespace StdString {
4082
4083 struct CasedString
4084 {
4085 CasedString(std::string const &str, CaseSensitive::Choice caseSensitivity);
4086 std::string adjustString(std::string const &str) const;
4087 std::string caseSensitivitySuffix() const;
4088
4089 CaseSensitive::Choice m_caseSensitivity;
4090 std::string m_str;
4091 };
4092
4093 struct StringMatcherBase : MatcherBase<std::string>
4094 {
4095 StringMatcherBase(std::string const &operation, CasedString const &comparator);
4096 std::string describe() const override;
4097
4098 CasedString m_comparator;
4099 std::string m_operation;
4100 };
4101
4102 struct EqualsMatcher : StringMatcherBase
4103 {
4104 EqualsMatcher(CasedString const &comparator);
4105 bool match(std::string const &source) const override;
4106 };
4107 struct ContainsMatcher : StringMatcherBase
4108 {
4109 ContainsMatcher(CasedString const &comparator);
4110 bool match(std::string const &source) const override;
4111 };
4112 struct StartsWithMatcher : StringMatcherBase
4113 {
4114 StartsWithMatcher(CasedString const &comparator);
4115 bool match(std::string const &source) const override;
4116 };
4117 struct EndsWithMatcher : StringMatcherBase
4118 {
4119 EndsWithMatcher(CasedString const &comparator);
4120 bool match(std::string const &source) const override;
4121 };
4122
4123 struct RegexMatcher : MatcherBase<std::string>
4124 {
4125 RegexMatcher(std::string regex, CaseSensitive::Choice caseSensitivity);
4126 bool match(std::string const &matchee) const override;
4127 std::string describe() const override;
4128
4129 private:
4130 std::string m_regex;
4131 CaseSensitive::Choice m_caseSensitivity;
4132 };
4133
4134 } // namespace StdString
4135
4136 // The following functions create the actual matcher objects.
4137 // This allows the types to be inferred
4138
4139 StdString::EqualsMatcher Equals(std::string const &str,
4140 CaseSensitive::Choice caseSensitivity = CaseSensitive::Yes);
4141 StdString::ContainsMatcher Contains(std::string const &str,
4142 CaseSensitive::Choice caseSensitivity = CaseSensitive::Yes);
4143 StdString::EndsWithMatcher EndsWith(std::string const &str,
4144 CaseSensitive::Choice caseSensitivity = CaseSensitive::Yes);
4145 StdString::StartsWithMatcher
4146 StartsWith(std::string const &str, CaseSensitive::Choice caseSensitivity = CaseSensitive::Yes);
4147 StdString::RegexMatcher Matches(std::string const &regex,
4148 CaseSensitive::Choice caseSensitivity = CaseSensitive::Yes);
4149
4150 } // namespace Matchers
4151 } // namespace Catch
4152
4153 // end catch_matchers_string.h
4154 // start catch_matchers_vector.h
4155
4156 #include <algorithm>
4157
4158 namespace Catch {
4159 namespace Matchers {
4160
4161 namespace Vector {
4162 template <typename T, typename Alloc>
4163 struct ContainsElementMatcher : MatcherBase<std::vector<T, Alloc>>
4164 {
4165
4166 ContainsElementMatcher(T const &comparator) : m_comparator(comparator) {}
4167
4168 bool match(std::vector<T, Alloc> const &v) const override
4169 {
4170 for (auto const &el : v) {
4171 if (el == m_comparator) {
4172 return true;
4173 }
4174 }
4175 return false;
4176 }
4177
4178 std::string describe() const override
4179 {
4180 return "Contains: " + ::Catch::Detail::stringify(m_comparator);
4181 }
4182
4183 T const &m_comparator;
4184 };
4185
4186 template <typename T, typename AllocComp, typename AllocMatch>
4187 struct ContainsMatcher : MatcherBase<std::vector<T, AllocMatch>>
4188 {
4189
4190 ContainsMatcher(std::vector<T, AllocComp> const &comparator) : m_comparator(comparator) {}
4191
4192 bool match(std::vector<T, AllocMatch> const &v) const override
4193 {
4194 // !TBD: see note in EqualsMatcher
4195 if (m_comparator.size() > v.size())
4196 return false;
4197 for (auto const &comparator : m_comparator) {
4198 auto present = false;
4199 for (const auto &el : v) {
4200 if (el == comparator) {
4201 present = true;
4202 break;
4203 }
4204 }
4205 if (!present) {
4206 return false;
4207 }
4208 }
4209 return true;
4210 }
4211 std::string describe() const override
4212 {
4213 return "Contains: " + ::Catch::Detail::stringify(m_comparator);
4214 }
4215
4216 std::vector<T, AllocComp> const &m_comparator;
4217 };
4218
4219 template <typename T, typename AllocComp, typename AllocMatch>
4220 struct EqualsMatcher : MatcherBase<std::vector<T, AllocMatch>>
4221 {
4222
4223 EqualsMatcher(std::vector<T, AllocComp> const &comparator) : m_comparator(comparator) {}
4224
4225 bool match(std::vector<T, AllocMatch> const &v) const override
4226 {
4227 // !TBD: This currently works if all elements can be compared using !=
4228 // - a more general approach would be via a compare template that defaults
4229 // to using !=. but could be specialised for, e.g. std::vector<T, Alloc> etc
4230 // - then just call that directly
4231 if (m_comparator.size() != v.size())
4232 return false;
4233 for (std::size_t i = 0; i < v.size(); ++i)
4234 if (m_comparator[i] != v[i])
4235 return false;
4236 return true;
4237 }
4238 std::string describe() const override
4239 {
4240 return "Equals: " + ::Catch::Detail::stringify(m_comparator);
4241 }
4242 std::vector<T, AllocComp> const &m_comparator;
4243 };
4244
4245 template <typename T, typename AllocComp, typename AllocMatch>
4246 struct ApproxMatcher : MatcherBase<std::vector<T, AllocMatch>>
4247 {
4248
4249 ApproxMatcher(std::vector<T, AllocComp> const &comparator) : m_comparator(comparator) {}
4250
4251 bool match(std::vector<T, AllocMatch> const &v) const override
4252 {
4253 if (m_comparator.size() != v.size())
4254 return false;
4255 for (std::size_t i = 0; i < v.size(); ++i)
4256 if (m_comparator[i] != approx(v[i]))
4257 return false;
4258 return true;
4259 }
4260 std::string describe() const override
4261 {
4262 return "is approx: " + ::Catch::Detail::stringify(m_comparator);
4263 }
4264 template <typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
4265 ApproxMatcher &epsilon(T const &newEpsilon)
4266 {
4267 approx.epsilon(newEpsilon);
4268 return *this;
4269 }
4270 template <typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
4271 ApproxMatcher &margin(T const &newMargin)
4272 {
4273 approx.margin(newMargin);
4274 return *this;
4275 }
4276 template <typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
4277 ApproxMatcher &scale(T const &newScale)
4278 {
4279 approx.scale(newScale);
4280 return *this;
4281 }
4282
4283 std::vector<T, AllocComp> const &m_comparator;
4284 mutable Catch::Detail::Approx approx = Catch::Detail::Approx::custom();
4285 };
4286
4287 template <typename T, typename AllocComp, typename AllocMatch>
4288 struct UnorderedEqualsMatcher : MatcherBase<std::vector<T, AllocMatch>>
4289 {
4290 UnorderedEqualsMatcher(std::vector<T, AllocComp> const &target) : m_target(target) {}
4291 bool match(std::vector<T, AllocMatch> const &vec) const override
4292 {
4293 if (m_target.size() != vec.size()) {
4294 return false;
4295 }
4296 return std::is_permutation(m_target.begin(), m_target.end(), vec.begin());
4297 }
4298
4299 std::string describe() const override
4300 {
4301 return "UnorderedEquals: " + ::Catch::Detail::stringify(m_target);
4302 }
4303
4304 private:
4305 std::vector<T, AllocComp> const &m_target;
4306 };
4307
4308 } // namespace Vector
4309
4310 // The following functions create the actual matcher objects.
4311 // This allows the types to be inferred
4312
4313 template <typename T, typename AllocComp = std::allocator<T>, typename AllocMatch = AllocComp>
4314 Vector::ContainsMatcher<T, AllocComp, AllocMatch>
4315 Contains(std::vector<T, AllocComp> const &comparator)
4316 {
4317 return Vector::ContainsMatcher<T, AllocComp, AllocMatch>(comparator);
4318 }
4319
4320 template <typename T, typename Alloc = std::allocator<T>>
4321 Vector::ContainsElementMatcher<T, Alloc> VectorContains(T const &comparator)
4322 {
4323 return Vector::ContainsElementMatcher<T, Alloc>(comparator);
4324 }
4325
4326 template <typename T, typename AllocComp = std::allocator<T>, typename AllocMatch = AllocComp>
4327 Vector::EqualsMatcher<T, AllocComp, AllocMatch>
4328 Equals(std::vector<T, AllocComp> const &comparator)
4329 {
4330 return Vector::EqualsMatcher<T, AllocComp, AllocMatch>(comparator);
4331 }
4332
4333 template <typename T, typename AllocComp = std::allocator<T>, typename AllocMatch = AllocComp>
4334 Vector::ApproxMatcher<T, AllocComp, AllocMatch>
4335 Approx(std::vector<T, AllocComp> const &comparator)
4336 {
4337 return Vector::ApproxMatcher<T, AllocComp, AllocMatch>(comparator);
4338 }
4339
4340 template <typename T, typename AllocComp = std::allocator<T>, typename AllocMatch = AllocComp>
4341 Vector::UnorderedEqualsMatcher<T, AllocComp, AllocMatch>
4342 UnorderedEquals(std::vector<T, AllocComp> const &target)
4343 {
4344 return Vector::UnorderedEqualsMatcher<T, AllocComp, AllocMatch>(target);
4345 }
4346
4347 } // namespace Matchers
4348 } // namespace Catch
4349
4350 // end catch_matchers_vector.h
4351 namespace Catch {
4352
4353 template <typename ArgT, typename MatcherT> class MatchExpr : public ITransientExpression
4354 {
4355 ArgT const &m_arg;
4356 MatcherT m_matcher;
4357 StringRef m_matcherString;
4358
4359 public:
4360 MatchExpr(ArgT const &arg, MatcherT const &matcher, StringRef const &matcherString)
4361 : ITransientExpression{true, matcher.match(arg)}, m_arg(arg), m_matcher(matcher),
4362 m_matcherString(matcherString)
4363 {
4364 }
4365
4366 void streamReconstructedExpression(std::ostream &os) const override
4367 {
4368 auto matcherAsString = m_matcher.toString();
4369 os << Catch::Detail::stringify(m_arg) << ' ';
4370 if (matcherAsString == Detail::unprintableString)
4371 os << m_matcherString;
4372 else
4373 os << matcherAsString;
4374 }
4375 };
4376
4377 using StringMatcher = Matchers::Impl::MatcherBase<std::string>;
4378
4379 void handleExceptionMatchExpr(AssertionHandler &handler, StringMatcher const &matcher,
4380 StringRef const &matcherString);
4381
4382 template <typename ArgT, typename MatcherT>
4383 auto makeMatchExpr(ArgT const &arg, MatcherT const &matcher,
4384 StringRef const &matcherString) -> MatchExpr<ArgT, MatcherT>
4385 {
4386 return MatchExpr<ArgT, MatcherT>(arg, matcher, matcherString);
4387 }
4388
4389 } // namespace Catch
4390
4391 ///////////////////////////////////////////////////////////////////////////////
4392 #define INTERNAL_CHECK_THAT(macroName, matcher, resultDisposition, arg) \
4393 do { \
4394 Catch::AssertionHandler catchAssertionHandler( \
4395 macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, \
4396 CATCH_INTERNAL_STRINGIFY(arg) ", " CATCH_INTERNAL_STRINGIFY(matcher), resultDisposition); \
4397 INTERNAL_CATCH_TRY \
4398 { \
4399 catchAssertionHandler.handleExpr(Catch::makeMatchExpr(arg, matcher, #matcher##_catch_sr)); \
4400 } \
4401 INTERNAL_CATCH_CATCH(catchAssertionHandler) \
4402 INTERNAL_CATCH_REACT(catchAssertionHandler) \
4403 } while (false)
4404
4405 ///////////////////////////////////////////////////////////////////////////////
4406 #define INTERNAL_CATCH_THROWS_MATCHES(macroName, exceptionType, resultDisposition, matcher, ...) \
4407 do { \
4408 Catch::AssertionHandler catchAssertionHandler( \
4409 macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, \
4410 CATCH_INTERNAL_STRINGIFY(__VA_ARGS__) ", " CATCH_INTERNAL_STRINGIFY( \
4411 exceptionType) ", " CATCH_INTERNAL_STRINGIFY(matcher), \
4412 resultDisposition); \
4413 if (catchAssertionHandler.allowThrows()) \
4414 try { \
4415 static_cast<void>(__VA_ARGS__); \
4416 catchAssertionHandler.handleUnexpectedExceptionNotThrown(); \
4417 } \
4418 catch (exceptionType const &ex) { \
4419 catchAssertionHandler.handleExpr(Catch::makeMatchExpr(ex, matcher, #matcher##_catch_sr)); \
4420 } \
4421 catch (...) { \
4422 catchAssertionHandler.handleUnexpectedInflightException(); \
4423 } \
4424 else \
4425 catchAssertionHandler.handleThrowingCallSkipped(); \
4426 INTERNAL_CATCH_REACT(catchAssertionHandler) \
4427 } while (false)
4428
4429 // end catch_capture_matchers.h
4430 #endif
4431 // start catch_generators.hpp
4432
4433 // start catch_interfaces_generatortracker.h
4434
4435 #include <memory>
4436
4437 namespace Catch {
4438
4439 namespace Generators {
4440 class GeneratorUntypedBase
4441 {
4442 public:
4443 GeneratorUntypedBase() = default;
4444 virtual ~GeneratorUntypedBase();
4445 // Attempts to move the generator to the next element
4446 //
4447 // Returns true iff the move succeeded (and a valid element
4448 // can be retrieved).
4449 virtual bool next() = 0;
4450 };
4451 using GeneratorBasePtr = std::unique_ptr<GeneratorUntypedBase>;
4452
4453 } // namespace Generators
4454
4455 struct IGeneratorTracker
4456 {
4457 virtual ~IGeneratorTracker();
4458 virtual auto hasGenerator() const -> bool = 0;
4459 virtual auto getGenerator() const -> Generators::GeneratorBasePtr const & = 0;
4460 virtual void setGenerator(Generators::GeneratorBasePtr &&generator) = 0;
4461 };
4462
4463 } // namespace Catch
4464
4465 // end catch_interfaces_generatortracker.h
4466 // start catch_enforce.h
4467
4468 #include <exception>
4469
4470 namespace Catch {
4471 #if !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
4472 template <typename Ex>
4473 [[noreturn]]
4474 void throw_exception(Ex const &e)
4475 {
4476 throw e;
4477 }
4478 #else // ^^ Exceptions are enabled // Exceptions are disabled vv
4479 [[noreturn]]
4480 void throw_exception(std::exception const &e);
4481 #endif
4482
4483 [[noreturn]]
4484 void throw_logic_error(std::string const &msg);
4485 [[noreturn]]
4486 void throw_domain_error(std::string const &msg);
4487 [[noreturn]]
4488 void throw_runtime_error(std::string const &msg);
4489
4490 } // namespace Catch
4491
4492 #define CATCH_MAKE_MSG(...) (Catch::ReusableStringStream() << __VA_ARGS__).str()
4493
4494 #define CATCH_INTERNAL_ERROR(...) \
4495 Catch::throw_logic_error( \
4496 CATCH_MAKE_MSG(CATCH_INTERNAL_LINEINFO << ": Internal Catch2 error: " << __VA_ARGS__))
4497
4498 #define CATCH_ERROR(...) Catch::throw_domain_error(CATCH_MAKE_MSG(__VA_ARGS__))
4499
4500 #define CATCH_RUNTIME_ERROR(...) Catch::throw_runtime_error(CATCH_MAKE_MSG(__VA_ARGS__))
4501
4502 #define CATCH_ENFORCE(condition, ...) \
4503 do { \
4504 if (!(condition)) \
4505 CATCH_ERROR(__VA_ARGS__); \
4506 } while (false)
4507
4508 // end catch_enforce.h
4509 #include <cassert>
4510 #include <memory>
4511 #include <vector>
4512
4513 #include <exception>
4514 #include <utility>
4515
4516 namespace Catch {
4517
4518 class GeneratorException : public std::exception
4519 {
4520 const char *const m_msg = "";
4521
4522 public:
4523 GeneratorException(const char *msg) : m_msg(msg) {}
4524
4525 const char *what() const noexcept override final;
4526 };
4527
4528 namespace Generators {
4529
4530 // !TBD move this into its own location?
4531 namespace pf {
4532 template <typename T, typename... Args> std::unique_ptr<T> make_unique(Args &&...args)
4533 {
4534 return std::unique_ptr<T>(new T(std::forward<Args>(args)...));
4535 }
4536 } // namespace pf
4537
4538 template <typename T> struct IGenerator : GeneratorUntypedBase
4539 {
4540 virtual ~IGenerator() = default;
4541
4542 // Returns the current element of the generator
4543 //
4544 // \Precondition The generator is either freshly constructed,
4545 // or the last call to `next()` returned true
4546 virtual T const &get() const = 0;
4547 using type = T;
4548 };
4549
4550 template <typename T> class SingleValueGenerator final : public IGenerator<T>
4551 {
4552 T m_value;
4553
4554 public:
4555 SingleValueGenerator(T &&value) : m_value(std::move(value)) {}
4556
4557 T const &get() const override { return m_value; }
4558 bool next() override { return false; }
4559 };
4560
4561 template <typename T> class FixedValuesGenerator final : public IGenerator<T>
4562 {
4563 static_assert(!std::is_same<T, bool>::value,
4564 "FixedValuesGenerator does not support bools because of std::vector<bool>"
4565 "specialization, use SingleValue Generator instead.");
4566 std::vector<T> m_values;
4567 size_t m_idx = 0;
4568
4569 public:
4570 FixedValuesGenerator(std::initializer_list<T> values) : m_values(values) {}
4571
4572 T const &get() const override { return m_values[m_idx]; }
4573 bool next() override
4574 {
4575 ++m_idx;
4576 return m_idx < m_values.size();
4577 }
4578 };
4579
4580 template <typename T> class GeneratorWrapper final
4581 {
4582 std::unique_ptr<IGenerator<T>> m_generator;
4583
4584 public:
4585 GeneratorWrapper(std::unique_ptr<IGenerator<T>> generator) : m_generator(std::move(generator))
4586 {
4587 }
4588 T const &get() const { return m_generator->get(); }
4589 bool next() { return m_generator->next(); }
4590 };
4591
4592 template <typename T> GeneratorWrapper<T> value(T &&value)
4593 {
4594 return GeneratorWrapper<T>(pf::make_unique<SingleValueGenerator<T>>(std::forward<T>(value)));
4595 }
4596 template <typename T> GeneratorWrapper<T> values(std::initializer_list<T> values)
4597 {
4598 return GeneratorWrapper<T>(pf::make_unique<FixedValuesGenerator<T>>(values));
4599 }
4600
4601 template <typename T> class Generators : public IGenerator<T>
4602 {
4603 std::vector<GeneratorWrapper<T>> m_generators;
4604 size_t m_current = 0;
4605
4606 void populate(GeneratorWrapper<T> &&generator)
4607 {
4608 m_generators.emplace_back(std::move(generator));
4609 }
4610 void populate(T &&val) { m_generators.emplace_back(value(std::forward<T>(val))); }
4611 template <typename U> void populate(U &&val) { populate(T(std::forward<U>(val))); }
4612 template <typename U, typename... Gs>
4613 void populate(U &&valueOrGenerator, Gs &&...moreGenerators)
4614 {
4615 populate(std::forward<U>(valueOrGenerator));
4616 populate(std::forward<Gs>(moreGenerators)...);
4617 }
4618
4619 public:
4620 template <typename... Gs> Generators(Gs &&...moreGenerators)
4621 {
4622 m_generators.reserve(sizeof...(Gs));
4623 populate(std::forward<Gs>(moreGenerators)...);
4624 }
4625
4626 T const &get() const override { return m_generators[m_current].get(); }
4627
4628 bool next() override
4629 {
4630 if (m_current >= m_generators.size()) {
4631 return false;
4632 }
4633 const bool current_status = m_generators[m_current].next();
4634 if (!current_status) {
4635 ++m_current;
4636 }
4637 return m_current < m_generators.size();
4638 }
4639 };
4640
4641 template <typename... Ts>
4642 GeneratorWrapper<std::tuple<Ts...>>
4643 table(std::initializer_list<std::tuple<typename std::decay<Ts>::type...>> tuples)
4644 {
4645 return values<std::tuple<Ts...>>(tuples);
4646 }
4647
4648 // Tag type to signal that a generator sequence should convert arguments to a specific type
4649 template <typename T> struct as
4650 {
4651 };
4652
4653 template <typename T, typename... Gs>
4654 auto makeGenerators(GeneratorWrapper<T> &&generator, Gs &&...moreGenerators) -> Generators<T>
4655 {
4656 return Generators<T>(std::move(generator), std::forward<Gs>(moreGenerators)...);
4657 }
4658 template <typename T> auto makeGenerators(GeneratorWrapper<T> &&generator) -> Generators<T>
4659 {
4660 return Generators<T>(std::move(generator));
4661 }
4662 template <typename T, typename... Gs>
4663 auto makeGenerators(T &&val, Gs &&...moreGenerators) -> Generators<T>
4664 {
4665 return makeGenerators(value(std::forward<T>(val)), std::forward<Gs>(moreGenerators)...);
4666 }
4667 template <typename T, typename U, typename... Gs>
4668 auto makeGenerators(as<T>, U &&val, Gs &&...moreGenerators) -> Generators<T>
4669 {
4670 return makeGenerators(value(T(std::forward<U>(val))), std::forward<Gs>(moreGenerators)...);
4671 }
4672
4673 auto acquireGeneratorTracker(StringRef generatorName,
4674 SourceLineInfo const &lineInfo) -> IGeneratorTracker &;
4675
4676 template <typename L>
4677 // Note: The type after -> is weird, because VS2015 cannot parse
4678 // the expression used in the typedef inside, when it is in
4679 // return type. Yeah.
4680 auto generate(StringRef generatorName, SourceLineInfo const &lineInfo,
4681 L const &generatorExpression)
4682 -> decltype(std::declval<decltype(generatorExpression())>().get())
4683 {
4684 using UnderlyingType = typename decltype(generatorExpression())::type;
4685
4686 IGeneratorTracker &tracker = acquireGeneratorTracker(generatorName, lineInfo);
4687 if (!tracker.hasGenerator()) {
4688 tracker.setGenerator(pf::make_unique<Generators<UnderlyingType>>(generatorExpression()));
4689 }
4690
4691 auto const &generator =
4692 static_cast<IGenerator<UnderlyingType> const &>(*tracker.getGenerator());
4693 return generator.get();
4694 }
4695
4696 } // namespace Generators
4697 } // namespace Catch
4698
4699 #define GENERATE(...) \
4700 Catch::Generators::generate(INTERNAL_CATCH_STRINGIZE(INTERNAL_CATCH_UNIQUE_NAME(generator)), \
4701 CATCH_INTERNAL_LINEINFO, [] { \
4702 using namespace Catch::Generators; \
4703 return makeGenerators(__VA_ARGS__); \
4704 }) // NOLINT(google-build-using-namespace)
4705 #define GENERATE_COPY(...) \
4706 Catch::Generators::generate(INTERNAL_CATCH_STRINGIZE(INTERNAL_CATCH_UNIQUE_NAME(generator)), \
4707 CATCH_INTERNAL_LINEINFO, [=] { \
4708 using namespace Catch::Generators; \
4709 return makeGenerators(__VA_ARGS__); \
4710 }) // NOLINT(google-build-using-namespace)
4711 #define GENERATE_REF(...) \
4712 Catch::Generators::generate(INTERNAL_CATCH_STRINGIZE(INTERNAL_CATCH_UNIQUE_NAME(generator)), \
4713 CATCH_INTERNAL_LINEINFO, [&] { \
4714 using namespace Catch::Generators; \
4715 return makeGenerators(__VA_ARGS__); \
4716 }) // NOLINT(google-build-using-namespace)
4717
4718 // end catch_generators.hpp
4719 // start catch_generators_generic.hpp
4720
4721 namespace Catch {
4722 namespace Generators {
4723
4724 template <typename T> class TakeGenerator : public IGenerator<T>
4725 {
4726 GeneratorWrapper<T> m_generator;
4727 size_t m_returned = 0;
4728 size_t m_target;
4729
4730 public:
4731 TakeGenerator(size_t target, GeneratorWrapper<T> &&generator)
4732 : m_generator(std::move(generator)), m_target(target)
4733 {
4734 assert(target != 0 && "Empty generators are not allowed");
4735 }
4736 T const &get() const override { return m_generator.get(); }
4737 bool next() override
4738 {
4739 ++m_returned;
4740 if (m_returned >= m_target) {
4741 return false;
4742 }
4743
4744 const auto success = m_generator.next();
4745 // If the underlying generator does not contain enough values
4746 // then we cut short as well
4747 if (!success) {
4748 m_returned = m_target;
4749 }
4750 return success;
4751 }
4752 };
4753
4754 template <typename T> GeneratorWrapper<T> take(size_t target, GeneratorWrapper<T> &&generator)
4755 {
4756 return GeneratorWrapper<T>(pf::make_unique<TakeGenerator<T>>(target, std::move(generator)));
4757 }
4758
4759 template <typename T, typename Predicate> class FilterGenerator : public IGenerator<T>
4760 {
4761 GeneratorWrapper<T> m_generator;
4762 Predicate m_predicate;
4763
4764 public:
4765 template <typename P = Predicate>
4766 FilterGenerator(P &&pred, GeneratorWrapper<T> &&generator)
4767 : m_generator(std::move(generator)), m_predicate(std::forward<P>(pred))
4768 {
4769 if (!m_predicate(m_generator.get())) {
4770 // It might happen that there are no values that pass the
4771 // filter. In that case we throw an exception.
4772 auto has_initial_value = next();
4773 if (!has_initial_value) {
4774 Catch::throw_exception(
4775 GeneratorException("No valid value found in filtered generator"));
4776 }
4777 }
4778 }
4779
4780 T const &get() const override { return m_generator.get(); }
4781
4782 bool next() override
4783 {
4784 bool success = m_generator.next();
4785 if (!success) {
4786 return false;
4787 }
4788 while (!m_predicate(m_generator.get()) && (success = m_generator.next()) == true)
4789 ;
4790 return success;
4791 }
4792 };
4793
4794 template <typename T, typename Predicate>
4795 GeneratorWrapper<T> filter(Predicate &&pred, GeneratorWrapper<T> &&generator)
4796 {
4797 return GeneratorWrapper<T>(
4798 std::unique_ptr<IGenerator<T>>(pf::make_unique<FilterGenerator<T, Predicate>>(
4799 std::forward<Predicate>(pred), std::move(generator))));
4800 }
4801
4802 template <typename T> class RepeatGenerator : public IGenerator<T>
4803 {
4804 static_assert(!std::is_same<T, bool>::value,
4805 "RepeatGenerator currently does not support bools"
4806 "because of std::vector<bool> specialization");
4807 GeneratorWrapper<T> m_generator;
4808 mutable std::vector<T> m_returned;
4809 size_t m_target_repeats;
4810 size_t m_current_repeat = 0;
4811 size_t m_repeat_index = 0;
4812
4813 public:
4814 RepeatGenerator(size_t repeats, GeneratorWrapper<T> &&generator)
4815 : m_generator(std::move(generator)), m_target_repeats(repeats)
4816 {
4817 assert(m_target_repeats > 0 && "Repeat generator must repeat at least once");
4818 }
4819
4820 T const &get() const override
4821 {
4822 if (m_current_repeat == 0) {
4823 m_returned.push_back(m_generator.get());
4824 return m_returned.back();
4825 }
4826 return m_returned[m_repeat_index];
4827 }
4828
4829 bool next() override
4830 {
4831 // There are 2 basic cases:
4832 // 1) We are still reading the generator
4833 // 2) We are reading our own cache
4834
4835 // In the first case, we need to poke the underlying generator.
4836 // If it happily moves, we are left in that state, otherwise it is time to start reading
4837 // from our cache
4838 if (m_current_repeat == 0) {
4839 const auto success = m_generator.next();
4840 if (!success) {
4841 ++m_current_repeat;
4842 }
4843 return m_current_repeat < m_target_repeats;
4844 }
4845
4846 // In the second case, we need to move indices forward and check that we haven't run up
4847 // against the end
4848 ++m_repeat_index;
4849 if (m_repeat_index == m_returned.size()) {
4850 m_repeat_index = 0;
4851 ++m_current_repeat;
4852 }
4853 return m_current_repeat < m_target_repeats;
4854 }
4855 };
4856
4857 template <typename T>
4858 GeneratorWrapper<T> repeat(size_t repeats, GeneratorWrapper<T> &&generator)
4859 {
4860 return GeneratorWrapper<T>(
4861 pf::make_unique<RepeatGenerator<T>>(repeats, std::move(generator)));
4862 }
4863
4864 template <typename T, typename U, typename Func> class MapGenerator : public IGenerator<T>
4865 {
4866 // TBD: provide static assert for mapping function, for friendly error message
4867 GeneratorWrapper<U> m_generator;
4868 Func m_function;
4869 // To avoid returning dangling reference, we have to save the values
4870 T m_cache;
4871
4872 public:
4873 template <typename F2 = Func>
4874 MapGenerator(F2 &&function, GeneratorWrapper<U> &&generator)
4875 : m_generator(std::move(generator)), m_function(std::forward<F2>(function)),
4876 m_cache(m_function(m_generator.get()))
4877 {
4878 }
4879
4880 T const &get() const override { return m_cache; }
4881 bool next() override
4882 {
4883 const auto success = m_generator.next();
4884 if (success) {
4885 m_cache = m_function(m_generator.get());
4886 }
4887 return success;
4888 }
4889 };
4890
4891 template <typename Func, typename U, typename T = FunctionReturnType<Func, U>>
4892 GeneratorWrapper<T> map(Func &&function, GeneratorWrapper<U> &&generator)
4893 {
4894 return GeneratorWrapper<T>(pf::make_unique<MapGenerator<T, U, Func>>(
4895 std::forward<Func>(function), std::move(generator)));
4896 }
4897
4898 template <typename T, typename U, typename Func>
4899 GeneratorWrapper<T> map(Func &&function, GeneratorWrapper<U> &&generator)
4900 {
4901 return GeneratorWrapper<T>(pf::make_unique<MapGenerator<T, U, Func>>(
4902 std::forward<Func>(function), std::move(generator)));
4903 }
4904
4905 template <typename T> class ChunkGenerator final : public IGenerator<std::vector<T>>
4906 {
4907 std::vector<T> m_chunk;
4908 size_t m_chunk_size;
4909 GeneratorWrapper<T> m_generator;
4910 bool m_used_up = false;
4911
4912 public:
4913 ChunkGenerator(size_t size, GeneratorWrapper<T> generator)
4914 : m_chunk_size(size), m_generator(std::move(generator))
4915 {
4916 m_chunk.reserve(m_chunk_size);
4917 if (m_chunk_size != 0) {
4918 m_chunk.push_back(m_generator.get());
4919 for (size_t i = 1; i < m_chunk_size; ++i) {
4920 if (!m_generator.next()) {
4921 Catch::throw_exception(
4922 GeneratorException("Not enough values to initialize the first chunk"));
4923 }
4924 m_chunk.push_back(m_generator.get());
4925 }
4926 }
4927 }
4928 std::vector<T> const &get() const override { return m_chunk; }
4929 bool next() override
4930 {
4931 m_chunk.clear();
4932 for (size_t idx = 0; idx < m_chunk_size; ++idx) {
4933 if (!m_generator.next()) {
4934 return false;
4935 }
4936 m_chunk.push_back(m_generator.get());
4937 }
4938 return true;
4939 }
4940 };
4941
4942 template <typename T>
4943 GeneratorWrapper<std::vector<T>> chunk(size_t size, GeneratorWrapper<T> &&generator)
4944 {
4945 return GeneratorWrapper<std::vector<T>>(
4946 pf::make_unique<ChunkGenerator<T>>(size, std::move(generator)));
4947 }
4948
4949 } // namespace Generators
4950 } // namespace Catch
4951
4952 // end catch_generators_generic.hpp
4953 // start catch_generators_specific.hpp
4954
4955 // start catch_context.h
4956
4957 #include <memory>
4958
4959 namespace Catch {
4960
4961 struct IResultCapture;
4962 struct IRunner;
4963 struct IConfig;
4964 struct IMutableContext;
4965
4966 using IConfigPtr = std::shared_ptr<IConfig const>;
4967
4968 struct IContext
4969 {
4970 virtual ~IContext();
4971
4972 virtual IResultCapture *getResultCapture() = 0;
4973 virtual IRunner *getRunner() = 0;
4974 virtual IConfigPtr const &getConfig() const = 0;
4975 };
4976
4977 struct IMutableContext : IContext
4978 {
4979 virtual ~IMutableContext();
4980 virtual void setResultCapture(IResultCapture *resultCapture) = 0;
4981 virtual void setRunner(IRunner *runner) = 0;
4982 virtual void setConfig(IConfigPtr const &config) = 0;
4983
4984 private:
4985 static IMutableContext *currentContext;
4986 friend IMutableContext &getCurrentMutableContext();
4987 friend void cleanUpContext();
4988 static void createContext();
4989 };
4990
4991 inline IMutableContext &getCurrentMutableContext()
4992 {
4993 if (!IMutableContext::currentContext)
4994 IMutableContext::createContext();
4995 // NOLINTNEXTLINE(clang-analyzer-core.uninitialized.UndefReturn)
4996 return *IMutableContext::currentContext;
4997 }
4998
4999 inline IContext &getCurrentContext() { return getCurrentMutableContext(); }
5000
5001 void cleanUpContext();
5002
5003 class SimplePcg32;
5004 SimplePcg32 &rng();
5005 } // namespace Catch
5006
5007 // end catch_context.h
5008 // start catch_interfaces_config.h
5009
5010 // start catch_option.hpp
5011
5012 namespace Catch {
5013
5014 // An optional type
5015 template <typename T> class Option
5016 {
5017 public:
5018 Option() : nullableValue(nullptr) {}
5019 Option(T const &_value) : nullableValue(new(storage) T(_value)) {}
5020 Option(Option const &_other) : nullableValue(_other ? new(storage) T(*_other) : nullptr) {}
5021
5022 ~Option() { reset(); }
5023
5024 Option &operator=(Option const &_other)
5025 {
5026 if (&_other != this) {
5027 reset();
5028 if (_other)
5029 nullableValue = new (storage) T(*_other);
5030 }
5031 return *this;
5032 }
5033 Option &operator=(T const &_value)
5034 {
5035 reset();
5036 nullableValue = new (storage) T(_value);
5037 return *this;
5038 }
5039
5040 void reset()
5041 {
5042 if (nullableValue)
5043 nullableValue->~T();
5044 nullableValue = nullptr;
5045 }
5046
5047 T &operator*() { return *nullableValue; }
5048 T const &operator*() const { return *nullableValue; }
5049 T *operator->() { return nullableValue; }
5050 const T *operator->() const { return nullableValue; }
5051
5052 T valueOr(T const &defaultValue) const { return nullableValue ? *nullableValue : defaultValue; }
5053
5054 bool some() const { return nullableValue != nullptr; }
5055 bool none() const { return nullableValue == nullptr; }
5056
5057 bool operator!() const { return nullableValue == nullptr; }
5058 explicit operator bool() const { return some(); }
5059
5060 private:
5061 T *nullableValue;
5062 alignas(alignof(T)) char storage[sizeof(T)];
5063 };
5064
5065 } // end namespace Catch
5066
5067 // end catch_option.hpp
5068 #include <chrono>
5069 #include <iosfwd>
5070 #include <memory>
5071 #include <string>
5072 #include <vector>
5073
5074 namespace Catch {
5075
5076 enum class Verbosity { Quiet = 0, Normal, High };
5077
5078 struct WarnAbout
5079 {
5080 enum What { Nothing = 0x00, NoAssertions = 0x01, NoTests = 0x02 };
5081 };
5082
5083 struct ShowDurations
5084 {
5085 enum OrNot { DefaultForReporter, Always, Never };
5086 };
5087 struct RunTests
5088 {
5089 enum InWhatOrder { InDeclarationOrder, InLexicographicalOrder, InRandomOrder };
5090 };
5091 struct UseColour
5092 {
5093 enum YesOrNo { Auto, Yes, No };
5094 };
5095 struct WaitForKeypress
5096 {
5097 enum When {
5098 Never,
5099 BeforeStart = 1,
5100 BeforeExit = 2,
5101 BeforeStartAndExit = BeforeStart | BeforeExit
5102 };
5103 };
5104
5105 class TestSpec;
5106
5107 struct IConfig : NonCopyable
5108 {
5109
5110 virtual ~IConfig();
5111
5112 virtual bool allowThrows() const = 0;
5113 virtual std::ostream &stream() const = 0;
5114 virtual std::string name() const = 0;
5115 virtual bool includeSuccessfulResults() const = 0;
5116 virtual bool shouldDebugBreak() const = 0;
5117 virtual bool warnAboutMissingAssertions() const = 0;
5118 virtual bool warnAboutNoTests() const = 0;
5119 virtual int abortAfter() const = 0;
5120 virtual bool showInvisibles() const = 0;
5121 virtual ShowDurations::OrNot showDurations() const = 0;
5122 virtual double minDuration() const = 0;
5123 virtual TestSpec const &testSpec() const = 0;
5124 virtual bool hasTestFilters() const = 0;
5125 virtual std::vector<std::string> const &getTestsOrTags() const = 0;
5126 virtual RunTests::InWhatOrder runOrder() const = 0;
5127 virtual unsigned int rngSeed() const = 0;
5128 virtual UseColour::YesOrNo useColour() const = 0;
5129 virtual std::vector<std::string> const &getSectionsToRun() const = 0;
5130 virtual Verbosity verbosity() const = 0;
5131
5132 virtual bool benchmarkNoAnalysis() const = 0;
5133 virtual int benchmarkSamples() const = 0;
5134 virtual double benchmarkConfidenceInterval() const = 0;
5135 virtual unsigned int benchmarkResamples() const = 0;
5136 virtual std::chrono::milliseconds benchmarkWarmupTime() const = 0;
5137 };
5138
5139 using IConfigPtr = std::shared_ptr<IConfig const>;
5140 } // namespace Catch
5141
5142 // end catch_interfaces_config.h
5143 // start catch_random_number_generator.h
5144
5145 #include <cstdint>
5146
5147 namespace Catch {
5148
5149 // This is a simple implementation of C++11 Uniform Random Number
5150 // Generator. It does not provide all operators, because Catch2
5151 // does not use it, but it should behave as expected inside stdlib's
5152 // distributions.
5153 // The implementation is based on the PCG family (http://pcg-random.org)
5154 class SimplePcg32
5155 {
5156 using state_type = std::uint64_t;
5157
5158 public:
5159 using result_type = std::uint32_t;
5160 static constexpr result_type(min)() { return 0; }
5161 static constexpr result_type(max)() { return static_cast<result_type>(-1); }
5162
5163 // Provide some default initial state for the default constructor
5164 SimplePcg32() : SimplePcg32(0xed743cc4U) {}
5165
5166 explicit SimplePcg32(result_type seed_);
5167
5168 void seed(result_type seed_);
5169 void discard(uint64_t skip);
5170
5171 result_type operator()();
5172
5173 private:
5174 friend bool operator==(SimplePcg32 const &lhs, SimplePcg32 const &rhs);
5175 friend bool operator!=(SimplePcg32 const &lhs, SimplePcg32 const &rhs);
5176
5177 // In theory we also need operator<< and operator>>
5178 // In practice we do not use them, so we will skip them for now
5179
5180 std::uint64_t m_state;
5181 // This part of the state determines which "stream" of the numbers
5182 // is chosen -- we take it as a constant for Catch2, so we only
5183 // need to deal with seeding the main state.
5184 // Picked by reading 8 bytes from `/dev/random` :-)
5185 static const std::uint64_t s_inc = (0x13ed0cc53f939476ULL << 1ULL) | 1ULL;
5186 };
5187
5188 } // end namespace Catch
5189
5190 // end catch_random_number_generator.h
5191 #include <random>
5192
5193 namespace Catch {
5194 namespace Generators {
5195
5196 template <typename Float> class RandomFloatingGenerator final : public IGenerator<Float>
5197 {
5198 Catch::SimplePcg32 &m_rng;
5199 std::uniform_real_distribution<Float> m_dist;
5200 Float m_current_number;
5201
5202 public:
5203 RandomFloatingGenerator(Float a, Float b) : m_rng(rng()), m_dist(a, b)
5204 {
5205 static_cast<void>(next());
5206 }
5207
5208 Float const &get() const override { return m_current_number; }
5209 bool next() override
5210 {
5211 m_current_number = m_dist(m_rng);
5212 return true;
5213 }
5214 };
5215
5216 template <typename Integer> class RandomIntegerGenerator final : public IGenerator<Integer>
5217 {
5218 Catch::SimplePcg32 &m_rng;
5219 std::uniform_int_distribution<Integer> m_dist;
5220 Integer m_current_number;
5221
5222 public:
5223 RandomIntegerGenerator(Integer a, Integer b) : m_rng(rng()), m_dist(a, b)
5224 {
5225 static_cast<void>(next());
5226 }
5227
5228 Integer const &get() const override { return m_current_number; }
5229 bool next() override
5230 {
5231 m_current_number = m_dist(m_rng);
5232 return true;
5233 }
5234 };
5235
5236 // TODO: Ideally this would be also constrained against the various char types,
5237 // but I don't expect users to run into that in practice.
5238 template <typename T>
5239 typename std::enable_if<std::is_integral<T>::value && !std::is_same<T, bool>::value,
5240 GeneratorWrapper<T>>::type
5241 random(T a, T b)
5242 {
5243 return GeneratorWrapper<T>(pf::make_unique<RandomIntegerGenerator<T>>(a, b));
5244 }
5245
5246 template <typename T>
5247 typename std::enable_if<std::is_floating_point<T>::value, GeneratorWrapper<T>>::type random(T a,
5248 T b)
5249 {
5250 return GeneratorWrapper<T>(pf::make_unique<RandomFloatingGenerator<T>>(a, b));
5251 }
5252
5253 template <typename T> class RangeGenerator final : public IGenerator<T>
5254 {
5255 T m_current;
5256 T m_end;
5257 T m_step;
5258 bool m_positive;
5259
5260 public:
5261 RangeGenerator(T const &start, T const &end, T const &step)
5262 : m_current(start), m_end(end), m_step(step), m_positive(m_step > T(0))
5263 {
5264 assert(m_current != m_end && "Range start and end cannot be equal");
5265 assert(m_step != T(0) && "Step size cannot be zero");
5266 assert(((m_positive && m_current <= m_end) || (!m_positive && m_current >= m_end)) &&
5267 "Step moves away from end");
5268 }
5269
5270 RangeGenerator(T const &start, T const &end)
5271 : RangeGenerator(start, end, (start < end) ? T(1) : T(-1))
5272 {
5273 }
5274
5275 T const &get() const override { return m_current; }
5276
5277 bool next() override
5278 {
5279 m_current += m_step;
5280 return (m_positive) ? (m_current < m_end) : (m_current > m_end);
5281 }
5282 };
5283
5284 template <typename T> GeneratorWrapper<T> range(T const &start, T const &end, T const &step)
5285 {
5286 static_assert(std::is_arithmetic<T>::value && !std::is_same<T, bool>::value,
5287 "Type must be numeric");
5288 return GeneratorWrapper<T>(pf::make_unique<RangeGenerator<T>>(start, end, step));
5289 }
5290
5291 template <typename T> GeneratorWrapper<T> range(T const &start, T const &end)
5292 {
5293 static_assert(std::is_integral<T>::value && !std::is_same<T, bool>::value,
5294 "Type must be an integer");
5295 return GeneratorWrapper<T>(pf::make_unique<RangeGenerator<T>>(start, end));
5296 }
5297
5298 template <typename T> class IteratorGenerator final : public IGenerator<T>
5299 {
5300 static_assert(!std::is_same<T, bool>::value,
5301 "IteratorGenerator currently does not support bools"
5302 "because of std::vector<bool> specialization");
5303
5304 std::vector<T> m_elems;
5305 size_t m_current = 0;
5306
5307 public:
5308 template <typename InputIterator, typename InputSentinel>
5309 IteratorGenerator(InputIterator first, InputSentinel last) : m_elems(first, last)
5310 {
5311 if (m_elems.empty()) {
5312 Catch::throw_exception(GeneratorException("IteratorGenerator received no valid values"));
5313 }
5314 }
5315
5316 T const &get() const override { return m_elems[m_current]; }
5317
5318 bool next() override
5319 {
5320 ++m_current;
5321 return m_current != m_elems.size();
5322 }
5323 };
5324
5325 template <typename InputIterator, typename InputSentinel,
5326 typename ResultType = typename std::iterator_traits<InputIterator>::value_type>
5327 GeneratorWrapper<ResultType> from_range(InputIterator from, InputSentinel to)
5328 {
5329 return GeneratorWrapper<ResultType>(pf::make_unique<IteratorGenerator<ResultType>>(from, to));
5330 }
5331
5332 template <typename Container, typename ResultType = typename Container::value_type>
5333 GeneratorWrapper<ResultType> from_range(Container const &cnt)
5334 {
5335 return GeneratorWrapper<ResultType>(
5336 pf::make_unique<IteratorGenerator<ResultType>>(cnt.begin(), cnt.end()));
5337 }
5338
5339 } // namespace Generators
5340 } // namespace Catch
5341
5342 // end catch_generators_specific.hpp
5343
5344 // These files are included here so the single_include script doesn't put them
5345 // in the conditionally compiled sections
5346 // start catch_test_case_info.h
5347
5348 #include <memory>
5349 #include <string>
5350 #include <vector>
5351
5352 #ifdef __clang__
5353 #pragma clang diagnostic push
5354 #pragma clang diagnostic ignored "-Wpadded"
5355 #endif
5356
5357 namespace Catch {
5358
5359 struct ITestInvoker;
5360
5361 struct TestCaseInfo
5362 {
5363 enum SpecialProperties {
5364 None = 0,
5365 IsHidden = 1 << 1,
5366 ShouldFail = 1 << 2,
5367 MayFail = 1 << 3,
5368 Throws = 1 << 4,
5369 NonPortable = 1 << 5,
5370 Benchmark = 1 << 6
5371 };
5372
5373 TestCaseInfo(std::string const &_name, std::string const &_className,
5374 std::string const &_description, std::vector<std::string> const &_tags,
5375 SourceLineInfo const &_lineInfo);
5376
5377 friend void setTags(TestCaseInfo &testCaseInfo, std::vector<std::string> tags);
5378
5379 bool isHidden() const;
5380 bool throws() const;
5381 bool okToFail() const;
5382 bool expectedToFail() const;
5383
5384 std::string tagsAsString() const;
5385
5386 std::string name;
5387 std::string className;
5388 std::string description;
5389 std::vector<std::string> tags;
5390 std::vector<std::string> lcaseTags;
5391 SourceLineInfo lineInfo;
5392 SpecialProperties properties;
5393 };
5394
5395 class TestCase : public TestCaseInfo
5396 {
5397 public:
5398 TestCase(ITestInvoker *testCase, TestCaseInfo &&info);
5399
5400 TestCase withName(std::string const &_newName) const;
5401
5402 void invoke() const;
5403
5404 TestCaseInfo const &getTestCaseInfo() const;
5405
5406 bool operator==(TestCase const &other) const;
5407 bool operator<(TestCase const &other) const;
5408
5409 private:
5410 std::shared_ptr<ITestInvoker> test;
5411 };
5412
5413 TestCase makeTestCase(ITestInvoker *testCase, std::string const &className,
5414 NameAndTags const &nameAndTags, SourceLineInfo const &lineInfo);
5415 } // namespace Catch
5416
5417 #ifdef __clang__
5418 #pragma clang diagnostic pop
5419 #endif
5420
5421 // end catch_test_case_info.h
5422 // start catch_interfaces_runner.h
5423
5424 namespace Catch {
5425
5426 struct IRunner
5427 {
5428 virtual ~IRunner();
5429 virtual bool aborting() const = 0;
5430 };
5431 } // namespace Catch
5432
5433 // end catch_interfaces_runner.h
5434
5435 #ifdef __OBJC__
5436 // start catch_objc.hpp
5437
5438 #import <objc/runtime.h>
5439
5440 #include <string>
5441
5442 // NB. Any general catch headers included here must be included
5443 // in catch.hpp first to make sure they are included by the single
5444 // header for non obj-usage
5445
5446 ///////////////////////////////////////////////////////////////////////////////
5447 // This protocol is really only here for (self) documenting purposes, since
5448 // all its methods are optional.
5449 @protocol OcFixture
5450
5451 @optional
5452
5453 - (void)setUp;
5454 - (void)tearDown;
5455
5456 @end
5457
5458 namespace Catch {
5459
5460 class OcMethod : public ITestInvoker
5461 {
5462
5463 public:
5464 OcMethod(Class cls, SEL sel) : m_cls(cls), m_sel(sel) {}
5465
5466 virtual void invoke() const
5467 {
5468 id obj = [[m_cls alloc] init];
5469
5470 performOptionalSelector(obj, @selector(setUp));
5471 performOptionalSelector(obj, m_sel);
5472 performOptionalSelector(obj, @selector(tearDown));
5473
5474 arcSafeRelease(obj);
5475 }
5476
5477 private:
5478 virtual ~OcMethod() {}
5479
5480 Class m_cls;
5481 SEL m_sel;
5482 };
5483
5484 namespace Detail {
5485
5486 inline std::string getAnnotation(Class cls, std::string const &annotationName,
5487 std::string const &testCaseName)
5488 {
5489 NSString *selStr = [[NSString alloc]
5490 initWithFormat:@"Catch_%s_%s", annotationName.c_str(), testCaseName.c_str()];
5491 SEL sel = NSSelectorFromString(selStr);
5492 arcSafeRelease(selStr);
5493 id value = performOptionalSelector(cls, sel);
5494 if (value)
5495 return [(NSString *)value UTF8String];
5496 return "";
5497 }
5498 } // namespace Detail
5499
5500 inline std::size_t registerTestMethods()
5501 {
5502 std::size_t noTestMethods = 0;
5503 int noClasses = objc_getClassList(nullptr, 0);
5504
5505 Class *classes = (CATCH_UNSAFE_UNRETAINED Class *)malloc(sizeof(Class) * noClasses);
5506 objc_getClassList(classes, noClasses);
5507
5508 for (int c = 0; c < noClasses; c++) {
5509 Class cls = classes[c];
5510 {
5511 u_int count;
5512 Method *methods = class_copyMethodList(cls, &count);
5513 for (u_int m = 0; m < count; m++) {
5514 SEL selector = method_getName(methods[m]);
5515 std::string methodName = sel_getName(selector);
5516 if (startsWith(methodName, "Catch_TestCase_")) {
5517 std::string testCaseName = methodName.substr(15);
5518 std::string name = Detail::getAnnotation(cls, "Name", testCaseName);
5519 std::string desc = Detail::getAnnotation(cls, "Description", testCaseName);
5520 const char *className = class_getName(cls);
5521
5522 getMutableRegistryHub().registerTest(
5523 makeTestCase(new OcMethod(cls, selector), className,
5524 NameAndTags(name.c_str(), desc.c_str()), SourceLineInfo("", 0)));
5525 noTestMethods++;
5526 }
5527 }
5528 free(methods);
5529 }
5530 }
5531 return noTestMethods;
5532 }
5533
5534 #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
5535
5536 namespace Matchers {
5537 namespace Impl {
5538 namespace NSStringMatchers {
5539
5540 struct StringHolder : MatcherBase<NSString *>
5541 {
5542 StringHolder(NSString *substr) : m_substr([substr copy]) {}
5543 StringHolder(StringHolder const &other) : m_substr([other.m_substr copy]) {}
5544 StringHolder() { arcSafeRelease(m_substr); }
5545
5546 bool match(NSString *str) const override { return false; }
5547
5548 NSString *CATCH_ARC_STRONG m_substr;
5549 };
5550
5551 struct Equals : StringHolder
5552 {
5553 Equals(NSString *substr) : StringHolder(substr) {}
5554
5555 bool match(NSString *str) const override
5556 {
5557 return (str != nil || m_substr == nil) && [str isEqualToString:m_substr];
5558 }
5559
5560 std::string describe() const override
5561 {
5562 return "equals string: " + Catch::Detail::stringify(m_substr);
5563 }
5564 };
5565
5566 struct Contains : StringHolder
5567 {
5568 Contains(NSString *substr) : StringHolder(substr) {}
5569
5570 bool match(NSString *str) const override
5571 {
5572 return (str != nil || m_substr == nil) &&
5573 [str rangeOfString:m_substr].location != NSNotFound;
5574 }
5575
5576 std::string describe() const override
5577 {
5578 return "contains string: " + Catch::Detail::stringify(m_substr);
5579 }
5580 };
5581
5582 struct StartsWith : StringHolder
5583 {
5584 StartsWith(NSString *substr) : StringHolder(substr) {}
5585
5586 bool match(NSString *str) const override
5587 {
5588 return (str != nil || m_substr == nil) && [str rangeOfString:m_substr].location == 0;
5589 }
5590
5591 std::string describe() const override
5592 {
5593 return "starts with: " + Catch::Detail::stringify(m_substr);
5594 }
5595 };
5596 struct EndsWith : StringHolder
5597 {
5598 EndsWith(NSString *substr) : StringHolder(substr) {}
5599
5600 bool match(NSString *str) const override
5601 {
5602 return (str != nil || m_substr == nil) &&
5603 [str rangeOfString:m_substr].location == [str length] - [m_substr length];
5604 }
5605
5606 std::string describe() const override
5607 {
5608 return "ends with: " + Catch::Detail::stringify(m_substr);
5609 }
5610 };
5611
5612 } // namespace NSStringMatchers
5613 } // namespace Impl
5614
5615 inline Impl::NSStringMatchers::Equals Equals(NSString *substr)
5616 {
5617 return Impl::NSStringMatchers::Equals(substr);
5618 }
5619
5620 inline Impl::NSStringMatchers::Contains Contains(NSString *substr)
5621 {
5622 return Impl::NSStringMatchers::Contains(substr);
5623 }
5624
5625 inline Impl::NSStringMatchers::StartsWith StartsWith(NSString *substr)
5626 {
5627 return Impl::NSStringMatchers::StartsWith(substr);
5628 }
5629
5630 inline Impl::NSStringMatchers::EndsWith EndsWith(NSString *substr)
5631 {
5632 return Impl::NSStringMatchers::EndsWith(substr);
5633 }
5634
5635 } // namespace Matchers
5636
5637 using namespace Matchers;
5638
5639 #endif // CATCH_CONFIG_DISABLE_MATCHERS
5640
5641 } // namespace Catch
5642
5643 ///////////////////////////////////////////////////////////////////////////////
5644 #define OC_MAKE_UNIQUE_NAME(root, uniqueSuffix) root##uniqueSuffix
5645 #define OC_TEST_CASE2(name, desc, uniqueSuffix) \
5646 +(NSString *)OC_MAKE_UNIQUE_NAME(Catch_Name_test_, uniqueSuffix) { return @name; } \
5647 +(NSString *)OC_MAKE_UNIQUE_NAME(Catch_Description_test_, uniqueSuffix) { return @desc; } \
5648 -(void)OC_MAKE_UNIQUE_NAME(Catch_TestCase_test_, uniqueSuffix)
5649
5650 #define OC_TEST_CASE(name, desc) OC_TEST_CASE2(name, desc, __LINE__)
5651
5652 // end catch_objc.hpp
5653 #endif
5654
5655 // Benchmarking needs the externally-facing parts of reporters to work
5656 #if defined(CATCH_CONFIG_EXTERNAL_INTERFACES) || defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
5657 // start catch_external_interfaces.h
5658
5659 // start catch_reporter_bases.hpp
5660
5661 // start catch_interfaces_reporter.h
5662
5663 // start catch_config.hpp
5664
5665 // start catch_test_spec_parser.h
5666
5667 #ifdef __clang__
5668 #pragma clang diagnostic push
5669 #pragma clang diagnostic ignored "-Wpadded"
5670 #endif
5671
5672 // start catch_test_spec.h
5673
5674 #ifdef __clang__
5675 #pragma clang diagnostic push
5676 #pragma clang diagnostic ignored "-Wpadded"
5677 #endif
5678
5679 // start catch_wildcard_pattern.h
5680
5681 namespace Catch {
5682 class WildcardPattern
5683 {
5684 enum WildcardPosition {
5685 NoWildcard = 0,
5686 WildcardAtStart = 1,
5687 WildcardAtEnd = 2,
5688 WildcardAtBothEnds = WildcardAtStart | WildcardAtEnd
5689 };
5690
5691 public:
5692 WildcardPattern(std::string const &pattern, CaseSensitive::Choice caseSensitivity);
5693 virtual ~WildcardPattern() = default;
5694 virtual bool matches(std::string const &str) const;
5695
5696 private:
5697 std::string normaliseString(std::string const &str) const;
5698 CaseSensitive::Choice m_caseSensitivity;
5699 WildcardPosition m_wildcard = NoWildcard;
5700 std::string m_pattern;
5701 };
5702 } // namespace Catch
5703
5704 // end catch_wildcard_pattern.h
5705 #include <memory>
5706 #include <string>
5707 #include <vector>
5708
5709 namespace Catch {
5710
5711 struct IConfig;
5712
5713 class TestSpec
5714 {
5715 class Pattern
5716 {
5717 public:
5718 explicit Pattern(std::string const &name);
5719 virtual ~Pattern();
5720 virtual bool matches(TestCaseInfo const &testCase) const = 0;
5721 std::string const &name() const;
5722
5723 private:
5724 std::string const m_name;
5725 };
5726 using PatternPtr = std::shared_ptr<Pattern>;
5727
5728 class NamePattern : public Pattern
5729 {
5730 public:
5731 explicit NamePattern(std::string const &name, std::string const &filterString);
5732 bool matches(TestCaseInfo const &testCase) const override;
5733
5734 private:
5735 WildcardPattern m_wildcardPattern;
5736 };
5737
5738 class TagPattern : public Pattern
5739 {
5740 public:
5741 explicit TagPattern(std::string const &tag, std::string const &filterString);
5742 bool matches(TestCaseInfo const &testCase) const override;
5743
5744 private:
5745 std::string m_tag;
5746 };
5747
5748 class ExcludedPattern : public Pattern
5749 {
5750 public:
5751 explicit ExcludedPattern(PatternPtr const &underlyingPattern);
5752 bool matches(TestCaseInfo const &testCase) const override;
5753
5754 private:
5755 PatternPtr m_underlyingPattern;
5756 };
5757
5758 struct Filter
5759 {
5760 std::vector<PatternPtr> m_patterns;
5761
5762 bool matches(TestCaseInfo const &testCase) const;
5763 std::string name() const;
5764 };
5765
5766 public:
5767 struct FilterMatch
5768 {
5769 std::string name;
5770 std::vector<TestCase const *> tests;
5771 };
5772 using Matches = std::vector<FilterMatch>;
5773 using vectorStrings = std::vector<std::string>;
5774
5775 bool hasFilters() const;
5776 bool matches(TestCaseInfo const &testCase) const;
5777 Matches matchesByFilter(std::vector<TestCase> const &testCases, IConfig const &config) const;
5778 const vectorStrings &getInvalidArgs() const;
5779
5780 private:
5781 std::vector<Filter> m_filters;
5782 std::vector<std::string> m_invalidArgs;
5783 friend class TestSpecParser;
5784 };
5785 } // namespace Catch
5786
5787 #ifdef __clang__
5788 #pragma clang diagnostic pop
5789 #endif
5790
5791 // end catch_test_spec.h
5792 // start catch_interfaces_tag_alias_registry.h
5793
5794 #include <string>
5795
5796 namespace Catch {
5797
5798 struct TagAlias;
5799
5800 struct ITagAliasRegistry
5801 {
5802 virtual ~ITagAliasRegistry();
5803 // Nullptr if not present
5804 virtual TagAlias const *find(std::string const &alias) const = 0;
5805 virtual std::string expandAliases(std::string const &unexpandedTestSpec) const = 0;
5806
5807 static ITagAliasRegistry const &get();
5808 };
5809
5810 } // end namespace Catch
5811
5812 // end catch_interfaces_tag_alias_registry.h
5813 namespace Catch {
5814
5815 class TestSpecParser
5816 {
5817 enum Mode { None, Name, QuotedName, Tag, EscapedName };
5818 Mode m_mode = None;
5819 Mode lastMode = None;
5820 bool m_exclusion = false;
5821 std::size_t m_pos = 0;
5822 std::size_t m_realPatternPos = 0;
5823 std::string m_arg;
5824 std::string m_substring;
5825 std::string m_patternName;
5826 std::vector<std::size_t> m_escapeChars;
5827 TestSpec::Filter m_currentFilter;
5828 TestSpec m_testSpec;
5829 ITagAliasRegistry const *m_tagAliases = nullptr;
5830
5831 public:
5832 TestSpecParser(ITagAliasRegistry const &tagAliases);
5833
5834 TestSpecParser &parse(std::string const &arg);
5835 TestSpec testSpec();
5836
5837 private:
5838 bool visitChar(char c);
5839 void startNewMode(Mode mode);
5840 bool processNoneChar(char c);
5841 void processNameChar(char c);
5842 bool processOtherChar(char c);
5843 void endMode();
5844 void escape();
5845 bool isControlChar(char c) const;
5846 void saveLastMode();
5847 void revertBackToLastMode();
5848 void addFilter();
5849 bool separate();
5850
5851 // Handles common preprocessing of the pattern for name/tag patterns
5852 std::string preprocessPattern();
5853 // Adds the current pattern as a test name
5854 void addNamePattern();
5855 // Adds the current pattern as a tag
5856 void addTagPattern();
5857
5858 inline void addCharToPattern(char c)
5859 {
5860 m_substring += c;
5861 m_patternName += c;
5862 m_realPatternPos++;
5863 }
5864 };
5865 TestSpec parseTestSpec(std::string const &arg);
5866
5867 } // namespace Catch
5868
5869 #ifdef __clang__
5870 #pragma clang diagnostic pop
5871 #endif
5872
5873 // end catch_test_spec_parser.h
5874 // Libstdc++ doesn't like incomplete classes for unique_ptr
5875
5876 #include <memory>
5877 #include <string>
5878 #include <vector>
5879
5880 #ifndef CATCH_CONFIG_CONSOLE_WIDTH
5881 #define CATCH_CONFIG_CONSOLE_WIDTH 80
5882 #endif
5883
5884 namespace Catch {
5885
5886 struct IStream;
5887
5888 struct ConfigData
5889 {
5890 bool listTests = false;
5891 bool listTags = false;
5892 bool listReporters = false;
5893 bool listTestNamesOnly = false;
5894
5895 bool showSuccessfulTests = false;
5896 bool shouldDebugBreak = false;
5897 bool noThrow = false;
5898 bool showHelp = false;
5899 bool showInvisibles = false;
5900 bool filenamesAsTags = false;
5901 bool libIdentify = false;
5902
5903 int abortAfter = -1;
5904 unsigned int rngSeed = 0;
5905
5906 bool benchmarkNoAnalysis = false;
5907 unsigned int benchmarkSamples = 100;
5908 double benchmarkConfidenceInterval = 0.95;
5909 unsigned int benchmarkResamples = 100000;
5910 std::chrono::milliseconds::rep benchmarkWarmupTime = 100;
5911
5912 Verbosity verbosity = Verbosity::Normal;
5913 WarnAbout::What warnings = WarnAbout::Nothing;
5914 ShowDurations::OrNot showDurations = ShowDurations::DefaultForReporter;
5915 double minDuration = -1;
5916 RunTests::InWhatOrder runOrder = RunTests::InDeclarationOrder;
5917 UseColour::YesOrNo useColour = UseColour::Auto;
5918 WaitForKeypress::When waitForKeypress = WaitForKeypress::Never;
5919
5920 std::string outputFilename;
5921 std::string name;
5922 std::string processName;
5923 #ifndef CATCH_CONFIG_DEFAULT_REPORTER
5924 #define CATCH_CONFIG_DEFAULT_REPORTER "console"
5925 #endif
5926 std::string reporterName = CATCH_CONFIG_DEFAULT_REPORTER;
5927 #undef CATCH_CONFIG_DEFAULT_REPORTER
5928
5929 std::vector<std::string> testsOrTags;
5930 std::vector<std::string> sectionsToRun;
5931 };
5932
5933 class Config : public IConfig
5934 {
5935 public:
5936 Config() = default;
5937 Config(ConfigData const &data);
5938 virtual ~Config() = default;
5939
5940 std::string const &getFilename() const;
5941
5942 bool listTests() const;
5943 bool listTestNamesOnly() const;
5944 bool listTags() const;
5945 bool listReporters() const;
5946
5947 std::string getProcessName() const;
5948 std::string const &getReporterName() const;
5949
5950 std::vector<std::string> const &getTestsOrTags() const override;
5951 std::vector<std::string> const &getSectionsToRun() const override;
5952
5953 TestSpec const &testSpec() const override;
5954 bool hasTestFilters() const override;
5955
5956 bool showHelp() const;
5957
5958 // IConfig interface
5959 bool allowThrows() const override;
5960 std::ostream &stream() const override;
5961 std::string name() const override;
5962 bool includeSuccessfulResults() const override;
5963 bool warnAboutMissingAssertions() const override;
5964 bool warnAboutNoTests() const override;
5965 ShowDurations::OrNot showDurations() const override;
5966 double minDuration() const override;
5967 RunTests::InWhatOrder runOrder() const override;
5968 unsigned int rngSeed() const override;
5969 UseColour::YesOrNo useColour() const override;
5970 bool shouldDebugBreak() const override;
5971 int abortAfter() const override;
5972 bool showInvisibles() const override;
5973 Verbosity verbosity() const override;
5974 bool benchmarkNoAnalysis() const override;
5975 int benchmarkSamples() const override;
5976 double benchmarkConfidenceInterval() const override;
5977 unsigned int benchmarkResamples() const override;
5978 std::chrono::milliseconds benchmarkWarmupTime() const override;
5979
5980 private:
5981 IStream const *openStream();
5982 ConfigData m_data;
5983
5984 std::unique_ptr<IStream const> m_stream;
5985 TestSpec m_testSpec;
5986 bool m_hasTestFilters = false;
5987 };
5988
5989 } // end namespace Catch
5990
5991 // end catch_config.hpp
5992 // start catch_assertionresult.h
5993
5994 #include <string>
5995
5996 namespace Catch {
5997
5998 struct AssertionResultData
5999 {
6000 AssertionResultData() = delete;
6001
6002 AssertionResultData(ResultWas::OfType _resultType, LazyExpression const &_lazyExpression);
6003
6004 std::string message;
6005 mutable std::string reconstructedExpression;
6006 LazyExpression lazyExpression;
6007 ResultWas::OfType resultType;
6008
6009 std::string reconstructExpression() const;
6010 };
6011
6012 class AssertionResult
6013 {
6014 public:
6015 AssertionResult() = delete;
6016 AssertionResult(AssertionInfo const &info, AssertionResultData const &data);
6017
6018 bool isOk() const;
6019 bool succeeded() const;
6020 ResultWas::OfType getResultType() const;
6021 bool hasExpression() const;
6022 bool hasMessage() const;
6023 std::string getExpression() const;
6024 std::string getExpressionInMacro() const;
6025 bool hasExpandedExpression() const;
6026 std::string getExpandedExpression() const;
6027 std::string getMessage() const;
6028 SourceLineInfo getSourceInfo() const;
6029 StringRef getTestMacroName() const;
6030
6031 // protected:
6032 AssertionInfo m_info;
6033 AssertionResultData m_resultData;
6034 };
6035
6036 } // end namespace Catch
6037
6038 // end catch_assertionresult.h
6039 #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
6040 // start catch_estimate.hpp
6041
6042 // Statistics estimates
6043
6044 namespace Catch {
6045 namespace Benchmark {
6046 template <typename Duration> struct Estimate
6047 {
6048 Duration point;
6049 Duration lower_bound;
6050 Duration upper_bound;
6051 double confidence_interval;
6052
6053 template <typename Duration2> operator Estimate<Duration2>() const
6054 {
6055 return {point, lower_bound, upper_bound, confidence_interval};
6056 }
6057 };
6058 } // namespace Benchmark
6059 } // namespace Catch
6060
6061 // end catch_estimate.hpp
6062 // start catch_outlier_classification.hpp
6063
6064 // Outlier information
6065
6066 namespace Catch {
6067 namespace Benchmark {
6068 struct OutlierClassification
6069 {
6070 int samples_seen = 0;
6071 int low_severe = 0; // more than 3 times IQR below Q1
6072 int low_mild = 0; // 1.5 to 3 times IQR below Q1
6073 int high_mild = 0; // 1.5 to 3 times IQR above Q3
6074 int high_severe = 0; // more than 3 times IQR above Q3
6075
6076 int total() const { return low_severe + low_mild + high_mild + high_severe; }
6077 };
6078 } // namespace Benchmark
6079 } // namespace Catch
6080
6081 // end catch_outlier_classification.hpp
6082 #endif // CATCH_CONFIG_ENABLE_BENCHMARKING
6083
6084 #include <algorithm>
6085 #include <iosfwd>
6086 #include <map>
6087 #include <memory>
6088 #include <set>
6089 #include <string>
6090
6091 namespace Catch {
6092
6093 struct ReporterConfig
6094 {
6095 explicit ReporterConfig(IConfigPtr const &_fullConfig);
6096
6097 ReporterConfig(IConfigPtr const &_fullConfig, std::ostream &_stream);
6098
6099 std::ostream &stream() const;
6100 IConfigPtr fullConfig() const;
6101
6102 private:
6103 std::ostream *m_stream;
6104 IConfigPtr m_fullConfig;
6105 };
6106
6107 struct ReporterPreferences
6108 {
6109 bool shouldRedirectStdOut = false;
6110 bool shouldReportAllAssertions = false;
6111 };
6112
6113 template <typename T> struct LazyStat : Option<T>
6114 {
6115 LazyStat &operator=(T const &_value)
6116 {
6117 Option<T>::operator=(_value);
6118 used = false;
6119 return *this;
6120 }
6121 void reset()
6122 {
6123 Option<T>::reset();
6124 used = false;
6125 }
6126 bool used = false;
6127 };
6128
6129 struct TestRunInfo
6130 {
6131 TestRunInfo(std::string const &_name);
6132 std::string name;
6133 };
6134 struct GroupInfo
6135 {
6136 GroupInfo(std::string const &_name, std::size_t _groupIndex, std::size_t _groupsCount);
6137
6138 std::string name;
6139 std::size_t groupIndex;
6140 std::size_t groupsCounts;
6141 };
6142
6143 struct AssertionStats
6144 {
6145 AssertionStats(AssertionResult const &_assertionResult,
6146 std::vector<MessageInfo> const &_infoMessages, Totals const &_totals);
6147
6148 AssertionStats(AssertionStats const &) = default;
6149 AssertionStats(AssertionStats &&) = default;
6150 AssertionStats &operator=(AssertionStats const &) = delete;
6151 AssertionStats &operator=(AssertionStats &&) = delete;
6152 virtual ~AssertionStats();
6153
6154 AssertionResult assertionResult;
6155 std::vector<MessageInfo> infoMessages;
6156 Totals totals;
6157 };
6158
6159 struct SectionStats
6160 {
6161 SectionStats(SectionInfo const &_sectionInfo, Counts const &_assertions,
6162 double _durationInSeconds, bool _missingAssertions);
6163 SectionStats(SectionStats const &) = default;
6164 SectionStats(SectionStats &&) = default;
6165 SectionStats &operator=(SectionStats const &) = default;
6166 SectionStats &operator=(SectionStats &&) = default;
6167 virtual ~SectionStats();
6168
6169 SectionInfo sectionInfo;
6170 Counts assertions;
6171 double durationInSeconds;
6172 bool missingAssertions;
6173 };
6174
6175 struct TestCaseStats
6176 {
6177 TestCaseStats(TestCaseInfo const &_testInfo, Totals const &_totals, std::string const &_stdOut,
6178 std::string const &_stdErr, bool _aborting);
6179
6180 TestCaseStats(TestCaseStats const &) = default;
6181 TestCaseStats(TestCaseStats &&) = default;
6182 TestCaseStats &operator=(TestCaseStats const &) = default;
6183 TestCaseStats &operator=(TestCaseStats &&) = default;
6184 virtual ~TestCaseStats();
6185
6186 TestCaseInfo testInfo;
6187 Totals totals;
6188 std::string stdOut;
6189 std::string stdErr;
6190 bool aborting;
6191 };
6192
6193 struct TestGroupStats
6194 {
6195 TestGroupStats(GroupInfo const &_groupInfo, Totals const &_totals, bool _aborting);
6196 TestGroupStats(GroupInfo const &_groupInfo);
6197
6198 TestGroupStats(TestGroupStats const &) = default;
6199 TestGroupStats(TestGroupStats &&) = default;
6200 TestGroupStats &operator=(TestGroupStats const &) = default;
6201 TestGroupStats &operator=(TestGroupStats &&) = default;
6202 virtual ~TestGroupStats();
6203
6204 GroupInfo groupInfo;
6205 Totals totals;
6206 bool aborting;
6207 };
6208
6209 struct TestRunStats
6210 {
6211 TestRunStats(TestRunInfo const &_runInfo, Totals const &_totals, bool _aborting);
6212
6213 TestRunStats(TestRunStats const &) = default;
6214 TestRunStats(TestRunStats &&) = default;
6215 TestRunStats &operator=(TestRunStats const &) = default;
6216 TestRunStats &operator=(TestRunStats &&) = default;
6217 virtual ~TestRunStats();
6218
6219 TestRunInfo runInfo;
6220 Totals totals;
6221 bool aborting;
6222 };
6223
6224 #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
6225 struct BenchmarkInfo
6226 {
6227 std::string name;
6228 double estimatedDuration;
6229 int iterations;
6230 int samples;
6231 unsigned int resamples;
6232 double clockResolution;
6233 double clockCost;
6234 };
6235
6236 template <class Duration> struct BenchmarkStats
6237 {
6238 BenchmarkInfo info;
6239
6240 std::vector<Duration> samples;
6241 Benchmark::Estimate<Duration> mean;
6242 Benchmark::Estimate<Duration> standardDeviation;
6243 Benchmark::OutlierClassification outliers;
6244 double outlierVariance;
6245
6246 template <typename Duration2> operator BenchmarkStats<Duration2>() const
6247 {
6248 std::vector<Duration2> samples2;
6249 samples2.reserve(samples.size());
6250 std::transform(samples.begin(), samples.end(), std::back_inserter(samples2),
6251 [](Duration d) { return Duration2(d); });
6252 return {
6253 info, std::move(samples2), mean, standardDeviation, outliers, outlierVariance,
6254 };
6255 }
6256 };
6257 #endif // CATCH_CONFIG_ENABLE_BENCHMARKING
6258
6259 struct IStreamingReporter
6260 {
6261 virtual ~IStreamingReporter() = default;
6262
6263 // Implementing class must also provide the following static methods:
6264 // static std::string getDescription();
6265 // static std::set<Verbosity> getSupportedVerbosities()
6266
6267 virtual ReporterPreferences getPreferences() const = 0;
6268
6269 virtual void noMatchingTestCases(std::string const &spec) = 0;
6270
6271 virtual void reportInvalidArguments(std::string const &) {}
6272
6273 virtual void testRunStarting(TestRunInfo const &testRunInfo) = 0;
6274 virtual void testGroupStarting(GroupInfo const &groupInfo) = 0;
6275
6276 virtual void testCaseStarting(TestCaseInfo const &testInfo) = 0;
6277 virtual void sectionStarting(SectionInfo const &sectionInfo) = 0;
6278
6279 #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
6280 virtual void benchmarkPreparing(std::string const &) {}
6281 virtual void benchmarkStarting(BenchmarkInfo const &) {}
6282 virtual void benchmarkEnded(BenchmarkStats<> const &) {}
6283 virtual void benchmarkFailed(std::string const &) {}
6284 #endif // CATCH_CONFIG_ENABLE_BENCHMARKING
6285
6286 virtual void assertionStarting(AssertionInfo const &assertionInfo) = 0;
6287
6288 // The return value indicates if the messages buffer should be cleared:
6289 virtual bool assertionEnded(AssertionStats const &assertionStats) = 0;
6290
6291 virtual void sectionEnded(SectionStats const &sectionStats) = 0;
6292 virtual void testCaseEnded(TestCaseStats const &testCaseStats) = 0;
6293 virtual void testGroupEnded(TestGroupStats const &testGroupStats) = 0;
6294 virtual void testRunEnded(TestRunStats const &testRunStats) = 0;
6295
6296 virtual void skipTest(TestCaseInfo const &testInfo) = 0;
6297
6298 // Default empty implementation provided
6299 virtual void fatalErrorEncountered(StringRef name);
6300
6301 virtual bool isMulti() const;
6302 };
6303 using IStreamingReporterPtr = std::unique_ptr<IStreamingReporter>;
6304
6305 struct IReporterFactory
6306 {
6307 virtual ~IReporterFactory();
6308 virtual IStreamingReporterPtr create(ReporterConfig const &config) const = 0;
6309 virtual std::string getDescription() const = 0;
6310 };
6311 using IReporterFactoryPtr = std::shared_ptr<IReporterFactory>;
6312
6313 struct IReporterRegistry
6314 {
6315 using FactoryMap = std::map<std::string, IReporterFactoryPtr>;
6316 using Listeners = std::vector<IReporterFactoryPtr>;
6317
6318 virtual ~IReporterRegistry();
6319 virtual IStreamingReporterPtr create(std::string const &name,
6320 IConfigPtr const &config) const = 0;
6321 virtual FactoryMap const &getFactories() const = 0;
6322 virtual Listeners const &getListeners() const = 0;
6323 };
6324
6325 } // end namespace Catch
6326
6327 // end catch_interfaces_reporter.h
6328 #include <algorithm>
6329 #include <cassert>
6330 #include <cfloat>
6331 #include <cstdio>
6332 #include <cstring>
6333 #include <memory>
6334 #include <ostream>
6335
6336 namespace Catch {
6337 void prepareExpandedExpression(AssertionResult &result);
6338
6339 // Returns double formatted as %.3f (format expected on output)
6340 std::string getFormattedDuration(double duration);
6341
6342 //! Should the reporter show
6343 bool shouldShowDuration(IConfig const &config, double duration);
6344
6345 std::string serializeFilters(std::vector<std::string> const &container);
6346
6347 template <typename DerivedT> struct StreamingReporterBase : IStreamingReporter
6348 {
6349
6350 StreamingReporterBase(ReporterConfig const &_config)
6351 : m_config(_config.fullConfig()), stream(_config.stream())
6352 {
6353 m_reporterPrefs.shouldRedirectStdOut = false;
6354 if (!DerivedT::getSupportedVerbosities().count(m_config->verbosity()))
6355 CATCH_ERROR("Verbosity level not supported by this reporter");
6356 }
6357
6358 ReporterPreferences getPreferences() const override { return m_reporterPrefs; }
6359
6360 static std::set<Verbosity> getSupportedVerbosities() { return {Verbosity::Normal}; }
6361
6362 ~StreamingReporterBase() override = default;
6363
6364 void noMatchingTestCases(std::string const &) override {}
6365
6366 void reportInvalidArguments(std::string const &) override {}
6367
6368 void testRunStarting(TestRunInfo const &_testRunInfo) override
6369 {
6370 currentTestRunInfo = _testRunInfo;
6371 }
6372
6373 void testGroupStarting(GroupInfo const &_groupInfo) override { currentGroupInfo = _groupInfo; }
6374
6375 void testCaseStarting(TestCaseInfo const &_testInfo) override
6376 {
6377 currentTestCaseInfo = _testInfo;
6378 }
6379 void sectionStarting(SectionInfo const &_sectionInfo) override
6380 {
6381 m_sectionStack.push_back(_sectionInfo);
6382 }
6383
6384 void sectionEnded(SectionStats const & /* _sectionStats */) override
6385 {
6386 m_sectionStack.pop_back();
6387 }
6388 void testCaseEnded(TestCaseStats const & /* _testCaseStats */) override
6389 {
6390 currentTestCaseInfo.reset();
6391 }
6392 void testGroupEnded(TestGroupStats const & /* _testGroupStats */) override
6393 {
6394 currentGroupInfo.reset();
6395 }
6396 void testRunEnded(TestRunStats const & /* _testRunStats */) override
6397 {
6398 currentTestCaseInfo.reset();
6399 currentGroupInfo.reset();
6400 currentTestRunInfo.reset();
6401 }
6402
6403 void skipTest(TestCaseInfo const &) override
6404 {
6405 // Don't do anything with this by default.
6406 // It can optionally be overridden in the derived class.
6407 }
6408
6409 IConfigPtr m_config;
6410 std::ostream &stream;
6411
6412 LazyStat<TestRunInfo> currentTestRunInfo;
6413 LazyStat<GroupInfo> currentGroupInfo;
6414 LazyStat<TestCaseInfo> currentTestCaseInfo;
6415
6416 std::vector<SectionInfo> m_sectionStack;
6417 ReporterPreferences m_reporterPrefs;
6418 };
6419
6420 template <typename DerivedT> struct CumulativeReporterBase : IStreamingReporter
6421 {
6422 template <typename T, typename ChildNodeT> struct Node
6423 {
6424 explicit Node(T const &_value) : value(_value) {}
6425 virtual ~Node() {}
6426
6427 using ChildNodes = std::vector<std::shared_ptr<ChildNodeT>>;
6428 T value;
6429 ChildNodes children;
6430 };
6431 struct SectionNode
6432 {
6433 explicit SectionNode(SectionStats const &_stats) : stats(_stats) {}
6434 virtual ~SectionNode() = default;
6435
6436 bool operator==(SectionNode const &other) const
6437 {
6438 return stats.sectionInfo.lineInfo == other.stats.sectionInfo.lineInfo;
6439 }
6440 bool operator==(std::shared_ptr<SectionNode> const &other) const
6441 {
6442 return operator==(*other);
6443 }
6444
6445 SectionStats stats;
6446 using ChildSections = std::vector<std::shared_ptr<SectionNode>>;
6447 using Assertions = std::vector<AssertionStats>;
6448 ChildSections childSections;
6449 Assertions assertions;
6450 std::string stdOut;
6451 std::string stdErr;
6452 };
6453
6454 struct BySectionInfo
6455 {
6456 BySectionInfo(SectionInfo const &other) : m_other(other) {}
6457 BySectionInfo(BySectionInfo const &other) : m_other(other.m_other) {}
6458 bool operator()(std::shared_ptr<SectionNode> const &node) const
6459 {
6460 return ((node->stats.sectionInfo.name == m_other.name) &&
6461 (node->stats.sectionInfo.lineInfo == m_other.lineInfo));
6462 }
6463 void operator=(BySectionInfo const &) = delete;
6464
6465 private:
6466 SectionInfo const &m_other;
6467 };
6468
6469 using TestCaseNode = Node<TestCaseStats, SectionNode>;
6470 using TestGroupNode = Node<TestGroupStats, TestCaseNode>;
6471 using TestRunNode = Node<TestRunStats, TestGroupNode>;
6472
6473 CumulativeReporterBase(ReporterConfig const &_config)
6474 : m_config(_config.fullConfig()), stream(_config.stream())
6475 {
6476 m_reporterPrefs.shouldRedirectStdOut = false;
6477 if (!DerivedT::getSupportedVerbosities().count(m_config->verbosity()))
6478 CATCH_ERROR("Verbosity level not supported by this reporter");
6479 }
6480 ~CumulativeReporterBase() override = default;
6481
6482 ReporterPreferences getPreferences() const override { return m_reporterPrefs; }
6483
6484 static std::set<Verbosity> getSupportedVerbosities() { return {Verbosity::Normal}; }
6485
6486 void testRunStarting(TestRunInfo const &) override {}
6487 void testGroupStarting(GroupInfo const &) override {}
6488
6489 void testCaseStarting(TestCaseInfo const &) override {}
6490
6491 void sectionStarting(SectionInfo const &sectionInfo) override
6492 {
6493 SectionStats incompleteStats(sectionInfo, Counts(), 0, false);
6494 std::shared_ptr<SectionNode> node;
6495 if (m_sectionStack.empty()) {
6496 if (!m_rootSection)
6497 m_rootSection = std::make_shared<SectionNode>(incompleteStats);
6498 node = m_rootSection;
6499 }
6500 else {
6501 SectionNode &parentNode = *m_sectionStack.back();
6502 auto it = std::find_if(parentNode.childSections.begin(), parentNode.childSections.end(),
6503 BySectionInfo(sectionInfo));
6504 if (it == parentNode.childSections.end()) {
6505 node = std::make_shared<SectionNode>(incompleteStats);
6506 parentNode.childSections.push_back(node);
6507 }
6508 else
6509 node = *it;
6510 }
6511 m_sectionStack.push_back(node);
6512 m_deepestSection = std::move(node);
6513 }
6514
6515 void assertionStarting(AssertionInfo const &) override {}
6516
6517 bool assertionEnded(AssertionStats const &assertionStats) override
6518 {
6519 assert(!m_sectionStack.empty());
6520 // AssertionResult holds a pointer to a temporary DecomposedExpression,
6521 // which getExpandedExpression() calls to build the expression string.
6522 // Our section stack copy of the assertionResult will likely outlive the
6523 // temporary, so it must be expanded or discarded now to avoid calling
6524 // a destroyed object later.
6525 prepareExpandedExpression(const_cast<AssertionResult &>(assertionStats.assertionResult));
6526 SectionNode &sectionNode = *m_sectionStack.back();
6527 sectionNode.assertions.push_back(assertionStats);
6528 return true;
6529 }
6530 void sectionEnded(SectionStats const &sectionStats) override
6531 {
6532 assert(!m_sectionStack.empty());
6533 SectionNode &node = *m_sectionStack.back();
6534 node.stats = sectionStats;
6535 m_sectionStack.pop_back();
6536 }
6537 void testCaseEnded(TestCaseStats const &testCaseStats) override
6538 {
6539 auto node = std::make_shared<TestCaseNode>(testCaseStats);
6540 assert(m_sectionStack.size() == 0);
6541 node->children.push_back(m_rootSection);
6542 m_testCases.push_back(node);
6543 m_rootSection.reset();
6544
6545 assert(m_deepestSection);
6546 m_deepestSection->stdOut = testCaseStats.stdOut;
6547 m_deepestSection->stdErr = testCaseStats.stdErr;
6548 }
6549 void testGroupEnded(TestGroupStats const &testGroupStats) override
6550 {
6551 auto node = std::make_shared<TestGroupNode>(testGroupStats);
6552 node->children.swap(m_testCases);
6553 m_testGroups.push_back(node);
6554 }
6555 void testRunEnded(TestRunStats const &testRunStats) override
6556 {
6557 auto node = std::make_shared<TestRunNode>(testRunStats);
6558 node->children.swap(m_testGroups);
6559 m_testRuns.push_back(node);
6560 testRunEndedCumulative();
6561 }
6562 virtual void testRunEndedCumulative() = 0;
6563
6564 void skipTest(TestCaseInfo const &) override {}
6565
6566 IConfigPtr m_config;
6567 std::ostream &stream;
6568 std::vector<AssertionStats> m_assertions;
6569 std::vector<std::vector<std::shared_ptr<SectionNode>>> m_sections;
6570 std::vector<std::shared_ptr<TestCaseNode>> m_testCases;
6571 std::vector<std::shared_ptr<TestGroupNode>> m_testGroups;
6572
6573 std::vector<std::shared_ptr<TestRunNode>> m_testRuns;
6574
6575 std::shared_ptr<SectionNode> m_rootSection;
6576 std::shared_ptr<SectionNode> m_deepestSection;
6577 std::vector<std::shared_ptr<SectionNode>> m_sectionStack;
6578 ReporterPreferences m_reporterPrefs;
6579 };
6580
6581 template <char C> char const *getLineOfChars()
6582 {
6583 static char line[CATCH_CONFIG_CONSOLE_WIDTH] = {0};
6584 if (!*line) {
6585 std::memset(line, C, CATCH_CONFIG_CONSOLE_WIDTH - 1);
6586 line[CATCH_CONFIG_CONSOLE_WIDTH - 1] = 0;
6587 }
6588 return line;
6589 }
6590
6591 struct TestEventListenerBase : StreamingReporterBase<TestEventListenerBase>
6592 {
6593 TestEventListenerBase(ReporterConfig const &_config);
6594
6595 static std::set<Verbosity> getSupportedVerbosities();
6596
6597 void assertionStarting(AssertionInfo const &) override;
6598 bool assertionEnded(AssertionStats const &) override;
6599 };
6600
6601 } // end namespace Catch
6602
6603 // end catch_reporter_bases.hpp
6604 // start catch_console_colour.h
6605
6606 namespace Catch {
6607
6608 struct Colour
6609 {
6610 enum Code {
6611 None = 0,
6612
6613 White,
6614 Red,
6615 Green,
6616 Blue,
6617 Cyan,
6618 Yellow,
6619 Grey,
6620
6621 Bright = 0x10,
6622
6623 BrightRed = Bright | Red,
6624 BrightGreen = Bright | Green,
6625 LightGrey = Bright | Grey,
6626 BrightWhite = Bright | White,
6627 BrightYellow = Bright | Yellow,
6628
6629 // By intention
6630 FileName = LightGrey,
6631 Warning = BrightYellow,
6632 ResultError = BrightRed,
6633 ResultSuccess = BrightGreen,
6634 ResultExpectedFailure = Warning,
6635
6636 Error = BrightRed,
6637 Success = Green,
6638
6639 OriginalExpression = Cyan,
6640 ReconstructedExpression = BrightYellow,
6641
6642 SecondaryText = LightGrey,
6643 Headers = White
6644 };
6645
6646 // Use constructed object for RAII guard
6647 Colour(Code _colourCode);
6648 Colour(Colour &&other) noexcept;
6649 Colour &operator=(Colour &&other) noexcept;
6650 ~Colour();
6651
6652 // Use static method for one-shot changes
6653 static void use(Code _colourCode);
6654
6655 private:
6656 bool m_moved = false;
6657 };
6658
6659 std::ostream &operator<<(std::ostream &os, Colour const &);
6660
6661 } // end namespace Catch
6662
6663 // end catch_console_colour.h
6664 // start catch_reporter_registrars.hpp
6665
6666 namespace Catch {
6667
6668 template <typename T> class ReporterRegistrar
6669 {
6670
6671 class ReporterFactory : public IReporterFactory
6672 {
6673
6674 IStreamingReporterPtr create(ReporterConfig const &config) const override
6675 {
6676 return std::unique_ptr<T>(new T(config));
6677 }
6678
6679 std::string getDescription() const override { return T::getDescription(); }
6680 };
6681
6682 public:
6683 explicit ReporterRegistrar(std::string const &name)
6684 {
6685 getMutableRegistryHub().registerReporter(name, std::make_shared<ReporterFactory>());
6686 }
6687 };
6688
6689 template <typename T> class ListenerRegistrar
6690 {
6691
6692 class ListenerFactory : public IReporterFactory
6693 {
6694
6695 IStreamingReporterPtr create(ReporterConfig const &config) const override
6696 {
6697 return std::unique_ptr<T>(new T(config));
6698 }
6699 std::string getDescription() const override { return std::string(); }
6700 };
6701
6702 public:
6703 ListenerRegistrar()
6704 {
6705 getMutableRegistryHub().registerListener(std::make_shared<ListenerFactory>());
6706 }
6707 };
6708 } // namespace Catch
6709
6710 #if !defined(CATCH_CONFIG_DISABLE)
6711
6712 #define CATCH_REGISTER_REPORTER(name, reporterType) \
6713 CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \
6714 CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
6715 namespace { \
6716 Catch::ReporterRegistrar<reporterType> catch_internal_RegistrarFor##reporterType(name); \
6717 } \
6718 CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION
6719
6720 #define CATCH_REGISTER_LISTENER(listenerType) \
6721 CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \
6722 CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
6723 namespace { \
6724 Catch::ListenerRegistrar<listenerType> catch_internal_RegistrarFor##listenerType; \
6725 } \
6726 CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION
6727 #else // CATCH_CONFIG_DISABLE
6728
6729 #define CATCH_REGISTER_REPORTER(name, reporterType)
6730 #define CATCH_REGISTER_LISTENER(listenerType)
6731
6732 #endif // CATCH_CONFIG_DISABLE
6733
6734 // end catch_reporter_registrars.hpp
6735 // Allow users to base their work off existing reporters
6736 // start catch_reporter_compact.h
6737
6738 namespace Catch {
6739
6740 struct CompactReporter : StreamingReporterBase<CompactReporter>
6741 {
6742
6743 using StreamingReporterBase::StreamingReporterBase;
6744
6745 ~CompactReporter() override;
6746
6747 static std::string getDescription();
6748
6749 void noMatchingTestCases(std::string const &spec) override;
6750
6751 void assertionStarting(AssertionInfo const &) override;
6752
6753 bool assertionEnded(AssertionStats const &_assertionStats) override;
6754
6755 void sectionEnded(SectionStats const &_sectionStats) override;
6756
6757 void testRunEnded(TestRunStats const &_testRunStats) override;
6758 };
6759
6760 } // end namespace Catch
6761
6762 // end catch_reporter_compact.h
6763 // start catch_reporter_console.h
6764
6765 #if defined(_MSC_VER)
6766 #pragma warning(push)
6767 #pragma warning(disable : 4061) // Not all labels are EXPLICITLY handled in switch
6768 // Note that 4062 (not all labels are handled
6769 // and default is missing) is enabled
6770 #endif
6771
6772 namespace Catch {
6773 // Fwd decls
6774 struct SummaryColumn;
6775 class TablePrinter;
6776
6777 struct ConsoleReporter : StreamingReporterBase<ConsoleReporter>
6778 {
6779 std::unique_ptr<TablePrinter> m_tablePrinter;
6780
6781 ConsoleReporter(ReporterConfig const &config);
6782 ~ConsoleReporter() override;
6783 static std::string getDescription();
6784
6785 void noMatchingTestCases(std::string const &spec) override;
6786
6787 void reportInvalidArguments(std::string const &arg) override;
6788
6789 void assertionStarting(AssertionInfo const &) override;
6790
6791 bool assertionEnded(AssertionStats const &_assertionStats) override;
6792
6793 void sectionStarting(SectionInfo const &_sectionInfo) override;
6794 void sectionEnded(SectionStats const &_sectionStats) override;
6795
6796 #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
6797 void benchmarkPreparing(std::string const &name) override;
6798 void benchmarkStarting(BenchmarkInfo const &info) override;
6799 void benchmarkEnded(BenchmarkStats<> const &stats) override;
6800 void benchmarkFailed(std::string const &error) override;
6801 #endif // CATCH_CONFIG_ENABLE_BENCHMARKING
6802
6803 void testCaseEnded(TestCaseStats const &_testCaseStats) override;
6804 void testGroupEnded(TestGroupStats const &_testGroupStats) override;
6805 void testRunEnded(TestRunStats const &_testRunStats) override;
6806 void testRunStarting(TestRunInfo const &_testRunInfo) override;
6807
6808 private:
6809 void lazyPrint();
6810
6811 void lazyPrintWithoutClosingBenchmarkTable();
6812 void lazyPrintRunInfo();
6813 void lazyPrintGroupInfo();
6814 void printTestCaseAndSectionHeader();
6815
6816 void printClosedHeader(std::string const &_name);
6817 void printOpenHeader(std::string const &_name);
6818
6819 // if string has a : in first line will set indent to follow it on
6820 // subsequent lines
6821 void printHeaderString(std::string const &_string, std::size_t indent = 0);
6822
6823 void printTotals(Totals const &totals);
6824 void printSummaryRow(std::string const &label, std::vector<SummaryColumn> const &cols,
6825 std::size_t row);
6826
6827 void printTotalsDivider(Totals const &totals);
6828 void printSummaryDivider();
6829 void printTestFilters();
6830
6831 private:
6832 bool m_headerPrinted = false;
6833 };
6834
6835 } // end namespace Catch
6836
6837 #if defined(_MSC_VER)
6838 #pragma warning(pop)
6839 #endif
6840
6841 // end catch_reporter_console.h
6842 // start catch_reporter_junit.h
6843
6844 // start catch_xmlwriter.h
6845
6846 #include <vector>
6847
6848 namespace Catch {
6849 enum class XmlFormatting {
6850 None = 0x00,
6851 Indent = 0x01,
6852 Newline = 0x02,
6853 };
6854
6855 XmlFormatting operator|(XmlFormatting lhs, XmlFormatting rhs);
6856 XmlFormatting operator&(XmlFormatting lhs, XmlFormatting rhs);
6857
6858 class XmlEncode
6859 {
6860 public:
6861 enum ForWhat { ForTextNodes, ForAttributes };
6862
6863 XmlEncode(std::string const &str, ForWhat forWhat = ForTextNodes);
6864
6865 void encodeTo(std::ostream &os) const;
6866
6867 friend std::ostream &operator<<(std::ostream &os, XmlEncode const &xmlEncode);
6868
6869 private:
6870 std::string m_str;
6871 ForWhat m_forWhat;
6872 };
6873
6874 class XmlWriter
6875 {
6876 public:
6877 class ScopedElement
6878 {
6879 public:
6880 ScopedElement(XmlWriter *writer, XmlFormatting fmt);
6881
6882 ScopedElement(ScopedElement &&other) noexcept;
6883 ScopedElement &operator=(ScopedElement &&other) noexcept;
6884
6885 ~ScopedElement();
6886
6887 ScopedElement &writeText(std::string const &text,
6888 XmlFormatting fmt = XmlFormatting::Newline | XmlFormatting::Indent);
6889
6890 template <typename T>
6891 ScopedElement &writeAttribute(std::string const &name, T const &attribute)
6892 {
6893 m_writer->writeAttribute(name, attribute);
6894 return *this;
6895 }
6896
6897 private:
6898 mutable XmlWriter *m_writer = nullptr;
6899 XmlFormatting m_fmt;
6900 };
6901
6902 XmlWriter(std::ostream &os = Catch::cout());
6903 ~XmlWriter();
6904
6905 XmlWriter(XmlWriter const &) = delete;
6906 XmlWriter &operator=(XmlWriter const &) = delete;
6907
6908 XmlWriter &startElement(std::string const &name,
6909 XmlFormatting fmt = XmlFormatting::Newline | XmlFormatting::Indent);
6910
6911 ScopedElement scopedElement(std::string const &name,
6912 XmlFormatting fmt = XmlFormatting::Newline | XmlFormatting::Indent);
6913
6914 XmlWriter &endElement(XmlFormatting fmt = XmlFormatting::Newline | XmlFormatting::Indent);
6915
6916 XmlWriter &writeAttribute(std::string const &name, std::string const &attribute);
6917
6918 XmlWriter &writeAttribute(std::string const &name, bool attribute);
6919
6920 template <typename T> XmlWriter &writeAttribute(std::string const &name, T const &attribute)
6921 {
6922 ReusableStringStream rss;
6923 rss << attribute;
6924 return writeAttribute(name, rss.str());
6925 }
6926
6927 XmlWriter &writeText(std::string const &text,
6928 XmlFormatting fmt = XmlFormatting::Newline | XmlFormatting::Indent);
6929
6930 XmlWriter &writeComment(std::string const &text,
6931 XmlFormatting fmt = XmlFormatting::Newline | XmlFormatting::Indent);
6932
6933 void writeStylesheetRef(std::string const &url);
6934
6935 XmlWriter &writeBlankLine();
6936
6937 void ensureTagClosed();
6938
6939 private:
6940 void applyFormatting(XmlFormatting fmt);
6941
6942 void writeDeclaration();
6943
6944 void newlineIfNecessary();
6945
6946 bool m_tagIsOpen = false;
6947 bool m_needsNewline = false;
6948 std::vector<std::string> m_tags;
6949 std::string m_indent;
6950 std::ostream &m_os;
6951 };
6952
6953 } // namespace Catch
6954
6955 // end catch_xmlwriter.h
6956 namespace Catch {
6957
6958 class JunitReporter : public CumulativeReporterBase<JunitReporter>
6959 {
6960 public:
6961 JunitReporter(ReporterConfig const &_config);
6962
6963 ~JunitReporter() override;
6964
6965 static std::string getDescription();
6966
6967 void noMatchingTestCases(std::string const & /*spec*/) override;
6968
6969 void testRunStarting(TestRunInfo const &runInfo) override;
6970
6971 void testGroupStarting(GroupInfo const &groupInfo) override;
6972
6973 void testCaseStarting(TestCaseInfo const &testCaseInfo) override;
6974 bool assertionEnded(AssertionStats const &assertionStats) override;
6975
6976 void testCaseEnded(TestCaseStats const &testCaseStats) override;
6977
6978 void testGroupEnded(TestGroupStats const &testGroupStats) override;
6979
6980 void testRunEndedCumulative() override;
6981
6982 void writeGroup(TestGroupNode const &groupNode, double suiteTime);
6983
6984 void writeTestCase(TestCaseNode const &testCaseNode);
6985
6986 void writeSection(std::string const &className, std::string const &rootName,
6987 SectionNode const &sectionNode);
6988
6989 void writeAssertions(SectionNode const &sectionNode);
6990 void writeAssertion(AssertionStats const &stats);
6991
6992 XmlWriter xml;
6993 Timer suiteTimer;
6994 std::string stdOutForSuite;
6995 std::string stdErrForSuite;
6996 unsigned int unexpectedExceptions = 0;
6997 bool m_okToFail = false;
6998 };
6999
7000 } // end namespace Catch
7001
7002 // end catch_reporter_junit.h
7003 // start catch_reporter_xml.h
7004
7005 namespace Catch {
7006 class XmlReporter : public StreamingReporterBase<XmlReporter>
7007 {
7008 public:
7009 XmlReporter(ReporterConfig const &_config);
7010
7011 ~XmlReporter() override;
7012
7013 static std::string getDescription();
7014
7015 virtual std::string getStylesheetRef() const;
7016
7017 void writeSourceInfo(SourceLineInfo const &sourceInfo);
7018
7019 public: // StreamingReporterBase
7020 void noMatchingTestCases(std::string const &s) override;
7021
7022 void testRunStarting(TestRunInfo const &testInfo) override;
7023
7024 void testGroupStarting(GroupInfo const &groupInfo) override;
7025
7026 void testCaseStarting(TestCaseInfo const &testInfo) override;
7027
7028 void sectionStarting(SectionInfo const &sectionInfo) override;
7029
7030 void assertionStarting(AssertionInfo const &) override;
7031
7032 bool assertionEnded(AssertionStats const &assertionStats) override;
7033
7034 void sectionEnded(SectionStats const &sectionStats) override;
7035
7036 void testCaseEnded(TestCaseStats const &testCaseStats) override;
7037
7038 void testGroupEnded(TestGroupStats const &testGroupStats) override;
7039
7040 void testRunEnded(TestRunStats const &testRunStats) override;
7041
7042 #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
7043 void benchmarkPreparing(std::string const &name) override;
7044 void benchmarkStarting(BenchmarkInfo const &) override;
7045 void benchmarkEnded(BenchmarkStats<> const &) override;
7046 void benchmarkFailed(std::string const &) override;
7047 #endif // CATCH_CONFIG_ENABLE_BENCHMARKING
7048
7049 private:
7050 Timer m_testCaseTimer;
7051 XmlWriter m_xml;
7052 int m_sectionDepth = 0;
7053 };
7054
7055 } // end namespace Catch
7056
7057 // end catch_reporter_xml.h
7058
7059 // end catch_external_interfaces.h
7060 #endif
7061
7062 #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
7063 // start catch_benchmarking_all.hpp
7064
7065 // A proxy header that includes all of the benchmarking headers to allow
7066 // concise include of the benchmarking features. You should prefer the
7067 // individual includes in standard use.
7068
7069 // start catch_benchmark.hpp
7070
7071 // Benchmark
7072
7073 // start catch_chronometer.hpp
7074
7075 // User-facing chronometer
7076
7077 // start catch_clock.hpp
7078
7079 // Clocks
7080
7081 #include <chrono>
7082 #include <ratio>
7083
7084 namespace Catch {
7085 namespace Benchmark {
7086 template <typename Clock> using ClockDuration = typename Clock::duration;
7087 template <typename Clock>
7088 using FloatDuration = std::chrono::duration<double, typename Clock::period>;
7089
7090 template <typename Clock> using TimePoint = typename Clock::time_point;
7091
7092 using default_clock = std::chrono::steady_clock;
7093
7094 template <typename Clock> struct now
7095 {
7096 TimePoint<Clock> operator()() const { return Clock::now(); }
7097 };
7098
7099 using fp_seconds = std::chrono::duration<double, std::ratio<1>>;
7100 } // namespace Benchmark
7101 } // namespace Catch
7102
7103 // end catch_clock.hpp
7104 // start catch_optimizer.hpp
7105
7106 // Hinting the optimizer
7107
7108 #if defined(_MSC_VER)
7109 #include <atomic> // atomic_thread_fence
7110 #endif
7111
7112 namespace Catch {
7113 namespace Benchmark {
7114 #if defined(__GNUC__) || defined(__clang__)
7115 template <typename T> inline void keep_memory(T *p) { asm volatile("" : : "g"(p) : "memory"); }
7116 inline void keep_memory() { asm volatile("" : : : "memory"); }
7117
7118 namespace Detail {
7119 inline void optimizer_barrier() { keep_memory(); }
7120 } // namespace Detail
7121 #elif defined(_MSC_VER)
7122
7123 #pragma optimize("", off)
7124 template <typename T> inline void keep_memory(T *p)
7125 {
7126 // thanks @milleniumbug
7127 *reinterpret_cast<char volatile *>(p) = *reinterpret_cast<char const volatile *>(p);
7128 }
7129 // TODO equivalent keep_memory()
7130 #pragma optimize("", on)
7131
7132 namespace Detail {
7133 inline void optimizer_barrier() { std::atomic_thread_fence(std::memory_order_seq_cst); }
7134 } // namespace Detail
7135
7136 #endif
7137
7138 template <typename T> inline void deoptimize_value(T &&x) { keep_memory(&x); }
7139
7140 template <typename Fn, typename... Args>
7141 inline auto invoke_deoptimized(Fn &&fn, Args &&...args) ->
7142 typename std::enable_if<!std::is_same<void, decltype(fn(args...))>::value>::type
7143 {
7144 deoptimize_value(std::forward<Fn>(fn)(std::forward<Args...>(args...)));
7145 }
7146
7147 template <typename Fn, typename... Args>
7148 inline auto invoke_deoptimized(Fn &&fn, Args &&...args) ->
7149 typename std::enable_if<std::is_same<void, decltype(fn(args...))>::value>::type
7150 {
7151 std::forward<Fn>(fn)(std::forward<Args...>(args...));
7152 }
7153 } // namespace Benchmark
7154 } // namespace Catch
7155
7156 // end catch_optimizer.hpp
7157 // start catch_complete_invoke.hpp
7158
7159 // Invoke with a special case for void
7160
7161 #include <type_traits>
7162 #include <utility>
7163
7164 namespace Catch {
7165 namespace Benchmark {
7166 namespace Detail {
7167 template <typename T> struct CompleteType
7168 {
7169 using type = T;
7170 };
7171 template <> struct CompleteType<void>
7172 {
7173 struct type
7174 {
7175 };
7176 };
7177
7178 template <typename T> using CompleteType_t = typename CompleteType<T>::type;
7179
7180 template <typename Result> struct CompleteInvoker
7181 {
7182 template <typename Fun, typename... Args> static Result invoke(Fun &&fun, Args &&...args)
7183 {
7184 return std::forward<Fun>(fun)(std::forward<Args>(args)...);
7185 }
7186 };
7187 template <> struct CompleteInvoker<void>
7188 {
7189 template <typename Fun, typename... Args>
7190 static CompleteType_t<void> invoke(Fun &&fun, Args &&...args)
7191 {
7192 std::forward<Fun>(fun)(std::forward<Args>(args)...);
7193 return {};
7194 }
7195 };
7196
7197 // invoke and not return void :(
7198 template <typename Fun, typename... Args>
7199 CompleteType_t<FunctionReturnType<Fun, Args...>> complete_invoke(Fun &&fun, Args &&...args)
7200 {
7201 return CompleteInvoker<FunctionReturnType<Fun, Args...>>::invoke(
7202 std::forward<Fun>(fun), std::forward<Args>(args)...);
7203 }
7204
7205 const std::string benchmarkErrorMsg = "a benchmark failed to run successfully";
7206 } // namespace Detail
7207
7208 template <typename Fun> Detail::CompleteType_t<FunctionReturnType<Fun>> user_code(Fun &&fun)
7209 {
7210 CATCH_TRY { return Detail::complete_invoke(std::forward<Fun>(fun)); }
7211 CATCH_CATCH_ALL
7212 {
7213 getResultCapture().benchmarkFailed(translateActiveException());
7214 CATCH_RUNTIME_ERROR(Detail::benchmarkErrorMsg);
7215 }
7216 }
7217 } // namespace Benchmark
7218 } // namespace Catch
7219
7220 // end catch_complete_invoke.hpp
7221 namespace Catch {
7222 namespace Benchmark {
7223 namespace Detail {
7224 struct ChronometerConcept
7225 {
7226 virtual void start() = 0;
7227 virtual void finish() = 0;
7228 virtual ~ChronometerConcept() = default;
7229 };
7230 template <typename Clock> struct ChronometerModel final : public ChronometerConcept
7231 {
7232 void start() override { started = Clock::now(); }
7233 void finish() override { finished = Clock::now(); }
7234
7235 ClockDuration<Clock> elapsed() const { return finished - started; }
7236
7237 TimePoint<Clock> started;
7238 TimePoint<Clock> finished;
7239 };
7240 } // namespace Detail
7241
7242 struct Chronometer
7243 {
7244 public:
7245 template <typename Fun> void measure(Fun &&fun)
7246 {
7247 measure(std::forward<Fun>(fun), is_callable<Fun(int)>());
7248 }
7249
7250 int runs() const { return k; }
7251
7252 Chronometer(Detail::ChronometerConcept &meter, int k) : impl(&meter), k(k) {}
7253
7254 private:
7255 template <typename Fun> void measure(Fun &&fun, std::false_type)
7256 {
7257 measure([&fun](int) { return fun(); }, std::true_type());
7258 }
7259
7260 template <typename Fun> void measure(Fun &&fun, std::true_type)
7261 {
7262 Detail::optimizer_barrier();
7263 impl->start();
7264 for (int i = 0; i < k; ++i)
7265 invoke_deoptimized(fun, i);
7266 impl->finish();
7267 Detail::optimizer_barrier();
7268 }
7269
7270 Detail::ChronometerConcept *impl;
7271 int k;
7272 };
7273 } // namespace Benchmark
7274 } // namespace Catch
7275
7276 // end catch_chronometer.hpp
7277 // start catch_environment.hpp
7278
7279 // Environment information
7280
7281 namespace Catch {
7282 namespace Benchmark {
7283 template <typename Duration> struct EnvironmentEstimate
7284 {
7285 Duration mean;
7286 OutlierClassification outliers;
7287
7288 template <typename Duration2> operator EnvironmentEstimate<Duration2>() const
7289 {
7290 return {mean, outliers};
7291 }
7292 };
7293 template <typename Clock> struct Environment
7294 {
7295 using clock_type = Clock;
7296 EnvironmentEstimate<FloatDuration<Clock>> clock_resolution;
7297 EnvironmentEstimate<FloatDuration<Clock>> clock_cost;
7298 };
7299 } // namespace Benchmark
7300 } // namespace Catch
7301
7302 // end catch_environment.hpp
7303 // start catch_execution_plan.hpp
7304
7305 // Execution plan
7306
7307 // start catch_benchmark_function.hpp
7308
7309 // Dumb std::function implementation for consistent call overhead
7310
7311 #include <cassert>
7312 #include <memory>
7313 #include <type_traits>
7314 #include <utility>
7315
7316 namespace Catch {
7317 namespace Benchmark {
7318 namespace Detail {
7319 template <typename T> using Decay = typename std::decay<T>::type;
7320 template <typename T, typename U> struct is_related : std::is_same<Decay<T>, Decay<U>>
7321 {
7322 };
7323
7324 /// We need to reinvent std::function because every piece of code that might add overhead
7325 /// in a measurement context needs to have consistent performance characteristics so that we
7326 /// can account for it in the measurement.
7327 /// Implementations of std::function with optimizations that aren't always applicable, like
7328 /// small buffer optimizations, are not uncommon.
7329 /// This is effectively an implementation of std::function without any such optimizations;
7330 /// it may be slow, but it is consistently slow.
7331 struct BenchmarkFunction
7332 {
7333 private:
7334 struct callable
7335 {
7336 virtual void call(Chronometer meter) const = 0;
7337 virtual callable *clone() const = 0;
7338 virtual ~callable() = default;
7339 };
7340 template <typename Fun> struct model : public callable
7341 {
7342 model(Fun &&fun) : fun(std::move(fun)) {}
7343 model(Fun const &fun) : fun(fun) {}
7344
7345 model<Fun> *clone() const override { return new model<Fun>(*this); }
7346
7347 void call(Chronometer meter) const override
7348 {
7349 call(meter, is_callable<Fun(Chronometer)>());
7350 }
7351 void call(Chronometer meter, std::true_type) const { fun(meter); }
7352 void call(Chronometer meter, std::false_type) const { meter.measure(fun); }
7353
7354 Fun fun;
7355 };
7356
7357 struct do_nothing
7358 {
7359 void operator()() const {}
7360 };
7361
7362 template <typename T> BenchmarkFunction(model<T> *c) : f(c) {}
7363
7364 public:
7365 BenchmarkFunction() : f(new model<do_nothing>{{}}) {}
7366
7367 template <typename Fun, typename std::enable_if<!is_related<Fun, BenchmarkFunction>::value,
7368 int>::type = 0>
7369 BenchmarkFunction(Fun &&fun)
7370 : f(new model<typename std::decay<Fun>::type>(std::forward<Fun>(fun)))
7371 {
7372 }
7373
7374 BenchmarkFunction(BenchmarkFunction &&that) : f(std::move(that.f)) {}
7375
7376 BenchmarkFunction(BenchmarkFunction const &that) : f(that.f->clone()) {}
7377
7378 BenchmarkFunction &operator=(BenchmarkFunction &&that)
7379 {
7380 f = std::move(that.f);
7381 return *this;
7382 }
7383
7384 BenchmarkFunction &operator=(BenchmarkFunction const &that)
7385 {
7386 f.reset(that.f->clone());
7387 return *this;
7388 }
7389
7390 void operator()(Chronometer meter) const { f->call(meter); }
7391
7392 private:
7393 std::unique_ptr<callable> f;
7394 };
7395 } // namespace Detail
7396 } // namespace Benchmark
7397 } // namespace Catch
7398
7399 // end catch_benchmark_function.hpp
7400 // start catch_repeat.hpp
7401
7402 // repeat algorithm
7403
7404 #include <type_traits>
7405 #include <utility>
7406
7407 namespace Catch {
7408 namespace Benchmark {
7409 namespace Detail {
7410 template <typename Fun> struct repeater
7411 {
7412 void operator()(int k) const
7413 {
7414 for (int i = 0; i < k; ++i) {
7415 fun();
7416 }
7417 }
7418 Fun fun;
7419 };
7420 template <typename Fun> repeater<typename std::decay<Fun>::type> repeat(Fun &&fun)
7421 {
7422 return {std::forward<Fun>(fun)};
7423 }
7424 } // namespace Detail
7425 } // namespace Benchmark
7426 } // namespace Catch
7427
7428 // end catch_repeat.hpp
7429 // start catch_run_for_at_least.hpp
7430
7431 // Run a function for a minimum amount of time
7432
7433 // start catch_measure.hpp
7434
7435 // Measure
7436
7437 // start catch_timing.hpp
7438
7439 // Timing
7440
7441 #include <tuple>
7442 #include <type_traits>
7443
7444 namespace Catch {
7445 namespace Benchmark {
7446 template <typename Duration, typename Result> struct Timing
7447 {
7448 Duration elapsed;
7449 Result result;
7450 int iterations;
7451 };
7452 template <typename Clock, typename Func, typename... Args>
7453 using TimingOf =
7454 Timing<ClockDuration<Clock>, Detail::CompleteType_t<FunctionReturnType<Func, Args...>>>;
7455 } // namespace Benchmark
7456 } // namespace Catch
7457
7458 // end catch_timing.hpp
7459 #include <utility>
7460
7461 namespace Catch {
7462 namespace Benchmark {
7463 namespace Detail {
7464 template <typename Clock, typename Fun, typename... Args>
7465 TimingOf<Clock, Fun, Args...> measure(Fun &&fun, Args &&...args)
7466 {
7467 auto start = Clock::now();
7468 auto &&r = Detail::complete_invoke(fun, std::forward<Args>(args)...);
7469 auto end = Clock::now();
7470 auto delta = end - start;
7471 return {delta, std::forward<decltype(r)>(r), 1};
7472 }
7473 } // namespace Detail
7474 } // namespace Benchmark
7475 } // namespace Catch
7476
7477 // end catch_measure.hpp
7478 #include <type_traits>
7479 #include <utility>
7480
7481 namespace Catch {
7482 namespace Benchmark {
7483 namespace Detail {
7484 template <typename Clock, typename Fun>
7485 TimingOf<Clock, Fun, int> measure_one(Fun &&fun, int iters, std::false_type)
7486 {
7487 return Detail::measure<Clock>(fun, iters);
7488 }
7489 template <typename Clock, typename Fun>
7490 TimingOf<Clock, Fun, Chronometer> measure_one(Fun &&fun, int iters, std::true_type)
7491 {
7492 Detail::ChronometerModel<Clock> meter;
7493 auto &&result = Detail::complete_invoke(fun, Chronometer(meter, iters));
7494
7495 return {meter.elapsed(), std::move(result), iters};
7496 }
7497
7498 template <typename Clock, typename Fun>
7499 using run_for_at_least_argument_t =
7500 typename std::conditional<is_callable<Fun(Chronometer)>::value, Chronometer, int>::type;
7501
7502 struct optimized_away_error : std::exception
7503 {
7504 const char *what() const noexcept override
7505 {
7506 return "could not measure benchmark, maybe it was optimized away";
7507 }
7508 };
7509
7510 template <typename Clock, typename Fun>
7511 TimingOf<Clock, Fun, run_for_at_least_argument_t<Clock, Fun>>
7512 run_for_at_least(ClockDuration<Clock> how_long, int seed, Fun &&fun)
7513 {
7514 auto iters = seed;
7515 while (iters < (1 << 30)) {
7516 auto &&Timing = measure_one<Clock>(fun, iters, is_callable<Fun(Chronometer)>());
7517
7518 if (Timing.elapsed >= how_long) {
7519 return {Timing.elapsed, std::move(Timing.result), iters};
7520 }
7521 iters *= 2;
7522 }
7523 throw optimized_away_error{};
7524 }
7525 } // namespace Detail
7526 } // namespace Benchmark
7527 } // namespace Catch
7528
7529 // end catch_run_for_at_least.hpp
7530 #include <algorithm>
7531
7532 namespace Catch {
7533 namespace Benchmark {
7534 template <typename Duration> struct ExecutionPlan
7535 {
7536 int iterations_per_sample;
7537 Duration estimated_duration;
7538 Detail::BenchmarkFunction benchmark;
7539 Duration warmup_time;
7540 int warmup_iterations;
7541
7542 template <typename Duration2> operator ExecutionPlan<Duration2>() const
7543 {
7544 return {iterations_per_sample, estimated_duration, benchmark, warmup_time,
7545 warmup_iterations};
7546 }
7547
7548 template <typename Clock>
7549 std::vector<FloatDuration<Clock>> run(const IConfig &cfg,
7550 Environment<FloatDuration<Clock>> env) const
7551 {
7552 // warmup a bit
7553 Detail::run_for_at_least<Clock>(
7554 std::chrono::duration_cast<ClockDuration<Clock>>(warmup_time), warmup_iterations,
7555 Detail::repeat(now<Clock>{}));
7556
7557 std::vector<FloatDuration<Clock>> times;
7558 times.reserve(cfg.benchmarkSamples());
7559 std::generate_n(std::back_inserter(times), cfg.benchmarkSamples(), [this, env] {
7560 Detail::ChronometerModel<Clock> model;
7561 this->benchmark(Chronometer(model, iterations_per_sample));
7562 auto sample_time = model.elapsed() - env.clock_cost.mean;
7563 if (sample_time < FloatDuration<Clock>::zero())
7564 sample_time = FloatDuration<Clock>::zero();
7565 return sample_time / iterations_per_sample;
7566 });
7567 return times;
7568 }
7569 };
7570 } // namespace Benchmark
7571 } // namespace Catch
7572
7573 // end catch_execution_plan.hpp
7574 // start catch_estimate_clock.hpp
7575
7576 // Environment measurement
7577
7578 // start catch_stats.hpp
7579
7580 // Statistical analysis tools
7581
7582 #include <algorithm>
7583 #include <cmath>
7584 #include <cstddef>
7585 #include <functional>
7586 #include <iterator>
7587 #include <numeric>
7588 #include <random>
7589 #include <tuple>
7590 #include <utility>
7591 #include <vector>
7592
7593 namespace Catch {
7594 namespace Benchmark {
7595 namespace Detail {
7596 using sample = std::vector<double>;
7597
7598 double weighted_average_quantile(int k, int q, std::vector<double>::iterator first,
7599 std::vector<double>::iterator last);
7600
7601 template <typename Iterator>
7602 OutlierClassification classify_outliers(Iterator first, Iterator last)
7603 {
7604 std::vector<double> copy(first, last);
7605
7606 auto q1 = weighted_average_quantile(1, 4, copy.begin(), copy.end());
7607 auto q3 = weighted_average_quantile(3, 4, copy.begin(), copy.end());
7608 auto iqr = q3 - q1;
7609 auto los = q1 - (iqr * 3.);
7610 auto lom = q1 - (iqr * 1.5);
7611 auto him = q3 + (iqr * 1.5);
7612 auto his = q3 + (iqr * 3.);
7613
7614 OutlierClassification o;
7615 for (; first != last; ++first) {
7616 auto &&t = *first;
7617 if (t < los)
7618 ++o.low_severe;
7619 else if (t < lom)
7620 ++o.low_mild;
7621 else if (t > his)
7622 ++o.high_severe;
7623 else if (t > him)
7624 ++o.high_mild;
7625 ++o.samples_seen;
7626 }
7627 return o;
7628 }
7629
7630 template <typename Iterator> double mean(Iterator first, Iterator last)
7631 {
7632 auto count = last - first;
7633 double sum = std::accumulate(first, last, 0.);
7634 return sum / count;
7635 }
7636
7637 template <typename URng, typename Iterator, typename Estimator>
7638 sample resample(URng &rng, int resamples, Iterator first, Iterator last, Estimator &estimator)
7639 {
7640 auto n = last - first;
7641 std::uniform_int_distribution<decltype(n)> dist(0, n - 1);
7642
7643 sample out;
7644 out.reserve(resamples);
7645 std::generate_n(std::back_inserter(out), resamples, [n, first, &estimator, &dist, &rng] {
7646 std::vector<double> resampled;
7647 resampled.reserve(n);
7648 std::generate_n(std::back_inserter(resampled), n,
7649 [first, &dist, &rng] { return first[dist(rng)]; });
7650 return estimator(resampled.begin(), resampled.end());
7651 });
7652 std::sort(out.begin(), out.end());
7653 return out;
7654 }
7655
7656 template <typename Estimator, typename Iterator>
7657 sample jackknife(Estimator &&estimator, Iterator first, Iterator last)
7658 {
7659 auto n = last - first;
7660 auto second = std::next(first);
7661 sample results;
7662 results.reserve(n);
7663
7664 for (auto it = first; it != last; ++it) {
7665 std::iter_swap(it, first);
7666 results.push_back(estimator(second, last));
7667 }
7668
7669 return results;
7670 }
7671
7672 inline double normal_cdf(double x) { return std::erfc(-x / std::sqrt(2.0)) / 2.0; }
7673
7674 double erfc_inv(double x);
7675
7676 double normal_quantile(double p);
7677
7678 template <typename Iterator, typename Estimator>
7679 Estimate<double> bootstrap(double confidence_level, Iterator first, Iterator last,
7680 sample const &resample, Estimator &&estimator)
7681 {
7682 auto n_samples = last - first;
7683
7684 double point = estimator(first, last);
7685 // Degenerate case with a single sample
7686 if (n_samples == 1)
7687 return {point, point, point, confidence_level};
7688
7689 sample jack = jackknife(estimator, first, last);
7690 double jack_mean = mean(jack.begin(), jack.end());
7691 double sum_squares, sum_cubes;
7692 std::tie(sum_squares, sum_cubes) = std::accumulate(
7693 jack.begin(), jack.end(), std::make_pair(0., 0.),
7694 [jack_mean](std::pair<double, double> sqcb, double x) -> std::pair<double, double> {
7695 auto d = jack_mean - x;
7696 auto d2 = d * d;
7697 auto d3 = d2 * d;
7698 return {sqcb.first + d2, sqcb.second + d3};
7699 });
7700
7701 double accel = sum_cubes / (6 * std::pow(sum_squares, 1.5));
7702 int n = static_cast<int>(resample.size());
7703 double prob_n = std::count_if(resample.begin(), resample.end(),
7704 [point](double x) { return x < point; }) /
7705 (double)n;
7706 // degenerate case with uniform samples
7707 if (prob_n == 0)
7708 return {point, point, point, confidence_level};
7709
7710 double bias = normal_quantile(prob_n);
7711 double z1 = normal_quantile((1. - confidence_level) / 2.);
7712
7713 auto cumn = [n](double x) -> int { return std::lround(normal_cdf(x) * n); };
7714 auto a = [bias, accel](double b) { return bias + b / (1. - accel * b); };
7715 double b1 = bias + z1;
7716 double b2 = bias - z1;
7717 double a1 = a(b1);
7718 double a2 = a(b2);
7719 auto lo = std::max(cumn(a1), 0);
7720 auto hi = std::min(cumn(a2), n - 1);
7721
7722 return {point, resample[lo], resample[hi], confidence_level};
7723 }
7724
7725 double outlier_variance(Estimate<double> mean, Estimate<double> stddev, int n);
7726
7727 struct bootstrap_analysis
7728 {
7729 Estimate<double> mean;
7730 Estimate<double> standard_deviation;
7731 double outlier_variance;
7732 };
7733
7734 bootstrap_analysis analyse_samples(double confidence_level, int n_resamples,
7735 std::vector<double>::iterator first,
7736 std::vector<double>::iterator last);
7737 } // namespace Detail
7738 } // namespace Benchmark
7739 } // namespace Catch
7740
7741 // end catch_stats.hpp
7742 #include <algorithm>
7743 #include <cmath>
7744 #include <iterator>
7745 #include <tuple>
7746 #include <vector>
7747
7748 namespace Catch {
7749 namespace Benchmark {
7750 namespace Detail {
7751 template <typename Clock> std::vector<double> resolution(int k)
7752 {
7753 std::vector<TimePoint<Clock>> times;
7754 times.reserve(k + 1);
7755 std::generate_n(std::back_inserter(times), k + 1, now<Clock>{});
7756
7757 std::vector<double> deltas;
7758 deltas.reserve(k);
7759 std::transform(std::next(times.begin()), times.end(), times.begin(),
7760 std::back_inserter(deltas), [](TimePoint<Clock> a, TimePoint<Clock> b) {
7761 return static_cast<double>((a - b).count());
7762 });
7763
7764 return deltas;
7765 }
7766
7767 const auto warmup_iterations = 10000;
7768 const auto warmup_time = std::chrono::milliseconds(100);
7769 const auto minimum_ticks = 1000;
7770 const auto warmup_seed = 10000;
7771 const auto clock_resolution_estimation_time = std::chrono::milliseconds(500);
7772 const auto clock_cost_estimation_time_limit = std::chrono::seconds(1);
7773 const auto clock_cost_estimation_tick_limit = 100000;
7774 const auto clock_cost_estimation_time = std::chrono::milliseconds(10);
7775 const auto clock_cost_estimation_iterations = 10000;
7776
7777 template <typename Clock> int warmup()
7778 {
7779 return run_for_at_least<Clock>(
7780 std::chrono::duration_cast<ClockDuration<Clock>>(warmup_time), warmup_seed,
7781 &resolution<Clock>)
7782 .iterations;
7783 }
7784 template <typename Clock>
7785 EnvironmentEstimate<FloatDuration<Clock>> estimate_clock_resolution(int iterations)
7786 {
7787 auto r = run_for_at_least<Clock>(std::chrono::duration_cast<ClockDuration<Clock>>(
7788 clock_resolution_estimation_time),
7789 iterations, &resolution<Clock>)
7790 .result;
7791 return {
7792 FloatDuration<Clock>(mean(r.begin(), r.end())),
7793 classify_outliers(r.begin(), r.end()),
7794 };
7795 }
7796 template <typename Clock>
7797 EnvironmentEstimate<FloatDuration<Clock>> estimate_clock_cost(FloatDuration<Clock> resolution)
7798 {
7799 auto time_limit = std::min(resolution * clock_cost_estimation_tick_limit,
7800 FloatDuration<Clock>(clock_cost_estimation_time_limit));
7801 auto time_clock = [](int k) {
7802 return Detail::measure<Clock>([k] {
7803 for (int i = 0; i < k; ++i) {
7804 volatile auto ignored = Clock::now();
7805 (void)ignored;
7806 }
7807 })
7808 .elapsed;
7809 };
7810 time_clock(1);
7811 int iters = clock_cost_estimation_iterations;
7812 auto &&r = run_for_at_least<Clock>(
7813 std::chrono::duration_cast<ClockDuration<Clock>>(clock_cost_estimation_time), iters,
7814 time_clock);
7815 std::vector<double> times;
7816 int nsamples = static_cast<int>(std::ceil(time_limit / r.elapsed));
7817 times.reserve(nsamples);
7818 std::generate_n(std::back_inserter(times), nsamples, [time_clock, &r] {
7819 return static_cast<double>((time_clock(r.iterations) / r.iterations).count());
7820 });
7821 return {
7822 FloatDuration<Clock>(mean(times.begin(), times.end())),
7823 classify_outliers(times.begin(), times.end()),
7824 };
7825 }
7826
7827 template <typename Clock> Environment<FloatDuration<Clock>> measure_environment()
7828 {
7829 static Environment<FloatDuration<Clock>> *env = nullptr;
7830 if (env) {
7831 return *env;
7832 }
7833
7834 auto iters = Detail::warmup<Clock>();
7835 auto resolution = Detail::estimate_clock_resolution<Clock>(iters);
7836 auto cost = Detail::estimate_clock_cost<Clock>(resolution.mean);
7837
7838 env = new Environment<FloatDuration<Clock>>{resolution, cost};
7839 return *env;
7840 }
7841 } // namespace Detail
7842 } // namespace Benchmark
7843 } // namespace Catch
7844
7845 // end catch_estimate_clock.hpp
7846 // start catch_analyse.hpp
7847
7848 // Run and analyse one benchmark
7849
7850 // start catch_sample_analysis.hpp
7851
7852 // Benchmark results
7853
7854 #include <algorithm>
7855 #include <iterator>
7856 #include <string>
7857 #include <vector>
7858
7859 namespace Catch {
7860 namespace Benchmark {
7861 template <typename Duration> struct SampleAnalysis
7862 {
7863 std::vector<Duration> samples;
7864 Estimate<Duration> mean;
7865 Estimate<Duration> standard_deviation;
7866 OutlierClassification outliers;
7867 double outlier_variance;
7868
7869 template <typename Duration2> operator SampleAnalysis<Duration2>() const
7870 {
7871 std::vector<Duration2> samples2;
7872 samples2.reserve(samples.size());
7873 std::transform(samples.begin(), samples.end(), std::back_inserter(samples2),
7874 [](Duration d) { return Duration2(d); });
7875 return {
7876 std::move(samples2), mean, standard_deviation, outliers, outlier_variance,
7877 };
7878 }
7879 };
7880 } // namespace Benchmark
7881 } // namespace Catch
7882
7883 // end catch_sample_analysis.hpp
7884 #include <algorithm>
7885 #include <iterator>
7886 #include <vector>
7887
7888 namespace Catch {
7889 namespace Benchmark {
7890 namespace Detail {
7891 template <typename Duration, typename Iterator>
7892 SampleAnalysis<Duration> analyse(const IConfig &cfg, Environment<Duration>, Iterator first,
7893 Iterator last)
7894 {
7895 if (!cfg.benchmarkNoAnalysis()) {
7896 std::vector<double> samples;
7897 samples.reserve(last - first);
7898 std::transform(first, last, std::back_inserter(samples),
7899 [](Duration d) { return d.count(); });
7900
7901 auto analysis = Catch::Benchmark::Detail::analyse_samples(
7902 cfg.benchmarkConfidenceInterval(), cfg.benchmarkResamples(), samples.begin(),
7903 samples.end());
7904 auto outliers =
7905 Catch::Benchmark::Detail::classify_outliers(samples.begin(), samples.end());
7906
7907 auto wrap_estimate = [](Estimate<double> e) {
7908 return Estimate<Duration>{
7909 Duration(e.point),
7910 Duration(e.lower_bound),
7911 Duration(e.upper_bound),
7912 e.confidence_interval,
7913 };
7914 };
7915 std::vector<Duration> samples2;
7916 samples2.reserve(samples.size());
7917 std::transform(samples.begin(), samples.end(), std::back_inserter(samples2),
7918 [](double d) { return Duration(d); });
7919 return {
7920 std::move(samples2),
7921 wrap_estimate(analysis.mean),
7922 wrap_estimate(analysis.standard_deviation),
7923 outliers,
7924 analysis.outlier_variance,
7925 };
7926 }
7927 else {
7928 std::vector<Duration> samples;
7929 samples.reserve(last - first);
7930
7931 Duration mean = Duration(0);
7932 int i = 0;
7933 for (auto it = first; it < last; ++it, ++i) {
7934 samples.push_back(Duration(*it));
7935 mean += Duration(*it);
7936 }
7937 mean /= i;
7938
7939 return {std::move(samples), Estimate<Duration>{mean, mean, mean, 0.0},
7940 Estimate<Duration>{Duration(0), Duration(0), Duration(0), 0.0},
7941 OutlierClassification{}, 0.0};
7942 }
7943 }
7944 } // namespace Detail
7945 } // namespace Benchmark
7946 } // namespace Catch
7947
7948 // end catch_analyse.hpp
7949 #include <algorithm>
7950 #include <cmath>
7951 #include <functional>
7952 #include <string>
7953 #include <vector>
7954
7955 namespace Catch {
7956 namespace Benchmark {
7957 struct Benchmark
7958 {
7959 Benchmark(std::string &&name) : name(std::move(name)) {}
7960
7961 template <class FUN>
7962 Benchmark(std::string &&name, FUN &&func) : fun(std::move(func)), name(std::move(name))
7963 {
7964 }
7965
7966 template <typename Clock>
7967 ExecutionPlan<FloatDuration<Clock>> prepare(const IConfig &cfg,
7968 Environment<FloatDuration<Clock>> env) const
7969 {
7970 auto min_time = env.clock_resolution.mean * Detail::minimum_ticks;
7971 auto run_time = std::max(
7972 min_time, std::chrono::duration_cast<decltype(min_time)>(cfg.benchmarkWarmupTime()));
7973 auto &&test = Detail::run_for_at_least<Clock>(
7974 std::chrono::duration_cast<ClockDuration<Clock>>(run_time), 1, fun);
7975 int new_iters = static_cast<int>(std::ceil(min_time * test.iterations / test.elapsed));
7976 return {new_iters, test.elapsed / test.iterations * new_iters * cfg.benchmarkSamples(), fun,
7977 std::chrono::duration_cast<FloatDuration<Clock>>(cfg.benchmarkWarmupTime()),
7978 Detail::warmup_iterations};
7979 }
7980
7981 template <typename Clock = default_clock> void run()
7982 {
7983 IConfigPtr cfg = getCurrentContext().getConfig();
7984
7985 auto env = Detail::measure_environment<Clock>();
7986
7987 getResultCapture().benchmarkPreparing(name);
7988 CATCH_TRY
7989 {
7990 auto plan = user_code([&] { return prepare<Clock>(*cfg, env); });
7991
7992 BenchmarkInfo info{name,
7993 plan.estimated_duration.count(),
7994 plan.iterations_per_sample,
7995 cfg->benchmarkSamples(),
7996 cfg->benchmarkResamples(),
7997 env.clock_resolution.mean.count(),
7998 env.clock_cost.mean.count()};
7999
8000 getResultCapture().benchmarkStarting(info);
8001
8002 auto samples = user_code([&] { return plan.template run<Clock>(*cfg, env); });
8003
8004 auto analysis = Detail::analyse(*cfg, env, samples.begin(), samples.end());
8005 BenchmarkStats<FloatDuration<Clock>> stats{info,
8006 analysis.samples,
8007 analysis.mean,
8008 analysis.standard_deviation,
8009 analysis.outliers,
8010 analysis.outlier_variance};
8011 getResultCapture().benchmarkEnded(stats);
8012 }
8013 CATCH_CATCH_ALL
8014 {
8015 if (translateActiveException() !=
8016 Detail::benchmarkErrorMsg) // benchmark errors have been reported, otherwise rethrow.
8017 std::rethrow_exception(std::current_exception());
8018 }
8019 }
8020
8021 // sets lambda to be used in fun *and* executes benchmark!
8022 template <typename Fun,
8023 typename std::enable_if<!Detail::is_related<Fun, Benchmark>::value, int>::type = 0>
8024 Benchmark &operator=(Fun func)
8025 {
8026 fun = Detail::BenchmarkFunction(func);
8027 run();
8028 return *this;
8029 }
8030
8031 explicit operator bool() { return true; }
8032
8033 private:
8034 Detail::BenchmarkFunction fun;
8035 std::string name;
8036 };
8037 } // namespace Benchmark
8038 } // namespace Catch
8039
8040 #define INTERNAL_CATCH_GET_1_ARG(arg1, arg2, ...) arg1
8041 #define INTERNAL_CATCH_GET_2_ARG(arg1, arg2, ...) arg2
8042
8043 #define INTERNAL_CATCH_BENCHMARK(BenchmarkName, name, benchmarkIndex) \
8044 if (Catch::Benchmark::Benchmark BenchmarkName{name}) \
8045 BenchmarkName = [&](int benchmarkIndex)
8046
8047 #define INTERNAL_CATCH_BENCHMARK_ADVANCED(BenchmarkName, name) \
8048 if (Catch::Benchmark::Benchmark BenchmarkName{name}) \
8049 BenchmarkName = [&]
8050
8051 // end catch_benchmark.hpp
8052 // start catch_constructor.hpp
8053
8054 // Constructor and destructor helpers
8055
8056 #include <type_traits>
8057
8058 namespace Catch {
8059 namespace Benchmark {
8060 namespace Detail {
8061 template <typename T, bool Destruct> struct ObjectStorage
8062 {
8063 using TStorage =
8064 typename std::aligned_storage<sizeof(T), std::alignment_of<T>::value>::type;
8065
8066 ObjectStorage() : data() {}
8067
8068 ObjectStorage(const ObjectStorage &other) { new (&data) T(other.stored_object()); }
8069
8070 ObjectStorage(ObjectStorage &&other) { new (&data) T(std::move(other.stored_object())); }
8071
8072 ~ObjectStorage() { destruct_on_exit<T>(); }
8073
8074 template <typename... Args> void construct(Args &&...args)
8075 {
8076 new (&data) T(std::forward<Args>(args)...);
8077 }
8078
8079 template <bool AllowManualDestruction = !Destruct>
8080 typename std::enable_if<AllowManualDestruction>::type destruct()
8081 {
8082 stored_object().~T();
8083 }
8084
8085 private:
8086 // If this is a constructor benchmark, destruct the underlying object
8087 template <typename U>
8088 void destruct_on_exit(typename std::enable_if<Destruct, U>::type * = 0)
8089 {
8090 destruct<true>();
8091 }
8092 // Otherwise, don't
8093 template <typename U>
8094 void destruct_on_exit(typename std::enable_if<!Destruct, U>::type * = 0)
8095 {
8096 }
8097
8098 T &stored_object() { return *static_cast<T *>(static_cast<void *>(&data)); }
8099
8100 T const &stored_object() const { return *static_cast<T *>(static_cast<void *>(&data)); }
8101
8102 TStorage data;
8103 };
8104 } // namespace Detail
8105
8106 template <typename T> using storage_for = Detail::ObjectStorage<T, true>;
8107
8108 template <typename T> using destructable_object = Detail::ObjectStorage<T, false>;
8109 } // namespace Benchmark
8110 } // namespace Catch
8111
8112 // end catch_constructor.hpp
8113 // end catch_benchmarking_all.hpp
8114 #endif
8115
8116 #endif // ! CATCH_CONFIG_IMPL_ONLY
8117
8118 #ifdef CATCH_IMPL
8119 // start catch_impl.hpp
8120
8121 #ifdef __clang__
8122 #pragma clang diagnostic push
8123 #pragma clang diagnostic ignored "-Wweak-vtables"
8124 #endif
8125
8126 // Keep these here for external reporters
8127 // start catch_test_case_tracker.h
8128
8129 #include <memory>
8130 #include <string>
8131 #include <vector>
8132
8133 namespace Catch {
8134 namespace TestCaseTracking {
8135
8136 struct NameAndLocation
8137 {
8138 std::string name;
8139 SourceLineInfo location;
8140
8141 NameAndLocation(std::string const &_name, SourceLineInfo const &_location);
8142 friend bool operator==(NameAndLocation const &lhs, NameAndLocation const &rhs)
8143 {
8144 return lhs.name == rhs.name && lhs.location == rhs.location;
8145 }
8146 };
8147
8148 class ITracker;
8149
8150 using ITrackerPtr = std::shared_ptr<ITracker>;
8151
8152 class ITracker
8153 {
8154 NameAndLocation m_nameAndLocation;
8155
8156 public:
8157 ITracker(NameAndLocation const &nameAndLoc) : m_nameAndLocation(nameAndLoc) {}
8158
8159 // static queries
8160 NameAndLocation const &nameAndLocation() const { return m_nameAndLocation; }
8161
8162 virtual ~ITracker();
8163
8164 // dynamic queries
8165 virtual bool isComplete() const = 0; // Successfully completed or failed
8166 virtual bool isSuccessfullyCompleted() const = 0;
8167 virtual bool isOpen() const = 0; // Started but not complete
8168 virtual bool hasChildren() const = 0;
8169 virtual bool hasStarted() const = 0;
8170
8171 virtual ITracker &parent() = 0;
8172
8173 // actions
8174 virtual void close() = 0; // Successfully complete
8175 virtual void fail() = 0;
8176 virtual void markAsNeedingAnotherRun() = 0;
8177
8178 virtual void addChild(ITrackerPtr const &child) = 0;
8179 virtual ITrackerPtr findChild(NameAndLocation const &nameAndLocation) = 0;
8180 virtual void openChild() = 0;
8181
8182 // Debug/ checking
8183 virtual bool isSectionTracker() const = 0;
8184 virtual bool isGeneratorTracker() const = 0;
8185 };
8186
8187 class TrackerContext
8188 {
8189
8190 enum RunState { NotStarted, Executing, CompletedCycle };
8191
8192 ITrackerPtr m_rootTracker;
8193 ITracker *m_currentTracker = nullptr;
8194 RunState m_runState = NotStarted;
8195
8196 public:
8197 ITracker &startRun();
8198 void endRun();
8199
8200 void startCycle();
8201 void completeCycle();
8202
8203 bool completedCycle() const;
8204 ITracker &currentTracker();
8205 void setCurrentTracker(ITracker *tracker);
8206 };
8207
8208 class TrackerBase : public ITracker
8209 {
8210 protected:
8211 enum CycleState {
8212 NotStarted,
8213 Executing,
8214 ExecutingChildren,
8215 NeedsAnotherRun,
8216 CompletedSuccessfully,
8217 Failed
8218 };
8219
8220 using Children = std::vector<ITrackerPtr>;
8221 TrackerContext &m_ctx;
8222 ITracker *m_parent;
8223 Children m_children;
8224 CycleState m_runState = NotStarted;
8225
8226 public:
8227 TrackerBase(NameAndLocation const &nameAndLocation, TrackerContext &ctx, ITracker *parent);
8228
8229 bool isComplete() const override;
8230 bool isSuccessfullyCompleted() const override;
8231 bool isOpen() const override;
8232 bool hasChildren() const override;
8233 bool hasStarted() const override { return m_runState != NotStarted; }
8234
8235 void addChild(ITrackerPtr const &child) override;
8236
8237 ITrackerPtr findChild(NameAndLocation const &nameAndLocation) override;
8238 ITracker &parent() override;
8239
8240 void openChild() override;
8241
8242 bool isSectionTracker() const override;
8243 bool isGeneratorTracker() const override;
8244
8245 void open();
8246
8247 void close() override;
8248 void fail() override;
8249 void markAsNeedingAnotherRun() override;
8250
8251 private:
8252 void moveToParent();
8253 void moveToThis();
8254 };
8255
8256 class SectionTracker : public TrackerBase
8257 {
8258 std::vector<std::string> m_filters;
8259 std::string m_trimmed_name;
8260
8261 public:
8262 SectionTracker(NameAndLocation const &nameAndLocation, TrackerContext &ctx, ITracker *parent);
8263
8264 bool isSectionTracker() const override;
8265
8266 bool isComplete() const override;
8267
8268 static SectionTracker &acquire(TrackerContext &ctx, NameAndLocation const &nameAndLocation);
8269
8270 void tryOpen();
8271
8272 void addInitialFilters(std::vector<std::string> const &filters);
8273 void addNextFilters(std::vector<std::string> const &filters);
8274 //! Returns filters active in this tracker
8275 std::vector<std::string> const &getFilters() const;
8276 //! Returns whitespace-trimmed name of the tracked section
8277 std::string const &trimmedName() const;
8278 };
8279
8280 } // namespace TestCaseTracking
8281
8282 using TestCaseTracking::ITracker;
8283 using TestCaseTracking::SectionTracker;
8284 using TestCaseTracking::TrackerContext;
8285
8286 } // namespace Catch
8287
8288 // end catch_test_case_tracker.h
8289
8290 // start catch_leak_detector.h
8291
8292 namespace Catch {
8293
8294 struct LeakDetector
8295 {
8296 LeakDetector();
8297 ~LeakDetector();
8298 };
8299
8300 } // namespace Catch
8301 // end catch_leak_detector.h
8302 // Cpp files will be included in the single-header file here
8303 // start catch_stats.cpp
8304
8305 // Statistical analysis tools
8306
8307 #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
8308
8309 #include <cassert>
8310 #include <random>
8311
8312 #if defined(CATCH_CONFIG_USE_ASYNC)
8313 #include <future>
8314 #endif
8315
8316 namespace {
8317 double erf_inv(double x)
8318 {
8319 // Code accompanying the article "Approximating the erfinv function" in GPU Computing Gems,
8320 // Volume 2
8321 double w, p;
8322
8323 w = -log((1.0 - x) * (1.0 + x));
8324
8325 if (w < 6.250000) {
8326 w = w - 3.125000;
8327 p = -3.6444120640178196996e-21;
8328 p = -1.685059138182016589e-19 + p * w;
8329 p = 1.2858480715256400167e-18 + p * w;
8330 p = 1.115787767802518096e-17 + p * w;
8331 p = -1.333171662854620906e-16 + p * w;
8332 p = 2.0972767875968561637e-17 + p * w;
8333 p = 6.6376381343583238325e-15 + p * w;
8334 p = -4.0545662729752068639e-14 + p * w;
8335 p = -8.1519341976054721522e-14 + p * w;
8336 p = 2.6335093153082322977e-12 + p * w;
8337 p = -1.2975133253453532498e-11 + p * w;
8338 p = -5.4154120542946279317e-11 + p * w;
8339 p = 1.051212273321532285e-09 + p * w;
8340 p = -4.1126339803469836976e-09 + p * w;
8341 p = -2.9070369957882005086e-08 + p * w;
8342 p = 4.2347877827932403518e-07 + p * w;
8343 p = -1.3654692000834678645e-06 + p * w;
8344 p = -1.3882523362786468719e-05 + p * w;
8345 p = 0.0001867342080340571352 + p * w;
8346 p = -0.00074070253416626697512 + p * w;
8347 p = -0.0060336708714301490533 + p * w;
8348 p = 0.24015818242558961693 + p * w;
8349 p = 1.6536545626831027356 + p * w;
8350 }
8351 else if (w < 16.000000) {
8352 w = sqrt(w) - 3.250000;
8353 p = 2.2137376921775787049e-09;
8354 p = 9.0756561938885390979e-08 + p * w;
8355 p = -2.7517406297064545428e-07 + p * w;
8356 p = 1.8239629214389227755e-08 + p * w;
8357 p = 1.5027403968909827627e-06 + p * w;
8358 p = -4.013867526981545969e-06 + p * w;
8359 p = 2.9234449089955446044e-06 + p * w;
8360 p = 1.2475304481671778723e-05 + p * w;
8361 p = -4.7318229009055733981e-05 + p * w;
8362 p = 6.8284851459573175448e-05 + p * w;
8363 p = 2.4031110387097893999e-05 + p * w;
8364 p = -0.0003550375203628474796 + p * w;
8365 p = 0.00095328937973738049703 + p * w;
8366 p = -0.0016882755560235047313 + p * w;
8367 p = 0.0024914420961078508066 + p * w;
8368 p = -0.0037512085075692412107 + p * w;
8369 p = 0.005370914553590063617 + p * w;
8370 p = 1.0052589676941592334 + p * w;
8371 p = 3.0838856104922207635 + p * w;
8372 }
8373 else {
8374 w = sqrt(w) - 5.000000;
8375 p = -2.7109920616438573243e-11;
8376 p = -2.5556418169965252055e-10 + p * w;
8377 p = 1.5076572693500548083e-09 + p * w;
8378 p = -3.7894654401267369937e-09 + p * w;
8379 p = 7.6157012080783393804e-09 + p * w;
8380 p = -1.4960026627149240478e-08 + p * w;
8381 p = 2.9147953450901080826e-08 + p * w;
8382 p = -6.7711997758452339498e-08 + p * w;
8383 p = 2.2900482228026654717e-07 + p * w;
8384 p = -9.9298272942317002539e-07 + p * w;
8385 p = 4.5260625972231537039e-06 + p * w;
8386 p = -1.9681778105531670567e-05 + p * w;
8387 p = 7.5995277030017761139e-05 + p * w;
8388 p = -0.00021503011930044477347 + p * w;
8389 p = -0.00013871931833623122026 + p * w;
8390 p = 1.0103004648645343977 + p * w;
8391 p = 4.8499064014085844221 + p * w;
8392 }
8393 return p * x;
8394 }
8395
8396 double standard_deviation(std::vector<double>::iterator first, std::vector<double>::iterator last)
8397 {
8398 auto m = Catch::Benchmark::Detail::mean(first, last);
8399 double variance = std::accumulate(first, last, 0.,
8400 [m](double a, double b) {
8401 double diff = b - m;
8402 return a + diff * diff;
8403 }) /
8404 (last - first);
8405 return std::sqrt(variance);
8406 }
8407
8408 } // namespace
8409
8410 namespace Catch {
8411 namespace Benchmark {
8412 namespace Detail {
8413
8414 double weighted_average_quantile(int k, int q, std::vector<double>::iterator first,
8415 std::vector<double>::iterator last)
8416 {
8417 auto count = last - first;
8418 double idx = (count - 1) * k / static_cast<double>(q);
8419 int j = static_cast<int>(idx);
8420 double g = idx - j;
8421 std::nth_element(first, first + j, last);
8422 auto xj = first[j];
8423 if (g == 0)
8424 return xj;
8425
8426 auto xj1 = *std::min_element(first + (j + 1), last);
8427 return xj + g * (xj1 - xj);
8428 }
8429
8430 double erfc_inv(double x) { return erf_inv(1.0 - x); }
8431
8432 double normal_quantile(double p)
8433 {
8434 static const double ROOT_TWO = std::sqrt(2.0);
8435
8436 double result = 0.0;
8437 assert(p >= 0 && p <= 1);
8438 if (p < 0 || p > 1) {
8439 return result;
8440 }
8441
8442 result = -erfc_inv(2.0 * p);
8443 // result *= normal distribution standard deviation (1.0) * sqrt(2)
8444 result *= /*sd * */ ROOT_TWO;
8445 // result += normal disttribution mean (0)
8446 return result;
8447 }
8448
8449 double outlier_variance(Estimate<double> mean, Estimate<double> stddev, int n)
8450 {
8451 double sb = stddev.point;
8452 double mn = mean.point / n;
8453 double mg_min = mn / 2.;
8454 double sg = std::min(mg_min / 4., sb / std::sqrt(n));
8455 double sg2 = sg * sg;
8456 double sb2 = sb * sb;
8457
8458 auto c_max = [n, mn, sb2, sg2](double x) -> double {
8459 double k = mn - x;
8460 double d = k * k;
8461 double nd = n * d;
8462 double k0 = -n * nd;
8463 double k1 = sb2 - n * sg2 + nd;
8464 double det = k1 * k1 - 4 * sg2 * k0;
8465 return (int)(-2. * k0 / (k1 + std::sqrt(det)));
8466 };
8467
8468 auto var_out = [n, sb2, sg2](double c) {
8469 double nc = n - c;
8470 return (nc / n) * (sb2 - nc * sg2);
8471 };
8472
8473 return std::min(var_out(1), var_out(std::min(c_max(0.), c_max(mg_min)))) / sb2;
8474 }
8475
8476 bootstrap_analysis analyse_samples(double confidence_level, int n_resamples,
8477 std::vector<double>::iterator first,
8478 std::vector<double>::iterator last)
8479 {
8480 CATCH_INTERNAL_START_WARNINGS_SUPPRESSION
8481 CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS
8482 static std::random_device entropy;
8483 CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION
8484
8485 auto n = static_cast<int>(
8486 last - first); // seriously, one can't use integral types without hell in C++
8487
8488 auto mean = &Detail::mean<std::vector<double>::iterator>;
8489 auto stddev = &standard_deviation;
8490
8491 #if defined(CATCH_CONFIG_USE_ASYNC)
8492 auto Estimate =
8493 [=](double (*f)(std::vector<double>::iterator, std::vector<double>::iterator)) {
8494 auto seed = entropy();
8495 return std::async(std::launch::async, [=] {
8496 std::mt19937 rng(seed);
8497 auto resampled = resample(rng, n_resamples, first, last, f);
8498 return bootstrap(confidence_level, first, last, resampled, f);
8499 });
8500 };
8501
8502 auto mean_future = Estimate(mean);
8503 auto stddev_future = Estimate(stddev);
8504
8505 auto mean_estimate = mean_future.get();
8506 auto stddev_estimate = stddev_future.get();
8507 #else
8508 auto Estimate =
8509 [=](double (*f)(std::vector<double>::iterator, std::vector<double>::iterator)) {
8510 auto seed = entropy();
8511 std::mt19937 rng(seed);
8512 auto resampled = resample(rng, n_resamples, first, last, f);
8513 return bootstrap(confidence_level, first, last, resampled, f);
8514 };
8515
8516 auto mean_estimate = Estimate(mean);
8517 auto stddev_estimate = Estimate(stddev);
8518 #endif // CATCH_USE_ASYNC
8519
8520 double outlier_variance = Detail::outlier_variance(mean_estimate, stddev_estimate, n);
8521
8522 return {mean_estimate, stddev_estimate, outlier_variance};
8523 }
8524 } // namespace Detail
8525 } // namespace Benchmark
8526 } // namespace Catch
8527
8528 #endif // CATCH_CONFIG_ENABLE_BENCHMARKING
8529 // end catch_stats.cpp
8530 // start catch_approx.cpp
8531
8532 #include <cmath>
8533 #include <limits>
8534
8535 namespace {
8536
8537 // Performs equivalent check of std::fabs(lhs - rhs) <= margin
8538 // But without the subtraction to allow for INFINITY in comparison
8539 bool marginComparison(double lhs, double rhs, double margin)
8540 {
8541 return (lhs + margin >= rhs) && (rhs + margin >= lhs);
8542 }
8543
8544 } // namespace
8545
8546 namespace Catch {
8547 namespace Detail {
8548
8549 Approx::Approx(double value)
8550 : m_epsilon(std::numeric_limits<float>::epsilon() * 100), m_margin(0.0), m_scale(0.0),
8551 m_value(value)
8552 {
8553 }
8554
8555 Approx Approx::custom() { return Approx(0); }
8556
8557 Approx Approx::operator-() const
8558 {
8559 auto temp(*this);
8560 temp.m_value = -temp.m_value;
8561 return temp;
8562 }
8563
8564 std::string Approx::toString() const
8565 {
8566 ReusableStringStream rss;
8567 rss << "Approx( " << ::Catch::Detail::stringify(m_value) << " )";
8568 return rss.str();
8569 }
8570
8571 bool Approx::equalityComparisonImpl(const double other) const
8572 {
8573 // First try with fixed margin, then compute margin based on epsilon, scale and Approx's value
8574 // Thanks to Richard Harris for his help refining the scaled margin value
8575 return marginComparison(m_value, other, m_margin) ||
8576 marginComparison(m_value, other,
8577 m_epsilon * (m_scale + std::fabs(std::isinf(m_value) ? 0 : m_value)));
8578 }
8579
8580 void Approx::setMargin(double newMargin)
8581 {
8582 CATCH_ENFORCE(newMargin >= 0,
8583 "Invalid Approx::margin: " << newMargin << '.'
8584 << " Approx::Margin has to be non-negative.");
8585 m_margin = newMargin;
8586 }
8587
8588 void Approx::setEpsilon(double newEpsilon)
8589 {
8590 CATCH_ENFORCE(newEpsilon >= 0 && newEpsilon <= 1.0,
8591 "Invalid Approx::epsilon: " << newEpsilon << '.'
8592 << " Approx::epsilon has to be in [0, 1]");
8593 m_epsilon = newEpsilon;
8594 }
8595
8596 } // end namespace Detail
8597
8598 namespace literals {
8599 Detail::Approx operator"" _a(long double val) { return Detail::Approx(val); }
8600 Detail::Approx operator"" _a(unsigned long long val) { return Detail::Approx(val); }
8601 } // end namespace literals
8602
8603 std::string StringMaker<Catch::Detail::Approx>::convert(Catch::Detail::Approx const &value)
8604 {
8605 return value.toString();
8606 }
8607
8608 } // end namespace Catch
8609 // end catch_approx.cpp
8610 // start catch_assertionhandler.cpp
8611
8612 // start catch_debugger.h
8613
8614 namespace Catch {
8615 bool isDebuggerActive();
8616 }
8617
8618 #ifdef CATCH_PLATFORM_MAC
8619
8620 #if defined(__i386__) || defined(__x86_64__)
8621 #define CATCH_TRAP() __asm__("int $3\n" : :) /* NOLINT */
8622 #elif defined(__aarch64__)
8623 #define CATCH_TRAP() __asm__(".inst 0xd4200000")
8624 #endif
8625
8626 #elif defined(CATCH_PLATFORM_IPHONE)
8627
8628 // use inline assembler
8629 #if defined(__i386__) || defined(__x86_64__)
8630 #define CATCH_TRAP() __asm__("int $3")
8631 #elif defined(__aarch64__)
8632 #define CATCH_TRAP() __asm__(".inst 0xd4200000")
8633 #elif defined(__arm__) && !defined(__thumb__)
8634 #define CATCH_TRAP() __asm__(".inst 0xe7f001f0")
8635 #elif defined(__arm__) && defined(__thumb__)
8636 #define CATCH_TRAP() __asm__(".inst 0xde01")
8637 #endif
8638
8639 #elif defined(CATCH_PLATFORM_LINUX)
8640 // If we can use inline assembler, do it because this allows us to break
8641 // directly at the location of the failing check instead of breaking inside
8642 // raise() called from it, i.e. one stack frame below.
8643 #if defined(__GNUC__) && (defined(__i386) || defined(__x86_64))
8644 #define CATCH_TRAP() asm volatile("int $3") /* NOLINT */
8645 #else // Fall back to the generic way.
8646 #include <signal.h>
8647
8648 #define CATCH_TRAP() raise(SIGTRAP)
8649 #endif
8650 #elif defined(_MSC_VER)
8651 #define CATCH_TRAP() __debugbreak()
8652 #elif defined(__MINGW32__)
8653 extern "C" __declspec(dllimport) void __stdcall DebugBreak();
8654 #define CATCH_TRAP() DebugBreak()
8655 #endif
8656
8657 #ifndef CATCH_BREAK_INTO_DEBUGGER
8658 #ifdef CATCH_TRAP
8659 #define CATCH_BREAK_INTO_DEBUGGER() \
8660 [] { \
8661 if (Catch::isDebuggerActive()) { \
8662 CATCH_TRAP(); \
8663 } \
8664 }()
8665 #else
8666 #define CATCH_BREAK_INTO_DEBUGGER() [] {}()
8667 #endif
8668 #endif
8669
8670 // end catch_debugger.h
8671 // start catch_run_context.h
8672
8673 // start catch_fatal_condition.h
8674
8675 // start catch_windows_h_proxy.h
8676
8677 #if defined(CATCH_PLATFORM_WINDOWS)
8678
8679 #if !defined(NOMINMAX) && !defined(CATCH_CONFIG_NO_NOMINMAX)
8680 #define CATCH_DEFINED_NOMINMAX
8681 #define NOMINMAX
8682 #endif
8683 #if !defined(WIN32_LEAN_AND_MEAN) && !defined(CATCH_CONFIG_NO_WIN32_LEAN_AND_MEAN)
8684 #define CATCH_DEFINED_WIN32_LEAN_AND_MEAN
8685 #define WIN32_LEAN_AND_MEAN
8686 #endif
8687
8688 #ifdef __AFXDLL
8689 #include <AfxWin.h>
8690 #else
8691 #include <windows.h>
8692 #endif
8693
8694 #ifdef CATCH_DEFINED_NOMINMAX
8695 #undef NOMINMAX
8696 #endif
8697 #ifdef CATCH_DEFINED_WIN32_LEAN_AND_MEAN
8698 #undef WIN32_LEAN_AND_MEAN
8699 #endif
8700
8701 #endif // defined(CATCH_PLATFORM_WINDOWS)
8702
8703 // end catch_windows_h_proxy.h
8704 #if defined(CATCH_CONFIG_WINDOWS_SEH)
8705
8706 namespace Catch {
8707
8708 struct FatalConditionHandler
8709 {
8710
8711 static LONG CALLBACK handleVectoredException(PEXCEPTION_POINTERS ExceptionInfo);
8712 FatalConditionHandler();
8713 static void reset();
8714 ~FatalConditionHandler();
8715
8716 private:
8717 static bool isSet;
8718 static ULONG guaranteeSize;
8719 static PVOID exceptionHandlerHandle;
8720 };
8721
8722 } // namespace Catch
8723
8724 #elif defined(CATCH_CONFIG_POSIX_SIGNALS)
8725
8726 #include <signal.h>
8727
8728 namespace Catch {
8729
8730 struct FatalConditionHandler
8731 {
8732
8733 static bool isSet;
8734 static struct sigaction oldSigActions[];
8735 static stack_t oldSigStack;
8736 static char altStackMem[];
8737
8738 static void handleSignal(int sig);
8739
8740 FatalConditionHandler();
8741 ~FatalConditionHandler();
8742 static void reset();
8743 };
8744
8745 } // namespace Catch
8746
8747 #else
8748
8749 namespace Catch {
8750 struct FatalConditionHandler
8751 {
8752 void reset();
8753 };
8754 } // namespace Catch
8755
8756 #endif
8757
8758 // end catch_fatal_condition.h
8759 #include <string>
8760
8761 namespace Catch {
8762
8763 struct IMutableContext;
8764
8765 ///////////////////////////////////////////////////////////////////////////
8766
8767 class RunContext : public IResultCapture, public IRunner
8768 {
8769
8770 public:
8771 RunContext(RunContext const &) = delete;
8772 RunContext &operator=(RunContext const &) = delete;
8773
8774 explicit RunContext(IConfigPtr const &_config, IStreamingReporterPtr &&reporter);
8775
8776 ~RunContext() override;
8777
8778 void testGroupStarting(std::string const &testSpec, std::size_t groupIndex,
8779 std::size_t groupsCount);
8780 void testGroupEnded(std::string const &testSpec, Totals const &totals, std::size_t groupIndex,
8781 std::size_t groupsCount);
8782
8783 Totals runTest(TestCase const &testCase);
8784
8785 IConfigPtr config() const;
8786 IStreamingReporter &reporter() const;
8787
8788 public: // IResultCapture
8789 // Assertion handlers
8790 void handleExpr(AssertionInfo const &info, ITransientExpression const &expr,
8791 AssertionReaction &reaction) override;
8792 void handleMessage(AssertionInfo const &info, ResultWas::OfType resultType,
8793 StringRef const &message, AssertionReaction &reaction) override;
8794 void handleUnexpectedExceptionNotThrown(AssertionInfo const &info,
8795 AssertionReaction &reaction) override;
8796 void handleUnexpectedInflightException(AssertionInfo const &info, std::string const &message,
8797 AssertionReaction &reaction) override;
8798 void handleIncomplete(AssertionInfo const &info) override;
8799 void handleNonExpr(AssertionInfo const &info, ResultWas::OfType resultType,
8800 AssertionReaction &reaction) override;
8801
8802 bool sectionStarted(SectionInfo const &sectionInfo, Counts &assertions) override;
8803
8804 void sectionEnded(SectionEndInfo const &endInfo) override;
8805 void sectionEndedEarly(SectionEndInfo const &endInfo) override;
8806
8807 auto acquireGeneratorTracker(StringRef generatorName,
8808 SourceLineInfo const &lineInfo) -> IGeneratorTracker & override;
8809
8810 #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
8811 void benchmarkPreparing(std::string const &name) override;
8812 void benchmarkStarting(BenchmarkInfo const &info) override;
8813 void benchmarkEnded(BenchmarkStats<> const &stats) override;
8814 void benchmarkFailed(std::string const &error) override;
8815 #endif // CATCH_CONFIG_ENABLE_BENCHMARKING
8816
8817 void pushScopedMessage(MessageInfo const &message) override;
8818 void popScopedMessage(MessageInfo const &message) override;
8819
8820 void emplaceUnscopedMessage(MessageBuilder const &builder) override;
8821
8822 std::string getCurrentTestName() const override;
8823
8824 const AssertionResult *getLastResult() const override;
8825
8826 void exceptionEarlyReported() override;
8827
8828 void handleFatalErrorCondition(StringRef message) override;
8829
8830 bool lastAssertionPassed() override;
8831
8832 void assertionPassed() override;
8833
8834 public:
8835 // !TBD We need to do this another way!
8836 bool aborting() const final;
8837
8838 private:
8839 void runCurrentTest(std::string &redirectedCout, std::string &redirectedCerr);
8840 void invokeActiveTestCase();
8841
8842 void resetAssertionInfo();
8843 bool testForMissingAssertions(Counts &assertions);
8844
8845 void assertionEnded(AssertionResult const &result);
8846 void reportExpr(AssertionInfo const &info, ResultWas::OfType resultType,
8847 ITransientExpression const *expr, bool negated);
8848
8849 void populateReaction(AssertionReaction &reaction);
8850
8851 private:
8852 void handleUnfinishedSections();
8853
8854 TestRunInfo m_runInfo;
8855 IMutableContext &m_context;
8856 TestCase const *m_activeTestCase = nullptr;
8857 ITracker *m_testCaseTracker = nullptr;
8858 Option<AssertionResult> m_lastResult;
8859
8860 IConfigPtr m_config;
8861 Totals m_totals;
8862 IStreamingReporterPtr m_reporter;
8863 std::vector<MessageInfo> m_messages;
8864 std::vector<ScopedMessage> m_messageScopes; /* Keeps owners of so-called unscoped messages. */
8865 AssertionInfo m_lastAssertionInfo;
8866 std::vector<SectionEndInfo> m_unfinishedSections;
8867 std::vector<ITracker *> m_activeSections;
8868 TrackerContext m_trackerContext;
8869 bool m_lastAssertionPassed = false;
8870 bool m_shouldReportUnexpected = true;
8871 bool m_includeSuccessfulResults;
8872 };
8873
8874 void seedRng(IConfig const &config);
8875 unsigned int rngSeed();
8876 } // end namespace Catch
8877
8878 // end catch_run_context.h
8879 namespace Catch {
8880
8881 namespace {
8882 auto operator<<(std::ostream &os, ITransientExpression const &expr) -> std::ostream &
8883 {
8884 expr.streamReconstructedExpression(os);
8885 return os;
8886 }
8887 } // namespace
8888
8889 LazyExpression::LazyExpression(bool isNegated) : m_isNegated(isNegated) {}
8890
8891 LazyExpression::LazyExpression(LazyExpression const &other) : m_isNegated(other.m_isNegated) {}
8892
8893 LazyExpression::operator bool() const { return m_transientExpression != nullptr; }
8894
8895 auto operator<<(std::ostream &os, LazyExpression const &lazyExpr) -> std::ostream &
8896 {
8897 if (lazyExpr.m_isNegated)
8898 os << "!";
8899
8900 if (lazyExpr) {
8901 if (lazyExpr.m_isNegated && lazyExpr.m_transientExpression->isBinaryExpression())
8902 os << "(" << *lazyExpr.m_transientExpression << ")";
8903 else
8904 os << *lazyExpr.m_transientExpression;
8905 }
8906 else {
8907 os << "{** error - unchecked empty expression requested **}";
8908 }
8909 return os;
8910 }
8911
8912 AssertionHandler::AssertionHandler(StringRef const &macroName, SourceLineInfo const &lineInfo,
8913 StringRef capturedExpression,
8914 ResultDisposition::Flags resultDisposition)
8915 : m_assertionInfo{macroName, lineInfo, capturedExpression, resultDisposition},
8916 m_resultCapture(getResultCapture())
8917 {
8918 }
8919
8920 void AssertionHandler::handleExpr(ITransientExpression const &expr)
8921 {
8922 m_resultCapture.handleExpr(m_assertionInfo, expr, m_reaction);
8923 }
8924 void AssertionHandler::handleMessage(ResultWas::OfType resultType, StringRef const &message)
8925 {
8926 m_resultCapture.handleMessage(m_assertionInfo, resultType, message, m_reaction);
8927 }
8928
8929 auto AssertionHandler::allowThrows() const -> bool
8930 {
8931 return getCurrentContext().getConfig()->allowThrows();
8932 }
8933
8934 void AssertionHandler::complete()
8935 {
8936 setCompleted();
8937 if (m_reaction.shouldDebugBreak) {
8938
8939 // If you find your debugger stopping you here then go one level up on the
8940 // call-stack for the code that caused it (typically a failed assertion)
8941
8942 // (To go back to the test and change execution, jump over the throw, next)
8943 CATCH_BREAK_INTO_DEBUGGER();
8944 }
8945 if (m_reaction.shouldThrow) {
8946 #if !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
8947 throw Catch::TestFailureException();
8948 #else
8949 CATCH_ERROR("Test failure requires aborting test!");
8950 #endif
8951 }
8952 }
8953 void AssertionHandler::setCompleted() { m_completed = true; }
8954
8955 void AssertionHandler::handleUnexpectedInflightException()
8956 {
8957 m_resultCapture.handleUnexpectedInflightException(
8958 m_assertionInfo, Catch::translateActiveException(), m_reaction);
8959 }
8960
8961 void AssertionHandler::handleExceptionThrownAsExpected()
8962 {
8963 m_resultCapture.handleNonExpr(m_assertionInfo, ResultWas::Ok, m_reaction);
8964 }
8965 void AssertionHandler::handleExceptionNotThrownAsExpected()
8966 {
8967 m_resultCapture.handleNonExpr(m_assertionInfo, ResultWas::Ok, m_reaction);
8968 }
8969
8970 void AssertionHandler::handleUnexpectedExceptionNotThrown()
8971 {
8972 m_resultCapture.handleUnexpectedExceptionNotThrown(m_assertionInfo, m_reaction);
8973 }
8974
8975 void AssertionHandler::handleThrowingCallSkipped()
8976 {
8977 m_resultCapture.handleNonExpr(m_assertionInfo, ResultWas::Ok, m_reaction);
8978 }
8979
8980 // This is the overload that takes a string and infers the Equals matcher from it
8981 // The more general overload, that takes any string matcher, is in catch_capture_matchers.cpp
8982 void handleExceptionMatchExpr(AssertionHandler &handler, std::string const &str,
8983 StringRef const &matcherString)
8984 {
8985 handleExceptionMatchExpr(handler, Matchers::Equals(str), matcherString);
8986 }
8987
8988 } // namespace Catch
8989 // end catch_assertionhandler.cpp
8990 // start catch_assertionresult.cpp
8991
8992 namespace Catch {
8993 AssertionResultData::AssertionResultData(ResultWas::OfType _resultType,
8994 LazyExpression const &_lazyExpression)
8995 : lazyExpression(_lazyExpression), resultType(_resultType)
8996 {
8997 }
8998
8999 std::string AssertionResultData::reconstructExpression() const
9000 {
9001
9002 if (reconstructedExpression.empty()) {
9003 if (lazyExpression) {
9004 ReusableStringStream rss;
9005 rss << lazyExpression;
9006 reconstructedExpression = rss.str();
9007 }
9008 }
9009 return reconstructedExpression;
9010 }
9011
9012 AssertionResult::AssertionResult(AssertionInfo const &info, AssertionResultData const &data)
9013 : m_info(info), m_resultData(data)
9014 {
9015 }
9016
9017 // Result was a success
9018 bool AssertionResult::succeeded() const { return Catch::isOk(m_resultData.resultType); }
9019
9020 // Result was a success, or failure is suppressed
9021 bool AssertionResult::isOk() const
9022 {
9023 return Catch::isOk(m_resultData.resultType) || shouldSuppressFailure(m_info.resultDisposition);
9024 }
9025
9026 ResultWas::OfType AssertionResult::getResultType() const { return m_resultData.resultType; }
9027
9028 bool AssertionResult::hasExpression() const { return !m_info.capturedExpression.empty(); }
9029
9030 bool AssertionResult::hasMessage() const { return !m_resultData.message.empty(); }
9031
9032 std::string AssertionResult::getExpression() const
9033 {
9034 // Possibly overallocating by 3 characters should be basically free
9035 std::string expr;
9036 expr.reserve(m_info.capturedExpression.size() + 3);
9037 if (isFalseTest(m_info.resultDisposition)) {
9038 expr += "!(";
9039 }
9040 expr += m_info.capturedExpression;
9041 if (isFalseTest(m_info.resultDisposition)) {
9042 expr += ')';
9043 }
9044 return expr;
9045 }
9046
9047 std::string AssertionResult::getExpressionInMacro() const
9048 {
9049 std::string expr;
9050 if (m_info.macroName.empty())
9051 expr = static_cast<std::string>(m_info.capturedExpression);
9052 else {
9053 expr.reserve(m_info.macroName.size() + m_info.capturedExpression.size() + 4);
9054 expr += m_info.macroName;
9055 expr += "( ";
9056 expr += m_info.capturedExpression;
9057 expr += " )";
9058 }
9059 return expr;
9060 }
9061
9062 bool AssertionResult::hasExpandedExpression() const
9063 {
9064 return hasExpression() && getExpandedExpression() != getExpression();
9065 }
9066
9067 std::string AssertionResult::getExpandedExpression() const
9068 {
9069 std::string expr = m_resultData.reconstructExpression();
9070 return expr.empty() ? getExpression() : expr;
9071 }
9072
9073 std::string AssertionResult::getMessage() const { return m_resultData.message; }
9074 SourceLineInfo AssertionResult::getSourceInfo() const { return m_info.lineInfo; }
9075
9076 StringRef AssertionResult::getTestMacroName() const { return m_info.macroName; }
9077
9078 } // end namespace Catch
9079 // end catch_assertionresult.cpp
9080 // start catch_capture_matchers.cpp
9081
9082 namespace Catch {
9083
9084 using StringMatcher = Matchers::Impl::MatcherBase<std::string>;
9085
9086 // This is the general overload that takes a any string matcher
9087 // There is another overload, in catch_assertionhandler.h/.cpp, that only takes a string and
9088 // infers the Equals matcher (so the header does not mention matchers)
9089 void handleExceptionMatchExpr(AssertionHandler &handler, StringMatcher const &matcher,
9090 StringRef const &matcherString)
9091 {
9092 std::string exceptionMessage = Catch::translateActiveException();
9093 MatchExpr<std::string, StringMatcher const &> expr(exceptionMessage, matcher, matcherString);
9094 handler.handleExpr(expr);
9095 }
9096
9097 } // namespace Catch
9098 // end catch_capture_matchers.cpp
9099 // start catch_commandline.cpp
9100
9101 // start catch_commandline.h
9102
9103 // start catch_clara.h
9104
9105 // Use Catch's value for console width (store Clara's off to the side, if present)
9106 #ifdef CLARA_CONFIG_CONSOLE_WIDTH
9107 #define CATCH_TEMP_CLARA_CONFIG_CONSOLE_WIDTH CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH
9108 #undef CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH
9109 #endif
9110 #define CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH CATCH_CONFIG_CONSOLE_WIDTH - 1
9111
9112 #ifdef __clang__
9113 #pragma clang diagnostic push
9114 #pragma clang diagnostic ignored "-Wweak-vtables"
9115 #pragma clang diagnostic ignored "-Wexit-time-destructors"
9116 #pragma clang diagnostic ignored "-Wshadow"
9117 #endif
9118
9119 // start clara.hpp
9120 // Copyright 2017 Two Blue Cubes Ltd. All rights reserved.
9121 //
9122 // Distributed under the Boost Software License, Version 1.0. (See accompanying
9123 // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
9124 //
9125 // See https://github.com/philsquared/Clara for more details
9126
9127 // Clara v1.1.5
9128
9129 #ifndef CATCH_CLARA_CONFIG_CONSOLE_WIDTH
9130 #define CATCH_CLARA_CONFIG_CONSOLE_WIDTH 80
9131 #endif
9132
9133 #ifndef CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH
9134 #define CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH CATCH_CLARA_CONFIG_CONSOLE_WIDTH
9135 #endif
9136
9137 #ifndef CLARA_CONFIG_OPTIONAL_TYPE
9138 #ifdef __has_include
9139 #if __has_include(<optional>) && __cplusplus >= 201703L
9140 #include <optional>
9141 #define CLARA_CONFIG_OPTIONAL_TYPE std::optional
9142 #endif
9143 #endif
9144 #endif
9145
9146 // ----------- #included from clara_textflow.hpp -----------
9147
9148 // TextFlowCpp
9149 //
9150 // A single-header library for wrapping and laying out basic text, by Phil Nash
9151 //
9152 // Distributed under the Boost Software License, Version 1.0. (See accompanying
9153 // file LICENSE.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
9154 //
9155 // This project is hosted at https://github.com/philsquared/textflowcpp
9156
9157 #include <cassert>
9158 #include <ostream>
9159 #include <sstream>
9160 #include <vector>
9161
9162 #ifndef CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH
9163 #define CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH 80
9164 #endif
9165
9166 namespace Catch {
9167 namespace clara {
9168 namespace TextFlow {
9169
9170 inline auto isWhitespace(char c) -> bool
9171 {
9172 static std::string chars = " \t\n\r";
9173 return chars.find(c) != std::string::npos;
9174 }
9175 inline auto isBreakableBefore(char c) -> bool
9176 {
9177 static std::string chars = "[({<|";
9178 return chars.find(c) != std::string::npos;
9179 }
9180 inline auto isBreakableAfter(char c) -> bool
9181 {
9182 static std::string chars = "])}>.,:;*+-=&/\\";
9183 return chars.find(c) != std::string::npos;
9184 }
9185
9186 class Columns;
9187
9188 class Column
9189 {
9190 std::vector<std::string> m_strings;
9191 size_t m_width = CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH;
9192 size_t m_indent = 0;
9193 size_t m_initialIndent = std::string::npos;
9194
9195 public:
9196 class iterator
9197 {
9198 friend Column;
9199
9200 Column const &m_column;
9201 size_t m_stringIndex = 0;
9202 size_t m_pos = 0;
9203
9204 size_t m_len = 0;
9205 size_t m_end = 0;
9206 bool m_suffix = false;
9207
9208 iterator(Column const &column, size_t stringIndex)
9209 : m_column(column), m_stringIndex(stringIndex)
9210 {
9211 }
9212
9213 auto line() const -> std::string const & { return m_column.m_strings[m_stringIndex]; }
9214
9215 auto isBoundary(size_t at) const -> bool
9216 {
9217 assert(at > 0);
9218 assert(at <= line().size());
9219
9220 return at == line().size() ||
9221 (isWhitespace(line()[at]) && !isWhitespace(line()[at - 1])) ||
9222 isBreakableBefore(line()[at]) || isBreakableAfter(line()[at - 1]);
9223 }
9224
9225 void calcLength()
9226 {
9227 assert(m_stringIndex < m_column.m_strings.size());
9228
9229 m_suffix = false;
9230 auto width = m_column.m_width - indent();
9231 m_end = m_pos;
9232 if (line()[m_pos] == '\n') {
9233 ++m_end;
9234 }
9235 while (m_end < line().size() && line()[m_end] != '\n')
9236 ++m_end;
9237
9238 if (m_end < m_pos + width) {
9239 m_len = m_end - m_pos;
9240 }
9241 else {
9242 size_t len = width;
9243 while (len > 0 && !isBoundary(m_pos + len))
9244 --len;
9245 while (len > 0 && isWhitespace(line()[m_pos + len - 1]))
9246 --len;
9247
9248 if (len > 0) {
9249 m_len = len;
9250 }
9251 else {
9252 m_suffix = true;
9253 m_len = width - 1;
9254 }
9255 }
9256 }
9257
9258 auto indent() const -> size_t
9259 {
9260 auto initial =
9261 m_pos == 0 && m_stringIndex == 0 ? m_column.m_initialIndent : std::string::npos;
9262 return initial == std::string::npos ? m_column.m_indent : initial;
9263 }
9264
9265 auto addIndentAndSuffix(std::string const &plain) const -> std::string
9266 {
9267 return std::string(indent(), ' ') + (m_suffix ? plain + "-" : plain);
9268 }
9269
9270 public:
9271 using difference_type = std::ptrdiff_t;
9272 using value_type = std::string;
9273 using pointer = value_type *;
9274 using reference = value_type &;
9275 using iterator_category = std::forward_iterator_tag;
9276
9277 explicit iterator(Column const &column) : m_column(column)
9278 {
9279 assert(m_column.m_width > m_column.m_indent);
9280 assert(m_column.m_initialIndent == std::string::npos ||
9281 m_column.m_width > m_column.m_initialIndent);
9282 calcLength();
9283 if (m_len == 0)
9284 m_stringIndex++; // Empty string
9285 }
9286
9287 auto operator*() const -> std::string
9288 {
9289 assert(m_stringIndex < m_column.m_strings.size());
9290 assert(m_pos <= m_end);
9291 return addIndentAndSuffix(line().substr(m_pos, m_len));
9292 }
9293
9294 auto operator++() -> iterator &
9295 {
9296 m_pos += m_len;
9297 if (m_pos < line().size() && line()[m_pos] == '\n')
9298 m_pos += 1;
9299 else
9300 while (m_pos < line().size() && isWhitespace(line()[m_pos]))
9301 ++m_pos;
9302
9303 if (m_pos == line().size()) {
9304 m_pos = 0;
9305 ++m_stringIndex;
9306 }
9307 if (m_stringIndex < m_column.m_strings.size())
9308 calcLength();
9309 return *this;
9310 }
9311 auto operator++(int) -> iterator
9312 {
9313 iterator prev(*this);
9314 operator++();
9315 return prev;
9316 }
9317
9318 auto operator==(iterator const &other) const -> bool
9319 {
9320 return m_pos == other.m_pos && m_stringIndex == other.m_stringIndex &&
9321 &m_column == &other.m_column;
9322 }
9323 auto operator!=(iterator const &other) const -> bool { return !operator==(other); }
9324 };
9325 using const_iterator = iterator;
9326
9327 explicit Column(std::string const &text) { m_strings.push_back(text); }
9328
9329 auto width(size_t newWidth) -> Column &
9330 {
9331 assert(newWidth > 0);
9332 m_width = newWidth;
9333 return *this;
9334 }
9335 auto indent(size_t newIndent) -> Column &
9336 {
9337 m_indent = newIndent;
9338 return *this;
9339 }
9340 auto initialIndent(size_t newIndent) -> Column &
9341 {
9342 m_initialIndent = newIndent;
9343 return *this;
9344 }
9345
9346 auto width() const -> size_t { return m_width; }
9347 auto begin() const -> iterator { return iterator(*this); }
9348 auto end() const -> iterator { return {*this, m_strings.size()}; }
9349
9350 inline friend std::ostream &operator<<(std::ostream &os, Column const &col)
9351 {
9352 bool first = true;
9353 for (auto line : col) {
9354 if (first)
9355 first = false;
9356 else
9357 os << "\n";
9358 os << line;
9359 }
9360 return os;
9361 }
9362
9363 auto operator+(Column const &other) -> Columns;
9364
9365 auto toString() const -> std::string
9366 {
9367 std::ostringstream oss;
9368 oss << *this;
9369 return oss.str();
9370 }
9371 };
9372
9373 class Spacer : public Column
9374 {
9375
9376 public:
9377 explicit Spacer(size_t spaceWidth) : Column("") { width(spaceWidth); }
9378 };
9379
9380 class Columns
9381 {
9382 std::vector<Column> m_columns;
9383
9384 public:
9385 class iterator
9386 {
9387 friend Columns;
9388 struct EndTag
9389 {
9390 };
9391
9392 std::vector<Column> const &m_columns;
9393 std::vector<Column::iterator> m_iterators;
9394 size_t m_activeIterators;
9395
9396 iterator(Columns const &columns, EndTag)
9397 : m_columns(columns.m_columns), m_activeIterators(0)
9398 {
9399 m_iterators.reserve(m_columns.size());
9400
9401 for (auto const &col : m_columns)
9402 m_iterators.push_back(col.end());
9403 }
9404
9405 public:
9406 using difference_type = std::ptrdiff_t;
9407 using value_type = std::string;
9408 using pointer = value_type *;
9409 using reference = value_type &;
9410 using iterator_category = std::forward_iterator_tag;
9411
9412 explicit iterator(Columns const &columns)
9413 : m_columns(columns.m_columns), m_activeIterators(m_columns.size())
9414 {
9415 m_iterators.reserve(m_columns.size());
9416
9417 for (auto const &col : m_columns)
9418 m_iterators.push_back(col.begin());
9419 }
9420
9421 auto operator==(iterator const &other) const -> bool
9422 {
9423 return m_iterators == other.m_iterators;
9424 }
9425 auto operator!=(iterator const &other) const -> bool
9426 {
9427 return m_iterators != other.m_iterators;
9428 }
9429 auto operator*() const -> std::string
9430 {
9431 std::string row, padding;
9432
9433 for (size_t i = 0; i < m_columns.size(); ++i) {
9434 auto width = m_columns[i].width();
9435 if (m_iterators[i] != m_columns[i].end()) {
9436 std::string col = *m_iterators[i];
9437 row += padding + col;
9438 if (col.size() < width)
9439 padding = std::string(width - col.size(), ' ');
9440 else
9441 padding = "";
9442 }
9443 else {
9444 padding += std::string(width, ' ');
9445 }
9446 }
9447 return row;
9448 }
9449 auto operator++() -> iterator &
9450 {
9451 for (size_t i = 0; i < m_columns.size(); ++i) {
9452 if (m_iterators[i] != m_columns[i].end())
9453 ++m_iterators[i];
9454 }
9455 return *this;
9456 }
9457 auto operator++(int) -> iterator
9458 {
9459 iterator prev(*this);
9460 operator++();
9461 return prev;
9462 }
9463 };
9464 using const_iterator = iterator;
9465
9466 auto begin() const -> iterator { return iterator(*this); }
9467 auto end() const -> iterator { return {*this, iterator::EndTag()}; }
9468
9469 auto operator+=(Column const &col) -> Columns &
9470 {
9471 m_columns.push_back(col);
9472 return *this;
9473 }
9474 auto operator+(Column const &col) -> Columns
9475 {
9476 Columns combined = *this;
9477 combined += col;
9478 return combined;
9479 }
9480
9481 inline friend std::ostream &operator<<(std::ostream &os, Columns const &cols)
9482 {
9483
9484 bool first = true;
9485 for (auto line : cols) {
9486 if (first)
9487 first = false;
9488 else
9489 os << "\n";
9490 os << line;
9491 }
9492 return os;
9493 }
9494
9495 auto toString() const -> std::string
9496 {
9497 std::ostringstream oss;
9498 oss << *this;
9499 return oss.str();
9500 }
9501 };
9502
9503 inline auto Column::operator+(Column const &other) -> Columns
9504 {
9505 Columns cols;
9506 cols += *this;
9507 cols += other;
9508 return cols;
9509 }
9510 } // namespace TextFlow
9511
9512 } // namespace clara
9513 } // namespace Catch
9514
9515 // ----------- end of #include from clara_textflow.hpp -----------
9516 // ........... back in clara.hpp
9517
9518 #include <algorithm>
9519 #include <cctype>
9520 #include <memory>
9521 #include <set>
9522 #include <string>
9523
9524 #if !defined(CATCH_PLATFORM_WINDOWS) && \
9525 (defined(WIN32) || defined(__WIN32__) || defined(_WIN32) || defined(_MSC_VER))
9526 #define CATCH_PLATFORM_WINDOWS
9527 #endif
9528
9529 namespace Catch {
9530 namespace clara {
9531 namespace detail {
9532
9533 // Traits for extracting arg and return type of lambdas (for single argument lambdas)
9534 template <typename L> struct UnaryLambdaTraits : UnaryLambdaTraits<decltype(&L::operator())>
9535 {
9536 };
9537
9538 template <typename ClassT, typename ReturnT, typename... Args>
9539 struct UnaryLambdaTraits<ReturnT (ClassT::*)(Args...) const>
9540 {
9541 static const bool isValid = false;
9542 };
9543
9544 template <typename ClassT, typename ReturnT, typename ArgT>
9545 struct UnaryLambdaTraits<ReturnT (ClassT::*)(ArgT) const>
9546 {
9547 static const bool isValid = true;
9548 using ArgType =
9549 typename std::remove_const<typename std::remove_reference<ArgT>::type>::type;
9550 using ReturnType = ReturnT;
9551 };
9552
9553 class TokenStream;
9554
9555 // Transport for raw args (copied from main args, or supplied via init list for testing)
9556 class Args
9557 {
9558 friend TokenStream;
9559 std::string m_exeName;
9560 std::vector<std::string> m_args;
9561
9562 public:
9563 Args(int argc, char const *const *argv) : m_exeName(argv[0]), m_args(argv + 1, argv + argc)
9564 {
9565 }
9566
9567 Args(std::initializer_list<std::string> args)
9568 : m_exeName(*args.begin()), m_args(args.begin() + 1, args.end())
9569 {
9570 }
9571
9572 auto exeName() const -> std::string { return m_exeName; }
9573 };
9574
9575 // Wraps a token coming from a token stream. These may not directly correspond to strings as a
9576 // single string may encode an option + its argument if the : or = form is used
9577 enum class TokenType { Option, Argument };
9578 struct Token
9579 {
9580 TokenType type;
9581 std::string token;
9582 };
9583
9584 inline auto isOptPrefix(char c) -> bool
9585 {
9586 return c == '-'
9587 #ifdef CATCH_PLATFORM_WINDOWS
9588 || c == '/'
9589 #endif
9590 ;
9591 }
9592
9593 // Abstracts iterators into args as a stream of tokens, with option arguments uniformly
9594 // handled
9595 class TokenStream
9596 {
9597 using Iterator = std::vector<std::string>::const_iterator;
9598 Iterator it;
9599 Iterator itEnd;
9600 std::vector<Token> m_tokenBuffer;
9601
9602 void loadBuffer()
9603 {
9604 m_tokenBuffer.resize(0);
9605
9606 // Skip any empty strings
9607 while (it != itEnd && it->empty())
9608 ++it;
9609
9610 if (it != itEnd) {
9611 auto const &next = *it;
9612 if (isOptPrefix(next[0])) {
9613 auto delimiterPos = next.find_first_of(" :=");
9614 if (delimiterPos != std::string::npos) {
9615 m_tokenBuffer.push_back({TokenType::Option, next.substr(0, delimiterPos)});
9616 m_tokenBuffer.push_back({TokenType::Argument, next.substr(delimiterPos + 1)});
9617 }
9618 else {
9619 if (next[1] != '-' && next.size() > 2) {
9620 std::string opt = "- ";
9621 for (size_t i = 1; i < next.size(); ++i) {
9622 opt[1] = next[i];
9623 m_tokenBuffer.push_back({TokenType::Option, opt});
9624 }
9625 }
9626 else {
9627 m_tokenBuffer.push_back({TokenType::Option, next});
9628 }
9629 }
9630 }
9631 else {
9632 m_tokenBuffer.push_back({TokenType::Argument, next});
9633 }
9634 }
9635 }
9636
9637 public:
9638 explicit TokenStream(Args const &args) : TokenStream(args.m_args.begin(), args.m_args.end())
9639 {
9640 }
9641
9642 TokenStream(Iterator it, Iterator itEnd) : it(it), itEnd(itEnd) { loadBuffer(); }
9643
9644 explicit operator bool() const { return !m_tokenBuffer.empty() || it != itEnd; }
9645
9646 auto count() const -> size_t { return m_tokenBuffer.size() + (itEnd - it); }
9647
9648 auto operator*() const -> Token
9649 {
9650 assert(!m_tokenBuffer.empty());
9651 return m_tokenBuffer.front();
9652 }
9653
9654 auto operator->() const -> Token const *
9655 {
9656 assert(!m_tokenBuffer.empty());
9657 return &m_tokenBuffer.front();
9658 }
9659
9660 auto operator++() -> TokenStream &
9661 {
9662 if (m_tokenBuffer.size() >= 2) {
9663 m_tokenBuffer.erase(m_tokenBuffer.begin());
9664 }
9665 else {
9666 if (it != itEnd)
9667 ++it;
9668 loadBuffer();
9669 }
9670 return *this;
9671 }
9672 };
9673
9674 class ResultBase
9675 {
9676 public:
9677 enum Type { Ok, LogicError, RuntimeError };
9678
9679 protected:
9680 ResultBase(Type type) : m_type(type) {}
9681 virtual ~ResultBase() = default;
9682
9683 virtual void enforceOk() const = 0;
9684
9685 Type m_type;
9686 };
9687
9688 template <typename T> class ResultValueBase : public ResultBase
9689 {
9690 public:
9691 auto value() const -> T const &
9692 {
9693 enforceOk();
9694 return m_value;
9695 }
9696
9697 protected:
9698 ResultValueBase(Type type) : ResultBase(type) {}
9699
9700 ResultValueBase(ResultValueBase const &other) : ResultBase(other)
9701 {
9702 if (m_type == ResultBase::Ok)
9703 new (&m_value) T(other.m_value);
9704 }
9705
9706 ResultValueBase(Type, T const &value) : ResultBase(Ok) { new (&m_value) T(value); }
9707
9708 auto operator=(ResultValueBase const &other) -> ResultValueBase &
9709 {
9710 if (m_type == ResultBase::Ok)
9711 m_value.~T();
9712 ResultBase::operator=(other);
9713 if (m_type == ResultBase::Ok)
9714 new (&m_value) T(other.m_value);
9715 return *this;
9716 }
9717
9718 ~ResultValueBase() override
9719 {
9720 if (m_type == Ok)
9721 m_value.~T();
9722 }
9723
9724 union {
9725 T m_value;
9726 };
9727 };
9728
9729 template <> class ResultValueBase<void> : public ResultBase
9730 {
9731 protected:
9732 using ResultBase::ResultBase;
9733 };
9734
9735 template <typename T = void> class BasicResult : public ResultValueBase<T>
9736 {
9737 public:
9738 template <typename U>
9739 explicit BasicResult(BasicResult<U> const &other)
9740 : ResultValueBase<T>(other.type()), m_errorMessage(other.errorMessage())
9741 {
9742 assert(type() != ResultBase::Ok);
9743 }
9744
9745 template <typename U> static auto ok(U const &value) -> BasicResult
9746 {
9747 return {ResultBase::Ok, value};
9748 }
9749 static auto ok() -> BasicResult { return {ResultBase::Ok}; }
9750 static auto logicError(std::string const &message) -> BasicResult
9751 {
9752 return {ResultBase::LogicError, message};
9753 }
9754 static auto runtimeError(std::string const &message) -> BasicResult
9755 {
9756 return {ResultBase::RuntimeError, message};
9757 }
9758
9759 explicit operator bool() const { return m_type == ResultBase::Ok; }
9760 auto type() const -> ResultBase::Type { return m_type; }
9761 auto errorMessage() const -> std::string { return m_errorMessage; }
9762
9763 protected:
9764 void enforceOk() const override
9765 {
9766
9767 // Errors shouldn't reach this point, but if they do
9768 // the actual error message will be in m_errorMessage
9769 assert(m_type != ResultBase::LogicError);
9770 assert(m_type != ResultBase::RuntimeError);
9771 if (m_type != ResultBase::Ok)
9772 std::abort();
9773 }
9774
9775 std::string m_errorMessage; // Only populated if resultType is an error
9776
9777 BasicResult(ResultBase::Type type, std::string const &message)
9778 : ResultValueBase<T>(type), m_errorMessage(message)
9779 {
9780 assert(m_type != ResultBase::Ok);
9781 }
9782
9783 using ResultValueBase<T>::ResultValueBase;
9784 using ResultBase::m_type;
9785 };
9786
9787 enum class ParseResultType { Matched, NoMatch, ShortCircuitAll, ShortCircuitSame };
9788
9789 class ParseState
9790 {
9791 public:
9792 ParseState(ParseResultType type, TokenStream const &remainingTokens)
9793 : m_type(type), m_remainingTokens(remainingTokens)
9794 {
9795 }
9796
9797 auto type() const -> ParseResultType { return m_type; }
9798 auto remainingTokens() const -> TokenStream { return m_remainingTokens; }
9799
9800 private:
9801 ParseResultType m_type;
9802 TokenStream m_remainingTokens;
9803 };
9804
9805 using Result = BasicResult<void>;
9806 using ParserResult = BasicResult<ParseResultType>;
9807 using InternalParseResult = BasicResult<ParseState>;
9808
9809 struct HelpColumns
9810 {
9811 std::string left;
9812 std::string right;
9813 };
9814
9815 template <typename T>
9816 inline auto convertInto(std::string const &source, T &target) -> ParserResult
9817 {
9818 std::stringstream ss;
9819 ss << source;
9820 ss >> target;
9821 if (ss.fail())
9822 return ParserResult::runtimeError("Unable to convert '" + source +
9823 "' to destination type");
9824 else
9825 return ParserResult::ok(ParseResultType::Matched);
9826 }
9827 inline auto convertInto(std::string const &source, std::string &target) -> ParserResult
9828 {
9829 target = source;
9830 return ParserResult::ok(ParseResultType::Matched);
9831 }
9832 inline auto convertInto(std::string const &source, bool &target) -> ParserResult
9833 {
9834 std::string srcLC = source;
9835 std::transform(srcLC.begin(), srcLC.end(), srcLC.begin(),
9836 [](unsigned char c) { return static_cast<char>(std::tolower(c)); });
9837 if (srcLC == "y" || srcLC == "1" || srcLC == "true" || srcLC == "yes" || srcLC == "on")
9838 target = true;
9839 else if (srcLC == "n" || srcLC == "0" || srcLC == "false" || srcLC == "no" ||
9840 srcLC == "off")
9841 target = false;
9842 else
9843 return ParserResult::runtimeError("Expected a boolean value but did not recognise: '" +
9844 source + "'");
9845 return ParserResult::ok(ParseResultType::Matched);
9846 }
9847 #ifdef CLARA_CONFIG_OPTIONAL_TYPE
9848 template <typename T>
9849 inline auto convertInto(std::string const &source,
9850 CLARA_CONFIG_OPTIONAL_TYPE<T> &target) -> ParserResult
9851 {
9852 T temp;
9853 auto result = convertInto(source, temp);
9854 if (result)
9855 target = std::move(temp);
9856 return result;
9857 }
9858 #endif // CLARA_CONFIG_OPTIONAL_TYPE
9859
9860 struct NonCopyable
9861 {
9862 NonCopyable() = default;
9863 NonCopyable(NonCopyable const &) = delete;
9864 NonCopyable(NonCopyable &&) = delete;
9865 NonCopyable &operator=(NonCopyable const &) = delete;
9866 NonCopyable &operator=(NonCopyable &&) = delete;
9867 };
9868
9869 struct BoundRef : NonCopyable
9870 {
9871 virtual ~BoundRef() = default;
9872 virtual auto isContainer() const -> bool { return false; }
9873 virtual auto isFlag() const -> bool { return false; }
9874 };
9875 struct BoundValueRefBase : BoundRef
9876 {
9877 virtual auto setValue(std::string const &arg) -> ParserResult = 0;
9878 };
9879 struct BoundFlagRefBase : BoundRef
9880 {
9881 virtual auto setFlag(bool flag) -> ParserResult = 0;
9882 virtual auto isFlag() const -> bool { return true; }
9883 };
9884
9885 template <typename T> struct BoundValueRef : BoundValueRefBase
9886 {
9887 T &m_ref;
9888
9889 explicit BoundValueRef(T &ref) : m_ref(ref) {}
9890
9891 auto setValue(std::string const &arg) -> ParserResult override
9892 {
9893 return convertInto(arg, m_ref);
9894 }
9895 };
9896
9897 template <typename T> struct BoundValueRef<std::vector<T>> : BoundValueRefBase
9898 {
9899 std::vector<T> &m_ref;
9900
9901 explicit BoundValueRef(std::vector<T> &ref) : m_ref(ref) {}
9902
9903 auto isContainer() const -> bool override { return true; }
9904
9905 auto setValue(std::string const &arg) -> ParserResult override
9906 {
9907 T temp;
9908 auto result = convertInto(arg, temp);
9909 if (result)
9910 m_ref.push_back(temp);
9911 return result;
9912 }
9913 };
9914
9915 struct BoundFlagRef : BoundFlagRefBase
9916 {
9917 bool &m_ref;
9918
9919 explicit BoundFlagRef(bool &ref) : m_ref(ref) {}
9920
9921 auto setFlag(bool flag) -> ParserResult override
9922 {
9923 m_ref = flag;
9924 return ParserResult::ok(ParseResultType::Matched);
9925 }
9926 };
9927
9928 template <typename ReturnType> struct LambdaInvoker
9929 {
9930 static_assert(std::is_same<ReturnType, ParserResult>::value,
9931 "Lambda must return void or clara::ParserResult");
9932
9933 template <typename L, typename ArgType>
9934 static auto invoke(L const &lambda, ArgType const &arg) -> ParserResult
9935 {
9936 return lambda(arg);
9937 }
9938 };
9939
9940 template <> struct LambdaInvoker<void>
9941 {
9942 template <typename L, typename ArgType>
9943 static auto invoke(L const &lambda, ArgType const &arg) -> ParserResult
9944 {
9945 lambda(arg);
9946 return ParserResult::ok(ParseResultType::Matched);
9947 }
9948 };
9949
9950 template <typename ArgType, typename L>
9951 inline auto invokeLambda(L const &lambda, std::string const &arg) -> ParserResult
9952 {
9953 ArgType temp{};
9954 auto result = convertInto(arg, temp);
9955 return !result
9956 ? result
9957 : LambdaInvoker<typename UnaryLambdaTraits<L>::ReturnType>::invoke(lambda, temp);
9958 }
9959
9960 template <typename L> struct BoundLambda : BoundValueRefBase
9961 {
9962 L m_lambda;
9963
9964 static_assert(UnaryLambdaTraits<L>::isValid,
9965 "Supplied lambda must take exactly one argument");
9966 explicit BoundLambda(L const &lambda) : m_lambda(lambda) {}
9967
9968 auto setValue(std::string const &arg) -> ParserResult override
9969 {
9970 return invokeLambda<typename UnaryLambdaTraits<L>::ArgType>(m_lambda, arg);
9971 }
9972 };
9973
9974 template <typename L> struct BoundFlagLambda : BoundFlagRefBase
9975 {
9976 L m_lambda;
9977
9978 static_assert(UnaryLambdaTraits<L>::isValid,
9979 "Supplied lambda must take exactly one argument");
9980 static_assert(std::is_same<typename UnaryLambdaTraits<L>::ArgType, bool>::value,
9981 "flags must be boolean");
9982
9983 explicit BoundFlagLambda(L const &lambda) : m_lambda(lambda) {}
9984
9985 auto setFlag(bool flag) -> ParserResult override
9986 {
9987 return LambdaInvoker<typename UnaryLambdaTraits<L>::ReturnType>::invoke(m_lambda, flag);
9988 }
9989 };
9990
9991 enum class Optionality { Optional, Required };
9992
9993 struct Parser;
9994
9995 class ParserBase
9996 {
9997 public:
9998 virtual ~ParserBase() = default;
9999 virtual auto validate() const -> Result { return Result::ok(); }
10000 virtual auto parse(std::string const &exeName,
10001 TokenStream const &tokens) const -> InternalParseResult = 0;
10002 virtual auto cardinality() const -> size_t { return 1; }
10003
10004 auto parse(Args const &args) const -> InternalParseResult
10005 {
10006 return parse(args.exeName(), TokenStream(args));
10007 }
10008 };
10009
10010 template <typename DerivedT> class ComposableParserImpl : public ParserBase
10011 {
10012 public:
10013 template <typename T> auto operator|(T const &other) const -> Parser;
10014
10015 template <typename T> auto operator+(T const &other) const -> Parser;
10016 };
10017
10018 // Common code and state for Args and Opts
10019 template <typename DerivedT> class ParserRefImpl : public ComposableParserImpl<DerivedT>
10020 {
10021 protected:
10022 Optionality m_optionality = Optionality::Optional;
10023 std::shared_ptr<BoundRef> m_ref;
10024 std::string m_hint;
10025 std::string m_description;
10026
10027 explicit ParserRefImpl(std::shared_ptr<BoundRef> const &ref) : m_ref(ref) {}
10028
10029 public:
10030 template <typename T>
10031 ParserRefImpl(T &ref, std::string const &hint)
10032 : m_ref(std::make_shared<BoundValueRef<T>>(ref)), m_hint(hint)
10033 {
10034 }
10035
10036 template <typename LambdaT>
10037 ParserRefImpl(LambdaT const &ref, std::string const &hint)
10038 : m_ref(std::make_shared<BoundLambda<LambdaT>>(ref)), m_hint(hint)
10039 {
10040 }
10041
10042 auto operator()(std::string const &description) -> DerivedT &
10043 {
10044 m_description = description;
10045 return static_cast<DerivedT &>(*this);
10046 }
10047
10048 auto optional() -> DerivedT &
10049 {
10050 m_optionality = Optionality::Optional;
10051 return static_cast<DerivedT &>(*this);
10052 };
10053
10054 auto required() -> DerivedT &
10055 {
10056 m_optionality = Optionality::Required;
10057 return static_cast<DerivedT &>(*this);
10058 };
10059
10060 auto isOptional() const -> bool { return m_optionality == Optionality::Optional; }
10061
10062 auto cardinality() const -> size_t override
10063 {
10064 if (m_ref->isContainer())
10065 return 0;
10066 else
10067 return 1;
10068 }
10069
10070 auto hint() const -> std::string { return m_hint; }
10071 };
10072
10073 class ExeName : public ComposableParserImpl<ExeName>
10074 {
10075 std::shared_ptr<std::string> m_name;
10076 std::shared_ptr<BoundValueRefBase> m_ref;
10077
10078 template <typename LambdaT>
10079 static auto makeRef(LambdaT const &lambda) -> std::shared_ptr<BoundValueRefBase>
10080 {
10081 return std::make_shared<BoundLambda<LambdaT>>(lambda);
10082 }
10083
10084 public:
10085 ExeName() : m_name(std::make_shared<std::string>("<executable>")) {}
10086
10087 explicit ExeName(std::string &ref) : ExeName()
10088 {
10089 m_ref = std::make_shared<BoundValueRef<std::string>>(ref);
10090 }
10091
10092 template <typename LambdaT> explicit ExeName(LambdaT const &lambda) : ExeName()
10093 {
10094 m_ref = std::make_shared<BoundLambda<LambdaT>>(lambda);
10095 }
10096
10097 // The exe name is not parsed out of the normal tokens, but is handled specially
10098 auto parse(std::string const &,
10099 TokenStream const &tokens) const -> InternalParseResult override
10100 {
10101 return InternalParseResult::ok(ParseState(ParseResultType::NoMatch, tokens));
10102 }
10103
10104 auto name() const -> std::string { return *m_name; }
10105 auto set(std::string const &newName) -> ParserResult
10106 {
10107
10108 auto lastSlash = newName.find_last_of("\\/");
10109 auto filename =
10110 (lastSlash == std::string::npos) ? newName : newName.substr(lastSlash + 1);
10111
10112 *m_name = filename;
10113 if (m_ref)
10114 return m_ref->setValue(filename);
10115 else
10116 return ParserResult::ok(ParseResultType::Matched);
10117 }
10118 };
10119
10120 class Arg : public ParserRefImpl<Arg>
10121 {
10122 public:
10123 using ParserRefImpl::ParserRefImpl;
10124
10125 auto parse(std::string const &,
10126 TokenStream const &tokens) const -> InternalParseResult override
10127 {
10128 auto validationResult = validate();
10129 if (!validationResult)
10130 return InternalParseResult(validationResult);
10131
10132 auto remainingTokens = tokens;
10133 auto const &token = *remainingTokens;
10134 if (token.type != TokenType::Argument)
10135 return InternalParseResult::ok(ParseState(ParseResultType::NoMatch, remainingTokens));
10136
10137 assert(!m_ref->isFlag());
10138 auto valueRef = static_cast<detail::BoundValueRefBase *>(m_ref.get());
10139
10140 auto result = valueRef->setValue(remainingTokens->token);
10141 if (!result)
10142 return InternalParseResult(result);
10143 else
10144 return InternalParseResult::ok(ParseState(ParseResultType::Matched, ++remainingTokens));
10145 }
10146 };
10147
10148 inline auto normaliseOpt(std::string const &optName) -> std::string
10149 {
10150 #ifdef CATCH_PLATFORM_WINDOWS
10151 if (optName[0] == '/')
10152 return "-" + optName.substr(1);
10153 else
10154 #endif
10155 return optName;
10156 }
10157
10158 class Opt : public ParserRefImpl<Opt>
10159 {
10160 protected:
10161 std::vector<std::string> m_optNames;
10162
10163 public:
10164 template <typename LambdaT>
10165 explicit Opt(LambdaT const &ref)
10166 : ParserRefImpl(std::make_shared<BoundFlagLambda<LambdaT>>(ref))
10167 {
10168 }
10169
10170 explicit Opt(bool &ref) : ParserRefImpl(std::make_shared<BoundFlagRef>(ref)) {}
10171
10172 template <typename LambdaT>
10173 Opt(LambdaT const &ref, std::string const &hint) : ParserRefImpl(ref, hint)
10174 {
10175 }
10176
10177 template <typename T> Opt(T &ref, std::string const &hint) : ParserRefImpl(ref, hint) {}
10178
10179 auto operator[](std::string const &optName) -> Opt &
10180 {
10181 m_optNames.push_back(optName);
10182 return *this;
10183 }
10184
10185 auto getHelpColumns() const -> std::vector<HelpColumns>
10186 {
10187 std::ostringstream oss;
10188 bool first = true;
10189 for (auto const &opt : m_optNames) {
10190 if (first)
10191 first = false;
10192 else
10193 oss << ", ";
10194 oss << opt;
10195 }
10196 if (!m_hint.empty())
10197 oss << " <" << m_hint << ">";
10198 return {{oss.str(), m_description}};
10199 }
10200
10201 auto isMatch(std::string const &optToken) const -> bool
10202 {
10203 auto normalisedToken = normaliseOpt(optToken);
10204 for (auto const &name : m_optNames) {
10205 if (normaliseOpt(name) == normalisedToken)
10206 return true;
10207 }
10208 return false;
10209 }
10210
10211 using ParserBase::parse;
10212
10213 auto parse(std::string const &,
10214 TokenStream const &tokens) const -> InternalParseResult override
10215 {
10216 auto validationResult = validate();
10217 if (!validationResult)
10218 return InternalParseResult(validationResult);
10219
10220 auto remainingTokens = tokens;
10221 if (remainingTokens && remainingTokens->type == TokenType::Option) {
10222 auto const &token = *remainingTokens;
10223 if (isMatch(token.token)) {
10224 if (m_ref->isFlag()) {
10225 auto flagRef = static_cast<detail::BoundFlagRefBase *>(m_ref.get());
10226 auto result = flagRef->setFlag(true);
10227 if (!result)
10228 return InternalParseResult(result);
10229 if (result.value() == ParseResultType::ShortCircuitAll)
10230 return InternalParseResult::ok(ParseState(result.value(), remainingTokens));
10231 }
10232 else {
10233 auto valueRef = static_cast<detail::BoundValueRefBase *>(m_ref.get());
10234 ++remainingTokens;
10235 if (!remainingTokens)
10236 return InternalParseResult::runtimeError("Expected argument following " +
10237 token.token);
10238 auto const &argToken = *remainingTokens;
10239 if (argToken.type != TokenType::Argument)
10240 return InternalParseResult::runtimeError("Expected argument following " +
10241 token.token);
10242 auto result = valueRef->setValue(argToken.token);
10243 if (!result)
10244 return InternalParseResult(result);
10245 if (result.value() == ParseResultType::ShortCircuitAll)
10246 return InternalParseResult::ok(ParseState(result.value(), remainingTokens));
10247 }
10248 return InternalParseResult::ok(
10249 ParseState(ParseResultType::Matched, ++remainingTokens));
10250 }
10251 }
10252 return InternalParseResult::ok(ParseState(ParseResultType::NoMatch, remainingTokens));
10253 }
10254
10255 auto validate() const -> Result override
10256 {
10257 if (m_optNames.empty())
10258 return Result::logicError("No options supplied to Opt");
10259 for (auto const &name : m_optNames) {
10260 if (name.empty())
10261 return Result::logicError("Option name cannot be empty");
10262 #ifdef CATCH_PLATFORM_WINDOWS
10263 if (name[0] != '-' && name[0] != '/')
10264 return Result::logicError("Option name must begin with '-' or '/'");
10265 #else
10266 if (name[0] != '-')
10267 return Result::logicError("Option name must begin with '-'");
10268 #endif
10269 }
10270 return ParserRefImpl::validate();
10271 }
10272 };
10273
10274 struct Help : Opt
10275 {
10276 Help(bool &showHelpFlag)
10277 : Opt([&](bool flag) {
10278 showHelpFlag = flag;
10279 return ParserResult::ok(ParseResultType::ShortCircuitAll);
10280 })
10281 {
10282 static_cast<Opt &>(*this)("display usage information")["-?"]["-h"]["--help"].optional();
10283 }
10284 };
10285
10286 struct Parser : ParserBase
10287 {
10288
10289 mutable ExeName m_exeName;
10290 std::vector<Opt> m_options;
10291 std::vector<Arg> m_args;
10292
10293 auto operator|=(ExeName const &exeName) -> Parser &
10294 {
10295 m_exeName = exeName;
10296 return *this;
10297 }
10298
10299 auto operator|=(Arg const &arg) -> Parser &
10300 {
10301 m_args.push_back(arg);
10302 return *this;
10303 }
10304
10305 auto operator|=(Opt const &opt) -> Parser &
10306 {
10307 m_options.push_back(opt);
10308 return *this;
10309 }
10310
10311 auto operator|=(Parser const &other) -> Parser &
10312 {
10313 m_options.insert(m_options.end(), other.m_options.begin(), other.m_options.end());
10314 m_args.insert(m_args.end(), other.m_args.begin(), other.m_args.end());
10315 return *this;
10316 }
10317
10318 template <typename T> auto operator|(T const &other) const -> Parser
10319 {
10320 return Parser(*this) |= other;
10321 }
10322
10323 // Forward deprecated interface with '+' instead of '|'
10324 template <typename T> auto operator+=(T const &other) -> Parser &
10325 {
10326 return operator|=(other);
10327 }
10328 template <typename T> auto operator+(T const &other) const -> Parser
10329 {
10330 return operator|(other);
10331 }
10332
10333 auto getHelpColumns() const -> std::vector<HelpColumns>
10334 {
10335 std::vector<HelpColumns> cols;
10336 for (auto const &o : m_options) {
10337 auto childCols = o.getHelpColumns();
10338 cols.insert(cols.end(), childCols.begin(), childCols.end());
10339 }
10340 return cols;
10341 }
10342
10343 void writeToStream(std::ostream &os) const
10344 {
10345 if (!m_exeName.name().empty()) {
10346 os << "usage:\n" << " " << m_exeName.name() << " ";
10347 bool required = true, first = true;
10348 for (auto const &arg : m_args) {
10349 if (first)
10350 first = false;
10351 else
10352 os << " ";
10353 if (arg.isOptional() && required) {
10354 os << "[";
10355 required = false;
10356 }
10357 os << "<" << arg.hint() << ">";
10358 if (arg.cardinality() == 0)
10359 os << " ... ";
10360 }
10361 if (!required)
10362 os << "]";
10363 if (!m_options.empty())
10364 os << " options";
10365 os << "\n\nwhere options are:" << std::endl;
10366 }
10367
10368 auto rows = getHelpColumns();
10369 size_t consoleWidth = CATCH_CLARA_CONFIG_CONSOLE_WIDTH;
10370 size_t optWidth = 0;
10371 for (auto const &cols : rows)
10372 optWidth = (std::max)(optWidth, cols.left.size() + 2);
10373
10374 optWidth = (std::min)(optWidth, consoleWidth / 2);
10375
10376 for (auto const &cols : rows) {
10377 auto row = TextFlow::Column(cols.left).width(optWidth).indent(2) + TextFlow::Spacer(4) +
10378 TextFlow::Column(cols.right).width(consoleWidth - 7 - optWidth);
10379 os << row << std::endl;
10380 }
10381 }
10382
10383 friend auto operator<<(std::ostream &os, Parser const &parser) -> std::ostream &
10384 {
10385 parser.writeToStream(os);
10386 return os;
10387 }
10388
10389 auto validate() const -> Result override
10390 {
10391 for (auto const &opt : m_options) {
10392 auto result = opt.validate();
10393 if (!result)
10394 return result;
10395 }
10396 for (auto const &arg : m_args) {
10397 auto result = arg.validate();
10398 if (!result)
10399 return result;
10400 }
10401 return Result::ok();
10402 }
10403
10404 using ParserBase::parse;
10405
10406 auto parse(std::string const &exeName,
10407 TokenStream const &tokens) const -> InternalParseResult override
10408 {
10409
10410 struct ParserInfo
10411 {
10412 ParserBase const *parser = nullptr;
10413 size_t count = 0;
10414 };
10415 const size_t totalParsers = m_options.size() + m_args.size();
10416 assert(totalParsers < 512);
10417 // ParserInfo parseInfos[totalParsers]; // <-- this is what we really want to do
10418 ParserInfo parseInfos[512];
10419
10420 {
10421 size_t i = 0;
10422 for (auto const &opt : m_options)
10423 parseInfos[i++].parser = &opt;
10424 for (auto const &arg : m_args)
10425 parseInfos[i++].parser = &arg;
10426 }
10427
10428 m_exeName.set(exeName);
10429
10430 auto result = InternalParseResult::ok(ParseState(ParseResultType::NoMatch, tokens));
10431 while (result.value().remainingTokens()) {
10432 bool tokenParsed = false;
10433
10434 for (size_t i = 0; i < totalParsers; ++i) {
10435 auto &parseInfo = parseInfos[i];
10436 if (parseInfo.parser->cardinality() == 0 ||
10437 parseInfo.count < parseInfo.parser->cardinality()) {
10438 result = parseInfo.parser->parse(exeName, result.value().remainingTokens());
10439 if (!result)
10440 return result;
10441 if (result.value().type() != ParseResultType::NoMatch) {
10442 tokenParsed = true;
10443 ++parseInfo.count;
10444 break;
10445 }
10446 }
10447 }
10448
10449 if (result.value().type() == ParseResultType::ShortCircuitAll)
10450 return result;
10451 if (!tokenParsed)
10452 return InternalParseResult::runtimeError("Unrecognised token: " +
10453 result.value().remainingTokens()->token);
10454 }
10455 // !TBD Check missing required options
10456 return result;
10457 }
10458 };
10459
10460 template <typename DerivedT>
10461 template <typename T>
10462 auto ComposableParserImpl<DerivedT>::operator|(T const &other) const -> Parser
10463 {
10464 return Parser() | static_cast<DerivedT const &>(*this) | other;
10465 }
10466 } // namespace detail
10467
10468 // A Combined parser
10469 using detail::Parser;
10470
10471 // A parser for options
10472 using detail::Opt;
10473
10474 // A parser for arguments
10475 using detail::Arg;
10476
10477 // Wrapper for argc, argv from main()
10478 using detail::Args;
10479
10480 // Specifies the name of the executable
10481 using detail::ExeName;
10482
10483 // Convenience wrapper for option parser that specifies the help option
10484 using detail::Help;
10485
10486 // enum of result types from a parse
10487 using detail::ParseResultType;
10488
10489 // Result type for parser operation
10490 using detail::ParserResult;
10491
10492 } // namespace clara
10493 } // namespace Catch
10494
10495 // end clara.hpp
10496 #ifdef __clang__
10497 #pragma clang diagnostic pop
10498 #endif
10499
10500 // Restore Clara's value for console width, if present
10501 #ifdef CATCH_TEMP_CLARA_CONFIG_CONSOLE_WIDTH
10502 #define CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH CATCH_TEMP_CLARA_CONFIG_CONSOLE_WIDTH
10503 #undef CATCH_TEMP_CLARA_CONFIG_CONSOLE_WIDTH
10504 #endif
10505
10506 // end catch_clara.h
10507 namespace Catch {
10508
10509 clara::Parser makeCommandLineParser(ConfigData &config);
10510
10511 } // end namespace Catch
10512
10513 // end catch_commandline.h
10514 #include <ctime>
10515 #include <fstream>
10516
10517 namespace Catch {
10518
10519 clara::Parser makeCommandLineParser(ConfigData &config)
10520 {
10521
10522 using namespace clara;
10523
10524 auto const setWarning = [&](std::string const &warning) {
10525 auto warningSet = [&]() {
10526 if (warning == "NoAssertions")
10527 return WarnAbout::NoAssertions;
10528
10529 if (warning == "NoTests")
10530 return WarnAbout::NoTests;
10531
10532 return WarnAbout::Nothing;
10533 }();
10534
10535 if (warningSet == WarnAbout::Nothing)
10536 return ParserResult::runtimeError("Unrecognised warning: '" + warning + "'");
10537 config.warnings = static_cast<WarnAbout::What>(config.warnings | warningSet);
10538 return ParserResult::ok(ParseResultType::Matched);
10539 };
10540 auto const loadTestNamesFromFile = [&](std::string const &filename) {
10541 std::ifstream f(filename.c_str());
10542 if (!f.is_open())
10543 return ParserResult::runtimeError("Unable to load input file: '" + filename + "'");
10544
10545 std::string line;
10546 while (std::getline(f, line)) {
10547 line = trim(line);
10548 if (!line.empty() && !startsWith(line, '#')) {
10549 if (!startsWith(line, '"'))
10550 line = '"' + line + '"';
10551 config.testsOrTags.push_back(line);
10552 config.testsOrTags.emplace_back(",");
10553 }
10554 }
10555 // Remove comma in the end
10556 if (!config.testsOrTags.empty())
10557 config.testsOrTags.erase(config.testsOrTags.end() - 1);
10558
10559 return ParserResult::ok(ParseResultType::Matched);
10560 };
10561 auto const setTestOrder = [&](std::string const &order) {
10562 if (startsWith("declared", order))
10563 config.runOrder = RunTests::InDeclarationOrder;
10564 else if (startsWith("lexical", order))
10565 config.runOrder = RunTests::InLexicographicalOrder;
10566 else if (startsWith("random", order))
10567 config.runOrder = RunTests::InRandomOrder;
10568 else
10569 return clara::ParserResult::runtimeError("Unrecognised ordering: '" + order + "'");
10570 return ParserResult::ok(ParseResultType::Matched);
10571 };
10572 auto const setRngSeed = [&](std::string const &seed) {
10573 if (seed != "time")
10574 return clara::detail::convertInto(seed, config.rngSeed);
10575 config.rngSeed = static_cast<unsigned int>(std::time(nullptr));
10576 return ParserResult::ok(ParseResultType::Matched);
10577 };
10578 auto const setColourUsage = [&](std::string const &useColour) {
10579 auto mode = toLower(useColour);
10580
10581 if (mode == "yes")
10582 config.useColour = UseColour::Yes;
10583 else if (mode == "no")
10584 config.useColour = UseColour::No;
10585 else if (mode == "auto")
10586 config.useColour = UseColour::Auto;
10587 else
10588 return ParserResult::runtimeError("colour mode must be one of: auto, yes or no. '" +
10589 useColour + "' not recognised");
10590 return ParserResult::ok(ParseResultType::Matched);
10591 };
10592 auto const setWaitForKeypress = [&](std::string const &keypress) {
10593 auto keypressLc = toLower(keypress);
10594 if (keypressLc == "never")
10595 config.waitForKeypress = WaitForKeypress::Never;
10596 else if (keypressLc == "start")
10597 config.waitForKeypress = WaitForKeypress::BeforeStart;
10598 else if (keypressLc == "exit")
10599 config.waitForKeypress = WaitForKeypress::BeforeExit;
10600 else if (keypressLc == "both")
10601 config.waitForKeypress = WaitForKeypress::BeforeStartAndExit;
10602 else
10603 return ParserResult::runtimeError(
10604 "keypress argument must be one of: never, start, exit or both. '" + keypress +
10605 "' not recognised");
10606 return ParserResult::ok(ParseResultType::Matched);
10607 };
10608 auto const setVerbosity = [&](std::string const &verbosity) {
10609 auto lcVerbosity = toLower(verbosity);
10610 if (lcVerbosity == "quiet")
10611 config.verbosity = Verbosity::Quiet;
10612 else if (lcVerbosity == "normal")
10613 config.verbosity = Verbosity::Normal;
10614 else if (lcVerbosity == "high")
10615 config.verbosity = Verbosity::High;
10616 else
10617 return ParserResult::runtimeError("Unrecognised verbosity, '" + verbosity + "'");
10618 return ParserResult::ok(ParseResultType::Matched);
10619 };
10620 auto const setReporter = [&](std::string const &reporter) {
10621 IReporterRegistry::FactoryMap const &factories =
10622 getRegistryHub().getReporterRegistry().getFactories();
10623
10624 auto lcReporter = toLower(reporter);
10625 auto result = factories.find(lcReporter);
10626
10627 if (factories.end() != result)
10628 config.reporterName = lcReporter;
10629 else
10630 return ParserResult::runtimeError("Unrecognized reporter, '" + reporter +
10631 "'. Check available with --list-reporters");
10632 return ParserResult::ok(ParseResultType::Matched);
10633 };
10634
10635 auto cli =
10636 ExeName(config.processName) | Help(config.showHelp) |
10637 Opt(config.listTests)["-l"]["--list-tests"]("list all/matching test cases") |
10638 Opt(config.listTags)["-t"]["--list-tags"]("list all/matching tags") |
10639 Opt(config.showSuccessfulTests)["-s"]["--success"]("include successful tests in output") |
10640 Opt(config.shouldDebugBreak)["-b"]["--break"]("break into debugger on failure") |
10641 Opt(config.noThrow)["-e"]["--nothrow"]("skip exception tests") |
10642 Opt(config.showInvisibles)["-i"]["--invisibles"]("show invisibles (tabs, newlines)") |
10643 Opt(config.outputFilename, "filename")["-o"]["--out"]("output filename") |
10644 Opt(setReporter, "name")["-r"]["--reporter"]("reporter to use (defaults to console)") |
10645 Opt(config.name, "name")["-n"]["--name"]("suite name") |
10646 Opt([&](bool) { config.abortAfter = 1; })["-a"]["--abort"]("abort at first failure") |
10647 Opt([&](int x) { config.abortAfter = x; },
10648 "no. failures")["-x"]["--abortx"]("abort after x failures") |
10649 Opt(setWarning, "warning name")["-w"]["--warn"]("enable warnings") |
10650 Opt(
10651 [&](bool flag) {
10652 config.showDurations = flag ? ShowDurations::Always : ShowDurations::Never;
10653 },
10654 "yes|no")["-d"]["--durations"]("show test durations") |
10655 Opt(config.minDuration, "seconds")["-D"]["--min-duration"](
10656 "show test durations for tests taking at least the given number of seconds") |
10657 Opt(loadTestNamesFromFile,
10658 "filename")["-f"]["--input-file"]("load test names to run from a file") |
10659 Opt(config.filenamesAsTags)["-#"]["--filenames-as-tags"]("adds a tag for the filename") |
10660 Opt(config.sectionsToRun, "section name")["-c"]["--section"]("specify section to run") |
10661 Opt(setVerbosity, "quiet|normal|high")["-v"]["--verbosity"]("set output verbosity") |
10662 Opt(config.listTestNamesOnly)["--list-test-names-only"](
10663 "list all/matching test cases names only") |
10664 Opt(config.listReporters)["--list-reporters"]("list all reporters") |
10665 Opt(setTestOrder, "decl|lex|rand")["--order"]("test case order (defaults to decl)") |
10666 Opt(setRngSeed, "'time'|number")["--rng-seed"]("set a specific seed for random numbers") |
10667 Opt(setColourUsage, "yes|no")["--use-colour"]("should output be colourised") |
10668 Opt(config.libIdentify)["--libidentify"](
10669 "report name and version according to libidentify standard") |
10670 Opt(setWaitForKeypress,
10671 "never|start|exit|both")["--wait-for-keypress"]("waits for a keypress before exiting") |
10672 Opt(config.benchmarkSamples,
10673 "samples")["--benchmark-samples"]("number of samples to collect (default: 100)") |
10674 Opt(config.benchmarkResamples, "resamples")["--benchmark-resamples"](
10675 "number of resamples for the bootstrap (default: 100000)") |
10676 Opt(config.benchmarkConfidenceInterval,
10677 "confidence interval")["--benchmark-confidence-interval"](
10678 "confidence interval for the bootstrap (between 0 and 1, default: 0.95)") |
10679 Opt(config.benchmarkNoAnalysis)["--benchmark-no-analysis"](
10680 "perform only measurements; do not perform any analysis") |
10681 Opt(config.benchmarkWarmupTime, "benchmarkWarmupTime")["--benchmark-warmup-time"](
10682 "amount of time in milliseconds spent on warming up each test (default: 100)") |
10683 Arg(config.testsOrTags, "test name|pattern|tags")("which test or tests to use");
10684
10685 return cli;
10686 }
10687
10688 } // end namespace Catch
10689 // end catch_commandline.cpp
10690 // start catch_common.cpp
10691
10692 #include <cstring>
10693 #include <ostream>
10694
10695 namespace Catch {
10696
10697 bool SourceLineInfo::operator==(SourceLineInfo const &other) const noexcept
10698 {
10699 return line == other.line && (file == other.file || std::strcmp(file, other.file) == 0);
10700 }
10701 bool SourceLineInfo::operator<(SourceLineInfo const &other) const noexcept
10702 {
10703 // We can assume that the same file will usually have the same pointer.
10704 // Thus, if the pointers are the same, there is no point in calling the strcmp
10705 return line < other.line ||
10706 (line == other.line && file != other.file && (std::strcmp(file, other.file) < 0));
10707 }
10708
10709 std::ostream &operator<<(std::ostream &os, SourceLineInfo const &info)
10710 {
10711 #ifndef __GNUG__
10712 os << info.file << '(' << info.line << ')';
10713 #else
10714 os << info.file << ':' << info.line;
10715 #endif
10716 return os;
10717 }
10718
10719 std::string StreamEndStop::operator+() const { return std::string(); }
10720
10721 NonCopyable::NonCopyable() = default;
10722 NonCopyable::~NonCopyable() = default;
10723
10724 } // namespace Catch
10725 // end catch_common.cpp
10726 // start catch_config.cpp
10727
10728 namespace Catch {
10729
10730 Config::Config(ConfigData const &data) : m_data(data), m_stream(openStream())
10731 {
10732 // We need to trim filter specs to avoid trouble with superfluous
10733 // whitespace (esp. important for bdd macros, as those are manually
10734 // aligned with whitespace).
10735
10736 for (auto &elem : m_data.testsOrTags) {
10737 elem = trim(elem);
10738 }
10739 for (auto &elem : m_data.sectionsToRun) {
10740 elem = trim(elem);
10741 }
10742
10743 TestSpecParser parser(ITagAliasRegistry::get());
10744 if (!m_data.testsOrTags.empty()) {
10745 m_hasTestFilters = true;
10746 for (auto const &testOrTags : m_data.testsOrTags) {
10747 parser.parse(testOrTags);
10748 }
10749 }
10750 m_testSpec = parser.testSpec();
10751 }
10752
10753 std::string const &Config::getFilename() const { return m_data.outputFilename; }
10754
10755 bool Config::listTests() const { return m_data.listTests; }
10756 bool Config::listTestNamesOnly() const { return m_data.listTestNamesOnly; }
10757 bool Config::listTags() const { return m_data.listTags; }
10758 bool Config::listReporters() const { return m_data.listReporters; }
10759
10760 std::string Config::getProcessName() const { return m_data.processName; }
10761 std::string const &Config::getReporterName() const { return m_data.reporterName; }
10762
10763 std::vector<std::string> const &Config::getTestsOrTags() const { return m_data.testsOrTags; }
10764 std::vector<std::string> const &Config::getSectionsToRun() const { return m_data.sectionsToRun; }
10765
10766 TestSpec const &Config::testSpec() const { return m_testSpec; }
10767 bool Config::hasTestFilters() const { return m_hasTestFilters; }
10768
10769 bool Config::showHelp() const { return m_data.showHelp; }
10770
10771 // IConfig interface
10772 bool Config::allowThrows() const { return !m_data.noThrow; }
10773 std::ostream &Config::stream() const { return m_stream->stream(); }
10774 std::string Config::name() const
10775 {
10776 return m_data.name.empty() ? m_data.processName : m_data.name;
10777 }
10778 bool Config::includeSuccessfulResults() const { return m_data.showSuccessfulTests; }
10779 bool Config::warnAboutMissingAssertions() const
10780 {
10781 return !!(m_data.warnings & WarnAbout::NoAssertions);
10782 }
10783 bool Config::warnAboutNoTests() const { return !!(m_data.warnings & WarnAbout::NoTests); }
10784 ShowDurations::OrNot Config::showDurations() const { return m_data.showDurations; }
10785 double Config::minDuration() const { return m_data.minDuration; }
10786 RunTests::InWhatOrder Config::runOrder() const { return m_data.runOrder; }
10787 unsigned int Config::rngSeed() const { return m_data.rngSeed; }
10788 UseColour::YesOrNo Config::useColour() const { return m_data.useColour; }
10789 bool Config::shouldDebugBreak() const { return m_data.shouldDebugBreak; }
10790 int Config::abortAfter() const { return m_data.abortAfter; }
10791 bool Config::showInvisibles() const { return m_data.showInvisibles; }
10792 Verbosity Config::verbosity() const { return m_data.verbosity; }
10793
10794 bool Config::benchmarkNoAnalysis() const { return m_data.benchmarkNoAnalysis; }
10795 int Config::benchmarkSamples() const { return m_data.benchmarkSamples; }
10796 double Config::benchmarkConfidenceInterval() const { return m_data.benchmarkConfidenceInterval; }
10797 unsigned int Config::benchmarkResamples() const { return m_data.benchmarkResamples; }
10798 std::chrono::milliseconds Config::benchmarkWarmupTime() const
10799 {
10800 return std::chrono::milliseconds(m_data.benchmarkWarmupTime);
10801 }
10802
10803 IStream const *Config::openStream() { return Catch::makeStream(m_data.outputFilename); }
10804
10805 } // end namespace Catch
10806 // end catch_config.cpp
10807 // start catch_console_colour.cpp
10808
10809 #if defined(__clang__)
10810 #pragma clang diagnostic push
10811 #pragma clang diagnostic ignored "-Wexit-time-destructors"
10812 #endif
10813
10814 // start catch_errno_guard.h
10815
10816 namespace Catch {
10817
10818 class ErrnoGuard
10819 {
10820 public:
10821 ErrnoGuard();
10822 ~ErrnoGuard();
10823
10824 private:
10825 int m_oldErrno;
10826 };
10827
10828 } // namespace Catch
10829
10830 // end catch_errno_guard.h
10831 #include <sstream>
10832
10833 namespace Catch {
10834 namespace {
10835
10836 struct IColourImpl
10837 {
10838 virtual ~IColourImpl() = default;
10839 virtual void use(Colour::Code _colourCode) = 0;
10840 };
10841
10842 struct NoColourImpl : IColourImpl
10843 {
10844 void use(Colour::Code) override {}
10845
10846 static IColourImpl *instance()
10847 {
10848 static NoColourImpl s_instance;
10849 return &s_instance;
10850 }
10851 };
10852
10853 } // namespace
10854 } // namespace Catch
10855
10856 #if !defined(CATCH_CONFIG_COLOUR_NONE) && !defined(CATCH_CONFIG_COLOUR_WINDOWS) && \
10857 !defined(CATCH_CONFIG_COLOUR_ANSI)
10858 #ifdef CATCH_PLATFORM_WINDOWS
10859 #define CATCH_CONFIG_COLOUR_WINDOWS
10860 #else
10861 #define CATCH_CONFIG_COLOUR_ANSI
10862 #endif
10863 #endif
10864
10865 #if defined(CATCH_CONFIG_COLOUR_WINDOWS) /////////////////////////////////////////
10866
10867 namespace Catch {
10868 namespace {
10869
10870 class Win32ColourImpl : public IColourImpl
10871 {
10872 public:
10873 Win32ColourImpl() : stdoutHandle(GetStdHandle(STD_OUTPUT_HANDLE))
10874 {
10875 CONSOLE_SCREEN_BUFFER_INFO csbiInfo;
10876 GetConsoleScreenBufferInfo(stdoutHandle, &csbiInfo);
10877 originalForegroundAttributes =
10878 csbiInfo.wAttributes &
10879 ~(BACKGROUND_GREEN | BACKGROUND_RED | BACKGROUND_BLUE | BACKGROUND_INTENSITY);
10880 originalBackgroundAttributes =
10881 csbiInfo.wAttributes &
10882 ~(FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_BLUE | FOREGROUND_INTENSITY);
10883 }
10884
10885 void use(Colour::Code _colourCode) override
10886 {
10887 switch (_colourCode) {
10888 case Colour::None: return setTextAttribute(originalForegroundAttributes);
10889 case Colour::White:
10890 return setTextAttribute(FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_BLUE);
10891 case Colour::Red: return setTextAttribute(FOREGROUND_RED);
10892 case Colour::Green: return setTextAttribute(FOREGROUND_GREEN);
10893 case Colour::Blue: return setTextAttribute(FOREGROUND_BLUE);
10894 case Colour::Cyan: return setTextAttribute(FOREGROUND_BLUE | FOREGROUND_GREEN);
10895 case Colour::Yellow: return setTextAttribute(FOREGROUND_RED | FOREGROUND_GREEN);
10896 case Colour::Grey: return setTextAttribute(0);
10897
10898 case Colour::LightGrey: return setTextAttribute(FOREGROUND_INTENSITY);
10899 case Colour::BrightRed: return setTextAttribute(FOREGROUND_INTENSITY | FOREGROUND_RED);
10900 case Colour::BrightGreen: return setTextAttribute(FOREGROUND_INTENSITY | FOREGROUND_GREEN);
10901 case Colour::BrightWhite:
10902 return setTextAttribute(FOREGROUND_INTENSITY | FOREGROUND_GREEN | FOREGROUND_RED |
10903 FOREGROUND_BLUE);
10904 case Colour::BrightYellow:
10905 return setTextAttribute(FOREGROUND_INTENSITY | FOREGROUND_RED | FOREGROUND_GREEN);
10906
10907 case Colour::Bright: CATCH_INTERNAL_ERROR("not a colour");
10908
10909 default: CATCH_ERROR("Unknown colour requested");
10910 }
10911 }
10912
10913 private:
10914 void setTextAttribute(WORD _textAttribute)
10915 {
10916 SetConsoleTextAttribute(stdoutHandle, _textAttribute | originalBackgroundAttributes);
10917 }
10918 HANDLE stdoutHandle;
10919 WORD originalForegroundAttributes;
10920 WORD originalBackgroundAttributes;
10921 };
10922
10923 IColourImpl *platformColourInstance()
10924 {
10925 static Win32ColourImpl s_instance;
10926
10927 IConfigPtr config = getCurrentContext().getConfig();
10928 UseColour::YesOrNo colourMode = config ? config->useColour() : UseColour::Auto;
10929 if (colourMode == UseColour::Auto)
10930 colourMode = UseColour::Yes;
10931 return colourMode == UseColour::Yes ? &s_instance : NoColourImpl::instance();
10932 }
10933
10934 } // namespace
10935 } // end namespace Catch
10936
10937 #elif defined(CATCH_CONFIG_COLOUR_ANSI) //////////////////////////////////////
10938
10939 #include <unistd.h>
10940
10941 namespace Catch {
10942 namespace {
10943
10944 // use POSIX/ ANSI console terminal codes
10945 // Thanks to Adam Strzelecki for original contribution
10946 // (http://github.com/nanoant)
10947 // https://github.com/philsquared/Catch/pull/131
10948 class PosixColourImpl : public IColourImpl
10949 {
10950 public:
10951 void use(Colour::Code _colourCode) override
10952 {
10953 switch (_colourCode) {
10954 case Colour::None:
10955 case Colour::White: return setColour("[0m");
10956 case Colour::Red: return setColour("[0;31m");
10957 case Colour::Green: return setColour("[0;32m");
10958 case Colour::Blue: return setColour("[0;34m");
10959 case Colour::Cyan: return setColour("[0;36m");
10960 case Colour::Yellow: return setColour("[0;33m");
10961 case Colour::Grey: return setColour("[1;30m");
10962
10963 case Colour::LightGrey: return setColour("[0;37m");
10964 case Colour::BrightRed: return setColour("[1;31m");
10965 case Colour::BrightGreen: return setColour("[1;32m");
10966 case Colour::BrightWhite: return setColour("[1;37m");
10967 case Colour::BrightYellow: return setColour("[1;33m");
10968
10969 case Colour::Bright: CATCH_INTERNAL_ERROR("not a colour");
10970 default: CATCH_INTERNAL_ERROR("Unknown colour requested");
10971 }
10972 }
10973 static IColourImpl *instance()
10974 {
10975 static PosixColourImpl s_instance;
10976 return &s_instance;
10977 }
10978
10979 private:
10980 void setColour(const char *_escapeCode)
10981 {
10982 getCurrentContext().getConfig()->stream() << '\033' << _escapeCode;
10983 }
10984 };
10985
10986 bool useColourOnPlatform()
10987 {
10988 return
10989 #if defined(CATCH_PLATFORM_MAC) || defined(CATCH_PLATFORM_IPHONE)
10990 !isDebuggerActive() &&
10991 #endif
10992 #if !(defined(__DJGPP__) && defined(__STRICT_ANSI__))
10993 isatty(STDOUT_FILENO)
10994 #else
10995 false
10996 #endif
10997 ;
10998 }
10999 IColourImpl *platformColourInstance()
11000 {
11001 ErrnoGuard guard;
11002 IConfigPtr config = getCurrentContext().getConfig();
11003 UseColour::YesOrNo colourMode = config ? config->useColour() : UseColour::Auto;
11004 if (colourMode == UseColour::Auto)
11005 colourMode = useColourOnPlatform() ? UseColour::Yes : UseColour::No;
11006 return colourMode == UseColour::Yes ? PosixColourImpl::instance() : NoColourImpl::instance();
11007 }
11008
11009 } // namespace
11010 } // end namespace Catch
11011
11012 #else // not Windows or ANSI ///////////////////////////////////////////////
11013
11014 namespace Catch {
11015
11016 static IColourImpl *platformColourInstance() { return NoColourImpl::instance(); }
11017
11018 } // end namespace Catch
11019
11020 #endif // Windows/ ANSI/ None
11021
11022 namespace Catch {
11023
11024 Colour::Colour(Code _colourCode) { use(_colourCode); }
11025 Colour::Colour(Colour &&other) noexcept
11026 {
11027 m_moved = other.m_moved;
11028 other.m_moved = true;
11029 }
11030 Colour &Colour::operator=(Colour &&other) noexcept
11031 {
11032 m_moved = other.m_moved;
11033 other.m_moved = true;
11034 return *this;
11035 }
11036
11037 Colour::~Colour()
11038 {
11039 if (!m_moved)
11040 use(None);
11041 }
11042
11043 void Colour::use(Code _colourCode)
11044 {
11045 static IColourImpl *impl = platformColourInstance();
11046 // Strictly speaking, this cannot possibly happen.
11047 // However, under some conditions it does happen (see #1626),
11048 // and this change is small enough that we can let practicality
11049 // triumph over purity in this case.
11050 if (impl != nullptr) {
11051 impl->use(_colourCode);
11052 }
11053 }
11054
11055 std::ostream &operator<<(std::ostream &os, Colour const &) { return os; }
11056
11057 } // end namespace Catch
11058
11059 #if defined(__clang__)
11060 #pragma clang diagnostic pop
11061 #endif
11062
11063 // end catch_console_colour.cpp
11064 // start catch_context.cpp
11065
11066 namespace Catch {
11067
11068 class Context : public IMutableContext, NonCopyable
11069 {
11070
11071 public: // IContext
11072 IResultCapture *getResultCapture() override { return m_resultCapture; }
11073 IRunner *getRunner() override { return m_runner; }
11074
11075 IConfigPtr const &getConfig() const override { return m_config; }
11076
11077 ~Context() override;
11078
11079 public: // IMutableContext
11080 void setResultCapture(IResultCapture *resultCapture) override
11081 {
11082 m_resultCapture = resultCapture;
11083 }
11084 void setRunner(IRunner *runner) override { m_runner = runner; }
11085 void setConfig(IConfigPtr const &config) override { m_config = config; }
11086
11087 friend IMutableContext &getCurrentMutableContext();
11088
11089 private:
11090 IConfigPtr m_config;
11091 IRunner *m_runner = nullptr;
11092 IResultCapture *m_resultCapture = nullptr;
11093 };
11094
11095 IMutableContext *IMutableContext::currentContext = nullptr;
11096
11097 void IMutableContext::createContext() { currentContext = new Context(); }
11098
11099 void cleanUpContext()
11100 {
11101 delete IMutableContext::currentContext;
11102 IMutableContext::currentContext = nullptr;
11103 }
11104 IContext::~IContext() = default;
11105 IMutableContext::~IMutableContext() = default;
11106 Context::~Context() = default;
11107
11108 SimplePcg32 &rng()
11109 {
11110 static SimplePcg32 s_rng;
11111 return s_rng;
11112 }
11113
11114 } // namespace Catch
11115 // end catch_context.cpp
11116 // start catch_debug_console.cpp
11117
11118 // start catch_debug_console.h
11119
11120 #include <string>
11121
11122 namespace Catch {
11123 void writeToDebugConsole(std::string const &text);
11124 }
11125
11126 // end catch_debug_console.h
11127 #if defined(CATCH_CONFIG_ANDROID_LOGWRITE)
11128 #include <android/log.h>
11129
11130 namespace Catch {
11131 void writeToDebugConsole(std::string const &text)
11132 {
11133 __android_log_write(ANDROID_LOG_DEBUG, "Catch", text.c_str());
11134 }
11135 } // namespace Catch
11136
11137 #elif defined(CATCH_PLATFORM_WINDOWS)
11138
11139 namespace Catch {
11140 void writeToDebugConsole(std::string const &text) { ::OutputDebugStringA(text.c_str()); }
11141 } // namespace Catch
11142
11143 #else
11144
11145 namespace Catch {
11146 void writeToDebugConsole(std::string const &text)
11147 {
11148 // !TBD: Need a version for Mac/ XCode and other IDEs
11149 Catch::cout() << text;
11150 }
11151 } // namespace Catch
11152
11153 #endif // Platform
11154 // end catch_debug_console.cpp
11155 // start catch_debugger.cpp
11156
11157 #if defined(CATCH_PLATFORM_MAC) || defined(CATCH_PLATFORM_IPHONE)
11158
11159 #include <cassert>
11160 #include <cstddef>
11161 #include <ostream>
11162 #include <sys/types.h>
11163 #include <unistd.h>
11164
11165 #ifdef __apple_build_version__
11166 // These headers will only compile with AppleClang (XCode)
11167 // For other compilers (Clang, GCC, ... ) we need to exclude them
11168 #include <sys/sysctl.h>
11169 #endif
11170
11171 namespace Catch {
11172 #ifdef __apple_build_version__
11173 // The following function is taken directly from the following technical note:
11174 // https://developer.apple.com/library/archive/qa/qa1361/_index.html
11175
11176 // Returns true if the current process is being debugged (either
11177 // running under the debugger or has a debugger attached post facto).
11178 bool isDebuggerActive()
11179 {
11180 int mib[4];
11181 struct kinfo_proc info;
11182 std::size_t size;
11183
11184 // Initialize the flags so that, if sysctl fails for some bizarre
11185 // reason, we get a predictable result.
11186
11187 info.kp_proc.p_flag = 0;
11188
11189 // Initialize mib, which tells sysctl the info we want, in this case
11190 // we're looking for information about a specific process ID.
11191
11192 mib[0] = CTL_KERN;
11193 mib[1] = KERN_PROC;
11194 mib[2] = KERN_PROC_PID;
11195 mib[3] = getpid();
11196
11197 // Call sysctl.
11198
11199 size = sizeof(info);
11200 if (sysctl(mib, sizeof(mib) / sizeof(*mib), &info, &size, nullptr, 0) != 0) {
11201 Catch::cerr() << "\n** Call to sysctl failed - unable to determine if debugger is active **\n"
11202 << std::endl;
11203 return false;
11204 }
11205
11206 // We're being debugged if the P_TRACED flag is set.
11207
11208 return ((info.kp_proc.p_flag & P_TRACED) != 0);
11209 }
11210 #else
11211 bool isDebuggerActive()
11212 {
11213 // We need to find another way to determine this for non-appleclang compilers on macOS
11214 return false;
11215 }
11216 #endif
11217 } // namespace Catch
11218
11219 #elif defined(CATCH_PLATFORM_LINUX)
11220 #include <fstream>
11221 #include <string>
11222
11223 namespace Catch {
11224 // The standard POSIX way of detecting a debugger is to attempt to
11225 // ptrace() the process, but this needs to be done from a child and not
11226 // this process itself to still allow attaching to this process later
11227 // if wanted, so is rather heavy. Under Linux we have the PID of the
11228 // "debugger" (which doesn't need to be gdb, of course, it could also
11229 // be strace, for example) in /proc/$PID/status, so just get it from
11230 // there instead.
11231 bool isDebuggerActive()
11232 {
11233 // Libstdc++ has a bug, where std::ifstream sets errno to 0
11234 // This way our users can properly assert over errno values
11235 ErrnoGuard guard;
11236 std::ifstream in("/proc/self/status");
11237 for (std::string line; std::getline(in, line);) {
11238 static const int PREFIX_LEN = 11;
11239 if (line.compare(0, PREFIX_LEN, "TracerPid:\t") == 0) {
11240 // We're traced if the PID is not 0 and no other PID starts
11241 // with 0 digit, so it's enough to check for just a single
11242 // character.
11243 return line.length() > PREFIX_LEN && line[PREFIX_LEN] != '0';
11244 }
11245 }
11246
11247 return false;
11248 }
11249 } // namespace Catch
11250 #elif defined(_MSC_VER)
11251 extern "C" __declspec(dllimport) int __stdcall IsDebuggerPresent();
11252 namespace Catch {
11253 bool isDebuggerActive() { return IsDebuggerPresent() != 0; }
11254 } // namespace Catch
11255 #elif defined(__MINGW32__)
11256 extern "C" __declspec(dllimport) int __stdcall IsDebuggerPresent();
11257 namespace Catch {
11258 bool isDebuggerActive() { return IsDebuggerPresent() != 0; }
11259 } // namespace Catch
11260 #else
11261 namespace Catch {
11262 bool isDebuggerActive() { return false; }
11263 } // namespace Catch
11264 #endif // Platform
11265 // end catch_debugger.cpp
11266 // start catch_decomposer.cpp
11267
11268 namespace Catch {
11269
11270 ITransientExpression::~ITransientExpression() = default;
11271
11272 void formatReconstructedExpression(std::ostream &os, std::string const &lhs, StringRef op,
11273 std::string const &rhs)
11274 {
11275 if (lhs.size() + rhs.size() < 40 && lhs.find('\n') == std::string::npos &&
11276 rhs.find('\n') == std::string::npos)
11277 os << lhs << " " << op << " " << rhs;
11278 else
11279 os << lhs << "\n" << op << "\n" << rhs;
11280 }
11281 } // namespace Catch
11282 // end catch_decomposer.cpp
11283 // start catch_enforce.cpp
11284
11285 #include <stdexcept>
11286
11287 namespace Catch {
11288 #if defined(CATCH_CONFIG_DISABLE_EXCEPTIONS) && \
11289 !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS_CUSTOM_HANDLER)
11290 [[noreturn]]
11291 void throw_exception(std::exception const &e)
11292 {
11293 Catch::cerr() << "Catch will terminate because it needed to throw an exception.\n"
11294 << "The message was: " << e.what() << '\n';
11295 std::terminate();
11296 }
11297 #endif
11298
11299 [[noreturn]]
11300 void throw_logic_error(std::string const &msg)
11301 {
11302 throw_exception(std::logic_error(msg));
11303 }
11304
11305 [[noreturn]]
11306 void throw_domain_error(std::string const &msg)
11307 {
11308 throw_exception(std::domain_error(msg));
11309 }
11310
11311 [[noreturn]]
11312 void throw_runtime_error(std::string const &msg)
11313 {
11314 throw_exception(std::runtime_error(msg));
11315 }
11316
11317 } // namespace Catch
11318 // end catch_enforce.cpp
11319 // start catch_enum_values_registry.cpp
11320 // start catch_enum_values_registry.h
11321
11322 #include <memory>
11323 #include <vector>
11324
11325 namespace Catch {
11326
11327 namespace Detail {
11328
11329 std::unique_ptr<EnumInfo> makeEnumInfo(StringRef enumName, StringRef allValueNames,
11330 std::vector<int> const &values);
11331
11332 class EnumValuesRegistry : public IMutableEnumValuesRegistry
11333 {
11334
11335 std::vector<std::unique_ptr<EnumInfo>> m_enumInfos;
11336
11337 EnumInfo const &registerEnum(StringRef enumName, StringRef allEnums,
11338 std::vector<int> const &values) override;
11339 };
11340
11341 std::vector<StringRef> parseEnums(StringRef enums);
11342
11343 } // namespace Detail
11344
11345 } // namespace Catch
11346
11347 // end catch_enum_values_registry.h
11348
11349 #include <cassert>
11350 #include <map>
11351
11352 namespace Catch {
11353
11354 IMutableEnumValuesRegistry::~IMutableEnumValuesRegistry() {}
11355
11356 namespace Detail {
11357
11358 namespace {
11359 // Extracts the actual name part of an enum instance
11360 // In other words, it returns the Blue part of Bikeshed::Colour::Blue
11361 StringRef extractInstanceName(StringRef enumInstance)
11362 {
11363 // Find last occurence of ":"
11364 size_t name_start = enumInstance.size();
11365 while (name_start > 0 && enumInstance[name_start - 1] != ':') {
11366 --name_start;
11367 }
11368 return enumInstance.substr(name_start, enumInstance.size() - name_start);
11369 }
11370 } // namespace
11371
11372 std::vector<StringRef> parseEnums(StringRef enums)
11373 {
11374 auto enumValues = splitStringRef(enums, ',');
11375 std::vector<StringRef> parsed;
11376 parsed.reserve(enumValues.size());
11377 for (auto const &enumValue : enumValues) {
11378 parsed.push_back(trim(extractInstanceName(enumValue)));
11379 }
11380 return parsed;
11381 }
11382
11383 EnumInfo::~EnumInfo() {}
11384
11385 StringRef EnumInfo::lookup(int value) const
11386 {
11387 for (auto const &valueToName : m_values) {
11388 if (valueToName.first == value)
11389 return valueToName.second;
11390 }
11391 return "{** unexpected enum value **}"_sr;
11392 }
11393
11394 std::unique_ptr<EnumInfo> makeEnumInfo(StringRef enumName, StringRef allValueNames,
11395 std::vector<int> const &values)
11396 {
11397 std::unique_ptr<EnumInfo> enumInfo(new EnumInfo);
11398 enumInfo->m_name = enumName;
11399 enumInfo->m_values.reserve(values.size());
11400
11401 const auto valueNames = Catch::Detail::parseEnums(allValueNames);
11402 assert(valueNames.size() == values.size());
11403 std::size_t i = 0;
11404 for (auto value : values)
11405 enumInfo->m_values.emplace_back(value, valueNames[i++]);
11406
11407 return enumInfo;
11408 }
11409
11410 EnumInfo const &EnumValuesRegistry::registerEnum(StringRef enumName, StringRef allValueNames,
11411 std::vector<int> const &values)
11412 {
11413 m_enumInfos.push_back(makeEnumInfo(enumName, allValueNames, values));
11414 return *m_enumInfos.back();
11415 }
11416
11417 } // namespace Detail
11418 } // namespace Catch
11419
11420 // end catch_enum_values_registry.cpp
11421 // start catch_errno_guard.cpp
11422
11423 #include <cerrno>
11424
11425 namespace Catch {
11426 ErrnoGuard::ErrnoGuard() : m_oldErrno(errno) {}
11427 ErrnoGuard::~ErrnoGuard() { errno = m_oldErrno; }
11428 } // namespace Catch
11429 // end catch_errno_guard.cpp
11430 // start catch_exception_translator_registry.cpp
11431
11432 // start catch_exception_translator_registry.h
11433
11434 #include <memory>
11435 #include <string>
11436 #include <vector>
11437
11438 namespace Catch {
11439
11440 class ExceptionTranslatorRegistry : public IExceptionTranslatorRegistry
11441 {
11442 public:
11443 ~ExceptionTranslatorRegistry();
11444 virtual void registerTranslator(const IExceptionTranslator *translator);
11445 std::string translateActiveException() const override;
11446 std::string tryTranslators() const;
11447
11448 private:
11449 std::vector<std::unique_ptr<IExceptionTranslator const>> m_translators;
11450 };
11451 } // namespace Catch
11452
11453 // end catch_exception_translator_registry.h
11454 #ifdef __OBJC__
11455 #import "Foundation/Foundation.h"
11456 #endif
11457
11458 namespace Catch {
11459
11460 ExceptionTranslatorRegistry::~ExceptionTranslatorRegistry() {}
11461
11462 void ExceptionTranslatorRegistry::registerTranslator(const IExceptionTranslator *translator)
11463 {
11464 m_translators.push_back(std::unique_ptr<const IExceptionTranslator>(translator));
11465 }
11466
11467 #if !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
11468 std::string ExceptionTranslatorRegistry::translateActiveException() const
11469 {
11470 try {
11471 #ifdef __OBJC__
11472 // In Objective-C try objective-c exceptions first
11473 @try {
11474 return tryTranslators();
11475 }
11476 @catch (NSException *exception) {
11477 return Catch::Detail::stringify([exception description]);
11478 }
11479 #else
11480 // Compiling a mixed mode project with MSVC means that CLR
11481 // exceptions will be caught in (...) as well. However, these
11482 // do not fill-in std::current_exception and thus lead to crash
11483 // when attempting rethrow.
11484 // /EHa switch also causes structured exceptions to be caught
11485 // here, but they fill-in current_exception properly, so
11486 // at worst the output should be a little weird, instead of
11487 // causing a crash.
11488 if (std::current_exception() == nullptr) {
11489 return "Non C++ exception. Possibly a CLR exception.";
11490 }
11491 return tryTranslators();
11492 #endif
11493 }
11494 catch (TestFailureException &) {
11495 std::rethrow_exception(std::current_exception());
11496 }
11497 catch (std::exception &ex) {
11498 return ex.what();
11499 }
11500 catch (std::string &msg) {
11501 return msg;
11502 }
11503 catch (const char *msg) {
11504 return msg;
11505 }
11506 catch (...) {
11507 return "Unknown exception";
11508 }
11509 }
11510
11511 std::string ExceptionTranslatorRegistry::tryTranslators() const
11512 {
11513 if (m_translators.empty()) {
11514 std::rethrow_exception(std::current_exception());
11515 }
11516 else {
11517 return m_translators[0]->translate(m_translators.begin() + 1, m_translators.end());
11518 }
11519 }
11520
11521 #else // ^^ Exceptions are enabled // Exceptions are disabled vv
11522 std::string ExceptionTranslatorRegistry::translateActiveException() const
11523 {
11524 CATCH_INTERNAL_ERROR(
11525 "Attempted to translate active exception under CATCH_CONFIG_DISABLE_EXCEPTIONS!");
11526 }
11527
11528 std::string ExceptionTranslatorRegistry::tryTranslators() const
11529 {
11530 CATCH_INTERNAL_ERROR(
11531 "Attempted to use exception translators under CATCH_CONFIG_DISABLE_EXCEPTIONS!");
11532 }
11533 #endif
11534
11535 } // namespace Catch
11536 // end catch_exception_translator_registry.cpp
11537 // start catch_fatal_condition.cpp
11538
11539 #if defined(__GNUC__)
11540 #pragma GCC diagnostic push
11541 #pragma GCC diagnostic ignored "-Wmissing-field-initializers"
11542 #endif
11543
11544 #if defined(CATCH_CONFIG_WINDOWS_SEH) || defined(CATCH_CONFIG_POSIX_SIGNALS)
11545
11546 namespace {
11547 // Report the error condition
11548 void reportFatal(char const *const message)
11549 {
11550 Catch::getCurrentContext().getResultCapture()->handleFatalErrorCondition(message);
11551 }
11552 } // namespace
11553
11554 #endif // signals/SEH handling
11555
11556 #if defined(CATCH_CONFIG_WINDOWS_SEH)
11557
11558 namespace Catch {
11559 struct SignalDefs
11560 {
11561 DWORD id;
11562 const char *name;
11563 };
11564
11565 // There is no 1-1 mapping between signals and windows exceptions.
11566 // Windows can easily distinguish between SO and SigSegV,
11567 // but SigInt, SigTerm, etc are handled differently.
11568 static SignalDefs signalDefs[] = {
11569 {static_cast<DWORD>(EXCEPTION_ILLEGAL_INSTRUCTION), "SIGILL - Illegal instruction signal"},
11570 {static_cast<DWORD>(EXCEPTION_STACK_OVERFLOW), "SIGSEGV - Stack overflow"},
11571 {static_cast<DWORD>(EXCEPTION_ACCESS_VIOLATION), "SIGSEGV - Segmentation violation signal"},
11572 {static_cast<DWORD>(EXCEPTION_INT_DIVIDE_BY_ZERO), "Divide by zero error"},
11573 };
11574
11575 LONG CALLBACK FatalConditionHandler::handleVectoredException(PEXCEPTION_POINTERS ExceptionInfo)
11576 {
11577 for (auto const &def : signalDefs) {
11578 if (ExceptionInfo->ExceptionRecord->ExceptionCode == def.id) {
11579 reportFatal(def.name);
11580 }
11581 }
11582 // If its not an exception we care about, pass it along.
11583 // This stops us from eating debugger breaks etc.
11584 return EXCEPTION_CONTINUE_SEARCH;
11585 }
11586
11587 FatalConditionHandler::FatalConditionHandler()
11588 {
11589 isSet = true;
11590 // 32k seems enough for Catch to handle stack overflow,
11591 // but the value was found experimentally, so there is no strong guarantee
11592 guaranteeSize = 32 * 1024;
11593 exceptionHandlerHandle = nullptr;
11594 // Register as first handler in current chain
11595 exceptionHandlerHandle = AddVectoredExceptionHandler(1, handleVectoredException);
11596 // Pass in guarantee size to be filled
11597 SetThreadStackGuarantee(&guaranteeSize);
11598 }
11599
11600 void FatalConditionHandler::reset()
11601 {
11602 if (isSet) {
11603 RemoveVectoredExceptionHandler(exceptionHandlerHandle);
11604 SetThreadStackGuarantee(&guaranteeSize);
11605 exceptionHandlerHandle = nullptr;
11606 isSet = false;
11607 }
11608 }
11609
11610 FatalConditionHandler::~FatalConditionHandler() { reset(); }
11611
11612 bool FatalConditionHandler::isSet = false;
11613 ULONG FatalConditionHandler::guaranteeSize = 0;
11614 PVOID FatalConditionHandler::exceptionHandlerHandle = nullptr;
11615
11616 } // namespace Catch
11617
11618 #elif defined(CATCH_CONFIG_POSIX_SIGNALS)
11619
11620 namespace Catch {
11621
11622 struct SignalDefs
11623 {
11624 int id;
11625 const char *name;
11626 };
11627
11628 // 32kb for the alternate stack seems to be sufficient. However, this value
11629 // is experimentally determined, so that's not guaranteed.
11630 static constexpr std::size_t sigStackSize = 32768 >= MINSIGSTKSZ ? 32768 : MINSIGSTKSZ;
11631
11632 static SignalDefs signalDefs[] = {{SIGINT, "SIGINT - Terminal interrupt signal"},
11633 {SIGILL, "SIGILL - Illegal instruction signal"},
11634 {SIGFPE, "SIGFPE - Floating point error signal"},
11635 {SIGSEGV, "SIGSEGV - Segmentation violation signal"},
11636 {SIGTERM, "SIGTERM - Termination request signal"},
11637 {SIGABRT, "SIGABRT - Abort (abnormal termination) signal"}};
11638
11639 void FatalConditionHandler::handleSignal(int sig)
11640 {
11641 char const *name = "<unknown signal>";
11642 for (auto const &def : signalDefs) {
11643 if (sig == def.id) {
11644 name = def.name;
11645 break;
11646 }
11647 }
11648 reset();
11649 reportFatal(name);
11650 raise(sig);
11651 }
11652
11653 FatalConditionHandler::FatalConditionHandler()
11654 {
11655 isSet = true;
11656 stack_t sigStack;
11657 sigStack.ss_sp = altStackMem;
11658 sigStack.ss_size = sigStackSize;
11659 sigStack.ss_flags = 0;
11660 sigaltstack(&sigStack, &oldSigStack);
11661 struct sigaction sa = {};
11662
11663 sa.sa_handler = handleSignal;
11664 sa.sa_flags = SA_ONSTACK;
11665 for (std::size_t i = 0; i < sizeof(signalDefs) / sizeof(SignalDefs); ++i) {
11666 sigaction(signalDefs[i].id, &sa, &oldSigActions[i]);
11667 }
11668 }
11669
11670 FatalConditionHandler::~FatalConditionHandler() { reset(); }
11671
11672 void FatalConditionHandler::reset()
11673 {
11674 if (isSet) {
11675 // Set signals back to previous values -- hopefully nobody overwrote them in the meantime
11676 for (std::size_t i = 0; i < sizeof(signalDefs) / sizeof(SignalDefs); ++i) {
11677 sigaction(signalDefs[i].id, &oldSigActions[i], nullptr);
11678 }
11679 // Return the old stack
11680 sigaltstack(&oldSigStack, nullptr);
11681 isSet = false;
11682 }
11683 }
11684
11685 bool FatalConditionHandler::isSet = false;
11686 struct sigaction FatalConditionHandler::oldSigActions[sizeof(signalDefs) / sizeof(SignalDefs)] =
11687 {};
11688 stack_t FatalConditionHandler::oldSigStack = {};
11689 char FatalConditionHandler::altStackMem[sigStackSize] = {};
11690
11691 } // namespace Catch
11692
11693 #else
11694
11695 namespace Catch {
11696 void FatalConditionHandler::reset() {}
11697 } // namespace Catch
11698
11699 #endif // signals/SEH handling
11700
11701 #if defined(__GNUC__)
11702 #pragma GCC diagnostic pop
11703 #endif
11704 // end catch_fatal_condition.cpp
11705 // start catch_generators.cpp
11706
11707 #include <limits>
11708 #include <set>
11709
11710 namespace Catch {
11711
11712 IGeneratorTracker::~IGeneratorTracker() {}
11713
11714 const char *GeneratorException::what() const noexcept { return m_msg; }
11715
11716 namespace Generators {
11717
11718 GeneratorUntypedBase::~GeneratorUntypedBase() {}
11719
11720 auto acquireGeneratorTracker(StringRef generatorName,
11721 SourceLineInfo const &lineInfo) -> IGeneratorTracker &
11722 {
11723 return getResultCapture().acquireGeneratorTracker(generatorName, lineInfo);
11724 }
11725
11726 } // namespace Generators
11727 } // namespace Catch
11728 // end catch_generators.cpp
11729 // start catch_interfaces_capture.cpp
11730
11731 namespace Catch {
11732 IResultCapture::~IResultCapture() = default;
11733 }
11734 // end catch_interfaces_capture.cpp
11735 // start catch_interfaces_config.cpp
11736
11737 namespace Catch {
11738 IConfig::~IConfig() = default;
11739 }
11740 // end catch_interfaces_config.cpp
11741 // start catch_interfaces_exception.cpp
11742
11743 namespace Catch {
11744 IExceptionTranslator::~IExceptionTranslator() = default;
11745 IExceptionTranslatorRegistry::~IExceptionTranslatorRegistry() = default;
11746 } // namespace Catch
11747 // end catch_interfaces_exception.cpp
11748 // start catch_interfaces_registry_hub.cpp
11749
11750 namespace Catch {
11751 IRegistryHub::~IRegistryHub() = default;
11752 IMutableRegistryHub::~IMutableRegistryHub() = default;
11753 } // namespace Catch
11754 // end catch_interfaces_registry_hub.cpp
11755 // start catch_interfaces_reporter.cpp
11756
11757 // start catch_reporter_listening.h
11758
11759 namespace Catch {
11760
11761 class ListeningReporter : public IStreamingReporter
11762 {
11763 using Reporters = std::vector<IStreamingReporterPtr>;
11764 Reporters m_listeners;
11765 IStreamingReporterPtr m_reporter = nullptr;
11766 ReporterPreferences m_preferences;
11767
11768 public:
11769 ListeningReporter();
11770
11771 void addListener(IStreamingReporterPtr &&listener);
11772 void addReporter(IStreamingReporterPtr &&reporter);
11773
11774 public: // IStreamingReporter
11775 ReporterPreferences getPreferences() const override;
11776
11777 void noMatchingTestCases(std::string const &spec) override;
11778
11779 void reportInvalidArguments(std::string const &arg) override;
11780
11781 static std::set<Verbosity> getSupportedVerbosities();
11782
11783 #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
11784 void benchmarkPreparing(std::string const &name) override;
11785 void benchmarkStarting(BenchmarkInfo const &benchmarkInfo) override;
11786 void benchmarkEnded(BenchmarkStats<> const &benchmarkStats) override;
11787 void benchmarkFailed(std::string const &) override;
11788 #endif // CATCH_CONFIG_ENABLE_BENCHMARKING
11789
11790 void testRunStarting(TestRunInfo const &testRunInfo) override;
11791 void testGroupStarting(GroupInfo const &groupInfo) override;
11792 void testCaseStarting(TestCaseInfo const &testInfo) override;
11793 void sectionStarting(SectionInfo const &sectionInfo) override;
11794 void assertionStarting(AssertionInfo const &assertionInfo) override;
11795
11796 // The return value indicates if the messages buffer should be cleared:
11797 bool assertionEnded(AssertionStats const &assertionStats) override;
11798 void sectionEnded(SectionStats const &sectionStats) override;
11799 void testCaseEnded(TestCaseStats const &testCaseStats) override;
11800 void testGroupEnded(TestGroupStats const &testGroupStats) override;
11801 void testRunEnded(TestRunStats const &testRunStats) override;
11802
11803 void skipTest(TestCaseInfo const &testInfo) override;
11804 bool isMulti() const override;
11805 };
11806
11807 } // end namespace Catch
11808
11809 // end catch_reporter_listening.h
11810 namespace Catch {
11811
11812 ReporterConfig::ReporterConfig(IConfigPtr const &_fullConfig)
11813 : m_stream(&_fullConfig->stream()), m_fullConfig(_fullConfig)
11814 {
11815 }
11816
11817 ReporterConfig::ReporterConfig(IConfigPtr const &_fullConfig, std::ostream &_stream)
11818 : m_stream(&_stream), m_fullConfig(_fullConfig)
11819 {
11820 }
11821
11822 std::ostream &ReporterConfig::stream() const { return *m_stream; }
11823 IConfigPtr ReporterConfig::fullConfig() const { return m_fullConfig; }
11824
11825 TestRunInfo::TestRunInfo(std::string const &_name) : name(_name) {}
11826
11827 GroupInfo::GroupInfo(std::string const &_name, std::size_t _groupIndex, std::size_t _groupsCount)
11828 : name(_name), groupIndex(_groupIndex), groupsCounts(_groupsCount)
11829 {
11830 }
11831
11832 AssertionStats::AssertionStats(AssertionResult const &_assertionResult,
11833 std::vector<MessageInfo> const &_infoMessages,
11834 Totals const &_totals)
11835 : assertionResult(_assertionResult), infoMessages(_infoMessages), totals(_totals)
11836 {
11837 assertionResult.m_resultData.lazyExpression.m_transientExpression =
11838 _assertionResult.m_resultData.lazyExpression.m_transientExpression;
11839
11840 if (assertionResult.hasMessage()) {
11841 // Copy message into messages list.
11842 // !TBD This should have been done earlier, somewhere
11843 MessageBuilder builder(assertionResult.getTestMacroName(), assertionResult.getSourceInfo(),
11844 assertionResult.getResultType());
11845 builder << assertionResult.getMessage();
11846 builder.m_info.message = builder.m_stream.str();
11847
11848 infoMessages.push_back(builder.m_info);
11849 }
11850 }
11851
11852 AssertionStats::~AssertionStats() = default;
11853
11854 SectionStats::SectionStats(SectionInfo const &_sectionInfo, Counts const &_assertions,
11855 double _durationInSeconds, bool _missingAssertions)
11856 : sectionInfo(_sectionInfo), assertions(_assertions), durationInSeconds(_durationInSeconds),
11857 missingAssertions(_missingAssertions)
11858 {
11859 }
11860
11861 SectionStats::~SectionStats() = default;
11862
11863 TestCaseStats::TestCaseStats(TestCaseInfo const &_testInfo, Totals const &_totals,
11864 std::string const &_stdOut, std::string const &_stdErr,
11865 bool _aborting)
11866 : testInfo(_testInfo), totals(_totals), stdOut(_stdOut), stdErr(_stdErr), aborting(_aborting)
11867 {
11868 }
11869
11870 TestCaseStats::~TestCaseStats() = default;
11871
11872 TestGroupStats::TestGroupStats(GroupInfo const &_groupInfo, Totals const &_totals, bool _aborting)
11873 : groupInfo(_groupInfo), totals(_totals), aborting(_aborting)
11874 {
11875 }
11876
11877 TestGroupStats::TestGroupStats(GroupInfo const &_groupInfo)
11878 : groupInfo(_groupInfo), aborting(false)
11879 {
11880 }
11881
11882 TestGroupStats::~TestGroupStats() = default;
11883
11884 TestRunStats::TestRunStats(TestRunInfo const &_runInfo, Totals const &_totals, bool _aborting)
11885 : runInfo(_runInfo), totals(_totals), aborting(_aborting)
11886 {
11887 }
11888
11889 TestRunStats::~TestRunStats() = default;
11890
11891 void IStreamingReporter::fatalErrorEncountered(StringRef) {}
11892 bool IStreamingReporter::isMulti() const { return false; }
11893
11894 IReporterFactory::~IReporterFactory() = default;
11895 IReporterRegistry::~IReporterRegistry() = default;
11896
11897 } // end namespace Catch
11898 // end catch_interfaces_reporter.cpp
11899 // start catch_interfaces_runner.cpp
11900
11901 namespace Catch {
11902 IRunner::~IRunner() = default;
11903 }
11904 // end catch_interfaces_runner.cpp
11905 // start catch_interfaces_testcase.cpp
11906
11907 namespace Catch {
11908 ITestInvoker::~ITestInvoker() = default;
11909 ITestCaseRegistry::~ITestCaseRegistry() = default;
11910 } // namespace Catch
11911 // end catch_interfaces_testcase.cpp
11912 // start catch_leak_detector.cpp
11913
11914 #ifdef CATCH_CONFIG_WINDOWS_CRTDBG
11915 #include <crtdbg.h>
11916
11917 namespace Catch {
11918
11919 LeakDetector::LeakDetector()
11920 {
11921 int flag = _CrtSetDbgFlag(_CRTDBG_REPORT_FLAG);
11922 flag |= _CRTDBG_LEAK_CHECK_DF;
11923 flag |= _CRTDBG_ALLOC_MEM_DF;
11924 _CrtSetDbgFlag(flag);
11925 _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE | _CRTDBG_MODE_DEBUG);
11926 _CrtSetReportFile(_CRT_WARN, _CRTDBG_FILE_STDERR);
11927 // Change this to leaking allocation's number to break there
11928 _CrtSetBreakAlloc(-1);
11929 }
11930 } // namespace Catch
11931
11932 #else
11933
11934 Catch::LeakDetector::LeakDetector() {}
11935
11936 #endif
11937
11938 Catch::LeakDetector::~LeakDetector() { Catch::cleanUp(); }
11939 // end catch_leak_detector.cpp
11940 // start catch_list.cpp
11941
11942 // start catch_list.h
11943
11944 #include <set>
11945
11946 namespace Catch {
11947
11948 std::size_t listTests(Config const &config);
11949
11950 std::size_t listTestsNamesOnly(Config const &config);
11951
11952 struct TagInfo
11953 {
11954 void add(std::string const &spelling);
11955 std::string all() const;
11956
11957 std::set<std::string> spellings;
11958 std::size_t count = 0;
11959 };
11960
11961 std::size_t listTags(Config const &config);
11962
11963 std::size_t listReporters();
11964
11965 Option<std::size_t> list(std::shared_ptr<Config> const &config);
11966
11967 } // end namespace Catch
11968
11969 // end catch_list.h
11970 // start catch_text.h
11971
11972 namespace Catch {
11973 using namespace clara::TextFlow;
11974 }
11975
11976 // end catch_text.h
11977 #include <algorithm>
11978 #include <iomanip>
11979 #include <limits>
11980
11981 namespace Catch {
11982
11983 std::size_t listTests(Config const &config)
11984 {
11985 TestSpec const &testSpec = config.testSpec();
11986 if (config.hasTestFilters())
11987 Catch::cout() << "Matching test cases:\n";
11988 else {
11989 Catch::cout() << "All available test cases:\n";
11990 }
11991
11992 auto matchedTestCases = filterTests(getAllTestCasesSorted(config), testSpec, config);
11993 for (auto const &testCaseInfo : matchedTestCases) {
11994 Colour::Code colour = testCaseInfo.isHidden() ? Colour::SecondaryText : Colour::None;
11995 Colour colourGuard(colour);
11996
11997 Catch::cout() << Column(testCaseInfo.name).initialIndent(2).indent(4) << "\n";
11998 if (config.verbosity() >= Verbosity::High) {
11999 Catch::cout() << Column(Catch::Detail::stringify(testCaseInfo.lineInfo)).indent(4)
12000 << std::endl;
12001 std::string description = testCaseInfo.description;
12002 if (description.empty())
12003 description = "(NO DESCRIPTION)";
12004 Catch::cout() << Column(description).indent(4) << std::endl;
12005 }
12006 if (!testCaseInfo.tags.empty())
12007 Catch::cout() << Column(testCaseInfo.tagsAsString()).indent(6) << "\n";
12008 }
12009
12010 if (!config.hasTestFilters())
12011 Catch::cout() << pluralise(matchedTestCases.size(), "test case") << '\n' << std::endl;
12012 else
12013 Catch::cout() << pluralise(matchedTestCases.size(), "matching test case") << '\n'
12014 << std::endl;
12015 return matchedTestCases.size();
12016 }
12017
12018 std::size_t listTestsNamesOnly(Config const &config)
12019 {
12020 TestSpec const &testSpec = config.testSpec();
12021 std::size_t matchedTests = 0;
12022 std::vector<TestCase> matchedTestCases =
12023 filterTests(getAllTestCasesSorted(config), testSpec, config);
12024 for (auto const &testCaseInfo : matchedTestCases) {
12025 matchedTests++;
12026 if (startsWith(testCaseInfo.name, '#'))
12027 Catch::cout() << '"' << testCaseInfo.name << '"';
12028 else
12029 Catch::cout() << testCaseInfo.name;
12030 if (config.verbosity() >= Verbosity::High)
12031 Catch::cout() << "\t@" << testCaseInfo.lineInfo;
12032 Catch::cout() << std::endl;
12033 }
12034 return matchedTests;
12035 }
12036
12037 void TagInfo::add(std::string const &spelling)
12038 {
12039 ++count;
12040 spellings.insert(spelling);
12041 }
12042
12043 std::string TagInfo::all() const
12044 {
12045 size_t size = 0;
12046 for (auto const &spelling : spellings) {
12047 // Add 2 for the brackes
12048 size += spelling.size() + 2;
12049 }
12050
12051 std::string out;
12052 out.reserve(size);
12053 for (auto const &spelling : spellings) {
12054 out += '[';
12055 out += spelling;
12056 out += ']';
12057 }
12058 return out;
12059 }
12060
12061 std::size_t listTags(Config const &config)
12062 {
12063 TestSpec const &testSpec = config.testSpec();
12064 if (config.hasTestFilters())
12065 Catch::cout() << "Tags for matching test cases:\n";
12066 else {
12067 Catch::cout() << "All available tags:\n";
12068 }
12069
12070 std::map<std::string, TagInfo> tagCounts;
12071
12072 std::vector<TestCase> matchedTestCases =
12073 filterTests(getAllTestCasesSorted(config), testSpec, config);
12074 for (auto const &testCase : matchedTestCases) {
12075 for (auto const &tagName : testCase.getTestCaseInfo().tags) {
12076 std::string lcaseTagName = toLower(tagName);
12077 auto countIt = tagCounts.find(lcaseTagName);
12078 if (countIt == tagCounts.end())
12079 countIt = tagCounts.insert(std::make_pair(lcaseTagName, TagInfo())).first;
12080 countIt->second.add(tagName);
12081 }
12082 }
12083
12084 for (auto const &tagCount : tagCounts) {
12085 ReusableStringStream rss;
12086 rss << " " << std::setw(2) << tagCount.second.count << " ";
12087 auto str = rss.str();
12088 auto wrapper = Column(tagCount.second.all())
12089 .initialIndent(0)
12090 .indent(str.size())
12091 .width(CATCH_CONFIG_CONSOLE_WIDTH - 10);
12092 Catch::cout() << str << wrapper << '\n';
12093 }
12094 Catch::cout() << pluralise(tagCounts.size(), "tag") << '\n' << std::endl;
12095 return tagCounts.size();
12096 }
12097
12098 std::size_t listReporters()
12099 {
12100 Catch::cout() << "Available reporters:\n";
12101 IReporterRegistry::FactoryMap const &factories =
12102 getRegistryHub().getReporterRegistry().getFactories();
12103 std::size_t maxNameLen = 0;
12104 for (auto const &factoryKvp : factories)
12105 maxNameLen = (std::max)(maxNameLen, factoryKvp.first.size());
12106
12107 for (auto const &factoryKvp : factories) {
12108 Catch::cout() << Column(factoryKvp.first + ":").indent(2).width(5 + maxNameLen) +
12109 Column(factoryKvp.second->getDescription())
12110 .initialIndent(0)
12111 .indent(2)
12112 .width(CATCH_CONFIG_CONSOLE_WIDTH - maxNameLen - 8)
12113 << "\n";
12114 }
12115 Catch::cout() << std::endl;
12116 return factories.size();
12117 }
12118
12119 Option<std::size_t> list(std::shared_ptr<Config> const &config)
12120 {
12121 Option<std::size_t> listedCount;
12122 getCurrentMutableContext().setConfig(config);
12123 if (config->listTests())
12124 listedCount = listedCount.valueOr(0) + listTests(*config);
12125 if (config->listTestNamesOnly())
12126 listedCount = listedCount.valueOr(0) + listTestsNamesOnly(*config);
12127 if (config->listTags())
12128 listedCount = listedCount.valueOr(0) + listTags(*config);
12129 if (config->listReporters())
12130 listedCount = listedCount.valueOr(0) + listReporters();
12131 return listedCount;
12132 }
12133
12134 } // end namespace Catch
12135 // end catch_list.cpp
12136 // start catch_matchers.cpp
12137
12138 namespace Catch {
12139 namespace Matchers {
12140 namespace Impl {
12141
12142 std::string MatcherUntypedBase::toString() const
12143 {
12144 if (m_cachedToString.empty())
12145 m_cachedToString = describe();
12146 return m_cachedToString;
12147 }
12148
12149 MatcherUntypedBase::~MatcherUntypedBase() = default;
12150
12151 } // namespace Impl
12152 } // namespace Matchers
12153
12154 using namespace Matchers;
12155 using Matchers::Impl::MatcherBase;
12156
12157 } // namespace Catch
12158 // end catch_matchers.cpp
12159 // start catch_matchers_exception.cpp
12160
12161 namespace Catch {
12162 namespace Matchers {
12163 namespace Exception {
12164
12165 bool ExceptionMessageMatcher::match(std::exception const &ex) const
12166 {
12167 return ex.what() == m_message;
12168 }
12169
12170 std::string ExceptionMessageMatcher::describe() const
12171 {
12172 return "exception message matches \"" + m_message + "\"";
12173 }
12174
12175 } // namespace Exception
12176 Exception::ExceptionMessageMatcher Message(std::string const &message)
12177 {
12178 return Exception::ExceptionMessageMatcher(message);
12179 }
12180
12181 // namespace Exception
12182 } // namespace Matchers
12183 } // namespace Catch
12184 // end catch_matchers_exception.cpp
12185 // start catch_matchers_floating.cpp
12186
12187 // start catch_polyfills.hpp
12188
12189 namespace Catch {
12190 bool isnan(float f);
12191 bool isnan(double d);
12192 } // namespace Catch
12193
12194 // end catch_polyfills.hpp
12195 // start catch_to_string.hpp
12196
12197 #include <string>
12198
12199 namespace Catch {
12200 template <typename T> std::string to_string(T const &t)
12201 {
12202 #if defined(CATCH_CONFIG_CPP11_TO_STRING)
12203 return std::to_string(t);
12204 #else
12205 ReusableStringStream rss;
12206 rss << t;
12207 return rss.str();
12208 #endif
12209 }
12210 } // end namespace Catch
12211
12212 // end catch_to_string.hpp
12213 #include <algorithm>
12214 #include <cmath>
12215 #include <cstdint>
12216 #include <cstdlib>
12217 #include <cstring>
12218 #include <iomanip>
12219 #include <limits>
12220 #include <sstream>
12221 #include <type_traits>
12222
12223 namespace Catch {
12224 namespace {
12225
12226 int32_t convert(float f)
12227 {
12228 static_assert(sizeof(float) == sizeof(int32_t), "Important ULP matcher assumption violated");
12229 int32_t i;
12230 std::memcpy(&i, &f, sizeof(f));
12231 return i;
12232 }
12233
12234 int64_t convert(double d)
12235 {
12236 static_assert(sizeof(double) == sizeof(int64_t), "Important ULP matcher assumption violated");
12237 int64_t i;
12238 std::memcpy(&i, &d, sizeof(d));
12239 return i;
12240 }
12241
12242 template <typename FP> bool almostEqualUlps(FP lhs, FP rhs, uint64_t maxUlpDiff)
12243 {
12244 // Comparison with NaN should always be false.
12245 // This way we can rule it out before getting into the ugly details
12246 if (Catch::isnan(lhs) || Catch::isnan(rhs)) {
12247 return false;
12248 }
12249
12250 auto lc = convert(lhs);
12251 auto rc = convert(rhs);
12252
12253 if ((lc < 0) != (rc < 0)) {
12254 // Potentially we can have +0 and -0
12255 return lhs == rhs;
12256 }
12257
12258 auto ulpDiff = std::abs(lc - rc);
12259 return static_cast<uint64_t>(ulpDiff) <= maxUlpDiff;
12260 }
12261
12262 #if defined(CATCH_CONFIG_GLOBAL_NEXTAFTER)
12263
12264 float nextafter(float x, float y) { return ::nextafterf(x, y); }
12265
12266 double nextafter(double x, double y) { return ::nextafter(x, y); }
12267
12268 #endif // ^^^ CATCH_CONFIG_GLOBAL_NEXTAFTER ^^^
12269
12270 template <typename FP> FP step(FP start, FP direction, uint64_t steps)
12271 {
12272 for (uint64_t i = 0; i < steps; ++i) {
12273 #if defined(CATCH_CONFIG_GLOBAL_NEXTAFTER)
12274 start = Catch::nextafter(start, direction);
12275 #else
12276 start = std::nextafter(start, direction);
12277 #endif
12278 }
12279 return start;
12280 }
12281
12282 // Performs equivalent check of std::fabs(lhs - rhs) <= margin
12283 // But without the subtraction to allow for INFINITY in comparison
12284 bool marginComparison(double lhs, double rhs, double margin)
12285 {
12286 return (lhs + margin >= rhs) && (rhs + margin >= lhs);
12287 }
12288
12289 template <typename FloatingPoint> void write(std::ostream &out, FloatingPoint num)
12290 {
12291 out << std::scientific
12292 << std::setprecision(std::numeric_limits<FloatingPoint>::max_digits10 - 1) << num;
12293 }
12294
12295 } // end anonymous namespace
12296
12297 namespace Matchers {
12298 namespace Floating {
12299
12300 enum class FloatingPointKind : uint8_t { Float, Double };
12301
12302 WithinAbsMatcher::WithinAbsMatcher(double target, double margin)
12303 : m_target{target}, m_margin{margin}
12304 {
12305 CATCH_ENFORCE(margin >= 0,
12306 "Invalid margin: " << margin << '.' << " Margin has to be non-negative.");
12307 }
12308
12309 // Performs equivalent check of std::fabs(lhs - rhs) <= margin
12310 // But without the subtraction to allow for INFINITY in comparison
12311 bool WithinAbsMatcher::match(double const &matchee) const
12312 {
12313 return (matchee + m_margin >= m_target) && (m_target + m_margin >= matchee);
12314 }
12315
12316 std::string WithinAbsMatcher::describe() const
12317 {
12318 return "is within " + ::Catch::Detail::stringify(m_margin) + " of " +
12319 ::Catch::Detail::stringify(m_target);
12320 }
12321
12322 WithinUlpsMatcher::WithinUlpsMatcher(double target, uint64_t ulps, FloatingPointKind baseType)
12323 : m_target{target}, m_ulps{ulps}, m_type{baseType}
12324 {
12325 CATCH_ENFORCE(m_type == FloatingPointKind::Double ||
12326 m_ulps < (std::numeric_limits<uint32_t>::max)(),
12327 "Provided ULP is impossibly large for a float comparison.");
12328 }
12329
12330 #if defined(__clang__)
12331 #pragma clang diagnostic push
12332 // Clang <3.5 reports on the default branch in the switch below
12333 #pragma clang diagnostic ignored "-Wunreachable-code"
12334 #endif
12335
12336 bool WithinUlpsMatcher::match(double const &matchee) const
12337 {
12338 switch (m_type) {
12339 case FloatingPointKind::Float:
12340 return almostEqualUlps<float>(static_cast<float>(matchee), static_cast<float>(m_target),
12341 m_ulps);
12342 case FloatingPointKind::Double: return almostEqualUlps<double>(matchee, m_target, m_ulps);
12343 default: CATCH_INTERNAL_ERROR("Unknown FloatingPointKind value");
12344 }
12345 }
12346
12347 #if defined(__clang__)
12348 #pragma clang diagnostic pop
12349 #endif
12350
12351 std::string WithinUlpsMatcher::describe() const
12352 {
12353 std::stringstream ret;
12354
12355 ret << "is within " << m_ulps << " ULPs of ";
12356
12357 if (m_type == FloatingPointKind::Float) {
12358 write(ret, static_cast<float>(m_target));
12359 ret << 'f';
12360 }
12361 else {
12362 write(ret, m_target);
12363 }
12364
12365 ret << " ([";
12366 if (m_type == FloatingPointKind::Double) {
12367 write(ret, step(m_target, static_cast<double>(-INFINITY), m_ulps));
12368 ret << ", ";
12369 write(ret, step(m_target, static_cast<double>(INFINITY), m_ulps));
12370 }
12371 else {
12372 // We have to cast INFINITY to float because of MinGW, see #1782
12373 write(ret, step(static_cast<float>(m_target), static_cast<float>(-INFINITY), m_ulps));
12374 ret << ", ";
12375 write(ret, step(static_cast<float>(m_target), static_cast<float>(INFINITY), m_ulps));
12376 }
12377 ret << "])";
12378
12379 return ret.str();
12380 }
12381
12382 WithinRelMatcher::WithinRelMatcher(double target, double epsilon)
12383 : m_target(target), m_epsilon(epsilon)
12384 {
12385 CATCH_ENFORCE(m_epsilon >= 0.,
12386 "Relative comparison with epsilon < 0 does not make sense.");
12387 CATCH_ENFORCE(m_epsilon < 1., "Relative comparison with epsilon >= 1 does not make sense.");
12388 }
12389
12390 bool WithinRelMatcher::match(double const &matchee) const
12391 {
12392 const auto relMargin = m_epsilon * (std::max)(std::fabs(matchee), std::fabs(m_target));
12393 return marginComparison(matchee, m_target, std::isinf(relMargin) ? 0 : relMargin);
12394 }
12395
12396 std::string WithinRelMatcher::describe() const
12397 {
12398 Catch::ReusableStringStream sstr;
12399 sstr << "and " << m_target << " are within " << m_epsilon * 100. << "% of each other";
12400 return sstr.str();
12401 }
12402
12403 } // namespace Floating
12404
12405 Floating::WithinUlpsMatcher WithinULP(double target, uint64_t maxUlpDiff)
12406 {
12407 return Floating::WithinUlpsMatcher(target, maxUlpDiff, Floating::FloatingPointKind::Double);
12408 }
12409
12410 Floating::WithinUlpsMatcher WithinULP(float target, uint64_t maxUlpDiff)
12411 {
12412 return Floating::WithinUlpsMatcher(target, maxUlpDiff, Floating::FloatingPointKind::Float);
12413 }
12414
12415 Floating::WithinAbsMatcher WithinAbs(double target, double margin)
12416 {
12417 return Floating::WithinAbsMatcher(target, margin);
12418 }
12419
12420 Floating::WithinRelMatcher WithinRel(double target, double eps)
12421 {
12422 return Floating::WithinRelMatcher(target, eps);
12423 }
12424
12425 Floating::WithinRelMatcher WithinRel(double target)
12426 {
12427 return Floating::WithinRelMatcher(target, std::numeric_limits<double>::epsilon() * 100);
12428 }
12429
12430 Floating::WithinRelMatcher WithinRel(float target, float eps)
12431 {
12432 return Floating::WithinRelMatcher(target, eps);
12433 }
12434
12435 Floating::WithinRelMatcher WithinRel(float target)
12436 {
12437 return Floating::WithinRelMatcher(target, std::numeric_limits<float>::epsilon() * 100);
12438 }
12439
12440 } // namespace Matchers
12441 } // namespace Catch
12442
12443 // end catch_matchers_floating.cpp
12444 // start catch_matchers_generic.cpp
12445
12446 std::string Catch::Matchers::Generic::Detail::finalizeDescription(const std::string &desc)
12447 {
12448 if (desc.empty()) {
12449 return "matches undescribed predicate";
12450 }
12451 else {
12452 return "matches predicate: \"" + desc + '"';
12453 }
12454 }
12455 // end catch_matchers_generic.cpp
12456 // start catch_matchers_string.cpp
12457
12458 #include <regex>
12459
12460 namespace Catch {
12461 namespace Matchers {
12462
12463 namespace StdString {
12464
12465 CasedString::CasedString(std::string const &str, CaseSensitive::Choice caseSensitivity)
12466 : m_caseSensitivity(caseSensitivity), m_str(adjustString(str))
12467 {
12468 }
12469 std::string CasedString::adjustString(std::string const &str) const
12470 {
12471 return m_caseSensitivity == CaseSensitive::No ? toLower(str) : str;
12472 }
12473 std::string CasedString::caseSensitivitySuffix() const
12474 {
12475 return m_caseSensitivity == CaseSensitive::No ? " (case insensitive)" : std::string();
12476 }
12477
12478 StringMatcherBase::StringMatcherBase(std::string const &operation,
12479 CasedString const &comparator)
12480 : m_comparator(comparator), m_operation(operation)
12481 {
12482 }
12483
12484 std::string StringMatcherBase::describe() const
12485 {
12486 std::string description;
12487 description.reserve(5 + m_operation.size() + m_comparator.m_str.size() +
12488 m_comparator.caseSensitivitySuffix().size());
12489 description += m_operation;
12490 description += ": \"";
12491 description += m_comparator.m_str;
12492 description += "\"";
12493 description += m_comparator.caseSensitivitySuffix();
12494 return description;
12495 }
12496
12497 EqualsMatcher::EqualsMatcher(CasedString const &comparator)
12498 : StringMatcherBase("equals", comparator)
12499 {
12500 }
12501
12502 bool EqualsMatcher::match(std::string const &source) const
12503 {
12504 return m_comparator.adjustString(source) == m_comparator.m_str;
12505 }
12506
12507 ContainsMatcher::ContainsMatcher(CasedString const &comparator)
12508 : StringMatcherBase("contains", comparator)
12509 {
12510 }
12511
12512 bool ContainsMatcher::match(std::string const &source) const
12513 {
12514 return contains(m_comparator.adjustString(source), m_comparator.m_str);
12515 }
12516
12517 StartsWithMatcher::StartsWithMatcher(CasedString const &comparator)
12518 : StringMatcherBase("starts with", comparator)
12519 {
12520 }
12521
12522 bool StartsWithMatcher::match(std::string const &source) const
12523 {
12524 return startsWith(m_comparator.adjustString(source), m_comparator.m_str);
12525 }
12526
12527 EndsWithMatcher::EndsWithMatcher(CasedString const &comparator)
12528 : StringMatcherBase("ends with", comparator)
12529 {
12530 }
12531
12532 bool EndsWithMatcher::match(std::string const &source) const
12533 {
12534 return endsWith(m_comparator.adjustString(source), m_comparator.m_str);
12535 }
12536
12537 RegexMatcher::RegexMatcher(std::string regex, CaseSensitive::Choice caseSensitivity)
12538 : m_regex(std::move(regex)), m_caseSensitivity(caseSensitivity)
12539 {
12540 }
12541
12542 bool RegexMatcher::match(std::string const &matchee) const
12543 {
12544 auto flags = std::regex::ECMAScript; // ECMAScript is the default syntax option anyway
12545 if (m_caseSensitivity == CaseSensitive::Choice::No) {
12546 flags |= std::regex::icase;
12547 }
12548 auto reg = std::regex(m_regex, flags);
12549 return std::regex_match(matchee, reg);
12550 }
12551
12552 std::string RegexMatcher::describe() const
12553 {
12554 return "matches " + ::Catch::Detail::stringify(m_regex) +
12555 ((m_caseSensitivity == CaseSensitive::Choice::Yes) ? " case sensitively"
12556 : " case insensitively");
12557 }
12558
12559 } // namespace StdString
12560
12561 StdString::EqualsMatcher Equals(std::string const &str, CaseSensitive::Choice caseSensitivity)
12562 {
12563 return StdString::EqualsMatcher(StdString::CasedString(str, caseSensitivity));
12564 }
12565 StdString::ContainsMatcher Contains(std::string const &str,
12566 CaseSensitive::Choice caseSensitivity)
12567 {
12568 return StdString::ContainsMatcher(StdString::CasedString(str, caseSensitivity));
12569 }
12570 StdString::EndsWithMatcher EndsWith(std::string const &str,
12571 CaseSensitive::Choice caseSensitivity)
12572 {
12573 return StdString::EndsWithMatcher(StdString::CasedString(str, caseSensitivity));
12574 }
12575 StdString::StartsWithMatcher StartsWith(std::string const &str,
12576 CaseSensitive::Choice caseSensitivity)
12577 {
12578 return StdString::StartsWithMatcher(StdString::CasedString(str, caseSensitivity));
12579 }
12580
12581 StdString::RegexMatcher Matches(std::string const &regex, CaseSensitive::Choice caseSensitivity)
12582 {
12583 return StdString::RegexMatcher(regex, caseSensitivity);
12584 }
12585
12586 } // namespace Matchers
12587 } // namespace Catch
12588 // end catch_matchers_string.cpp
12589 // start catch_message.cpp
12590
12591 // start catch_uncaught_exceptions.h
12592
12593 namespace Catch {
12594 bool uncaught_exceptions();
12595 } // end namespace Catch
12596
12597 // end catch_uncaught_exceptions.h
12598 #include <cassert>
12599 #include <stack>
12600
12601 namespace Catch {
12602
12603 MessageInfo::MessageInfo(StringRef const &_macroName, SourceLineInfo const &_lineInfo,
12604 ResultWas::OfType _type)
12605 : macroName(_macroName), lineInfo(_lineInfo), type(_type), sequence(++globalCount)
12606 {
12607 }
12608
12609 bool MessageInfo::operator==(MessageInfo const &other) const
12610 {
12611 return sequence == other.sequence;
12612 }
12613
12614 bool MessageInfo::operator<(MessageInfo const &other) const { return sequence < other.sequence; }
12615
12616 // This may need protecting if threading support is added
12617 unsigned int MessageInfo::globalCount = 0;
12618
12619 ////////////////////////////////////////////////////////////////////////////
12620
12621 Catch::MessageBuilder::MessageBuilder(StringRef const &macroName, SourceLineInfo const &lineInfo,
12622 ResultWas::OfType type)
12623 : m_info(macroName, lineInfo, type)
12624 {
12625 }
12626
12627 ////////////////////////////////////////////////////////////////////////////
12628
12629 ScopedMessage::ScopedMessage(MessageBuilder const &builder) : m_info(builder.m_info), m_moved()
12630 {
12631 m_info.message = builder.m_stream.str();
12632 getResultCapture().pushScopedMessage(m_info);
12633 }
12634
12635 ScopedMessage::ScopedMessage(ScopedMessage &&old) : m_info(old.m_info), m_moved()
12636 {
12637 old.m_moved = true;
12638 }
12639
12640 ScopedMessage::~ScopedMessage()
12641 {
12642 if (!uncaught_exceptions() && !m_moved) {
12643 getResultCapture().popScopedMessage(m_info);
12644 }
12645 }
12646
12647 Capturer::Capturer(StringRef macroName, SourceLineInfo const &lineInfo,
12648 ResultWas::OfType resultType, StringRef names)
12649 {
12650 auto trimmed = [&](size_t start, size_t end) {
12651 while (names[start] == ',' || isspace(static_cast<unsigned char>(names[start]))) {
12652 ++start;
12653 }
12654 while (names[end] == ',' || isspace(static_cast<unsigned char>(names[end]))) {
12655 --end;
12656 }
12657 return names.substr(start, end - start + 1);
12658 };
12659 auto skipq = [&](size_t start, char quote) {
12660 for (auto i = start + 1; i < names.size(); ++i) {
12661 if (names[i] == quote)
12662 return i;
12663 if (names[i] == '\\')
12664 ++i;
12665 }
12666 CATCH_INTERNAL_ERROR("CAPTURE parsing encountered unmatched quote");
12667 };
12668
12669 size_t start = 0;
12670 std::stack<char> openings;
12671 for (size_t pos = 0; pos < names.size(); ++pos) {
12672 char c = names[pos];
12673 switch (c) {
12674 case '[':
12675 case '{':
12676 case '(':
12677 // It is basically impossible to disambiguate between
12678 // comparison and start of template args in this context
12679 // case '<':
12680 openings.push(c);
12681 break;
12682 case ']':
12683 case '}':
12684 case ')':
12685 // case '>':
12686 openings.pop();
12687 break;
12688 case '"':
12689 case '\'': pos = skipq(pos, c); break;
12690 case ',':
12691 if (start != pos && openings.empty()) {
12692 m_messages.emplace_back(macroName, lineInfo, resultType);
12693 m_messages.back().message = static_cast<std::string>(trimmed(start, pos));
12694 m_messages.back().message += " := ";
12695 start = pos;
12696 }
12697 }
12698 }
12699 assert(openings.empty() && "Mismatched openings");
12700 m_messages.emplace_back(macroName, lineInfo, resultType);
12701 m_messages.back().message = static_cast<std::string>(trimmed(start, names.size() - 1));
12702 m_messages.back().message += " := ";
12703 }
12704 Capturer::~Capturer()
12705 {
12706 if (!uncaught_exceptions()) {
12707 assert(m_captured == m_messages.size());
12708 for (size_t i = 0; i < m_captured; ++i)
12709 m_resultCapture.popScopedMessage(m_messages[i]);
12710 }
12711 }
12712
12713 void Capturer::captureValue(size_t index, std::string const &value)
12714 {
12715 assert(index < m_messages.size());
12716 m_messages[index].message += value;
12717 m_resultCapture.pushScopedMessage(m_messages[index]);
12718 m_captured++;
12719 }
12720
12721 } // end namespace Catch
12722 // end catch_message.cpp
12723 // start catch_output_redirect.cpp
12724
12725 // start catch_output_redirect.h
12726 #ifndef TWOBLUECUBES_CATCH_OUTPUT_REDIRECT_H
12727 #define TWOBLUECUBES_CATCH_OUTPUT_REDIRECT_H
12728
12729 #include <cstdio>
12730 #include <iosfwd>
12731 #include <string>
12732
12733 namespace Catch {
12734
12735 class RedirectedStream
12736 {
12737 std::ostream &m_originalStream;
12738 std::ostream &m_redirectionStream;
12739 std::streambuf *m_prevBuf;
12740
12741 public:
12742 RedirectedStream(std::ostream &originalStream, std::ostream &redirectionStream);
12743 ~RedirectedStream();
12744 };
12745
12746 class RedirectedStdOut
12747 {
12748 ReusableStringStream m_rss;
12749 RedirectedStream m_cout;
12750
12751 public:
12752 RedirectedStdOut();
12753 auto str() const -> std::string;
12754 };
12755
12756 // StdErr has two constituent streams in C++, std::cerr and std::clog
12757 // This means that we need to redirect 2 streams into 1 to keep proper
12758 // order of writes
12759 class RedirectedStdErr
12760 {
12761 ReusableStringStream m_rss;
12762 RedirectedStream m_cerr;
12763 RedirectedStream m_clog;
12764
12765 public:
12766 RedirectedStdErr();
12767 auto str() const -> std::string;
12768 };
12769
12770 class RedirectedStreams
12771 {
12772 public:
12773 RedirectedStreams(RedirectedStreams const &) = delete;
12774 RedirectedStreams &operator=(RedirectedStreams const &) = delete;
12775 RedirectedStreams(RedirectedStreams &&) = delete;
12776 RedirectedStreams &operator=(RedirectedStreams &&) = delete;
12777
12778 RedirectedStreams(std::string &redirectedCout, std::string &redirectedCerr);
12779 ~RedirectedStreams();
12780
12781 private:
12782 std::string &m_redirectedCout;
12783 std::string &m_redirectedCerr;
12784 RedirectedStdOut m_redirectedStdOut;
12785 RedirectedStdErr m_redirectedStdErr;
12786 };
12787
12788 #if defined(CATCH_CONFIG_NEW_CAPTURE)
12789
12790 // Windows's implementation of std::tmpfile is terrible (it tries
12791 // to create a file inside system folder, thus requiring elevated
12792 // privileges for the binary), so we have to use tmpnam(_s) and
12793 // create the file ourselves there.
12794 class TempFile
12795 {
12796 public:
12797 TempFile(TempFile const &) = delete;
12798 TempFile &operator=(TempFile const &) = delete;
12799 TempFile(TempFile &&) = delete;
12800 TempFile &operator=(TempFile &&) = delete;
12801
12802 TempFile();
12803 ~TempFile();
12804
12805 std::FILE *getFile();
12806 std::string getContents();
12807
12808 private:
12809 std::FILE *m_file = nullptr;
12810 #if defined(_MSC_VER)
12811 char m_buffer[L_tmpnam] = {0};
12812 #endif
12813 };
12814
12815 class OutputRedirect
12816 {
12817 public:
12818 OutputRedirect(OutputRedirect const &) = delete;
12819 OutputRedirect &operator=(OutputRedirect const &) = delete;
12820 OutputRedirect(OutputRedirect &&) = delete;
12821 OutputRedirect &operator=(OutputRedirect &&) = delete;
12822
12823 OutputRedirect(std::string &stdout_dest, std::string &stderr_dest);
12824 ~OutputRedirect();
12825
12826 private:
12827 int m_originalStdout = -1;
12828 int m_originalStderr = -1;
12829 TempFile m_stdoutFile;
12830 TempFile m_stderrFile;
12831 std::string &m_stdoutDest;
12832 std::string &m_stderrDest;
12833 };
12834
12835 #endif
12836
12837 } // end namespace Catch
12838
12839 #endif // TWOBLUECUBES_CATCH_OUTPUT_REDIRECT_H
12840 // end catch_output_redirect.h
12841 #include <cstdio>
12842 #include <cstring>
12843 #include <fstream>
12844 #include <sstream>
12845 #include <stdexcept>
12846
12847 #if defined(CATCH_CONFIG_NEW_CAPTURE)
12848 #if defined(_MSC_VER)
12849 #include <io.h> //_dup and _dup2
12850 #define dup _dup
12851 #define dup2 _dup2
12852 #define fileno _fileno
12853 #else
12854 #include <unistd.h> // dup and dup2
12855 #endif
12856 #endif
12857
12858 namespace Catch {
12859
12860 RedirectedStream::RedirectedStream(std::ostream &originalStream, std::ostream &redirectionStream)
12861 : m_originalStream(originalStream), m_redirectionStream(redirectionStream),
12862 m_prevBuf(m_originalStream.rdbuf())
12863 {
12864 m_originalStream.rdbuf(m_redirectionStream.rdbuf());
12865 }
12866
12867 RedirectedStream::~RedirectedStream() { m_originalStream.rdbuf(m_prevBuf); }
12868
12869 RedirectedStdOut::RedirectedStdOut() : m_cout(Catch::cout(), m_rss.get()) {}
12870 auto RedirectedStdOut::str() const -> std::string { return m_rss.str(); }
12871
12872 RedirectedStdErr::RedirectedStdErr()
12873 : m_cerr(Catch::cerr(), m_rss.get()), m_clog(Catch::clog(), m_rss.get())
12874 {
12875 }
12876 auto RedirectedStdErr::str() const -> std::string { return m_rss.str(); }
12877
12878 RedirectedStreams::RedirectedStreams(std::string &redirectedCout, std::string &redirectedCerr)
12879 : m_redirectedCout(redirectedCout), m_redirectedCerr(redirectedCerr)
12880 {
12881 }
12882
12883 RedirectedStreams::~RedirectedStreams()
12884 {
12885 m_redirectedCout += m_redirectedStdOut.str();
12886 m_redirectedCerr += m_redirectedStdErr.str();
12887 }
12888
12889 #if defined(CATCH_CONFIG_NEW_CAPTURE)
12890
12891 #if defined(_MSC_VER)
12892 TempFile::TempFile()
12893 {
12894 if (tmpnam_s(m_buffer)) {
12895 CATCH_RUNTIME_ERROR("Could not get a temp filename");
12896 }
12897 if (fopen_s(&m_file, m_buffer, "w+")) {
12898 char buffer[100];
12899 if (strerror_s(buffer, errno)) {
12900 CATCH_RUNTIME_ERROR("Could not translate errno to a string");
12901 }
12902 CATCH_RUNTIME_ERROR("Could not open the temp file: '" << m_buffer << "' because: " << buffer);
12903 }
12904 }
12905 #else
12906 TempFile::TempFile()
12907 {
12908 m_file = std::tmpfile();
12909 if (!m_file) {
12910 CATCH_RUNTIME_ERROR("Could not create a temp file.");
12911 }
12912 }
12913
12914 #endif
12915
12916 TempFile::~TempFile()
12917 {
12918 // TBD: What to do about errors here?
12919 std::fclose(m_file);
12920 // We manually create the file on Windows only, on Linux
12921 // it will be autodeleted
12922 #if defined(_MSC_VER)
12923 std::remove(m_buffer);
12924 #endif
12925 }
12926
12927 FILE *TempFile::getFile() { return m_file; }
12928
12929 std::string TempFile::getContents()
12930 {
12931 std::stringstream sstr;
12932 char buffer[100] = {};
12933 std::rewind(m_file);
12934 while (std::fgets(buffer, sizeof(buffer), m_file)) {
12935 sstr << buffer;
12936 }
12937 return sstr.str();
12938 }
12939
12940 OutputRedirect::OutputRedirect(std::string &stdout_dest, std::string &stderr_dest)
12941 : m_originalStdout(dup(1)), m_originalStderr(dup(2)), m_stdoutDest(stdout_dest),
12942 m_stderrDest(stderr_dest)
12943 {
12944 dup2(fileno(m_stdoutFile.getFile()), 1);
12945 dup2(fileno(m_stderrFile.getFile()), 2);
12946 }
12947
12948 OutputRedirect::~OutputRedirect()
12949 {
12950 Catch::cout() << std::flush;
12951 fflush(stdout);
12952 // Since we support overriding these streams, we flush cerr
12953 // even though std::cerr is unbuffered
12954 Catch::cerr() << std::flush;
12955 Catch::clog() << std::flush;
12956 fflush(stderr);
12957
12958 dup2(m_originalStdout, 1);
12959 dup2(m_originalStderr, 2);
12960
12961 m_stdoutDest += m_stdoutFile.getContents();
12962 m_stderrDest += m_stderrFile.getContents();
12963 }
12964
12965 #endif // CATCH_CONFIG_NEW_CAPTURE
12966
12967 } // namespace Catch
12968
12969 #if defined(CATCH_CONFIG_NEW_CAPTURE)
12970 #if defined(_MSC_VER)
12971 #undef dup
12972 #undef dup2
12973 #undef fileno
12974 #endif
12975 #endif
12976 // end catch_output_redirect.cpp
12977 // start catch_polyfills.cpp
12978
12979 #include <cmath>
12980
12981 namespace Catch {
12982
12983 #if !defined(CATCH_CONFIG_POLYFILL_ISNAN)
12984 bool isnan(float f) { return std::isnan(f); }
12985 bool isnan(double d) { return std::isnan(d); }
12986 #else
12987 // For now we only use this for embarcadero
12988 bool isnan(float f) { return std::_isnan(f); }
12989 bool isnan(double d) { return std::_isnan(d); }
12990 #endif
12991
12992 } // end namespace Catch
12993 // end catch_polyfills.cpp
12994 // start catch_random_number_generator.cpp
12995
12996 namespace Catch {
12997
12998 namespace {
12999
13000 #if defined(_MSC_VER)
13001 #pragma warning(push)
13002 #pragma warning(disable : 4146) // we negate uint32 during the rotate
13003 #endif
13004 // Safe rotr implementation thanks to John Regehr
13005 uint32_t rotate_right(uint32_t val, uint32_t count)
13006 {
13007 const uint32_t mask = 31;
13008 count &= mask;
13009 return (val >> count) | (val << (-count & mask));
13010 }
13011
13012 #if defined(_MSC_VER)
13013 #pragma warning(pop)
13014 #endif
13015
13016 } // namespace
13017
13018 SimplePcg32::SimplePcg32(result_type seed_) { seed(seed_); }
13019
13020 void SimplePcg32::seed(result_type seed_)
13021 {
13022 m_state = 0;
13023 (*this)();
13024 m_state += seed_;
13025 (*this)();
13026 }
13027
13028 void SimplePcg32::discard(uint64_t skip)
13029 {
13030 // We could implement this to run in O(log n) steps, but this
13031 // should suffice for our use case.
13032 for (uint64_t s = 0; s < skip; ++s) {
13033 static_cast<void>((*this)());
13034 }
13035 }
13036
13037 SimplePcg32::result_type SimplePcg32::operator()()
13038 {
13039 // prepare the output value
13040 const uint32_t xorshifted = static_cast<uint32_t>(((m_state >> 18u) ^ m_state) >> 27u);
13041 const auto output = rotate_right(xorshifted, m_state >> 59u);
13042
13043 // advance state
13044 m_state = m_state * 6364136223846793005ULL + s_inc;
13045
13046 return output;
13047 }
13048
13049 bool operator==(SimplePcg32 const &lhs, SimplePcg32 const &rhs)
13050 {
13051 return lhs.m_state == rhs.m_state;
13052 }
13053
13054 bool operator!=(SimplePcg32 const &lhs, SimplePcg32 const &rhs)
13055 {
13056 return lhs.m_state != rhs.m_state;
13057 }
13058 } // namespace Catch
13059 // end catch_random_number_generator.cpp
13060 // start catch_registry_hub.cpp
13061
13062 // start catch_test_case_registry_impl.h
13063
13064 #include <algorithm>
13065 #include <ios>
13066 #include <set>
13067 #include <vector>
13068
13069 namespace Catch {
13070
13071 class TestCase;
13072 struct IConfig;
13073
13074 std::vector<TestCase> sortTests(IConfig const &config,
13075 std::vector<TestCase> const &unsortedTestCases);
13076
13077 bool isThrowSafe(TestCase const &testCase, IConfig const &config);
13078 bool matchTest(TestCase const &testCase, TestSpec const &testSpec, IConfig const &config);
13079
13080 void enforceNoDuplicateTestCases(std::vector<TestCase> const &functions);
13081
13082 std::vector<TestCase> filterTests(std::vector<TestCase> const &testCases,
13083 TestSpec const &testSpec, IConfig const &config);
13084 std::vector<TestCase> const &getAllTestCasesSorted(IConfig const &config);
13085
13086 class TestRegistry : public ITestCaseRegistry
13087 {
13088 public:
13089 virtual ~TestRegistry() = default;
13090
13091 virtual void registerTest(TestCase const &testCase);
13092
13093 std::vector<TestCase> const &getAllTests() const override;
13094 std::vector<TestCase> const &getAllTestsSorted(IConfig const &config) const override;
13095
13096 private:
13097 std::vector<TestCase> m_functions;
13098 mutable RunTests::InWhatOrder m_currentSortOrder = RunTests::InDeclarationOrder;
13099 mutable std::vector<TestCase> m_sortedFunctions;
13100 std::size_t m_unnamedCount = 0;
13101 std::ios_base::Init m_ostreamInit; // Forces cout/ cerr to be initialised
13102 };
13103
13104 ///////////////////////////////////////////////////////////////////////////
13105
13106 class TestInvokerAsFunction : public ITestInvoker
13107 {
13108 void (*m_testAsFunction)();
13109
13110 public:
13111 TestInvokerAsFunction(void (*testAsFunction)()) noexcept;
13112
13113 void invoke() const override;
13114 };
13115
13116 std::string extractClassName(StringRef const &classOrQualifiedMethodName);
13117
13118 ///////////////////////////////////////////////////////////////////////////
13119
13120 } // end namespace Catch
13121
13122 // end catch_test_case_registry_impl.h
13123 // start catch_reporter_registry.h
13124
13125 #include <map>
13126
13127 namespace Catch {
13128
13129 class ReporterRegistry : public IReporterRegistry
13130 {
13131
13132 public:
13133 ~ReporterRegistry() override;
13134
13135 IStreamingReporterPtr create(std::string const &name, IConfigPtr const &config) const override;
13136
13137 void registerReporter(std::string const &name, IReporterFactoryPtr const &factory);
13138 void registerListener(IReporterFactoryPtr const &factory);
13139
13140 FactoryMap const &getFactories() const override;
13141 Listeners const &getListeners() const override;
13142
13143 private:
13144 FactoryMap m_factories;
13145 Listeners m_listeners;
13146 };
13147 } // namespace Catch
13148
13149 // end catch_reporter_registry.h
13150 // start catch_tag_alias_registry.h
13151
13152 // start catch_tag_alias.h
13153
13154 #include <string>
13155
13156 namespace Catch {
13157
13158 struct TagAlias
13159 {
13160 TagAlias(std::string const &_tag, SourceLineInfo _lineInfo);
13161
13162 std::string tag;
13163 SourceLineInfo lineInfo;
13164 };
13165
13166 } // end namespace Catch
13167
13168 // end catch_tag_alias.h
13169 #include <map>
13170
13171 namespace Catch {
13172
13173 class TagAliasRegistry : public ITagAliasRegistry
13174 {
13175 public:
13176 ~TagAliasRegistry() override;
13177 TagAlias const *find(std::string const &alias) const override;
13178 std::string expandAliases(std::string const &unexpandedTestSpec) const override;
13179 void add(std::string const &alias, std::string const &tag, SourceLineInfo const &lineInfo);
13180
13181 private:
13182 std::map<std::string, TagAlias> m_registry;
13183 };
13184
13185 } // end namespace Catch
13186
13187 // end catch_tag_alias_registry.h
13188 // start catch_startup_exception_registry.h
13189
13190 #include <exception>
13191 #include <vector>
13192
13193 namespace Catch {
13194
13195 class StartupExceptionRegistry
13196 {
13197 #if !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
13198 public:
13199 void add(std::exception_ptr const &exception) noexcept;
13200 std::vector<std::exception_ptr> const &getExceptions() const noexcept;
13201
13202 private:
13203 std::vector<std::exception_ptr> m_exceptions;
13204 #endif
13205 };
13206
13207 } // end namespace Catch
13208
13209 // end catch_startup_exception_registry.h
13210 // start catch_singletons.hpp
13211
13212 namespace Catch {
13213
13214 struct ISingleton
13215 {
13216 virtual ~ISingleton();
13217 };
13218
13219 void addSingleton(ISingleton *singleton);
13220 void cleanupSingletons();
13221
13222 template <typename SingletonImplT, typename InterfaceT = SingletonImplT,
13223 typename MutableInterfaceT = InterfaceT>
13224 class Singleton : SingletonImplT, public ISingleton
13225 {
13226
13227 static auto getInternal() -> Singleton *
13228 {
13229 static Singleton *s_instance = nullptr;
13230 if (!s_instance) {
13231 s_instance = new Singleton;
13232 addSingleton(s_instance);
13233 }
13234 return s_instance;
13235 }
13236
13237 public:
13238 static auto get() -> InterfaceT const & { return *getInternal(); }
13239 static auto getMutable() -> MutableInterfaceT & { return *getInternal(); }
13240 };
13241
13242 } // namespace Catch
13243
13244 // end catch_singletons.hpp
13245 namespace Catch {
13246
13247 namespace {
13248
13249 class RegistryHub : public IRegistryHub, public IMutableRegistryHub, private NonCopyable
13250 {
13251
13252 public: // IRegistryHub
13253 RegistryHub() = default;
13254 IReporterRegistry const &getReporterRegistry() const override { return m_reporterRegistry; }
13255 ITestCaseRegistry const &getTestCaseRegistry() const override { return m_testCaseRegistry; }
13256 IExceptionTranslatorRegistry const &getExceptionTranslatorRegistry() const override
13257 {
13258 return m_exceptionTranslatorRegistry;
13259 }
13260 ITagAliasRegistry const &getTagAliasRegistry() const override { return m_tagAliasRegistry; }
13261 StartupExceptionRegistry const &getStartupExceptionRegistry() const override
13262 {
13263 return m_exceptionRegistry;
13264 }
13265
13266 public: // IMutableRegistryHub
13267 void registerReporter(std::string const &name, IReporterFactoryPtr const &factory) override
13268 {
13269 m_reporterRegistry.registerReporter(name, factory);
13270 }
13271 void registerListener(IReporterFactoryPtr const &factory) override
13272 {
13273 m_reporterRegistry.registerListener(factory);
13274 }
13275 void registerTest(TestCase const &testInfo) override
13276 {
13277 m_testCaseRegistry.registerTest(testInfo);
13278 }
13279 void registerTranslator(const IExceptionTranslator *translator) override
13280 {
13281 m_exceptionTranslatorRegistry.registerTranslator(translator);
13282 }
13283 void registerTagAlias(std::string const &alias, std::string const &tag,
13284 SourceLineInfo const &lineInfo) override
13285 {
13286 m_tagAliasRegistry.add(alias, tag, lineInfo);
13287 }
13288 void registerStartupException() noexcept override
13289 {
13290 #if !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
13291 m_exceptionRegistry.add(std::current_exception());
13292 #else
13293 CATCH_INTERNAL_ERROR(
13294 "Attempted to register active exception under CATCH_CONFIG_DISABLE_EXCEPTIONS!");
13295 #endif
13296 }
13297 IMutableEnumValuesRegistry &getMutableEnumValuesRegistry() override
13298 {
13299 return m_enumValuesRegistry;
13300 }
13301
13302 private:
13303 TestRegistry m_testCaseRegistry;
13304 ReporterRegistry m_reporterRegistry;
13305 ExceptionTranslatorRegistry m_exceptionTranslatorRegistry;
13306 TagAliasRegistry m_tagAliasRegistry;
13307 StartupExceptionRegistry m_exceptionRegistry;
13308 Detail::EnumValuesRegistry m_enumValuesRegistry;
13309 };
13310 } // namespace
13311
13312 using RegistryHubSingleton = Singleton<RegistryHub, IRegistryHub, IMutableRegistryHub>;
13313
13314 IRegistryHub const &getRegistryHub() { return RegistryHubSingleton::get(); }
13315 IMutableRegistryHub &getMutableRegistryHub() { return RegistryHubSingleton::getMutable(); }
13316 void cleanUp()
13317 {
13318 cleanupSingletons();
13319 cleanUpContext();
13320 }
13321 std::string translateActiveException()
13322 {
13323 return getRegistryHub().getExceptionTranslatorRegistry().translateActiveException();
13324 }
13325
13326 } // end namespace Catch
13327 // end catch_registry_hub.cpp
13328 // start catch_reporter_registry.cpp
13329
13330 namespace Catch {
13331
13332 ReporterRegistry::~ReporterRegistry() = default;
13333
13334 IStreamingReporterPtr ReporterRegistry::create(std::string const &name,
13335 IConfigPtr const &config) const
13336 {
13337 auto it = m_factories.find(name);
13338 if (it == m_factories.end())
13339 return nullptr;
13340 return it->second->create(ReporterConfig(config));
13341 }
13342
13343 void ReporterRegistry::registerReporter(std::string const &name,
13344 IReporterFactoryPtr const &factory)
13345 {
13346 m_factories.emplace(name, factory);
13347 }
13348 void ReporterRegistry::registerListener(IReporterFactoryPtr const &factory)
13349 {
13350 m_listeners.push_back(factory);
13351 }
13352
13353 IReporterRegistry::FactoryMap const &ReporterRegistry::getFactories() const
13354 {
13355 return m_factories;
13356 }
13357 IReporterRegistry::Listeners const &ReporterRegistry::getListeners() const { return m_listeners; }
13358
13359 } // namespace Catch
13360 // end catch_reporter_registry.cpp
13361 // start catch_result_type.cpp
13362
13363 namespace Catch {
13364
13365 bool isOk(ResultWas::OfType resultType) { return (resultType & ResultWas::FailureBit) == 0; }
13366 bool isJustInfo(int flags) { return flags == ResultWas::Info; }
13367
13368 ResultDisposition::Flags operator|(ResultDisposition::Flags lhs, ResultDisposition::Flags rhs)
13369 {
13370 return static_cast<ResultDisposition::Flags>(static_cast<int>(lhs) | static_cast<int>(rhs));
13371 }
13372
13373 bool shouldContinueOnFailure(int flags)
13374 {
13375 return (flags & ResultDisposition::ContinueOnFailure) != 0;
13376 }
13377 bool shouldSuppressFailure(int flags) { return (flags & ResultDisposition::SuppressFail) != 0; }
13378
13379 } // end namespace Catch
13380 // end catch_result_type.cpp
13381 // start catch_run_context.cpp
13382
13383 #include <algorithm>
13384 #include <cassert>
13385 #include <sstream>
13386
13387 namespace Catch {
13388
13389 namespace Generators {
13390 struct GeneratorTracker : TestCaseTracking::TrackerBase, IGeneratorTracker
13391 {
13392 GeneratorBasePtr m_generator;
13393
13394 GeneratorTracker(TestCaseTracking::NameAndLocation const &nameAndLocation,
13395 TrackerContext &ctx, ITracker *parent)
13396 : TrackerBase(nameAndLocation, ctx, parent)
13397 {
13398 }
13399 ~GeneratorTracker();
13400
13401 static GeneratorTracker &acquire(TrackerContext &ctx,
13402 TestCaseTracking::NameAndLocation const &nameAndLocation)
13403 {
13404 std::shared_ptr<GeneratorTracker> tracker;
13405
13406 ITracker &currentTracker = ctx.currentTracker();
13407 // Under specific circumstances, the generator we want
13408 // to acquire is also the current tracker. If this is
13409 // the case, we have to avoid looking through current
13410 // tracker's children, and instead return the current
13411 // tracker.
13412 // A case where this check is important is e.g.
13413 // for (int i = 0; i < 5; ++i) {
13414 // int n = GENERATE(1, 2);
13415 // }
13416 //
13417 // without it, the code above creates 5 nested generators.
13418 if (currentTracker.nameAndLocation() == nameAndLocation) {
13419 auto thisTracker = currentTracker.parent().findChild(nameAndLocation);
13420 assert(thisTracker);
13421 assert(thisTracker->isGeneratorTracker());
13422 tracker = std::static_pointer_cast<GeneratorTracker>(thisTracker);
13423 }
13424 else if (TestCaseTracking::ITrackerPtr childTracker =
13425 currentTracker.findChild(nameAndLocation)) {
13426 assert(childTracker);
13427 assert(childTracker->isGeneratorTracker());
13428 tracker = std::static_pointer_cast<GeneratorTracker>(childTracker);
13429 }
13430 else {
13431 tracker = std::make_shared<GeneratorTracker>(nameAndLocation, ctx, &currentTracker);
13432 currentTracker.addChild(tracker);
13433 }
13434
13435 if (!tracker->isComplete()) {
13436 tracker->open();
13437 }
13438
13439 return *tracker;
13440 }
13441
13442 // TrackerBase interface
13443 bool isGeneratorTracker() const override { return true; }
13444 auto hasGenerator() const -> bool override { return !!m_generator; }
13445 void close() override
13446 {
13447 TrackerBase::close();
13448 // If a generator has a child (it is followed by a section)
13449 // and none of its children have started, then we must wait
13450 // until later to start consuming its values.
13451 // This catches cases where `GENERATE` is placed between two
13452 // `SECTION`s.
13453 // **The check for m_children.empty cannot be removed**.
13454 // doing so would break `GENERATE` _not_ followed by `SECTION`s.
13455 const bool should_wait_for_child = [&]() {
13456 // No children -> nobody to wait for
13457 if (m_children.empty()) {
13458 return false;
13459 }
13460 // If at least one child started executing, don't wait
13461 if (std::find_if(m_children.begin(), m_children.end(),
13462 [](TestCaseTracking::ITrackerPtr tracker) {
13463 return tracker->hasStarted();
13464 }) != m_children.end()) {
13465 return false;
13466 }
13467
13468 // No children have started. We need to check if they _can_
13469 // start, and thus we should wait for them, or they cannot
13470 // start (due to filters), and we shouldn't wait for them
13471 auto *parent = m_parent;
13472 // This is safe: there is always at least one section
13473 // tracker in a test case tracking tree
13474 while (!parent->isSectionTracker()) {
13475 parent = &(parent->parent());
13476 }
13477 assert(parent && "Missing root (test case) level section");
13478
13479 auto const &parentSection = static_cast<SectionTracker &>(*parent);
13480 auto const &filters = parentSection.getFilters();
13481 // No filters -> no restrictions on running sections
13482 if (filters.empty()) {
13483 return true;
13484 }
13485
13486 for (auto const &child : m_children) {
13487 if (child->isSectionTracker() &&
13488 std::find(filters.begin(), filters.end(),
13489 static_cast<SectionTracker &>(*child).trimmedName()) != filters.end()) {
13490 return true;
13491 }
13492 }
13493 return false;
13494 }();
13495
13496 // This check is a bit tricky, because m_generator->next()
13497 // has a side-effect, where it consumes generator's current
13498 // value, but we do not want to invoke the side-effect if
13499 // this generator is still waiting for any child to start.
13500 if (should_wait_for_child || (m_runState == CompletedSuccessfully && m_generator->next())) {
13501 m_children.clear();
13502 m_runState = Executing;
13503 }
13504 }
13505
13506 // IGeneratorTracker interface
13507 auto getGenerator() const -> GeneratorBasePtr const & override { return m_generator; }
13508 void setGenerator(GeneratorBasePtr &&generator) override
13509 {
13510 m_generator = std::move(generator);
13511 }
13512 };
13513 GeneratorTracker::~GeneratorTracker() {}
13514 } // namespace Generators
13515
13516 RunContext::RunContext(IConfigPtr const &_config, IStreamingReporterPtr &&reporter)
13517 : m_runInfo(_config->name()), m_context(getCurrentMutableContext()), m_config(_config),
13518 m_reporter(std::move(reporter)),
13519 m_lastAssertionInfo{StringRef(), SourceLineInfo("", 0), StringRef(),
13520 ResultDisposition::Normal},
13521 m_includeSuccessfulResults(m_config->includeSuccessfulResults() ||
13522 m_reporter->getPreferences().shouldReportAllAssertions)
13523 {
13524 m_context.setRunner(this);
13525 m_context.setConfig(m_config);
13526 m_context.setResultCapture(this);
13527 m_reporter->testRunStarting(m_runInfo);
13528 }
13529
13530 RunContext::~RunContext()
13531 {
13532 m_reporter->testRunEnded(TestRunStats(m_runInfo, m_totals, aborting()));
13533 }
13534
13535 void RunContext::testGroupStarting(std::string const &testSpec, std::size_t groupIndex,
13536 std::size_t groupsCount)
13537 {
13538 m_reporter->testGroupStarting(GroupInfo(testSpec, groupIndex, groupsCount));
13539 }
13540
13541 void RunContext::testGroupEnded(std::string const &testSpec, Totals const &totals,
13542 std::size_t groupIndex, std::size_t groupsCount)
13543 {
13544 m_reporter->testGroupEnded(
13545 TestGroupStats(GroupInfo(testSpec, groupIndex, groupsCount), totals, aborting()));
13546 }
13547
13548 Totals RunContext::runTest(TestCase const &testCase)
13549 {
13550 Totals prevTotals = m_totals;
13551
13552 std::string redirectedCout;
13553 std::string redirectedCerr;
13554
13555 auto const &testInfo = testCase.getTestCaseInfo();
13556
13557 m_reporter->testCaseStarting(testInfo);
13558
13559 m_activeTestCase = &testCase;
13560
13561 ITracker &rootTracker = m_trackerContext.startRun();
13562 assert(rootTracker.isSectionTracker());
13563 static_cast<SectionTracker &>(rootTracker).addInitialFilters(m_config->getSectionsToRun());
13564 do {
13565 m_trackerContext.startCycle();
13566 m_testCaseTracker = &SectionTracker::acquire(
13567 m_trackerContext, TestCaseTracking::NameAndLocation(testInfo.name, testInfo.lineInfo));
13568 runCurrentTest(redirectedCout, redirectedCerr);
13569 } while (!m_testCaseTracker->isSuccessfullyCompleted() && !aborting());
13570
13571 Totals deltaTotals = m_totals.delta(prevTotals);
13572 if (testInfo.expectedToFail() && deltaTotals.testCases.passed > 0) {
13573 deltaTotals.assertions.failed++;
13574 deltaTotals.testCases.passed--;
13575 deltaTotals.testCases.failed++;
13576 }
13577 m_totals.testCases += deltaTotals.testCases;
13578 m_reporter->testCaseEnded(
13579 TestCaseStats(testInfo, deltaTotals, redirectedCout, redirectedCerr, aborting()));
13580
13581 m_activeTestCase = nullptr;
13582 m_testCaseTracker = nullptr;
13583
13584 return deltaTotals;
13585 }
13586
13587 IConfigPtr RunContext::config() const { return m_config; }
13588
13589 IStreamingReporter &RunContext::reporter() const { return *m_reporter; }
13590
13591 void RunContext::assertionEnded(AssertionResult const &result)
13592 {
13593 if (result.getResultType() == ResultWas::Ok) {
13594 m_totals.assertions.passed++;
13595 m_lastAssertionPassed = true;
13596 }
13597 else if (!result.isOk()) {
13598 m_lastAssertionPassed = false;
13599 if (m_activeTestCase->getTestCaseInfo().okToFail())
13600 m_totals.assertions.failedButOk++;
13601 else
13602 m_totals.assertions.failed++;
13603 }
13604 else {
13605 m_lastAssertionPassed = true;
13606 }
13607
13608 // We have no use for the return value (whether messages should be cleared), because messages
13609 // were made scoped and should be let to clear themselves out.
13610 static_cast<void>(m_reporter->assertionEnded(AssertionStats(result, m_messages, m_totals)));
13611
13612 if (result.getResultType() != ResultWas::Warning)
13613 m_messageScopes.clear();
13614
13615 // Reset working state
13616 resetAssertionInfo();
13617 m_lastResult = result;
13618 }
13619 void RunContext::resetAssertionInfo()
13620 {
13621 m_lastAssertionInfo.macroName = StringRef();
13622 m_lastAssertionInfo.capturedExpression = "{Unknown expression after the reported line}"_sr;
13623 }
13624
13625 bool RunContext::sectionStarted(SectionInfo const &sectionInfo, Counts &assertions)
13626 {
13627 ITracker &sectionTracker = SectionTracker::acquire(
13628 m_trackerContext,
13629 TestCaseTracking::NameAndLocation(sectionInfo.name, sectionInfo.lineInfo));
13630 if (!sectionTracker.isOpen())
13631 return false;
13632 m_activeSections.push_back(&sectionTracker);
13633
13634 m_lastAssertionInfo.lineInfo = sectionInfo.lineInfo;
13635
13636 m_reporter->sectionStarting(sectionInfo);
13637
13638 assertions = m_totals.assertions;
13639
13640 return true;
13641 }
13642 auto RunContext::acquireGeneratorTracker(StringRef generatorName,
13643 SourceLineInfo const &lineInfo) -> IGeneratorTracker &
13644 {
13645 using namespace Generators;
13646 GeneratorTracker &tracker = GeneratorTracker::acquire(
13647 m_trackerContext,
13648 TestCaseTracking::NameAndLocation(static_cast<std::string>(generatorName), lineInfo));
13649 m_lastAssertionInfo.lineInfo = lineInfo;
13650 return tracker;
13651 }
13652
13653 bool RunContext::testForMissingAssertions(Counts &assertions)
13654 {
13655 if (assertions.total() != 0)
13656 return false;
13657 if (!m_config->warnAboutMissingAssertions())
13658 return false;
13659 if (m_trackerContext.currentTracker().hasChildren())
13660 return false;
13661 m_totals.assertions.failed++;
13662 assertions.failed++;
13663 return true;
13664 }
13665
13666 void RunContext::sectionEnded(SectionEndInfo const &endInfo)
13667 {
13668 Counts assertions = m_totals.assertions - endInfo.prevAssertions;
13669 bool missingAssertions = testForMissingAssertions(assertions);
13670
13671 if (!m_activeSections.empty()) {
13672 m_activeSections.back()->close();
13673 m_activeSections.pop_back();
13674 }
13675
13676 m_reporter->sectionEnded(SectionStats(endInfo.sectionInfo, assertions,
13677 endInfo.durationInSeconds, missingAssertions));
13678 m_messages.clear();
13679 m_messageScopes.clear();
13680 }
13681
13682 void RunContext::sectionEndedEarly(SectionEndInfo const &endInfo)
13683 {
13684 if (m_unfinishedSections.empty())
13685 m_activeSections.back()->fail();
13686 else
13687 m_activeSections.back()->close();
13688 m_activeSections.pop_back();
13689
13690 m_unfinishedSections.push_back(endInfo);
13691 }
13692
13693 #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
13694 void RunContext::benchmarkPreparing(std::string const &name)
13695 {
13696 m_reporter->benchmarkPreparing(name);
13697 }
13698 void RunContext::benchmarkStarting(BenchmarkInfo const &info)
13699 {
13700 m_reporter->benchmarkStarting(info);
13701 }
13702 void RunContext::benchmarkEnded(BenchmarkStats<> const &stats)
13703 {
13704 m_reporter->benchmarkEnded(stats);
13705 }
13706 void RunContext::benchmarkFailed(std::string const &error) { m_reporter->benchmarkFailed(error); }
13707 #endif // CATCH_CONFIG_ENABLE_BENCHMARKING
13708
13709 void RunContext::pushScopedMessage(MessageInfo const &message) { m_messages.push_back(message); }
13710
13711 void RunContext::popScopedMessage(MessageInfo const &message)
13712 {
13713 m_messages.erase(std::remove(m_messages.begin(), m_messages.end(), message), m_messages.end());
13714 }
13715
13716 void RunContext::emplaceUnscopedMessage(MessageBuilder const &builder)
13717 {
13718 m_messageScopes.emplace_back(builder);
13719 }
13720
13721 std::string RunContext::getCurrentTestName() const
13722 {
13723 return m_activeTestCase ? m_activeTestCase->getTestCaseInfo().name : std::string();
13724 }
13725
13726 const AssertionResult *RunContext::getLastResult() const { return &(*m_lastResult); }
13727
13728 void RunContext::exceptionEarlyReported() { m_shouldReportUnexpected = false; }
13729
13730 void RunContext::handleFatalErrorCondition(StringRef message)
13731 {
13732 // First notify reporter that bad things happened
13733 m_reporter->fatalErrorEncountered(message);
13734
13735 // Don't rebuild the result -- the stringification itself can cause more fatal errors
13736 // Instead, fake a result data.
13737 AssertionResultData tempResult(ResultWas::FatalErrorCondition, {false});
13738 tempResult.message = static_cast<std::string>(message);
13739 AssertionResult result(m_lastAssertionInfo, tempResult);
13740
13741 assertionEnded(result);
13742
13743 handleUnfinishedSections();
13744
13745 // Recreate section for test case (as we will lose the one that was in scope)
13746 auto const &testCaseInfo = m_activeTestCase->getTestCaseInfo();
13747 SectionInfo testCaseSection(testCaseInfo.lineInfo, testCaseInfo.name);
13748
13749 Counts assertions;
13750 assertions.failed = 1;
13751 SectionStats testCaseSectionStats(testCaseSection, assertions, 0, false);
13752 m_reporter->sectionEnded(testCaseSectionStats);
13753
13754 auto const &testInfo = m_activeTestCase->getTestCaseInfo();
13755
13756 Totals deltaTotals;
13757 deltaTotals.testCases.failed = 1;
13758 deltaTotals.assertions.failed = 1;
13759 m_reporter->testCaseEnded(
13760 TestCaseStats(testInfo, deltaTotals, std::string(), std::string(), false));
13761 m_totals.testCases.failed++;
13762 testGroupEnded(std::string(), m_totals, 1, 1);
13763 m_reporter->testRunEnded(TestRunStats(m_runInfo, m_totals, false));
13764 }
13765
13766 bool RunContext::lastAssertionPassed() { return m_lastAssertionPassed; }
13767
13768 void RunContext::assertionPassed()
13769 {
13770 m_lastAssertionPassed = true;
13771 ++m_totals.assertions.passed;
13772 resetAssertionInfo();
13773 m_messageScopes.clear();
13774 }
13775
13776 bool RunContext::aborting() const
13777 {
13778 return m_totals.assertions.failed >= static_cast<std::size_t>(m_config->abortAfter());
13779 }
13780
13781 void RunContext::runCurrentTest(std::string &redirectedCout, std::string &redirectedCerr)
13782 {
13783 auto const &testCaseInfo = m_activeTestCase->getTestCaseInfo();
13784 SectionInfo testCaseSection(testCaseInfo.lineInfo, testCaseInfo.name);
13785 m_reporter->sectionStarting(testCaseSection);
13786 Counts prevAssertions = m_totals.assertions;
13787 double duration = 0;
13788 m_shouldReportUnexpected = true;
13789 m_lastAssertionInfo = {"TEST_CASE"_sr, testCaseInfo.lineInfo, StringRef(),
13790 ResultDisposition::Normal};
13791
13792 seedRng(*m_config);
13793
13794 Timer timer;
13795 CATCH_TRY
13796 {
13797 if (m_reporter->getPreferences().shouldRedirectStdOut) {
13798 #if !defined(CATCH_CONFIG_EXPERIMENTAL_REDIRECT)
13799 RedirectedStreams redirectedStreams(redirectedCout, redirectedCerr);
13800
13801 timer.start();
13802 invokeActiveTestCase();
13803 #else
13804 OutputRedirect r(redirectedCout, redirectedCerr);
13805 timer.start();
13806 invokeActiveTestCase();
13807 #endif
13808 }
13809 else {
13810 timer.start();
13811 invokeActiveTestCase();
13812 }
13813 duration = timer.getElapsedSeconds();
13814 }
13815 CATCH_CATCH_ANON(TestFailureException &)
13816 {
13817 // This just means the test was aborted due to failure
13818 }
13819 CATCH_CATCH_ALL
13820 {
13821 // Under CATCH_CONFIG_FAST_COMPILE, unexpected exceptions under REQUIRE assertions
13822 // are reported without translation at the point of origin.
13823 if (m_shouldReportUnexpected) {
13824 AssertionReaction dummyReaction;
13825 handleUnexpectedInflightException(m_lastAssertionInfo, translateActiveException(),
13826 dummyReaction);
13827 }
13828 }
13829 Counts assertions = m_totals.assertions - prevAssertions;
13830 bool missingAssertions = testForMissingAssertions(assertions);
13831
13832 m_testCaseTracker->close();
13833 handleUnfinishedSections();
13834 m_messages.clear();
13835 m_messageScopes.clear();
13836
13837 SectionStats testCaseSectionStats(testCaseSection, assertions, duration, missingAssertions);
13838 m_reporter->sectionEnded(testCaseSectionStats);
13839 }
13840
13841 void RunContext::invokeActiveTestCase()
13842 {
13843 FatalConditionHandler fatalConditionHandler; // Handle signals
13844 m_activeTestCase->invoke();
13845 fatalConditionHandler.reset();
13846 }
13847
13848 void RunContext::handleUnfinishedSections()
13849 {
13850 // If sections ended prematurely due to an exception we stored their
13851 // infos here so we can tear them down outside the unwind process.
13852 for (auto it = m_unfinishedSections.rbegin(), itEnd = m_unfinishedSections.rend(); it != itEnd;
13853 ++it)
13854 sectionEnded(*it);
13855 m_unfinishedSections.clear();
13856 }
13857
13858 void RunContext::handleExpr(AssertionInfo const &info, ITransientExpression const &expr,
13859 AssertionReaction &reaction)
13860 {
13861 m_reporter->assertionStarting(info);
13862
13863 bool negated = isFalseTest(info.resultDisposition);
13864 bool result = expr.getResult() != negated;
13865
13866 if (result) {
13867 if (!m_includeSuccessfulResults) {
13868 assertionPassed();
13869 }
13870 else {
13871 reportExpr(info, ResultWas::Ok, &expr, negated);
13872 }
13873 }
13874 else {
13875 reportExpr(info, ResultWas::ExpressionFailed, &expr, negated);
13876 populateReaction(reaction);
13877 }
13878 }
13879 void RunContext::reportExpr(AssertionInfo const &info, ResultWas::OfType resultType,
13880 ITransientExpression const *expr, bool negated)
13881 {
13882
13883 m_lastAssertionInfo = info;
13884 AssertionResultData data(resultType, LazyExpression(negated));
13885
13886 AssertionResult assertionResult{info, data};
13887 assertionResult.m_resultData.lazyExpression.m_transientExpression = expr;
13888
13889 assertionEnded(assertionResult);
13890 }
13891
13892 void RunContext::handleMessage(AssertionInfo const &info, ResultWas::OfType resultType,
13893 StringRef const &message, AssertionReaction &reaction)
13894 {
13895 m_reporter->assertionStarting(info);
13896
13897 m_lastAssertionInfo = info;
13898
13899 AssertionResultData data(resultType, LazyExpression(false));
13900 data.message = static_cast<std::string>(message);
13901 AssertionResult assertionResult{m_lastAssertionInfo, data};
13902 assertionEnded(assertionResult);
13903 if (!assertionResult.isOk())
13904 populateReaction(reaction);
13905 }
13906 void RunContext::handleUnexpectedExceptionNotThrown(AssertionInfo const &info,
13907 AssertionReaction &reaction)
13908 {
13909 handleNonExpr(info, Catch::ResultWas::DidntThrowException, reaction);
13910 }
13911
13912 void RunContext::handleUnexpectedInflightException(AssertionInfo const &info,
13913 std::string const &message,
13914 AssertionReaction &reaction)
13915 {
13916 m_lastAssertionInfo = info;
13917
13918 AssertionResultData data(ResultWas::ThrewException, LazyExpression(false));
13919 data.message = message;
13920 AssertionResult assertionResult{info, data};
13921 assertionEnded(assertionResult);
13922 populateReaction(reaction);
13923 }
13924
13925 void RunContext::populateReaction(AssertionReaction &reaction)
13926 {
13927 reaction.shouldDebugBreak = m_config->shouldDebugBreak();
13928 reaction.shouldThrow =
13929 aborting() || (m_lastAssertionInfo.resultDisposition & ResultDisposition::Normal);
13930 }
13931
13932 void RunContext::handleIncomplete(AssertionInfo const &info)
13933 {
13934 m_lastAssertionInfo = info;
13935
13936 AssertionResultData data(ResultWas::ThrewException, LazyExpression(false));
13937 data.message = "Exception translation was disabled by CATCH_CONFIG_FAST_COMPILE";
13938 AssertionResult assertionResult{info, data};
13939 assertionEnded(assertionResult);
13940 }
13941 void RunContext::handleNonExpr(AssertionInfo const &info, ResultWas::OfType resultType,
13942 AssertionReaction &reaction)
13943 {
13944 m_lastAssertionInfo = info;
13945
13946 AssertionResultData data(resultType, LazyExpression(false));
13947 AssertionResult assertionResult{info, data};
13948 assertionEnded(assertionResult);
13949
13950 if (!assertionResult.isOk())
13951 populateReaction(reaction);
13952 }
13953
13954 IResultCapture &getResultCapture()
13955 {
13956 if (auto *capture = getCurrentContext().getResultCapture())
13957 return *capture;
13958 else
13959 CATCH_INTERNAL_ERROR("No result capture instance");
13960 }
13961
13962 void seedRng(IConfig const &config)
13963 {
13964 if (config.rngSeed() != 0) {
13965 std::srand(config.rngSeed());
13966 rng().seed(config.rngSeed());
13967 }
13968 }
13969
13970 unsigned int rngSeed() { return getCurrentContext().getConfig()->rngSeed(); }
13971
13972 } // namespace Catch
13973 // end catch_run_context.cpp
13974 // start catch_section.cpp
13975
13976 namespace Catch {
13977
13978 Section::Section(SectionInfo const &info)
13979 : m_info(info), m_sectionIncluded(getResultCapture().sectionStarted(m_info, m_assertions))
13980 {
13981 m_timer.start();
13982 }
13983
13984 Section::~Section()
13985 {
13986 if (m_sectionIncluded) {
13987 SectionEndInfo endInfo{m_info, m_assertions, m_timer.getElapsedSeconds()};
13988 if (uncaught_exceptions())
13989 getResultCapture().sectionEndedEarly(endInfo);
13990 else
13991 getResultCapture().sectionEnded(endInfo);
13992 }
13993 }
13994
13995 // This indicates whether the section should be executed or not
13996 Section::operator bool() const { return m_sectionIncluded; }
13997
13998 } // end namespace Catch
13999 // end catch_section.cpp
14000 // start catch_section_info.cpp
14001
14002 namespace Catch {
14003
14004 SectionInfo::SectionInfo(SourceLineInfo const &_lineInfo, std::string const &_name)
14005 : name(_name), lineInfo(_lineInfo)
14006 {
14007 }
14008
14009 } // end namespace Catch
14010 // end catch_section_info.cpp
14011 // start catch_session.cpp
14012
14013 // start catch_session.h
14014
14015 #include <memory>
14016
14017 namespace Catch {
14018
14019 class Session : NonCopyable
14020 {
14021 public:
14022 Session();
14023 ~Session() override;
14024
14025 void showHelp() const;
14026 void libIdentify();
14027
14028 int applyCommandLine(int argc, char const *const *argv);
14029 #if defined(CATCH_CONFIG_WCHAR) && defined(_WIN32) && defined(UNICODE)
14030 int applyCommandLine(int argc, wchar_t const *const *argv);
14031 #endif
14032
14033 void useConfigData(ConfigData const &configData);
14034
14035 template <typename CharT> int run(int argc, CharT const *const argv[])
14036 {
14037 if (m_startupExceptions)
14038 return 1;
14039 int returnCode = applyCommandLine(argc, argv);
14040 if (returnCode == 0)
14041 returnCode = run();
14042 return returnCode;
14043 }
14044
14045 int run();
14046
14047 clara::Parser const &cli() const;
14048 void cli(clara::Parser const &newParser);
14049 ConfigData &configData();
14050 Config &config();
14051
14052 private:
14053 int runInternal();
14054
14055 clara::Parser m_cli;
14056 ConfigData m_configData;
14057 std::shared_ptr<Config> m_config;
14058 bool m_startupExceptions = false;
14059 };
14060
14061 } // end namespace Catch
14062
14063 // end catch_session.h
14064 // start catch_version.h
14065
14066 #include <iosfwd>
14067
14068 namespace Catch {
14069
14070 // Versioning information
14071 struct Version
14072 {
14073 Version(Version const &) = delete;
14074 Version &operator=(Version const &) = delete;
14075 Version(unsigned int _majorVersion, unsigned int _minorVersion, unsigned int _patchNumber,
14076 char const *const _branchName, unsigned int _buildNumber);
14077
14078 unsigned int const majorVersion;
14079 unsigned int const minorVersion;
14080 unsigned int const patchNumber;
14081
14082 // buildNumber is only used if branchName is not null
14083 char const *const branchName;
14084 unsigned int const buildNumber;
14085
14086 friend std::ostream &operator<<(std::ostream &os, Version const &version);
14087 };
14088
14089 Version const &libraryVersion();
14090 } // namespace Catch
14091
14092 // end catch_version.h
14093 #include <cstdlib>
14094 #include <iomanip>
14095 #include <iterator>
14096 #include <set>
14097
14098 namespace Catch {
14099
14100 namespace {
14101 const int MaxExitCode = 255;
14102
14103 IStreamingReporterPtr createReporter(std::string const &reporterName, IConfigPtr const &config)
14104 {
14105 auto reporter = Catch::getRegistryHub().getReporterRegistry().create(reporterName, config);
14106 CATCH_ENFORCE(reporter, "No reporter registered with name: '" << reporterName << "'");
14107
14108 return reporter;
14109 }
14110
14111 IStreamingReporterPtr makeReporter(std::shared_ptr<Config> const &config)
14112 {
14113 if (Catch::getRegistryHub().getReporterRegistry().getListeners().empty()) {
14114 return createReporter(config->getReporterName(), config);
14115 }
14116
14117 // On older platforms, returning std::unique_ptr<ListeningReporter>
14118 // when the return type is std::unique_ptr<IStreamingReporter>
14119 // doesn't compile without a std::move call. However, this causes
14120 // a warning on newer platforms. Thus, we have to work around
14121 // it a bit and downcast the pointer manually.
14122 auto ret = std::unique_ptr<IStreamingReporter>(new ListeningReporter);
14123 auto &multi = static_cast<ListeningReporter &>(*ret);
14124 auto const &listeners = Catch::getRegistryHub().getReporterRegistry().getListeners();
14125 for (auto const &listener : listeners) {
14126 multi.addListener(listener->create(Catch::ReporterConfig(config)));
14127 }
14128 multi.addReporter(createReporter(config->getReporterName(), config));
14129 return ret;
14130 }
14131
14132 class TestGroup
14133 {
14134 public:
14135 explicit TestGroup(std::shared_ptr<Config> const &config)
14136 : m_config{config}, m_context{config, makeReporter(config)}
14137 {
14138 auto const &allTestCases = getAllTestCasesSorted(*m_config);
14139 m_matches = m_config->testSpec().matchesByFilter(allTestCases, *m_config);
14140 auto const &invalidArgs = m_config->testSpec().getInvalidArgs();
14141
14142 if (m_matches.empty() && invalidArgs.empty()) {
14143 for (auto const &test : allTestCases)
14144 if (!test.isHidden())
14145 m_tests.emplace(&test);
14146 }
14147 else {
14148 for (auto const &match : m_matches)
14149 m_tests.insert(match.tests.begin(), match.tests.end());
14150 }
14151 }
14152
14153 Totals execute()
14154 {
14155 auto const &invalidArgs = m_config->testSpec().getInvalidArgs();
14156 Totals totals;
14157 m_context.testGroupStarting(m_config->name(), 1, 1);
14158 for (auto const &testCase : m_tests) {
14159 if (!m_context.aborting())
14160 totals += m_context.runTest(*testCase);
14161 else
14162 m_context.reporter().skipTest(*testCase);
14163 }
14164
14165 for (auto const &match : m_matches) {
14166 if (match.tests.empty()) {
14167 m_context.reporter().noMatchingTestCases(match.name);
14168 totals.error = -1;
14169 }
14170 }
14171
14172 if (!invalidArgs.empty()) {
14173 for (auto const &invalidArg : invalidArgs)
14174 m_context.reporter().reportInvalidArguments(invalidArg);
14175 }
14176
14177 m_context.testGroupEnded(m_config->name(), totals, 1, 1);
14178 return totals;
14179 }
14180
14181 private:
14182 using Tests = std::set<TestCase const *>;
14183
14184 std::shared_ptr<Config> m_config;
14185 RunContext m_context;
14186 Tests m_tests;
14187 TestSpec::Matches m_matches;
14188 };
14189
14190 void applyFilenamesAsTags(Catch::IConfig const &config)
14191 {
14192 auto &tests = const_cast<std::vector<TestCase> &>(getAllTestCasesSorted(config));
14193 for (auto &testCase : tests) {
14194 auto tags = testCase.tags;
14195
14196 std::string filename = testCase.lineInfo.file;
14197 auto lastSlash = filename.find_last_of("\\/");
14198 if (lastSlash != std::string::npos) {
14199 filename.erase(0, lastSlash);
14200 filename[0] = '#';
14201 }
14202
14203 auto lastDot = filename.find_last_of('.');
14204 if (lastDot != std::string::npos) {
14205 filename.erase(lastDot);
14206 }
14207
14208 tags.push_back(std::move(filename));
14209 setTags(testCase, tags);
14210 }
14211 }
14212
14213 } // namespace
14214
14215 Session::Session()
14216 {
14217 static bool alreadyInstantiated = false;
14218 if (alreadyInstantiated) {
14219 CATCH_TRY { CATCH_INTERNAL_ERROR("Only one instance of Catch::Session can ever be used"); }
14220 CATCH_CATCH_ALL { getMutableRegistryHub().registerStartupException(); }
14221 }
14222
14223 // There cannot be exceptions at startup in no-exception mode.
14224 #if !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
14225 const auto &exceptions = getRegistryHub().getStartupExceptionRegistry().getExceptions();
14226 if (!exceptions.empty()) {
14227 config();
14228 getCurrentMutableContext().setConfig(m_config);
14229
14230 m_startupExceptions = true;
14231 Colour colourGuard(Colour::Red);
14232 Catch::cerr() << "Errors occurred during startup!" << '\n';
14233 // iterate over all exceptions and notify user
14234 for (const auto &ex_ptr : exceptions) {
14235 try {
14236 std::rethrow_exception(ex_ptr);
14237 }
14238 catch (std::exception const &ex) {
14239 Catch::cerr() << Column(ex.what()).indent(2) << '\n';
14240 }
14241 }
14242 }
14243 #endif
14244
14245 alreadyInstantiated = true;
14246 m_cli = makeCommandLineParser(m_configData);
14247 }
14248 Session::~Session() { Catch::cleanUp(); }
14249
14250 void Session::showHelp() const
14251 {
14252 Catch::cout() << "\nCatch v" << libraryVersion() << "\n"
14253 << m_cli << std::endl
14254 << "For more detailed usage please see the project docs\n"
14255 << std::endl;
14256 }
14257 void Session::libIdentify()
14258 {
14259 Catch::cout() << std::left << std::setw(16) << "description: " << "A Catch2 test executable\n"
14260 << std::left << std::setw(16) << "category: " << "testframework\n"
14261 << std::left << std::setw(16) << "framework: " << "Catch Test\n"
14262 << std::left << std::setw(16) << "version: " << libraryVersion() << std::endl;
14263 }
14264
14265 int Session::applyCommandLine(int argc, char const *const *argv)
14266 {
14267 if (m_startupExceptions)
14268 return 1;
14269
14270 auto result = m_cli.parse(clara::Args(argc, argv));
14271 if (!result) {
14272 config();
14273 getCurrentMutableContext().setConfig(m_config);
14274 Catch::cerr() << Colour(Colour::Red) << "\nError(s) in input:\n"
14275 << Column(result.errorMessage()).indent(2) << "\n\n";
14276 Catch::cerr() << "Run with -? for usage\n" << std::endl;
14277 return MaxExitCode;
14278 }
14279
14280 if (m_configData.showHelp)
14281 showHelp();
14282 if (m_configData.libIdentify)
14283 libIdentify();
14284 m_config.reset();
14285 return 0;
14286 }
14287
14288 #if defined(CATCH_CONFIG_WCHAR) && defined(_WIN32) && defined(UNICODE)
14289 int Session::applyCommandLine(int argc, wchar_t const *const *argv)
14290 {
14291
14292 char **utf8Argv = new char *[argc];
14293
14294 for (int i = 0; i < argc; ++i) {
14295 int bufSize = WideCharToMultiByte(CP_UTF8, 0, argv[i], -1, nullptr, 0, nullptr, nullptr);
14296
14297 utf8Argv[i] = new char[bufSize];
14298
14299 WideCharToMultiByte(CP_UTF8, 0, argv[i], -1, utf8Argv[i], bufSize, nullptr, nullptr);
14300 }
14301
14302 int returnCode = applyCommandLine(argc, utf8Argv);
14303
14304 for (int i = 0; i < argc; ++i)
14305 delete[] utf8Argv[i];
14306
14307 delete[] utf8Argv;
14308
14309 return returnCode;
14310 }
14311 #endif
14312
14313 void Session::useConfigData(ConfigData const &configData)
14314 {
14315 m_configData = configData;
14316 m_config.reset();
14317 }
14318
14319 int Session::run()
14320 {
14321 if ((m_configData.waitForKeypress & WaitForKeypress::BeforeStart) != 0) {
14322 Catch::cout() << "...waiting for enter/ return before starting" << std::endl;
14323 static_cast<void>(std::getchar());
14324 }
14325 int exitCode = runInternal();
14326 if ((m_configData.waitForKeypress & WaitForKeypress::BeforeExit) != 0) {
14327 Catch::cout() << "...waiting for enter/ return before exiting, with code: " << exitCode
14328 << std::endl;
14329 static_cast<void>(std::getchar());
14330 }
14331 return exitCode;
14332 }
14333
14334 clara::Parser const &Session::cli() const { return m_cli; }
14335 void Session::cli(clara::Parser const &newParser) { m_cli = newParser; }
14336 ConfigData &Session::configData() { return m_configData; }
14337 Config &Session::config()
14338 {
14339 if (!m_config)
14340 m_config = std::make_shared<Config>(m_configData);
14341 return *m_config;
14342 }
14343
14344 int Session::runInternal()
14345 {
14346 if (m_startupExceptions)
14347 return 1;
14348
14349 if (m_configData.showHelp || m_configData.libIdentify) {
14350 return 0;
14351 }
14352
14353 CATCH_TRY
14354 {
14355 config(); // Force config to be constructed
14356
14357 seedRng(*m_config);
14358
14359 if (m_configData.filenamesAsTags)
14360 applyFilenamesAsTags(*m_config);
14361
14362 // Handle list request
14363 if (Option<std::size_t> listed = list(m_config))
14364 return static_cast<int>(*listed);
14365
14366 TestGroup tests{m_config};
14367 auto const totals = tests.execute();
14368
14369 if (m_config->warnAboutNoTests() && totals.error == -1)
14370 return 2;
14371
14372 // Note that on unices only the lower 8 bits are usually used, clamping
14373 // the return value to 255 prevents false negative when some multiple
14374 // of 256 tests has failed
14375 return (std::min)(MaxExitCode,
14376 (std::max)(totals.error, static_cast<int>(totals.assertions.failed)));
14377 }
14378 #if !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
14379 catch (std::exception &ex)
14380 {
14381 Catch::cerr() << ex.what() << std::endl;
14382 return MaxExitCode;
14383 }
14384 #endif
14385 }
14386
14387 } // end namespace Catch
14388 // end catch_session.cpp
14389 // start catch_singletons.cpp
14390
14391 #include <vector>
14392
14393 namespace Catch {
14394
14395 namespace {
14396 static auto getSingletons() -> std::vector<ISingleton *> *&
14397 {
14398 static std::vector<ISingleton *> *g_singletons = nullptr;
14399 if (!g_singletons)
14400 g_singletons = new std::vector<ISingleton *>();
14401 return g_singletons;
14402 }
14403 } // namespace
14404
14405 ISingleton::~ISingleton() {}
14406
14407 void addSingleton(ISingleton *singleton) { getSingletons()->push_back(singleton); }
14408 void cleanupSingletons()
14409 {
14410 auto &singletons = getSingletons();
14411 for (auto singleton : *singletons)
14412 delete singleton;
14413 delete singletons;
14414 singletons = nullptr;
14415 }
14416
14417 } // namespace Catch
14418 // end catch_singletons.cpp
14419 // start catch_startup_exception_registry.cpp
14420
14421 #if !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
14422 namespace Catch {
14423 void StartupExceptionRegistry::add(std::exception_ptr const &exception) noexcept
14424 {
14425 CATCH_TRY { m_exceptions.push_back(exception); }
14426 CATCH_CATCH_ALL
14427 {
14428 // If we run out of memory during start-up there's really not a lot more we can do about it
14429 std::terminate();
14430 }
14431 }
14432
14433 std::vector<std::exception_ptr> const &StartupExceptionRegistry::getExceptions() const noexcept
14434 {
14435 return m_exceptions;
14436 }
14437
14438 } // end namespace Catch
14439 #endif
14440 // end catch_startup_exception_registry.cpp
14441 // start catch_stream.cpp
14442
14443 #include <cstdio>
14444 #include <fstream>
14445 #include <iostream>
14446 #include <memory>
14447 #include <sstream>
14448 #include <vector>
14449
14450 namespace Catch {
14451
14452 Catch::IStream::~IStream() = default;
14453
14454 namespace Detail {
14455 namespace {
14456 template <typename WriterF, std::size_t bufferSize = 256>
14457 class StreamBufImpl : public std::streambuf
14458 {
14459 char data[bufferSize];
14460 WriterF m_writer;
14461
14462 public:
14463 StreamBufImpl() { setp(data, data + sizeof(data)); }
14464
14465 ~StreamBufImpl() noexcept { StreamBufImpl::sync(); }
14466
14467 private:
14468 int overflow(int c) override
14469 {
14470 sync();
14471
14472 if (c != EOF) {
14473 if (pbase() == epptr())
14474 m_writer(std::string(1, static_cast<char>(c)));
14475 else
14476 sputc(static_cast<char>(c));
14477 }
14478 return 0;
14479 }
14480
14481 int sync() override
14482 {
14483 if (pbase() != pptr()) {
14484 m_writer(std::string(pbase(), static_cast<std::string::size_type>(pptr() - pbase())));
14485 setp(pbase(), epptr());
14486 }
14487 return 0;
14488 }
14489 };
14490
14491 ///////////////////////////////////////////////////////////////////////////
14492
14493 struct OutputDebugWriter
14494 {
14495
14496 void operator()(std::string const &str) { writeToDebugConsole(str); }
14497 };
14498
14499 ///////////////////////////////////////////////////////////////////////////
14500
14501 class FileStream : public IStream
14502 {
14503 mutable std::ofstream m_ofs;
14504
14505 public:
14506 FileStream(StringRef filename)
14507 {
14508 m_ofs.open(filename.c_str());
14509 CATCH_ENFORCE(!m_ofs.fail(), "Unable to open file: '" << filename << "'");
14510 }
14511 ~FileStream() override = default;
14512
14513 public: // IStream
14514 std::ostream &stream() const override { return m_ofs; }
14515 };
14516
14517 ///////////////////////////////////////////////////////////////////////////
14518
14519 class CoutStream : public IStream
14520 {
14521 mutable std::ostream m_os;
14522
14523 public:
14524 // Store the streambuf from cout up-front because
14525 // cout may get redirected when running tests
14526 CoutStream() : m_os(Catch::cout().rdbuf()) {}
14527 ~CoutStream() override = default;
14528
14529 public: // IStream
14530 std::ostream &stream() const override { return m_os; }
14531 };
14532
14533 ///////////////////////////////////////////////////////////////////////////
14534
14535 class DebugOutStream : public IStream
14536 {
14537 std::unique_ptr<StreamBufImpl<OutputDebugWriter>> m_streamBuf;
14538 mutable std::ostream m_os;
14539
14540 public:
14541 DebugOutStream()
14542 : m_streamBuf(new StreamBufImpl<OutputDebugWriter>()), m_os(m_streamBuf.get())
14543 {
14544 }
14545
14546 ~DebugOutStream() override = default;
14547
14548 public: // IStream
14549 std::ostream &stream() const override { return m_os; }
14550 };
14551
14552 } // namespace
14553 } // namespace Detail
14554
14555 ///////////////////////////////////////////////////////////////////////////
14556
14557 auto makeStream(StringRef const &filename) -> IStream const *
14558 {
14559 if (filename.empty())
14560 return new Detail::CoutStream();
14561 else if (filename[0] == '%') {
14562 if (filename == "%debug")
14563 return new Detail::DebugOutStream();
14564 else
14565 CATCH_ERROR("Unrecognised stream: '" << filename << "'");
14566 }
14567 else
14568 return new Detail::FileStream(filename);
14569 }
14570
14571 // This class encapsulates the idea of a pool of ostringstreams that can be reused.
14572 struct StringStreams
14573 {
14574 std::vector<std::unique_ptr<std::ostringstream>> m_streams;
14575 std::vector<std::size_t> m_unused;
14576 std::ostringstream m_referenceStream; // Used for copy state/ flags from
14577
14578 auto add() -> std::size_t
14579 {
14580 if (m_unused.empty()) {
14581 m_streams.push_back(std::unique_ptr<std::ostringstream>(new std::ostringstream));
14582 return m_streams.size() - 1;
14583 }
14584 else {
14585 auto index = m_unused.back();
14586 m_unused.pop_back();
14587 return index;
14588 }
14589 }
14590
14591 void release(std::size_t index)
14592 {
14593 m_streams[index]->copyfmt(m_referenceStream); // Restore initial flags and other state
14594 m_unused.push_back(index);
14595 }
14596 };
14597
14598 ReusableStringStream::ReusableStringStream()
14599 : m_index(Singleton<StringStreams>::getMutable().add()),
14600 m_oss(Singleton<StringStreams>::getMutable().m_streams[m_index].get())
14601 {
14602 }
14603
14604 ReusableStringStream::~ReusableStringStream()
14605 {
14606 static_cast<std::ostringstream *>(m_oss)->str("");
14607 m_oss->clear();
14608 Singleton<StringStreams>::getMutable().release(m_index);
14609 }
14610
14611 auto ReusableStringStream::str() const -> std::string
14612 {
14613 return static_cast<std::ostringstream *>(m_oss)->str();
14614 }
14615
14616 ///////////////////////////////////////////////////////////////////////////
14617
14618 #ifndef CATCH_CONFIG_NOSTDOUT // If you #define this you must implement these functions
14619 std::ostream &cout() { return std::cout; }
14620 std::ostream &cerr() { return std::cerr; }
14621 std::ostream &clog() { return std::clog; }
14622 #endif
14623 } // namespace Catch
14624 // end catch_stream.cpp
14625 // start catch_string_manip.cpp
14626
14627 #include <algorithm>
14628 #include <cctype>
14629 #include <cstring>
14630 #include <ostream>
14631 #include <vector>
14632
14633 namespace Catch {
14634
14635 namespace {
14636 char toLowerCh(char c)
14637 {
14638 return static_cast<char>(std::tolower(static_cast<unsigned char>(c)));
14639 }
14640 } // namespace
14641
14642 bool startsWith(std::string const &s, std::string const &prefix)
14643 {
14644 return s.size() >= prefix.size() && std::equal(prefix.begin(), prefix.end(), s.begin());
14645 }
14646 bool startsWith(std::string const &s, char prefix) { return !s.empty() && s[0] == prefix; }
14647 bool endsWith(std::string const &s, std::string const &suffix)
14648 {
14649 return s.size() >= suffix.size() && std::equal(suffix.rbegin(), suffix.rend(), s.rbegin());
14650 }
14651 bool endsWith(std::string const &s, char suffix)
14652 {
14653 return !s.empty() && s[s.size() - 1] == suffix;
14654 }
14655 bool contains(std::string const &s, std::string const &infix)
14656 {
14657 return s.find(infix) != std::string::npos;
14658 }
14659 void toLowerInPlace(std::string &s) { std::transform(s.begin(), s.end(), s.begin(), toLowerCh); }
14660 std::string toLower(std::string const &s)
14661 {
14662 std::string lc = s;
14663 toLowerInPlace(lc);
14664 return lc;
14665 }
14666 std::string trim(std::string const &str)
14667 {
14668 static char const *whitespaceChars = "\n\r\t ";
14669 std::string::size_type start = str.find_first_not_of(whitespaceChars);
14670 std::string::size_type end = str.find_last_not_of(whitespaceChars);
14671
14672 return start != std::string::npos ? str.substr(start, 1 + end - start) : std::string();
14673 }
14674
14675 StringRef trim(StringRef ref)
14676 {
14677 const auto is_ws = [](char c) { return c == ' ' || c == '\t' || c == '\n' || c == '\r'; };
14678 size_t real_begin = 0;
14679 while (real_begin < ref.size() && is_ws(ref[real_begin])) {
14680 ++real_begin;
14681 }
14682 size_t real_end = ref.size();
14683 while (real_end > real_begin && is_ws(ref[real_end - 1])) {
14684 --real_end;
14685 }
14686
14687 return ref.substr(real_begin, real_end - real_begin);
14688 }
14689
14690 bool replaceInPlace(std::string &str, std::string const &replaceThis, std::string const &withThis)
14691 {
14692 bool replaced = false;
14693 std::size_t i = str.find(replaceThis);
14694 while (i != std::string::npos) {
14695 replaced = true;
14696 str = str.substr(0, i) + withThis + str.substr(i + replaceThis.size());
14697 if (i < str.size() - withThis.size())
14698 i = str.find(replaceThis, i + withThis.size());
14699 else
14700 i = std::string::npos;
14701 }
14702 return replaced;
14703 }
14704
14705 std::vector<StringRef> splitStringRef(StringRef str, char delimiter)
14706 {
14707 std::vector<StringRef> subStrings;
14708 std::size_t start = 0;
14709 for (std::size_t pos = 0; pos < str.size(); ++pos) {
14710 if (str[pos] == delimiter) {
14711 if (pos - start > 1)
14712 subStrings.push_back(str.substr(start, pos - start));
14713 start = pos + 1;
14714 }
14715 }
14716 if (start < str.size())
14717 subStrings.push_back(str.substr(start, str.size() - start));
14718 return subStrings;
14719 }
14720
14721 pluralise::pluralise(std::size_t count, std::string const &label) : m_count(count), m_label(label)
14722 {
14723 }
14724
14725 std::ostream &operator<<(std::ostream &os, pluralise const &pluraliser)
14726 {
14727 os << pluraliser.m_count << ' ' << pluraliser.m_label;
14728 if (pluraliser.m_count != 1)
14729 os << 's';
14730 return os;
14731 }
14732
14733 } // namespace Catch
14734 // end catch_string_manip.cpp
14735 // start catch_stringref.cpp
14736
14737 #include <algorithm>
14738 #include <cstdint>
14739 #include <cstring>
14740 #include <ostream>
14741
14742 namespace Catch {
14743 StringRef::StringRef(char const *rawChars) noexcept
14744 : StringRef(rawChars, static_cast<StringRef::size_type>(std::strlen(rawChars)))
14745 {
14746 }
14747
14748 auto StringRef::c_str() const -> char const *
14749 {
14750 CATCH_ENFORCE(isNullTerminated(),
14751 "Called StringRef::c_str() on a non-null-terminated instance");
14752 return m_start;
14753 }
14754 auto StringRef::data() const noexcept -> char const * { return m_start; }
14755
14756 auto StringRef::substr(size_type start, size_type size) const noexcept -> StringRef
14757 {
14758 if (start < m_size) {
14759 return StringRef(m_start + start, (std::min)(m_size - start, size));
14760 }
14761 else {
14762 return StringRef();
14763 }
14764 }
14765 auto StringRef::operator==(StringRef const &other) const noexcept -> bool
14766 {
14767 return m_size == other.m_size && (std::memcmp(m_start, other.m_start, m_size) == 0);
14768 }
14769
14770 auto operator<<(std::ostream &os, StringRef const &str) -> std::ostream &
14771 {
14772 return os.write(str.data(), str.size());
14773 }
14774
14775 auto operator+=(std::string &lhs, StringRef const &rhs) -> std::string &
14776 {
14777 lhs.append(rhs.data(), rhs.size());
14778 return lhs;
14779 }
14780
14781 } // namespace Catch
14782 // end catch_stringref.cpp
14783 // start catch_tag_alias.cpp
14784
14785 namespace Catch {
14786 TagAlias::TagAlias(std::string const &_tag, SourceLineInfo _lineInfo)
14787 : tag(_tag), lineInfo(_lineInfo)
14788 {
14789 }
14790 } // namespace Catch
14791 // end catch_tag_alias.cpp
14792 // start catch_tag_alias_autoregistrar.cpp
14793
14794 namespace Catch {
14795
14796 RegistrarForTagAliases::RegistrarForTagAliases(char const *alias, char const *tag,
14797 SourceLineInfo const &lineInfo)
14798 {
14799 CATCH_TRY { getMutableRegistryHub().registerTagAlias(alias, tag, lineInfo); }
14800 CATCH_CATCH_ALL
14801 {
14802 // Do not throw when constructing global objects, instead register the exception to be
14803 // processed later
14804 getMutableRegistryHub().registerStartupException();
14805 }
14806 }
14807
14808 } // namespace Catch
14809 // end catch_tag_alias_autoregistrar.cpp
14810 // start catch_tag_alias_registry.cpp
14811
14812 #include <sstream>
14813
14814 namespace Catch {
14815
14816 TagAliasRegistry::~TagAliasRegistry() {}
14817
14818 TagAlias const *TagAliasRegistry::find(std::string const &alias) const
14819 {
14820 auto it = m_registry.find(alias);
14821 if (it != m_registry.end())
14822 return &(it->second);
14823 else
14824 return nullptr;
14825 }
14826
14827 std::string TagAliasRegistry::expandAliases(std::string const &unexpandedTestSpec) const
14828 {
14829 std::string expandedTestSpec = unexpandedTestSpec;
14830 for (auto const &registryKvp : m_registry) {
14831 std::size_t pos = expandedTestSpec.find(registryKvp.first);
14832 if (pos != std::string::npos) {
14833 expandedTestSpec = expandedTestSpec.substr(0, pos) + registryKvp.second.tag +
14834 expandedTestSpec.substr(pos + registryKvp.first.size());
14835 }
14836 }
14837 return expandedTestSpec;
14838 }
14839
14840 void TagAliasRegistry::add(std::string const &alias, std::string const &tag,
14841 SourceLineInfo const &lineInfo)
14842 {
14843 CATCH_ENFORCE(startsWith(alias, "[@") && endsWith(alias, ']'),
14844 "error: tag alias, '" << alias << "' is not of the form [@alias name].\n"
14845 << lineInfo);
14846
14847 CATCH_ENFORCE(m_registry.insert(std::make_pair(alias, TagAlias(tag, lineInfo))).second,
14848 "error: tag alias, '" << alias << "' already registered.\n"
14849 << "\tFirst seen at: " << find(alias)->lineInfo << "\n"
14850 << "\tRedefined at: " << lineInfo);
14851 }
14852
14853 ITagAliasRegistry::~ITagAliasRegistry() {}
14854
14855 ITagAliasRegistry const &ITagAliasRegistry::get()
14856 {
14857 return getRegistryHub().getTagAliasRegistry();
14858 }
14859
14860 } // end namespace Catch
14861 // end catch_tag_alias_registry.cpp
14862 // start catch_test_case_info.cpp
14863
14864 #include <algorithm>
14865 #include <cctype>
14866 #include <exception>
14867 #include <sstream>
14868
14869 namespace Catch {
14870
14871 namespace {
14872 TestCaseInfo::SpecialProperties parseSpecialTag(std::string const &tag)
14873 {
14874 if (startsWith(tag, '.') || tag == "!hide")
14875 return TestCaseInfo::IsHidden;
14876 else if (tag == "!throws")
14877 return TestCaseInfo::Throws;
14878 else if (tag == "!shouldfail")
14879 return TestCaseInfo::ShouldFail;
14880 else if (tag == "!mayfail")
14881 return TestCaseInfo::MayFail;
14882 else if (tag == "!nonportable")
14883 return TestCaseInfo::NonPortable;
14884 else if (tag == "!benchmark")
14885 return static_cast<TestCaseInfo::SpecialProperties>(TestCaseInfo::Benchmark |
14886 TestCaseInfo::IsHidden);
14887 else
14888 return TestCaseInfo::None;
14889 }
14890 bool isReservedTag(std::string const &tag)
14891 {
14892 return parseSpecialTag(tag) == TestCaseInfo::None && tag.size() > 0 &&
14893 !std::isalnum(static_cast<unsigned char>(tag[0]));
14894 }
14895 void enforceNotReservedTag(std::string const &tag, SourceLineInfo const &_lineInfo)
14896 {
14897 CATCH_ENFORCE(
14898 !isReservedTag(tag),
14899 "Tag name: [" << tag << "] is not allowed.\n"
14900 << "Tag names starting with non alphanumeric characters are reserved\n"
14901 << _lineInfo);
14902 }
14903 } // namespace
14904
14905 TestCase makeTestCase(ITestInvoker *_testCase, std::string const &_className,
14906 NameAndTags const &nameAndTags, SourceLineInfo const &_lineInfo)
14907 {
14908 bool isHidden = false;
14909
14910 // Parse out tags
14911 std::vector<std::string> tags;
14912 std::string desc, tag;
14913 bool inTag = false;
14914 for (char c : nameAndTags.tags) {
14915 if (!inTag) {
14916 if (c == '[')
14917 inTag = true;
14918 else
14919 desc += c;
14920 }
14921 else {
14922 if (c == ']') {
14923 TestCaseInfo::SpecialProperties prop = parseSpecialTag(tag);
14924 if ((prop & TestCaseInfo::IsHidden) != 0)
14925 isHidden = true;
14926 else if (prop == TestCaseInfo::None)
14927 enforceNotReservedTag(tag, _lineInfo);
14928
14929 // Merged hide tags like `[.approvals]` should be added as
14930 // `[.][approvals]`. The `[.]` is added at later point, so
14931 // we only strip the prefix
14932 if (startsWith(tag, '.') && tag.size() > 1) {
14933 tag.erase(0, 1);
14934 }
14935 tags.push_back(tag);
14936 tag.clear();
14937 inTag = false;
14938 }
14939 else
14940 tag += c;
14941 }
14942 }
14943 if (isHidden) {
14944 // Add all "hidden" tags to make them behave identically
14945 tags.insert(tags.end(), {".", "!hide"});
14946 }
14947
14948 TestCaseInfo info(static_cast<std::string>(nameAndTags.name), _className, desc, tags,
14949 _lineInfo);
14950 return TestCase(_testCase, std::move(info));
14951 }
14952
14953 void setTags(TestCaseInfo &testCaseInfo, std::vector<std::string> tags)
14954 {
14955 std::sort(begin(tags), end(tags));
14956 tags.erase(std::unique(begin(tags), end(tags)), end(tags));
14957 testCaseInfo.lcaseTags.clear();
14958
14959 for (auto const &tag : tags) {
14960 std::string lcaseTag = toLower(tag);
14961 testCaseInfo.properties = static_cast<TestCaseInfo::SpecialProperties>(
14962 testCaseInfo.properties | parseSpecialTag(lcaseTag));
14963 testCaseInfo.lcaseTags.push_back(lcaseTag);
14964 }
14965 testCaseInfo.tags = std::move(tags);
14966 }
14967
14968 TestCaseInfo::TestCaseInfo(std::string const &_name, std::string const &_className,
14969 std::string const &_description, std::vector<std::string> const &_tags,
14970 SourceLineInfo const &_lineInfo)
14971 : name(_name), className(_className), description(_description), lineInfo(_lineInfo),
14972 properties(None)
14973 {
14974 setTags(*this, _tags);
14975 }
14976
14977 bool TestCaseInfo::isHidden() const { return (properties & IsHidden) != 0; }
14978 bool TestCaseInfo::throws() const { return (properties & Throws) != 0; }
14979 bool TestCaseInfo::okToFail() const { return (properties & (ShouldFail | MayFail)) != 0; }
14980 bool TestCaseInfo::expectedToFail() const { return (properties & (ShouldFail)) != 0; }
14981
14982 std::string TestCaseInfo::tagsAsString() const
14983 {
14984 std::string ret;
14985 // '[' and ']' per tag
14986 std::size_t full_size = 2 * tags.size();
14987 for (const auto &tag : tags) {
14988 full_size += tag.size();
14989 }
14990 ret.reserve(full_size);
14991 for (const auto &tag : tags) {
14992 ret.push_back('[');
14993 ret.append(tag);
14994 ret.push_back(']');
14995 }
14996
14997 return ret;
14998 }
14999
15000 TestCase::TestCase(ITestInvoker *testCase, TestCaseInfo &&info)
15001 : TestCaseInfo(std::move(info)), test(testCase)
15002 {
15003 }
15004
15005 TestCase TestCase::withName(std::string const &_newName) const
15006 {
15007 TestCase other(*this);
15008 other.name = _newName;
15009 return other;
15010 }
15011
15012 void TestCase::invoke() const { test->invoke(); }
15013
15014 bool TestCase::operator==(TestCase const &other) const
15015 {
15016 return test.get() == other.test.get() && name == other.name && className == other.className;
15017 }
15018
15019 bool TestCase::operator<(TestCase const &other) const { return name < other.name; }
15020
15021 TestCaseInfo const &TestCase::getTestCaseInfo() const { return *this; }
15022
15023 } // end namespace Catch
15024 // end catch_test_case_info.cpp
15025 // start catch_test_case_registry_impl.cpp
15026
15027 #include <algorithm>
15028 #include <sstream>
15029
15030 namespace Catch {
15031
15032 namespace {
15033 struct TestHasher
15034 {
15035 using hash_t = uint64_t;
15036
15037 explicit TestHasher(hash_t hashSuffix) : m_hashSuffix{hashSuffix} {}
15038
15039 uint32_t operator()(TestCase const &t) const
15040 {
15041 // FNV-1a hash with multiplication fold.
15042 const hash_t prime = 1099511628211u;
15043 hash_t hash = 14695981039346656037u;
15044 for (const char c : t.name) {
15045 hash ^= c;
15046 hash *= prime;
15047 }
15048 hash ^= m_hashSuffix;
15049 hash *= prime;
15050 const uint32_t low{static_cast<uint32_t>(hash)};
15051 const uint32_t high{static_cast<uint32_t>(hash >> 32)};
15052 return low * high;
15053 }
15054
15055 private:
15056 hash_t m_hashSuffix;
15057 };
15058 } // end unnamed namespace
15059
15060 std::vector<TestCase> sortTests(IConfig const &config,
15061 std::vector<TestCase> const &unsortedTestCases)
15062 {
15063 switch (config.runOrder()) {
15064 case RunTests::InDeclarationOrder:
15065 // already in declaration order
15066 break;
15067
15068 case RunTests::InLexicographicalOrder: {
15069 std::vector<TestCase> sorted = unsortedTestCases;
15070 std::sort(sorted.begin(), sorted.end());
15071 return sorted;
15072 }
15073
15074 case RunTests::InRandomOrder: {
15075 seedRng(config);
15076 TestHasher h{config.rngSeed()};
15077
15078 using hashedTest = std::pair<TestHasher::hash_t, TestCase const *>;
15079 std::vector<hashedTest> indexed_tests;
15080 indexed_tests.reserve(unsortedTestCases.size());
15081
15082 for (auto const &testCase : unsortedTestCases) {
15083 indexed_tests.emplace_back(h(testCase), &testCase);
15084 }
15085
15086 std::sort(indexed_tests.begin(), indexed_tests.end(),
15087 [](hashedTest const &lhs, hashedTest const &rhs) {
15088 if (lhs.first == rhs.first) {
15089 return lhs.second->name < rhs.second->name;
15090 }
15091 return lhs.first < rhs.first;
15092 });
15093
15094 std::vector<TestCase> sorted;
15095 sorted.reserve(indexed_tests.size());
15096
15097 for (auto const &hashed : indexed_tests) {
15098 sorted.emplace_back(*hashed.second);
15099 }
15100
15101 return sorted;
15102 }
15103 }
15104 return unsortedTestCases;
15105 }
15106
15107 bool isThrowSafe(TestCase const &testCase, IConfig const &config)
15108 {
15109 return !testCase.throws() || config.allowThrows();
15110 }
15111
15112 bool matchTest(TestCase const &testCase, TestSpec const &testSpec, IConfig const &config)
15113 {
15114 return testSpec.matches(testCase) && isThrowSafe(testCase, config);
15115 }
15116
15117 void enforceNoDuplicateTestCases(std::vector<TestCase> const &functions)
15118 {
15119 std::set<TestCase> seenFunctions;
15120 for (auto const &function : functions) {
15121 auto prev = seenFunctions.insert(function);
15122 CATCH_ENFORCE(prev.second, "error: TEST_CASE( \""
15123 << function.name << "\" ) already defined.\n"
15124 << "\tFirst seen at " << prev.first->getTestCaseInfo().lineInfo
15125 << "\n"
15126 << "\tRedefined at " << function.getTestCaseInfo().lineInfo);
15127 }
15128 }
15129
15130 std::vector<TestCase> filterTests(std::vector<TestCase> const &testCases,
15131 TestSpec const &testSpec, IConfig const &config)
15132 {
15133 std::vector<TestCase> filtered;
15134 filtered.reserve(testCases.size());
15135 for (auto const &testCase : testCases) {
15136 if ((!testSpec.hasFilters() && !testCase.isHidden()) ||
15137 (testSpec.hasFilters() && matchTest(testCase, testSpec, config))) {
15138 filtered.push_back(testCase);
15139 }
15140 }
15141 return filtered;
15142 }
15143 std::vector<TestCase> const &getAllTestCasesSorted(IConfig const &config)
15144 {
15145 return getRegistryHub().getTestCaseRegistry().getAllTestsSorted(config);
15146 }
15147
15148 void TestRegistry::registerTest(TestCase const &testCase)
15149 {
15150 std::string name = testCase.getTestCaseInfo().name;
15151 if (name.empty()) {
15152 ReusableStringStream rss;
15153 rss << "Anonymous test case " << ++m_unnamedCount;
15154 return registerTest(testCase.withName(rss.str()));
15155 }
15156 m_functions.push_back(testCase);
15157 }
15158
15159 std::vector<TestCase> const &TestRegistry::getAllTests() const { return m_functions; }
15160 std::vector<TestCase> const &TestRegistry::getAllTestsSorted(IConfig const &config) const
15161 {
15162 if (m_sortedFunctions.empty())
15163 enforceNoDuplicateTestCases(m_functions);
15164
15165 if (m_currentSortOrder != config.runOrder() || m_sortedFunctions.empty()) {
15166 m_sortedFunctions = sortTests(config, m_functions);
15167 m_currentSortOrder = config.runOrder();
15168 }
15169 return m_sortedFunctions;
15170 }
15171
15172 ///////////////////////////////////////////////////////////////////////////
15173 TestInvokerAsFunction::TestInvokerAsFunction(void (*testAsFunction)()) noexcept
15174 : m_testAsFunction(testAsFunction)
15175 {
15176 }
15177
15178 void TestInvokerAsFunction::invoke() const { m_testAsFunction(); }
15179
15180 std::string extractClassName(StringRef const &classOrQualifiedMethodName)
15181 {
15182 std::string className(classOrQualifiedMethodName);
15183 if (startsWith(className, '&')) {
15184 std::size_t lastColons = className.rfind("::");
15185 std::size_t penultimateColons = className.rfind("::", lastColons - 1);
15186 if (penultimateColons == std::string::npos)
15187 penultimateColons = 1;
15188 className = className.substr(penultimateColons, lastColons - penultimateColons);
15189 }
15190 return className;
15191 }
15192
15193 } // end namespace Catch
15194 // end catch_test_case_registry_impl.cpp
15195 // start catch_test_case_tracker.cpp
15196
15197 #include <algorithm>
15198 #include <cassert>
15199 #include <memory>
15200 #include <sstream>
15201 #include <stdexcept>
15202
15203 #if defined(__clang__)
15204 #pragma clang diagnostic push
15205 #pragma clang diagnostic ignored "-Wexit-time-destructors"
15206 #endif
15207
15208 namespace Catch {
15209 namespace TestCaseTracking {
15210
15211 NameAndLocation::NameAndLocation(std::string const &_name, SourceLineInfo const &_location)
15212 : name(_name), location(_location)
15213 {
15214 }
15215
15216 ITracker::~ITracker() = default;
15217
15218 ITracker &TrackerContext::startRun()
15219 {
15220 m_rootTracker = std::make_shared<SectionTracker>(
15221 NameAndLocation("{root}", CATCH_INTERNAL_LINEINFO), *this, nullptr);
15222 m_currentTracker = nullptr;
15223 m_runState = Executing;
15224 return *m_rootTracker;
15225 }
15226
15227 void TrackerContext::endRun()
15228 {
15229 m_rootTracker.reset();
15230 m_currentTracker = nullptr;
15231 m_runState = NotStarted;
15232 }
15233
15234 void TrackerContext::startCycle()
15235 {
15236 m_currentTracker = m_rootTracker.get();
15237 m_runState = Executing;
15238 }
15239 void TrackerContext::completeCycle() { m_runState = CompletedCycle; }
15240
15241 bool TrackerContext::completedCycle() const { return m_runState == CompletedCycle; }
15242 ITracker &TrackerContext::currentTracker() { return *m_currentTracker; }
15243 void TrackerContext::setCurrentTracker(ITracker *tracker) { m_currentTracker = tracker; }
15244
15245 TrackerBase::TrackerBase(NameAndLocation const &nameAndLocation, TrackerContext &ctx,
15246 ITracker *parent)
15247 : ITracker(nameAndLocation), m_ctx(ctx), m_parent(parent)
15248 {
15249 }
15250
15251 bool TrackerBase::isComplete() const
15252 {
15253 return m_runState == CompletedSuccessfully || m_runState == Failed;
15254 }
15255 bool TrackerBase::isSuccessfullyCompleted() const
15256 {
15257 return m_runState == CompletedSuccessfully;
15258 }
15259 bool TrackerBase::isOpen() const { return m_runState != NotStarted && !isComplete(); }
15260 bool TrackerBase::hasChildren() const { return !m_children.empty(); }
15261
15262 void TrackerBase::addChild(ITrackerPtr const &child) { m_children.push_back(child); }
15263
15264 ITrackerPtr TrackerBase::findChild(NameAndLocation const &nameAndLocation)
15265 {
15266 auto it = std::find_if(
15267 m_children.begin(), m_children.end(), [&nameAndLocation](ITrackerPtr const &tracker) {
15268 return tracker->nameAndLocation().location == nameAndLocation.location &&
15269 tracker->nameAndLocation().name == nameAndLocation.name;
15270 });
15271 return (it != m_children.end()) ? *it : nullptr;
15272 }
15273 ITracker &TrackerBase::parent()
15274 {
15275 assert(m_parent); // Should always be non-null except for root
15276 return *m_parent;
15277 }
15278
15279 void TrackerBase::openChild()
15280 {
15281 if (m_runState != ExecutingChildren) {
15282 m_runState = ExecutingChildren;
15283 if (m_parent)
15284 m_parent->openChild();
15285 }
15286 }
15287
15288 bool TrackerBase::isSectionTracker() const { return false; }
15289 bool TrackerBase::isGeneratorTracker() const { return false; }
15290
15291 void TrackerBase::open()
15292 {
15293 m_runState = Executing;
15294 moveToThis();
15295 if (m_parent)
15296 m_parent->openChild();
15297 }
15298
15299 void TrackerBase::close()
15300 {
15301
15302 // Close any still open children (e.g. generators)
15303 while (&m_ctx.currentTracker() != this)
15304 m_ctx.currentTracker().close();
15305
15306 switch (m_runState) {
15307 case NeedsAnotherRun: break;
15308
15309 case Executing: m_runState = CompletedSuccessfully; break;
15310 case ExecutingChildren:
15311 if (std::all_of(m_children.begin(), m_children.end(),
15312 [](ITrackerPtr const &t) { return t->isComplete(); }))
15313 m_runState = CompletedSuccessfully;
15314 break;
15315
15316 case NotStarted:
15317 case CompletedSuccessfully:
15318 case Failed: CATCH_INTERNAL_ERROR("Illogical state: " << m_runState);
15319
15320 default: CATCH_INTERNAL_ERROR("Unknown state: " << m_runState);
15321 }
15322 moveToParent();
15323 m_ctx.completeCycle();
15324 }
15325 void TrackerBase::fail()
15326 {
15327 m_runState = Failed;
15328 if (m_parent)
15329 m_parent->markAsNeedingAnotherRun();
15330 moveToParent();
15331 m_ctx.completeCycle();
15332 }
15333 void TrackerBase::markAsNeedingAnotherRun() { m_runState = NeedsAnotherRun; }
15334
15335 void TrackerBase::moveToParent()
15336 {
15337 assert(m_parent);
15338 m_ctx.setCurrentTracker(m_parent);
15339 }
15340 void TrackerBase::moveToThis() { m_ctx.setCurrentTracker(this); }
15341
15342 SectionTracker::SectionTracker(NameAndLocation const &nameAndLocation, TrackerContext &ctx,
15343 ITracker *parent)
15344 : TrackerBase(nameAndLocation, ctx, parent), m_trimmed_name(trim(nameAndLocation.name))
15345 {
15346 if (parent) {
15347 while (!parent->isSectionTracker())
15348 parent = &parent->parent();
15349
15350 SectionTracker &parentSection = static_cast<SectionTracker &>(*parent);
15351 addNextFilters(parentSection.m_filters);
15352 }
15353 }
15354
15355 bool SectionTracker::isComplete() const
15356 {
15357 bool complete = true;
15358
15359 if (m_filters.empty() || m_filters[0] == "" ||
15360 std::find(m_filters.begin(), m_filters.end(), m_trimmed_name) != m_filters.end()) {
15361 complete = TrackerBase::isComplete();
15362 }
15363 return complete;
15364 }
15365
15366 bool SectionTracker::isSectionTracker() const { return true; }
15367
15368 SectionTracker &SectionTracker::acquire(TrackerContext &ctx,
15369 NameAndLocation const &nameAndLocation)
15370 {
15371 std::shared_ptr<SectionTracker> section;
15372
15373 ITracker &currentTracker = ctx.currentTracker();
15374 if (ITrackerPtr childTracker = currentTracker.findChild(nameAndLocation)) {
15375 assert(childTracker);
15376 assert(childTracker->isSectionTracker());
15377 section = std::static_pointer_cast<SectionTracker>(childTracker);
15378 }
15379 else {
15380 section = std::make_shared<SectionTracker>(nameAndLocation, ctx, &currentTracker);
15381 currentTracker.addChild(section);
15382 }
15383 if (!ctx.completedCycle())
15384 section->tryOpen();
15385 return *section;
15386 }
15387
15388 void SectionTracker::tryOpen()
15389 {
15390 if (!isComplete())
15391 open();
15392 }
15393
15394 void SectionTracker::addInitialFilters(std::vector<std::string> const &filters)
15395 {
15396 if (!filters.empty()) {
15397 m_filters.reserve(m_filters.size() + filters.size() + 2);
15398 m_filters.emplace_back(""); // Root - should never be consulted
15399 m_filters.emplace_back(""); // Test Case - not a section filter
15400 m_filters.insert(m_filters.end(), filters.begin(), filters.end());
15401 }
15402 }
15403 void SectionTracker::addNextFilters(std::vector<std::string> const &filters)
15404 {
15405 if (filters.size() > 1)
15406 m_filters.insert(m_filters.end(), filters.begin() + 1, filters.end());
15407 }
15408
15409 std::vector<std::string> const &SectionTracker::getFilters() const { return m_filters; }
15410
15411 std::string const &SectionTracker::trimmedName() const { return m_trimmed_name; }
15412
15413 } // namespace TestCaseTracking
15414
15415 using TestCaseTracking::ITracker;
15416 using TestCaseTracking::SectionTracker;
15417 using TestCaseTracking::TrackerContext;
15418
15419 } // namespace Catch
15420
15421 #if defined(__clang__)
15422 #pragma clang diagnostic pop
15423 #endif
15424 // end catch_test_case_tracker.cpp
15425 // start catch_test_registry.cpp
15426
15427 namespace Catch {
15428
15429 auto makeTestInvoker(void (*testAsFunction)()) noexcept -> ITestInvoker *
15430 {
15431 return new (std::nothrow) TestInvokerAsFunction(testAsFunction);
15432 }
15433
15434 NameAndTags::NameAndTags(StringRef const &name_, StringRef const &tags_) noexcept
15435 : name(name_), tags(tags_)
15436 {
15437 }
15438
15439 AutoReg::AutoReg(ITestInvoker *invoker, SourceLineInfo const &lineInfo,
15440 StringRef const &classOrMethod, NameAndTags const &nameAndTags) noexcept
15441 {
15442 CATCH_TRY
15443 {
15444 getMutableRegistryHub().registerTest(
15445 makeTestCase(invoker, extractClassName(classOrMethod), nameAndTags, lineInfo));
15446 }
15447 CATCH_CATCH_ALL
15448 {
15449 // Do not throw when constructing global objects, instead register the exception to be
15450 // processed later
15451 getMutableRegistryHub().registerStartupException();
15452 }
15453 }
15454
15455 AutoReg::~AutoReg() = default;
15456 } // namespace Catch
15457 // end catch_test_registry.cpp
15458 // start catch_test_spec.cpp
15459
15460 #include <algorithm>
15461 #include <memory>
15462 #include <string>
15463 #include <vector>
15464
15465 namespace Catch {
15466
15467 TestSpec::Pattern::Pattern(std::string const &name) : m_name(name) {}
15468
15469 TestSpec::Pattern::~Pattern() = default;
15470
15471 std::string const &TestSpec::Pattern::name() const { return m_name; }
15472
15473 TestSpec::NamePattern::NamePattern(std::string const &name, std::string const &filterString)
15474 : Pattern(filterString), m_wildcardPattern(toLower(name), CaseSensitive::No)
15475 {
15476 }
15477
15478 bool TestSpec::NamePattern::matches(TestCaseInfo const &testCase) const
15479 {
15480 return m_wildcardPattern.matches(testCase.name);
15481 }
15482
15483 TestSpec::TagPattern::TagPattern(std::string const &tag, std::string const &filterString)
15484 : Pattern(filterString), m_tag(toLower(tag))
15485 {
15486 }
15487
15488 bool TestSpec::TagPattern::matches(TestCaseInfo const &testCase) const
15489 {
15490 return std::find(begin(testCase.lcaseTags), end(testCase.lcaseTags), m_tag) !=
15491 end(testCase.lcaseTags);
15492 }
15493
15494 TestSpec::ExcludedPattern::ExcludedPattern(PatternPtr const &underlyingPattern)
15495 : Pattern(underlyingPattern->name()), m_underlyingPattern(underlyingPattern)
15496 {
15497 }
15498
15499 bool TestSpec::ExcludedPattern::matches(TestCaseInfo const &testCase) const
15500 {
15501 return !m_underlyingPattern->matches(testCase);
15502 }
15503
15504 bool TestSpec::Filter::matches(TestCaseInfo const &testCase) const
15505 {
15506 return std::all_of(m_patterns.begin(), m_patterns.end(),
15507 [&](PatternPtr const &p) { return p->matches(testCase); });
15508 }
15509
15510 std::string TestSpec::Filter::name() const
15511 {
15512 std::string name;
15513 for (auto const &p : m_patterns)
15514 name += p->name();
15515 return name;
15516 }
15517
15518 bool TestSpec::hasFilters() const { return !m_filters.empty(); }
15519
15520 bool TestSpec::matches(TestCaseInfo const &testCase) const
15521 {
15522 return std::any_of(m_filters.begin(), m_filters.end(),
15523 [&](Filter const &f) { return f.matches(testCase); });
15524 }
15525
15526 TestSpec::Matches TestSpec::matchesByFilter(std::vector<TestCase> const &testCases,
15527 IConfig const &config) const
15528 {
15529 Matches matches(m_filters.size());
15530 std::transform(m_filters.begin(), m_filters.end(), matches.begin(), [&](Filter const &filter) {
15531 std::vector<TestCase const *> currentMatches;
15532 for (auto const &test : testCases)
15533 if (isThrowSafe(test, config) && filter.matches(test))
15534 currentMatches.emplace_back(&test);
15535 return FilterMatch{filter.name(), currentMatches};
15536 });
15537 return matches;
15538 }
15539
15540 const TestSpec::vectorStrings &TestSpec::getInvalidArgs() const { return (m_invalidArgs); }
15541
15542 } // namespace Catch
15543 // end catch_test_spec.cpp
15544 // start catch_test_spec_parser.cpp
15545
15546 namespace Catch {
15547
15548 TestSpecParser::TestSpecParser(ITagAliasRegistry const &tagAliases) : m_tagAliases(&tagAliases) {}
15549
15550 TestSpecParser &TestSpecParser::parse(std::string const &arg)
15551 {
15552 m_mode = None;
15553 m_exclusion = false;
15554 m_arg = m_tagAliases->expandAliases(arg);
15555 m_escapeChars.clear();
15556 m_substring.reserve(m_arg.size());
15557 m_patternName.reserve(m_arg.size());
15558 m_realPatternPos = 0;
15559
15560 for (m_pos = 0; m_pos < m_arg.size(); ++m_pos)
15561 // if visitChar fails
15562 if (!visitChar(m_arg[m_pos])) {
15563 m_testSpec.m_invalidArgs.push_back(arg);
15564 break;
15565 }
15566 endMode();
15567 return *this;
15568 }
15569 TestSpec TestSpecParser::testSpec()
15570 {
15571 addFilter();
15572 return m_testSpec;
15573 }
15574 bool TestSpecParser::visitChar(char c)
15575 {
15576 if ((m_mode != EscapedName) && (c == '\\')) {
15577 escape();
15578 addCharToPattern(c);
15579 return true;
15580 }
15581 else if ((m_mode != EscapedName) && (c == ',')) {
15582 return separate();
15583 }
15584
15585 switch (m_mode) {
15586 case None:
15587 if (processNoneChar(c))
15588 return true;
15589 break;
15590 case Name: processNameChar(c); break;
15591 case EscapedName:
15592 endMode();
15593 addCharToPattern(c);
15594 return true;
15595 default:
15596 case Tag:
15597 case QuotedName:
15598 if (processOtherChar(c))
15599 return true;
15600 break;
15601 }
15602
15603 m_substring += c;
15604 if (!isControlChar(c)) {
15605 m_patternName += c;
15606 m_realPatternPos++;
15607 }
15608 return true;
15609 }
15610 // Two of the processing methods return true to signal the caller to return
15611 // without adding the given character to the current pattern strings
15612 bool TestSpecParser::processNoneChar(char c)
15613 {
15614 switch (c) {
15615 case ' ': return true;
15616 case '~': m_exclusion = true; return false;
15617 case '[': startNewMode(Tag); return false;
15618 case '"': startNewMode(QuotedName); return false;
15619 default: startNewMode(Name); return false;
15620 }
15621 }
15622 void TestSpecParser::processNameChar(char c)
15623 {
15624 if (c == '[') {
15625 if (m_substring == "exclude:")
15626 m_exclusion = true;
15627 else
15628 endMode();
15629 startNewMode(Tag);
15630 }
15631 }
15632 bool TestSpecParser::processOtherChar(char c)
15633 {
15634 if (!isControlChar(c))
15635 return false;
15636 m_substring += c;
15637 endMode();
15638 return true;
15639 }
15640 void TestSpecParser::startNewMode(Mode mode) { m_mode = mode; }
15641 void TestSpecParser::endMode()
15642 {
15643 switch (m_mode) {
15644 case Name:
15645 case QuotedName: return addNamePattern();
15646 case Tag: return addTagPattern();
15647 case EscapedName: revertBackToLastMode(); return;
15648 case None:
15649 default: return startNewMode(None);
15650 }
15651 }
15652 void TestSpecParser::escape()
15653 {
15654 saveLastMode();
15655 m_mode = EscapedName;
15656 m_escapeChars.push_back(m_realPatternPos);
15657 }
15658 bool TestSpecParser::isControlChar(char c) const
15659 {
15660 switch (m_mode) {
15661 default: return false;
15662 case None: return c == '~';
15663 case Name: return c == '[';
15664 case EscapedName: return true;
15665 case QuotedName: return c == '"';
15666 case Tag: return c == '[' || c == ']';
15667 }
15668 }
15669
15670 void TestSpecParser::addFilter()
15671 {
15672 if (!m_currentFilter.m_patterns.empty()) {
15673 m_testSpec.m_filters.push_back(m_currentFilter);
15674 m_currentFilter = TestSpec::Filter();
15675 }
15676 }
15677
15678 void TestSpecParser::saveLastMode() { lastMode = m_mode; }
15679
15680 void TestSpecParser::revertBackToLastMode() { m_mode = lastMode; }
15681
15682 bool TestSpecParser::separate()
15683 {
15684 if ((m_mode == QuotedName) || (m_mode == Tag)) {
15685 // invalid argument, signal failure to previous scope.
15686 m_mode = None;
15687 m_pos = m_arg.size();
15688 m_substring.clear();
15689 m_patternName.clear();
15690 m_realPatternPos = 0;
15691 return false;
15692 }
15693 endMode();
15694 addFilter();
15695 return true; // success
15696 }
15697
15698 std::string TestSpecParser::preprocessPattern()
15699 {
15700 std::string token = m_patternName;
15701 for (std::size_t i = 0; i < m_escapeChars.size(); ++i)
15702 token = token.substr(0, m_escapeChars[i] - i) + token.substr(m_escapeChars[i] - i + 1);
15703 m_escapeChars.clear();
15704 if (startsWith(token, "exclude:")) {
15705 m_exclusion = true;
15706 token = token.substr(8);
15707 }
15708
15709 m_patternName.clear();
15710 m_realPatternPos = 0;
15711
15712 return token;
15713 }
15714
15715 void TestSpecParser::addNamePattern()
15716 {
15717 auto token = preprocessPattern();
15718
15719 if (!token.empty()) {
15720 TestSpec::PatternPtr pattern = std::make_shared<TestSpec::NamePattern>(token, m_substring);
15721 if (m_exclusion)
15722 pattern = std::make_shared<TestSpec::ExcludedPattern>(pattern);
15723 m_currentFilter.m_patterns.push_back(pattern);
15724 }
15725 m_substring.clear();
15726 m_exclusion = false;
15727 m_mode = None;
15728 }
15729
15730 void TestSpecParser::addTagPattern()
15731 {
15732 auto token = preprocessPattern();
15733
15734 if (!token.empty()) {
15735 // If the tag pattern is the "hide and tag" shorthand (e.g. [.foo])
15736 // we have to create a separate hide tag and shorten the real one
15737 if (token.size() > 1 && token[0] == '.') {
15738 token.erase(token.begin());
15739 TestSpec::PatternPtr pattern = std::make_shared<TestSpec::TagPattern>(".", m_substring);
15740 if (m_exclusion) {
15741 pattern = std::make_shared<TestSpec::ExcludedPattern>(pattern);
15742 }
15743 m_currentFilter.m_patterns.push_back(pattern);
15744 }
15745
15746 TestSpec::PatternPtr pattern = std::make_shared<TestSpec::TagPattern>(token, m_substring);
15747
15748 if (m_exclusion) {
15749 pattern = std::make_shared<TestSpec::ExcludedPattern>(pattern);
15750 }
15751 m_currentFilter.m_patterns.push_back(pattern);
15752 }
15753 m_substring.clear();
15754 m_exclusion = false;
15755 m_mode = None;
15756 }
15757
15758 TestSpec parseTestSpec(std::string const &arg)
15759 {
15760 return TestSpecParser(ITagAliasRegistry::get()).parse(arg).testSpec();
15761 }
15762
15763 } // namespace Catch
15764 // end catch_test_spec_parser.cpp
15765 // start catch_timer.cpp
15766
15767 #include <chrono>
15768
15769 static const uint64_t nanosecondsInSecond = 1000000000;
15770
15771 namespace Catch {
15772
15773 auto getCurrentNanosecondsSinceEpoch() -> uint64_t
15774 {
15775 return std::chrono::duration_cast<std::chrono::nanoseconds>(
15776 std::chrono::high_resolution_clock::now().time_since_epoch())
15777 .count();
15778 }
15779
15780 namespace {
15781 auto estimateClockResolution() -> uint64_t
15782 {
15783 uint64_t sum = 0;
15784 static const uint64_t iterations = 1000000;
15785
15786 auto startTime = getCurrentNanosecondsSinceEpoch();
15787
15788 for (std::size_t i = 0; i < iterations; ++i) {
15789
15790 uint64_t ticks;
15791 uint64_t baseTicks = getCurrentNanosecondsSinceEpoch();
15792 do {
15793 ticks = getCurrentNanosecondsSinceEpoch();
15794 } while (ticks == baseTicks);
15795
15796 auto delta = ticks - baseTicks;
15797 sum += delta;
15798
15799 // If we have been calibrating for over 3 seconds -- the clock
15800 // is terrible and we should move on.
15801 // TBD: How to signal that the measured resolution is probably wrong?
15802 if (ticks > startTime + 3 * nanosecondsInSecond) {
15803 return sum / (i + 1u);
15804 }
15805 }
15806
15807 // We're just taking the mean, here. To do better we could take the std. dev and exclude
15808 // outliers
15809 // - and potentially do more iterations if there's a high variance.
15810 return sum / iterations;
15811 }
15812 } // namespace
15813 auto getEstimatedClockResolution() -> uint64_t
15814 {
15815 static auto s_resolution = estimateClockResolution();
15816 return s_resolution;
15817 }
15818
15819 void Timer::start() { m_nanoseconds = getCurrentNanosecondsSinceEpoch(); }
15820 auto Timer::getElapsedNanoseconds() const -> uint64_t
15821 {
15822 return getCurrentNanosecondsSinceEpoch() - m_nanoseconds;
15823 }
15824 auto Timer::getElapsedMicroseconds() const -> uint64_t { return getElapsedNanoseconds() / 1000; }
15825 auto Timer::getElapsedMilliseconds() const -> unsigned int
15826 {
15827 return static_cast<unsigned int>(getElapsedMicroseconds() / 1000);
15828 }
15829 auto Timer::getElapsedSeconds() const -> double { return getElapsedMicroseconds() / 1000000.0; }
15830
15831 } // namespace Catch
15832 // end catch_timer.cpp
15833 // start catch_tostring.cpp
15834
15835 #if defined(__clang__)
15836 #pragma clang diagnostic push
15837 #pragma clang diagnostic ignored "-Wexit-time-destructors"
15838 #pragma clang diagnostic ignored "-Wglobal-constructors"
15839 #endif
15840
15841 // Enable specific decls locally
15842 #if !defined(CATCH_CONFIG_ENABLE_CHRONO_STRINGMAKER)
15843 #define CATCH_CONFIG_ENABLE_CHRONO_STRINGMAKER
15844 #endif
15845
15846 #include <cmath>
15847 #include <iomanip>
15848
15849 namespace Catch {
15850
15851 namespace Detail {
15852
15853 const std::string unprintableString = "{?}";
15854
15855 namespace {
15856 const int hexThreshold = 255;
15857
15858 struct Endianness
15859 {
15860 enum Arch { Big, Little };
15861
15862 static Arch which()
15863 {
15864 int one = 1;
15865 // If the lowest byte we read is non-zero, we can assume
15866 // that little endian format is used.
15867 auto value = *reinterpret_cast<char *>(&one);
15868 return value ? Little : Big;
15869 }
15870 };
15871 } // namespace
15872
15873 std::string rawMemoryToString(const void *object, std::size_t size)
15874 {
15875 // Reverse order for little endian architectures
15876 int i = 0, end = static_cast<int>(size), inc = 1;
15877 if (Endianness::which() == Endianness::Little) {
15878 i = end - 1;
15879 end = inc = -1;
15880 }
15881
15882 unsigned char const *bytes = static_cast<unsigned char const *>(object);
15883 ReusableStringStream rss;
15884 rss << "0x" << std::setfill('0') << std::hex;
15885 for (; i != end; i += inc)
15886 rss << std::setw(2) << static_cast<unsigned>(bytes[i]);
15887 return rss.str();
15888 }
15889 } // namespace Detail
15890
15891 template <typename T> std::string fpToString(T value, int precision)
15892 {
15893 if (Catch::isnan(value)) {
15894 return "nan";
15895 }
15896
15897 ReusableStringStream rss;
15898 rss << std::setprecision(precision) << std::fixed << value;
15899 std::string d = rss.str();
15900 std::size_t i = d.find_last_not_of('0');
15901 if (i != std::string::npos && i != d.size() - 1) {
15902 if (d[i] == '.')
15903 i++;
15904 d = d.substr(0, i + 1);
15905 }
15906 return d;
15907 }
15908
15909 //// ======================================================= ////
15910 //
15911 // Out-of-line defs for full specialization of StringMaker
15912 //
15913 //// ======================================================= ////
15914
15915 std::string StringMaker<std::string>::convert(const std::string &str)
15916 {
15917 if (!getCurrentContext().getConfig()->showInvisibles()) {
15918 return '"' + str + '"';
15919 }
15920
15921 std::string s("\"");
15922 for (char c : str) {
15923 switch (c) {
15924 case '\n': s.append("\\n"); break;
15925 case '\t': s.append("\\t"); break;
15926 default: s.push_back(c); break;
15927 }
15928 }
15929 s.append("\"");
15930 return s;
15931 }
15932
15933 #ifdef CATCH_CONFIG_CPP17_STRING_VIEW
15934 std::string StringMaker<std::string_view>::convert(std::string_view str)
15935 {
15936 return ::Catch::Detail::stringify(std::string{str});
15937 }
15938 #endif
15939
15940 std::string StringMaker<char const *>::convert(char const *str)
15941 {
15942 if (str) {
15943 return ::Catch::Detail::stringify(std::string{str});
15944 }
15945 else {
15946 return {"{null string}"};
15947 }
15948 }
15949 std::string StringMaker<char *>::convert(char *str)
15950 {
15951 if (str) {
15952 return ::Catch::Detail::stringify(std::string{str});
15953 }
15954 else {
15955 return {"{null string}"};
15956 }
15957 }
15958
15959 #ifdef CATCH_CONFIG_WCHAR
15960 std::string StringMaker<std::wstring>::convert(const std::wstring &wstr)
15961 {
15962 std::string s;
15963 s.reserve(wstr.size());
15964 for (auto c : wstr) {
15965 s += (c <= 0xff) ? static_cast<char>(c) : '?';
15966 }
15967 return ::Catch::Detail::stringify(s);
15968 }
15969
15970 #ifdef CATCH_CONFIG_CPP17_STRING_VIEW
15971 std::string StringMaker<std::wstring_view>::convert(std::wstring_view str)
15972 {
15973 return StringMaker<std::wstring>::convert(std::wstring(str));
15974 }
15975 #endif
15976
15977 std::string StringMaker<wchar_t const *>::convert(wchar_t const *str)
15978 {
15979 if (str) {
15980 return ::Catch::Detail::stringify(std::wstring{str});
15981 }
15982 else {
15983 return {"{null string}"};
15984 }
15985 }
15986 std::string StringMaker<wchar_t *>::convert(wchar_t *str)
15987 {
15988 if (str) {
15989 return ::Catch::Detail::stringify(std::wstring{str});
15990 }
15991 else {
15992 return {"{null string}"};
15993 }
15994 }
15995 #endif
15996
15997 #if defined(CATCH_CONFIG_CPP17_BYTE)
15998 #include <cstddef>
15999 std::string StringMaker<std::byte>::convert(std::byte value)
16000 {
16001 return ::Catch::Detail::stringify(std::to_integer<unsigned long long>(value));
16002 }
16003 #endif // defined(CATCH_CONFIG_CPP17_BYTE)
16004
16005 std::string StringMaker<int>::convert(int value)
16006 {
16007 return ::Catch::Detail::stringify(static_cast<long long>(value));
16008 }
16009 std::string StringMaker<long>::convert(long value)
16010 {
16011 return ::Catch::Detail::stringify(static_cast<long long>(value));
16012 }
16013 std::string StringMaker<long long>::convert(long long value)
16014 {
16015 ReusableStringStream rss;
16016 rss << value;
16017 if (value > Detail::hexThreshold) {
16018 rss << " (0x" << std::hex << value << ')';
16019 }
16020 return rss.str();
16021 }
16022
16023 std::string StringMaker<unsigned int>::convert(unsigned int value)
16024 {
16025 return ::Catch::Detail::stringify(static_cast<unsigned long long>(value));
16026 }
16027 std::string StringMaker<unsigned long>::convert(unsigned long value)
16028 {
16029 return ::Catch::Detail::stringify(static_cast<unsigned long long>(value));
16030 }
16031 std::string StringMaker<unsigned long long>::convert(unsigned long long value)
16032 {
16033 ReusableStringStream rss;
16034 rss << value;
16035 if (value > Detail::hexThreshold) {
16036 rss << " (0x" << std::hex << value << ')';
16037 }
16038 return rss.str();
16039 }
16040
16041 std::string StringMaker<bool>::convert(bool b) { return b ? "true" : "false"; }
16042
16043 std::string StringMaker<signed char>::convert(signed char value)
16044 {
16045 if (value == '\r') {
16046 return "'\\r'";
16047 }
16048 else if (value == '\f') {
16049 return "'\\f'";
16050 }
16051 else if (value == '\n') {
16052 return "'\\n'";
16053 }
16054 else if (value == '\t') {
16055 return "'\\t'";
16056 }
16057 else if ('\0' <= value && value < ' ') {
16058 return ::Catch::Detail::stringify(static_cast<unsigned int>(value));
16059 }
16060 else {
16061 char chstr[] = "' '";
16062 chstr[1] = value;
16063 return chstr;
16064 }
16065 }
16066 std::string StringMaker<char>::convert(char c)
16067 {
16068 return ::Catch::Detail::stringify(static_cast<signed char>(c));
16069 }
16070 std::string StringMaker<unsigned char>::convert(unsigned char c)
16071 {
16072 return ::Catch::Detail::stringify(static_cast<char>(c));
16073 }
16074
16075 std::string StringMaker<std::nullptr_t>::convert(std::nullptr_t) { return "nullptr"; }
16076
16077 int StringMaker<float>::precision = 5;
16078
16079 std::string StringMaker<float>::convert(float value)
16080 {
16081 return fpToString(value, precision) + 'f';
16082 }
16083
16084 int StringMaker<double>::precision = 10;
16085
16086 std::string StringMaker<double>::convert(double value) { return fpToString(value, precision); }
16087
16088 std::string ratio_string<std::atto>::symbol() { return "a"; }
16089 std::string ratio_string<std::femto>::symbol() { return "f"; }
16090 std::string ratio_string<std::pico>::symbol() { return "p"; }
16091 std::string ratio_string<std::nano>::symbol() { return "n"; }
16092 std::string ratio_string<std::micro>::symbol() { return "u"; }
16093 std::string ratio_string<std::milli>::symbol() { return "m"; }
16094
16095 } // end namespace Catch
16096
16097 #if defined(__clang__)
16098 #pragma clang diagnostic pop
16099 #endif
16100
16101 // end catch_tostring.cpp
16102 // start catch_totals.cpp
16103
16104 namespace Catch {
16105
16106 Counts Counts::operator-(Counts const &other) const
16107 {
16108 Counts diff;
16109 diff.passed = passed - other.passed;
16110 diff.failed = failed - other.failed;
16111 diff.failedButOk = failedButOk - other.failedButOk;
16112 return diff;
16113 }
16114
16115 Counts &Counts::operator+=(Counts const &other)
16116 {
16117 passed += other.passed;
16118 failed += other.failed;
16119 failedButOk += other.failedButOk;
16120 return *this;
16121 }
16122
16123 std::size_t Counts::total() const { return passed + failed + failedButOk; }
16124 bool Counts::allPassed() const { return failed == 0 && failedButOk == 0; }
16125 bool Counts::allOk() const { return failed == 0; }
16126
16127 Totals Totals::operator-(Totals const &other) const
16128 {
16129 Totals diff;
16130 diff.assertions = assertions - other.assertions;
16131 diff.testCases = testCases - other.testCases;
16132 return diff;
16133 }
16134
16135 Totals &Totals::operator+=(Totals const &other)
16136 {
16137 assertions += other.assertions;
16138 testCases += other.testCases;
16139 return *this;
16140 }
16141
16142 Totals Totals::delta(Totals const &prevTotals) const
16143 {
16144 Totals diff = *this - prevTotals;
16145 if (diff.assertions.failed > 0)
16146 ++diff.testCases.failed;
16147 else if (diff.assertions.failedButOk > 0)
16148 ++diff.testCases.failedButOk;
16149 else
16150 ++diff.testCases.passed;
16151 return diff;
16152 }
16153
16154 } // namespace Catch
16155 // end catch_totals.cpp
16156 // start catch_uncaught_exceptions.cpp
16157
16158 // start catch_config_uncaught_exceptions.hpp
16159
16160 // Copyright Catch2 Authors
16161 // Distributed under the Boost Software License, Version 1.0.
16162 // (See accompanying file LICENSE_1_0.txt or copy at
16163 // https://www.boost.org/LICENSE_1_0.txt)
16164
16165 // SPDX-License-Identifier: BSL-1.0
16166
16167 #ifndef CATCH_CONFIG_UNCAUGHT_EXCEPTIONS_HPP
16168 #define CATCH_CONFIG_UNCAUGHT_EXCEPTIONS_HPP
16169
16170 #if defined(_MSC_VER)
16171 #if _MSC_VER >= 1900 // Visual Studio 2015 or newer
16172 #define CATCH_INTERNAL_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS
16173 #endif
16174 #endif
16175
16176 #include <exception>
16177
16178 #if defined(__cpp_lib_uncaught_exceptions) && \
16179 !defined(CATCH_INTERNAL_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS)
16180
16181 #define CATCH_INTERNAL_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS
16182 #endif // __cpp_lib_uncaught_exceptions
16183
16184 #if defined(CATCH_INTERNAL_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS) && \
16185 !defined(CATCH_CONFIG_NO_CPP17_UNCAUGHT_EXCEPTIONS) && \
16186 !defined(CATCH_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS)
16187
16188 #define CATCH_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS
16189 #endif
16190
16191 #endif // CATCH_CONFIG_UNCAUGHT_EXCEPTIONS_HPP
16192 // end catch_config_uncaught_exceptions.hpp
16193 #include <exception>
16194
16195 namespace Catch {
16196 bool uncaught_exceptions()
16197 {
16198 #if defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
16199 return false;
16200 #elif defined(CATCH_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS)
16201 return std::uncaught_exceptions() > 0;
16202 #else
16203 return std::uncaught_exception();
16204 #endif
16205 }
16206 } // end namespace Catch
16207 // end catch_uncaught_exceptions.cpp
16208 // start catch_version.cpp
16209
16210 #include <ostream>
16211
16212 namespace Catch {
16213
16214 Version::Version(unsigned int _majorVersion, unsigned int _minorVersion,
16215 unsigned int _patchNumber, char const *const _branchName,
16216 unsigned int _buildNumber)
16217 : majorVersion(_majorVersion), minorVersion(_minorVersion), patchNumber(_patchNumber),
16218 branchName(_branchName), buildNumber(_buildNumber)
16219 {
16220 }
16221
16222 std::ostream &operator<<(std::ostream &os, Version const &version)
16223 {
16224 os << version.majorVersion << '.' << version.minorVersion << '.' << version.patchNumber;
16225 // branchName is never null -> 0th char is \0 if it is empty
16226 if (version.branchName[0]) {
16227 os << '-' << version.branchName << '.' << version.buildNumber;
16228 }
16229 return os;
16230 }
16231
16232 Version const &libraryVersion()
16233 {
16234 static Version version(2, 13, 4, "", 0);
16235 return version;
16236 }
16237
16238 } // namespace Catch
16239 // end catch_version.cpp
16240 // start catch_wildcard_pattern.cpp
16241
16242 namespace Catch {
16243
16244 WildcardPattern::WildcardPattern(std::string const &pattern,
16245 CaseSensitive::Choice caseSensitivity)
16246 : m_caseSensitivity(caseSensitivity), m_pattern(normaliseString(pattern))
16247 {
16248 if (startsWith(m_pattern, '*')) {
16249 m_pattern = m_pattern.substr(1);
16250 m_wildcard = WildcardAtStart;
16251 }
16252 if (endsWith(m_pattern, '*')) {
16253 m_pattern = m_pattern.substr(0, m_pattern.size() - 1);
16254 m_wildcard = static_cast<WildcardPosition>(m_wildcard | WildcardAtEnd);
16255 }
16256 }
16257
16258 bool WildcardPattern::matches(std::string const &str) const
16259 {
16260 switch (m_wildcard) {
16261 case NoWildcard: return m_pattern == normaliseString(str);
16262 case WildcardAtStart: return endsWith(normaliseString(str), m_pattern);
16263 case WildcardAtEnd: return startsWith(normaliseString(str), m_pattern);
16264 case WildcardAtBothEnds: return contains(normaliseString(str), m_pattern);
16265 default: CATCH_INTERNAL_ERROR("Unknown enum");
16266 }
16267 }
16268
16269 std::string WildcardPattern::normaliseString(std::string const &str) const
16270 {
16271 return trim(m_caseSensitivity == CaseSensitive::No ? toLower(str) : str);
16272 }
16273 } // namespace Catch
16274 // end catch_wildcard_pattern.cpp
16275 // start catch_xmlwriter.cpp
16276
16277 #include <iomanip>
16278 #include <type_traits>
16279
16280 namespace Catch {
16281
16282 namespace {
16283
16284 size_t trailingBytes(unsigned char c)
16285 {
16286 if ((c & 0xE0) == 0xC0) {
16287 return 2;
16288 }
16289 if ((c & 0xF0) == 0xE0) {
16290 return 3;
16291 }
16292 if ((c & 0xF8) == 0xF0) {
16293 return 4;
16294 }
16295 CATCH_INTERNAL_ERROR("Invalid multibyte utf-8 start byte encountered");
16296 }
16297
16298 uint32_t headerValue(unsigned char c)
16299 {
16300 if ((c & 0xE0) == 0xC0) {
16301 return c & 0x1F;
16302 }
16303 if ((c & 0xF0) == 0xE0) {
16304 return c & 0x0F;
16305 }
16306 if ((c & 0xF8) == 0xF0) {
16307 return c & 0x07;
16308 }
16309 CATCH_INTERNAL_ERROR("Invalid multibyte utf-8 start byte encountered");
16310 }
16311
16312 void hexEscapeChar(std::ostream &os, unsigned char c)
16313 {
16314 std::ios_base::fmtflags f(os.flags());
16315 os << "\\x" << std::uppercase << std::hex << std::setfill('0') << std::setw(2)
16316 << static_cast<int>(c);
16317 os.flags(f);
16318 }
16319
16320 bool shouldNewline(XmlFormatting fmt)
16321 {
16322 return !!(
16323 static_cast<std::underlying_type<XmlFormatting>::type>(fmt & XmlFormatting::Newline));
16324 }
16325
16326 bool shouldIndent(XmlFormatting fmt)
16327 {
16328 return !!(
16329 static_cast<std::underlying_type<XmlFormatting>::type>(fmt & XmlFormatting::Indent));
16330 }
16331
16332 } // anonymous namespace
16333
16334 XmlFormatting operator|(XmlFormatting lhs, XmlFormatting rhs)
16335 {
16336 return static_cast<XmlFormatting>(static_cast<std::underlying_type<XmlFormatting>::type>(lhs) |
16337 static_cast<std::underlying_type<XmlFormatting>::type>(rhs));
16338 }
16339
16340 XmlFormatting operator&(XmlFormatting lhs, XmlFormatting rhs)
16341 {
16342 return static_cast<XmlFormatting>(static_cast<std::underlying_type<XmlFormatting>::type>(lhs) &
16343 static_cast<std::underlying_type<XmlFormatting>::type>(rhs));
16344 }
16345
16346 XmlEncode::XmlEncode(std::string const &str, ForWhat forWhat) : m_str(str), m_forWhat(forWhat) {}
16347
16348 void XmlEncode::encodeTo(std::ostream &os) const
16349 {
16350 // Apostrophe escaping not necessary if we always use " to write attributes
16351 // (see: http://www.w3.org/TR/xml/#syntax)
16352
16353 for (std::size_t idx = 0; idx < m_str.size(); ++idx) {
16354 unsigned char c = m_str[idx];
16355 switch (c) {
16356 case '<': os << "&lt;"; break;
16357 case '&': os << "&amp;"; break;
16358
16359 case '>':
16360 // See: http://www.w3.org/TR/xml/#syntax
16361 if (idx > 2 && m_str[idx - 1] == ']' && m_str[idx - 2] == ']')
16362 os << "&gt;";
16363 else
16364 os << c;
16365 break;
16366
16367 case '\"':
16368 if (m_forWhat == ForAttributes)
16369 os << "&quot;";
16370 else
16371 os << c;
16372 break;
16373
16374 default:
16375 // Check for control characters and invalid utf-8
16376
16377 // Escape control characters in standard ascii
16378 // see
16379 // http://stackoverflow.com/questions/404107/why-are-control-characters-illegal-in-xml-1-0
16380 if (c < 0x09 || (c > 0x0D && c < 0x20) || c == 0x7F) {
16381 hexEscapeChar(os, c);
16382 break;
16383 }
16384
16385 // Plain ASCII: Write it to stream
16386 if (c < 0x7F) {
16387 os << c;
16388 break;
16389 }
16390
16391 // UTF-8 territory
16392 // Check if the encoding is valid and if it is not, hex escape bytes.
16393 // Important: We do not check the exact decoded values for validity, only the encoding
16394 // format First check that this bytes is a valid lead byte: This means that it is not
16395 // encoded as 1111 1XXX Or as 10XX XXXX
16396 if (c < 0xC0 || c >= 0xF8) {
16397 hexEscapeChar(os, c);
16398 break;
16399 }
16400
16401 auto encBytes = trailingBytes(c);
16402 // Are there enough bytes left to avoid accessing out-of-bounds memory?
16403 if (idx + encBytes - 1 >= m_str.size()) {
16404 hexEscapeChar(os, c);
16405 break;
16406 }
16407 // The header is valid, check data
16408 // The next encBytes bytes must together be a valid utf-8
16409 // This means: bitpattern 10XX XXXX and the extracted value is sane (ish)
16410 bool valid = true;
16411 uint32_t value = headerValue(c);
16412 for (std::size_t n = 1; n < encBytes; ++n) {
16413 unsigned char nc = m_str[idx + n];
16414 valid &= ((nc & 0xC0) == 0x80);
16415 value = (value << 6) | (nc & 0x3F);
16416 }
16417
16418 if (
16419 // Wrong bit pattern of following bytes
16420 (!valid) ||
16421 // Overlong encodings
16422 (value < 0x80) || (0x80 <= value && value < 0x800 && encBytes > 2) ||
16423 (0x800 < value && value < 0x10000 && encBytes > 3) ||
16424 // Encoded value out of range
16425 (value >= 0x110000)) {
16426 hexEscapeChar(os, c);
16427 break;
16428 }
16429
16430 // If we got here, this is in fact a valid(ish) utf-8 sequence
16431 for (std::size_t n = 0; n < encBytes; ++n) {
16432 os << m_str[idx + n];
16433 }
16434 idx += encBytes - 1;
16435 break;
16436 }
16437 }
16438 }
16439
16440 std::ostream &operator<<(std::ostream &os, XmlEncode const &xmlEncode)
16441 {
16442 xmlEncode.encodeTo(os);
16443 return os;
16444 }
16445
16446 XmlWriter::ScopedElement::ScopedElement(XmlWriter *writer, XmlFormatting fmt)
16447 : m_writer(writer), m_fmt(fmt)
16448 {
16449 }
16450
16451 XmlWriter::ScopedElement::ScopedElement(ScopedElement &&other) noexcept
16452 : m_writer(other.m_writer), m_fmt(other.m_fmt)
16453 {
16454 other.m_writer = nullptr;
16455 other.m_fmt = XmlFormatting::None;
16456 }
16457 XmlWriter::ScopedElement &XmlWriter::ScopedElement::operator=(ScopedElement &&other) noexcept
16458 {
16459 if (m_writer) {
16460 m_writer->endElement();
16461 }
16462 m_writer = other.m_writer;
16463 other.m_writer = nullptr;
16464 m_fmt = other.m_fmt;
16465 other.m_fmt = XmlFormatting::None;
16466 return *this;
16467 }
16468
16469 XmlWriter::ScopedElement::~ScopedElement()
16470 {
16471 if (m_writer) {
16472 m_writer->endElement(m_fmt);
16473 }
16474 }
16475
16476 XmlWriter::ScopedElement &XmlWriter::ScopedElement::writeText(std::string const &text,
16477 XmlFormatting fmt)
16478 {
16479 m_writer->writeText(text, fmt);
16480 return *this;
16481 }
16482
16483 XmlWriter::XmlWriter(std::ostream &os) : m_os(os) { writeDeclaration(); }
16484
16485 XmlWriter::~XmlWriter()
16486 {
16487 while (!m_tags.empty()) {
16488 endElement();
16489 }
16490 newlineIfNecessary();
16491 }
16492
16493 XmlWriter &XmlWriter::startElement(std::string const &name, XmlFormatting fmt)
16494 {
16495 ensureTagClosed();
16496 newlineIfNecessary();
16497 if (shouldIndent(fmt)) {
16498 m_os << m_indent;
16499 m_indent += " ";
16500 }
16501 m_os << '<' << name;
16502 m_tags.push_back(name);
16503 m_tagIsOpen = true;
16504 applyFormatting(fmt);
16505 return *this;
16506 }
16507
16508 XmlWriter::ScopedElement XmlWriter::scopedElement(std::string const &name, XmlFormatting fmt)
16509 {
16510 ScopedElement scoped(this, fmt);
16511 startElement(name, fmt);
16512 return scoped;
16513 }
16514
16515 XmlWriter &XmlWriter::endElement(XmlFormatting fmt)
16516 {
16517 m_indent = m_indent.substr(0, m_indent.size() - 2);
16518
16519 if (m_tagIsOpen) {
16520 m_os << "/>";
16521 m_tagIsOpen = false;
16522 }
16523 else {
16524 newlineIfNecessary();
16525 if (shouldIndent(fmt)) {
16526 m_os << m_indent;
16527 }
16528 m_os << "</" << m_tags.back() << ">";
16529 }
16530 m_os << std::flush;
16531 applyFormatting(fmt);
16532 m_tags.pop_back();
16533 return *this;
16534 }
16535
16536 XmlWriter &XmlWriter::writeAttribute(std::string const &name, std::string const &attribute)
16537 {
16538 if (!name.empty() && !attribute.empty())
16539 m_os << ' ' << name << "=\"" << XmlEncode(attribute, XmlEncode::ForAttributes) << '"';
16540 return *this;
16541 }
16542
16543 XmlWriter &XmlWriter::writeAttribute(std::string const &name, bool attribute)
16544 {
16545 m_os << ' ' << name << "=\"" << (attribute ? "true" : "false") << '"';
16546 return *this;
16547 }
16548
16549 XmlWriter &XmlWriter::writeText(std::string const &text, XmlFormatting fmt)
16550 {
16551 if (!text.empty()) {
16552 bool tagWasOpen = m_tagIsOpen;
16553 ensureTagClosed();
16554 if (tagWasOpen && shouldIndent(fmt)) {
16555 m_os << m_indent;
16556 }
16557 m_os << XmlEncode(text);
16558 applyFormatting(fmt);
16559 }
16560 return *this;
16561 }
16562
16563 XmlWriter &XmlWriter::writeComment(std::string const &text, XmlFormatting fmt)
16564 {
16565 ensureTagClosed();
16566 if (shouldIndent(fmt)) {
16567 m_os << m_indent;
16568 }
16569 m_os << "<!--" << text << "-->";
16570 applyFormatting(fmt);
16571 return *this;
16572 }
16573
16574 void XmlWriter::writeStylesheetRef(std::string const &url)
16575 {
16576 m_os << "<?xml-stylesheet type=\"text/xsl\" href=\"" << url << "\"?>\n";
16577 }
16578
16579 XmlWriter &XmlWriter::writeBlankLine()
16580 {
16581 ensureTagClosed();
16582 m_os << '\n';
16583 return *this;
16584 }
16585
16586 void XmlWriter::ensureTagClosed()
16587 {
16588 if (m_tagIsOpen) {
16589 m_os << '>' << std::flush;
16590 newlineIfNecessary();
16591 m_tagIsOpen = false;
16592 }
16593 }
16594
16595 void XmlWriter::applyFormatting(XmlFormatting fmt) { m_needsNewline = shouldNewline(fmt); }
16596
16597 void XmlWriter::writeDeclaration() { m_os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"; }
16598
16599 void XmlWriter::newlineIfNecessary()
16600 {
16601 if (m_needsNewline) {
16602 m_os << std::endl;
16603 m_needsNewline = false;
16604 }
16605 }
16606 } // namespace Catch
16607 // end catch_xmlwriter.cpp
16608 // start catch_reporter_bases.cpp
16609
16610 #include <cassert>
16611 #include <cfloat>
16612 #include <cstdio>
16613 #include <cstring>
16614 #include <memory>
16615
16616 namespace Catch {
16617 void prepareExpandedExpression(AssertionResult &result) { result.getExpandedExpression(); }
16618
16619 // Because formatting using c++ streams is stateful, drop down to C is required
16620 // Alternatively we could use stringstream, but its performance is... not good.
16621 std::string getFormattedDuration(double duration)
16622 {
16623 // Max exponent + 1 is required to represent the whole part
16624 // + 1 for decimal point
16625 // + 3 for the 3 decimal places
16626 // + 1 for null terminator
16627 const std::size_t maxDoubleSize = DBL_MAX_10_EXP + 1 + 1 + 3 + 1;
16628 char buffer[maxDoubleSize];
16629
16630 // Save previous errno, to prevent sprintf from overwriting it
16631 ErrnoGuard guard;
16632 #ifdef _MSC_VER
16633 sprintf_s(buffer, "%.3f", duration);
16634 #else
16635 std::sprintf(buffer, "%.3f", duration);
16636 #endif
16637 return std::string(buffer);
16638 }
16639
16640 bool shouldShowDuration(IConfig const &config, double duration)
16641 {
16642 if (config.showDurations() == ShowDurations::Always) {
16643 return true;
16644 }
16645 if (config.showDurations() == ShowDurations::Never) {
16646 return false;
16647 }
16648 const double min = config.minDuration();
16649 return min >= 0 && duration >= min;
16650 }
16651
16652 std::string serializeFilters(std::vector<std::string> const &container)
16653 {
16654 ReusableStringStream oss;
16655 bool first = true;
16656 for (auto &&filter : container) {
16657 if (!first)
16658 oss << ' ';
16659 else
16660 first = false;
16661
16662 oss << filter;
16663 }
16664 return oss.str();
16665 }
16666
16667 TestEventListenerBase::TestEventListenerBase(ReporterConfig const &_config)
16668 : StreamingReporterBase(_config)
16669 {
16670 }
16671
16672 std::set<Verbosity> TestEventListenerBase::getSupportedVerbosities()
16673 {
16674 return {Verbosity::Quiet, Verbosity::Normal, Verbosity::High};
16675 }
16676
16677 void TestEventListenerBase::assertionStarting(AssertionInfo const &) {}
16678
16679 bool TestEventListenerBase::assertionEnded(AssertionStats const &) { return false; }
16680
16681 } // end namespace Catch
16682 // end catch_reporter_bases.cpp
16683 // start catch_reporter_compact.cpp
16684
16685 namespace {
16686
16687 #ifdef CATCH_PLATFORM_MAC
16688 const char *failedString() { return "FAILED"; }
16689 const char *passedString() { return "PASSED"; }
16690 #else
16691 const char *failedString() { return "failed"; }
16692 const char *passedString() { return "passed"; }
16693 #endif
16694
16695 // Colour::LightGrey
16696 Catch::Colour::Code dimColour() { return Catch::Colour::FileName; }
16697
16698 std::string bothOrAll(std::size_t count)
16699 {
16700 return count == 1 ? std::string() : count == 2 ? "both " : "all ";
16701 }
16702
16703 } // namespace
16704
16705 namespace Catch {
16706 namespace {
16707 // Colour, message variants:
16708 // - white: No tests ran.
16709 // - red: Failed [both/all] N test cases, failed [both/all] M assertions.
16710 // - white: Passed [both/all] N test cases (no assertions).
16711 // - red: Failed N tests cases, failed M assertions.
16712 // - green: Passed [both/all] N tests cases with M assertions.
16713 void printTotals(std::ostream &out, const Totals &totals)
16714 {
16715 if (totals.testCases.total() == 0) {
16716 out << "No tests ran.";
16717 }
16718 else if (totals.testCases.failed == totals.testCases.total()) {
16719 Colour colour(Colour::ResultError);
16720 const std::string qualify_assertions_failed =
16721 totals.assertions.failed == totals.assertions.total()
16722 ? bothOrAll(totals.assertions.failed)
16723 : std::string();
16724 out << "Failed " << bothOrAll(totals.testCases.failed)
16725 << pluralise(totals.testCases.failed, "test case")
16726 << ", "
16727 "failed "
16728 << qualify_assertions_failed << pluralise(totals.assertions.failed, "assertion") << '.';
16729 }
16730 else if (totals.assertions.total() == 0) {
16731 out << "Passed " << bothOrAll(totals.testCases.total())
16732 << pluralise(totals.testCases.total(), "test case") << " (no assertions).";
16733 }
16734 else if (totals.assertions.failed) {
16735 Colour colour(Colour::ResultError);
16736 out << "Failed " << pluralise(totals.testCases.failed, "test case")
16737 << ", "
16738 "failed "
16739 << pluralise(totals.assertions.failed, "assertion") << '.';
16740 }
16741 else {
16742 Colour colour(Colour::ResultSuccess);
16743 out << "Passed " << bothOrAll(totals.testCases.passed)
16744 << pluralise(totals.testCases.passed, "test case") << " with "
16745 << pluralise(totals.assertions.passed, "assertion") << '.';
16746 }
16747 }
16748
16749 // Implementation of CompactReporter formatting
16750 class AssertionPrinter
16751 {
16752 public:
16753 AssertionPrinter &operator=(AssertionPrinter const &) = delete;
16754 AssertionPrinter(AssertionPrinter const &) = delete;
16755 AssertionPrinter(std::ostream &_stream, AssertionStats const &_stats, bool _printInfoMessages)
16756 : stream(_stream), result(_stats.assertionResult), messages(_stats.infoMessages),
16757 itMessage(_stats.infoMessages.begin()), printInfoMessages(_printInfoMessages)
16758 {
16759 }
16760
16761 void print()
16762 {
16763 printSourceInfo();
16764
16765 itMessage = messages.begin();
16766
16767 switch (result.getResultType()) {
16768 case ResultWas::Ok:
16769 printResultType(Colour::ResultSuccess, passedString());
16770 printOriginalExpression();
16771 printReconstructedExpression();
16772 if (!result.hasExpression())
16773 printRemainingMessages(Colour::None);
16774 else
16775 printRemainingMessages();
16776 break;
16777 case ResultWas::ExpressionFailed:
16778 if (result.isOk())
16779 printResultType(Colour::ResultSuccess, failedString() + std::string(" - but was ok"));
16780 else
16781 printResultType(Colour::Error, failedString());
16782 printOriginalExpression();
16783 printReconstructedExpression();
16784 printRemainingMessages();
16785 break;
16786 case ResultWas::ThrewException:
16787 printResultType(Colour::Error, failedString());
16788 printIssue("unexpected exception with message:");
16789 printMessage();
16790 printExpressionWas();
16791 printRemainingMessages();
16792 break;
16793 case ResultWas::FatalErrorCondition:
16794 printResultType(Colour::Error, failedString());
16795 printIssue("fatal error condition with message:");
16796 printMessage();
16797 printExpressionWas();
16798 printRemainingMessages();
16799 break;
16800 case ResultWas::DidntThrowException:
16801 printResultType(Colour::Error, failedString());
16802 printIssue("expected exception, got none");
16803 printExpressionWas();
16804 printRemainingMessages();
16805 break;
16806 case ResultWas::Info:
16807 printResultType(Colour::None, "info");
16808 printMessage();
16809 printRemainingMessages();
16810 break;
16811 case ResultWas::Warning:
16812 printResultType(Colour::None, "warning");
16813 printMessage();
16814 printRemainingMessages();
16815 break;
16816 case ResultWas::ExplicitFailure:
16817 printResultType(Colour::Error, failedString());
16818 printIssue("explicitly");
16819 printRemainingMessages(Colour::None);
16820 break;
16821 // These cases are here to prevent compiler warnings
16822 case ResultWas::Unknown:
16823 case ResultWas::FailureBit:
16824 case ResultWas::Exception: printResultType(Colour::Error, "** internal error **"); break;
16825 }
16826 }
16827
16828 private:
16829 void printSourceInfo() const
16830 {
16831 Colour colourGuard(Colour::FileName);
16832 stream << result.getSourceInfo() << ':';
16833 }
16834
16835 void printResultType(Colour::Code colour, std::string const &passOrFail) const
16836 {
16837 if (!passOrFail.empty()) {
16838 {
16839 Colour colourGuard(colour);
16840 stream << ' ' << passOrFail;
16841 }
16842 stream << ':';
16843 }
16844 }
16845
16846 void printIssue(std::string const &issue) const { stream << ' ' << issue; }
16847
16848 void printExpressionWas()
16849 {
16850 if (result.hasExpression()) {
16851 stream << ';';
16852 {
16853 Colour colour(dimColour());
16854 stream << " expression was:";
16855 }
16856 printOriginalExpression();
16857 }
16858 }
16859
16860 void printOriginalExpression() const
16861 {
16862 if (result.hasExpression()) {
16863 stream << ' ' << result.getExpression();
16864 }
16865 }
16866
16867 void printReconstructedExpression() const
16868 {
16869 if (result.hasExpandedExpression()) {
16870 {
16871 Colour colour(dimColour());
16872 stream << " for: ";
16873 }
16874 stream << result.getExpandedExpression();
16875 }
16876 }
16877
16878 void printMessage()
16879 {
16880 if (itMessage != messages.end()) {
16881 stream << " '" << itMessage->message << '\'';
16882 ++itMessage;
16883 }
16884 }
16885
16886 void printRemainingMessages(Colour::Code colour = dimColour())
16887 {
16888 if (itMessage == messages.end())
16889 return;
16890
16891 const auto itEnd = messages.cend();
16892 const auto N = static_cast<std::size_t>(std::distance(itMessage, itEnd));
16893
16894 {
16895 Colour colourGuard(colour);
16896 stream << " with " << pluralise(N, "message") << ':';
16897 }
16898
16899 while (itMessage != itEnd) {
16900 // If this assertion is a warning ignore any INFO messages
16901 if (printInfoMessages || itMessage->type != ResultWas::Info) {
16902 printMessage();
16903 if (itMessage != itEnd) {
16904 Colour colourGuard(dimColour());
16905 stream << " and";
16906 }
16907 continue;
16908 }
16909 ++itMessage;
16910 }
16911 }
16912
16913 private:
16914 std::ostream &stream;
16915 AssertionResult const &result;
16916 std::vector<MessageInfo> messages;
16917 std::vector<MessageInfo>::const_iterator itMessage;
16918 bool printInfoMessages;
16919 };
16920
16921 } // namespace
16922
16923 std::string CompactReporter::getDescription()
16924 {
16925 return "Reports test results on a single line, suitable for IDEs";
16926 }
16927
16928 void CompactReporter::noMatchingTestCases(std::string const &spec)
16929 {
16930 stream << "No test cases matched '" << spec << '\'' << std::endl;
16931 }
16932
16933 void CompactReporter::assertionStarting(AssertionInfo const &) {}
16934
16935 bool CompactReporter::assertionEnded(AssertionStats const &_assertionStats)
16936 {
16937 AssertionResult const &result = _assertionStats.assertionResult;
16938
16939 bool printInfoMessages = true;
16940
16941 // Drop out if result was successful and we're not printing those
16942 if (!m_config->includeSuccessfulResults() && result.isOk()) {
16943 if (result.getResultType() != ResultWas::Warning)
16944 return false;
16945 printInfoMessages = false;
16946 }
16947
16948 AssertionPrinter printer(stream, _assertionStats, printInfoMessages);
16949 printer.print();
16950
16951 stream << std::endl;
16952 return true;
16953 }
16954
16955 void CompactReporter::sectionEnded(SectionStats const &_sectionStats)
16956 {
16957 double dur = _sectionStats.durationInSeconds;
16958 if (shouldShowDuration(*m_config, dur)) {
16959 stream << getFormattedDuration(dur) << " s: " << _sectionStats.sectionInfo.name << std::endl;
16960 }
16961 }
16962
16963 void CompactReporter::testRunEnded(TestRunStats const &_testRunStats)
16964 {
16965 printTotals(stream, _testRunStats.totals);
16966 stream << '\n' << std::endl;
16967 StreamingReporterBase::testRunEnded(_testRunStats);
16968 }
16969
16970 CompactReporter::~CompactReporter() {}
16971
16972 CATCH_REGISTER_REPORTER("compact", CompactReporter)
16973
16974 } // end namespace Catch
16975 // end catch_reporter_compact.cpp
16976 // start catch_reporter_console.cpp
16977
16978 #include <cfloat>
16979 #include <cstdio>
16980
16981 #if defined(_MSC_VER)
16982 #pragma warning(push)
16983 #pragma warning(disable : 4061) // Not all labels are EXPLICITLY handled in switch
16984 // Note that 4062 (not all labels are handled and default is missing) is enabled
16985 #endif
16986
16987 #if defined(__clang__)
16988 #pragma clang diagnostic push
16989 // For simplicity, benchmarking-only helpers are always enabled
16990 #pragma clang diagnostic ignored "-Wunused-function"
16991 #endif
16992
16993 namespace Catch {
16994
16995 namespace {
16996
16997 // Formatter impl for ConsoleReporter
16998 class ConsoleAssertionPrinter
16999 {
17000 public:
17001 ConsoleAssertionPrinter &operator=(ConsoleAssertionPrinter const &) = delete;
17002 ConsoleAssertionPrinter(ConsoleAssertionPrinter const &) = delete;
17003 ConsoleAssertionPrinter(std::ostream &_stream, AssertionStats const &_stats,
17004 bool _printInfoMessages)
17005 : stream(_stream), stats(_stats), result(_stats.assertionResult), colour(Colour::None),
17006 message(result.getMessage()), messages(_stats.infoMessages),
17007 printInfoMessages(_printInfoMessages)
17008 {
17009 switch (result.getResultType()) {
17010 case ResultWas::Ok:
17011 colour = Colour::Success;
17012 passOrFail = "PASSED";
17013 // if( result.hasMessage() )
17014 if (_stats.infoMessages.size() == 1)
17015 messageLabel = "with message";
17016 if (_stats.infoMessages.size() > 1)
17017 messageLabel = "with messages";
17018 break;
17019 case ResultWas::ExpressionFailed:
17020 if (result.isOk()) {
17021 colour = Colour::Success;
17022 passOrFail = "FAILED - but was ok";
17023 }
17024 else {
17025 colour = Colour::Error;
17026 passOrFail = "FAILED";
17027 }
17028 if (_stats.infoMessages.size() == 1)
17029 messageLabel = "with message";
17030 if (_stats.infoMessages.size() > 1)
17031 messageLabel = "with messages";
17032 break;
17033 case ResultWas::ThrewException:
17034 colour = Colour::Error;
17035 passOrFail = "FAILED";
17036 messageLabel = "due to unexpected exception with ";
17037 if (_stats.infoMessages.size() == 1)
17038 messageLabel += "message";
17039 if (_stats.infoMessages.size() > 1)
17040 messageLabel += "messages";
17041 break;
17042 case ResultWas::FatalErrorCondition:
17043 colour = Colour::Error;
17044 passOrFail = "FAILED";
17045 messageLabel = "due to a fatal error condition";
17046 break;
17047 case ResultWas::DidntThrowException:
17048 colour = Colour::Error;
17049 passOrFail = "FAILED";
17050 messageLabel = "because no exception was thrown where one was expected";
17051 break;
17052 case ResultWas::Info: messageLabel = "info"; break;
17053 case ResultWas::Warning: messageLabel = "warning"; break;
17054 case ResultWas::ExplicitFailure:
17055 passOrFail = "FAILED";
17056 colour = Colour::Error;
17057 if (_stats.infoMessages.size() == 1)
17058 messageLabel = "explicitly with message";
17059 if (_stats.infoMessages.size() > 1)
17060 messageLabel = "explicitly with messages";
17061 break;
17062 // These cases are here to prevent compiler warnings
17063 case ResultWas::Unknown:
17064 case ResultWas::FailureBit:
17065 case ResultWas::Exception:
17066 passOrFail = "** internal error **";
17067 colour = Colour::Error;
17068 break;
17069 }
17070 }
17071
17072 void print() const
17073 {
17074 printSourceInfo();
17075 if (stats.totals.assertions.total() > 0) {
17076 printResultType();
17077 printOriginalExpression();
17078 printReconstructedExpression();
17079 }
17080 else {
17081 stream << '\n';
17082 }
17083 printMessage();
17084 }
17085
17086 private:
17087 void printResultType() const
17088 {
17089 if (!passOrFail.empty()) {
17090 Colour colourGuard(colour);
17091 stream << passOrFail << ":\n";
17092 }
17093 }
17094 void printOriginalExpression() const
17095 {
17096 if (result.hasExpression()) {
17097 Colour colourGuard(Colour::OriginalExpression);
17098 stream << " ";
17099 stream << result.getExpressionInMacro();
17100 stream << '\n';
17101 }
17102 }
17103 void printReconstructedExpression() const
17104 {
17105 if (result.hasExpandedExpression()) {
17106 stream << "with expansion:\n";
17107 Colour colourGuard(Colour::ReconstructedExpression);
17108 stream << Column(result.getExpandedExpression()).indent(2) << '\n';
17109 }
17110 }
17111 void printMessage() const
17112 {
17113 if (!messageLabel.empty())
17114 stream << messageLabel << ':' << '\n';
17115 for (auto const &msg : messages) {
17116 // If this assertion is a warning ignore any INFO messages
17117 if (printInfoMessages || msg.type != ResultWas::Info)
17118 stream << Column(msg.message).indent(2) << '\n';
17119 }
17120 }
17121 void printSourceInfo() const
17122 {
17123 Colour colourGuard(Colour::FileName);
17124 stream << result.getSourceInfo() << ": ";
17125 }
17126
17127 std::ostream &stream;
17128 AssertionStats const &stats;
17129 AssertionResult const &result;
17130 Colour::Code colour;
17131 std::string passOrFail;
17132 std::string messageLabel;
17133 std::string message;
17134 std::vector<MessageInfo> messages;
17135 bool printInfoMessages;
17136 };
17137
17138 std::size_t makeRatio(std::size_t number, std::size_t total)
17139 {
17140 std::size_t ratio = total > 0 ? CATCH_CONFIG_CONSOLE_WIDTH * number / total : 0;
17141 return (ratio == 0 && number > 0) ? 1 : ratio;
17142 }
17143
17144 std::size_t &findMax(std::size_t &i, std::size_t &j, std::size_t &k)
17145 {
17146 if (i > j && i > k)
17147 return i;
17148 else if (j > k)
17149 return j;
17150 else
17151 return k;
17152 }
17153
17154 struct ColumnInfo
17155 {
17156 enum Justification { Left, Right };
17157 std::string name;
17158 int width;
17159 Justification justification;
17160 };
17161 struct ColumnBreak
17162 {
17163 };
17164 struct RowBreak
17165 {
17166 };
17167
17168 class Duration
17169 {
17170 enum class Unit { Auto, Nanoseconds, Microseconds, Milliseconds, Seconds, Minutes };
17171 static const uint64_t s_nanosecondsInAMicrosecond = 1000;
17172 static const uint64_t s_nanosecondsInAMillisecond = 1000 * s_nanosecondsInAMicrosecond;
17173 static const uint64_t s_nanosecondsInASecond = 1000 * s_nanosecondsInAMillisecond;
17174 static const uint64_t s_nanosecondsInAMinute = 60 * s_nanosecondsInASecond;
17175
17176 double m_inNanoseconds;
17177 Unit m_units;
17178
17179 public:
17180 explicit Duration(double inNanoseconds, Unit units = Unit::Auto)
17181 : m_inNanoseconds(inNanoseconds), m_units(units)
17182 {
17183 if (m_units == Unit::Auto) {
17184 if (m_inNanoseconds < s_nanosecondsInAMicrosecond)
17185 m_units = Unit::Nanoseconds;
17186 else if (m_inNanoseconds < s_nanosecondsInAMillisecond)
17187 m_units = Unit::Microseconds;
17188 else if (m_inNanoseconds < s_nanosecondsInASecond)
17189 m_units = Unit::Milliseconds;
17190 else if (m_inNanoseconds < s_nanosecondsInAMinute)
17191 m_units = Unit::Seconds;
17192 else
17193 m_units = Unit::Minutes;
17194 }
17195 }
17196
17197 auto value() const -> double
17198 {
17199 switch (m_units) {
17200 case Unit::Microseconds:
17201 return m_inNanoseconds / static_cast<double>(s_nanosecondsInAMicrosecond);
17202 case Unit::Milliseconds:
17203 return m_inNanoseconds / static_cast<double>(s_nanosecondsInAMillisecond);
17204 case Unit::Seconds: return m_inNanoseconds / static_cast<double>(s_nanosecondsInASecond);
17205 case Unit::Minutes: return m_inNanoseconds / static_cast<double>(s_nanosecondsInAMinute);
17206 default: return m_inNanoseconds;
17207 }
17208 }
17209 auto unitsAsString() const -> std::string
17210 {
17211 switch (m_units) {
17212 case Unit::Nanoseconds: return "ns";
17213 case Unit::Microseconds: return "us";
17214 case Unit::Milliseconds: return "ms";
17215 case Unit::Seconds: return "s";
17216 case Unit::Minutes: return "m";
17217 default: return "** internal error **";
17218 }
17219 }
17220 friend auto operator<<(std::ostream &os, Duration const &duration) -> std::ostream &
17221 {
17222 return os << duration.value() << ' ' << duration.unitsAsString();
17223 }
17224 };
17225 } // namespace
17226
17227 class TablePrinter
17228 {
17229 std::ostream &m_os;
17230 std::vector<ColumnInfo> m_columnInfos;
17231 std::ostringstream m_oss;
17232 int m_currentColumn = -1;
17233 bool m_isOpen = false;
17234
17235 public:
17236 TablePrinter(std::ostream &os, std::vector<ColumnInfo> columnInfos)
17237 : m_os(os), m_columnInfos(std::move(columnInfos))
17238 {
17239 }
17240
17241 auto columnInfos() const -> std::vector<ColumnInfo> const & { return m_columnInfos; }
17242
17243 void open()
17244 {
17245 if (!m_isOpen) {
17246 m_isOpen = true;
17247 *this << RowBreak();
17248
17249 Columns headerCols;
17250 Spacer spacer(2);
17251 for (auto const &info : m_columnInfos) {
17252 headerCols += Column(info.name).width(static_cast<std::size_t>(info.width - 2));
17253 headerCols += spacer;
17254 }
17255 m_os << headerCols << '\n';
17256
17257 m_os << Catch::getLineOfChars<'-'>() << '\n';
17258 }
17259 }
17260 void close()
17261 {
17262 if (m_isOpen) {
17263 *this << RowBreak();
17264 m_os << std::endl;
17265 m_isOpen = false;
17266 }
17267 }
17268
17269 template <typename T> friend TablePrinter &operator<<(TablePrinter &tp, T const &value)
17270 {
17271 tp.m_oss << value;
17272 return tp;
17273 }
17274
17275 friend TablePrinter &operator<<(TablePrinter &tp, ColumnBreak)
17276 {
17277 auto colStr = tp.m_oss.str();
17278 const auto strSize = colStr.size();
17279 tp.m_oss.str("");
17280 tp.open();
17281 if (tp.m_currentColumn == static_cast<int>(tp.m_columnInfos.size() - 1)) {
17282 tp.m_currentColumn = -1;
17283 tp.m_os << '\n';
17284 }
17285 tp.m_currentColumn++;
17286
17287 auto colInfo = tp.m_columnInfos[tp.m_currentColumn];
17288 auto padding = (strSize + 1 < static_cast<std::size_t>(colInfo.width))
17289 ? std::string(colInfo.width - (strSize + 1), ' ')
17290 : std::string();
17291 if (colInfo.justification == ColumnInfo::Left)
17292 tp.m_os << colStr << padding << ' ';
17293 else
17294 tp.m_os << padding << colStr << ' ';
17295 return tp;
17296 }
17297
17298 friend TablePrinter &operator<<(TablePrinter &tp, RowBreak)
17299 {
17300 if (tp.m_currentColumn > 0) {
17301 tp.m_os << '\n';
17302 tp.m_currentColumn = -1;
17303 }
17304 return tp;
17305 }
17306 };
17307
17308 ConsoleReporter::ConsoleReporter(ReporterConfig const &config)
17309 : StreamingReporterBase(config),
17310 m_tablePrinter(new TablePrinter(config.stream(), [&config]() -> std::vector<ColumnInfo> {
17311 if (config.fullConfig()->benchmarkNoAnalysis()) {
17312 return {{"benchmark name", CATCH_CONFIG_CONSOLE_WIDTH - 43, ColumnInfo::Left},
17313 {" samples", 14, ColumnInfo::Right},
17314 {" iterations", 14, ColumnInfo::Right},
17315 {" mean", 14, ColumnInfo::Right}};
17316 }
17317 else {
17318 return {{"benchmark name", CATCH_CONFIG_CONSOLE_WIDTH - 43, ColumnInfo::Left},
17319 {"samples mean std dev", 14, ColumnInfo::Right},
17320 {"iterations low mean low std dev", 14, ColumnInfo::Right},
17321 {"estimated high mean high std dev", 14, ColumnInfo::Right}};
17322 }
17323 }()))
17324 {
17325 }
17326 ConsoleReporter::~ConsoleReporter() = default;
17327
17328 std::string ConsoleReporter::getDescription()
17329 {
17330 return "Reports test results as plain lines of text";
17331 }
17332
17333 void ConsoleReporter::noMatchingTestCases(std::string const &spec)
17334 {
17335 stream << "No test cases matched '" << spec << '\'' << std::endl;
17336 }
17337
17338 void ConsoleReporter::reportInvalidArguments(std::string const &arg)
17339 {
17340 stream << "Invalid Filter: " << arg << std::endl;
17341 }
17342
17343 void ConsoleReporter::assertionStarting(AssertionInfo const &) {}
17344
17345 bool ConsoleReporter::assertionEnded(AssertionStats const &_assertionStats)
17346 {
17347 AssertionResult const &result = _assertionStats.assertionResult;
17348
17349 bool includeResults = m_config->includeSuccessfulResults() || !result.isOk();
17350
17351 // Drop out if result was successful but we're not printing them.
17352 if (!includeResults && result.getResultType() != ResultWas::Warning)
17353 return false;
17354
17355 lazyPrint();
17356
17357 ConsoleAssertionPrinter printer(stream, _assertionStats, includeResults);
17358 printer.print();
17359 stream << std::endl;
17360 return true;
17361 }
17362
17363 void ConsoleReporter::sectionStarting(SectionInfo const &_sectionInfo)
17364 {
17365 m_tablePrinter->close();
17366 m_headerPrinted = false;
17367 StreamingReporterBase::sectionStarting(_sectionInfo);
17368 }
17369 void ConsoleReporter::sectionEnded(SectionStats const &_sectionStats)
17370 {
17371 m_tablePrinter->close();
17372 if (_sectionStats.missingAssertions) {
17373 lazyPrint();
17374 Colour colour(Colour::ResultError);
17375 if (m_sectionStack.size() > 1)
17376 stream << "\nNo assertions in section";
17377 else
17378 stream << "\nNo assertions in test case";
17379 stream << " '" << _sectionStats.sectionInfo.name << "'\n" << std::endl;
17380 }
17381 double dur = _sectionStats.durationInSeconds;
17382 if (shouldShowDuration(*m_config, dur)) {
17383 stream << getFormattedDuration(dur) << " s: " << _sectionStats.sectionInfo.name << std::endl;
17384 }
17385 if (m_headerPrinted) {
17386 m_headerPrinted = false;
17387 }
17388 StreamingReporterBase::sectionEnded(_sectionStats);
17389 }
17390
17391 #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
17392 void ConsoleReporter::benchmarkPreparing(std::string const &name)
17393 {
17394 lazyPrintWithoutClosingBenchmarkTable();
17395
17396 auto nameCol =
17397 Column(name).width(static_cast<std::size_t>(m_tablePrinter->columnInfos()[0].width - 2));
17398
17399 bool firstLine = true;
17400 for (auto line : nameCol) {
17401 if (!firstLine)
17402 (*m_tablePrinter) << ColumnBreak() << ColumnBreak() << ColumnBreak();
17403 else
17404 firstLine = false;
17405
17406 (*m_tablePrinter) << line << ColumnBreak();
17407 }
17408 }
17409
17410 void ConsoleReporter::benchmarkStarting(BenchmarkInfo const &info)
17411 {
17412 (*m_tablePrinter) << info.samples << ColumnBreak() << info.iterations << ColumnBreak();
17413 if (!m_config->benchmarkNoAnalysis())
17414 (*m_tablePrinter) << Duration(info.estimatedDuration) << ColumnBreak();
17415 }
17416 void ConsoleReporter::benchmarkEnded(BenchmarkStats<> const &stats)
17417 {
17418 if (m_config->benchmarkNoAnalysis()) {
17419 (*m_tablePrinter) << Duration(stats.mean.point.count()) << ColumnBreak();
17420 }
17421 else {
17422 (*m_tablePrinter) << ColumnBreak() << Duration(stats.mean.point.count()) << ColumnBreak()
17423 << Duration(stats.mean.lower_bound.count()) << ColumnBreak()
17424 << Duration(stats.mean.upper_bound.count()) << ColumnBreak()
17425 << ColumnBreak() << Duration(stats.standardDeviation.point.count())
17426 << ColumnBreak() << Duration(stats.standardDeviation.lower_bound.count())
17427 << ColumnBreak() << Duration(stats.standardDeviation.upper_bound.count())
17428 << ColumnBreak() << ColumnBreak() << ColumnBreak() << ColumnBreak()
17429 << ColumnBreak();
17430 }
17431 }
17432
17433 void ConsoleReporter::benchmarkFailed(std::string const &error)
17434 {
17435 Colour colour(Colour::Red);
17436 (*m_tablePrinter) << "Benchmark failed (" << error << ')' << ColumnBreak() << RowBreak();
17437 }
17438 #endif // CATCH_CONFIG_ENABLE_BENCHMARKING
17439
17440 void ConsoleReporter::testCaseEnded(TestCaseStats const &_testCaseStats)
17441 {
17442 m_tablePrinter->close();
17443 StreamingReporterBase::testCaseEnded(_testCaseStats);
17444 m_headerPrinted = false;
17445 }
17446 void ConsoleReporter::testGroupEnded(TestGroupStats const &_testGroupStats)
17447 {
17448 if (currentGroupInfo.used) {
17449 printSummaryDivider();
17450 stream << "Summary for group '" << _testGroupStats.groupInfo.name << "':\n";
17451 printTotals(_testGroupStats.totals);
17452 stream << '\n' << std::endl;
17453 }
17454 StreamingReporterBase::testGroupEnded(_testGroupStats);
17455 }
17456 void ConsoleReporter::testRunEnded(TestRunStats const &_testRunStats)
17457 {
17458 printTotalsDivider(_testRunStats.totals);
17459 printTotals(_testRunStats.totals);
17460 stream << std::endl;
17461 StreamingReporterBase::testRunEnded(_testRunStats);
17462 }
17463 void ConsoleReporter::testRunStarting(TestRunInfo const &_testInfo)
17464 {
17465 StreamingReporterBase::testRunStarting(_testInfo);
17466 printTestFilters();
17467 }
17468
17469 void ConsoleReporter::lazyPrint()
17470 {
17471
17472 m_tablePrinter->close();
17473 lazyPrintWithoutClosingBenchmarkTable();
17474 }
17475
17476 void ConsoleReporter::lazyPrintWithoutClosingBenchmarkTable()
17477 {
17478
17479 if (!currentTestRunInfo.used)
17480 lazyPrintRunInfo();
17481 if (!currentGroupInfo.used)
17482 lazyPrintGroupInfo();
17483
17484 if (!m_headerPrinted) {
17485 printTestCaseAndSectionHeader();
17486 m_headerPrinted = true;
17487 }
17488 }
17489 void ConsoleReporter::lazyPrintRunInfo()
17490 {
17491 stream << '\n' << getLineOfChars<'~'>() << '\n';
17492 Colour colour(Colour::SecondaryText);
17493 stream << currentTestRunInfo->name << " is a Catch v" << libraryVersion()
17494 << " host application.\n"
17495 << "Run with -? for options\n\n";
17496
17497 if (m_config->rngSeed() != 0)
17498 stream << "Randomness seeded to: " << m_config->rngSeed() << "\n\n";
17499
17500 currentTestRunInfo.used = true;
17501 }
17502 void ConsoleReporter::lazyPrintGroupInfo()
17503 {
17504 if (!currentGroupInfo->name.empty() && currentGroupInfo->groupsCounts > 1) {
17505 printClosedHeader("Group: " + currentGroupInfo->name);
17506 currentGroupInfo.used = true;
17507 }
17508 }
17509 void ConsoleReporter::printTestCaseAndSectionHeader()
17510 {
17511 assert(!m_sectionStack.empty());
17512 printOpenHeader(currentTestCaseInfo->name);
17513
17514 if (m_sectionStack.size() > 1) {
17515 Colour colourGuard(Colour::Headers);
17516
17517 auto it = m_sectionStack.begin() + 1, // Skip first section (test case)
17518 itEnd = m_sectionStack.end();
17519 for (; it != itEnd; ++it)
17520 printHeaderString(it->name, 2);
17521 }
17522
17523 SourceLineInfo lineInfo = m_sectionStack.back().lineInfo;
17524
17525 stream << getLineOfChars<'-'>() << '\n';
17526 Colour colourGuard(Colour::FileName);
17527 stream << lineInfo << '\n';
17528 stream << getLineOfChars<'.'>() << '\n' << std::endl;
17529 }
17530
17531 void ConsoleReporter::printClosedHeader(std::string const &_name)
17532 {
17533 printOpenHeader(_name);
17534 stream << getLineOfChars<'.'>() << '\n';
17535 }
17536 void ConsoleReporter::printOpenHeader(std::string const &_name)
17537 {
17538 stream << getLineOfChars<'-'>() << '\n';
17539 {
17540 Colour colourGuard(Colour::Headers);
17541 printHeaderString(_name);
17542 }
17543 }
17544
17545 // if string has a : in first line will set indent to follow it on
17546 // subsequent lines
17547 void ConsoleReporter::printHeaderString(std::string const &_string, std::size_t indent)
17548 {
17549 std::size_t i = _string.find(": ");
17550 if (i != std::string::npos)
17551 i += 2;
17552 else
17553 i = 0;
17554 stream << Column(_string).indent(indent + i).initialIndent(indent) << '\n';
17555 }
17556
17557 struct SummaryColumn
17558 {
17559
17560 SummaryColumn(std::string _label, Colour::Code _colour)
17561 : label(std::move(_label)), colour(_colour)
17562 {
17563 }
17564 SummaryColumn addRow(std::size_t count)
17565 {
17566 ReusableStringStream rss;
17567 rss << count;
17568 std::string row = rss.str();
17569 for (auto &oldRow : rows) {
17570 while (oldRow.size() < row.size())
17571 oldRow = ' ' + oldRow;
17572 while (oldRow.size() > row.size())
17573 row = ' ' + row;
17574 }
17575 rows.push_back(row);
17576 return *this;
17577 }
17578
17579 std::string label;
17580 Colour::Code colour;
17581 std::vector<std::string> rows;
17582 };
17583
17584 void ConsoleReporter::printTotals(Totals const &totals)
17585 {
17586 if (totals.testCases.total() == 0) {
17587 stream << Colour(Colour::Warning) << "No tests ran\n";
17588 }
17589 else if (totals.assertions.total() > 0 && totals.testCases.allPassed()) {
17590 stream << Colour(Colour::ResultSuccess) << "All tests passed";
17591 stream << " (" << pluralise(totals.assertions.passed, "assertion") << " in "
17592 << pluralise(totals.testCases.passed, "test case") << ')' << '\n';
17593 }
17594 else {
17595
17596 std::vector<SummaryColumn> columns;
17597 columns.push_back(SummaryColumn("", Colour::None)
17598 .addRow(totals.testCases.total())
17599 .addRow(totals.assertions.total()));
17600 columns.push_back(SummaryColumn("passed", Colour::Success)
17601 .addRow(totals.testCases.passed)
17602 .addRow(totals.assertions.passed));
17603 columns.push_back(SummaryColumn("failed", Colour::ResultError)
17604 .addRow(totals.testCases.failed)
17605 .addRow(totals.assertions.failed));
17606 columns.push_back(SummaryColumn("failed as expected", Colour::ResultExpectedFailure)
17607 .addRow(totals.testCases.failedButOk)
17608 .addRow(totals.assertions.failedButOk));
17609
17610 printSummaryRow("test cases", columns, 0);
17611 printSummaryRow("assertions", columns, 1);
17612 }
17613 }
17614 void ConsoleReporter::printSummaryRow(std::string const &label,
17615 std::vector<SummaryColumn> const &cols, std::size_t row)
17616 {
17617 for (auto col : cols) {
17618 std::string value = col.rows[row];
17619 if (col.label.empty()) {
17620 stream << label << ": ";
17621 if (value != "0")
17622 stream << value;
17623 else
17624 stream << Colour(Colour::Warning) << "- none -";
17625 }
17626 else if (value != "0") {
17627 stream << Colour(Colour::LightGrey) << " | ";
17628 stream << Colour(col.colour) << value << ' ' << col.label;
17629 }
17630 }
17631 stream << '\n';
17632 }
17633
17634 void ConsoleReporter::printTotalsDivider(Totals const &totals)
17635 {
17636 if (totals.testCases.total() > 0) {
17637 std::size_t failedRatio = makeRatio(totals.testCases.failed, totals.testCases.total());
17638 std::size_t failedButOkRatio =
17639 makeRatio(totals.testCases.failedButOk, totals.testCases.total());
17640 std::size_t passedRatio = makeRatio(totals.testCases.passed, totals.testCases.total());
17641 while (failedRatio + failedButOkRatio + passedRatio < CATCH_CONFIG_CONSOLE_WIDTH - 1)
17642 findMax(failedRatio, failedButOkRatio, passedRatio)++;
17643 while (failedRatio + failedButOkRatio + passedRatio > CATCH_CONFIG_CONSOLE_WIDTH - 1)
17644 findMax(failedRatio, failedButOkRatio, passedRatio)--;
17645
17646 stream << Colour(Colour::Error) << std::string(failedRatio, '=');
17647 stream << Colour(Colour::ResultExpectedFailure) << std::string(failedButOkRatio, '=');
17648 if (totals.testCases.allPassed())
17649 stream << Colour(Colour::ResultSuccess) << std::string(passedRatio, '=');
17650 else
17651 stream << Colour(Colour::Success) << std::string(passedRatio, '=');
17652 }
17653 else {
17654 stream << Colour(Colour::Warning) << std::string(CATCH_CONFIG_CONSOLE_WIDTH - 1, '=');
17655 }
17656 stream << '\n';
17657 }
17658 void ConsoleReporter::printSummaryDivider() { stream << getLineOfChars<'-'>() << '\n'; }
17659
17660 void ConsoleReporter::printTestFilters()
17661 {
17662 if (m_config->testSpec().hasFilters()) {
17663 Colour guard(Colour::BrightYellow);
17664 stream << "Filters: " << serializeFilters(m_config->getTestsOrTags()) << '\n';
17665 }
17666 }
17667
17668 CATCH_REGISTER_REPORTER("console", ConsoleReporter)
17669
17670 } // end namespace Catch
17671
17672 #if defined(_MSC_VER)
17673 #pragma warning(pop)
17674 #endif
17675
17676 #if defined(__clang__)
17677 #pragma clang diagnostic pop
17678 #endif
17679 // end catch_reporter_console.cpp
17680 // start catch_reporter_junit.cpp
17681
17682 #include <algorithm>
17683 #include <cassert>
17684 #include <ctime>
17685 #include <sstream>
17686
17687 namespace Catch {
17688
17689 namespace {
17690 std::string getCurrentTimestamp()
17691 {
17692 // Beware, this is not reentrant because of backward compatibility issues
17693 // Also, UTC only, again because of backward compatibility (%z is C++11)
17694 time_t rawtime;
17695 std::time(&rawtime);
17696 auto const timeStampSize = sizeof("2017-01-16T17:06:45Z");
17697
17698 #ifdef _MSC_VER
17699 std::tm timeInfo = {};
17700 gmtime_s(&timeInfo, &rawtime);
17701 #else
17702 std::tm *timeInfo;
17703 timeInfo = std::gmtime(&rawtime);
17704 #endif
17705
17706 char timeStamp[timeStampSize];
17707 const char *const fmt = "%Y-%m-%dT%H:%M:%SZ";
17708
17709 #ifdef _MSC_VER
17710 std::strftime(timeStamp, timeStampSize, fmt, &timeInfo);
17711 #else
17712 std::strftime(timeStamp, timeStampSize, fmt, timeInfo);
17713 #endif
17714 return std::string(timeStamp);
17715 }
17716
17717 std::string fileNameTag(const std::vector<std::string> &tags)
17718 {
17719 auto it = std::find_if(begin(tags), end(tags),
17720 [](std::string const &tag) { return tag.front() == '#'; });
17721 if (it != tags.end())
17722 return it->substr(1);
17723 return std::string();
17724 }
17725 } // anonymous namespace
17726
17727 JunitReporter::JunitReporter(ReporterConfig const &_config)
17728 : CumulativeReporterBase(_config), xml(_config.stream())
17729 {
17730 m_reporterPrefs.shouldRedirectStdOut = true;
17731 m_reporterPrefs.shouldReportAllAssertions = true;
17732 }
17733
17734 JunitReporter::~JunitReporter() {}
17735
17736 std::string JunitReporter::getDescription()
17737 {
17738 return "Reports test results in an XML format that looks like Ant's junitreport target";
17739 }
17740
17741 void JunitReporter::noMatchingTestCases(std::string const & /*spec*/) {}
17742
17743 void JunitReporter::testRunStarting(TestRunInfo const &runInfo)
17744 {
17745 CumulativeReporterBase::testRunStarting(runInfo);
17746 xml.startElement("testsuites");
17747 }
17748
17749 void JunitReporter::testGroupStarting(GroupInfo const &groupInfo)
17750 {
17751 suiteTimer.start();
17752 stdOutForSuite.clear();
17753 stdErrForSuite.clear();
17754 unexpectedExceptions = 0;
17755 CumulativeReporterBase::testGroupStarting(groupInfo);
17756 }
17757
17758 void JunitReporter::testCaseStarting(TestCaseInfo const &testCaseInfo)
17759 {
17760 m_okToFail = testCaseInfo.okToFail();
17761 }
17762
17763 bool JunitReporter::assertionEnded(AssertionStats const &assertionStats)
17764 {
17765 if (assertionStats.assertionResult.getResultType() == ResultWas::ThrewException && !m_okToFail)
17766 unexpectedExceptions++;
17767 return CumulativeReporterBase::assertionEnded(assertionStats);
17768 }
17769
17770 void JunitReporter::testCaseEnded(TestCaseStats const &testCaseStats)
17771 {
17772 stdOutForSuite += testCaseStats.stdOut;
17773 stdErrForSuite += testCaseStats.stdErr;
17774 CumulativeReporterBase::testCaseEnded(testCaseStats);
17775 }
17776
17777 void JunitReporter::testGroupEnded(TestGroupStats const &testGroupStats)
17778 {
17779 double suiteTime = suiteTimer.getElapsedSeconds();
17780 CumulativeReporterBase::testGroupEnded(testGroupStats);
17781 writeGroup(*m_testGroups.back(), suiteTime);
17782 }
17783
17784 void JunitReporter::testRunEndedCumulative() { xml.endElement(); }
17785
17786 void JunitReporter::writeGroup(TestGroupNode const &groupNode, double suiteTime)
17787 {
17788 XmlWriter::ScopedElement e = xml.scopedElement("testsuite");
17789
17790 TestGroupStats const &stats = groupNode.value;
17791 xml.writeAttribute("name", stats.groupInfo.name);
17792 xml.writeAttribute("errors", unexpectedExceptions);
17793 xml.writeAttribute("failures", stats.totals.assertions.failed - unexpectedExceptions);
17794 xml.writeAttribute("tests", stats.totals.assertions.total());
17795 xml.writeAttribute("hostname", "tbd"); // !TBD
17796 if (m_config->showDurations() == ShowDurations::Never)
17797 xml.writeAttribute("time", "");
17798 else
17799 xml.writeAttribute("time", suiteTime);
17800 xml.writeAttribute("timestamp", getCurrentTimestamp());
17801
17802 // Write properties if there are any
17803 if (m_config->hasTestFilters() || m_config->rngSeed() != 0) {
17804 auto properties = xml.scopedElement("properties");
17805 if (m_config->hasTestFilters()) {
17806 xml.scopedElement("property")
17807 .writeAttribute("name", "filters")
17808 .writeAttribute("value", serializeFilters(m_config->getTestsOrTags()));
17809 }
17810 if (m_config->rngSeed() != 0) {
17811 xml.scopedElement("property")
17812 .writeAttribute("name", "random-seed")
17813 .writeAttribute("value", m_config->rngSeed());
17814 }
17815 }
17816
17817 // Write test cases
17818 for (auto const &child : groupNode.children)
17819 writeTestCase(*child);
17820
17821 xml.scopedElement("system-out").writeText(trim(stdOutForSuite), XmlFormatting::Newline);
17822 xml.scopedElement("system-err").writeText(trim(stdErrForSuite), XmlFormatting::Newline);
17823 }
17824
17825 void JunitReporter::writeTestCase(TestCaseNode const &testCaseNode)
17826 {
17827 TestCaseStats const &stats = testCaseNode.value;
17828
17829 // All test cases have exactly one section - which represents the
17830 // test case itself. That section may have 0-n nested sections
17831 assert(testCaseNode.children.size() == 1);
17832 SectionNode const &rootSection = *testCaseNode.children.front();
17833
17834 std::string className = stats.testInfo.className;
17835
17836 if (className.empty()) {
17837 className = fileNameTag(stats.testInfo.tags);
17838 if (className.empty())
17839 className = "global";
17840 }
17841
17842 if (!m_config->name().empty())
17843 className = m_config->name() + "." + className;
17844
17845 writeSection(className, "", rootSection);
17846 }
17847
17848 void JunitReporter::writeSection(std::string const &className, std::string const &rootName,
17849 SectionNode const &sectionNode)
17850 {
17851 std::string name = trim(sectionNode.stats.sectionInfo.name);
17852 if (!rootName.empty())
17853 name = rootName + '/' + name;
17854
17855 if (!sectionNode.assertions.empty() || !sectionNode.stdOut.empty() ||
17856 !sectionNode.stdErr.empty()) {
17857 XmlWriter::ScopedElement e = xml.scopedElement("testcase");
17858 if (className.empty()) {
17859 xml.writeAttribute("classname", name);
17860 xml.writeAttribute("name", "root");
17861 }
17862 else {
17863 xml.writeAttribute("classname", className);
17864 xml.writeAttribute("name", name);
17865 }
17866 xml.writeAttribute("time", ::Catch::Detail::stringify(sectionNode.stats.durationInSeconds));
17867 // This is not ideal, but it should be enough to mimic gtest's
17868 // junit output.
17869 // Ideally the JUnit reporter would also handle `skipTest`
17870 // events and write those out appropriately.
17871 xml.writeAttribute("status", "run");
17872
17873 writeAssertions(sectionNode);
17874
17875 if (!sectionNode.stdOut.empty())
17876 xml.scopedElement("system-out").writeText(trim(sectionNode.stdOut), XmlFormatting::Newline);
17877 if (!sectionNode.stdErr.empty())
17878 xml.scopedElement("system-err").writeText(trim(sectionNode.stdErr), XmlFormatting::Newline);
17879 }
17880 for (auto const &childNode : sectionNode.childSections)
17881 if (className.empty())
17882 writeSection(name, "", *childNode);
17883 else
17884 writeSection(className, name, *childNode);
17885 }
17886
17887 void JunitReporter::writeAssertions(SectionNode const &sectionNode)
17888 {
17889 for (auto const &assertion : sectionNode.assertions)
17890 writeAssertion(assertion);
17891 }
17892
17893 void JunitReporter::writeAssertion(AssertionStats const &stats)
17894 {
17895 AssertionResult const &result = stats.assertionResult;
17896 if (!result.isOk()) {
17897 std::string elementName;
17898 switch (result.getResultType()) {
17899 case ResultWas::ThrewException:
17900 case ResultWas::FatalErrorCondition: elementName = "error"; break;
17901 case ResultWas::ExplicitFailure:
17902 case ResultWas::ExpressionFailed:
17903 case ResultWas::DidntThrowException: elementName = "failure"; break;
17904
17905 // We should never see these here:
17906 case ResultWas::Info:
17907 case ResultWas::Warning:
17908 case ResultWas::Ok:
17909 case ResultWas::Unknown:
17910 case ResultWas::FailureBit:
17911 case ResultWas::Exception: elementName = "internalError"; break;
17912 }
17913
17914 XmlWriter::ScopedElement e = xml.scopedElement(elementName);
17915
17916 xml.writeAttribute("message", result.getExpression());
17917 xml.writeAttribute("type", result.getTestMacroName());
17918
17919 ReusableStringStream rss;
17920 if (stats.totals.assertions.total() > 0) {
17921 rss << "FAILED" << ":\n";
17922 if (result.hasExpression()) {
17923 rss << " ";
17924 rss << result.getExpressionInMacro();
17925 rss << '\n';
17926 }
17927 if (result.hasExpandedExpression()) {
17928 rss << "with expansion:\n";
17929 rss << Column(result.getExpandedExpression()).indent(2) << '\n';
17930 }
17931 }
17932 else {
17933 rss << '\n';
17934 }
17935
17936 if (!result.getMessage().empty())
17937 rss << result.getMessage() << '\n';
17938 for (auto const &msg : stats.infoMessages)
17939 if (msg.type == ResultWas::Info)
17940 rss << msg.message << '\n';
17941
17942 rss << "at " << result.getSourceInfo();
17943 xml.writeText(rss.str(), XmlFormatting::Newline);
17944 }
17945 }
17946
17947 CATCH_REGISTER_REPORTER("junit", JunitReporter)
17948
17949 } // end namespace Catch
17950 // end catch_reporter_junit.cpp
17951 // start catch_reporter_listening.cpp
17952
17953 #include <cassert>
17954
17955 namespace Catch {
17956
17957 ListeningReporter::ListeningReporter()
17958 {
17959 // We will assume that listeners will always want all assertions
17960 m_preferences.shouldReportAllAssertions = true;
17961 }
17962
17963 void ListeningReporter::addListener(IStreamingReporterPtr &&listener)
17964 {
17965 m_listeners.push_back(std::move(listener));
17966 }
17967
17968 void ListeningReporter::addReporter(IStreamingReporterPtr &&reporter)
17969 {
17970 assert(!m_reporter && "Listening reporter can wrap only 1 real reporter");
17971 m_reporter = std::move(reporter);
17972 m_preferences.shouldRedirectStdOut = m_reporter->getPreferences().shouldRedirectStdOut;
17973 }
17974
17975 ReporterPreferences ListeningReporter::getPreferences() const { return m_preferences; }
17976
17977 std::set<Verbosity> ListeningReporter::getSupportedVerbosities() { return std::set<Verbosity>{}; }
17978
17979 void ListeningReporter::noMatchingTestCases(std::string const &spec)
17980 {
17981 for (auto const &listener : m_listeners) {
17982 listener->noMatchingTestCases(spec);
17983 }
17984 m_reporter->noMatchingTestCases(spec);
17985 }
17986
17987 void ListeningReporter::reportInvalidArguments(std::string const &arg)
17988 {
17989 for (auto const &listener : m_listeners) {
17990 listener->reportInvalidArguments(arg);
17991 }
17992 m_reporter->reportInvalidArguments(arg);
17993 }
17994
17995 #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
17996 void ListeningReporter::benchmarkPreparing(std::string const &name)
17997 {
17998 for (auto const &listener : m_listeners) {
17999 listener->benchmarkPreparing(name);
18000 }
18001 m_reporter->benchmarkPreparing(name);
18002 }
18003 void ListeningReporter::benchmarkStarting(BenchmarkInfo const &benchmarkInfo)
18004 {
18005 for (auto const &listener : m_listeners) {
18006 listener->benchmarkStarting(benchmarkInfo);
18007 }
18008 m_reporter->benchmarkStarting(benchmarkInfo);
18009 }
18010 void ListeningReporter::benchmarkEnded(BenchmarkStats<> const &benchmarkStats)
18011 {
18012 for (auto const &listener : m_listeners) {
18013 listener->benchmarkEnded(benchmarkStats);
18014 }
18015 m_reporter->benchmarkEnded(benchmarkStats);
18016 }
18017
18018 void ListeningReporter::benchmarkFailed(std::string const &error)
18019 {
18020 for (auto const &listener : m_listeners) {
18021 listener->benchmarkFailed(error);
18022 }
18023 m_reporter->benchmarkFailed(error);
18024 }
18025 #endif // CATCH_CONFIG_ENABLE_BENCHMARKING
18026
18027 void ListeningReporter::testRunStarting(TestRunInfo const &testRunInfo)
18028 {
18029 for (auto const &listener : m_listeners) {
18030 listener->testRunStarting(testRunInfo);
18031 }
18032 m_reporter->testRunStarting(testRunInfo);
18033 }
18034
18035 void ListeningReporter::testGroupStarting(GroupInfo const &groupInfo)
18036 {
18037 for (auto const &listener : m_listeners) {
18038 listener->testGroupStarting(groupInfo);
18039 }
18040 m_reporter->testGroupStarting(groupInfo);
18041 }
18042
18043 void ListeningReporter::testCaseStarting(TestCaseInfo const &testInfo)
18044 {
18045 for (auto const &listener : m_listeners) {
18046 listener->testCaseStarting(testInfo);
18047 }
18048 m_reporter->testCaseStarting(testInfo);
18049 }
18050
18051 void ListeningReporter::sectionStarting(SectionInfo const &sectionInfo)
18052 {
18053 for (auto const &listener : m_listeners) {
18054 listener->sectionStarting(sectionInfo);
18055 }
18056 m_reporter->sectionStarting(sectionInfo);
18057 }
18058
18059 void ListeningReporter::assertionStarting(AssertionInfo const &assertionInfo)
18060 {
18061 for (auto const &listener : m_listeners) {
18062 listener->assertionStarting(assertionInfo);
18063 }
18064 m_reporter->assertionStarting(assertionInfo);
18065 }
18066
18067 // The return value indicates if the messages buffer should be cleared:
18068 bool ListeningReporter::assertionEnded(AssertionStats const &assertionStats)
18069 {
18070 for (auto const &listener : m_listeners) {
18071 static_cast<void>(listener->assertionEnded(assertionStats));
18072 }
18073 return m_reporter->assertionEnded(assertionStats);
18074 }
18075
18076 void ListeningReporter::sectionEnded(SectionStats const &sectionStats)
18077 {
18078 for (auto const &listener : m_listeners) {
18079 listener->sectionEnded(sectionStats);
18080 }
18081 m_reporter->sectionEnded(sectionStats);
18082 }
18083
18084 void ListeningReporter::testCaseEnded(TestCaseStats const &testCaseStats)
18085 {
18086 for (auto const &listener : m_listeners) {
18087 listener->testCaseEnded(testCaseStats);
18088 }
18089 m_reporter->testCaseEnded(testCaseStats);
18090 }
18091
18092 void ListeningReporter::testGroupEnded(TestGroupStats const &testGroupStats)
18093 {
18094 for (auto const &listener : m_listeners) {
18095 listener->testGroupEnded(testGroupStats);
18096 }
18097 m_reporter->testGroupEnded(testGroupStats);
18098 }
18099
18100 void ListeningReporter::testRunEnded(TestRunStats const &testRunStats)
18101 {
18102 for (auto const &listener : m_listeners) {
18103 listener->testRunEnded(testRunStats);
18104 }
18105 m_reporter->testRunEnded(testRunStats);
18106 }
18107
18108 void ListeningReporter::skipTest(TestCaseInfo const &testInfo)
18109 {
18110 for (auto const &listener : m_listeners) {
18111 listener->skipTest(testInfo);
18112 }
18113 m_reporter->skipTest(testInfo);
18114 }
18115
18116 bool ListeningReporter::isMulti() const { return true; }
18117
18118 } // end namespace Catch
18119 // end catch_reporter_listening.cpp
18120 // start catch_reporter_xml.cpp
18121
18122 #if defined(_MSC_VER)
18123 #pragma warning(push)
18124 #pragma warning(disable : 4061) // Not all labels are EXPLICITLY handled in switch
18125 // Note that 4062 (not all labels are handled
18126 // and default is missing) is enabled
18127 #endif
18128
18129 namespace Catch {
18130 XmlReporter::XmlReporter(ReporterConfig const &_config)
18131 : StreamingReporterBase(_config), m_xml(_config.stream())
18132 {
18133 m_reporterPrefs.shouldRedirectStdOut = true;
18134 m_reporterPrefs.shouldReportAllAssertions = true;
18135 }
18136
18137 XmlReporter::~XmlReporter() = default;
18138
18139 std::string XmlReporter::getDescription() { return "Reports test results as an XML document"; }
18140
18141 std::string XmlReporter::getStylesheetRef() const { return std::string(); }
18142
18143 void XmlReporter::writeSourceInfo(SourceLineInfo const &sourceInfo)
18144 {
18145 m_xml.writeAttribute("filename", sourceInfo.file).writeAttribute("line", sourceInfo.line);
18146 }
18147
18148 void XmlReporter::noMatchingTestCases(std::string const &s)
18149 {
18150 StreamingReporterBase::noMatchingTestCases(s);
18151 }
18152
18153 void XmlReporter::testRunStarting(TestRunInfo const &testInfo)
18154 {
18155 StreamingReporterBase::testRunStarting(testInfo);
18156 std::string stylesheetRef = getStylesheetRef();
18157 if (!stylesheetRef.empty())
18158 m_xml.writeStylesheetRef(stylesheetRef);
18159 m_xml.startElement("Catch");
18160 if (!m_config->name().empty())
18161 m_xml.writeAttribute("name", m_config->name());
18162 if (m_config->testSpec().hasFilters())
18163 m_xml.writeAttribute("filters", serializeFilters(m_config->getTestsOrTags()));
18164 if (m_config->rngSeed() != 0)
18165 m_xml.scopedElement("Randomness").writeAttribute("seed", m_config->rngSeed());
18166 }
18167
18168 void XmlReporter::testGroupStarting(GroupInfo const &groupInfo)
18169 {
18170 StreamingReporterBase::testGroupStarting(groupInfo);
18171 m_xml.startElement("Group").writeAttribute("name", groupInfo.name);
18172 }
18173
18174 void XmlReporter::testCaseStarting(TestCaseInfo const &testInfo)
18175 {
18176 StreamingReporterBase::testCaseStarting(testInfo);
18177 m_xml.startElement("TestCase")
18178 .writeAttribute("name", trim(testInfo.name))
18179 .writeAttribute("description", testInfo.description)
18180 .writeAttribute("tags", testInfo.tagsAsString());
18181
18182 writeSourceInfo(testInfo.lineInfo);
18183
18184 if (m_config->showDurations() == ShowDurations::Always)
18185 m_testCaseTimer.start();
18186 m_xml.ensureTagClosed();
18187 }
18188
18189 void XmlReporter::sectionStarting(SectionInfo const &sectionInfo)
18190 {
18191 StreamingReporterBase::sectionStarting(sectionInfo);
18192 if (m_sectionDepth++ > 0) {
18193 m_xml.startElement("Section").writeAttribute("name", trim(sectionInfo.name));
18194 writeSourceInfo(sectionInfo.lineInfo);
18195 m_xml.ensureTagClosed();
18196 }
18197 }
18198
18199 void XmlReporter::assertionStarting(AssertionInfo const &) {}
18200
18201 bool XmlReporter::assertionEnded(AssertionStats const &assertionStats)
18202 {
18203
18204 AssertionResult const &result = assertionStats.assertionResult;
18205
18206 bool includeResults = m_config->includeSuccessfulResults() || !result.isOk();
18207
18208 if (includeResults || result.getResultType() == ResultWas::Warning) {
18209 // Print any info messages in <Info> tags.
18210 for (auto const &msg : assertionStats.infoMessages) {
18211 if (msg.type == ResultWas::Info && includeResults) {
18212 m_xml.scopedElement("Info").writeText(msg.message);
18213 }
18214 else if (msg.type == ResultWas::Warning) {
18215 m_xml.scopedElement("Warning").writeText(msg.message);
18216 }
18217 }
18218 }
18219
18220 // Drop out if result was successful but we're not printing them.
18221 if (!includeResults && result.getResultType() != ResultWas::Warning)
18222 return true;
18223
18224 // Print the expression if there is one.
18225 if (result.hasExpression()) {
18226 m_xml.startElement("Expression")
18227 .writeAttribute("success", result.succeeded())
18228 .writeAttribute("type", result.getTestMacroName());
18229
18230 writeSourceInfo(result.getSourceInfo());
18231
18232 m_xml.scopedElement("Original").writeText(result.getExpression());
18233 m_xml.scopedElement("Expanded").writeText(result.getExpandedExpression());
18234 }
18235
18236 // And... Print a result applicable to each result type.
18237 switch (result.getResultType()) {
18238 case ResultWas::ThrewException:
18239 m_xml.startElement("Exception");
18240 writeSourceInfo(result.getSourceInfo());
18241 m_xml.writeText(result.getMessage());
18242 m_xml.endElement();
18243 break;
18244 case ResultWas::FatalErrorCondition:
18245 m_xml.startElement("FatalErrorCondition");
18246 writeSourceInfo(result.getSourceInfo());
18247 m_xml.writeText(result.getMessage());
18248 m_xml.endElement();
18249 break;
18250 case ResultWas::Info: m_xml.scopedElement("Info").writeText(result.getMessage()); break;
18251 case ResultWas::Warning:
18252 // Warning will already have been written
18253 break;
18254 case ResultWas::ExplicitFailure:
18255 m_xml.startElement("Failure");
18256 writeSourceInfo(result.getSourceInfo());
18257 m_xml.writeText(result.getMessage());
18258 m_xml.endElement();
18259 break;
18260 default: break;
18261 }
18262
18263 if (result.hasExpression())
18264 m_xml.endElement();
18265
18266 return true;
18267 }
18268
18269 void XmlReporter::sectionEnded(SectionStats const &sectionStats)
18270 {
18271 StreamingReporterBase::sectionEnded(sectionStats);
18272 if (--m_sectionDepth > 0) {
18273 XmlWriter::ScopedElement e = m_xml.scopedElement("OverallResults");
18274 e.writeAttribute("successes", sectionStats.assertions.passed);
18275 e.writeAttribute("failures", sectionStats.assertions.failed);
18276 e.writeAttribute("expectedFailures", sectionStats.assertions.failedButOk);
18277
18278 if (m_config->showDurations() == ShowDurations::Always)
18279 e.writeAttribute("durationInSeconds", sectionStats.durationInSeconds);
18280
18281 m_xml.endElement();
18282 }
18283 }
18284
18285 void XmlReporter::testCaseEnded(TestCaseStats const &testCaseStats)
18286 {
18287 StreamingReporterBase::testCaseEnded(testCaseStats);
18288 XmlWriter::ScopedElement e = m_xml.scopedElement("OverallResult");
18289 e.writeAttribute("success", testCaseStats.totals.assertions.allOk());
18290
18291 if (m_config->showDurations() == ShowDurations::Always)
18292 e.writeAttribute("durationInSeconds", m_testCaseTimer.getElapsedSeconds());
18293
18294 if (!testCaseStats.stdOut.empty())
18295 m_xml.scopedElement("StdOut").writeText(trim(testCaseStats.stdOut), XmlFormatting::Newline);
18296 if (!testCaseStats.stdErr.empty())
18297 m_xml.scopedElement("StdErr").writeText(trim(testCaseStats.stdErr), XmlFormatting::Newline);
18298
18299 m_xml.endElement();
18300 }
18301
18302 void XmlReporter::testGroupEnded(TestGroupStats const &testGroupStats)
18303 {
18304 StreamingReporterBase::testGroupEnded(testGroupStats);
18305 // TODO: Check testGroupStats.aborting and act accordingly.
18306 m_xml.scopedElement("OverallResults")
18307 .writeAttribute("successes", testGroupStats.totals.assertions.passed)
18308 .writeAttribute("failures", testGroupStats.totals.assertions.failed)
18309 .writeAttribute("expectedFailures", testGroupStats.totals.assertions.failedButOk);
18310 m_xml.scopedElement("OverallResultsCases")
18311 .writeAttribute("successes", testGroupStats.totals.testCases.passed)
18312 .writeAttribute("failures", testGroupStats.totals.testCases.failed)
18313 .writeAttribute("expectedFailures", testGroupStats.totals.testCases.failedButOk);
18314 m_xml.endElement();
18315 }
18316
18317 void XmlReporter::testRunEnded(TestRunStats const &testRunStats)
18318 {
18319 StreamingReporterBase::testRunEnded(testRunStats);
18320 m_xml.scopedElement("OverallResults")
18321 .writeAttribute("successes", testRunStats.totals.assertions.passed)
18322 .writeAttribute("failures", testRunStats.totals.assertions.failed)
18323 .writeAttribute("expectedFailures", testRunStats.totals.assertions.failedButOk);
18324 m_xml.scopedElement("OverallResultsCases")
18325 .writeAttribute("successes", testRunStats.totals.testCases.passed)
18326 .writeAttribute("failures", testRunStats.totals.testCases.failed)
18327 .writeAttribute("expectedFailures", testRunStats.totals.testCases.failedButOk);
18328 m_xml.endElement();
18329 }
18330
18331 #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
18332 void XmlReporter::benchmarkPreparing(std::string const &name)
18333 {
18334 m_xml.startElement("BenchmarkResults").writeAttribute("name", name);
18335 }
18336
18337 void XmlReporter::benchmarkStarting(BenchmarkInfo const &info)
18338 {
18339 m_xml.writeAttribute("samples", info.samples)
18340 .writeAttribute("resamples", info.resamples)
18341 .writeAttribute("iterations", info.iterations)
18342 .writeAttribute("clockResolution", info.clockResolution)
18343 .writeAttribute("estimatedDuration", info.estimatedDuration)
18344 .writeComment("All values in nano seconds");
18345 }
18346
18347 void XmlReporter::benchmarkEnded(BenchmarkStats<> const &benchmarkStats)
18348 {
18349 m_xml.startElement("mean")
18350 .writeAttribute("value", benchmarkStats.mean.point.count())
18351 .writeAttribute("lowerBound", benchmarkStats.mean.lower_bound.count())
18352 .writeAttribute("upperBound", benchmarkStats.mean.upper_bound.count())
18353 .writeAttribute("ci", benchmarkStats.mean.confidence_interval);
18354 m_xml.endElement();
18355 m_xml.startElement("standardDeviation")
18356 .writeAttribute("value", benchmarkStats.standardDeviation.point.count())
18357 .writeAttribute("lowerBound", benchmarkStats.standardDeviation.lower_bound.count())
18358 .writeAttribute("upperBound", benchmarkStats.standardDeviation.upper_bound.count())
18359 .writeAttribute("ci", benchmarkStats.standardDeviation.confidence_interval);
18360 m_xml.endElement();
18361 m_xml.startElement("outliers")
18362 .writeAttribute("variance", benchmarkStats.outlierVariance)
18363 .writeAttribute("lowMild", benchmarkStats.outliers.low_mild)
18364 .writeAttribute("lowSevere", benchmarkStats.outliers.low_severe)
18365 .writeAttribute("highMild", benchmarkStats.outliers.high_mild)
18366 .writeAttribute("highSevere", benchmarkStats.outliers.high_severe);
18367 m_xml.endElement();
18368 m_xml.endElement();
18369 }
18370
18371 void XmlReporter::benchmarkFailed(std::string const &error)
18372 {
18373 m_xml.scopedElement("failed").writeAttribute("message", error);
18374 m_xml.endElement();
18375 }
18376 #endif // CATCH_CONFIG_ENABLE_BENCHMARKING
18377
18378 CATCH_REGISTER_REPORTER("xml", XmlReporter)
18379
18380 } // end namespace Catch
18381
18382 #if defined(_MSC_VER)
18383 #pragma warning(pop)
18384 #endif
18385 // end catch_reporter_xml.cpp
18386
18387 namespace Catch {
18388 LeakDetector leakDetector;
18389 }
18390
18391 #ifdef __clang__
18392 #pragma clang diagnostic pop
18393 #endif
18394
18395 // end catch_impl.hpp
18396 #endif
18397
18398 #ifdef CATCH_CONFIG_MAIN
18399 // start catch_default_main.hpp
18400
18401 #ifndef __OBJC__
18402
18403 #if defined(CATCH_CONFIG_WCHAR) && defined(CATCH_PLATFORM_WINDOWS) && defined(_UNICODE) && \
18404 !defined(DO_NOT_USE_WMAIN)
18405 // Standard C/C++ Win32 Unicode wmain entry point
18406 extern "C" int wmain(int argc, wchar_t *argv[], wchar_t *[])
18407 {
18408 #else
18409 // Standard C/C++ main entry point
18410 int main(int argc, char *argv[])
18411 {
18412 #endif
18413
18414 return Catch::Session().run(argc, argv);
18415 }
18416
18417 #else // __OBJC__
18418
18419 // Objective-C entry point
18420 int main(int argc, char *const argv[])
18421 {
18422 #if !CATCH_ARC_ENABLED
18423 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
18424 #endif
18425
18426 Catch::registerTestMethods();
18427 int result = Catch::Session().run(argc, (char **)argv);
18428
18429 #if !CATCH_ARC_ENABLED
18430 [pool drain];
18431 #endif
18432
18433 return result;
18434 }
18435
18436 #endif // __OBJC__
18437
18438 // end catch_default_main.hpp
18439 #endif
18440
18441 #if !defined(CATCH_CONFIG_IMPL_ONLY)
18442
18443 #ifdef CLARA_CONFIG_MAIN_NOT_DEFINED
18444 #undef CLARA_CONFIG_MAIN
18445 #endif
18446
18447 #if !defined(CATCH_CONFIG_DISABLE)
18448 //////
18449 // If this config identifier is defined then all CATCH macros are prefixed with CATCH_
18450 #ifdef CATCH_CONFIG_PREFIX_ALL
18451
18452 #define CATCH_REQUIRE(...) \
18453 INTERNAL_CATCH_TEST("CATCH_REQUIRE", Catch::ResultDisposition::Normal, __VA_ARGS__)
18454 #define CATCH_REQUIRE_FALSE(...) \
18455 INTERNAL_CATCH_TEST("CATCH_REQUIRE_FALSE", \
18456 Catch::ResultDisposition::Normal | Catch::ResultDisposition::FalseTest, \
18457 __VA_ARGS__)
18458
18459 #define CATCH_REQUIRE_THROWS(...) \
18460 INTERNAL_CATCH_THROWS("CATCH_REQUIRE_THROWS", Catch::ResultDisposition::Normal, __VA_ARGS__)
18461 #define CATCH_REQUIRE_THROWS_AS(expr, exceptionType) \
18462 INTERNAL_CATCH_THROWS_AS("CATCH_REQUIRE_THROWS_AS", exceptionType, \
18463 Catch::ResultDisposition::Normal, expr)
18464 #define CATCH_REQUIRE_THROWS_WITH(expr, matcher) \
18465 INTERNAL_CATCH_THROWS_STR_MATCHES("CATCH_REQUIRE_THROWS_WITH", Catch::ResultDisposition::Normal, \
18466 matcher, expr)
18467 #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
18468 #define CATCH_REQUIRE_THROWS_MATCHES(expr, exceptionType, matcher) \
18469 INTERNAL_CATCH_THROWS_MATCHES("CATCH_REQUIRE_THROWS_MATCHES", exceptionType, \
18470 Catch::ResultDisposition::Normal, matcher, expr)
18471 #endif // CATCH_CONFIG_DISABLE_MATCHERS
18472 #define CATCH_REQUIRE_NOTHROW(...) \
18473 INTERNAL_CATCH_NO_THROW("CATCH_REQUIRE_NOTHROW", Catch::ResultDisposition::Normal, __VA_ARGS__)
18474
18475 #define CATCH_CHECK(...) \
18476 INTERNAL_CATCH_TEST("CATCH_CHECK", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__)
18477 #define CATCH_CHECK_FALSE(...) \
18478 INTERNAL_CATCH_TEST("CATCH_CHECK_FALSE", \
18479 Catch::ResultDisposition::ContinueOnFailure | \
18480 Catch::ResultDisposition::FalseTest, \
18481 __VA_ARGS__)
18482 #define CATCH_CHECKED_IF(...) \
18483 INTERNAL_CATCH_IF("CATCH_CHECKED_IF", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__)
18484 #define CATCH_CHECKED_ELSE(...) \
18485 INTERNAL_CATCH_ELSE("CATCH_CHECKED_ELSE", Catch::ResultDisposition::ContinueOnFailure, \
18486 __VA_ARGS__)
18487 #define CATCH_CHECK_NOFAIL(...) \
18488 INTERNAL_CATCH_TEST("CATCH_CHECK_NOFAIL", \
18489 Catch::ResultDisposition::ContinueOnFailure | \
18490 Catch::ResultDisposition::SuppressFail, \
18491 __VA_ARGS__)
18492
18493 #define CATCH_CHECK_THROWS(...) \
18494 INTERNAL_CATCH_THROWS("CATCH_CHECK_THROWS", Catch::ResultDisposition::ContinueOnFailure, \
18495 __VA_ARGS__)
18496 #define CATCH_CHECK_THROWS_AS(expr, exceptionType) \
18497 INTERNAL_CATCH_THROWS_AS("CATCH_CHECK_THROWS_AS", exceptionType, \
18498 Catch::ResultDisposition::ContinueOnFailure, expr)
18499 #define CATCH_CHECK_THROWS_WITH(expr, matcher) \
18500 INTERNAL_CATCH_THROWS_STR_MATCHES("CATCH_CHECK_THROWS_WITH", \
18501 Catch::ResultDisposition::ContinueOnFailure, matcher, expr)
18502 #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
18503 #define CATCH_CHECK_THROWS_MATCHES(expr, exceptionType, matcher) \
18504 INTERNAL_CATCH_THROWS_MATCHES("CATCH_CHECK_THROWS_MATCHES", exceptionType, \
18505 Catch::ResultDisposition::ContinueOnFailure, matcher, expr)
18506 #endif // CATCH_CONFIG_DISABLE_MATCHERS
18507 #define CATCH_CHECK_NOTHROW(...) \
18508 INTERNAL_CATCH_NO_THROW("CATCH_CHECK_NOTHROW", Catch::ResultDisposition::ContinueOnFailure, \
18509 __VA_ARGS__)
18510
18511 #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
18512 #define CATCH_CHECK_THAT(arg, matcher) \
18513 INTERNAL_CHECK_THAT("CATCH_CHECK_THAT", matcher, Catch::ResultDisposition::ContinueOnFailure, arg)
18514
18515 #define CATCH_REQUIRE_THAT(arg, matcher) \
18516 INTERNAL_CHECK_THAT("CATCH_REQUIRE_THAT", matcher, Catch::ResultDisposition::Normal, arg)
18517 #endif // CATCH_CONFIG_DISABLE_MATCHERS
18518
18519 #define CATCH_INFO(msg) INTERNAL_CATCH_INFO("CATCH_INFO", msg)
18520 #define CATCH_UNSCOPED_INFO(msg) INTERNAL_CATCH_UNSCOPED_INFO("CATCH_UNSCOPED_INFO", msg)
18521 #define CATCH_WARN(msg) \
18522 INTERNAL_CATCH_MSG("CATCH_WARN", Catch::ResultWas::Warning, \
18523 Catch::ResultDisposition::ContinueOnFailure, msg)
18524 #define CATCH_CAPTURE(...) \
18525 INTERNAL_CATCH_CAPTURE(INTERNAL_CATCH_UNIQUE_NAME(capturer), "CATCH_CAPTURE", __VA_ARGS__)
18526
18527 #define CATCH_TEST_CASE(...) INTERNAL_CATCH_TESTCASE(__VA_ARGS__)
18528 #define CATCH_TEST_CASE_METHOD(className, ...) \
18529 INTERNAL_CATCH_TEST_CASE_METHOD(className, __VA_ARGS__)
18530 #define CATCH_METHOD_AS_TEST_CASE(method, ...) \
18531 INTERNAL_CATCH_METHOD_AS_TEST_CASE(method, __VA_ARGS__)
18532 #define CATCH_REGISTER_TEST_CASE(Function, ...) \
18533 INTERNAL_CATCH_REGISTER_TESTCASE(Function, __VA_ARGS__)
18534 #define CATCH_SECTION(...) INTERNAL_CATCH_SECTION(__VA_ARGS__)
18535 #define CATCH_DYNAMIC_SECTION(...) INTERNAL_CATCH_DYNAMIC_SECTION(__VA_ARGS__)
18536 #define CATCH_FAIL(...) \
18537 INTERNAL_CATCH_MSG("CATCH_FAIL", Catch::ResultWas::ExplicitFailure, \
18538 Catch::ResultDisposition::Normal, __VA_ARGS__)
18539 #define CATCH_FAIL_CHECK(...) \
18540 INTERNAL_CATCH_MSG("CATCH_FAIL_CHECK", Catch::ResultWas::ExplicitFailure, \
18541 Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__)
18542 #define CATCH_SUCCEED(...) \
18543 INTERNAL_CATCH_MSG("CATCH_SUCCEED", Catch::ResultWas::Ok, \
18544 Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__)
18545
18546 #define CATCH_ANON_TEST_CASE() INTERNAL_CATCH_TESTCASE()
18547
18548 #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
18549 #define CATCH_TEMPLATE_TEST_CASE(...) INTERNAL_CATCH_TEMPLATE_TEST_CASE(__VA_ARGS__)
18550 #define CATCH_TEMPLATE_TEST_CASE_SIG(...) INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG(__VA_ARGS__)
18551 #define CATCH_TEMPLATE_TEST_CASE_METHOD(className, ...) \
18552 INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD(className, __VA_ARGS__)
18553 #define CATCH_TEMPLATE_TEST_CASE_METHOD_SIG(className, ...) \
18554 INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG(className, __VA_ARGS__)
18555 #define CATCH_TEMPLATE_PRODUCT_TEST_CASE(...) INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE(__VA_ARGS__)
18556 #define CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG(...) \
18557 INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG(__VA_ARGS__)
18558 #define CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD(className, ...) \
18559 INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD(className, __VA_ARGS__)
18560 #define CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG(className, ...) \
18561 INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG(className, __VA_ARGS__)
18562 #else
18563 #define CATCH_TEMPLATE_TEST_CASE(...) \
18564 INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_TEMPLATE_TEST_CASE(__VA_ARGS__))
18565 #define CATCH_TEMPLATE_TEST_CASE_SIG(...) \
18566 INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG(__VA_ARGS__))
18567 #define CATCH_TEMPLATE_TEST_CASE_METHOD(className, ...) \
18568 INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD(className, __VA_ARGS__))
18569 #define CATCH_TEMPLATE_TEST_CASE_METHOD_SIG(className, ...) \
18570 INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG(className, __VA_ARGS__))
18571 #define CATCH_TEMPLATE_PRODUCT_TEST_CASE(...) \
18572 INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE(__VA_ARGS__))
18573 #define CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG(...) \
18574 INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG(__VA_ARGS__))
18575 #define CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD(className, ...) \
18576 INTERNAL_CATCH_EXPAND_VARGS( \
18577 INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD(className, __VA_ARGS__))
18578 #define CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG(className, ...) \
18579 INTERNAL_CATCH_EXPAND_VARGS( \
18580 INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG(className, __VA_ARGS__))
18581 #endif
18582
18583 #if !defined(CATCH_CONFIG_RUNTIME_STATIC_REQUIRE)
18584 #define CATCH_STATIC_REQUIRE(...) \
18585 static_assert(__VA_ARGS__, #__VA_ARGS__); \
18586 CATCH_SUCCEED(#__VA_ARGS__)
18587 #define CATCH_STATIC_REQUIRE_FALSE(...) \
18588 static_assert(!(__VA_ARGS__), "!(" #__VA_ARGS__ ")"); \
18589 CATCH_SUCCEED(#__VA_ARGS__)
18590 #else
18591 #define CATCH_STATIC_REQUIRE(...) CATCH_REQUIRE(__VA_ARGS__)
18592 #define CATCH_STATIC_REQUIRE_FALSE(...) CATCH_REQUIRE_FALSE(__VA_ARGS__)
18593 #endif
18594
18595 // "BDD-style" convenience wrappers
18596 #define CATCH_SCENARIO(...) CATCH_TEST_CASE("Scenario: " __VA_ARGS__)
18597 #define CATCH_SCENARIO_METHOD(className, ...) \
18598 INTERNAL_CATCH_TEST_CASE_METHOD(className, "Scenario: " __VA_ARGS__)
18599 #define CATCH_GIVEN(desc) INTERNAL_CATCH_DYNAMIC_SECTION(" Given: " << desc)
18600 #define CATCH_AND_GIVEN(desc) INTERNAL_CATCH_DYNAMIC_SECTION("And given: " << desc)
18601 #define CATCH_WHEN(desc) INTERNAL_CATCH_DYNAMIC_SECTION(" When: " << desc)
18602 #define CATCH_AND_WHEN(desc) INTERNAL_CATCH_DYNAMIC_SECTION(" And when: " << desc)
18603 #define CATCH_THEN(desc) INTERNAL_CATCH_DYNAMIC_SECTION(" Then: " << desc)
18604 #define CATCH_AND_THEN(desc) INTERNAL_CATCH_DYNAMIC_SECTION(" And: " << desc)
18605
18606 #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
18607 #define CATCH_BENCHMARK(...) \
18608 INTERNAL_CATCH_BENCHMARK(INTERNAL_CATCH_UNIQUE_NAME(____C_A_T_C_H____B_E_N_C_H____), \
18609 INTERNAL_CATCH_GET_1_ARG(__VA_ARGS__, , ), \
18610 INTERNAL_CATCH_GET_2_ARG(__VA_ARGS__, , ))
18611 #define CATCH_BENCHMARK_ADVANCED(name) \
18612 INTERNAL_CATCH_BENCHMARK_ADVANCED(INTERNAL_CATCH_UNIQUE_NAME(____C_A_T_C_H____B_E_N_C_H____), \
18613 name)
18614 #endif // CATCH_CONFIG_ENABLE_BENCHMARKING
18615
18616 // If CATCH_CONFIG_PREFIX_ALL is not defined then the CATCH_ prefix is not required
18617 #else
18618
18619 #define REQUIRE(...) INTERNAL_CATCH_TEST("REQUIRE", Catch::ResultDisposition::Normal, __VA_ARGS__)
18620 #define REQUIRE_FALSE(...) \
18621 INTERNAL_CATCH_TEST("REQUIRE_FALSE", \
18622 Catch::ResultDisposition::Normal | Catch::ResultDisposition::FalseTest, \
18623 __VA_ARGS__)
18624
18625 #define REQUIRE_THROWS(...) \
18626 INTERNAL_CATCH_THROWS("REQUIRE_THROWS", Catch::ResultDisposition::Normal, __VA_ARGS__)
18627 #define REQUIRE_THROWS_AS(expr, exceptionType) \
18628 INTERNAL_CATCH_THROWS_AS("REQUIRE_THROWS_AS", exceptionType, Catch::ResultDisposition::Normal, \
18629 expr)
18630 #define REQUIRE_THROWS_WITH(expr, matcher) \
18631 INTERNAL_CATCH_THROWS_STR_MATCHES("REQUIRE_THROWS_WITH", Catch::ResultDisposition::Normal, \
18632 matcher, expr)
18633 #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
18634 #define REQUIRE_THROWS_MATCHES(expr, exceptionType, matcher) \
18635 INTERNAL_CATCH_THROWS_MATCHES("REQUIRE_THROWS_MATCHES", exceptionType, \
18636 Catch::ResultDisposition::Normal, matcher, expr)
18637 #endif // CATCH_CONFIG_DISABLE_MATCHERS
18638 #define REQUIRE_NOTHROW(...) \
18639 INTERNAL_CATCH_NO_THROW("REQUIRE_NOTHROW", Catch::ResultDisposition::Normal, __VA_ARGS__)
18640
18641 #define CHECK(...) \
18642 INTERNAL_CATCH_TEST("CHECK", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__)
18643 #define CHECK_FALSE(...) \
18644 INTERNAL_CATCH_TEST("CHECK_FALSE", \
18645 Catch::ResultDisposition::ContinueOnFailure | \
18646 Catch::ResultDisposition::FalseTest, \
18647 __VA_ARGS__)
18648 #define CHECKED_IF(...) \
18649 INTERNAL_CATCH_IF("CHECKED_IF", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__)
18650 #define CHECKED_ELSE(...) \
18651 INTERNAL_CATCH_ELSE("CHECKED_ELSE", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__)
18652 #define CHECK_NOFAIL(...) \
18653 INTERNAL_CATCH_TEST("CHECK_NOFAIL", \
18654 Catch::ResultDisposition::ContinueOnFailure | \
18655 Catch::ResultDisposition::SuppressFail, \
18656 __VA_ARGS__)
18657
18658 #define CHECK_THROWS(...) \
18659 INTERNAL_CATCH_THROWS("CHECK_THROWS", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__)
18660 #define CHECK_THROWS_AS(expr, exceptionType) \
18661 INTERNAL_CATCH_THROWS_AS("CHECK_THROWS_AS", exceptionType, \
18662 Catch::ResultDisposition::ContinueOnFailure, expr)
18663 #define CHECK_THROWS_WITH(expr, matcher) \
18664 INTERNAL_CATCH_THROWS_STR_MATCHES("CHECK_THROWS_WITH", \
18665 Catch::ResultDisposition::ContinueOnFailure, matcher, expr)
18666 #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
18667 #define CHECK_THROWS_MATCHES(expr, exceptionType, matcher) \
18668 INTERNAL_CATCH_THROWS_MATCHES("CHECK_THROWS_MATCHES", exceptionType, \
18669 Catch::ResultDisposition::ContinueOnFailure, matcher, expr)
18670 #endif // CATCH_CONFIG_DISABLE_MATCHERS
18671 #define CHECK_NOTHROW(...) \
18672 INTERNAL_CATCH_NO_THROW("CHECK_NOTHROW", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__)
18673
18674 #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
18675 #define CHECK_THAT(arg, matcher) \
18676 INTERNAL_CHECK_THAT("CHECK_THAT", matcher, Catch::ResultDisposition::ContinueOnFailure, arg)
18677
18678 #define REQUIRE_THAT(arg, matcher) \
18679 INTERNAL_CHECK_THAT("REQUIRE_THAT", matcher, Catch::ResultDisposition::Normal, arg)
18680 #endif // CATCH_CONFIG_DISABLE_MATCHERS
18681
18682 #define INFO(msg) INTERNAL_CATCH_INFO("INFO", msg)
18683 #define UNSCOPED_INFO(msg) INTERNAL_CATCH_UNSCOPED_INFO("UNSCOPED_INFO", msg)
18684 #define WARN(msg) \
18685 INTERNAL_CATCH_MSG("WARN", Catch::ResultWas::Warning, \
18686 Catch::ResultDisposition::ContinueOnFailure, msg)
18687 #define CAPTURE(...) \
18688 INTERNAL_CATCH_CAPTURE(INTERNAL_CATCH_UNIQUE_NAME(capturer), "CAPTURE", __VA_ARGS__)
18689
18690 #define TEST_CASE(...) INTERNAL_CATCH_TESTCASE(__VA_ARGS__)
18691 #define TEST_CASE_METHOD(className, ...) INTERNAL_CATCH_TEST_CASE_METHOD(className, __VA_ARGS__)
18692 #define METHOD_AS_TEST_CASE(method, ...) INTERNAL_CATCH_METHOD_AS_TEST_CASE(method, __VA_ARGS__)
18693 #define REGISTER_TEST_CASE(Function, ...) INTERNAL_CATCH_REGISTER_TESTCASE(Function, __VA_ARGS__)
18694 #define SECTION(...) INTERNAL_CATCH_SECTION(__VA_ARGS__)
18695 #define DYNAMIC_SECTION(...) INTERNAL_CATCH_DYNAMIC_SECTION(__VA_ARGS__)
18696 #define FAIL(...) \
18697 INTERNAL_CATCH_MSG("FAIL", Catch::ResultWas::ExplicitFailure, Catch::ResultDisposition::Normal, \
18698 __VA_ARGS__)
18699 #define FAIL_CHECK(...) \
18700 INTERNAL_CATCH_MSG("FAIL_CHECK", Catch::ResultWas::ExplicitFailure, \
18701 Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__)
18702 #define SUCCEED(...) \
18703 INTERNAL_CATCH_MSG("SUCCEED", Catch::ResultWas::Ok, Catch::ResultDisposition::ContinueOnFailure, \
18704 __VA_ARGS__)
18705 #define ANON_TEST_CASE() INTERNAL_CATCH_TESTCASE()
18706
18707 #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
18708 #define TEMPLATE_TEST_CASE(...) INTERNAL_CATCH_TEMPLATE_TEST_CASE(__VA_ARGS__)
18709 #define TEMPLATE_TEST_CASE_SIG(...) INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG(__VA_ARGS__)
18710 #define TEMPLATE_TEST_CASE_METHOD(className, ...) \
18711 INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD(className, __VA_ARGS__)
18712 #define TEMPLATE_TEST_CASE_METHOD_SIG(className, ...) \
18713 INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG(className, __VA_ARGS__)
18714 #define TEMPLATE_PRODUCT_TEST_CASE(...) INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE(__VA_ARGS__)
18715 #define TEMPLATE_PRODUCT_TEST_CASE_SIG(...) \
18716 INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG(__VA_ARGS__)
18717 #define TEMPLATE_PRODUCT_TEST_CASE_METHOD(className, ...) \
18718 INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD(className, __VA_ARGS__)
18719 #define TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG(className, ...) \
18720 INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG(className, __VA_ARGS__)
18721 #define TEMPLATE_LIST_TEST_CASE(...) INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE(__VA_ARGS__)
18722 #define TEMPLATE_LIST_TEST_CASE_METHOD(className, ...) \
18723 INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE_METHOD(className, __VA_ARGS__)
18724 #else
18725 #define TEMPLATE_TEST_CASE(...) \
18726 INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_TEMPLATE_TEST_CASE(__VA_ARGS__))
18727 #define TEMPLATE_TEST_CASE_SIG(...) \
18728 INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG(__VA_ARGS__))
18729 #define TEMPLATE_TEST_CASE_METHOD(className, ...) \
18730 INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD(className, __VA_ARGS__))
18731 #define TEMPLATE_TEST_CASE_METHOD_SIG(className, ...) \
18732 INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG(className, __VA_ARGS__))
18733 #define TEMPLATE_PRODUCT_TEST_CASE(...) \
18734 INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE(__VA_ARGS__))
18735 #define TEMPLATE_PRODUCT_TEST_CASE_SIG(...) \
18736 INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG(__VA_ARGS__))
18737 #define TEMPLATE_PRODUCT_TEST_CASE_METHOD(className, ...) \
18738 INTERNAL_CATCH_EXPAND_VARGS( \
18739 INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD(className, __VA_ARGS__))
18740 #define TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG(className, ...) \
18741 INTERNAL_CATCH_EXPAND_VARGS( \
18742 INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG(className, __VA_ARGS__))
18743 #define TEMPLATE_LIST_TEST_CASE(...) \
18744 INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE(__VA_ARGS__))
18745 #define TEMPLATE_LIST_TEST_CASE_METHOD(className, ...) \
18746 INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE_METHOD(className, __VA_ARGS__))
18747 #endif
18748
18749 #if !defined(CATCH_CONFIG_RUNTIME_STATIC_REQUIRE)
18750 #define STATIC_REQUIRE(...) \
18751 static_assert(__VA_ARGS__, #__VA_ARGS__); \
18752 SUCCEED(#__VA_ARGS__)
18753 #define STATIC_REQUIRE_FALSE(...) \
18754 static_assert(!(__VA_ARGS__), "!(" #__VA_ARGS__ ")"); \
18755 SUCCEED("!(" #__VA_ARGS__ ")")
18756 #else
18757 #define STATIC_REQUIRE(...) REQUIRE(__VA_ARGS__)
18758 #define STATIC_REQUIRE_FALSE(...) REQUIRE_FALSE(__VA_ARGS__)
18759 #endif
18760
18761 #endif
18762
18763 #define CATCH_TRANSLATE_EXCEPTION(signature) INTERNAL_CATCH_TRANSLATE_EXCEPTION(signature)
18764
18765 // "BDD-style" convenience wrappers
18766 #define SCENARIO(...) TEST_CASE("Scenario: " __VA_ARGS__)
18767 #define SCENARIO_METHOD(className, ...) \
18768 INTERNAL_CATCH_TEST_CASE_METHOD(className, "Scenario: " __VA_ARGS__)
18769
18770 #define GIVEN(desc) INTERNAL_CATCH_DYNAMIC_SECTION(" Given: " << desc)
18771 #define AND_GIVEN(desc) INTERNAL_CATCH_DYNAMIC_SECTION("And given: " << desc)
18772 #define WHEN(desc) INTERNAL_CATCH_DYNAMIC_SECTION(" When: " << desc)
18773 #define AND_WHEN(desc) INTERNAL_CATCH_DYNAMIC_SECTION(" And when: " << desc)
18774 #define THEN(desc) INTERNAL_CATCH_DYNAMIC_SECTION(" Then: " << desc)
18775 #define AND_THEN(desc) INTERNAL_CATCH_DYNAMIC_SECTION(" And: " << desc)
18776
18777 #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
18778 #define BENCHMARK(...) \
18779 INTERNAL_CATCH_BENCHMARK(INTERNAL_CATCH_UNIQUE_NAME(____C_A_T_C_H____B_E_N_C_H____), \
18780 INTERNAL_CATCH_GET_1_ARG(__VA_ARGS__, , ), \
18781 INTERNAL_CATCH_GET_2_ARG(__VA_ARGS__, , ))
18782 #define BENCHMARK_ADVANCED(name) \
18783 INTERNAL_CATCH_BENCHMARK_ADVANCED(INTERNAL_CATCH_UNIQUE_NAME(____C_A_T_C_H____B_E_N_C_H____), \
18784 name)
18785 #endif // CATCH_CONFIG_ENABLE_BENCHMARKING
18786
18787 using Catch::Detail::Approx;
18788
18789 #else // CATCH_CONFIG_DISABLE
18790
18791 //////
18792 // If this config identifier is defined then all CATCH macros are prefixed with CATCH_
18793 #ifdef CATCH_CONFIG_PREFIX_ALL
18794
18795 #define CATCH_REQUIRE(...) (void)(0)
18796 #define CATCH_REQUIRE_FALSE(...) (void)(0)
18797
18798 #define CATCH_REQUIRE_THROWS(...) (void)(0)
18799 #define CATCH_REQUIRE_THROWS_AS(expr, exceptionType) (void)(0)
18800 #define CATCH_REQUIRE_THROWS_WITH(expr, matcher) (void)(0)
18801 #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
18802 #define CATCH_REQUIRE_THROWS_MATCHES(expr, exceptionType, matcher) (void)(0)
18803 #endif // CATCH_CONFIG_DISABLE_MATCHERS
18804 #define CATCH_REQUIRE_NOTHROW(...) (void)(0)
18805
18806 #define CATCH_CHECK(...) (void)(0)
18807 #define CATCH_CHECK_FALSE(...) (void)(0)
18808 #define CATCH_CHECKED_IF(...) if (__VA_ARGS__)
18809 #define CATCH_CHECKED_ELSE(...) if (!(__VA_ARGS__))
18810 #define CATCH_CHECK_NOFAIL(...) (void)(0)
18811
18812 #define CATCH_CHECK_THROWS(...) (void)(0)
18813 #define CATCH_CHECK_THROWS_AS(expr, exceptionType) (void)(0)
18814 #define CATCH_CHECK_THROWS_WITH(expr, matcher) (void)(0)
18815 #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
18816 #define CATCH_CHECK_THROWS_MATCHES(expr, exceptionType, matcher) (void)(0)
18817 #endif // CATCH_CONFIG_DISABLE_MATCHERS
18818 #define CATCH_CHECK_NOTHROW(...) (void)(0)
18819
18820 #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
18821 #define CATCH_CHECK_THAT(arg, matcher) (void)(0)
18822
18823 #define CATCH_REQUIRE_THAT(arg, matcher) (void)(0)
18824 #endif // CATCH_CONFIG_DISABLE_MATCHERS
18825
18826 #define CATCH_INFO(msg) (void)(0)
18827 #define CATCH_UNSCOPED_INFO(msg) (void)(0)
18828 #define CATCH_WARN(msg) (void)(0)
18829 #define CATCH_CAPTURE(msg) (void)(0)
18830
18831 #define CATCH_TEST_CASE(...) \
18832 INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME(____C_A_T_C_H____T_E_S_T____))
18833 #define CATCH_TEST_CASE_METHOD(className, ...) \
18834 INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME(____C_A_T_C_H____T_E_S_T____))
18835 #define CATCH_METHOD_AS_TEST_CASE(method, ...)
18836 #define CATCH_REGISTER_TEST_CASE(Function, ...) (void)(0)
18837 #define CATCH_SECTION(...)
18838 #define CATCH_DYNAMIC_SECTION(...)
18839 #define CATCH_FAIL(...) (void)(0)
18840 #define CATCH_FAIL_CHECK(...) (void)(0)
18841 #define CATCH_SUCCEED(...) (void)(0)
18842
18843 #define CATCH_ANON_TEST_CASE() \
18844 INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME(____C_A_T_C_H____T_E_S_T____))
18845
18846 #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
18847 #define CATCH_TEMPLATE_TEST_CASE(...) INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION(__VA_ARGS__)
18848 #define CATCH_TEMPLATE_TEST_CASE_SIG(...) \
18849 INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG_NO_REGISTRATION(__VA_ARGS__)
18850 #define CATCH_TEMPLATE_TEST_CASE_METHOD(className, ...) \
18851 INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION(className, __VA_ARGS__)
18852 #define CATCH_TEMPLATE_TEST_CASE_METHOD_SIG(className, ...) \
18853 INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG_NO_REGISTRATION(className, __VA_ARGS__)
18854 #define CATCH_TEMPLATE_PRODUCT_TEST_CASE(...) CATCH_TEMPLATE_TEST_CASE(__VA_ARGS__)
18855 #define CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG(...) CATCH_TEMPLATE_TEST_CASE(__VA_ARGS__)
18856 #define CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD(className, ...) \
18857 CATCH_TEMPLATE_TEST_CASE_METHOD(className, __VA_ARGS__)
18858 #define CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG(className, ...) \
18859 CATCH_TEMPLATE_TEST_CASE_METHOD(className, __VA_ARGS__)
18860 #else
18861 #define CATCH_TEMPLATE_TEST_CASE(...) \
18862 INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION(__VA_ARGS__))
18863 #define CATCH_TEMPLATE_TEST_CASE_SIG(...) \
18864 INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG_NO_REGISTRATION(__VA_ARGS__))
18865 #define CATCH_TEMPLATE_TEST_CASE_METHOD(className, ...) \
18866 INTERNAL_CATCH_EXPAND_VARGS( \
18867 INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION(className, __VA_ARGS__))
18868 #define CATCH_TEMPLATE_TEST_CASE_METHOD_SIG(className, ...) \
18869 INTERNAL_CATCH_EXPAND_VARGS( \
18870 INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG_NO_REGISTRATION(className, __VA_ARGS__))
18871 #define CATCH_TEMPLATE_PRODUCT_TEST_CASE(...) CATCH_TEMPLATE_TEST_CASE(__VA_ARGS__)
18872 #define CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG(...) CATCH_TEMPLATE_TEST_CASE(__VA_ARGS__)
18873 #define CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD(className, ...) \
18874 CATCH_TEMPLATE_TEST_CASE_METHOD(className, __VA_ARGS__)
18875 #define CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG(className, ...) \
18876 CATCH_TEMPLATE_TEST_CASE_METHOD(className, __VA_ARGS__)
18877 #endif
18878
18879 // "BDD-style" convenience wrappers
18880 #define CATCH_SCENARIO(...) \
18881 INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME(____C_A_T_C_H____T_E_S_T____))
18882 #define CATCH_SCENARIO_METHOD(className, ...) \
18883 INTERNAL_CATCH_TESTCASE_METHOD_NO_REGISTRATION( \
18884 INTERNAL_CATCH_UNIQUE_NAME(____C_A_T_C_H____T_E_S_T____), className)
18885 #define CATCH_GIVEN(desc)
18886 #define CATCH_AND_GIVEN(desc)
18887 #define CATCH_WHEN(desc)
18888 #define CATCH_AND_WHEN(desc)
18889 #define CATCH_THEN(desc)
18890 #define CATCH_AND_THEN(desc)
18891
18892 #define CATCH_STATIC_REQUIRE(...) (void)(0)
18893 #define CATCH_STATIC_REQUIRE_FALSE(...) (void)(0)
18894
18895 // If CATCH_CONFIG_PREFIX_ALL is not defined then the CATCH_ prefix is not required
18896 #else
18897
18898 #define REQUIRE(...) (void)(0)
18899 #define REQUIRE_FALSE(...) (void)(0)
18900
18901 #define REQUIRE_THROWS(...) (void)(0)
18902 #define REQUIRE_THROWS_AS(expr, exceptionType) (void)(0)
18903 #define REQUIRE_THROWS_WITH(expr, matcher) (void)(0)
18904 #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
18905 #define REQUIRE_THROWS_MATCHES(expr, exceptionType, matcher) (void)(0)
18906 #endif // CATCH_CONFIG_DISABLE_MATCHERS
18907 #define REQUIRE_NOTHROW(...) (void)(0)
18908
18909 #define CHECK(...) (void)(0)
18910 #define CHECK_FALSE(...) (void)(0)
18911 #define CHECKED_IF(...) if (__VA_ARGS__)
18912 #define CHECKED_ELSE(...) if (!(__VA_ARGS__))
18913 #define CHECK_NOFAIL(...) (void)(0)
18914
18915 #define CHECK_THROWS(...) (void)(0)
18916 #define CHECK_THROWS_AS(expr, exceptionType) (void)(0)
18917 #define CHECK_THROWS_WITH(expr, matcher) (void)(0)
18918 #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
18919 #define CHECK_THROWS_MATCHES(expr, exceptionType, matcher) (void)(0)
18920 #endif // CATCH_CONFIG_DISABLE_MATCHERS
18921 #define CHECK_NOTHROW(...) (void)(0)
18922
18923 #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
18924 #define CHECK_THAT(arg, matcher) (void)(0)
18925
18926 #define REQUIRE_THAT(arg, matcher) (void)(0)
18927 #endif // CATCH_CONFIG_DISABLE_MATCHERS
18928
18929 #define INFO(msg) (void)(0)
18930 #define UNSCOPED_INFO(msg) (void)(0)
18931 #define WARN(msg) (void)(0)
18932 #define CAPTURE(msg) (void)(0)
18933
18934 #define TEST_CASE(...) \
18935 INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME(____C_A_T_C_H____T_E_S_T____))
18936 #define TEST_CASE_METHOD(className, ...) \
18937 INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME(____C_A_T_C_H____T_E_S_T____))
18938 #define METHOD_AS_TEST_CASE(method, ...)
18939 #define REGISTER_TEST_CASE(Function, ...) (void)(0)
18940 #define SECTION(...)
18941 #define DYNAMIC_SECTION(...)
18942 #define FAIL(...) (void)(0)
18943 #define FAIL_CHECK(...) (void)(0)
18944 #define SUCCEED(...) (void)(0)
18945 #define ANON_TEST_CASE() \
18946 INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME(____C_A_T_C_H____T_E_S_T____))
18947
18948 #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
18949 #define TEMPLATE_TEST_CASE(...) INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION(__VA_ARGS__)
18950 #define TEMPLATE_TEST_CASE_SIG(...) \
18951 INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG_NO_REGISTRATION(__VA_ARGS__)
18952 #define TEMPLATE_TEST_CASE_METHOD(className, ...) \
18953 INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION(className, __VA_ARGS__)
18954 #define TEMPLATE_TEST_CASE_METHOD_SIG(className, ...) \
18955 INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG_NO_REGISTRATION(className, __VA_ARGS__)
18956 #define TEMPLATE_PRODUCT_TEST_CASE(...) TEMPLATE_TEST_CASE(__VA_ARGS__)
18957 #define TEMPLATE_PRODUCT_TEST_CASE_SIG(...) TEMPLATE_TEST_CASE(__VA_ARGS__)
18958 #define TEMPLATE_PRODUCT_TEST_CASE_METHOD(className, ...) \
18959 TEMPLATE_TEST_CASE_METHOD(className, __VA_ARGS__)
18960 #define TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG(className, ...) \
18961 TEMPLATE_TEST_CASE_METHOD(className, __VA_ARGS__)
18962 #else
18963 #define TEMPLATE_TEST_CASE(...) \
18964 INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION(__VA_ARGS__))
18965 #define TEMPLATE_TEST_CASE_SIG(...) \
18966 INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG_NO_REGISTRATION(__VA_ARGS__))
18967 #define TEMPLATE_TEST_CASE_METHOD(className, ...) \
18968 INTERNAL_CATCH_EXPAND_VARGS( \
18969 INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION(className, __VA_ARGS__))
18970 #define TEMPLATE_TEST_CASE_METHOD_SIG(className, ...) \
18971 INTERNAL_CATCH_EXPAND_VARGS( \
18972 INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG_NO_REGISTRATION(className, __VA_ARGS__))
18973 #define TEMPLATE_PRODUCT_TEST_CASE(...) TEMPLATE_TEST_CASE(__VA_ARGS__)
18974 #define TEMPLATE_PRODUCT_TEST_CASE_SIG(...) TEMPLATE_TEST_CASE(__VA_ARGS__)
18975 #define TEMPLATE_PRODUCT_TEST_CASE_METHOD(className, ...) \
18976 TEMPLATE_TEST_CASE_METHOD(className, __VA_ARGS__)
18977 #define TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG(className, ...) \
18978 TEMPLATE_TEST_CASE_METHOD(className, __VA_ARGS__)
18979 #endif
18980
18981 #define STATIC_REQUIRE(...) (void)(0)
18982 #define STATIC_REQUIRE_FALSE(...) (void)(0)
18983
18984 #endif
18985
18986 #define CATCH_TRANSLATE_EXCEPTION(signature) \
18987 INTERNAL_CATCH_TRANSLATE_EXCEPTION_NO_REG( \
18988 INTERNAL_CATCH_UNIQUE_NAME(catch_internal_ExceptionTranslator), signature)
18989
18990 // "BDD-style" convenience wrappers
18991 #define SCENARIO(...) \
18992 INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME(____C_A_T_C_H____T_E_S_T____))
18993 #define SCENARIO_METHOD(className, ...) \
18994 INTERNAL_CATCH_TESTCASE_METHOD_NO_REGISTRATION( \
18995 INTERNAL_CATCH_UNIQUE_NAME(____C_A_T_C_H____T_E_S_T____), className)
18996
18997 #define GIVEN(desc)
18998 #define AND_GIVEN(desc)
18999 #define WHEN(desc)
19000 #define AND_WHEN(desc)
19001 #define THEN(desc)
19002 #define AND_THEN(desc)
19003
19004 using Catch::Detail::Approx;
19005
19006 #endif
19007
19008 #endif // ! CATCH_CONFIG_IMPL_ONLY
19009
19010 // start catch_reenable_warnings.h
19011
19012 #ifdef __clang__
19013 #ifdef __ICC // icpc defines the __clang__ macro
19014 #pragma warning(pop)
19015 #else
19016 #pragma clang diagnostic pop
19017 #endif
19018 #elif defined __GNUC__
19019 #pragma GCC diagnostic pop
19020 #endif
19021
19022 // end catch_reenable_warnings.h
19023 // end catch.hpp
19024 #endif // TWOBLUECUBES_SINGLE_INCLUDE_CATCH_HPP_INCLUDED