Repository navigation
Expand file tree
/
Copy pathUnitTest.mpp
More file actions
807 lines (747 loc) · 32.7 KB
/
Copy pathUnitTest.mpp
File metadata and controls
807 lines (747 loc) · 32.7 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
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
module;
#if not defined(_WIN32)
# include <signal.h>
#endif
export module CppUtils.UnitTest;
import std;
import CppUtils.Chrono;
import CppUtils.Container;
import CppUtils.Logger;
import CppUtils.Log.Exception;
import CppUtils.Log.Config.UnitTests;
import CppUtils.String;
import CppUtils.Terminal;
import CppUtils.System;
import CppUtils.Math.Utility;
import CppUtils.Math.Random;
import CppUtils.Language.Parameters;
import CppUtils.Thread;
import CppUtils.Type;
export import CppUtils.UnitTest.Assertion;
export import CppUtils.UnitTest.Benchmark;
export import CppUtils.UnitTest.EventWatcher;
export import CppUtils.UnitTest.Expectation;
export import CppUtils.UnitTest.JUnitFormatter;
export import CppUtils.UnitTest.LifetimeChecker;
export import CppUtils.UnitTest.Report;
export import CppUtils.UnitTest.Runner;
namespace CppUtils::UnitTest
{
/**
* @brief Core test suite execution context providing assertion methods, builders, and test registration.
*
* Instances are passed to test suite definitions configured via `testSuite("SuiteName") = [](TestSuite& suite) { ... };`.
* Supports regular tests, compile-time tests, parameterized tests (types, values, ranges), fuzz tests, and benchmarks.
*
* @see https://morgancaron.github.io/CppUtils/fr/guides/unit-test/ (Guide des tests unitaires)
* @see https://morgancaron.github.io/CppUtils/en/guides/unit-test/ (Unit test guide)
*/
export struct TestSuite final
{
using Logger = Logger<"UnitTests">;
private:
friend struct TestSuiteBuilder;
friend struct TestBuilder;
friend struct FuzzTestBuilder;
template<class... Types>
friend struct TypedTestSuiteBuilder;
template<class ValuesContainer>
friend struct ParameterizedTestSuiteBuilder;
inline explicit TestSuite(const std::string& name, std::vector<std::string> prerequisites, auto&& function)
{
function(*this);
testRunner.addTestSuite(name, prerequisites, 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);
}
static constexpr auto forEachParameterValue(const auto& container, auto&& invocable)
{
if constexpr (Type::Specializes<std::remove_cvref_t<decltype(container)>, std::tuple>)
{
std::apply([&](const auto&... values) {
(invocable(values), ...);
}, container);
}
else
{
for (const auto& value : container)
invocable(value);
}
}
static auto formatParameterName(std::string_view baseName, const auto& value, std::size_t& index) -> std::string
{
if constexpr (requires { std::format("{}", value); })
return std::format("{} [{}]", baseName, value);
else
return std::format("{} [value {}]", baseName, index++);
}
public:
/**
* @brief Base CRTP helper providing timeout configuration for test builders.
* @tparam Derived Derived builder type for method chaining.
*/
template<class Derived>
struct TimeoutBuilder
{
std::chrono::seconds testTimeout{10}; ///< Maximum execution timeout duration.
/**
* @brief Sets the execution timeout before the test is aborted.
* @param newTimeout Timeout duration.
* @return Reference to this builder.
*/
inline auto timeout(std::chrono::seconds newTimeout) -> Derived&
{
testTimeout = newTimeout;
return static_cast<Derived&>(*this);
}
};
/**
* @brief Builder for registering type-parameterized tests within a TestSuite.
* @note Returned by TestBuilder::forTypes(); not intended to be instantiated directly by user code.
* @tparam Types Type list to instantiate the test with.
*
* @see https://morgancaron.github.io/CppUtils/fr/guides/unit-test/#itération-sur-une-liste-de-types-fortypes (Tests paramétrés par types)
* @see https://morgancaron.github.io/CppUtils/en/guides/unit-test/#iterating-over-a-list-of-types-fortypes (Type-parameterized tests)
*/
template<class... Types>
struct TypedTestBuilder final: TimeoutBuilder<TypedTestBuilder<Types...>>
{
using TimeoutBuilder<TypedTestBuilder<Types...>>::testTimeout;
TestSuite& parentSuite; ///< Reference to the enclosing test suite registering the tests.
std::string testName; ///< Identifier of the test case.
TypedTestBuilder(std::chrono::seconds timeout, TestSuite& suite, std::string name):
TimeoutBuilder<TypedTestBuilder<Types...>>{timeout},
parentSuite{suite},
testName{std::move(name)}
{}
/**
* @brief Registers the test implementation callback invoked for each type.
* @param function Invocable accepting either a template type argument or `std::type_identity<Type>`.
*/
inline auto operator=(auto&& function) -> void
{
auto index = 0uz;
auto registerType = [&]<class Type>() {
auto name = std::format("{} [type {}]", testName, index++);
if constexpr (requires { function.template operator()<Type>(); })
parentSuite.addTest(std::move(name), [function] {
function.template operator()<Type>();
}, testTimeout);
else if constexpr (requires { function(std::type_identity<Type>{}); })
parentSuite.addTest(std::move(name), [function] {
function(std::type_identity<Type>{});
}, testTimeout);
else if constexpr (requires (std::stop_token token) { function.template operator()<Type>(token); })
parentSuite.addTest(std::move(name), [function](std::stop_token token) {
function.template operator()<Type>(token);
}, testTimeout);
else if constexpr (requires (std::stop_token token) { function(std::type_identity<Type>{}, token); })
parentSuite.addTest(std::move(name), [function](std::stop_token token) {
function(std::type_identity<Type>{}, token);
}, testTimeout);
};
(registerType.template operator()<Types>(), ...);
}
};
/**
* @brief Builder for registering a test parameterized over values (std::tuple or input range).
* @note Returned by TestBuilder::forValues(); not intended to be instantiated or manipulated directly by user code.
* @tparam ValuesContainer Container holding parameter values (std::tuple or input range).
*
* @see https://morgancaron.github.io/CppUtils/fr/guides/unit-test/#itération-sur-une-liste-de-valeurs-forvalues (Tests paramétrés par valeurs)
* @see https://morgancaron.github.io/CppUtils/en/guides/unit-test/#iterating-over-a-list-of-values-forvalues (Value-parameterized tests)
*/
template<class ValuesContainer>
struct ParameterizedTestBuilder final: TimeoutBuilder<ParameterizedTestBuilder<ValuesContainer>>
{
using TimeoutBuilder<ParameterizedTestBuilder<ValuesContainer>>::testTimeout;
TestSuite& parentSuite; ///< Reference to the enclosing test suite registering the tests.
std::string testName; ///< Identifier of the test case.
ValuesContainer values; ///< Discrete values tuple or range of values.
ParameterizedTestBuilder(std::chrono::seconds timeout, TestSuite& suite, std::string name, ValuesContainer valuesContainer):
TimeoutBuilder<ParameterizedTestBuilder<ValuesContainer>>{timeout},
parentSuite{suite},
testName{std::move(name)},
values{std::move(valuesContainer)}
{}
/**
* @brief Registers the test implementation callback invoked for each parameter value.
* @param function Invocable accepting the parameter value.
*/
inline auto operator=(auto&& function) -> void
{
auto index = 0uz;
forEachParameterValue(values, [&](const auto& value) {
auto name = formatParameterName(testName, value, index);
if constexpr (requires { function(value); })
parentSuite.addTest(std::move(name), [function, value] {
function(value);
}, testTimeout);
else if constexpr (requires (std::stop_token token) { function(value, token); })
parentSuite.addTest(std::move(name), [function, value](std::stop_token token) {
function(value, token);
}, testTimeout);
});
}
};
template<class... Values>
using ValueTestBuilder = ParameterizedTestBuilder<std::tuple<Values...>>;
template<std::ranges::input_range Range>
using RangeTestBuilder = ParameterizedTestBuilder<Range>;
/**
* @brief Builder for configuring and registering an individual test case.
* @note Returned by TestSuite::test(std::string); not intended to be instantiated directly by user code.
*
* @see https://morgancaron.github.io/CppUtils/fr/guides/unit-test/#déclarer-une-suite-de-tests (Déclarer une suite de tests)
* @see https://morgancaron.github.io/CppUtils/en/guides/unit-test/#declaring-a-test-suite (Declaring a test suite)
*/
struct TestBuilder final: TimeoutBuilder<TestBuilder>
{
TestSuite& parentSuite; ///< Reference to the enclosing test suite registering the test.
std::string testName; ///< Identifier of the test case.
TestBuilder(std::chrono::seconds timeout, TestSuite& suite, std::string name):
TimeoutBuilder<TestBuilder>{timeout},
parentSuite{suite},
testName{std::move(name)}
{}
/**
* @brief Converts this test into a type-parameterized test across the specified types.
* @tparam Types Type parameters to instantiate the test with.
* @return TypedTestBuilder instance.
*/
template<class... Types>
[[nodiscard]] inline auto forTypes() -> TypedTestBuilder<Types...>
{
return TypedTestBuilder<Types...>{testTimeout, parentSuite, std::move(testName)};
}
/**
* @brief Converts this test into a value-parameterized test across discrete values or a range.
* @tparam Values Value types or single range type.
* @param values Values or range to iterate over.
* @return ParameterizedTestBuilder instance.
*/
template<class... Values>
[[nodiscard]] inline auto forValues(Values&&... values)
{
if constexpr (sizeof...(Values) == 1 and (std::ranges::input_range<std::decay_t<Values>> and ...))
return ParameterizedTestBuilder<std::decay_t<Values>...>{
testTimeout, parentSuite, std::move(testName), (std::forward<Values>(values), ...)};
else
return ParameterizedTestBuilder<std::tuple<std::decay_t<Values>...>>{
testTimeout, parentSuite, std::move(testName), std::make_tuple(std::forward<Values>(values)...)};
}
/**
* @brief Assigns the test body callback and registers the test into the parent suite.
* @param function Invocable containing test logic (accepts optional std::stop_token).
*/
inline auto operator=(auto&& function) -> void
{
if constexpr (std::is_invocable_v<decltype(function), std::stop_token>)
parentSuite.addTest(std::move(testName), std::forward<decltype(function)>(function), testTimeout);
else
parentSuite.addTest(std::move(testName), [function = std::forward<decltype(function)>(function)] { function(); }, testTimeout);
}
};
/**
* @brief Builder for configuring and registering a randomized fuzz test.
* @note Returned by TestSuite::fuzzTest(std::string, std::size_t); not intended to be instantiated directly by user code.
*
* @see https://morgancaron.github.io/CppUtils/fr/guides/unit-test/#tests-de-robustesse-et-fuzzing-fuzztest-et-fuzz (Tests de robustesse et fuzzing)
* @see https://morgancaron.github.io/CppUtils/en/guides/unit-test/#robustness-testing-and-fuzzing-fuzztest-and-fuzz (Fuzz testing)
*/
struct FuzzTestBuilder final: TimeoutBuilder<FuzzTestBuilder>
{
TestSuite& parentSuite; ///< Reference to the enclosing test suite registering the test.
std::string testName; ///< Identifier of the test case.
std::size_t testIterations; ///< Number of randomized iterations to execute.
std::uint64_t testSeed{Math::DeterministicRandomEngine::defaultSeed}; ///< Deterministic pseudo-random number generator initial seed.
/**
* @brief Sets the deterministic initial pseudo-random number generator seed for fuzz reproducibility.
* @param newSeed Seed value.
* @return Reference to this builder.
*/
inline auto seed(std::uint64_t newSeed) -> FuzzTestBuilder&
{
testSeed = newSeed;
return *this;
}
/**
* @brief Registers the fuzz test callback executed for the configured iteration count.
* @param function Invocable accepting a DeterministicRandomEngine&.
*/
inline auto operator=(auto&& function) -> void
{
parentSuite.addTest(std::move(testName), [iterations = testIterations, function = std::forward<decltype(function)>(function), seed = testSeed](std::stop_token stopToken) {
auto fuzzer = Math::DeterministicRandomEngine{seed};
for (auto _ : std::views::iota(0uz, iterations))
{
if (stopToken.stop_requested())
break;
function(fuzzer);
}
}, testTimeout);
}
};
/**
* @brief Declares a test case with the specified name, returning a builder to configure and assign its body.
* @param name Descriptive test name.
* @return TestBuilder instance.
*/
[[nodiscard]] inline auto test(std::string name) -> TestBuilder
{
return TestBuilder{std::chrono::seconds{10}, *this, std::move(name)};
}
/**
* @brief Evaluates a test predicate at compile time via static_assert and registers it as a passed test.
*
* The template predicate is evaluated at compile time: any assertion failure immediately breaks
* the build before the test executable is even run.
*
* At runtime, this method registers an empty test body in the test runner so that the test appears
* in reports and metrics while avoiding the process isolation fork() overhead of runtime test cases.
* Prefer this overload when verifying constexpr functions, concepts, type traits, or template metaprogramming.
*
* @tparam Predicate Constexpr invocable returning a boolean or performing static assertions.
* @param name Descriptive test name.
*/
template<auto Predicate>
inline auto test(std::string name) -> void
{
if constexpr (requires { { Predicate() } -> std::convertible_to<bool>; })
{
static_assert(Predicate(), "Compile-time test assertion evaluated to false");
}
else
{
constexpr auto runTest = [] {
Predicate();
return true;
};
static_assert(runTest(), "Compile-time test failed");
}
addTest(std::move(name), [] {});
}
/**
* @brief Registers a fuzz test executed for a specified number of randomized iterations.
* @param name Test identifier.
* @param iterations Number of iterations to run.
* @return FuzzTestBuilder for assigning the test body callback.
*/
[[nodiscard]] inline auto fuzzTest(std::string name, std::size_t iterations) -> FuzzTestBuilder
{
return FuzzTestBuilder{.parentSuite = *this, .testName = std::move(name), .testIterations = iterations};
}
std::vector<TestCase> tests;
};
/**
* @brief Tag token returned by test suite registration assignments.
* @note Returned upon assigning a suite callback (e.g. via TestSuiteBuilder::operator=); not intended to be instantiated, stored, or managed directly by user code.
*
* @see https://morgancaron.github.io/CppUtils/fr/guides/unit-test/#déclarer-une-suite-de-tests (Déclarer une suite de tests)
* @see https://morgancaron.github.io/CppUtils/en/guides/unit-test/#declaring-a-test-suite (Declaring a test suite)
*/
export struct TestSuiteRegistration final
{};
/**
* @brief Builder for registering an entire test suite parameterized over a list of types.
* @note Returned by TestSuiteBuilder::forTypes(); not intended to be instantiated directly by user code.
* @tparam Types Type parameters instantiated for each suite instance.
*
* @see https://morgancaron.github.io/CppUtils/fr/guides/unit-test/#paramétrage-au-niveau-dune-suite-complète (Suites de tests paramétrées)
* @see https://morgancaron.github.io/CppUtils/en/guides/unit-test/#parameterization-on-a-complete-suite (Parameterized test suites)
*/
export template<class... Types>
struct TypedTestSuiteBuilder final
{
std::string name; ///< Identifier of the test suite.
std::vector<std::string> prerequisites; ///< Names of prerequisite test suites that must succeed before this suite runs.
/**
* @brief Registers the suite callback instantiated for each specified type.
* @param function Invocable accepting (TestSuite&) and optional `std::type_identity<Type>`.
* @return TestSuiteRegistration token.
*/
inline auto operator=(auto&& function) -> TestSuiteRegistration
{
auto index = 0uz;
auto registerType = [&]<class Type>() {
auto suiteName = std::format("{} [type {}]", name, index++);
auto registeredSuite = TestSuite{std::move(suiteName), prerequisites, [function](TestSuite& suite) {
if constexpr (requires { function.template operator()<Type>(suite); })
function.template operator()<Type>(suite);
else if constexpr (requires { function(suite, std::type_identity<Type>{}); })
function(suite, std::type_identity<Type>{});
}};
};
(registerType.template operator()<Types>(), ...);
return TestSuiteRegistration{};
}
};
/**
* @brief Builder for registering an entire test suite parameterized over values (std::tuple or input range).
* @note Returned by TestSuiteBuilder::forValues(); not intended to be instantiated or manipulated directly by user code.
* @tparam ValuesContainer Container holding parameter values (std::tuple or input range).
*
* @see https://morgancaron.github.io/CppUtils/fr/guides/unit-test/#paramétrage-au-niveau-dune-suite-complète (Suites de tests paramétrées)
* @see https://morgancaron.github.io/CppUtils/en/guides/unit-test/#parameterization-on-a-complete-suite (Parameterized test suites)
*/
export template<class ValuesContainer>
struct ParameterizedTestSuiteBuilder final
{
std::string name; ///< Identifier of the test suite.
std::vector<std::string> prerequisites; ///< Names of prerequisite test suites that must succeed before this suite runs.
ValuesContainer values; ///< Discrete values tuple or range of values.
/**
* @brief Registers the suite callback instantiated for each parameter value.
* @param function Invocable accepting (TestSuite&, const Value&).
* @return TestSuiteRegistration token.
*/
inline auto operator=(auto&& function) -> TestSuiteRegistration
{
auto index = 0uz;
TestSuite::forEachParameterValue(values, [&](const auto& value) {
auto suiteName = TestSuite::formatParameterName(name, value, index);
auto registeredSuite = TestSuite{std::move(suiteName), prerequisites, [function, value](TestSuite& suite) {
function(suite, value);
}};
});
return TestSuiteRegistration{};
}
};
/**
* @brief Builder for registering a test suite parameterized over a discrete pack of values.
* @note Returned by TestSuiteBuilder::forValues(...); not intended to be instantiated or manipulated directly by user code.
*
* Wraps the variadic parameter pack into a `std::tuple` container passed to ParameterizedTestSuiteBuilder.
*
* @tparam Values Types of the individual parameter values.
*
* @see https://morgancaron.github.io/CppUtils/fr/guides/unit-test/#paramétrage-au-niveau-dune-suite-complète (Suites de tests paramétrées)
* @see https://morgancaron.github.io/CppUtils/en/guides/unit-test/#parameterization-on-a-complete-suite (Parameterized test suites)
*/
export template<class... Values>
using ValueTestSuiteBuilder = ParameterizedTestSuiteBuilder<std::tuple<Values...>>;
/**
* @brief Builder for registering a test suite parameterized over an input range.
* @note Returned by TestSuiteBuilder::forValues(range); not intended to be instantiated or manipulated directly by user code.
*
* Evaluates each element of the provided range as an independent test suite parameter.
*
* @tparam Range Type satisfying std::ranges::input_range.
*
* @see https://morgancaron.github.io/CppUtils/fr/guides/unit-test/#paramétrage-au-niveau-dune-suite-complète (Suites de tests paramétrées)
* @see https://morgancaron.github.io/CppUtils/en/guides/unit-test/#parameterization-on-a-complete-suite (Parameterized test suites)
*/
export template<std::ranges::input_range Range>
using RangeTestSuiteBuilder = ParameterizedTestSuiteBuilder<Range>;
/**
* @brief Top-level builder used to declare a test suite, configure dependencies, and define its body.
* @note Returned by testSuite(std::string); not intended to be instantiated directly by user code.
*
* @see https://morgancaron.github.io/CppUtils/fr/guides/unit-test/#déclarer-une-suite-de-tests (Déclarer une suite de tests)
* @see https://morgancaron.github.io/CppUtils/en/guides/unit-test/#declaring-a-test-suite (Declaring a test suite)
*/
export struct TestSuiteBuilder final
{
std::string name; ///< Identifier of the test suite.
std::vector<std::string> prerequisites; ///< Names of prerequisite test suites that must succeed before this suite runs.
/**
* @brief Adds prerequisite test suites that must succeed before executing this suite.
* @param dependencies Prerequisite test suite names.
* @return Reference to this builder.
*/
template<class... Dependencies>
requires (std::is_convertible_v<Dependencies, std::string> and ...)
inline auto dependsOn(Dependencies&&... dependencies) -> TestSuiteBuilder&
{
(prerequisites.emplace_back(std::forward<Dependencies>(dependencies)), ...);
return *this;
}
/**
* @brief Converts this suite into a type-parameterized test suite.
* @tparam Types Type parameter list.
* @return TypedTestSuiteBuilder instance.
*/
template<class... Types>
[[nodiscard]] inline auto forTypes() -> TypedTestSuiteBuilder<Types...>
{
return TypedTestSuiteBuilder<Types...>{.name = std::move(name), .prerequisites = std::move(prerequisites)};
}
/**
* @brief Converts this suite into a value-parameterized test suite over values or a range.
* @tparam Values Value types or single range type.
* @param values Values or range to parameterize the suite with.
* @return ParameterizedTestSuiteBuilder instance.
*/
template<class... Values>
[[nodiscard]] inline auto forValues(Values&&... values)
{
if constexpr (sizeof...(Values) == 1 and (std::ranges::input_range<std::decay_t<Values>> and ...))
return ParameterizedTestSuiteBuilder<std::decay_t<Values>...>{
.name = std::move(name),
.prerequisites = std::move(prerequisites),
.values = (std::forward<Values>(values), ...)};
else
return ParameterizedTestSuiteBuilder<std::tuple<std::decay_t<Values>...>>{
.name = std::move(name),
.prerequisites = std::move(prerequisites),
.values = std::make_tuple(std::forward<Values>(values)...)};
}
/**
* @brief Registers the test suite callback into the global test runner.
* @param function Invocable accepting a TestSuite&.
* @return TestSuiteRegistration token.
*/
inline auto operator=(auto&& function) -> TestSuiteRegistration
{
auto registeredSuite = TestSuite{std::move(name), std::move(prerequisites), std::forward<decltype(function)>(function)};
return TestSuiteRegistration{};
}
};
/**
* @brief Declares a test suite.
*
* @param name Descriptive test suite identifier.
* @return TestSuiteBuilder used to configure dependencies or assign suite body.
*
* @see https://morgancaron.github.io/CppUtils/fr/guides/unit-test/#déclarer-une-suite-de-tests (Guide des tests unitaires)
* @see https://morgancaron.github.io/CppUtils/en/guides/unit-test/#declaring-a-test-suite (Unit test guide)
*/
export [[nodiscard]] inline auto testSuite(std::string name) -> TestSuiteBuilder
{
return TestSuiteBuilder{.name = std::move(name), .prerequisites = {}};
}
/**
* @brief Deliberately skips the current test, reporting it as skipped in test results.
* @param message Justification for skipping the test.
* @param location Source location used for skip reporting (automatically captured).
*/
export [[noreturn]] inline auto skip(std::string message, std::source_location location = std::source_location::current()) -> void
{
throw TestSkipped{std::move(message), location};
}
/**
* @brief Conditionally skips the current test if the provided condition evaluates to true.
* @param condition Boolean flag determining whether to skip.
* @param message Justification for skipping the test.
* @param location Source location used for skip reporting (automatically captured).
*/
export inline auto skipIf(bool condition, std::string message, std::source_location location = std::source_location::current()) -> void
{
if (condition)
skip(std::move(message), location);
}
/**
* @brief Explicitly fails the current test with a diagnostic message.
* @param message Diagnostic description explaining why the test failed.
* @param location Source location used for failure reporting (automatically captured).
*/
export [[noreturn]] inline auto fail(std::string message = "Explicit test failure", std::source_location location = std::source_location::current()) -> void
{
throw TestException{std::format(
"In {}\nAt line {}, column {}\n{}",
location.file_name(),
location.line(),
location.column(),
message)};
}
/**
* @brief Creates an RAII EventWatcher to observe emitted events.
* @tparam eventName Hashed string identifying the event.
* @tparam Args Payload parameter types.
* @param emitter Event emitter instance to subscribe to.
* @return EventWatcher instance managing event subscription.
*/
export template<String::Hasher eventName = Type::Hash{}, class... Args, class Emitter>
[[nodiscard]] inline auto watch(Emitter& emitter)
{
return EventWatcher<eventName, Args...>{emitter};
}
/**
* @brief Times the synchronous execution of a callable.
* @param name Diagnostic identifier of the benchmark.
* @param function Callable to measure.
* @return BenchmarkResult containing measured duration in nanoseconds.
*/
export inline auto benchmark(std::string name, Type::Callable auto&& function) -> BenchmarkResult
{
const auto startTime = std::chrono::steady_clock::now();
function();
const auto endTime = std::chrono::steady_clock::now();
return BenchmarkResult{
.name = std::move(name),
.duration = std::chrono::duration_cast<std::chrono::nanoseconds>(endTime - startTime)};
}
/**
* @brief Compares two benchmark results, logs their relative speedup, and returns the comparison.
* @param first First benchmark result (candidate).
* @param second Second benchmark result (baseline).
* @return BenchmarkComparison structure with speedup and relative performance analysis.
*/
export inline auto compareBenchmarks(const BenchmarkResult& first, const BenchmarkResult& second) -> BenchmarkComparison
{
auto comparison = BenchmarkComparison{first, second};
if (comparison.isFirstFaster())
Logger<"UnitTests">::print<"detail">("Benchmark comparison: '{}' ({}) is {:.2f}x faster than '{}' ({})",
first.name,
first.durationString(),
comparison.speedup(),
second.name,
second.durationString());
else
Logger<"UnitTests">::print<"detail">("Benchmark comparison: '{}' ({}) is {:.2f}x slower than '{}' ({})",
first.name,
first.durationString(),
comparison.speedup(),
second.name,
second.durationString());
return comparison;
}
/**
* @brief Emits a warning log if a candidate benchmark ran slower than a baseline benchmark.
* @param candidate Benchmark result being evaluated.
* @param baseline Reference benchmark result.
*/
export inline auto warnIfSlower(const BenchmarkResult& candidate, const BenchmarkResult& baseline) -> void
{
if (candidate.duration > baseline.duration)
{
const auto ratio = static_cast<double>(candidate.duration.count()) / static_cast<double>(baseline.duration.count());
Logger<"UnitTests">::emit<"color">(Terminal::TextColor::TextColorEnum::Yellow,
std::format("Warning: '{}' ({}) was {:.2f}x slower than '{}' ({})",
candidate.name,
candidate.durationString(),
ratio,
baseline.name,
baseline.durationString()));
}
}
/**
* @brief Executes a fuzz testing loop passing a DeterministicRandomEngine to the test body.
* @param name Descriptive identifier of the fuzz test.
* @param iterations Number of iterations to execute.
* @param function Test callback receiving a DeterministicRandomEngine&.
* @param seed Initial pseudo-random number generator seed (defaults to DeterministicRandomEngine::defaultSeed).
* @param location Source location used for failure reporting (automatically captured).
*/
export inline auto fuzz(
std::string name,
std::size_t iterations,
Type::Callable<Math::DeterministicRandomEngine&> auto&& function,
std::uint64_t seed = Math::DeterministicRandomEngine::defaultSeed,
std::source_location location = std::source_location::current()) -> void
{
auto fuzzer = Math::DeterministicRandomEngine{seed};
for (auto iteration : std::views::iota(0uz, iterations))
{
try
{
function(fuzzer);
}
catch (const TestException& exception)
{
throw TestException{std::format("In {}\nAt line {}, column {}\nFuzz test '{}' failed at iteration {} with seed {:#x}:\n{}",
location.file_name(),
location.line(),
location.column(),
name,
iteration,
seed,
exception.what())};
}
catch (const std::exception& exception)
{
throw TestException{std::format("In {}\nAt line {}, column {}\nFuzz test '{}' threw exception at iteration {} with seed {:#x}: {}",
location.file_name(),
location.line(),
location.column(),
name,
iteration,
seed,
exception.what())};
}
}
}
/**
* @brief Runs all registered test suites respecting dependency order and configuration settings.
* @param settings Execution settings controlling verbose output, filtering, and abort conditions.
* @return Exit code: 0 on success, non-zero if any test suite failed.
*/
export inline auto executeTests(TestSettings settings) -> int
{
return testRunner.executeTests(std::move(settings));
}
/**
* @brief Parses command-line arguments into a TestSettings configuration object.
* @param arguments Span of command-line argument tokens.
* @return Parsed TestSettings configuration.
*/
export inline auto executeCommands(std::span<const std::string_view> arguments) -> TestSettings
{
auto settings = TestSettings{};
const auto parametersLexer = Language::Parameters::ParametersLexer{};
const auto parameters = parametersLexer.parseParameters(arguments);
for (const auto& [parameterName, parameterValue] : parameters)
{
if (parameterName == "help" or parameterName == "h")
{
Logger<"UnitTests">::print<"info">(
"Available parameters:\n"
" -h, --help Show this help message\n"
" -m, --mode=<mode> Execution mode [debug|test|prod]\n"
" -v, --verbose[=<bool>] Enable/disable verbose test output\n"
" -d, --detail[=<bool>] Enable/disable execution details\n"
" --fail-fast Stop on first failure\n"
" -c, --chrono[=<bool>] Display test execution times\n"
" -f, --filter=<str> Filter test suites by substring\n"
" -r, --report=<path> Export test results (e.g. junit:report.xml)\n\n"
"Usage: ./UnitTests --filter=Log --verbose --report=junit:report.xml");
settings.abort = true;
return settings;
}
else if (parameterName == "mode" or parameterName == "m")
{
if (parameterValue == "test")
settings.chrono = true;
else if (parameterValue == "prod")
{
settings.verbose = false;
settings.detail = false;
settings.failFast = true;
}
}
else if (parameterName == "verbose" or parameterName == "v")
settings.verbose = (std::ranges::empty(parameterValue) or parameterValue == "1" or parameterValue == "true");
else if (parameterName == "detail" or parameterName == "d")
settings.detail = (std::ranges::empty(parameterValue) or parameterValue == "1" or parameterValue == "true");
else if (parameterName == "fail-fast")
settings.failFast = (std::ranges::empty(parameterValue) or parameterValue == "1" or parameterValue == "true");
else if (parameterName == "chrono" or parameterName == "c")
settings.chrono = (std::ranges::empty(parameterValue) or parameterValue == "1" or parameterValue == "true");
else if (parameterName == "filter" or parameterName == "f")
settings.filter = parameterValue;
else if (parameterName == "report" or parameterName == "r")
settings.report = parameterValue;
else
Logger<"CppUtils">::print<"warning">("Unknown command: {}", parameterName);
}
return settings;
}
/**
* @brief Parses standard main() arguments (argc, argv) into a TestSettings configuration object.
* @param argc Argument count.
* @param argv Array of argument strings.
* @return Parsed TestSettings configuration.
*/
export inline auto executeCommands(int argc, const char* const argv[]) -> TestSettings
{
if (argc <= 1 or argv == nullptr)
return TestSettings{};
return executeCommands(std::vector<std::string_view>{argv + 1, argv + argc});
}
}