forked from doctest/doctest
-
Notifications
You must be signed in to change notification settings - Fork 1
/
asserts_used_outside_of_tests.cpp
72 lines (57 loc) · 2.6 KB
/
asserts_used_outside_of_tests.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
#ifndef DOCTEST_CONFIG_DISABLE
#define DOCTEST_CONFIG_SUPER_FAST_ASSERTS // defined so the asserts are crazy fast - both for compilation and execution
#endif
#include <doctest/doctest.h>
#include "header.h"
DOCTEST_MAKE_STD_HEADERS_CLEAN_FROM_WARNINGS_ON_WALL_BEGIN
#include <iostream>
#include <cstring>
#include <algorithm>
DOCTEST_MAKE_STD_HEADERS_CLEAN_FROM_WARNINGS_ON_WALL_END
DOCTEST_GCC_SUPPRESS_WARNING("-Wmissing-declarations")
DOCTEST_CLANG_SUPPRESS_WARNING("-Wmissing-prototypes")
// some function which uses asserts not just for unit testing but also for ensuring contracts in production code
static void some_func() {
CHECK_EQ(true, false);
CHECK_UNARY(false);
CHECK_UNARY_FALSE(true);
CHECK(false);
CHECK_THROWS(std::cout << "hello! \n");
}
static void handler(const doctest::AssertData& ad) {
using namespace doctest;
// here we can choose what to do:
// - log the failed assert
// - throw an exception
// - call std::abort() or std::terminate()
std::cout << Color::LightGrey << skipPathFromFilename(ad.m_file) << "(" << ad.m_line << "): ";
std::cout << Color::Red << failureString(ad.m_at) << ": ";
// handling only normal (comparison and unary) asserts - nothing exceptions-related
if(ad.m_at & assertType::is_normal) {
std::cout << Color::Cyan << assertString(ad.m_at) << "( " << ad.m_expr << " ) ";
std::cout << Color::None << (ad.m_threw ? "THREW exception: " : "is NOT correct!\n");
if(ad.m_threw)
std::cout << ad.m_exception;
else
std::cout << " values: " << assertString(ad.m_at) << "( " << ad.m_decomp << " )";
} else {
std::cout << Color::None << "an assert dealing with exceptions has failed!";
}
std::cout << std::endl;
}
void some_program_code(int argc, char** argv) {
// return if the current test from the doctest CMake tests is not for this file
if(std::find_if(argv, argv + argc, [](const char* str) {
return strcmp(str, "-sf=*asserts_used_outside_of_tests.cpp") == 0;
}) == argv + argc)
return;
// construct a context
doctest::Context context(argc, argv);
// sets the context as the default one - so asserts used outside of a testing context do not crash
context.setAsDefaultForAssertsOutOfTestCases();
// set a handler with a signature: void(const doctest::AssertData&)
// without setting a handler we would get std::abort() called when an assert fails
context.setAssertHandler(handler);
// call the function with asserts out of a testing context - the above handler will be called on failure
some_func();
}