enum_name
Loading...
Searching...
No Matches
doctest.cpp
1#if defined(DOCTEST_CONFIG_IMPLEMENT) || !defined(DOCTEST_SINGLE_HEADER)
2
3#ifndef DOCTEST_SINGLE_HEADER
4#include "doctest_fwd.h"
5#endif // DOCTEST_SINGLE_HEADER
6
7DOCTEST_CLANG_SUPPRESS_WARNING_WITH_PUSH("-Wunused-macros")
8
9#ifndef DOCTEST_LIBRARY_IMPLEMENTATION
10#define DOCTEST_LIBRARY_IMPLEMENTATION
11
12DOCTEST_CLANG_SUPPRESS_WARNING_POP
13
14DOCTEST_SUPPRESS_COMMON_WARNINGS_PUSH
15
16DOCTEST_CLANG_SUPPRESS_WARNING_PUSH
17DOCTEST_CLANG_SUPPRESS_WARNING("-Wglobal-constructors")
18DOCTEST_CLANG_SUPPRESS_WARNING("-Wexit-time-destructors")
19DOCTEST_CLANG_SUPPRESS_WARNING("-Wsign-conversion")
20DOCTEST_CLANG_SUPPRESS_WARNING("-Wshorten-64-to-32")
21DOCTEST_CLANG_SUPPRESS_WARNING("-Wmissing-variable-declarations")
22DOCTEST_CLANG_SUPPRESS_WARNING("-Wswitch")
23DOCTEST_CLANG_SUPPRESS_WARNING("-Wswitch-enum")
24DOCTEST_CLANG_SUPPRESS_WARNING("-Wcovered-switch-default")
25DOCTEST_CLANG_SUPPRESS_WARNING("-Wmissing-noreturn")
26DOCTEST_CLANG_SUPPRESS_WARNING("-Wdisabled-macro-expansion")
27DOCTEST_CLANG_SUPPRESS_WARNING("-Wmissing-braces")
28DOCTEST_CLANG_SUPPRESS_WARNING("-Wmissing-field-initializers")
29DOCTEST_CLANG_SUPPRESS_WARNING("-Wunused-member-function")
30DOCTEST_CLANG_SUPPRESS_WARNING("-Wnonportable-system-include-path")
31
32DOCTEST_GCC_SUPPRESS_WARNING_PUSH
33DOCTEST_GCC_SUPPRESS_WARNING("-Wconversion")
34DOCTEST_GCC_SUPPRESS_WARNING("-Wsign-conversion")
35DOCTEST_GCC_SUPPRESS_WARNING("-Wmissing-field-initializers")
36DOCTEST_GCC_SUPPRESS_WARNING("-Wmissing-braces")
37DOCTEST_GCC_SUPPRESS_WARNING("-Wswitch")
38DOCTEST_GCC_SUPPRESS_WARNING("-Wswitch-enum")
39DOCTEST_GCC_SUPPRESS_WARNING("-Wswitch-default")
40DOCTEST_GCC_SUPPRESS_WARNING("-Wunsafe-loop-optimizations")
41DOCTEST_GCC_SUPPRESS_WARNING("-Wold-style-cast")
42DOCTEST_GCC_SUPPRESS_WARNING("-Wunused-function")
43DOCTEST_GCC_SUPPRESS_WARNING("-Wmultiple-inheritance")
44DOCTEST_GCC_SUPPRESS_WARNING("-Wsuggest-attribute")
45
46DOCTEST_MSVC_SUPPRESS_WARNING_PUSH
47DOCTEST_MSVC_SUPPRESS_WARNING(4267) // 'var' : conversion from 'x' to 'y', possible loss of data
48DOCTEST_MSVC_SUPPRESS_WARNING(4530) // C++ exception handler used, but unwind semantics not enabled
49DOCTEST_MSVC_SUPPRESS_WARNING(4577) // 'noexcept' used with no exception handling mode specified
50DOCTEST_MSVC_SUPPRESS_WARNING(4774) // format string expected in argument is not a string literal
51DOCTEST_MSVC_SUPPRESS_WARNING(4365) // conversion from 'int' to 'unsigned', signed/unsigned mismatch
52DOCTEST_MSVC_SUPPRESS_WARNING(5039) // pointer to potentially throwing function passed to extern C
53DOCTEST_MSVC_SUPPRESS_WARNING(4800) // forcing value to bool 'true' or 'false' (performance warning)
54DOCTEST_MSVC_SUPPRESS_WARNING(5245) // unreferenced function with internal linkage has been removed
55
56DOCTEST_MAKE_STD_HEADERS_CLEAN_FROM_WARNINGS_ON_WALL_BEGIN
57
58// required includes - will go only in one translation unit!
59#include <ctime>
60#include <cmath>
61#include <climits>
62// borland (Embarcadero) compiler requires math.h and not cmath - https://github.com/doctest/doctest/pull/37
63#ifdef __BORLANDC__
64#include <math.h>
65#endif // __BORLANDC__
66#include <new>
67#include <cstdio>
68#include <cstdlib>
69#include <cstring>
70#include <limits>
71#include <utility>
72#include <fstream>
73#include <sstream>
74#ifndef DOCTEST_CONFIG_NO_INCLUDE_IOSTREAM
75#include <iostream>
76#endif // DOCTEST_CONFIG_NO_INCLUDE_IOSTREAM
77#include <algorithm>
78#include <iomanip>
79#include <vector>
80#ifndef DOCTEST_CONFIG_NO_MULTITHREADING
81#include <atomic>
82#include <mutex>
83#define DOCTEST_DECLARE_MUTEX(name) std::mutex name;
84#define DOCTEST_DECLARE_STATIC_MUTEX(name) static DOCTEST_DECLARE_MUTEX(name)
85#define DOCTEST_LOCK_MUTEX(name) std::lock_guard<std::mutex> DOCTEST_ANONYMOUS(DOCTEST_ANON_LOCK_)(name);
86#else // DOCTEST_CONFIG_NO_MULTITHREADING
87#define DOCTEST_DECLARE_MUTEX(name)
88#define DOCTEST_DECLARE_STATIC_MUTEX(name)
89#define DOCTEST_LOCK_MUTEX(name)
90#endif // DOCTEST_CONFIG_NO_MULTITHREADING
91#include <set>
92#include <map>
93#include <unordered_set>
94#include <exception>
95#include <stdexcept>
96#include <csignal>
97#include <cfloat>
98#include <cctype>
99#include <cstdint>
100#include <string>
101
102#ifdef DOCTEST_PLATFORM_MAC
103#include <sys/types.h>
104#include <unistd.h>
105#include <sys/sysctl.h>
106#endif // DOCTEST_PLATFORM_MAC
107
108#ifdef DOCTEST_PLATFORM_WINDOWS
109
110// defines for a leaner windows.h
111#ifndef WIN32_LEAN_AND_MEAN
112#define WIN32_LEAN_AND_MEAN
113#define DOCTEST_UNDEF_WIN32_LEAN_AND_MEAN
114#endif // WIN32_LEAN_AND_MEAN
115#ifndef NOMINMAX
116#define NOMINMAX
117#define DOCTEST_UNDEF_NOMINMAX
118#endif // NOMINMAX
119
120// not sure what AfxWin.h is for - here I do what Catch does
121#ifdef __AFXDLL
122#include <AfxWin.h>
123#else
124#include <windows.h>
125#endif
126#include <io.h>
127
128#else // DOCTEST_PLATFORM_WINDOWS
129
130#include <sys/time.h>
131#include <unistd.h>
132
133#endif // DOCTEST_PLATFORM_WINDOWS
134
135// this is a fix for https://github.com/doctest/doctest/issues/348
136// https://mail.gnome.org/archives/xml/2012-January/msg00000.html
137#if !defined(HAVE_UNISTD_H) && !defined(STDOUT_FILENO)
138#define STDOUT_FILENO fileno(stdout)
139#endif // HAVE_UNISTD_H
140
141DOCTEST_MAKE_STD_HEADERS_CLEAN_FROM_WARNINGS_ON_WALL_END
142
143// counts the number of elements in a C array
144#define DOCTEST_COUNTOF(x) (sizeof(x) / sizeof(x[0]))
145
146#ifdef DOCTEST_CONFIG_DISABLE
147#define DOCTEST_BRANCH_ON_DISABLED(if_disabled, if_not_disabled) if_disabled
148#else // DOCTEST_CONFIG_DISABLE
149#define DOCTEST_BRANCH_ON_DISABLED(if_disabled, if_not_disabled) if_not_disabled
150#endif // DOCTEST_CONFIG_DISABLE
151
152#ifndef DOCTEST_CONFIG_OPTIONS_PREFIX
153#define DOCTEST_CONFIG_OPTIONS_PREFIX "dt-"
154#endif
155
156#ifndef DOCTEST_THREAD_LOCAL
157#if defined(DOCTEST_CONFIG_NO_MULTITHREADING) || DOCTEST_MSVC && (DOCTEST_MSVC < DOCTEST_COMPILER(19, 0, 0))
158#define DOCTEST_THREAD_LOCAL
159#else // DOCTEST_MSVC
160#define DOCTEST_THREAD_LOCAL thread_local
161#endif // DOCTEST_MSVC
162#endif // DOCTEST_THREAD_LOCAL
163
164#ifndef DOCTEST_MULTI_LANE_ATOMICS_THREAD_LANES
165#define DOCTEST_MULTI_LANE_ATOMICS_THREAD_LANES 32
166#endif
167
168#ifndef DOCTEST_MULTI_LANE_ATOMICS_CACHE_LINE_SIZE
169#define DOCTEST_MULTI_LANE_ATOMICS_CACHE_LINE_SIZE 64
170#endif
171
172#ifdef DOCTEST_CONFIG_NO_UNPREFIXED_OPTIONS
173#define DOCTEST_OPTIONS_PREFIX_DISPLAY DOCTEST_CONFIG_OPTIONS_PREFIX
174#else
175#define DOCTEST_OPTIONS_PREFIX_DISPLAY ""
176#endif
177
178#if defined(WINAPI_FAMILY) && (WINAPI_FAMILY == WINAPI_FAMILY_APP)
179#define DOCTEST_CONFIG_NO_MULTI_LANE_ATOMICS
180#endif
181
182#ifndef DOCTEST_CDECL
183#define DOCTEST_CDECL __cdecl
184#endif
185
186namespace doctest {
187
188bool is_running_in_test = false;
189
190namespace {
191 using namespace detail;
192
193 template <typename Ex>
194 DOCTEST_NORETURN void throw_exception(Ex const& e) {
195#ifndef DOCTEST_CONFIG_NO_EXCEPTIONS
196 throw e;
197#else // DOCTEST_CONFIG_NO_EXCEPTIONS
198#ifdef DOCTEST_CONFIG_HANDLE_EXCEPTION
199 DOCTEST_CONFIG_HANDLE_EXCEPTION(e);
200#else // DOCTEST_CONFIG_HANDLE_EXCEPTION
201#ifndef DOCTEST_CONFIG_NO_INCLUDE_IOSTREAM
202 std::cerr << "doctest will terminate because it needed to throw an exception.\n"
203 << "The message was: " << e.what() << '\n';
204#endif // DOCTEST_CONFIG_NO_INCLUDE_IOSTREAM
205#endif // DOCTEST_CONFIG_HANDLE_EXCEPTION
206 std::terminate();
207#endif // DOCTEST_CONFIG_NO_EXCEPTIONS
208 }
209
210#ifndef DOCTEST_INTERNAL_ERROR
211#define DOCTEST_INTERNAL_ERROR(msg) \
212 throw_exception(std::logic_error( \
213 __FILE__ ":" DOCTEST_TOSTR(__LINE__) ": Internal doctest error: " msg))
214#endif // DOCTEST_INTERNAL_ERROR
215
216 // case insensitive strcmp
217 int stricmp(const char* a, const char* b) {
218 for(;; a++, b++) {
219 const int d = tolower(*a) - tolower(*b);
220 if(d != 0 || !*a)
221 return d;
222 }
223 }
224
225 struct Endianness
226 {
227 enum Arch
228 {
229 Big,
230 Little
231 };
232
233 static Arch which() {
234 int x = 1;
235 // casting any data pointer to char* is allowed
236 auto ptr = reinterpret_cast<char*>(&x);
237 if(*ptr)
238 return Little;
239 return Big;
240 }
241 };
242} // namespace
243
244namespace detail {
245 DOCTEST_THREAD_LOCAL class
246 {
247 std::vector<std::streampos> stack;
248 std::stringstream ss;
249
250 public:
251 std::ostream* push() {
252 stack.push_back(ss.tellp());
253 return &ss;
254 }
255
256 String pop() {
257 if (stack.empty())
258 DOCTEST_INTERNAL_ERROR("TLSS was empty when trying to pop!");
259
260 std::streampos pos = stack.back();
261 stack.pop_back();
262 unsigned sz = static_cast<unsigned>(ss.tellp() - pos);
263 ss.rdbuf()->pubseekpos(pos, std::ios::in | std::ios::out);
264 return String(ss, sz);
265 }
266 } g_oss;
267
268 std::ostream* tlssPush() {
269 return g_oss.push();
270 }
271
272 String tlssPop() {
273 return g_oss.pop();
274 }
275
276#ifndef DOCTEST_CONFIG_DISABLE
277
278namespace timer_large_integer
279{
280
281#if defined(DOCTEST_PLATFORM_WINDOWS)
282 using type = ULONGLONG;
283#else // DOCTEST_PLATFORM_WINDOWS
284 using type = std::uint64_t;
285#endif // DOCTEST_PLATFORM_WINDOWS
286}
287
288using ticks_t = timer_large_integer::type;
289
290#ifdef DOCTEST_CONFIG_GETCURRENTTICKS
291 ticks_t getCurrentTicks() { return DOCTEST_CONFIG_GETCURRENTTICKS(); }
292#elif defined(DOCTEST_PLATFORM_WINDOWS)
293 ticks_t getCurrentTicks() {
294 static LARGE_INTEGER hz = { {0} }, hzo = { {0} };
295 if(!hz.QuadPart) {
296 QueryPerformanceFrequency(&hz);
297 QueryPerformanceCounter(&hzo);
298 }
299 LARGE_INTEGER t;
300 QueryPerformanceCounter(&t);
301 return ((t.QuadPart - hzo.QuadPart) * LONGLONG(1000000)) / hz.QuadPart;
302 }
303#else // DOCTEST_PLATFORM_WINDOWS
304 ticks_t getCurrentTicks() {
305 timeval t;
306 gettimeofday(&t, nullptr);
307 return static_cast<ticks_t>(t.tv_sec) * 1000000 + static_cast<ticks_t>(t.tv_usec);
308 }
309#endif // DOCTEST_PLATFORM_WINDOWS
310
311 struct Timer
312 {
313 void start() { m_ticks = getCurrentTicks(); }
314 unsigned int getElapsedMicroseconds() const {
315 return static_cast<unsigned int>(getCurrentTicks() - m_ticks);
316 }
317 //unsigned int getElapsedMilliseconds() const {
318 // return static_cast<unsigned int>(getElapsedMicroseconds() / 1000);
319 //}
320 double getElapsedSeconds() const { return static_cast<double>(getCurrentTicks() - m_ticks) / 1000000.0; }
321
322 private:
323 ticks_t m_ticks = 0;
324 };
325
326#ifdef DOCTEST_CONFIG_NO_MULTITHREADING
327 template <typename T>
328 using Atomic = T;
329#else // DOCTEST_CONFIG_NO_MULTITHREADING
330 template <typename T>
331 using Atomic = std::atomic<T>;
332#endif // DOCTEST_CONFIG_NO_MULTITHREADING
333
334#if defined(DOCTEST_CONFIG_NO_MULTI_LANE_ATOMICS) || defined(DOCTEST_CONFIG_NO_MULTITHREADING)
335 template <typename T>
336 using MultiLaneAtomic = Atomic<T>;
337#else // DOCTEST_CONFIG_NO_MULTI_LANE_ATOMICS
338 // Provides a multilane implementation of an atomic variable that supports add, sub, load,
339 // store. Instead of using a single atomic variable, this splits up into multiple ones,
340 // each sitting on a separate cache line. The goal is to provide a speedup when most
341 // operations are modifying. It achieves this with two properties:
342 //
343 // * Multiple atomics are used, so chance of congestion from the same atomic is reduced.
344 // * Each atomic sits on a separate cache line, so false sharing is reduced.
345 //
346 // The disadvantage is that there is a small overhead due to the use of TLS, and load/store
347 // is slower because all atomics have to be accessed.
348 template <typename T>
350 {
351 struct CacheLineAlignedAtomic
352 {
353 Atomic<T> atomic{};
354 char padding[DOCTEST_MULTI_LANE_ATOMICS_CACHE_LINE_SIZE - sizeof(Atomic<T>)];
355 };
356 CacheLineAlignedAtomic m_atomics[DOCTEST_MULTI_LANE_ATOMICS_THREAD_LANES];
357
358 static_assert(sizeof(CacheLineAlignedAtomic) == DOCTEST_MULTI_LANE_ATOMICS_CACHE_LINE_SIZE,
359 "guarantee one atomic takes exactly one cache line");
360
361 public:
362 T operator++() DOCTEST_NOEXCEPT { return fetch_add(1) + 1; }
363
364 T operator++(int) DOCTEST_NOEXCEPT { return fetch_add(1); }
365
366 T fetch_add(T arg, std::memory_order order = std::memory_order_seq_cst) DOCTEST_NOEXCEPT {
367 return myAtomic().fetch_add(arg, order);
368 }
369
370 T fetch_sub(T arg, std::memory_order order = std::memory_order_seq_cst) DOCTEST_NOEXCEPT {
371 return myAtomic().fetch_sub(arg, order);
372 }
373
374 operator T() const DOCTEST_NOEXCEPT { return load(); }
375
376 T load(std::memory_order order = std::memory_order_seq_cst) const DOCTEST_NOEXCEPT {
377 auto result = T();
378 for(auto const& c : m_atomics) {
379 result += c.atomic.load(order);
380 }
381 return result;
382 }
383
384 T operator=(T desired) DOCTEST_NOEXCEPT { // lgtm [cpp/assignment-does-not-return-this]
385 store(desired);
386 return desired;
387 }
388
389 void store(T desired, std::memory_order order = std::memory_order_seq_cst) DOCTEST_NOEXCEPT {
390 // first value becomes desired", all others become 0.
391 for(auto& c : m_atomics) {
392 c.atomic.store(desired, order);
393 desired = {};
394 }
395 }
396
397 private:
398 // Each thread has a different atomic that it operates on. If more than NumLanes threads
399 // use this, some will use the same atomic. So performance will degrade a bit, but still
400 // everything will work.
401 //
402 // The logic here is a bit tricky. The call should be as fast as possible, so that there
403 // is minimal to no overhead in determining the correct atomic for the current thread.
404 //
405 // 1. A global static counter laneCounter counts continuously up.
406 // 2. Each successive thread will use modulo operation of that counter so it gets an atomic
407 // assigned in a round-robin fashion.
408 // 3. This tlsLaneIdx is stored in the thread local data, so it is directly available with
409 // little overhead.
410 Atomic<T>& myAtomic() DOCTEST_NOEXCEPT {
411 static Atomic<size_t> laneCounter;
412 DOCTEST_THREAD_LOCAL size_t tlsLaneIdx =
413 laneCounter++ % DOCTEST_MULTI_LANE_ATOMICS_THREAD_LANES;
414
415 return m_atomics[tlsLaneIdx].atomic;
416 }
417 };
418#endif // DOCTEST_CONFIG_NO_MULTI_LANE_ATOMICS
419
420 // this holds both parameters from the command line and runtime data for tests
422 {
423 MultiLaneAtomic<int> numAssertsCurrentTest_atomic;
424 MultiLaneAtomic<int> numAssertsFailedCurrentTest_atomic;
425
426 std::vector<std::vector<String>> filters = decltype(filters)(9); // 9 different filters
427
428 std::vector<IReporter*> reporters_currently_used;
429
430 assert_handler ah = nullptr;
431
432 Timer timer;
433
434 std::vector<String> stringifiedContexts; // logging from INFO() due to an exception
435
436 // stuff for subcases
437 bool reachedLeaf;
438 std::vector<SubcaseSignature> subcaseStack;
439 std::vector<SubcaseSignature> nextSubcaseStack;
440 std::unordered_set<unsigned long long> fullyTraversedSubcases;
441 size_t currentSubcaseDepth;
442 Atomic<bool> shouldLogCurrentException;
443
444 void resetRunData() {
445 numTestCases = 0;
446 numTestCasesPassingFilters = 0;
447 numTestSuitesPassingFilters = 0;
448 numTestCasesFailed = 0;
449 numAsserts = 0;
450 numAssertsFailed = 0;
451 numAssertsCurrentTest = 0;
452 numAssertsFailedCurrentTest = 0;
453 }
454
455 void finalizeTestCaseData() {
456 seconds = timer.getElapsedSeconds();
457
458 // update the non-atomic counters
459 numAsserts += numAssertsCurrentTest_atomic;
460 numAssertsFailed += numAssertsFailedCurrentTest_atomic;
461 numAssertsCurrentTest = numAssertsCurrentTest_atomic;
462 numAssertsFailedCurrentTest = numAssertsFailedCurrentTest_atomic;
463
464 if(numAssertsFailedCurrentTest)
465 failure_flags |= TestCaseFailureReason::AssertFailure;
466
467 if(Approx(currentTest->m_timeout).epsilon(DBL_EPSILON) != 0 &&
468 Approx(seconds).epsilon(DBL_EPSILON) > currentTest->m_timeout)
469 failure_flags |= TestCaseFailureReason::Timeout;
470
471 if(currentTest->m_should_fail) {
472 if(failure_flags) {
473 failure_flags |= TestCaseFailureReason::ShouldHaveFailedAndDid;
474 } else {
475 failure_flags |= TestCaseFailureReason::ShouldHaveFailedButDidnt;
476 }
477 } else if(failure_flags && currentTest->m_may_fail) {
478 failure_flags |= TestCaseFailureReason::CouldHaveFailedAndDid;
479 } else if(currentTest->m_expected_failures > 0) {
480 if(numAssertsFailedCurrentTest == currentTest->m_expected_failures) {
481 failure_flags |= TestCaseFailureReason::FailedExactlyNumTimes;
482 } else {
483 failure_flags |= TestCaseFailureReason::DidntFailExactlyNumTimes;
484 }
485 }
486
487 bool ok_to_fail = (TestCaseFailureReason::ShouldHaveFailedAndDid & failure_flags) ||
488 (TestCaseFailureReason::CouldHaveFailedAndDid & failure_flags) ||
489 (TestCaseFailureReason::FailedExactlyNumTimes & failure_flags);
490
491 // if any subcase has failed - the whole test case has failed
492 testCaseSuccess = !(failure_flags && !ok_to_fail);
493 if(!testCaseSuccess)
494 numTestCasesFailed++;
495 }
496 };
497
498 ContextState* g_cs = nullptr;
499
500 // used to avoid locks for the debug output
501 // TODO: figure out if this is indeed necessary/correct - seems like either there still
502 // could be a race or that there wouldn't be a race even if using the context directly
503 DOCTEST_THREAD_LOCAL bool g_no_colors;
504
505#endif // DOCTEST_CONFIG_DISABLE
506} // namespace detail
507
508char* String::allocate(size_type sz) {
509 if (sz <= last) {
510 buf[sz] = '\0';
511 setLast(last - sz);
512 return buf;
513 } else {
514 setOnHeap();
515 data.size = sz;
516 data.capacity = data.size + 1;
517 data.ptr = new char[data.capacity];
518 data.ptr[sz] = '\0';
519 return data.ptr;
520 }
521}
522
523void String::setOnHeap() noexcept { *reinterpret_cast<unsigned char*>(&buf[last]) = 128; }
524void String::setLast(size_type in) noexcept { buf[last] = char(in); }
525void String::setSize(size_type sz) noexcept {
526 if (isOnStack()) { buf[sz] = '\0'; setLast(last - sz); }
527 else { data.ptr[sz] = '\0'; data.size = sz; }
528}
529
530void String::copy(const String& other) {
531 if(other.isOnStack()) {
532 memcpy(buf, other.buf, len);
533 } else {
534 memcpy(allocate(other.data.size), other.data.ptr, other.data.size);
535 }
536}
537
538String::String() noexcept {
539 buf[0] = '\0';
540 setLast();
541}
542
543String::~String() {
544 if(!isOnStack())
545 delete[] data.ptr;
546} // NOLINT(clang-analyzer-cplusplus.NewDeleteLeaks)
547
548String::String(const char* in)
549 : String(in, strlen(in)) {}
550
551String::String(const char* in, size_type in_size) {
552 memcpy(allocate(in_size), in, in_size);
553}
554
555String::String(std::istream& in, size_type in_size) {
556 in.read(allocate(in_size), in_size);
557}
558
559String::String(const String& other) { copy(other); }
560
561String& String::operator=(const String& other) {
562 if(this != &other) {
563 if(!isOnStack())
564 delete[] data.ptr;
565
566 copy(other);
567 }
568
569 return *this;
570}
571
572String& String::operator+=(const String& other) {
573 const size_type my_old_size = size();
574 const size_type other_size = other.size();
575 const size_type total_size = my_old_size + other_size;
576 if(isOnStack()) {
577 if(total_size < len) {
578 // append to the current stack space
579 memcpy(buf + my_old_size, other.c_str(), other_size + 1);
580 // NOLINTNEXTLINE(clang-analyzer-cplusplus.NewDeleteLeaks)
581 setLast(last - total_size);
582 } else {
583 // alloc new chunk
584 char* temp = new char[total_size + 1];
585 // copy current data to new location before writing in the union
586 memcpy(temp, buf, my_old_size); // skip the +1 ('\0') for speed
587 // update data in union
588 setOnHeap();
589 data.size = total_size;
590 data.capacity = data.size + 1;
591 data.ptr = temp;
592 // transfer the rest of the data
593 memcpy(data.ptr + my_old_size, other.c_str(), other_size + 1);
594 }
595 } else {
596 if(data.capacity > total_size) {
597 // append to the current heap block
598 data.size = total_size;
599 memcpy(data.ptr + my_old_size, other.c_str(), other_size + 1);
600 } else {
601 // resize
602 data.capacity *= 2;
603 if(data.capacity <= total_size)
604 data.capacity = total_size + 1;
605 // alloc new chunk
606 char* temp = new char[data.capacity];
607 // copy current data to new location before releasing it
608 memcpy(temp, data.ptr, my_old_size); // skip the +1 ('\0') for speed
609 // release old chunk
610 delete[] data.ptr;
611 // update the rest of the union members
612 data.size = total_size;
613 data.ptr = temp;
614 // transfer the rest of the data
615 memcpy(data.ptr + my_old_size, other.c_str(), other_size + 1);
616 }
617 }
618
619 return *this;
620}
621
622String::String(String&& other) noexcept {
623 memcpy(buf, other.buf, len);
624 other.buf[0] = '\0';
625 other.setLast();
626}
627
628String& String::operator=(String&& other) noexcept {
629 if(this != &other) {
630 if(!isOnStack())
631 delete[] data.ptr;
632 memcpy(buf, other.buf, len);
633 other.buf[0] = '\0';
634 other.setLast();
635 }
636 return *this;
637}
638
639char String::operator[](size_type i) const {
640 return const_cast<String*>(this)->operator[](i);
641}
642
643char& String::operator[](size_type i) {
644 if(isOnStack())
645 return reinterpret_cast<char*>(buf)[i];
646 return data.ptr[i];
647}
648
649DOCTEST_GCC_SUPPRESS_WARNING_WITH_PUSH("-Wmaybe-uninitialized")
650String::size_type String::size() const {
651 if(isOnStack())
652 return last - (size_type(buf[last]) & 31); // using "last" would work only if "len" is 32
653 return data.size;
654}
655DOCTEST_GCC_SUPPRESS_WARNING_POP
656
657String::size_type String::capacity() const {
658 if(isOnStack())
659 return len;
660 return data.capacity;
661}
662
663String String::substr(size_type pos, size_type cnt) && {
664 cnt = std::min(cnt, size() - 1 - pos);
665 char* cptr = c_str();
666 memmove(cptr, cptr + pos, cnt);
667 setSize(cnt);
668 return std::move(*this);
669}
670
671String String::substr(size_type pos, size_type cnt) const & {
672 cnt = std::min(cnt, size() - 1 - pos);
673 return String{ c_str() + pos, cnt };
674}
675
676String::size_type String::find(char ch, size_type pos) const {
677 const char* begin = c_str();
678 const char* end = begin + size();
679 const char* it = begin + pos;
680 for (; it < end && *it != ch; it++);
681 if (it < end) { return static_cast<size_type>(it - begin); }
682 else { return npos; }
683}
684
685String::size_type String::rfind(char ch, size_type pos) const {
686 const char* begin = c_str();
687 const char* it = begin + std::min(pos, size() - 1);
688 for (; it >= begin && *it != ch; it--);
689 if (it >= begin) { return static_cast<size_type>(it - begin); }
690 else { return npos; }
691}
692
693int String::compare(const char* other, bool no_case) const {
694 if(no_case)
695 return doctest::stricmp(c_str(), other);
696 return std::strcmp(c_str(), other);
697}
698
699int String::compare(const String& other, bool no_case) const {
700 return compare(other.c_str(), no_case);
701}
702
703String operator+(const String& lhs, const String& rhs) { return String(lhs) += rhs; }
704
705bool operator==(const String& lhs, const String& rhs) { return lhs.compare(rhs) == 0; }
706bool operator!=(const String& lhs, const String& rhs) { return lhs.compare(rhs) != 0; }
707bool operator< (const String& lhs, const String& rhs) { return lhs.compare(rhs) < 0; }
708bool operator> (const String& lhs, const String& rhs) { return lhs.compare(rhs) > 0; }
709bool operator<=(const String& lhs, const String& rhs) { return (lhs != rhs) ? lhs.compare(rhs) < 0 : true; }
710bool operator>=(const String& lhs, const String& rhs) { return (lhs != rhs) ? lhs.compare(rhs) > 0 : true; }
711
712std::ostream& operator<<(std::ostream& s, const String& in) { return s << in.c_str(); }
713
714Contains::Contains(const String& str) : string(str) { }
715
716bool Contains::checkWith(const String& other) const {
717 return strstr(other.c_str(), string.c_str()) != nullptr;
718}
719
720String toString(const Contains& in) {
721 return "Contains( " + in.string + " )";
722}
723
724bool operator==(const String& lhs, const Contains& rhs) { return rhs.checkWith(lhs); }
725bool operator==(const Contains& lhs, const String& rhs) { return lhs.checkWith(rhs); }
726bool operator!=(const String& lhs, const Contains& rhs) { return !rhs.checkWith(lhs); }
727bool operator!=(const Contains& lhs, const String& rhs) { return !lhs.checkWith(rhs); }
728
729namespace {
730 void color_to_stream(std::ostream&, Color::Enum) DOCTEST_BRANCH_ON_DISABLED({}, ;)
731} // namespace
732
733namespace Color {
734 std::ostream& operator<<(std::ostream& s, Color::Enum code) {
735 color_to_stream(s, code);
736 return s;
737 }
738} // namespace Color
739
740// clang-format off
741const char* assertString(assertType::Enum at) {
742 DOCTEST_MSVC_SUPPRESS_WARNING_WITH_PUSH(4061) // enum 'x' in switch of enum 'y' is not explicitly handled
743 #define DOCTEST_GENERATE_ASSERT_TYPE_CASE(assert_type) case assertType::DT_ ## assert_type: return #assert_type
744 #define DOCTEST_GENERATE_ASSERT_TYPE_CASES(assert_type) \
745 DOCTEST_GENERATE_ASSERT_TYPE_CASE(WARN_ ## assert_type); \
746 DOCTEST_GENERATE_ASSERT_TYPE_CASE(CHECK_ ## assert_type); \
747 DOCTEST_GENERATE_ASSERT_TYPE_CASE(REQUIRE_ ## assert_type)
748 switch(at) {
749 DOCTEST_GENERATE_ASSERT_TYPE_CASE(WARN);
750 DOCTEST_GENERATE_ASSERT_TYPE_CASE(CHECK);
751 DOCTEST_GENERATE_ASSERT_TYPE_CASE(REQUIRE);
752
753 DOCTEST_GENERATE_ASSERT_TYPE_CASES(FALSE);
754
755 DOCTEST_GENERATE_ASSERT_TYPE_CASES(THROWS);
756
757 DOCTEST_GENERATE_ASSERT_TYPE_CASES(THROWS_AS);
758
759 DOCTEST_GENERATE_ASSERT_TYPE_CASES(THROWS_WITH);
760
761 DOCTEST_GENERATE_ASSERT_TYPE_CASES(THROWS_WITH_AS);
762
763 DOCTEST_GENERATE_ASSERT_TYPE_CASES(NOTHROW);
764
765 DOCTEST_GENERATE_ASSERT_TYPE_CASES(EQ);
766 DOCTEST_GENERATE_ASSERT_TYPE_CASES(NE);
767 DOCTEST_GENERATE_ASSERT_TYPE_CASES(GT);
768 DOCTEST_GENERATE_ASSERT_TYPE_CASES(LT);
769 DOCTEST_GENERATE_ASSERT_TYPE_CASES(GE);
770 DOCTEST_GENERATE_ASSERT_TYPE_CASES(LE);
771
772 DOCTEST_GENERATE_ASSERT_TYPE_CASES(UNARY);
773 DOCTEST_GENERATE_ASSERT_TYPE_CASES(UNARY_FALSE);
774
775 default: DOCTEST_INTERNAL_ERROR("Tried stringifying invalid assert type!");
776 }
777 DOCTEST_MSVC_SUPPRESS_WARNING_POP
778}
779// clang-format on
780
781const char* failureString(assertType::Enum at) {
782 if(at & assertType::is_warn)
783 return "WARNING";
784 if(at & assertType::is_check)
785 return "ERROR";
786 if(at & assertType::is_require)
787 return "FATAL ERROR";
788 return "";
789}
790
791DOCTEST_CLANG_SUPPRESS_WARNING_WITH_PUSH("-Wnull-dereference")
792DOCTEST_GCC_SUPPRESS_WARNING_WITH_PUSH("-Wnull-dereference")
793// depending on the current options this will remove the path of filenames
794const char* skipPathFromFilename(const char* file) {
795#ifndef DOCTEST_CONFIG_DISABLE
796 if(getContextOptions()->no_path_in_filenames) {
797 auto back = std::strrchr(file, '\\');
798 auto forward = std::strrchr(file, '/');
799 if(back || forward) {
800 if(back > forward)
801 forward = back;
802 return forward + 1;
803 }
804 }
805#endif // DOCTEST_CONFIG_DISABLE
806 return file;
807}
808DOCTEST_CLANG_SUPPRESS_WARNING_POP
809DOCTEST_GCC_SUPPRESS_WARNING_POP
810
811bool SubcaseSignature::operator==(const SubcaseSignature& other) const {
812 return m_line == other.m_line
813 && std::strcmp(m_file, other.m_file) == 0
814 && m_name == other.m_name;
815}
816
817bool SubcaseSignature::operator<(const SubcaseSignature& other) const {
818 if(m_line != other.m_line)
819 return m_line < other.m_line;
820 if(std::strcmp(m_file, other.m_file) != 0)
821 return std::strcmp(m_file, other.m_file) < 0;
822 return m_name.compare(other.m_name) < 0;
823}
824
825DOCTEST_DEFINE_INTERFACE(IContextScope)
826
827namespace detail {
828 void filldata<const void*>::fill(std::ostream* stream, const void* in) {
829 if (in) { *stream << in; }
830 else { *stream << "nullptr"; }
831 }
832
833 template <typename T>
834 String toStreamLit(T t) {
835 std::ostream* os = tlssPush();
836 os->operator<<(t);
837 return tlssPop();
838 }
839}
840
841#ifdef DOCTEST_CONFIG_TREAT_CHAR_STAR_AS_STRING
842String toString(const char* in) { return String("\"") + (in ? in : "{null string}") + "\""; }
843#endif // DOCTEST_CONFIG_TREAT_CHAR_STAR_AS_STRING
844
845#if DOCTEST_MSVC >= DOCTEST_COMPILER(19, 20, 0)
846// see this issue on why this is needed: https://github.com/doctest/doctest/issues/183
847String toString(const std::string& in) { return in.c_str(); }
848#endif // VS 2019
849
850String toString(String in) { return in; }
851
852String toString(std::nullptr_t) { return "nullptr"; }
853
854String toString(bool in) { return in ? "true" : "false"; }
855
856String toString(float in) { return toStreamLit(in); }
857String toString(double in) { return toStreamLit(in); }
858String toString(double long in) { return toStreamLit(in); }
859
860String toString(char in) { return toStreamLit(static_cast<signed>(in)); }
861String toString(char signed in) { return toStreamLit(static_cast<signed>(in)); }
862String toString(char unsigned in) { return toStreamLit(static_cast<unsigned>(in)); }
863String toString(short in) { return toStreamLit(in); }
864String toString(short unsigned in) { return toStreamLit(in); }
865String toString(signed in) { return toStreamLit(in); }
866String toString(unsigned in) { return toStreamLit(in); }
867String toString(long in) { return toStreamLit(in); }
868String toString(long unsigned in) { return toStreamLit(in); }
869String toString(long long in) { return toStreamLit(in); }
870String toString(long long unsigned in) { return toStreamLit(in); }
871
872Approx::Approx(double value)
873 : m_epsilon(static_cast<double>(std::numeric_limits<float>::epsilon()) * 100)
874 , m_scale(1.0)
875 , m_value(value) {}
876
877Approx Approx::operator()(double value) const {
878 Approx approx(value);
879 approx.epsilon(m_epsilon);
880 approx.scale(m_scale);
881 return approx;
882}
883
884Approx& Approx::epsilon(double newEpsilon) {
885 m_epsilon = newEpsilon;
886 return *this;
887}
888Approx& Approx::scale(double newScale) {
889 m_scale = newScale;
890 return *this;
891}
892
893bool operator==(double lhs, const Approx& rhs) {
894 // Thanks to Richard Harris for his help refining this formula
895 return std::fabs(lhs - rhs.m_value) <
896 rhs.m_epsilon * (rhs.m_scale + std::max<double>(std::fabs(lhs), std::fabs(rhs.m_value)));
897}
898bool operator==(const Approx& lhs, double rhs) { return operator==(rhs, lhs); }
899bool operator!=(double lhs, const Approx& rhs) { return !operator==(lhs, rhs); }
900bool operator!=(const Approx& lhs, double rhs) { return !operator==(rhs, lhs); }
901bool operator<=(double lhs, const Approx& rhs) { return lhs < rhs.m_value || lhs == rhs; }
902bool operator<=(const Approx& lhs, double rhs) { return lhs.m_value < rhs || lhs == rhs; }
903bool operator>=(double lhs, const Approx& rhs) { return lhs > rhs.m_value || lhs == rhs; }
904bool operator>=(const Approx& lhs, double rhs) { return lhs.m_value > rhs || lhs == rhs; }
905bool operator<(double lhs, const Approx& rhs) { return lhs < rhs.m_value && lhs != rhs; }
906bool operator<(const Approx& lhs, double rhs) { return lhs.m_value < rhs && lhs != rhs; }
907bool operator>(double lhs, const Approx& rhs) { return lhs > rhs.m_value && lhs != rhs; }
908bool operator>(const Approx& lhs, double rhs) { return lhs.m_value > rhs && lhs != rhs; }
909
910String toString(const Approx& in) {
911 return "Approx( " + doctest::toString(in.m_value) + " )";
912}
913const ContextOptions* getContextOptions() { return DOCTEST_BRANCH_ON_DISABLED(nullptr, g_cs); }
914
915DOCTEST_MSVC_SUPPRESS_WARNING_WITH_PUSH(4738)
916template <typename F>
917IsNaN<F>::operator bool() const {
918 return std::isnan(value) ^ flipped;
919}
920DOCTEST_MSVC_SUPPRESS_WARNING_POP
921template struct DOCTEST_INTERFACE_DEF IsNaN<float>;
922template struct DOCTEST_INTERFACE_DEF IsNaN<double>;
923template struct DOCTEST_INTERFACE_DEF IsNaN<long double>;
924template <typename F>
925String toString(IsNaN<F> in) { return String(in.flipped ? "! " : "") + "IsNaN( " + doctest::toString(in.value) + " )"; }
926String toString(IsNaN<float> in) { return toString<float>(in); }
927String toString(IsNaN<double> in) { return toString<double>(in); }
928String toString(IsNaN<double long> in) { return toString<double long>(in); }
929
930} // namespace doctest
931
932#ifdef DOCTEST_CONFIG_DISABLE
933namespace doctest {
934Context::Context(int, const char* const*) {}
935Context::~Context() = default;
936void Context::applyCommandLine(int, const char* const*) {}
937void Context::addFilter(const char*, const char*) {}
938void Context::clearFilters() {}
939void Context::setOption(const char*, bool) {}
940void Context::setOption(const char*, int) {}
941void Context::setOption(const char*, const char*) {}
942bool Context::shouldExit() { return false; }
943void Context::setAsDefaultForAssertsOutOfTestCases() {}
944void Context::setAssertHandler(detail::assert_handler) {}
945void Context::setCout(std::ostream*) {}
946int Context::run() { return 0; }
947
948int IReporter::get_num_active_contexts() { return 0; }
949const IContextScope* const* IReporter::get_active_contexts() { return nullptr; }
950int IReporter::get_num_stringified_contexts() { return 0; }
951const String* IReporter::get_stringified_contexts() { return nullptr; }
952
953int registerReporter(const char*, int, IReporter*) { return 0; }
954
955} // namespace doctest
956#else // DOCTEST_CONFIG_DISABLE
957
958#if !defined(DOCTEST_CONFIG_COLORS_NONE)
959#if !defined(DOCTEST_CONFIG_COLORS_WINDOWS) && !defined(DOCTEST_CONFIG_COLORS_ANSI)
960#ifdef DOCTEST_PLATFORM_WINDOWS
961#define DOCTEST_CONFIG_COLORS_WINDOWS
962#else // linux
963#define DOCTEST_CONFIG_COLORS_ANSI
964#endif // platform
965#endif // DOCTEST_CONFIG_COLORS_WINDOWS && DOCTEST_CONFIG_COLORS_ANSI
966#endif // DOCTEST_CONFIG_COLORS_NONE
967
968namespace doctest_detail_test_suite_ns {
969// holds the current test suite
970doctest::detail::TestSuite& getCurrentTestSuite() {
971 static doctest::detail::TestSuite data{};
972 return data;
973}
974} // namespace doctest_detail_test_suite_ns
975
976namespace doctest {
977namespace {
978 // the int (priority) is part of the key for automatic sorting - sadly one can register a
979 // reporter with a duplicate name and a different priority but hopefully that won't happen often :|
980 using reporterMap = std::map<std::pair<int, String>, reporterCreatorFunc>;
981
982 reporterMap& getReporters() {
983 static reporterMap data;
984 return data;
985 }
986 reporterMap& getListeners() {
987 static reporterMap data;
988 return data;
989 }
990} // namespace
991namespace detail {
992#define DOCTEST_ITERATE_THROUGH_REPORTERS(function, ...) \
993 for(auto& curr_rep : g_cs->reporters_currently_used) \
994 curr_rep->function(__VA_ARGS__)
995
996 bool checkIfShouldThrow(assertType::Enum at) {
997 if(at & assertType::is_require)
998 return true;
999
1000 if((at & assertType::is_check)
1001 && getContextOptions()->abort_after > 0 &&
1002 (g_cs->numAssertsFailed + g_cs->numAssertsFailedCurrentTest_atomic) >=
1003 getContextOptions()->abort_after)
1004 return true;
1005
1006 return false;
1007 }
1008
1009#ifndef DOCTEST_CONFIG_NO_EXCEPTIONS
1010 DOCTEST_NORETURN void throwException() {
1011 g_cs->shouldLogCurrentException = false;
1012 throw TestFailureException(); // NOLINT(hicpp-exception-baseclass)
1013 }
1014#else // DOCTEST_CONFIG_NO_EXCEPTIONS
1015 void throwException() {}
1016#endif // DOCTEST_CONFIG_NO_EXCEPTIONS
1017} // namespace detail
1018
1019namespace {
1020 using namespace detail;
1021 // matching of a string against a wildcard mask (case sensitivity configurable) taken from
1022 // https://www.codeproject.com/Articles/1088/Wildcard-string-compare-globbing
1023 int wildcmp(const char* str, const char* wild, bool caseSensitive) {
1024 const char* cp = str;
1025 const char* mp = wild;
1026
1027 while((*str) && (*wild != '*')) {
1028 if((caseSensitive ? (*wild != *str) : (tolower(*wild) != tolower(*str))) &&
1029 (*wild != '?')) {
1030 return 0;
1031 }
1032 wild++;
1033 str++;
1034 }
1035
1036 while(*str) {
1037 if(*wild == '*') {
1038 if(!*++wild) {
1039 return 1;
1040 }
1041 mp = wild;
1042 cp = str + 1;
1043 } else if((caseSensitive ? (*wild == *str) : (tolower(*wild) == tolower(*str))) ||
1044 (*wild == '?')) {
1045 wild++;
1046 str++;
1047 } else {
1048 wild = mp;
1049 str = cp++;
1050 }
1051 }
1052
1053 while(*wild == '*') {
1054 wild++;
1055 }
1056 return !*wild;
1057 }
1058
1059 // checks if the name matches any of the filters (and can be configured what to do when empty)
1060 bool matchesAny(const char* name, const std::vector<String>& filters, bool matchEmpty,
1061 bool caseSensitive) {
1062 if (filters.empty() && matchEmpty)
1063 return true;
1064 for (auto& curr : filters)
1065 if (wildcmp(name, curr.c_str(), caseSensitive))
1066 return true;
1067 return false;
1068 }
1069
1070 DOCTEST_NO_SANITIZE_INTEGER
1071 unsigned long long hash(unsigned long long a, unsigned long long b) {
1072 return (a << 5) + b;
1073 }
1074
1075 // C string hash function (djb2) - taken from http://www.cse.yorku.ca/~oz/hash.html
1076 DOCTEST_NO_SANITIZE_INTEGER
1077 unsigned long long hash(const char* str) {
1078 unsigned long long hash = 5381;
1079 char c;
1080 while ((c = *str++))
1081 hash = ((hash << 5) + hash) + c; // hash * 33 + c
1082 return hash;
1083 }
1084
1085 unsigned long long hash(const SubcaseSignature& sig) {
1086 return hash(hash(hash(sig.m_file), hash(sig.m_name.c_str())), sig.m_line);
1087 }
1088
1089 unsigned long long hash(const std::vector<SubcaseSignature>& sigs, size_t count) {
1090 unsigned long long running = 0;
1091 auto end = sigs.begin() + count;
1092 for (auto it = sigs.begin(); it != end; it++) {
1093 running = hash(running, hash(*it));
1094 }
1095 return running;
1096 }
1097
1098 unsigned long long hash(const std::vector<SubcaseSignature>& sigs) {
1099 unsigned long long running = 0;
1100 for (const SubcaseSignature& sig : sigs) {
1101 running = hash(running, hash(sig));
1102 }
1103 return running;
1104 }
1105} // namespace
1106namespace detail {
1107 bool Subcase::checkFilters() {
1108 if (g_cs->subcaseStack.size() < size_t(g_cs->subcase_filter_levels)) {
1109 if (!matchesAny(m_signature.m_name.c_str(), g_cs->filters[6], true, g_cs->case_sensitive))
1110 return true;
1111 if (matchesAny(m_signature.m_name.c_str(), g_cs->filters[7], false, g_cs->case_sensitive))
1112 return true;
1113 }
1114 return false;
1115 }
1116
1117 Subcase::Subcase(const String& name, const char* file, int line)
1118 : m_signature({name, file, line}) {
1119 if (!g_cs->reachedLeaf) {
1120 if (g_cs->nextSubcaseStack.size() <= g_cs->subcaseStack.size()
1121 || g_cs->nextSubcaseStack[g_cs->subcaseStack.size()] == m_signature) {
1122 // Going down.
1123 if (checkFilters()) { return; }
1124
1125 g_cs->subcaseStack.push_back(m_signature);
1126 g_cs->currentSubcaseDepth++;
1127 m_entered = true;
1128 DOCTEST_ITERATE_THROUGH_REPORTERS(subcase_start, m_signature);
1129 }
1130 } else {
1131 if (g_cs->subcaseStack[g_cs->currentSubcaseDepth] == m_signature) {
1132 // This subcase is reentered via control flow.
1133 g_cs->currentSubcaseDepth++;
1134 m_entered = true;
1135 DOCTEST_ITERATE_THROUGH_REPORTERS(subcase_start, m_signature);
1136 } else if (g_cs->nextSubcaseStack.size() <= g_cs->currentSubcaseDepth
1137 && g_cs->fullyTraversedSubcases.find(hash(hash(g_cs->subcaseStack, g_cs->currentSubcaseDepth), hash(m_signature)))
1138 == g_cs->fullyTraversedSubcases.end()) {
1139 if (checkFilters()) { return; }
1140 // This subcase is part of the one to be executed next.
1141 g_cs->nextSubcaseStack.clear();
1142 g_cs->nextSubcaseStack.insert(g_cs->nextSubcaseStack.end(),
1143 g_cs->subcaseStack.begin(), g_cs->subcaseStack.begin() + g_cs->currentSubcaseDepth);
1144 g_cs->nextSubcaseStack.push_back(m_signature);
1145 }
1146 }
1147 }
1148
1149 DOCTEST_MSVC_SUPPRESS_WARNING_WITH_PUSH(4996) // std::uncaught_exception is deprecated in C++17
1150 DOCTEST_GCC_SUPPRESS_WARNING_WITH_PUSH("-Wdeprecated-declarations")
1151 DOCTEST_CLANG_SUPPRESS_WARNING_WITH_PUSH("-Wdeprecated-declarations")
1152
1153 Subcase::~Subcase() {
1154 if (m_entered) {
1155 g_cs->currentSubcaseDepth--;
1156
1157 if (!g_cs->reachedLeaf) {
1158 // Leaf.
1159 g_cs->fullyTraversedSubcases.insert(hash(g_cs->subcaseStack));
1160 g_cs->nextSubcaseStack.clear();
1161 g_cs->reachedLeaf = true;
1162 } else if (g_cs->nextSubcaseStack.empty()) {
1163 // All children are finished.
1164 g_cs->fullyTraversedSubcases.insert(hash(g_cs->subcaseStack));
1165 }
1166
1167#if defined(__cpp_lib_uncaught_exceptions) && __cpp_lib_uncaught_exceptions >= 201411L && (!defined(__MAC_OS_X_VERSION_MIN_REQUIRED) || __MAC_OS_X_VERSION_MIN_REQUIRED >= 101200)
1168 if(std::uncaught_exceptions() > 0
1169#else
1170 if(std::uncaught_exception()
1171#endif
1172 && g_cs->shouldLogCurrentException) {
1173 DOCTEST_ITERATE_THROUGH_REPORTERS(
1174 test_case_exception, {"exception thrown in subcase - will translate later "
1175 "when the whole test case has been exited (cannot "
1176 "translate while there is an active exception)",
1177 false});
1178 g_cs->shouldLogCurrentException = false;
1179 }
1180
1181 DOCTEST_ITERATE_THROUGH_REPORTERS(subcase_end, DOCTEST_EMPTY);
1182 }
1183 }
1184
1185 DOCTEST_CLANG_SUPPRESS_WARNING_POP
1186 DOCTEST_GCC_SUPPRESS_WARNING_POP
1187 DOCTEST_MSVC_SUPPRESS_WARNING_POP
1188
1189 Subcase::operator bool() const { return m_entered; }
1190
1191 Result::Result(bool passed, const String& decomposition)
1192 : m_passed(passed)
1193 , m_decomp(decomposition) {}
1194
1195 ExpressionDecomposer::ExpressionDecomposer(assertType::Enum at)
1196 : m_at(at) {}
1197
1198 TestSuite& TestSuite::operator*(const char* in) {
1199 m_test_suite = in;
1200 return *this;
1201 }
1202
1203 TestCase::TestCase(funcType test, const char* file, unsigned line, const TestSuite& test_suite,
1204 const String& type, int template_id) {
1205 m_file = file;
1206 m_line = line;
1207 m_name = nullptr; // will be later overridden in operator*
1208 m_test_suite = test_suite.m_test_suite;
1209 m_description = test_suite.m_description;
1210 m_skip = test_suite.m_skip;
1211 m_no_breaks = test_suite.m_no_breaks;
1212 m_no_output = test_suite.m_no_output;
1213 m_may_fail = test_suite.m_may_fail;
1214 m_should_fail = test_suite.m_should_fail;
1215 m_expected_failures = test_suite.m_expected_failures;
1216 m_timeout = test_suite.m_timeout;
1217
1218 m_test = test;
1219 m_type = type;
1220 m_template_id = template_id;
1221 }
1222
1223 TestCase::TestCase(const TestCase& other)
1224 : TestCaseData() {
1225 *this = other;
1226 }
1227
1228 DOCTEST_MSVC_SUPPRESS_WARNING_WITH_PUSH(26434) // hides a non-virtual function
1229 TestCase& TestCase::operator=(const TestCase& other) {
1230 TestCaseData::operator=(other);
1231 m_test = other.m_test;
1232 m_type = other.m_type;
1233 m_template_id = other.m_template_id;
1234 m_full_name = other.m_full_name;
1235
1236 if(m_template_id != -1)
1237 m_name = m_full_name.c_str();
1238 return *this;
1239 }
1240 DOCTEST_MSVC_SUPPRESS_WARNING_POP
1241
1242 TestCase& TestCase::operator*(const char* in) {
1243 m_name = in;
1244 // make a new name with an appended type for templated test case
1245 if(m_template_id != -1) {
1246 m_full_name = String(m_name) + "<" + m_type + ">";
1247 // redirect the name to point to the newly constructed full name
1248 m_name = m_full_name.c_str();
1249 }
1250 return *this;
1251 }
1252
1253 bool TestCase::operator<(const TestCase& other) const {
1254 // this will be used only to differentiate between test cases - not relevant for sorting
1255 if(m_line != other.m_line)
1256 return m_line < other.m_line;
1257 const int name_cmp = strcmp(m_name, other.m_name);
1258 if(name_cmp != 0)
1259 return name_cmp < 0;
1260 const int file_cmp = m_file.compare(other.m_file);
1261 if(file_cmp != 0)
1262 return file_cmp < 0;
1263 return m_template_id < other.m_template_id;
1264 }
1265
1266 // all the registered tests
1267 std::set<TestCase>& getRegisteredTests() {
1268 static std::set<TestCase> data;
1269 return data;
1270 }
1271} // namespace detail
1272namespace {
1273 using namespace detail;
1274 // for sorting tests by file/line
1275 bool fileOrderComparator(const TestCase* lhs, const TestCase* rhs) {
1276 // this is needed because MSVC gives different case for drive letters
1277 // for __FILE__ when evaluated in a header and a source file
1278 const int res = lhs->m_file.compare(rhs->m_file, bool(DOCTEST_MSVC));
1279 if(res != 0)
1280 return res < 0;
1281 if(lhs->m_line != rhs->m_line)
1282 return lhs->m_line < rhs->m_line;
1283 return lhs->m_template_id < rhs->m_template_id;
1284 }
1285
1286 // for sorting tests by suite/file/line
1287 bool suiteOrderComparator(const TestCase* lhs, const TestCase* rhs) {
1288 const int res = std::strcmp(lhs->m_test_suite, rhs->m_test_suite);
1289 if(res != 0)
1290 return res < 0;
1291 return fileOrderComparator(lhs, rhs);
1292 }
1293
1294 // for sorting tests by name/suite/file/line
1295 bool nameOrderComparator(const TestCase* lhs, const TestCase* rhs) {
1296 const int res = std::strcmp(lhs->m_name, rhs->m_name);
1297 if(res != 0)
1298 return res < 0;
1299 return suiteOrderComparator(lhs, rhs);
1300 }
1301
1302 DOCTEST_CLANG_SUPPRESS_WARNING_WITH_PUSH("-Wdeprecated-declarations")
1303 void color_to_stream(std::ostream& s, Color::Enum code) {
1304 static_cast<void>(s); // for DOCTEST_CONFIG_COLORS_NONE or DOCTEST_CONFIG_COLORS_WINDOWS
1305 static_cast<void>(code); // for DOCTEST_CONFIG_COLORS_NONE
1306#ifdef DOCTEST_CONFIG_COLORS_ANSI
1307 if(g_no_colors ||
1308 (isatty(STDOUT_FILENO) == false && getContextOptions()->force_colors == false))
1309 return;
1310
1311 auto col = "";
1312 // clang-format off
1313 switch(code) {
1314 case Color::Red: col = "[0;31m"; break;
1315 case Color::Green: col = "[0;32m"; break;
1316 case Color::Blue: col = "[0;34m"; break;
1317 case Color::Cyan: col = "[0;36m"; break;
1318 case Color::Yellow: col = "[0;33m"; break;
1319 case Color::Grey: col = "[1;30m"; break;
1320 case Color::LightGrey: col = "[0;37m"; break;
1321 case Color::BrightRed: col = "[1;31m"; break;
1322 case Color::BrightGreen: col = "[1;32m"; break;
1323 case Color::BrightWhite: col = "[1;37m"; break;
1324 case Color::Bright: // invalid
1325 case Color::None:
1326 case Color::White:
1327 default: col = "[0m";
1328 }
1329 // clang-format on
1330 s << "\033" << col;
1331#endif // DOCTEST_CONFIG_COLORS_ANSI
1332
1333#ifdef DOCTEST_CONFIG_COLORS_WINDOWS
1334 if(g_no_colors ||
1335 (_isatty(_fileno(stdout)) == false && getContextOptions()->force_colors == false))
1336 return;
1337
1338 static struct ConsoleHelper {
1339 HANDLE stdoutHandle;
1340 WORD origFgAttrs;
1341 WORD origBgAttrs;
1342
1343 ConsoleHelper() {
1344 stdoutHandle = GetStdHandle(STD_OUTPUT_HANDLE);
1345 CONSOLE_SCREEN_BUFFER_INFO csbiInfo;
1346 GetConsoleScreenBufferInfo(stdoutHandle, &csbiInfo);
1347 origFgAttrs = csbiInfo.wAttributes & ~(BACKGROUND_GREEN | BACKGROUND_RED |
1348 BACKGROUND_BLUE | BACKGROUND_INTENSITY);
1349 origBgAttrs = csbiInfo.wAttributes & ~(FOREGROUND_GREEN | FOREGROUND_RED |
1350 FOREGROUND_BLUE | FOREGROUND_INTENSITY);
1351 }
1352 } ch;
1353
1354#define DOCTEST_SET_ATTR(x) SetConsoleTextAttribute(ch.stdoutHandle, x | ch.origBgAttrs)
1355
1356 // clang-format off
1357 switch (code) {
1358 case Color::White: DOCTEST_SET_ATTR(FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_BLUE); break;
1359 case Color::Red: DOCTEST_SET_ATTR(FOREGROUND_RED); break;
1360 case Color::Green: DOCTEST_SET_ATTR(FOREGROUND_GREEN); break;
1361 case Color::Blue: DOCTEST_SET_ATTR(FOREGROUND_BLUE); break;
1362 case Color::Cyan: DOCTEST_SET_ATTR(FOREGROUND_BLUE | FOREGROUND_GREEN); break;
1363 case Color::Yellow: DOCTEST_SET_ATTR(FOREGROUND_RED | FOREGROUND_GREEN); break;
1364 case Color::Grey: DOCTEST_SET_ATTR(0); break;
1365 case Color::LightGrey: DOCTEST_SET_ATTR(FOREGROUND_INTENSITY); break;
1366 case Color::BrightRed: DOCTEST_SET_ATTR(FOREGROUND_INTENSITY | FOREGROUND_RED); break;
1367 case Color::BrightGreen: DOCTEST_SET_ATTR(FOREGROUND_INTENSITY | FOREGROUND_GREEN); break;
1368 case Color::BrightWhite: DOCTEST_SET_ATTR(FOREGROUND_INTENSITY | FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_BLUE); break;
1369 case Color::None:
1370 case Color::Bright: // invalid
1371 default: DOCTEST_SET_ATTR(ch.origFgAttrs);
1372 }
1373 // clang-format on
1374#endif // DOCTEST_CONFIG_COLORS_WINDOWS
1375 }
1376 DOCTEST_CLANG_SUPPRESS_WARNING_POP
1377
1378 std::vector<const IExceptionTranslator*>& getExceptionTranslators() {
1379 static std::vector<const IExceptionTranslator*> data;
1380 return data;
1381 }
1382
1383 String translateActiveException() {
1384#ifndef DOCTEST_CONFIG_NO_EXCEPTIONS
1385 String res;
1386 auto& translators = getExceptionTranslators();
1387 for(auto& curr : translators)
1388 if(curr->translate(res))
1389 return res;
1390 // clang-format off
1391 DOCTEST_GCC_SUPPRESS_WARNING_WITH_PUSH("-Wcatch-value")
1392 try {
1393 throw;
1394 } catch(std::exception& ex) {
1395 return ex.what();
1396 } catch(std::string& msg) {
1397 return msg.c_str();
1398 } catch(const char* msg) {
1399 return msg;
1400 } catch(...) {
1401 return "unknown exception";
1402 }
1403 DOCTEST_GCC_SUPPRESS_WARNING_POP
1404// clang-format on
1405#else // DOCTEST_CONFIG_NO_EXCEPTIONS
1406 return "";
1407#endif // DOCTEST_CONFIG_NO_EXCEPTIONS
1408 }
1409} // namespace
1410
1411namespace detail {
1412 // used by the macros for registering tests
1413 int regTest(const TestCase& tc) {
1414 getRegisteredTests().insert(tc);
1415 return 0;
1416 }
1417
1418 // sets the current test suite
1419 int setTestSuite(const TestSuite& ts) {
1420 doctest_detail_test_suite_ns::getCurrentTestSuite() = ts;
1421 return 0;
1422 }
1423
1424#ifdef DOCTEST_IS_DEBUGGER_ACTIVE
1425 bool isDebuggerActive() { return DOCTEST_IS_DEBUGGER_ACTIVE(); }
1426#else // DOCTEST_IS_DEBUGGER_ACTIVE
1427#ifdef DOCTEST_PLATFORM_LINUX
1429 public:
1430 ErrnoGuard() : m_oldErrno(errno) {}
1431 ~ErrnoGuard() { errno = m_oldErrno; }
1432 private:
1433 int m_oldErrno;
1434 };
1435 // See the comments in Catch2 for the reasoning behind this implementation:
1436 // https://github.com/catchorg/Catch2/blob/v2.13.1/include/internal/catch_debugger.cpp#L79-L102
1437 bool isDebuggerActive() {
1438 ErrnoGuard guard;
1439 std::ifstream in("/proc/self/status");
1440 for(std::string line; std::getline(in, line);) {
1441 static const int PREFIX_LEN = 11;
1442 if(line.compare(0, PREFIX_LEN, "TracerPid:\t") == 0) {
1443 return line.length() > PREFIX_LEN && line[PREFIX_LEN] != '0';
1444 }
1445 }
1446 return false;
1447 }
1448#elif defined(DOCTEST_PLATFORM_MAC)
1449 // The following function is taken directly from the following technical note:
1450 // https://developer.apple.com/library/archive/qa/qa1361/_index.html
1451 // Returns true if the current process is being debugged (either
1452 // running under the debugger or has a debugger attached post facto).
1453 bool isDebuggerActive() {
1454 int mib[4];
1455 kinfo_proc info;
1456 size_t size;
1457 // Initialize the flags so that, if sysctl fails for some bizarre
1458 // reason, we get a predictable result.
1459 info.kp_proc.p_flag = 0;
1460 // Initialize mib, which tells sysctl the info we want, in this case
1461 // we're looking for information about a specific process ID.
1462 mib[0] = CTL_KERN;
1463 mib[1] = KERN_PROC;
1464 mib[2] = KERN_PROC_PID;
1465 mib[3] = getpid();
1466 // Call sysctl.
1467 size = sizeof(info);
1468 if(sysctl(mib, DOCTEST_COUNTOF(mib), &info, &size, 0, 0) != 0) {
1469 std::cerr << "\nCall to sysctl failed - unable to determine if debugger is active **\n";
1470 return false;
1471 }
1472 // We're being debugged if the P_TRACED flag is set.
1473 return ((info.kp_proc.p_flag & P_TRACED) != 0);
1474 }
1475#elif DOCTEST_MSVC || defined(__MINGW32__) || defined(__MINGW64__)
1476 bool isDebuggerActive() { return ::IsDebuggerPresent() != 0; }
1477#else
1478 bool isDebuggerActive() { return false; }
1479#endif // Platform
1480#endif // DOCTEST_IS_DEBUGGER_ACTIVE
1481
1482 void registerExceptionTranslatorImpl(const IExceptionTranslator* et) {
1483 if(std::find(getExceptionTranslators().begin(), getExceptionTranslators().end(), et) ==
1484 getExceptionTranslators().end())
1485 getExceptionTranslators().push_back(et);
1486 }
1487
1488 DOCTEST_THREAD_LOCAL std::vector<IContextScope*> g_infoContexts; // for logging with INFO()
1489
1490 ContextScopeBase::ContextScopeBase() {
1491 g_infoContexts.push_back(this);
1492 }
1493
1494 ContextScopeBase::ContextScopeBase(ContextScopeBase&& other) noexcept {
1495 if (other.need_to_destroy) {
1496 other.destroy();
1497 }
1498 other.need_to_destroy = false;
1499 g_infoContexts.push_back(this);
1500 }
1501
1502 DOCTEST_MSVC_SUPPRESS_WARNING_WITH_PUSH(4996) // std::uncaught_exception is deprecated in C++17
1503 DOCTEST_GCC_SUPPRESS_WARNING_WITH_PUSH("-Wdeprecated-declarations")
1504 DOCTEST_CLANG_SUPPRESS_WARNING_WITH_PUSH("-Wdeprecated-declarations")
1505
1506 // destroy cannot be inlined into the destructor because that would mean calling stringify after
1507 // ContextScope has been destroyed (base class destructors run after derived class destructors).
1508 // Instead, ContextScope calls this method directly from its destructor.
1509 void ContextScopeBase::destroy() {
1510#if defined(__cpp_lib_uncaught_exceptions) && __cpp_lib_uncaught_exceptions >= 201411L && (!defined(__MAC_OS_X_VERSION_MIN_REQUIRED) || __MAC_OS_X_VERSION_MIN_REQUIRED >= 101200)
1511 if(std::uncaught_exceptions() > 0) {
1512#else
1513 if(std::uncaught_exception()) {
1514#endif
1515 std::ostringstream s;
1516 this->stringify(&s);
1517 g_cs->stringifiedContexts.push_back(s.str().c_str());
1518 }
1519 g_infoContexts.pop_back();
1520 }
1521
1522 DOCTEST_CLANG_SUPPRESS_WARNING_POP
1523 DOCTEST_GCC_SUPPRESS_WARNING_POP
1524 DOCTEST_MSVC_SUPPRESS_WARNING_POP
1525} // namespace detail
1526namespace {
1527 using namespace detail;
1528
1529#if !defined(DOCTEST_CONFIG_POSIX_SIGNALS) && !defined(DOCTEST_CONFIG_WINDOWS_SEH)
1530 struct FatalConditionHandler
1531 {
1532 static void reset() {}
1533 static void allocateAltStackMem() {}
1534 static void freeAltStackMem() {}
1535 };
1536#else // DOCTEST_CONFIG_POSIX_SIGNALS || DOCTEST_CONFIG_WINDOWS_SEH
1537
1538 void reportFatal(const std::string&);
1539
1540#ifdef DOCTEST_PLATFORM_WINDOWS
1541
1542 struct SignalDefs
1543 {
1544 DWORD id;
1545 const char* name;
1546 };
1547 // There is no 1-1 mapping between signals and windows exceptions.
1548 // Windows can easily distinguish between SO and SigSegV,
1549 // but SigInt, SigTerm, etc are handled differently.
1550 SignalDefs signalDefs[] = {
1551 {static_cast<DWORD>(EXCEPTION_ILLEGAL_INSTRUCTION),
1552 "SIGILL - Illegal instruction signal"},
1553 {static_cast<DWORD>(EXCEPTION_STACK_OVERFLOW), "SIGSEGV - Stack overflow"},
1554 {static_cast<DWORD>(EXCEPTION_ACCESS_VIOLATION),
1555 "SIGSEGV - Segmentation violation signal"},
1556 {static_cast<DWORD>(EXCEPTION_INT_DIVIDE_BY_ZERO), "Divide by zero error"},
1557 };
1558
1559 struct FatalConditionHandler
1560 {
1561 static LONG CALLBACK handleException(PEXCEPTION_POINTERS ExceptionInfo) {
1562 // Multiple threads may enter this filter/handler at once. We want the error message to be printed on the
1563 // console just once no matter how many threads have crashed.
1564 DOCTEST_DECLARE_STATIC_MUTEX(mutex)
1565 static bool execute = true;
1566 {
1567 DOCTEST_LOCK_MUTEX(mutex)
1568 if(execute) {
1569 bool reported = false;
1570 for(size_t i = 0; i < DOCTEST_COUNTOF(signalDefs); ++i) {
1571 if(ExceptionInfo->ExceptionRecord->ExceptionCode == signalDefs[i].id) {
1572 reportFatal(signalDefs[i].name);
1573 reported = true;
1574 break;
1575 }
1576 }
1577 if(reported == false)
1578 reportFatal("Unhandled SEH exception caught");
1579 if(isDebuggerActive() && !g_cs->no_breaks)
1580 DOCTEST_BREAK_INTO_DEBUGGER();
1581 }
1582 execute = false;
1583 }
1584 std::exit(EXIT_FAILURE);
1585 }
1586
1587 static void allocateAltStackMem() {}
1588 static void freeAltStackMem() {}
1589
1590 FatalConditionHandler() {
1591 isSet = true;
1592 // 32k seems enough for doctest to handle stack overflow,
1593 // but the value was found experimentally, so there is no strong guarantee
1594 guaranteeSize = 32 * 1024;
1595 // Register an unhandled exception filter
1596 previousTop = SetUnhandledExceptionFilter(handleException);
1597 // Pass in guarantee size to be filled
1598 SetThreadStackGuarantee(&guaranteeSize);
1599
1600 // On Windows uncaught exceptions from another thread, exceptions from
1601 // destructors, or calls to std::terminate are not a SEH exception
1602
1603 // The terminal handler gets called when:
1604 // - std::terminate is called FROM THE TEST RUNNER THREAD
1605 // - an exception is thrown from a destructor FROM THE TEST RUNNER THREAD
1606 original_terminate_handler = std::get_terminate();
1607 std::set_terminate([]() DOCTEST_NOEXCEPT {
1608 reportFatal("Terminate handler called");
1609 if(isDebuggerActive() && !g_cs->no_breaks)
1610 DOCTEST_BREAK_INTO_DEBUGGER();
1611 std::exit(EXIT_FAILURE); // explicitly exit - otherwise the SIGABRT handler may be called as well
1612 });
1613
1614 // SIGABRT is raised when:
1615 // - std::terminate is called FROM A DIFFERENT THREAD
1616 // - an exception is thrown from a destructor FROM A DIFFERENT THREAD
1617 // - an uncaught exception is thrown FROM A DIFFERENT THREAD
1618 prev_sigabrt_handler = std::signal(SIGABRT, [](int signal) DOCTEST_NOEXCEPT {
1619 if(signal == SIGABRT) {
1620 reportFatal("SIGABRT - Abort (abnormal termination) signal");
1621 if(isDebuggerActive() && !g_cs->no_breaks)
1622 DOCTEST_BREAK_INTO_DEBUGGER();
1623 std::exit(EXIT_FAILURE);
1624 }
1625 });
1626
1627 // The following settings are taken from google test, and more
1628 // specifically from UnitTest::Run() inside of gtest.cc
1629
1630 // the user does not want to see pop-up dialogs about crashes
1631 prev_error_mode_1 = SetErrorMode(SEM_FAILCRITICALERRORS | SEM_NOALIGNMENTFAULTEXCEPT |
1632 SEM_NOGPFAULTERRORBOX | SEM_NOOPENFILEERRORBOX);
1633 // This forces the abort message to go to stderr in all circumstances.
1634 prev_error_mode_2 = _set_error_mode(_OUT_TO_STDERR);
1635 // In the debug version, Visual Studio pops up a separate dialog
1636 // offering a choice to debug the aborted program - we want to disable that.
1637 prev_abort_behavior = _set_abort_behavior(0x0, _WRITE_ABORT_MSG | _CALL_REPORTFAULT);
1638 // In debug mode, the Windows CRT can crash with an assertion over invalid
1639 // input (e.g. passing an invalid file descriptor). The default handling
1640 // for these assertions is to pop up a dialog and wait for user input.
1641 // Instead ask the CRT to dump such assertions to stderr non-interactively.
1642 prev_report_mode = _CrtSetReportMode(_CRT_ASSERT, _CRTDBG_MODE_FILE | _CRTDBG_MODE_DEBUG);
1643 prev_report_file = _CrtSetReportFile(_CRT_ASSERT, _CRTDBG_FILE_STDERR);
1644 }
1645
1646 static void reset() {
1647 if(isSet) {
1648 // Unregister handler and restore the old guarantee
1649 SetUnhandledExceptionFilter(previousTop);
1650 SetThreadStackGuarantee(&guaranteeSize);
1651 std::set_terminate(original_terminate_handler);
1652 std::signal(SIGABRT, prev_sigabrt_handler);
1653 SetErrorMode(prev_error_mode_1);
1654 _set_error_mode(prev_error_mode_2);
1655 _set_abort_behavior(prev_abort_behavior, _WRITE_ABORT_MSG | _CALL_REPORTFAULT);
1656 static_cast<void>(_CrtSetReportMode(_CRT_ASSERT, prev_report_mode));
1657 static_cast<void>(_CrtSetReportFile(_CRT_ASSERT, prev_report_file));
1658 isSet = false;
1659 }
1660 }
1661
1662 ~FatalConditionHandler() { reset(); }
1663
1664 private:
1665 static UINT prev_error_mode_1;
1666 static int prev_error_mode_2;
1667 static unsigned int prev_abort_behavior;
1668 static int prev_report_mode;
1669 static _HFILE prev_report_file;
1670 static void (DOCTEST_CDECL *prev_sigabrt_handler)(int);
1671 static std::terminate_handler original_terminate_handler;
1672 static bool isSet;
1673 static ULONG guaranteeSize;
1674 static LPTOP_LEVEL_EXCEPTION_FILTER previousTop;
1675 };
1676
1677 UINT FatalConditionHandler::prev_error_mode_1;
1678 int FatalConditionHandler::prev_error_mode_2;
1679 unsigned int FatalConditionHandler::prev_abort_behavior;
1680 int FatalConditionHandler::prev_report_mode;
1681 _HFILE FatalConditionHandler::prev_report_file;
1682 void (DOCTEST_CDECL *FatalConditionHandler::prev_sigabrt_handler)(int);
1683 std::terminate_handler FatalConditionHandler::original_terminate_handler;
1684 bool FatalConditionHandler::isSet = false;
1685 ULONG FatalConditionHandler::guaranteeSize = 0;
1686 LPTOP_LEVEL_EXCEPTION_FILTER FatalConditionHandler::previousTop = nullptr;
1687
1688#else // DOCTEST_PLATFORM_WINDOWS
1689
1690 struct SignalDefs
1691 {
1692 int id;
1693 const char* name;
1694 };
1695 SignalDefs signalDefs[] = {{SIGINT, "SIGINT - Terminal interrupt signal"},
1696 {SIGILL, "SIGILL - Illegal instruction signal"},
1697 {SIGFPE, "SIGFPE - Floating point error signal"},
1698 {SIGSEGV, "SIGSEGV - Segmentation violation signal"},
1699 {SIGTERM, "SIGTERM - Termination request signal"},
1700 {SIGABRT, "SIGABRT - Abort (abnormal termination) signal"}};
1701
1702 struct FatalConditionHandler
1703 {
1704 static bool isSet;
1705 static struct sigaction oldSigActions[DOCTEST_COUNTOF(signalDefs)];
1706 static stack_t oldSigStack;
1707 static size_t altStackSize;
1708 static char* altStackMem;
1709
1710 static void handleSignal(int sig) {
1711 const char* name = "<unknown signal>";
1712 for(std::size_t i = 0; i < DOCTEST_COUNTOF(signalDefs); ++i) {
1713 SignalDefs& def = signalDefs[i];
1714 if(sig == def.id) {
1715 name = def.name;
1716 break;
1717 }
1718 }
1719 reset();
1720 reportFatal(name);
1721 raise(sig);
1722 }
1723
1724 static void allocateAltStackMem() {
1725 altStackMem = new char[altStackSize];
1726 }
1727
1728 static void freeAltStackMem() {
1729 delete[] altStackMem;
1730 }
1731
1732 FatalConditionHandler() {
1733 isSet = true;
1734 stack_t sigStack;
1735 sigStack.ss_sp = altStackMem;
1736 sigStack.ss_size = altStackSize;
1737 sigStack.ss_flags = 0;
1738 sigaltstack(&sigStack, &oldSigStack);
1739 struct sigaction sa = {};
1740 sa.sa_handler = handleSignal;
1741 sa.sa_flags = SA_ONSTACK;
1742 for(std::size_t i = 0; i < DOCTEST_COUNTOF(signalDefs); ++i) {
1743 sigaction(signalDefs[i].id, &sa, &oldSigActions[i]);
1744 }
1745 }
1746
1747 ~FatalConditionHandler() { reset(); }
1748 static void reset() {
1749 if(isSet) {
1750 // Set signals back to previous values -- hopefully nobody overwrote them in the meantime
1751 for(std::size_t i = 0; i < DOCTEST_COUNTOF(signalDefs); ++i) {
1752 sigaction(signalDefs[i].id, &oldSigActions[i], nullptr);
1753 }
1754 // Return the old stack
1755 sigaltstack(&oldSigStack, nullptr);
1756 isSet = false;
1757 }
1758 }
1759 };
1760
1761 bool FatalConditionHandler::isSet = false;
1762 struct sigaction FatalConditionHandler::oldSigActions[DOCTEST_COUNTOF(signalDefs)] = {};
1763 stack_t FatalConditionHandler::oldSigStack = {};
1764 size_t FatalConditionHandler::altStackSize = 4 * SIGSTKSZ;
1765 char* FatalConditionHandler::altStackMem = nullptr;
1766
1767#endif // DOCTEST_PLATFORM_WINDOWS
1768#endif // DOCTEST_CONFIG_POSIX_SIGNALS || DOCTEST_CONFIG_WINDOWS_SEH
1769
1770} // namespace
1771
1772namespace {
1773 using namespace detail;
1774
1775#ifdef DOCTEST_PLATFORM_WINDOWS
1776#define DOCTEST_OUTPUT_DEBUG_STRING(text) ::OutputDebugStringA(text)
1777#else
1778 // TODO: integration with XCode and other IDEs
1779#define DOCTEST_OUTPUT_DEBUG_STRING(text)
1780#endif // Platform
1781
1782 void addAssert(assertType::Enum at) {
1783 if((at & assertType::is_warn) == 0)
1784 g_cs->numAssertsCurrentTest_atomic++;
1785 }
1786
1787 void addFailedAssert(assertType::Enum at) {
1788 if((at & assertType::is_warn) == 0)
1789 g_cs->numAssertsFailedCurrentTest_atomic++;
1790 }
1791
1792#if defined(DOCTEST_CONFIG_POSIX_SIGNALS) || defined(DOCTEST_CONFIG_WINDOWS_SEH)
1793 void reportFatal(const std::string& message) {
1794 g_cs->failure_flags |= TestCaseFailureReason::Crash;
1795
1796 DOCTEST_ITERATE_THROUGH_REPORTERS(test_case_exception, {message.c_str(), true});
1797
1798 while (g_cs->subcaseStack.size()) {
1799 g_cs->subcaseStack.pop_back();
1800 DOCTEST_ITERATE_THROUGH_REPORTERS(subcase_end, DOCTEST_EMPTY);
1801 }
1802
1803 g_cs->finalizeTestCaseData();
1804
1805 DOCTEST_ITERATE_THROUGH_REPORTERS(test_case_end, *g_cs);
1806
1807 DOCTEST_ITERATE_THROUGH_REPORTERS(test_run_end, *g_cs);
1808 }
1809#endif // DOCTEST_CONFIG_POSIX_SIGNALS || DOCTEST_CONFIG_WINDOWS_SEH
1810} // namespace
1811
1812AssertData::AssertData(assertType::Enum at, const char* file, int line, const char* expr,
1813 const char* exception_type, const StringContains& exception_string)
1814 : m_test_case(g_cs->currentTest), m_at(at), m_file(file), m_line(line), m_expr(expr),
1815 m_failed(true), m_threw(false), m_threw_as(false), m_exception_type(exception_type),
1816 m_exception_string(exception_string) {
1817#if DOCTEST_MSVC
1818 if (m_expr[0] == ' ') // this happens when variadic macros are disabled under MSVC
1819 ++m_expr;
1820#endif // MSVC
1821}
1822
1823namespace detail {
1824 ResultBuilder::ResultBuilder(assertType::Enum at, const char* file, int line, const char* expr,
1825 const char* exception_type, const String& exception_string)
1826 : AssertData(at, file, line, expr, exception_type, exception_string) { }
1827
1828 ResultBuilder::ResultBuilder(assertType::Enum at, const char* file, int line, const char* expr,
1829 const char* exception_type, const Contains& exception_string)
1830 : AssertData(at, file, line, expr, exception_type, exception_string) { }
1831
1832 void ResultBuilder::setResult(const Result& res) {
1833 m_decomp = res.m_decomp;
1834 m_failed = !res.m_passed;
1835 }
1836
1837 void ResultBuilder::translateException() {
1838 m_threw = true;
1839 m_exception = translateActiveException();
1840 }
1841
1843 if(m_at & assertType::is_throws) {
1844 m_failed = !m_threw;
1845 } else if((m_at & assertType::is_throws_as) && (m_at & assertType::is_throws_with)) {
1846 m_failed = !m_threw_as || !m_exception_string.check(m_exception);
1847 } else if(m_at & assertType::is_throws_as) {
1848 m_failed = !m_threw_as;
1849 } else if(m_at & assertType::is_throws_with) {
1850 m_failed = !m_exception_string.check(m_exception);
1851 } else if(m_at & assertType::is_nothrow) {
1852 m_failed = m_threw;
1853 }
1854
1855 if(m_exception.size())
1856 m_exception = "\"" + m_exception + "\"";
1857
1858 if(is_running_in_test) {
1859 addAssert(m_at);
1860 DOCTEST_ITERATE_THROUGH_REPORTERS(log_assert, *this);
1861
1862 if(m_failed)
1863 addFailedAssert(m_at);
1864 } else if(m_failed) {
1865 failed_out_of_a_testing_context(*this);
1866 }
1867
1868 return m_failed && isDebuggerActive() && !getContextOptions()->no_breaks &&
1869 (g_cs->currentTest == nullptr || !g_cs->currentTest->m_no_breaks); // break into debugger
1870 }
1871
1872 void ResultBuilder::react() const {
1873 if(m_failed && checkIfShouldThrow(m_at))
1874 throwException();
1875 }
1876
1877 void failed_out_of_a_testing_context(const AssertData& ad) {
1878 if(g_cs->ah)
1879 g_cs->ah(ad);
1880 else
1881 std::abort();
1882 }
1883
1884 bool decomp_assert(assertType::Enum at, const char* file, int line, const char* expr,
1885 const Result& result) {
1886 bool failed = !result.m_passed;
1887
1888 // ###################################################################################
1889 // IF THE DEBUGGER BREAKS HERE - GO 1 LEVEL UP IN THE CALLSTACK FOR THE FAILING ASSERT
1890 // THIS IS THE EFFECT OF HAVING 'DOCTEST_CONFIG_SUPER_FAST_ASSERTS' DEFINED
1891 // ###################################################################################
1892 DOCTEST_ASSERT_OUT_OF_TESTS(result.m_decomp);
1893 DOCTEST_ASSERT_IN_TESTS(result.m_decomp);
1894 return !failed;
1895 }
1896
1897 MessageBuilder::MessageBuilder(const char* file, int line, assertType::Enum severity) {
1898 m_stream = tlssPush();
1899 m_file = file;
1900 m_line = line;
1901 m_severity = severity;
1902 }
1903
1904 MessageBuilder::~MessageBuilder() {
1905 if (!logged)
1906 tlssPop();
1907 }
1908
1909 DOCTEST_DEFINE_INTERFACE(IExceptionTranslator)
1910
1911 bool MessageBuilder::log() {
1912 if (!logged) {
1913 m_string = tlssPop();
1914 logged = true;
1915 }
1916
1917 DOCTEST_ITERATE_THROUGH_REPORTERS(log_message, *this);
1918
1919 const bool isWarn = m_severity & assertType::is_warn;
1920
1921 // warn is just a message in this context so we don't treat it as an assert
1922 if(!isWarn) {
1923 addAssert(m_severity);
1924 addFailedAssert(m_severity);
1925 }
1926
1927 return isDebuggerActive() && !getContextOptions()->no_breaks && !isWarn &&
1928 (g_cs->currentTest == nullptr || !g_cs->currentTest->m_no_breaks); // break into debugger
1929 }
1930
1932 if(m_severity & assertType::is_require)
1933 throwException();
1934 }
1935} // namespace detail
1936namespace {
1937 using namespace detail;
1938
1939 // clang-format off
1940
1941// =================================================================================================
1942// The following code has been taken verbatim from Catch2/include/internal/catch_xmlwriter.h/cpp
1943// This is done so cherry-picking bug fixes is trivial - even the style/formatting is untouched.
1944// =================================================================================================
1945
1946 class XmlEncode {
1947 public:
1948 enum ForWhat { ForTextNodes, ForAttributes };
1949
1950 XmlEncode( std::string const& str, ForWhat forWhat = ForTextNodes );
1951
1952 void encodeTo( std::ostream& os ) const;
1953
1954 friend std::ostream& operator << ( std::ostream& os, XmlEncode const& xmlEncode );
1955
1956 private:
1957 std::string m_str;
1958 ForWhat m_forWhat;
1959 };
1960
1961 class XmlWriter {
1962 public:
1963
1964 class ScopedElement {
1965 public:
1966 ScopedElement( XmlWriter* writer );
1967
1968 ScopedElement( ScopedElement&& other ) DOCTEST_NOEXCEPT;
1969 ScopedElement& operator=( ScopedElement&& other ) DOCTEST_NOEXCEPT;
1970
1971 ~ScopedElement();
1972
1973 ScopedElement& writeText( std::string const& text, bool indent = true );
1974
1975 template<typename T>
1976 ScopedElement& writeAttribute( std::string const& name, T const& attribute ) {
1977 m_writer->writeAttribute( name, attribute );
1978 return *this;
1979 }
1980
1981 private:
1982 mutable XmlWriter* m_writer = nullptr;
1983 };
1984
1985#ifndef DOCTEST_CONFIG_NO_INCLUDE_IOSTREAM
1986 XmlWriter( std::ostream& os = std::cout );
1987#else // DOCTEST_CONFIG_NO_INCLUDE_IOSTREAM
1988 XmlWriter( std::ostream& os );
1989#endif // DOCTEST_CONFIG_NO_INCLUDE_IOSTREAM
1990 ~XmlWriter();
1991
1992 XmlWriter( XmlWriter const& ) = delete;
1993 XmlWriter& operator=( XmlWriter const& ) = delete;
1994
1995 XmlWriter& startElement( std::string const& name );
1996
1997 ScopedElement scopedElement( std::string const& name );
1998
1999 XmlWriter& endElement();
2000
2001 XmlWriter& writeAttribute( std::string const& name, std::string const& attribute );
2002
2003 XmlWriter& writeAttribute( std::string const& name, const char* attribute );
2004
2005 XmlWriter& writeAttribute( std::string const& name, bool attribute );
2006
2007 template<typename T>
2008 XmlWriter& writeAttribute( std::string const& name, T const& attribute ) {
2009 std::stringstream rss;
2010 rss << attribute;
2011 return writeAttribute( name, rss.str() );
2012 }
2013
2014 XmlWriter& writeText( std::string const& text, bool indent = true );
2015
2016 //XmlWriter& writeComment( std::string const& text );
2017
2018 //void writeStylesheetRef( std::string const& url );
2019
2020 //XmlWriter& writeBlankLine();
2021
2022 void ensureTagClosed();
2023
2024 void writeDeclaration();
2025
2026 private:
2027
2028 void newlineIfNecessary();
2029
2030 bool m_tagIsOpen = false;
2031 bool m_needsNewline = false;
2032 std::vector<std::string> m_tags;
2033 std::string m_indent;
2034 std::ostream& m_os;
2035 };
2036
2037// =================================================================================================
2038// The following code has been taken verbatim from Catch2/include/internal/catch_xmlwriter.h/cpp
2039// This is done so cherry-picking bug fixes is trivial - even the style/formatting is untouched.
2040// =================================================================================================
2041
2042using uchar = unsigned char;
2043
2044namespace {
2045
2046 size_t trailingBytes(unsigned char c) {
2047 if ((c & 0xE0) == 0xC0) {
2048 return 2;
2049 }
2050 if ((c & 0xF0) == 0xE0) {
2051 return 3;
2052 }
2053 if ((c & 0xF8) == 0xF0) {
2054 return 4;
2055 }
2056 DOCTEST_INTERNAL_ERROR("Invalid multibyte utf-8 start byte encountered");
2057 }
2058
2059 uint32_t headerValue(unsigned char c) {
2060 if ((c & 0xE0) == 0xC0) {
2061 return c & 0x1F;
2062 }
2063 if ((c & 0xF0) == 0xE0) {
2064 return c & 0x0F;
2065 }
2066 if ((c & 0xF8) == 0xF0) {
2067 return c & 0x07;
2068 }
2069 DOCTEST_INTERNAL_ERROR("Invalid multibyte utf-8 start byte encountered");
2070 }
2071
2072 void hexEscapeChar(std::ostream& os, unsigned char c) {
2073 std::ios_base::fmtflags f(os.flags());
2074 os << "\\x"
2075 << std::uppercase << std::hex << std::setfill('0') << std::setw(2)
2076 << static_cast<int>(c);
2077 os.flags(f);
2078 }
2079
2080} // anonymous namespace
2081
2082 XmlEncode::XmlEncode( std::string const& str, ForWhat forWhat )
2083 : m_str( str ),
2084 m_forWhat( forWhat )
2085 {}
2086
2087 void XmlEncode::encodeTo( std::ostream& os ) const {
2088 // Apostrophe escaping not necessary if we always use " to write attributes
2089 // (see: https://www.w3.org/TR/xml/#syntax)
2090
2091 for( std::size_t idx = 0; idx < m_str.size(); ++ idx ) {
2092 uchar c = m_str[idx];
2093 switch (c) {
2094 case '<': os << "&lt;"; break;
2095 case '&': os << "&amp;"; break;
2096
2097 case '>':
2098 // See: https://www.w3.org/TR/xml/#syntax
2099 if (idx > 2 && m_str[idx - 1] == ']' && m_str[idx - 2] == ']')
2100 os << "&gt;";
2101 else
2102 os << c;
2103 break;
2104
2105 case '\"':
2106 if (m_forWhat == ForAttributes)
2107 os << "&quot;";
2108 else
2109 os << c;
2110 break;
2111
2112 default:
2113 // Check for control characters and invalid utf-8
2114
2115 // Escape control characters in standard ascii
2116 // see https://stackoverflow.com/questions/404107/why-are-control-characters-illegal-in-xml-1-0
2117 if (c < 0x09 || (c > 0x0D && c < 0x20) || c == 0x7F) {
2118 hexEscapeChar(os, c);
2119 break;
2120 }
2121
2122 // Plain ASCII: Write it to stream
2123 if (c < 0x7F) {
2124 os << c;
2125 break;
2126 }
2127
2128 // UTF-8 territory
2129 // Check if the encoding is valid and if it is not, hex escape bytes.
2130 // Important: We do not check the exact decoded values for validity, only the encoding format
2131 // First check that this bytes is a valid lead byte:
2132 // This means that it is not encoded as 1111 1XXX
2133 // Or as 10XX XXXX
2134 if (c < 0xC0 ||
2135 c >= 0xF8) {
2136 hexEscapeChar(os, c);
2137 break;
2138 }
2139
2140 auto encBytes = trailingBytes(c);
2141 // Are there enough bytes left to avoid accessing out-of-bounds memory?
2142 if (idx + encBytes - 1 >= m_str.size()) {
2143 hexEscapeChar(os, c);
2144 break;
2145 }
2146 // The header is valid, check data
2147 // The next encBytes bytes must together be a valid utf-8
2148 // This means: bitpattern 10XX XXXX and the extracted value is sane (ish)
2149 bool valid = true;
2150 uint32_t value = headerValue(c);
2151 for (std::size_t n = 1; n < encBytes; ++n) {
2152 uchar nc = m_str[idx + n];
2153 valid &= ((nc & 0xC0) == 0x80);
2154 value = (value << 6) | (nc & 0x3F);
2155 }
2156
2157 if (
2158 // Wrong bit pattern of following bytes
2159 (!valid) ||
2160 // Overlong encodings
2161 (value < 0x80) ||
2162 ( value < 0x800 && encBytes > 2) || // removed "0x80 <= value &&" because redundant
2163 (0x800 < value && value < 0x10000 && encBytes > 3) ||
2164 // Encoded value out of range
2165 (value >= 0x110000)
2166 ) {
2167 hexEscapeChar(os, c);
2168 break;
2169 }
2170
2171 // If we got here, this is in fact a valid(ish) utf-8 sequence
2172 for (std::size_t n = 0; n < encBytes; ++n) {
2173 os << m_str[idx + n];
2174 }
2175 idx += encBytes - 1;
2176 break;
2177 }
2178 }
2179 }
2180
2181 std::ostream& operator << ( std::ostream& os, XmlEncode const& xmlEncode ) {
2182 xmlEncode.encodeTo( os );
2183 return os;
2184 }
2185
2186 XmlWriter::ScopedElement::ScopedElement( XmlWriter* writer )
2187 : m_writer( writer )
2188 {}
2189
2190 XmlWriter::ScopedElement::ScopedElement( ScopedElement&& other ) DOCTEST_NOEXCEPT
2191 : m_writer( other.m_writer ){
2192 other.m_writer = nullptr;
2193 }
2194 XmlWriter::ScopedElement& XmlWriter::ScopedElement::operator=( ScopedElement&& other ) DOCTEST_NOEXCEPT {
2195 if ( m_writer ) {
2196 m_writer->endElement();
2197 }
2198 m_writer = other.m_writer;
2199 other.m_writer = nullptr;
2200 return *this;
2201 }
2202
2203
2204 XmlWriter::ScopedElement::~ScopedElement() {
2205 if( m_writer )
2206 m_writer->endElement();
2207 }
2208
2209 XmlWriter::ScopedElement& XmlWriter::ScopedElement::writeText( std::string const& text, bool indent ) {
2210 m_writer->writeText( text, indent );
2211 return *this;
2212 }
2213
2214 XmlWriter::XmlWriter( std::ostream& os ) : m_os( os )
2215 {
2216 // writeDeclaration(); // called explicitly by the reporters that use the writer class - see issue #627
2217 }
2218
2219 XmlWriter::~XmlWriter() {
2220 while( !m_tags.empty() )
2221 endElement();
2222 }
2223
2224 XmlWriter& XmlWriter::startElement( std::string const& name ) {
2225 ensureTagClosed();
2226 newlineIfNecessary();
2227 m_os << m_indent << '<' << name;
2228 m_tags.push_back( name );
2229 m_indent += " ";
2230 m_tagIsOpen = true;
2231 return *this;
2232 }
2233
2234 XmlWriter::ScopedElement XmlWriter::scopedElement( std::string const& name ) {
2235 ScopedElement scoped( this );
2236 startElement( name );
2237 return scoped;
2238 }
2239
2240 XmlWriter& XmlWriter::endElement() {
2241 newlineIfNecessary();
2242 m_indent = m_indent.substr( 0, m_indent.size()-2 );
2243 if( m_tagIsOpen ) {
2244 m_os << "/>";
2245 m_tagIsOpen = false;
2246 }
2247 else {
2248 m_os << m_indent << "</" << m_tags.back() << ">";
2249 }
2250 m_os << std::endl;
2251 m_tags.pop_back();
2252 return *this;
2253 }
2254
2255 XmlWriter& XmlWriter::writeAttribute( std::string const& name, std::string const& attribute ) {
2256 if( !name.empty() && !attribute.empty() )
2257 m_os << ' ' << name << "=\"" << XmlEncode( attribute, XmlEncode::ForAttributes ) << '"';
2258 return *this;
2259 }
2260
2261 XmlWriter& XmlWriter::writeAttribute( std::string const& name, const char* attribute ) {
2262 if( !name.empty() && attribute && attribute[0] != '\0' )
2263 m_os << ' ' << name << "=\"" << XmlEncode( attribute, XmlEncode::ForAttributes ) << '"';
2264 return *this;
2265 }
2266
2267 XmlWriter& XmlWriter::writeAttribute( std::string const& name, bool attribute ) {
2268 m_os << ' ' << name << "=\"" << ( attribute ? "true" : "false" ) << '"';
2269 return *this;
2270 }
2271
2272 XmlWriter& XmlWriter::writeText( std::string const& text, bool indent ) {
2273 if( !text.empty() ){
2274 bool tagWasOpen = m_tagIsOpen;
2275 ensureTagClosed();
2276 if( tagWasOpen && indent )
2277 m_os << m_indent;
2278 m_os << XmlEncode( text );
2279 m_needsNewline = true;
2280 }
2281 return *this;
2282 }
2283
2284 //XmlWriter& XmlWriter::writeComment( std::string const& text ) {
2285 // ensureTagClosed();
2286 // m_os << m_indent << "<!--" << text << "-->";
2287 // m_needsNewline = true;
2288 // return *this;
2289 //}
2290
2291 //void XmlWriter::writeStylesheetRef( std::string const& url ) {
2292 // m_os << "<?xml-stylesheet type=\"text/xsl\" href=\"" << url << "\"?>\n";
2293 //}
2294
2295 //XmlWriter& XmlWriter::writeBlankLine() {
2296 // ensureTagClosed();
2297 // m_os << '\n';
2298 // return *this;
2299 //}
2300
2301 void XmlWriter::ensureTagClosed() {
2302 if( m_tagIsOpen ) {
2303 m_os << ">" << std::endl;
2304 m_tagIsOpen = false;
2305 }
2306 }
2307
2308 void XmlWriter::writeDeclaration() {
2309 m_os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
2310 }
2311
2312 void XmlWriter::newlineIfNecessary() {
2313 if( m_needsNewline ) {
2314 m_os << std::endl;
2315 m_needsNewline = false;
2316 }
2317 }
2318
2319// =================================================================================================
2320// End of copy-pasted code from Catch
2321// =================================================================================================
2322
2323 // clang-format on
2324
2325 struct XmlReporter : public IReporter
2326 {
2327 XmlWriter xml;
2328 DOCTEST_DECLARE_MUTEX(mutex)
2329
2330 // caching pointers/references to objects of these types - safe to do
2331 const ContextOptions& opt;
2332 const TestCaseData* tc = nullptr;
2333
2334 XmlReporter(const ContextOptions& co)
2335 : xml(*co.cout)
2336 , opt(co) {}
2337
2338 void log_contexts() {
2339 int num_contexts = get_num_active_contexts();
2340 if(num_contexts) {
2341 auto contexts = get_active_contexts();
2342 std::stringstream ss;
2343 for(int i = 0; i < num_contexts; ++i) {
2344 contexts[i]->stringify(&ss);
2345 xml.scopedElement("Info").writeText(ss.str());
2346 ss.str("");
2347 }
2348 }
2349 }
2350
2351 unsigned line(unsigned l) const { return opt.no_line_numbers ? 0 : l; }
2352
2353 void test_case_start_impl(const TestCaseData& in) {
2354 bool open_ts_tag = false;
2355 if(tc != nullptr) { // we have already opened a test suite
2356 if(std::strcmp(tc->m_test_suite, in.m_test_suite) != 0) {
2357 xml.endElement();
2358 open_ts_tag = true;
2359 }
2360 }
2361 else {
2362 open_ts_tag = true; // first test case ==> first test suite
2363 }
2364
2365 if(open_ts_tag) {
2366 xml.startElement("TestSuite");
2367 xml.writeAttribute("name", in.m_test_suite);
2368 }
2369
2370 tc = &in;
2371 xml.startElement("TestCase")
2372 .writeAttribute("name", in.m_name)
2373 .writeAttribute("filename", skipPathFromFilename(in.m_file.c_str()))
2374 .writeAttribute("line", line(in.m_line))
2375 .writeAttribute("description", in.m_description);
2376
2377 if(Approx(in.m_timeout) != 0)
2378 xml.writeAttribute("timeout", in.m_timeout);
2379 if(in.m_may_fail)
2380 xml.writeAttribute("may_fail", true);
2381 if(in.m_should_fail)
2382 xml.writeAttribute("should_fail", true);
2383 }
2384
2385 // =========================================================================================
2386 // WHAT FOLLOWS ARE OVERRIDES OF THE VIRTUAL METHODS OF THE REPORTER INTERFACE
2387 // =========================================================================================
2388
2389 void report_query(const QueryData& in) override {
2390 test_run_start();
2391 if(opt.list_reporters) {
2392 for(auto& curr : getListeners())
2393 xml.scopedElement("Listener")
2394 .writeAttribute("priority", curr.first.first)
2395 .writeAttribute("name", curr.first.second);
2396 for(auto& curr : getReporters())
2397 xml.scopedElement("Reporter")
2398 .writeAttribute("priority", curr.first.first)
2399 .writeAttribute("name", curr.first.second);
2400 } else if(opt.count || opt.list_test_cases) {
2401 for(unsigned i = 0; i < in.num_data; ++i) {
2402 xml.scopedElement("TestCase").writeAttribute("name", in.data[i]->m_name)
2403 .writeAttribute("testsuite", in.data[i]->m_test_suite)
2404 .writeAttribute("filename", skipPathFromFilename(in.data[i]->m_file.c_str()))
2405 .writeAttribute("line", line(in.data[i]->m_line))
2406 .writeAttribute("skipped", in.data[i]->m_skip);
2407 }
2408 xml.scopedElement("OverallResultsTestCases")
2409 .writeAttribute("unskipped", in.run_stats->numTestCasesPassingFilters);
2410 } else if(opt.list_test_suites) {
2411 for(unsigned i = 0; i < in.num_data; ++i)
2412 xml.scopedElement("TestSuite").writeAttribute("name", in.data[i]->m_test_suite);
2413 xml.scopedElement("OverallResultsTestCases")
2414 .writeAttribute("unskipped", in.run_stats->numTestCasesPassingFilters);
2415 xml.scopedElement("OverallResultsTestSuites")
2416 .writeAttribute("unskipped", in.run_stats->numTestSuitesPassingFilters);
2417 }
2418 xml.endElement();
2419 }
2420
2421 void test_run_start() override {
2422 xml.writeDeclaration();
2423
2424 // remove .exe extension - mainly to have the same output on UNIX and Windows
2425 std::string binary_name = skipPathFromFilename(opt.binary_name.c_str());
2426#ifdef DOCTEST_PLATFORM_WINDOWS
2427 if(binary_name.rfind(".exe") != std::string::npos)
2428 binary_name = binary_name.substr(0, binary_name.length() - 4);
2429#endif // DOCTEST_PLATFORM_WINDOWS
2430
2431 xml.startElement("doctest").writeAttribute("binary", binary_name);
2432 if(opt.no_version == false)
2433 xml.writeAttribute("version", DOCTEST_VERSION_STR);
2434
2435 // only the consequential ones (TODO: filters)
2436 xml.scopedElement("Options")
2437 .writeAttribute("order_by", opt.order_by.c_str())
2438 .writeAttribute("rand_seed", opt.rand_seed)
2439 .writeAttribute("first", opt.first)
2440 .writeAttribute("last", opt.last)
2441 .writeAttribute("abort_after", opt.abort_after)
2442 .writeAttribute("subcase_filter_levels", opt.subcase_filter_levels)
2443 .writeAttribute("case_sensitive", opt.case_sensitive)
2444 .writeAttribute("no_throw", opt.no_throw)
2445 .writeAttribute("no_skip", opt.no_skip);
2446 }
2447
2448 void test_run_end(const TestRunStats& p) override {
2449 if(tc) // the TestSuite tag - only if there has been at least 1 test case
2450 xml.endElement();
2451
2452 xml.scopedElement("OverallResultsAsserts")
2453 .writeAttribute("successes", p.numAsserts - p.numAssertsFailed)
2454 .writeAttribute("failures", p.numAssertsFailed);
2455
2456 xml.startElement("OverallResultsTestCases")
2457 .writeAttribute("successes",
2458 p.numTestCasesPassingFilters - p.numTestCasesFailed)
2459 .writeAttribute("failures", p.numTestCasesFailed);
2460 if(opt.no_skipped_summary == false)
2461 xml.writeAttribute("skipped", p.numTestCases - p.numTestCasesPassingFilters);
2462 xml.endElement();
2463
2464 xml.endElement();
2465 }
2466
2467 void test_case_start(const TestCaseData& in) override {
2468 test_case_start_impl(in);
2469 xml.ensureTagClosed();
2470 }
2471
2472 void test_case_reenter(const TestCaseData&) override {}
2473
2474 void test_case_end(const CurrentTestCaseStats& st) override {
2475 xml.startElement("OverallResultsAsserts")
2476 .writeAttribute("successes",
2477 st.numAssertsCurrentTest - st.numAssertsFailedCurrentTest)
2478 .writeAttribute("failures", st.numAssertsFailedCurrentTest)
2479 .writeAttribute("test_case_success", st.testCaseSuccess);
2480 if(opt.duration)
2481 xml.writeAttribute("duration", st.seconds);
2482 if(tc->m_expected_failures)
2483 xml.writeAttribute("expected_failures", tc->m_expected_failures);
2484 xml.endElement();
2485
2486 xml.endElement();
2487 }
2488
2489 void test_case_exception(const TestCaseException& e) override {
2490 DOCTEST_LOCK_MUTEX(mutex)
2491
2492 xml.scopedElement("Exception")
2493 .writeAttribute("crash", e.is_crash)
2494 .writeText(e.error_string.c_str());
2495 }
2496
2497 void subcase_start(const SubcaseSignature& in) override {
2498 xml.startElement("SubCase")
2499 .writeAttribute("name", in.m_name)
2500 .writeAttribute("filename", skipPathFromFilename(in.m_file))
2501 .writeAttribute("line", line(in.m_line));
2502 xml.ensureTagClosed();
2503 }
2504
2505 void subcase_end() override { xml.endElement(); }
2506
2507 void log_assert(const AssertData& rb) override {
2508 if(!rb.m_failed && !opt.success)
2509 return;
2510
2511 DOCTEST_LOCK_MUTEX(mutex)
2512
2513 xml.startElement("Expression")
2514 .writeAttribute("success", !rb.m_failed)
2515 .writeAttribute("type", assertString(rb.m_at))
2516 .writeAttribute("filename", skipPathFromFilename(rb.m_file))
2517 .writeAttribute("line", line(rb.m_line));
2518
2519 xml.scopedElement("Original").writeText(rb.m_expr);
2520
2521 if(rb.m_threw)
2522 xml.scopedElement("Exception").writeText(rb.m_exception.c_str());
2523
2524 if(rb.m_at & assertType::is_throws_as)
2525 xml.scopedElement("ExpectedException").writeText(rb.m_exception_type);
2526 if(rb.m_at & assertType::is_throws_with)
2527 xml.scopedElement("ExpectedExceptionString").writeText(rb.m_exception_string.c_str());
2528 if((rb.m_at & assertType::is_normal) && !rb.m_threw)
2529 xml.scopedElement("Expanded").writeText(rb.m_decomp.c_str());
2530
2531 log_contexts();
2532
2533 xml.endElement();
2534 }
2535
2536 void log_message(const MessageData& mb) override {
2537 DOCTEST_LOCK_MUTEX(mutex)
2538
2539 xml.startElement("Message")
2540 .writeAttribute("type", failureString(mb.m_severity))
2541 .writeAttribute("filename", skipPathFromFilename(mb.m_file))
2542 .writeAttribute("line", line(mb.m_line));
2543
2544 xml.scopedElement("Text").writeText(mb.m_string.c_str());
2545
2546 log_contexts();
2547
2548 xml.endElement();
2549 }
2550
2551 void test_case_skipped(const TestCaseData& in) override {
2552 if(opt.no_skipped_summary == false) {
2553 test_case_start_impl(in);
2554 xml.writeAttribute("skipped", "true");
2555 xml.endElement();
2556 }
2557 }
2558 };
2559
2560 DOCTEST_REGISTER_REPORTER("xml", 0, XmlReporter);
2561
2562 void fulltext_log_assert_to_stream(std::ostream& s, const AssertData& rb) {
2563 if((rb.m_at & (assertType::is_throws_as | assertType::is_throws_with)) ==
2564 0)
2565 s << Color::Cyan << assertString(rb.m_at) << "( " << rb.m_expr << " ) "
2566 << Color::None;
2567
2568 if(rb.m_at & assertType::is_throws) {
2569 s << (rb.m_threw ? "threw as expected!" : "did NOT throw at all!") << "\n";
2570 } else if((rb.m_at & assertType::is_throws_as) &&
2571 (rb.m_at & assertType::is_throws_with)) {
2572 s << Color::Cyan << assertString(rb.m_at) << "( " << rb.m_expr << ", \""
2573 << rb.m_exception_string.c_str()
2574 << "\", " << rb.m_exception_type << " ) " << Color::None;
2575 if(rb.m_threw) {
2576 if(!rb.m_failed) {
2577 s << "threw as expected!\n";
2578 } else {
2579 s << "threw a DIFFERENT exception! (contents: " << rb.m_exception << ")\n";
2580 }
2581 } else {
2582 s << "did NOT throw at all!\n";
2583 }
2584 } else if(rb.m_at &
2585 assertType::is_throws_as) {
2586 s << Color::Cyan << assertString(rb.m_at) << "( " << rb.m_expr << ", "
2587 << rb.m_exception_type << " ) " << Color::None
2588 << (rb.m_threw ? (rb.m_threw_as ? "threw as expected!" :
2589 "threw a DIFFERENT exception: ") :
2590 "did NOT throw at all!")
2591 << Color::Cyan << rb.m_exception << "\n";
2592 } else if(rb.m_at &
2593 assertType::is_throws_with) {
2594 s << Color::Cyan << assertString(rb.m_at) << "( " << rb.m_expr << ", \""
2595 << rb.m_exception_string.c_str()
2596 << "\" ) " << Color::None
2597 << (rb.m_threw ? (!rb.m_failed ? "threw as expected!" :
2598 "threw a DIFFERENT exception: ") :
2599 "did NOT throw at all!")
2600 << Color::Cyan << rb.m_exception << "\n";
2601 } else if(rb.m_at & assertType::is_nothrow) {
2602 s << (rb.m_threw ? "THREW exception: " : "didn't throw!") << Color::Cyan
2603 << rb.m_exception << "\n";
2604 } else {
2605 s << (rb.m_threw ? "THREW exception: " :
2606 (!rb.m_failed ? "is correct!\n" : "is NOT correct!\n"));
2607 if(rb.m_threw)
2608 s << rb.m_exception << "\n";
2609 else
2610 s << " values: " << assertString(rb.m_at) << "( " << rb.m_decomp << " )\n";
2611 }
2612 }
2613
2614 // TODO:
2615 // - log_message()
2616 // - respond to queries
2617 // - honor remaining options
2618 // - more attributes in tags
2619 struct JUnitReporter : public IReporter
2620 {
2621 XmlWriter xml;
2622 DOCTEST_DECLARE_MUTEX(mutex)
2623 Timer timer;
2624 std::vector<String> deepestSubcaseStackNames;
2625
2626 struct JUnitTestCaseData
2627 {
2628 static std::string getCurrentTimestamp() {
2629 // Beware, this is not reentrant because of backward compatibility issues
2630 // Also, UTC only, again because of backward compatibility (%z is C++11)
2631 time_t rawtime;
2632 std::time(&rawtime);
2633 auto const timeStampSize = sizeof("2017-01-16T17:06:45Z");
2634
2635 std::tm timeInfo;
2636#ifdef DOCTEST_PLATFORM_WINDOWS
2637 gmtime_s(&timeInfo, &rawtime);
2638#else // DOCTEST_PLATFORM_WINDOWS
2639 gmtime_r(&rawtime, &timeInfo);
2640#endif // DOCTEST_PLATFORM_WINDOWS
2641
2642 char timeStamp[timeStampSize];
2643 const char* const fmt = "%Y-%m-%dT%H:%M:%SZ";
2644
2645 std::strftime(timeStamp, timeStampSize, fmt, &timeInfo);
2646 return std::string(timeStamp);
2647 }
2648
2649 struct JUnitTestMessage
2650 {
2651 JUnitTestMessage(const std::string& _message, const std::string& _type, const std::string& _details)
2652 : message(_message), type(_type), details(_details) {}
2653
2654 JUnitTestMessage(const std::string& _message, const std::string& _details)
2655 : message(_message), type(), details(_details) {}
2656
2657 std::string message, type, details;
2658 };
2659
2660 struct JUnitTestCase
2661 {
2662 JUnitTestCase(const std::string& _classname, const std::string& _name)
2663 : classname(_classname), name(_name), time(0), failures() {}
2664
2665 std::string classname, name;
2666 double time;
2667 std::vector<JUnitTestMessage> failures, errors;
2668 };
2669
2670 void add(const std::string& classname, const std::string& name) {
2671 testcases.emplace_back(classname, name);
2672 }
2673
2674 void appendSubcaseNamesToLastTestcase(std::vector<String> nameStack) {
2675 for(auto& curr: nameStack)
2676 if(curr.size())
2677 testcases.back().name += std::string("/") + curr.c_str();
2678 }
2679
2680 void addTime(double time) {
2681 if(time < 1e-4)
2682 time = 0;
2683 testcases.back().time = time;
2684 totalSeconds += time;
2685 }
2686
2687 void addFailure(const std::string& message, const std::string& type, const std::string& details) {
2688 testcases.back().failures.emplace_back(message, type, details);
2689 ++totalFailures;
2690 }
2691
2692 void addError(const std::string& message, const std::string& details) {
2693 testcases.back().errors.emplace_back(message, details);
2694 ++totalErrors;
2695 }
2696
2697 std::vector<JUnitTestCase> testcases;
2698 double totalSeconds = 0;
2699 int totalErrors = 0, totalFailures = 0;
2700 };
2701
2702 JUnitTestCaseData testCaseData;
2703
2704 // caching pointers/references to objects of these types - safe to do
2705 const ContextOptions& opt;
2706 const TestCaseData* tc = nullptr;
2707
2708 JUnitReporter(const ContextOptions& co)
2709 : xml(*co.cout)
2710 , opt(co) {}
2711
2712 unsigned line(unsigned l) const { return opt.no_line_numbers ? 0 : l; }
2713
2714 // =========================================================================================
2715 // WHAT FOLLOWS ARE OVERRIDES OF THE VIRTUAL METHODS OF THE REPORTER INTERFACE
2716 // =========================================================================================
2717
2718 void report_query(const QueryData&) override {
2719 xml.writeDeclaration();
2720 }
2721
2722 void test_run_start() override {
2723 xml.writeDeclaration();
2724 }
2725
2726 void test_run_end(const TestRunStats& p) override {
2727 // remove .exe extension - mainly to have the same output on UNIX and Windows
2728 std::string binary_name = skipPathFromFilename(opt.binary_name.c_str());
2729#ifdef DOCTEST_PLATFORM_WINDOWS
2730 if(binary_name.rfind(".exe") != std::string::npos)
2731 binary_name = binary_name.substr(0, binary_name.length() - 4);
2732#endif // DOCTEST_PLATFORM_WINDOWS
2733 xml.startElement("testsuites");
2734 xml.startElement("testsuite").writeAttribute("name", binary_name)
2735 .writeAttribute("errors", testCaseData.totalErrors)
2736 .writeAttribute("failures", testCaseData.totalFailures)
2737 .writeAttribute("tests", p.numAsserts);
2738 if(opt.no_time_in_output == false) {
2739 xml.writeAttribute("time", testCaseData.totalSeconds);
2740 xml.writeAttribute("timestamp", JUnitTestCaseData::getCurrentTimestamp());
2741 }
2742 if(opt.no_version == false)
2743 xml.writeAttribute("doctest_version", DOCTEST_VERSION_STR);
2744
2745 for(const auto& testCase : testCaseData.testcases) {
2746 xml.startElement("testcase")
2747 .writeAttribute("classname", testCase.classname)
2748 .writeAttribute("name", testCase.name);
2749 if(opt.no_time_in_output == false)
2750 xml.writeAttribute("time", testCase.time);
2751 // This is not ideal, but it should be enough to mimic gtest's junit output.
2752 xml.writeAttribute("status", "run");
2753
2754 for(const auto& failure : testCase.failures) {
2755 xml.scopedElement("failure")
2756 .writeAttribute("message", failure.message)
2757 .writeAttribute("type", failure.type)
2758 .writeText(failure.details, false);
2759 }
2760
2761 for(const auto& error : testCase.errors) {
2762 xml.scopedElement("error")
2763 .writeAttribute("message", error.message)
2764 .writeText(error.details);
2765 }
2766
2767 xml.endElement();
2768 }
2769 xml.endElement();
2770 xml.endElement();
2771 }
2772
2773 void test_case_start(const TestCaseData& in) override {
2774 testCaseData.add(skipPathFromFilename(in.m_file.c_str()), in.m_name);
2775 timer.start();
2776 }
2777
2778 void test_case_reenter(const TestCaseData& in) override {
2779 testCaseData.addTime(timer.getElapsedSeconds());
2780 testCaseData.appendSubcaseNamesToLastTestcase(deepestSubcaseStackNames);
2781 deepestSubcaseStackNames.clear();
2782
2783 timer.start();
2784 testCaseData.add(skipPathFromFilename(in.m_file.c_str()), in.m_name);
2785 }
2786
2787 void test_case_end(const CurrentTestCaseStats&) override {
2788 testCaseData.addTime(timer.getElapsedSeconds());
2789 testCaseData.appendSubcaseNamesToLastTestcase(deepestSubcaseStackNames);
2790 deepestSubcaseStackNames.clear();
2791 }
2792
2793 void test_case_exception(const TestCaseException& e) override {
2794 DOCTEST_LOCK_MUTEX(mutex)
2795 testCaseData.addError("exception", e.error_string.c_str());
2796 }
2797
2798 void subcase_start(const SubcaseSignature& in) override {
2799 deepestSubcaseStackNames.push_back(in.m_name);
2800 }
2801
2802 void subcase_end() override {}
2803
2804 void log_assert(const AssertData& rb) override {
2805 if(!rb.m_failed) // report only failures & ignore the `success` option
2806 return;
2807
2808 DOCTEST_LOCK_MUTEX(mutex)
2809
2810 std::ostringstream os;
2811 os << skipPathFromFilename(rb.m_file) << (opt.gnu_file_line ? ":" : "(")
2812 << line(rb.m_line) << (opt.gnu_file_line ? ":" : "):") << std::endl;
2813
2814 fulltext_log_assert_to_stream(os, rb);
2815 log_contexts(os);
2816 testCaseData.addFailure(rb.m_decomp.c_str(), assertString(rb.m_at), os.str());
2817 }
2818
2819 void log_message(const MessageData& mb) override {
2820 if(mb.m_severity & assertType::is_warn) // report only failures
2821 return;
2822
2823 DOCTEST_LOCK_MUTEX(mutex)
2824
2825 std::ostringstream os;
2826 os << skipPathFromFilename(mb.m_file) << (opt.gnu_file_line ? ":" : "(")
2827 << line(mb.m_line) << (opt.gnu_file_line ? ":" : "):") << std::endl;
2828
2829 os << mb.m_string.c_str() << "\n";
2830 log_contexts(os);
2831
2832 testCaseData.addFailure(mb.m_string.c_str(),
2833 mb.m_severity & assertType::is_check ? "FAIL_CHECK" : "FAIL", os.str());
2834 }
2835
2836 void test_case_skipped(const TestCaseData&) override {}
2837
2838 void log_contexts(std::ostringstream& s) {
2839 int num_contexts = get_num_active_contexts();
2840 if(num_contexts) {
2841 auto contexts = get_active_contexts();
2842
2843 s << " logged: ";
2844 for(int i = 0; i < num_contexts; ++i) {
2845 s << (i == 0 ? "" : " ");
2846 contexts[i]->stringify(&s);
2847 s << std::endl;
2848 }
2849 }
2850 }
2851 };
2852
2853 DOCTEST_REGISTER_REPORTER("junit", 0, JUnitReporter);
2854
2855 struct Whitespace
2856 {
2857 int nrSpaces;
2858 explicit Whitespace(int nr)
2859 : nrSpaces(nr) {}
2860 };
2861
2862 std::ostream& operator<<(std::ostream& out, const Whitespace& ws) {
2863 if(ws.nrSpaces != 0)
2864 out << std::setw(ws.nrSpaces) << ' ';
2865 return out;
2866 }
2867
2868 struct ConsoleReporter : public IReporter
2869 {
2870 std::ostream& s;
2871 bool hasLoggedCurrentTestStart;
2872 std::vector<SubcaseSignature> subcasesStack;
2873 size_t currentSubcaseLevel;
2874 DOCTEST_DECLARE_MUTEX(mutex)
2875
2876 // caching pointers/references to objects of these types - safe to do
2877 const ContextOptions& opt;
2878 const TestCaseData* tc;
2879
2880 ConsoleReporter(const ContextOptions& co)
2881 : s(*co.cout)
2882 , opt(co) {}
2883
2884 ConsoleReporter(const ContextOptions& co, std::ostream& ostr)
2885 : s(ostr)
2886 , opt(co) {}
2887
2888 // =========================================================================================
2889 // WHAT FOLLOWS ARE HELPERS USED BY THE OVERRIDES OF THE VIRTUAL METHODS OF THE INTERFACE
2890 // =========================================================================================
2891
2892 void separator_to_stream() {
2893 s << Color::Yellow
2894 << "==============================================================================="
2895 "\n";
2896 }
2897
2898 const char* getSuccessOrFailString(bool success, assertType::Enum at,
2899 const char* success_str) {
2900 if(success)
2901 return success_str;
2902 return failureString(at);
2903 }
2904
2905 Color::Enum getSuccessOrFailColor(bool success, assertType::Enum at) {
2906 return success ? Color::BrightGreen :
2907 (at & assertType::is_warn) ? Color::Yellow : Color::Red;
2908 }
2909
2910 void successOrFailColoredStringToStream(bool success, assertType::Enum at,
2911 const char* success_str = "SUCCESS") {
2912 s << getSuccessOrFailColor(success, at)
2913 << getSuccessOrFailString(success, at, success_str) << ": ";
2914 }
2915
2916 void log_contexts() {
2917 int num_contexts = get_num_active_contexts();
2918 if(num_contexts) {
2919 auto contexts = get_active_contexts();
2920
2921 s << Color::None << " logged: ";
2922 for(int i = 0; i < num_contexts; ++i) {
2923 s << (i == 0 ? "" : " ");
2924 contexts[i]->stringify(&s);
2925 s << "\n";
2926 }
2927 }
2928
2929 s << "\n";
2930 }
2931
2932 // this was requested to be made virtual so users could override it
2933 virtual void file_line_to_stream(const char* file, int line,
2934 const char* tail = "") {
2935 s << Color::LightGrey << skipPathFromFilename(file) << (opt.gnu_file_line ? ":" : "(")
2936 << (opt.no_line_numbers ? 0 : line) // 0 or the real num depending on the option
2937 << (opt.gnu_file_line ? ":" : "):") << tail;
2938 }
2939
2940 void logTestStart() {
2941 if(hasLoggedCurrentTestStart)
2942 return;
2943
2944 separator_to_stream();
2945 file_line_to_stream(tc->m_file.c_str(), tc->m_line, "\n");
2946 if(tc->m_description)
2947 s << Color::Yellow << "DESCRIPTION: " << Color::None << tc->m_description << "\n";
2948 if(tc->m_test_suite && tc->m_test_suite[0] != '\0')
2949 s << Color::Yellow << "TEST SUITE: " << Color::None << tc->m_test_suite << "\n";
2950 if(strncmp(tc->m_name, " Scenario:", 11) != 0)
2951 s << Color::Yellow << "TEST CASE: ";
2952 s << Color::None << tc->m_name << "\n";
2953
2954 for(size_t i = 0; i < currentSubcaseLevel; ++i) {
2955 if(subcasesStack[i].m_name[0] != '\0')
2956 s << " " << subcasesStack[i].m_name << "\n";
2957 }
2958
2959 if(currentSubcaseLevel != subcasesStack.size()) {
2960 s << Color::Yellow << "\nDEEPEST SUBCASE STACK REACHED (DIFFERENT FROM THE CURRENT ONE):\n" << Color::None;
2961 for(size_t i = 0; i < subcasesStack.size(); ++i) {
2962 if(subcasesStack[i].m_name[0] != '\0')
2963 s << " " << subcasesStack[i].m_name << "\n";
2964 }
2965 }
2966
2967 s << "\n";
2968
2969 hasLoggedCurrentTestStart = true;
2970 }
2971
2972 void printVersion() {
2973 if(opt.no_version == false)
2974 s << Color::Cyan << "[doctest] " << Color::None << "doctest version is \""
2975 << DOCTEST_VERSION_STR << "\"\n";
2976 }
2977
2978 void printIntro() {
2979 if(opt.no_intro == false) {
2980 printVersion();
2981 s << Color::Cyan << "[doctest] " << Color::None
2982 << "run with \"--" DOCTEST_OPTIONS_PREFIX_DISPLAY "help\" for options\n";
2983 }
2984 }
2985
2986 void printHelp() {
2987 int sizePrefixDisplay = static_cast<int>(strlen(DOCTEST_OPTIONS_PREFIX_DISPLAY));
2988 printVersion();
2989 // clang-format off
2990 s << Color::Cyan << "[doctest]\n" << Color::None;
2991 s << Color::Cyan << "[doctest] " << Color::None;
2992 s << "boolean values: \"1/on/yes/true\" or \"0/off/no/false\"\n";
2993 s << Color::Cyan << "[doctest] " << Color::None;
2994 s << "filter values: \"str1,str2,str3\" (comma separated strings)\n";
2995 s << Color::Cyan << "[doctest]\n" << Color::None;
2996 s << Color::Cyan << "[doctest] " << Color::None;
2997 s << "filters use wildcards for matching strings\n";
2998 s << Color::Cyan << "[doctest] " << Color::None;
2999 s << "something passes a filter if any of the strings in a filter matches\n";
3000#ifndef DOCTEST_CONFIG_NO_UNPREFIXED_OPTIONS
3001 s << Color::Cyan << "[doctest]\n" << Color::None;
3002 s << Color::Cyan << "[doctest] " << Color::None;
3003 s << "ALL FLAGS, OPTIONS AND FILTERS ALSO AVAILABLE WITH A \"" DOCTEST_CONFIG_OPTIONS_PREFIX "\" PREFIX!!!\n";
3004#endif
3005 s << Color::Cyan << "[doctest]\n" << Color::None;
3006 s << Color::Cyan << "[doctest] " << Color::None;
3007 s << "Query flags - the program quits after them. Available:\n\n";
3008 s << " -" DOCTEST_OPTIONS_PREFIX_DISPLAY "?, --" DOCTEST_OPTIONS_PREFIX_DISPLAY "help, -" DOCTEST_OPTIONS_PREFIX_DISPLAY "h "
3009 << Whitespace(sizePrefixDisplay*0) << "prints this message\n";
3010 s << " -" DOCTEST_OPTIONS_PREFIX_DISPLAY "v, --" DOCTEST_OPTIONS_PREFIX_DISPLAY "version "
3011 << Whitespace(sizePrefixDisplay*1) << "prints the version\n";
3012 s << " -" DOCTEST_OPTIONS_PREFIX_DISPLAY "c, --" DOCTEST_OPTIONS_PREFIX_DISPLAY "count "
3013 << Whitespace(sizePrefixDisplay*1) << "prints the number of matching tests\n";
3014 s << " -" DOCTEST_OPTIONS_PREFIX_DISPLAY "ltc, --" DOCTEST_OPTIONS_PREFIX_DISPLAY "list-test-cases "
3015 << Whitespace(sizePrefixDisplay*1) << "lists all matching tests by name\n";
3016 s << " -" DOCTEST_OPTIONS_PREFIX_DISPLAY "lts, --" DOCTEST_OPTIONS_PREFIX_DISPLAY "list-test-suites "
3017 << Whitespace(sizePrefixDisplay*1) << "lists all matching test suites\n";
3018 s << " -" DOCTEST_OPTIONS_PREFIX_DISPLAY "lr, --" DOCTEST_OPTIONS_PREFIX_DISPLAY "list-reporters "
3019 << Whitespace(sizePrefixDisplay*1) << "lists all registered reporters\n\n";
3020 // ================================================================================== << 79
3021 s << Color::Cyan << "[doctest] " << Color::None;
3022 s << "The available <int>/<string> options/filters are:\n\n";
3023 s << " -" DOCTEST_OPTIONS_PREFIX_DISPLAY "tc, --" DOCTEST_OPTIONS_PREFIX_DISPLAY "test-case=<filters> "
3024 << Whitespace(sizePrefixDisplay*1) << "filters tests by their name\n";
3025 s << " -" DOCTEST_OPTIONS_PREFIX_DISPLAY "tce, --" DOCTEST_OPTIONS_PREFIX_DISPLAY "test-case-exclude=<filters> "
3026 << Whitespace(sizePrefixDisplay*1) << "filters OUT tests by their name\n";
3027 s << " -" DOCTEST_OPTIONS_PREFIX_DISPLAY "sf, --" DOCTEST_OPTIONS_PREFIX_DISPLAY "source-file=<filters> "
3028 << Whitespace(sizePrefixDisplay*1) << "filters tests by their file\n";
3029 s << " -" DOCTEST_OPTIONS_PREFIX_DISPLAY "sfe, --" DOCTEST_OPTIONS_PREFIX_DISPLAY "source-file-exclude=<filters> "
3030 << Whitespace(sizePrefixDisplay*1) << "filters OUT tests by their file\n";
3031 s << " -" DOCTEST_OPTIONS_PREFIX_DISPLAY "ts, --" DOCTEST_OPTIONS_PREFIX_DISPLAY "test-suite=<filters> "
3032 << Whitespace(sizePrefixDisplay*1) << "filters tests by their test suite\n";
3033 s << " -" DOCTEST_OPTIONS_PREFIX_DISPLAY "tse, --" DOCTEST_OPTIONS_PREFIX_DISPLAY "test-suite-exclude=<filters> "
3034 << Whitespace(sizePrefixDisplay*1) << "filters OUT tests by their test suite\n";
3035 s << " -" DOCTEST_OPTIONS_PREFIX_DISPLAY "sc, --" DOCTEST_OPTIONS_PREFIX_DISPLAY "subcase=<filters> "
3036 << Whitespace(sizePrefixDisplay*1) << "filters subcases by their name\n";
3037 s << " -" DOCTEST_OPTIONS_PREFIX_DISPLAY "sce, --" DOCTEST_OPTIONS_PREFIX_DISPLAY "subcase-exclude=<filters> "
3038 << Whitespace(sizePrefixDisplay*1) << "filters OUT subcases by their name\n";
3039 s << " -" DOCTEST_OPTIONS_PREFIX_DISPLAY "r, --" DOCTEST_OPTIONS_PREFIX_DISPLAY "reporters=<filters> "
3040 << Whitespace(sizePrefixDisplay*1) << "reporters to use (console is default)\n";
3041 s << " -" DOCTEST_OPTIONS_PREFIX_DISPLAY "o, --" DOCTEST_OPTIONS_PREFIX_DISPLAY "out=<string> "
3042 << Whitespace(sizePrefixDisplay*1) << "output filename\n";
3043 s << " -" DOCTEST_OPTIONS_PREFIX_DISPLAY "ob, --" DOCTEST_OPTIONS_PREFIX_DISPLAY "order-by=<string> "
3044 << Whitespace(sizePrefixDisplay*1) << "how the tests should be ordered\n";
3045 s << Whitespace(sizePrefixDisplay*3) << " <string> - [file/suite/name/rand/none]\n";
3046 s << " -" DOCTEST_OPTIONS_PREFIX_DISPLAY "rs, --" DOCTEST_OPTIONS_PREFIX_DISPLAY "rand-seed=<int> "
3047 << Whitespace(sizePrefixDisplay*1) << "seed for random ordering\n";
3048 s << " -" DOCTEST_OPTIONS_PREFIX_DISPLAY "f, --" DOCTEST_OPTIONS_PREFIX_DISPLAY "first=<int> "
3049 << Whitespace(sizePrefixDisplay*1) << "the first test passing the filters to\n";
3050 s << Whitespace(sizePrefixDisplay*3) << " execute - for range-based execution\n";
3051 s << " -" DOCTEST_OPTIONS_PREFIX_DISPLAY "l, --" DOCTEST_OPTIONS_PREFIX_DISPLAY "last=<int> "
3052 << Whitespace(sizePrefixDisplay*1) << "the last test passing the filters to\n";
3053 s << Whitespace(sizePrefixDisplay*3) << " execute - for range-based execution\n";
3054 s << " -" DOCTEST_OPTIONS_PREFIX_DISPLAY "aa, --" DOCTEST_OPTIONS_PREFIX_DISPLAY "abort-after=<int> "
3055 << Whitespace(sizePrefixDisplay*1) << "stop after <int> failed assertions\n";
3056 s << " -" DOCTEST_OPTIONS_PREFIX_DISPLAY "scfl,--" DOCTEST_OPTIONS_PREFIX_DISPLAY "subcase-filter-levels=<int> "
3057 << Whitespace(sizePrefixDisplay*1) << "apply filters for the first <int> levels\n";
3058 s << Color::Cyan << "\n[doctest] " << Color::None;
3059 s << "Bool options - can be used like flags and true is assumed. Available:\n\n";
3060 s << " -" DOCTEST_OPTIONS_PREFIX_DISPLAY "s, --" DOCTEST_OPTIONS_PREFIX_DISPLAY "success=<bool> "
3061 << Whitespace(sizePrefixDisplay*1) << "include successful assertions in output\n";
3062 s << " -" DOCTEST_OPTIONS_PREFIX_DISPLAY "cs, --" DOCTEST_OPTIONS_PREFIX_DISPLAY "case-sensitive=<bool> "
3063 << Whitespace(sizePrefixDisplay*1) << "filters being treated as case sensitive\n";
3064 s << " -" DOCTEST_OPTIONS_PREFIX_DISPLAY "e, --" DOCTEST_OPTIONS_PREFIX_DISPLAY "exit=<bool> "
3065 << Whitespace(sizePrefixDisplay*1) << "exits after the tests finish\n";
3066 s << " -" DOCTEST_OPTIONS_PREFIX_DISPLAY "d, --" DOCTEST_OPTIONS_PREFIX_DISPLAY "duration=<bool> "
3067 << Whitespace(sizePrefixDisplay*1) << "prints the time duration of each test\n";
3068 s << " -" DOCTEST_OPTIONS_PREFIX_DISPLAY "m, --" DOCTEST_OPTIONS_PREFIX_DISPLAY "minimal=<bool> "
3069 << Whitespace(sizePrefixDisplay*1) << "minimal console output (only failures)\n";
3070 s << " -" DOCTEST_OPTIONS_PREFIX_DISPLAY "q, --" DOCTEST_OPTIONS_PREFIX_DISPLAY "quiet=<bool> "
3071 << Whitespace(sizePrefixDisplay*1) << "no console output\n";
3072 s << " -" DOCTEST_OPTIONS_PREFIX_DISPLAY "nt, --" DOCTEST_OPTIONS_PREFIX_DISPLAY "no-throw=<bool> "
3073 << Whitespace(sizePrefixDisplay*1) << "skips exceptions-related assert checks\n";
3074 s << " -" DOCTEST_OPTIONS_PREFIX_DISPLAY "ne, --" DOCTEST_OPTIONS_PREFIX_DISPLAY "no-exitcode=<bool> "
3075 << Whitespace(sizePrefixDisplay*1) << "returns (or exits) always with success\n";
3076 s << " -" DOCTEST_OPTIONS_PREFIX_DISPLAY "nr, --" DOCTEST_OPTIONS_PREFIX_DISPLAY "no-run=<bool> "
3077 << Whitespace(sizePrefixDisplay*1) << "skips all runtime doctest operations\n";
3078 s << " -" DOCTEST_OPTIONS_PREFIX_DISPLAY "ni, --" DOCTEST_OPTIONS_PREFIX_DISPLAY "no-intro=<bool> "
3079 << Whitespace(sizePrefixDisplay*1) << "omit the framework intro in the output\n";
3080 s << " -" DOCTEST_OPTIONS_PREFIX_DISPLAY "nv, --" DOCTEST_OPTIONS_PREFIX_DISPLAY "no-version=<bool> "
3081 << Whitespace(sizePrefixDisplay*1) << "omit the framework version in the output\n";
3082 s << " -" DOCTEST_OPTIONS_PREFIX_DISPLAY "nc, --" DOCTEST_OPTIONS_PREFIX_DISPLAY "no-colors=<bool> "
3083 << Whitespace(sizePrefixDisplay*1) << "disables colors in output\n";
3084 s << " -" DOCTEST_OPTIONS_PREFIX_DISPLAY "fc, --" DOCTEST_OPTIONS_PREFIX_DISPLAY "force-colors=<bool> "
3085 << Whitespace(sizePrefixDisplay*1) << "use colors even when not in a tty\n";
3086 s << " -" DOCTEST_OPTIONS_PREFIX_DISPLAY "nb, --" DOCTEST_OPTIONS_PREFIX_DISPLAY "no-breaks=<bool> "
3087 << Whitespace(sizePrefixDisplay*1) << "disables breakpoints in debuggers\n";
3088 s << " -" DOCTEST_OPTIONS_PREFIX_DISPLAY "ns, --" DOCTEST_OPTIONS_PREFIX_DISPLAY "no-skip=<bool> "
3089 << Whitespace(sizePrefixDisplay*1) << "don't skip test cases marked as skip\n";
3090 s << " -" DOCTEST_OPTIONS_PREFIX_DISPLAY "gfl, --" DOCTEST_OPTIONS_PREFIX_DISPLAY "gnu-file-line=<bool> "
3091 << Whitespace(sizePrefixDisplay*1) << ":n: vs (n): for line numbers in output\n";
3092 s << " -" DOCTEST_OPTIONS_PREFIX_DISPLAY "npf, --" DOCTEST_OPTIONS_PREFIX_DISPLAY "no-path-filenames=<bool> "
3093 << Whitespace(sizePrefixDisplay*1) << "only filenames and no paths in output\n";
3094 s << " -" DOCTEST_OPTIONS_PREFIX_DISPLAY "nln, --" DOCTEST_OPTIONS_PREFIX_DISPLAY "no-line-numbers=<bool> "
3095 << Whitespace(sizePrefixDisplay*1) << "0 instead of real line numbers in output\n";
3096 // ================================================================================== << 79
3097 // clang-format on
3098
3099 s << Color::Cyan << "\n[doctest] " << Color::None;
3100 s << "for more information visit the project documentation\n\n";
3101 }
3102
3103 void printRegisteredReporters() {
3104 printVersion();
3105 auto printReporters = [this] (const reporterMap& reporters, const char* type) {
3106 if(reporters.size()) {
3107 s << Color::Cyan << "[doctest] " << Color::None << "listing all registered " << type << "\n";
3108 for(auto& curr : reporters)
3109 s << "priority: " << std::setw(5) << curr.first.first
3110 << " name: " << curr.first.second << "\n";
3111 }
3112 };
3113 printReporters(getListeners(), "listeners");
3114 printReporters(getReporters(), "reporters");
3115 }
3116
3117 // =========================================================================================
3118 // WHAT FOLLOWS ARE OVERRIDES OF THE VIRTUAL METHODS OF THE REPORTER INTERFACE
3119 // =========================================================================================
3120
3121 void report_query(const QueryData& in) override {
3122 if(opt.version) {
3123 printVersion();
3124 } else if(opt.help) {
3125 printHelp();
3126 } else if(opt.list_reporters) {
3127 printRegisteredReporters();
3128 } else if(opt.count || opt.list_test_cases) {
3129 if(opt.list_test_cases) {
3130 s << Color::Cyan << "[doctest] " << Color::None
3131 << "listing all test case names\n";
3132 separator_to_stream();
3133 }
3134
3135 for(unsigned i = 0; i < in.num_data; ++i)
3136 s << Color::None << in.data[i]->m_name << "\n";
3137
3138 separator_to_stream();
3139
3140 s << Color::Cyan << "[doctest] " << Color::None
3141 << "unskipped test cases passing the current filters: "
3142 << g_cs->numTestCasesPassingFilters << "\n";
3143
3144 } else if(opt.list_test_suites) {
3145 s << Color::Cyan << "[doctest] " << Color::None << "listing all test suites\n";
3146 separator_to_stream();
3147
3148 for(unsigned i = 0; i < in.num_data; ++i)
3149 s << Color::None << in.data[i]->m_test_suite << "\n";
3150
3151 separator_to_stream();
3152
3153 s << Color::Cyan << "[doctest] " << Color::None
3154 << "unskipped test cases passing the current filters: "
3155 << g_cs->numTestCasesPassingFilters << "\n";
3156 s << Color::Cyan << "[doctest] " << Color::None
3157 << "test suites with unskipped test cases passing the current filters: "
3158 << g_cs->numTestSuitesPassingFilters << "\n";
3159 }
3160 }
3161
3162 void test_run_start() override {
3163 if(!opt.minimal)
3164 printIntro();
3165 }
3166
3167 void test_run_end(const TestRunStats& p) override {
3168 if(opt.minimal && p.numTestCasesFailed == 0)
3169 return;
3170
3171 separator_to_stream();
3172 s << std::dec;
3173
3174 auto totwidth = int(std::ceil(log10(static_cast<double>(std::max(p.numTestCasesPassingFilters, static_cast<unsigned>(p.numAsserts))) + 1)));
3175 auto passwidth = int(std::ceil(log10(static_cast<double>(std::max(p.numTestCasesPassingFilters - p.numTestCasesFailed, static_cast<unsigned>(p.numAsserts - p.numAssertsFailed))) + 1)));
3176 auto failwidth = int(std::ceil(log10(static_cast<double>(std::max(p.numTestCasesFailed, static_cast<unsigned>(p.numAssertsFailed))) + 1)));
3177 const bool anythingFailed = p.numTestCasesFailed > 0 || p.numAssertsFailed > 0;
3178 s << Color::Cyan << "[doctest] " << Color::None << "test cases: " << std::setw(totwidth)
3179 << p.numTestCasesPassingFilters << " | "
3180 << ((p.numTestCasesPassingFilters == 0 || anythingFailed) ? Color::None :
3181 Color::Green)
3182 << std::setw(passwidth) << p.numTestCasesPassingFilters - p.numTestCasesFailed << " passed"
3183 << Color::None << " | " << (p.numTestCasesFailed > 0 ? Color::Red : Color::None)
3184 << std::setw(failwidth) << p.numTestCasesFailed << " failed" << Color::None << " |";
3185 if(opt.no_skipped_summary == false) {
3186 const int numSkipped = p.numTestCases - p.numTestCasesPassingFilters;
3187 s << " " << (numSkipped == 0 ? Color::None : Color::Yellow) << numSkipped
3188 << " skipped" << Color::None;
3189 }
3190 s << "\n";
3191 s << Color::Cyan << "[doctest] " << Color::None << "assertions: " << std::setw(totwidth)
3192 << p.numAsserts << " | "
3193 << ((p.numAsserts == 0 || anythingFailed) ? Color::None : Color::Green)
3194 << std::setw(passwidth) << (p.numAsserts - p.numAssertsFailed) << " passed" << Color::None
3195 << " | " << (p.numAssertsFailed > 0 ? Color::Red : Color::None) << std::setw(failwidth)
3196 << p.numAssertsFailed << " failed" << Color::None << " |\n";
3197 s << Color::Cyan << "[doctest] " << Color::None
3198 << "Status: " << (p.numTestCasesFailed > 0 ? Color::Red : Color::Green)
3199 << ((p.numTestCasesFailed > 0) ? "FAILURE!" : "SUCCESS!") << Color::None << std::endl;
3200 }
3201
3202 void test_case_start(const TestCaseData& in) override {
3203 hasLoggedCurrentTestStart = false;
3204 tc = &in;
3205 subcasesStack.clear();
3206 currentSubcaseLevel = 0;
3207 }
3208
3209 void test_case_reenter(const TestCaseData&) override {
3210 subcasesStack.clear();
3211 }
3212
3213 void test_case_end(const CurrentTestCaseStats& st) override {
3214 if(tc->m_no_output)
3215 return;
3216
3217 // log the preamble of the test case only if there is something
3218 // else to print - something other than that an assert has failed
3219 if(opt.duration ||
3220 (st.failure_flags && st.failure_flags != static_cast<int>(TestCaseFailureReason::AssertFailure)))
3221 logTestStart();
3222
3223 if(opt.duration)
3224 s << Color::None << std::setprecision(6) << std::fixed << st.seconds
3225 << " s: " << tc->m_name << "\n";
3226
3227 if(st.failure_flags & TestCaseFailureReason::Timeout)
3228 s << Color::Red << "Test case exceeded time limit of " << std::setprecision(6)
3229 << std::fixed << tc->m_timeout << "!\n";
3230
3231 if(st.failure_flags & TestCaseFailureReason::ShouldHaveFailedButDidnt) {
3232 s << Color::Red << "Should have failed but didn't! Marking it as failed!\n";
3233 } else if(st.failure_flags & TestCaseFailureReason::ShouldHaveFailedAndDid) {
3234 s << Color::Yellow << "Failed as expected so marking it as not failed\n";
3235 } else if(st.failure_flags & TestCaseFailureReason::CouldHaveFailedAndDid) {
3236 s << Color::Yellow << "Allowed to fail so marking it as not failed\n";
3237 } else if(st.failure_flags & TestCaseFailureReason::DidntFailExactlyNumTimes) {
3238 s << Color::Red << "Didn't fail exactly " << tc->m_expected_failures
3239 << " times so marking it as failed!\n";
3240 } else if(st.failure_flags & TestCaseFailureReason::FailedExactlyNumTimes) {
3241 s << Color::Yellow << "Failed exactly " << tc->m_expected_failures
3242 << " times as expected so marking it as not failed!\n";
3243 }
3244 if(st.failure_flags & TestCaseFailureReason::TooManyFailedAsserts) {
3245 s << Color::Red << "Aborting - too many failed asserts!\n";
3246 }
3247 s << Color::None; // lgtm [cpp/useless-expression]
3248 }
3249
3250 void test_case_exception(const TestCaseException& e) override {
3251 DOCTEST_LOCK_MUTEX(mutex)
3252 if(tc->m_no_output)
3253 return;
3254
3255 logTestStart();
3256
3257 file_line_to_stream(tc->m_file.c_str(), tc->m_line, " ");
3258 successOrFailColoredStringToStream(false, e.is_crash ? assertType::is_require :
3259 assertType::is_check);
3260 s << Color::Red << (e.is_crash ? "test case CRASHED: " : "test case THREW exception: ")
3261 << Color::Cyan << e.error_string << "\n";
3262
3263 int num_stringified_contexts = get_num_stringified_contexts();
3264 if(num_stringified_contexts) {
3265 auto stringified_contexts = get_stringified_contexts();
3266 s << Color::None << " logged: ";
3267 for(int i = num_stringified_contexts; i > 0; --i) {
3268 s << (i == num_stringified_contexts ? "" : " ")
3269 << stringified_contexts[i - 1] << "\n";
3270 }
3271 }
3272 s << "\n" << Color::None;
3273 }
3274
3275 void subcase_start(const SubcaseSignature& subc) override {
3276 subcasesStack.push_back(subc);
3277 ++currentSubcaseLevel;
3278 hasLoggedCurrentTestStart = false;
3279 }
3280
3281 void subcase_end() override {
3282 --currentSubcaseLevel;
3283 hasLoggedCurrentTestStart = false;
3284 }
3285
3286 void log_assert(const AssertData& rb) override {
3287 if((!rb.m_failed && !opt.success) || tc->m_no_output)
3288 return;
3289
3290 DOCTEST_LOCK_MUTEX(mutex)
3291
3292 logTestStart();
3293
3294 file_line_to_stream(rb.m_file, rb.m_line, " ");
3295 successOrFailColoredStringToStream(!rb.m_failed, rb.m_at);
3296
3297 fulltext_log_assert_to_stream(s, rb);
3298
3299 log_contexts();
3300 }
3301
3302 void log_message(const MessageData& mb) override {
3303 if(tc->m_no_output)
3304 return;
3305
3306 DOCTEST_LOCK_MUTEX(mutex)
3307
3308 logTestStart();
3309
3310 file_line_to_stream(mb.m_file, mb.m_line, " ");
3311 s << getSuccessOrFailColor(false, mb.m_severity)
3312 << getSuccessOrFailString(mb.m_severity & assertType::is_warn, mb.m_severity,
3313 "MESSAGE") << ": ";
3314 s << Color::None << mb.m_string << "\n";
3315 log_contexts();
3316 }
3317
3318 void test_case_skipped(const TestCaseData&) override {}
3319 };
3320
3321 DOCTEST_REGISTER_REPORTER("console", 0, ConsoleReporter);
3322
3323#ifdef DOCTEST_PLATFORM_WINDOWS
3324 struct DebugOutputWindowReporter : public ConsoleReporter
3325 {
3326 DOCTEST_THREAD_LOCAL static std::ostringstream oss;
3327
3328 DebugOutputWindowReporter(const ContextOptions& co)
3329 : ConsoleReporter(co, oss) {}
3330
3331#define DOCTEST_DEBUG_OUTPUT_REPORTER_OVERRIDE(func, type, arg) \
3332 void func(type arg) override { \
3333 bool with_col = g_no_colors; \
3334 g_no_colors = false; \
3335 ConsoleReporter::func(arg); \
3336 if(oss.tellp() != std::streampos{}) { \
3337 DOCTEST_OUTPUT_DEBUG_STRING(oss.str().c_str()); \
3338 oss.str(""); \
3339 } \
3340 g_no_colors = with_col; \
3341 }
3342
3343 DOCTEST_DEBUG_OUTPUT_REPORTER_OVERRIDE(test_run_start, DOCTEST_EMPTY, DOCTEST_EMPTY)
3344 DOCTEST_DEBUG_OUTPUT_REPORTER_OVERRIDE(test_run_end, const TestRunStats&, in)
3345 DOCTEST_DEBUG_OUTPUT_REPORTER_OVERRIDE(test_case_start, const TestCaseData&, in)
3346 DOCTEST_DEBUG_OUTPUT_REPORTER_OVERRIDE(test_case_reenter, const TestCaseData&, in)
3347 DOCTEST_DEBUG_OUTPUT_REPORTER_OVERRIDE(test_case_end, const CurrentTestCaseStats&, in)
3348 DOCTEST_DEBUG_OUTPUT_REPORTER_OVERRIDE(test_case_exception, const TestCaseException&, in)
3349 DOCTEST_DEBUG_OUTPUT_REPORTER_OVERRIDE(subcase_start, const SubcaseSignature&, in)
3350 DOCTEST_DEBUG_OUTPUT_REPORTER_OVERRIDE(subcase_end, DOCTEST_EMPTY, DOCTEST_EMPTY)
3351 DOCTEST_DEBUG_OUTPUT_REPORTER_OVERRIDE(log_assert, const AssertData&, in)
3352 DOCTEST_DEBUG_OUTPUT_REPORTER_OVERRIDE(log_message, const MessageData&, in)
3353 DOCTEST_DEBUG_OUTPUT_REPORTER_OVERRIDE(test_case_skipped, const TestCaseData&, in)
3354 };
3355
3356 DOCTEST_THREAD_LOCAL std::ostringstream DebugOutputWindowReporter::oss;
3357#endif // DOCTEST_PLATFORM_WINDOWS
3358
3359 // the implementation of parseOption()
3360 bool parseOptionImpl(int argc, const char* const* argv, const char* pattern, String* value) {
3361 // going from the end to the beginning and stopping on the first occurrence from the end
3362 for(int i = argc; i > 0; --i) {
3363 auto index = i - 1;
3364 auto temp = std::strstr(argv[index], pattern);
3365 if(temp && (value || strlen(temp) == strlen(pattern))) {
3366 // eliminate matches in which the chars before the option are not '-'
3367 bool noBadCharsFound = true;
3368 auto curr = argv[index];
3369 while(curr != temp) {
3370 if(*curr++ != '-') {
3371 noBadCharsFound = false;
3372 break;
3373 }
3374 }
3375 if(noBadCharsFound && argv[index][0] == '-') {
3376 if(value) {
3377 // parsing the value of an option
3378 temp += strlen(pattern);
3379 const unsigned len = strlen(temp);
3380 if(len) {
3381 *value = temp;
3382 return true;
3383 }
3384 } else {
3385 // just a flag - no value
3386 return true;
3387 }
3388 }
3389 }
3390 }
3391 return false;
3392 }
3393
3394 // parses an option and returns the string after the '=' character
3395 bool parseOption(int argc, const char* const* argv, const char* pattern, String* value = nullptr,
3396 const String& defaultVal = String()) {
3397 if(value)
3398 *value = defaultVal;
3399#ifndef DOCTEST_CONFIG_NO_UNPREFIXED_OPTIONS
3400 // offset (normally 3 for "dt-") to skip prefix
3401 if(parseOptionImpl(argc, argv, pattern + strlen(DOCTEST_CONFIG_OPTIONS_PREFIX), value))
3402 return true;
3403#endif // DOCTEST_CONFIG_NO_UNPREFIXED_OPTIONS
3404 return parseOptionImpl(argc, argv, pattern, value);
3405 }
3406
3407 // locates a flag on the command line
3408 bool parseFlag(int argc, const char* const* argv, const char* pattern) {
3409 return parseOption(argc, argv, pattern);
3410 }
3411
3412 // parses a comma separated list of words after a pattern in one of the arguments in argv
3413 bool parseCommaSepArgs(int argc, const char* const* argv, const char* pattern,
3414 std::vector<String>& res) {
3415 String filtersString;
3416 if(parseOption(argc, argv, pattern, &filtersString)) {
3417 // tokenize with "," as a separator, unless escaped with backslash
3418 std::ostringstream s;
3419 auto flush = [&s, &res]() {
3420 auto string = s.str();
3421 if(string.size() > 0) {
3422 res.push_back(string.c_str());
3423 }
3424 s.str("");
3425 };
3426
3427 bool seenBackslash = false;
3428 const char* current = filtersString.c_str();
3429 const char* end = current + strlen(current);
3430 while(current != end) {
3431 char character = *current++;
3432 if(seenBackslash) {
3433 seenBackslash = false;
3434 if(character == ',' || character == '\\') {
3435 s.put(character);
3436 continue;
3437 }
3438 s.put('\\');
3439 }
3440 if(character == '\\') {
3441 seenBackslash = true;
3442 } else if(character == ',') {
3443 flush();
3444 } else {
3445 s.put(character);
3446 }
3447 }
3448
3449 if(seenBackslash) {
3450 s.put('\\');
3451 }
3452 flush();
3453 return true;
3454 }
3455 return false;
3456 }
3457
3458 enum optionType
3459 {
3460 option_bool,
3461 option_int
3462 };
3463
3464 // parses an int/bool option from the command line
3465 bool parseIntOption(int argc, const char* const* argv, const char* pattern, optionType type,
3466 int& res) {
3467 String parsedValue;
3468 if(!parseOption(argc, argv, pattern, &parsedValue))
3469 return false;
3470
3471 if(type) {
3472 // integer
3473 // TODO: change this to use std::stoi or something else! currently it uses undefined behavior - assumes '0' on failed parse...
3474 int theInt = std::atoi(parsedValue.c_str());
3475 if (theInt != 0) {
3476 res = theInt;
3477 return true;
3478 }
3479 } else {
3480 // boolean
3481 const char positive[][5] = { "1", "true", "on", "yes" }; // 5 - strlen("true") + 1
3482 const char negative[][6] = { "0", "false", "off", "no" }; // 6 - strlen("false") + 1
3483
3484 // if the value matches any of the positive/negative possibilities
3485 for (unsigned i = 0; i < 4; i++) {
3486 if (parsedValue.compare(positive[i], true) == 0) {
3487 res = 1;
3488 return true;
3489 }
3490 if (parsedValue.compare(negative[i], true) == 0) {
3491 res = 0;
3492 return true;
3493 }
3494 }
3495 }
3496 return false;
3497 }
3498} // namespace
3499
3500Context::Context(int argc, const char* const* argv)
3501 : p(new detail::ContextState) {
3502 parseArgs(argc, argv, true);
3503 if(argc)
3504 p->binary_name = argv[0];
3505}
3506
3507Context::~Context() {
3508 if(g_cs == p)
3509 g_cs = nullptr;
3510 delete p;
3511}
3512
3513void Context::applyCommandLine(int argc, const char* const* argv) {
3514 parseArgs(argc, argv);
3515 if(argc)
3516 p->binary_name = argv[0];
3517}
3518
3519// parses args
3520void Context::parseArgs(int argc, const char* const* argv, bool withDefaults) {
3521 using namespace detail;
3522
3523 // clang-format off
3524 parseCommaSepArgs(argc, argv, DOCTEST_CONFIG_OPTIONS_PREFIX "source-file=", p->filters[0]);
3525 parseCommaSepArgs(argc, argv, DOCTEST_CONFIG_OPTIONS_PREFIX "sf=", p->filters[0]);
3526 parseCommaSepArgs(argc, argv, DOCTEST_CONFIG_OPTIONS_PREFIX "source-file-exclude=",p->filters[1]);
3527 parseCommaSepArgs(argc, argv, DOCTEST_CONFIG_OPTIONS_PREFIX "sfe=", p->filters[1]);
3528 parseCommaSepArgs(argc, argv, DOCTEST_CONFIG_OPTIONS_PREFIX "test-suite=", p->filters[2]);
3529 parseCommaSepArgs(argc, argv, DOCTEST_CONFIG_OPTIONS_PREFIX "ts=", p->filters[2]);
3530 parseCommaSepArgs(argc, argv, DOCTEST_CONFIG_OPTIONS_PREFIX "test-suite-exclude=", p->filters[3]);
3531 parseCommaSepArgs(argc, argv, DOCTEST_CONFIG_OPTIONS_PREFIX "tse=", p->filters[3]);
3532 parseCommaSepArgs(argc, argv, DOCTEST_CONFIG_OPTIONS_PREFIX "test-case=", p->filters[4]);
3533 parseCommaSepArgs(argc, argv, DOCTEST_CONFIG_OPTIONS_PREFIX "tc=", p->filters[4]);
3534 parseCommaSepArgs(argc, argv, DOCTEST_CONFIG_OPTIONS_PREFIX "test-case-exclude=", p->filters[5]);
3535 parseCommaSepArgs(argc, argv, DOCTEST_CONFIG_OPTIONS_PREFIX "tce=", p->filters[5]);
3536 parseCommaSepArgs(argc, argv, DOCTEST_CONFIG_OPTIONS_PREFIX "subcase=", p->filters[6]);
3537 parseCommaSepArgs(argc, argv, DOCTEST_CONFIG_OPTIONS_PREFIX "sc=", p->filters[6]);
3538 parseCommaSepArgs(argc, argv, DOCTEST_CONFIG_OPTIONS_PREFIX "subcase-exclude=", p->filters[7]);
3539 parseCommaSepArgs(argc, argv, DOCTEST_CONFIG_OPTIONS_PREFIX "sce=", p->filters[7]);
3540 parseCommaSepArgs(argc, argv, DOCTEST_CONFIG_OPTIONS_PREFIX "reporters=", p->filters[8]);
3541 parseCommaSepArgs(argc, argv, DOCTEST_CONFIG_OPTIONS_PREFIX "r=", p->filters[8]);
3542 // clang-format on
3543
3544 int intRes = 0;
3545 String strRes;
3546
3547#define DOCTEST_PARSE_AS_BOOL_OR_FLAG(name, sname, var, default) \
3548 if(parseIntOption(argc, argv, DOCTEST_CONFIG_OPTIONS_PREFIX name "=", option_bool, intRes) || \
3549 parseIntOption(argc, argv, DOCTEST_CONFIG_OPTIONS_PREFIX sname "=", option_bool, intRes)) \
3550 p->var = static_cast<bool>(intRes); \
3551 else if(parseFlag(argc, argv, DOCTEST_CONFIG_OPTIONS_PREFIX name) || \
3552 parseFlag(argc, argv, DOCTEST_CONFIG_OPTIONS_PREFIX sname)) \
3553 p->var = true; \
3554 else if(withDefaults) \
3555 p->var = default
3556
3557#define DOCTEST_PARSE_INT_OPTION(name, sname, var, default) \
3558 if(parseIntOption(argc, argv, DOCTEST_CONFIG_OPTIONS_PREFIX name "=", option_int, intRes) || \
3559 parseIntOption(argc, argv, DOCTEST_CONFIG_OPTIONS_PREFIX sname "=", option_int, intRes)) \
3560 p->var = intRes; \
3561 else if(withDefaults) \
3562 p->var = default
3563
3564#define DOCTEST_PARSE_STR_OPTION(name, sname, var, default) \
3565 if(parseOption(argc, argv, DOCTEST_CONFIG_OPTIONS_PREFIX name "=", &strRes, default) || \
3566 parseOption(argc, argv, DOCTEST_CONFIG_OPTIONS_PREFIX sname "=", &strRes, default) || \
3567 withDefaults) \
3568 p->var = strRes
3569
3570 // clang-format off
3571 DOCTEST_PARSE_STR_OPTION("out", "o", out, "");
3572 DOCTEST_PARSE_STR_OPTION("order-by", "ob", order_by, "file");
3573 DOCTEST_PARSE_INT_OPTION("rand-seed", "rs", rand_seed, 0);
3574
3575 DOCTEST_PARSE_INT_OPTION("first", "f", first, 0);
3576 DOCTEST_PARSE_INT_OPTION("last", "l", last, UINT_MAX);
3577
3578 DOCTEST_PARSE_INT_OPTION("abort-after", "aa", abort_after, 0);
3579 DOCTEST_PARSE_INT_OPTION("subcase-filter-levels", "scfl", subcase_filter_levels, INT_MAX);
3580
3581 DOCTEST_PARSE_AS_BOOL_OR_FLAG("success", "s", success, false);
3582 DOCTEST_PARSE_AS_BOOL_OR_FLAG("case-sensitive", "cs", case_sensitive, false);
3583 DOCTEST_PARSE_AS_BOOL_OR_FLAG("exit", "e", exit, false);
3584 DOCTEST_PARSE_AS_BOOL_OR_FLAG("duration", "d", duration, false);
3585 DOCTEST_PARSE_AS_BOOL_OR_FLAG("minimal", "m", minimal, false);
3586 DOCTEST_PARSE_AS_BOOL_OR_FLAG("quiet", "q", quiet, false);
3587 DOCTEST_PARSE_AS_BOOL_OR_FLAG("no-throw", "nt", no_throw, false);
3588 DOCTEST_PARSE_AS_BOOL_OR_FLAG("no-exitcode", "ne", no_exitcode, false);
3589 DOCTEST_PARSE_AS_BOOL_OR_FLAG("no-run", "nr", no_run, false);
3590 DOCTEST_PARSE_AS_BOOL_OR_FLAG("no-intro", "ni", no_intro, false);
3591 DOCTEST_PARSE_AS_BOOL_OR_FLAG("no-version", "nv", no_version, false);
3592 DOCTEST_PARSE_AS_BOOL_OR_FLAG("no-colors", "nc", no_colors, false);
3593 DOCTEST_PARSE_AS_BOOL_OR_FLAG("force-colors", "fc", force_colors, false);
3594 DOCTEST_PARSE_AS_BOOL_OR_FLAG("no-breaks", "nb", no_breaks, false);
3595 DOCTEST_PARSE_AS_BOOL_OR_FLAG("no-skip", "ns", no_skip, false);
3596 DOCTEST_PARSE_AS_BOOL_OR_FLAG("gnu-file-line", "gfl", gnu_file_line, !bool(DOCTEST_MSVC));
3597 DOCTEST_PARSE_AS_BOOL_OR_FLAG("no-path-filenames", "npf", no_path_in_filenames, false);
3598 DOCTEST_PARSE_AS_BOOL_OR_FLAG("no-line-numbers", "nln", no_line_numbers, false);
3599 DOCTEST_PARSE_AS_BOOL_OR_FLAG("no-debug-output", "ndo", no_debug_output, false);
3600 DOCTEST_PARSE_AS_BOOL_OR_FLAG("no-skipped-summary", "nss", no_skipped_summary, false);
3601 DOCTEST_PARSE_AS_BOOL_OR_FLAG("no-time-in-output", "ntio", no_time_in_output, false);
3602 // clang-format on
3603
3604 if(withDefaults) {
3605 p->help = false;
3606 p->version = false;
3607 p->count = false;
3608 p->list_test_cases = false;
3609 p->list_test_suites = false;
3610 p->list_reporters = false;
3611 }
3612 if(parseFlag(argc, argv, DOCTEST_CONFIG_OPTIONS_PREFIX "help") ||
3613 parseFlag(argc, argv, DOCTEST_CONFIG_OPTIONS_PREFIX "h") ||
3614 parseFlag(argc, argv, DOCTEST_CONFIG_OPTIONS_PREFIX "?")) {
3615 p->help = true;
3616 p->exit = true;
3617 }
3618 if(parseFlag(argc, argv, DOCTEST_CONFIG_OPTIONS_PREFIX "version") ||
3619 parseFlag(argc, argv, DOCTEST_CONFIG_OPTIONS_PREFIX "v")) {
3620 p->version = true;
3621 p->exit = true;
3622 }
3623 if(parseFlag(argc, argv, DOCTEST_CONFIG_OPTIONS_PREFIX "count") ||
3624 parseFlag(argc, argv, DOCTEST_CONFIG_OPTIONS_PREFIX "c")) {
3625 p->count = true;
3626 p->exit = true;
3627 }
3628 if(parseFlag(argc, argv, DOCTEST_CONFIG_OPTIONS_PREFIX "list-test-cases") ||
3629 parseFlag(argc, argv, DOCTEST_CONFIG_OPTIONS_PREFIX "ltc")) {
3630 p->list_test_cases = true;
3631 p->exit = true;
3632 }
3633 if(parseFlag(argc, argv, DOCTEST_CONFIG_OPTIONS_PREFIX "list-test-suites") ||
3634 parseFlag(argc, argv, DOCTEST_CONFIG_OPTIONS_PREFIX "lts")) {
3635 p->list_test_suites = true;
3636 p->exit = true;
3637 }
3638 if(parseFlag(argc, argv, DOCTEST_CONFIG_OPTIONS_PREFIX "list-reporters") ||
3639 parseFlag(argc, argv, DOCTEST_CONFIG_OPTIONS_PREFIX "lr")) {
3640 p->list_reporters = true;
3641 p->exit = true;
3642 }
3643}
3644
3645// allows the user to add procedurally to the filters from the command line
3646void Context::addFilter(const char* filter, const char* value) { setOption(filter, value); }
3647
3648// allows the user to clear all filters from the command line
3649void Context::clearFilters() {
3650 for(auto& curr : p->filters)
3651 curr.clear();
3652}
3653
3654// allows the user to override procedurally the bool options from the command line
3655void Context::setOption(const char* option, bool value) {
3656 setOption(option, value ? "true" : "false");
3657}
3658
3659// allows the user to override procedurally the int options from the command line
3660void Context::setOption(const char* option, int value) {
3661 setOption(option, toString(value).c_str());
3662}
3663
3664// allows the user to override procedurally the string options from the command line
3665void Context::setOption(const char* option, const char* value) {
3666 auto argv = String("-") + option + "=" + value;
3667 auto lvalue = argv.c_str();
3668 parseArgs(1, &lvalue);
3669}
3670
3671// users should query this in their main() and exit the program if true
3672bool Context::shouldExit() { return p->exit; }
3673
3674void Context::setAsDefaultForAssertsOutOfTestCases() { g_cs = p; }
3675
3676void Context::setAssertHandler(detail::assert_handler ah) { p->ah = ah; }
3677
3678void Context::setCout(std::ostream* out) { p->cout = out; }
3679
3680static class DiscardOStream : public std::ostream
3681{
3682private:
3683 class : public std::streambuf
3684 {
3685 private:
3686 // allowing some buffering decreases the amount of calls to overflow
3687 char buf[1024];
3688
3689 protected:
3690 std::streamsize xsputn(const char_type*, std::streamsize count) override { return count; }
3691
3692 int_type overflow(int_type ch) override {
3693 setp(std::begin(buf), std::end(buf));
3694 return traits_type::not_eof(ch);
3695 }
3696 } discardBuf;
3697
3698public:
3699 DiscardOStream()
3700 : std::ostream(&discardBuf) {}
3701} discardOut;
3702
3703// the main function that does all the filtering and test running
3704int Context::run() {
3705 using namespace detail;
3706
3707 // save the old context state in case such was setup - for using asserts out of a testing context
3708 auto old_cs = g_cs;
3709 // this is the current contest
3710 g_cs = p;
3711 is_running_in_test = true;
3712
3713 g_no_colors = p->no_colors;
3714 p->resetRunData();
3715
3716 std::fstream fstr;
3717 if(p->cout == nullptr) {
3718 if(p->quiet) {
3719 p->cout = &discardOut;
3720 } else if(p->out.size()) {
3721 // to a file if specified
3722 fstr.open(p->out.c_str(), std::fstream::out);
3723 p->cout = &fstr;
3724 } else {
3725#ifndef DOCTEST_CONFIG_NO_INCLUDE_IOSTREAM
3726 // stdout by default
3727 p->cout = &std::cout;
3728#else // DOCTEST_CONFIG_NO_INCLUDE_IOSTREAM
3729 return EXIT_FAILURE;
3730#endif // DOCTEST_CONFIG_NO_INCLUDE_IOSTREAM
3731 }
3732 }
3733
3734 FatalConditionHandler::allocateAltStackMem();
3735
3736 auto cleanup_and_return = [&]() {
3737 FatalConditionHandler::freeAltStackMem();
3738
3739 if(fstr.is_open())
3740 fstr.close();
3741
3742 // restore context
3743 g_cs = old_cs;
3744 is_running_in_test = false;
3745
3746 // we have to free the reporters which were allocated when the run started
3747 for(auto& curr : p->reporters_currently_used)
3748 delete curr;
3749 p->reporters_currently_used.clear();
3750
3751 if(p->numTestCasesFailed && !p->no_exitcode)
3752 return EXIT_FAILURE;
3753 return EXIT_SUCCESS;
3754 };
3755
3756 // setup default reporter if none is given through the command line
3757 if(p->filters[8].empty())
3758 p->filters[8].push_back("console");
3759
3760 // check to see if any of the registered reporters has been selected
3761 for(auto& curr : getReporters()) {
3762 if(matchesAny(curr.first.second.c_str(), p->filters[8], false, p->case_sensitive))
3763 p->reporters_currently_used.push_back(curr.second(*g_cs));
3764 }
3765
3766 // TODO: check if there is nothing in reporters_currently_used
3767
3768 // prepend all listeners
3769 for(auto& curr : getListeners())
3770 p->reporters_currently_used.insert(p->reporters_currently_used.begin(), curr.second(*g_cs));
3771
3772#ifdef DOCTEST_PLATFORM_WINDOWS
3773 if(isDebuggerActive() && p->no_debug_output == false)
3774 p->reporters_currently_used.push_back(new DebugOutputWindowReporter(*g_cs));
3775#endif // DOCTEST_PLATFORM_WINDOWS
3776
3777 // handle version, help and no_run
3778 if(p->no_run || p->version || p->help || p->list_reporters) {
3779 DOCTEST_ITERATE_THROUGH_REPORTERS(report_query, QueryData());
3780
3781 return cleanup_and_return();
3782 }
3783
3784 std::vector<const TestCase*> testArray;
3785 for(auto& curr : getRegisteredTests())
3786 testArray.push_back(&curr);
3787 p->numTestCases = testArray.size();
3788
3789 // sort the collected records
3790 if(!testArray.empty()) {
3791 if(p->order_by.compare("file", true) == 0) {
3792 std::sort(testArray.begin(), testArray.end(), fileOrderComparator);
3793 } else if(p->order_by.compare("suite", true) == 0) {
3794 std::sort(testArray.begin(), testArray.end(), suiteOrderComparator);
3795 } else if(p->order_by.compare("name", true) == 0) {
3796 std::sort(testArray.begin(), testArray.end(), nameOrderComparator);
3797 } else if(p->order_by.compare("rand", true) == 0) {
3798 std::srand(p->rand_seed);
3799
3800 // random_shuffle implementation
3801 const auto first = &testArray[0];
3802 for(size_t i = testArray.size() - 1; i > 0; --i) {
3803 int idxToSwap = std::rand() % (i + 1);
3804
3805 const auto temp = first[i];
3806
3807 first[i] = first[idxToSwap];
3808 first[idxToSwap] = temp;
3809 }
3810 } else if(p->order_by.compare("none", true) == 0) {
3811 // means no sorting - beneficial for death tests which call into the executable
3812 // with a specific test case in mind - we don't want to slow down the startup times
3813 }
3814 }
3815
3816 std::set<String> testSuitesPassingFilt;
3817
3818 bool query_mode = p->count || p->list_test_cases || p->list_test_suites;
3819 std::vector<const TestCaseData*> queryResults;
3820
3821 if(!query_mode)
3822 DOCTEST_ITERATE_THROUGH_REPORTERS(test_run_start, DOCTEST_EMPTY);
3823
3824 // invoke the registered functions if they match the filter criteria (or just count them)
3825 for(auto& curr : testArray) {
3826 const auto& tc = *curr;
3827
3828 bool skip_me = false;
3829 if(tc.m_skip && !p->no_skip)
3830 skip_me = true;
3831
3832 if(!matchesAny(tc.m_file.c_str(), p->filters[0], true, p->case_sensitive))
3833 skip_me = true;
3834 if(matchesAny(tc.m_file.c_str(), p->filters[1], false, p->case_sensitive))
3835 skip_me = true;
3836 if(!matchesAny(tc.m_test_suite, p->filters[2], true, p->case_sensitive))
3837 skip_me = true;
3838 if(matchesAny(tc.m_test_suite, p->filters[3], false, p->case_sensitive))
3839 skip_me = true;
3840 if(!matchesAny(tc.m_name, p->filters[4], true, p->case_sensitive))
3841 skip_me = true;
3842 if(matchesAny(tc.m_name, p->filters[5], false, p->case_sensitive))
3843 skip_me = true;
3844
3845 if(!skip_me)
3846 p->numTestCasesPassingFilters++;
3847
3848 // skip the test if it is not in the execution range
3849 if((p->last < p->numTestCasesPassingFilters && p->first <= p->last) ||
3850 (p->first > p->numTestCasesPassingFilters))
3851 skip_me = true;
3852
3853 if(skip_me) {
3854 if(!query_mode)
3855 DOCTEST_ITERATE_THROUGH_REPORTERS(test_case_skipped, tc);
3856 continue;
3857 }
3858
3859 // do not execute the test if we are to only count the number of filter passing tests
3860 if(p->count)
3861 continue;
3862
3863 // print the name of the test and don't execute it
3864 if(p->list_test_cases) {
3865 queryResults.push_back(&tc);
3866 continue;
3867 }
3868
3869 // print the name of the test suite if not done already and don't execute it
3870 if(p->list_test_suites) {
3871 if((testSuitesPassingFilt.count(tc.m_test_suite) == 0) && tc.m_test_suite[0] != '\0') {
3872 queryResults.push_back(&tc);
3873 testSuitesPassingFilt.insert(tc.m_test_suite);
3874 p->numTestSuitesPassingFilters++;
3875 }
3876 continue;
3877 }
3878
3879 // execute the test if it passes all the filtering
3880 {
3881 p->currentTest = &tc;
3882
3883 p->failure_flags = TestCaseFailureReason::None;
3884 p->seconds = 0;
3885
3886 // reset atomic counters
3887 p->numAssertsFailedCurrentTest_atomic = 0;
3888 p->numAssertsCurrentTest_atomic = 0;
3889
3890 p->fullyTraversedSubcases.clear();
3891
3892 DOCTEST_ITERATE_THROUGH_REPORTERS(test_case_start, tc);
3893
3894 p->timer.start();
3895
3896 bool run_test = true;
3897
3898 do {
3899 // reset some of the fields for subcases (except for the set of fully passed ones)
3900 p->reachedLeaf = false;
3901 // May not be empty if previous subcase exited via exception.
3902 p->subcaseStack.clear();
3903 p->currentSubcaseDepth = 0;
3904
3905 p->shouldLogCurrentException = true;
3906
3907 // reset stuff for logging with INFO()
3908 p->stringifiedContexts.clear();
3909
3910#ifndef DOCTEST_CONFIG_NO_EXCEPTIONS
3911 try {
3912#endif // DOCTEST_CONFIG_NO_EXCEPTIONS
3913// MSVC 2015 diagnoses fatalConditionHandler as unused (because reset() is a static method)
3914DOCTEST_MSVC_SUPPRESS_WARNING_WITH_PUSH(4101) // unreferenced local variable
3915 FatalConditionHandler fatalConditionHandler; // Handle signals
3916 // execute the test
3917 tc.m_test();
3918 fatalConditionHandler.reset();
3919DOCTEST_MSVC_SUPPRESS_WARNING_POP
3920#ifndef DOCTEST_CONFIG_NO_EXCEPTIONS
3921 } catch(const TestFailureException&) {
3922 p->failure_flags |= TestCaseFailureReason::AssertFailure;
3923 } catch(...) {
3924 DOCTEST_ITERATE_THROUGH_REPORTERS(test_case_exception,
3925 {translateActiveException(), false});
3926 p->failure_flags |= TestCaseFailureReason::Exception;
3927 }
3928#endif // DOCTEST_CONFIG_NO_EXCEPTIONS
3929
3930 // exit this loop if enough assertions have failed - even if there are more subcases
3931 if(p->abort_after > 0 &&
3932 p->numAssertsFailed + p->numAssertsFailedCurrentTest_atomic >= p->abort_after) {
3933 run_test = false;
3934 p->failure_flags |= TestCaseFailureReason::TooManyFailedAsserts;
3935 }
3936
3937 if(!p->nextSubcaseStack.empty() && run_test)
3938 DOCTEST_ITERATE_THROUGH_REPORTERS(test_case_reenter, tc);
3939 if(p->nextSubcaseStack.empty())
3940 run_test = false;
3941 } while(run_test);
3942
3943 p->finalizeTestCaseData();
3944
3945 DOCTEST_ITERATE_THROUGH_REPORTERS(test_case_end, *g_cs);
3946
3947 p->currentTest = nullptr;
3948
3949 // stop executing tests if enough assertions have failed
3950 if(p->abort_after > 0 && p->numAssertsFailed >= p->abort_after)
3951 break;
3952 }
3953 }
3954
3955 if(!query_mode) {
3956 DOCTEST_ITERATE_THROUGH_REPORTERS(test_run_end, *g_cs);
3957 } else {
3958 QueryData qdata;
3959 qdata.run_stats = g_cs;
3960 qdata.data = queryResults.data();
3961 qdata.num_data = unsigned(queryResults.size());
3962 DOCTEST_ITERATE_THROUGH_REPORTERS(report_query, qdata);
3963 }
3964
3965 return cleanup_and_return();
3966}
3967
3968DOCTEST_DEFINE_INTERFACE(IReporter)
3969
3970int IReporter::get_num_active_contexts() { return detail::g_infoContexts.size(); }
3971const IContextScope* const* IReporter::get_active_contexts() {
3972 return get_num_active_contexts() ? &detail::g_infoContexts[0] : nullptr;
3973}
3974
3975int IReporter::get_num_stringified_contexts() { return detail::g_cs->stringifiedContexts.size(); }
3976const String* IReporter::get_stringified_contexts() {
3977 return get_num_stringified_contexts() ? &detail::g_cs->stringifiedContexts[0] : nullptr;
3978}
3979
3980namespace detail {
3981 void registerReporterImpl(const char* name, int priority, reporterCreatorFunc c, bool isReporter) {
3982 if(isReporter)
3983 getReporters().insert(reporterMap::value_type(reporterMap::key_type(priority, name), c));
3984 else
3985 getListeners().insert(reporterMap::value_type(reporterMap::key_type(priority, name), c));
3986 }
3987} // namespace detail
3988
3989} // namespace doctest
3990
3991#endif // DOCTEST_CONFIG_DISABLE
3992
3993#ifdef DOCTEST_CONFIG_IMPLEMENT_WITH_MAIN
3994DOCTEST_MSVC_SUPPRESS_WARNING_WITH_PUSH(4007) // 'function' : must be 'attribute' - see issue #182
3995int main(int argc, char** argv) { return doctest::Context(argc, argv).run(); }
3996DOCTEST_MSVC_SUPPRESS_WARNING_POP
3997#endif // DOCTEST_CONFIG_IMPLEMENT_WITH_MAIN
3998
3999DOCTEST_CLANG_SUPPRESS_WARNING_POP
4000DOCTEST_MSVC_SUPPRESS_WARNING_POP
4001DOCTEST_GCC_SUPPRESS_WARNING_POP
4002
4003DOCTEST_SUPPRESS_COMMON_WARNINGS_POP
4004
4005#endif // DOCTEST_LIBRARY_IMPLEMENTATION
4006#endif // DOCTEST_CONFIG_IMPLEMENT
4007
4008#ifdef DOCTEST_UNDEF_WIN32_LEAN_AND_MEAN
4009#undef WIN32_LEAN_AND_MEAN
4010#undef DOCTEST_UNDEF_WIN32_LEAN_AND_MEAN
4011#endif // DOCTEST_UNDEF_WIN32_LEAN_AND_MEAN
4012
4013#ifdef DOCTEST_UNDEF_NOMINMAX
4014#undef NOMINMAX
4015#undef DOCTEST_UNDEF_NOMINMAX
4016#endif // DOCTEST_UNDEF_NOMINMAX
Definition doctest.h:1965
Definition doctest.cpp:1428
Definition doctest.cpp:350
Definition doctest.h:536
Definition doctest.h:530
Definition how_subcases_work.cpp:32
Definition doctest.h:1210
Definition doctest.h:825
OCLINT too many fields.
Definition doctest.h:894
Definition doctest.h:2018
Definition doctest.h:2033
Definition doctest.cpp:422
void react()
Definition doctest.cpp:1931
bool log()
Definition doctest.cpp:1842
Definition doctest.h:1592
Definition doctest.cpp:312