-
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathUnitTest.mpp
More file actions
321 lines (279 loc) · 9.57 KB
/
UnitTest.mpp
File metadata and controls
321 lines (279 loc) · 9.57 KB
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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
module;
#include <cstdio>
export module CppUtils.UnitTest;
import std;
import CppUtils.Chrono.Concept;
import CppUtils.ChronoLogger;
import CppUtils.Container;
import CppUtils.Logger;
import CppUtils.Log.Exception;
import CppUtils.Log.Config.UnitTests;
import CppUtils.String;
import CppUtils.Terminal;
import CppUtils.System.Main;
export import CppUtils.UnitTest.DummyObject;
namespace CppUtils::UnitTest
{
export struct TestSettings final
{
bool verbose = true;
bool detail = true;
bool chrono = false;
bool fastAbort = false;
};
struct Test final
{
std::string name;
std::function<void(std::stop_token)> function;
std::chrono::seconds timeout = std::chrono::seconds{10};
};
class TestException: public std::runtime_error
{
public:
inline TestException(std::string message):
std::runtime_error{std::move(message)}
{}
};
class TestRunner final
{
using Logger = Logger<"UnitTests">;
public:
inline auto addTestSuite(const std::string& name, std::vector<Test> tests) -> void
{
for (auto& test : tests)
test.name = std::format("{}/{}", name, test.name);
m_testSuites.insert(name, std::move(tests));
}
inline auto addTestSuite(const std::string& name, std::vector<std::string> prerequisites, std::vector<Test> tests) -> void
{
addTestSuite(name, tests);
for (const auto& prerequisite : prerequisites)
m_testSuites.addDependency(name, prerequisite);
}
inline auto executeTest(const Test& test, const TestSettings& settings) const -> bool
{
using namespace std::chrono_literals;
if (settings.verbose)
{
Logger::emit<"separator">();
Logger::print<"detail">("{}:", test.name);
}
try
{
try
{
auto chronoLogger = Log::ChronoLogger{[](std::string_view duration) {
Logger::print<"detail">("Test duration: {}", duration);
}, settings.verbose and settings.chrono};
auto promise = std::promise<void>{};
auto future = promise.get_future();
auto worker = std::jthread{[promise = std::move(promise), function = test.function](std::stop_token stopToken) mutable {
try
{
function(stopToken);
promise.set_value();
}
catch (...)
{
promise.set_exception(std::current_exception());
}
}};
if (future.wait_for(test.timeout) == std::future_status::timeout)
{
worker.request_stop();
worker.detach();
throw TestException{std::format("Test timed out after {}s", test.timeout.count())};
}
future.get();
}
catch (const TestException&)
{
std::throw_with_nested(std::runtime_error{std::format("The following test didn't pass:\n{}", test.name)});
}
catch (const std::exception& exception)
{
std::throw_with_nested(std::runtime_error{std::format("An exception occurred during the test:\n{}\n{}", test.name, exception.what())});
}
}
catch (const std::exception& exception)
{
logException<Logger>(exception);
return false;
}
if (settings.verbose)
Logger::print<"success">("Passed");
Logger::waitUntilFinished(10s);
return true;
}
inline auto executeTests(TestSettings settings) -> int
{
using namespace std::chrono_literals;
auto testSuiteIsSuccess = std::unordered_map<std::string, bool>{};
const auto nbTests = std::ranges::fold_left(
std::views::values(m_testSuites.nodes) | std::views::transform([](auto&& node) { return std::ranges::size(node.value); }),
0uz,
std::plus{});
Logger::print<"info">("{} tests found. Execution:", nbTests);
auto failedTestSuites = std::vector<std::string>{};
auto skippedTestSuites = std::vector<std::string>{};
auto nbSuccess = 0uz;
auto nbFail = 0uz;
auto nbSkip = 0uz;
if (auto result = m_testSuites.forEach([&](const auto& name, const auto& tests, const auto& dependencies) -> bool {
if (std::empty(tests))
{
Logger::print<"warning">("No tests found in test suite {}", name);
testSuiteIsSuccess[name] = true;
return not settings.fastAbort;
}
for (const auto& dependency : dependencies)
if (not testSuiteIsSuccess[dependency])
{
Logger::print<"warning">("Skipping test suite {} due to failed prerequisites in test suite {}", name, dependency);
testSuiteIsSuccess[name] = false;
skippedTestSuites.push_back(name);
nbSkip += std::size(tests);
return not settings.fastAbort;
}
auto allTestsPassed = true;
for (const auto& test : tests)
{
if (executeTest(test, settings))
++nbSuccess;
else
{
++nbFail;
allTestsPassed = false;
if (settings.fastAbort)
break;
}
}
testSuiteIsSuccess[name] = allTestsPassed;
if (not allTestsPassed)
failedTestSuites.push_back(name);
return allTestsPassed or not settings.fastAbort;
});
not result)
Logger::print<"error">("The tests cannot be run: {}", result.error());
Logger::emit<"separator">();
Logger::print<"detail">("Test results");
if (nbFail == 0 and nbSkip == 0)
{
Logger::print<"success">("All tests passed successfully");
return exitSuccess;
}
if (nbFail > 0)
Logger::emit<"color">(Terminal::TextColor::TextColorEnum::Red, "The tests failed:");
else
Logger::emit<"color">(Terminal::TextColor::TextColorEnum::Yellow, "Some tests were skipped:");
if (nbSuccess > 0)
Logger::print<"success">("- {} successful tests", nbSuccess);
if (nbSuccess == 0)
Logger::emit<"color">(Terminal::TextColor::TextColorEnum::Red, "- 0 successful tests");
if (nbFail > 0)
{
Logger::emit<"color">(Terminal::TextColor::TextColorEnum::Red, std::format("- {} failed tests", nbFail));
for (const auto& failedTestSuite : failedTestSuites)
Logger::emit<"color">(Terminal::TextColor::TextColorEnum::Red, std::format(" - {}", failedTestSuite));
}
if (nbSkip > 0)
{
Logger::emit<"color">(Terminal::TextColor::TextColorEnum::Yellow, std::format("- {} skipped tests (due to failed dependencies)", nbSkip));
for (const auto& skippedTestSuite : skippedTestSuites)
Logger::emit<"color">(Terminal::TextColor::TextColorEnum::Yellow, std::format(" - {}", skippedTestSuite));
}
Logger::waitUntilFinished(10s);
return nbFail == 0 ? exitSuccess : exitFailure;
}
private:
Container::DependencyGraph<std::string, std::vector<Test>> m_testSuites;
};
inline /* constinit */ auto testRunner = TestRunner{};
export struct TestSuite final
{
using Logger = Logger<"UnitTests">;
inline explicit TestSuite(const std::string& name, std::vector<std::string> prerequisites, std::function<void(TestSuite&)> function)
{
function(*this);
testRunner.addTestSuite(name, prerequisites, std::move(tests));
}
inline explicit TestSuite(std::string name, std::function<void(TestSuite&)> function)
{
function(*this);
testRunner.addTestSuite(name, std::move(tests));
}
inline auto addTest(std::string name, std::function<void(std::stop_token)> function, std::chrono::seconds timeout = std::chrono::seconds{10}) -> void
{
tests.emplace_back(std::move(name), std::move(function), timeout);
}
inline auto addTest(std::string name, std::function<void()> function, std::chrono::seconds timeout = std::chrono::seconds{10}) -> void
{
tests.emplace_back(std::move(name), [function = std::move(function)](std::stop_token) { function(); }, timeout);
}
// Todo C++23: std::stacktrace stacktrace = std::current_stacktrace()
inline auto expect(bool condition, std::source_location sourceLocation = std::source_location::current()) -> void
{
if (not condition) [[unlikely]]
throw TestException{std::format("In {}\nAt line {}, column {}\nIn expect(condition)",
sourceLocation.file_name(),
sourceLocation.line(),
sourceLocation.column())};
}
inline auto expectEqual(const auto& lhs, const auto& rhs, std::source_location sourceLocation = std::source_location::current()) -> void
{
if (lhs != rhs) [[unlikely]]
throw TestException{std::format("In {}\nAt line {}, column {}\nIn expectEqual(lhs, rhs)\nwith lhs:\n{}\nand rhs:\n{}",
sourceLocation.file_name(),
sourceLocation.line(),
sourceLocation.column(),
String::formatValue(lhs),
String::formatValue(rhs))};
}
template<class ExceptionType>
inline auto expectThrow(auto&& function, std::source_location sourceLocation = std::source_location::current()) -> void
{
try
{
function();
throw TestException{std::format("In {}\nAt line {}, column {}\nExpected throw of type {}, but no exception was thrown.",
sourceLocation.file_name(),
sourceLocation.line(),
sourceLocation.column(),
typeid(ExceptionType).name())};
}
catch (const ExceptionType&)
{
Logger::emit<"success">("Expected exception caught.");
}
catch (const std::exception& exception)
{
throw TestException{std::format("In {}\nAt line {}, column {}\nExpected throw of type {}, but caught different exception: {}",
sourceLocation.file_name(),
sourceLocation.line(),
sourceLocation.column(),
typeid(ExceptionType).name(),
exception.what())};
}
}
inline auto expectNoThrow(auto&& function, std::source_location sourceLocation = std::source_location::current()) -> void
{
try
{
function();
}
catch (const std::exception& exception)
{
throw TestException{std::format("In {}\nAt line {}, column {}\nExpected no throw, but an exception was thrown: {}",
sourceLocation.file_name(),
sourceLocation.line(),
sourceLocation.column(),
exception.what())};
}
}
std::vector<Test> tests;
};
export inline auto executeTests(TestSettings settings) -> int
{
return testRunner.executeTests(std::move(settings));
}
}