Repository navigation
Expand file tree
/
Copy pathUnitTest.mpp
More file actions
976 lines (898 loc) · 39.2 KB
/
Copy pathUnitTest.mpp
File metadata and controls
976 lines (898 loc) · 39.2 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
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
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 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 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">;
TestSuite() = default;
private:
friend struct TestSuiteBuilder;
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);
}
inline auto addSkippedTest(std::string name, std::string message, std::chrono::seconds timeout = std::chrono::seconds{10}) -> void
{
addTest(std::move(name), [message = std::move(message)] {
UnitTest::skip(message);
}, timeout);
}
template<class... Values>
static constexpr auto makeValuesContainer(Values&&... values)
{
if constexpr (sizeof...(Values) == 1 and (std::ranges::input_range<std::decay_t<Values>> and ...))
return (std::forward<Values>(values), ...);
else
return std::make_tuple(std::forward<Values>(values)...);
}
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 common configuration (timeout, skip) for test builders.
* @tparam Derived Derived builder type for method chaining.
* @tparam IsSkipped Indicates whether the test execution is bypassed.
*/
template<class Derived, bool IsSkipped>
struct TestBuilderBase
{
TestSuite& parentSuite; ///< Reference to the enclosing test suite registering the test.
std::string testName; ///< Identifier of the test case.
std::chrono::seconds testTimeout{10}; ///< Maximum execution timeout duration.
std::string skipMessage{}; ///< Explanatory reason if skipped.
TestBuilderBase(TestSuite& suite, std::string name, std::chrono::seconds timeout = std::chrono::seconds{10}, std::string skipReason = {}):
parentSuite{suite},
testName{std::move(name)},
testTimeout{timeout},
skipMessage{std::move(skipReason)}
{}
/**
* @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 Deliberately marks this test case to be skipped.
* @param message Justification for skipping.
* @return Rebound builder with skipping enabled.
*/
[[nodiscard]] inline auto skip(std::string message)
{
return skipIf<true>(std::move(message));
}
/**
* @brief Conditionally marks this test case to be skipped.
* @tparam Condition Compile-time condition flag.
* @param message Justification for skipping.
* @return Rebound builder configured with the specified condition.
*/
template<bool Condition>
[[nodiscard]] inline auto skipIf(std::string message)
{
return static_cast<Derived*>(this)->template rebind<Condition>(std::move(message));
}
/**
* @brief Adds a test callback into the parent suite, taking skip status into account.
* @param name Test identifier.
* @param function Invocable test body.
* @param timeout Execution timeout duration.
*/
template<class Function>
requires Type::Callable<Function> or Type::Callable<Function, std::stop_token>
inline auto addTest(std::string name, Function&& function, std::chrono::seconds timeout) -> void
{
if constexpr (IsSkipped)
parentSuite.addSkippedTest(std::move(name), skipMessage, timeout);
else
parentSuite.addTest(std::move(name), std::forward<Function>(function), timeout);
}
/**
* @brief Adds a compile-time test into the parent suite, taking skip status into account.
* @param name Test identifier.
*/
inline auto addCompileTimeTest(std::string name) -> void
{
if constexpr (IsSkipped)
parentSuite.addSkippedTest(std::move(name), skipMessage, std::chrono::seconds{0});
else
parentSuite.addTest(std::move(name), [] {});
}
};
/**
* @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<bool IsSkipped = false, class... Types>
struct TypedTestBuilder final: TestBuilderBase<TypedTestBuilder<IsSkipped, Types...>, IsSkipped>
{
using Base = TestBuilderBase<TypedTestBuilder<IsSkipped, Types...>, IsSkipped>;
using Base::Base;
template<bool Condition>
[[nodiscard]] inline auto rebind(std::string message) -> TypedTestBuilder<Condition, Types...>
{
return TypedTestBuilder<Condition, Types...>{this->parentSuite, std::move(this->testName), this->testTimeout, std::move(message)};
}
/**
* @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>() {
this->addTest(std::format("{} [type {}]", this->testName, index++), [function](std::stop_token token) {
if constexpr (requires { function.template operator()<Type>(); })
function.template operator()<Type>();
else if constexpr (requires { function(std::type_identity<Type>{}); })
function(std::type_identity<Type>{});
else if constexpr (requires { function.template operator()<Type>(token); })
function.template operator()<Type>(token);
else if constexpr (requires { function(std::type_identity<Type>{}, token); })
function(std::type_identity<Type>{}, token);
}, this->testTimeout);
};
(registerType.template operator()<Types>(), ...);
}
/**
* @brief Evaluates compile-time test predicates for each type via static assertions.
* @tparam Predicate Constexpr invocable parameterized by type.
*/
template<auto Predicate>
inline auto constexprTest() -> void
{
if constexpr (not IsSkipped)
{
auto evaluateType = []<class Type> {
if constexpr (requires { Predicate.template operator()<Type>(); })
{
if constexpr (not std::is_void_v<decltype(Predicate.template operator()<Type>())>)
static_assert(Predicate.template operator()<Type>(), "Compile-time type test assertion evaluated to false");
else
static_assert((Predicate.template operator()<Type>(), true), "Compile-time type test failed");
}
else
{
if constexpr (not std::is_void_v<decltype(Predicate(std::type_identity<Type>{}))>)
static_assert(Predicate(std::type_identity<Type>{}), "Compile-time type test assertion evaluated to false");
else
static_assert((Predicate(std::type_identity<Type>{}), true), "Compile-time type test failed");
}
};
(evaluateType.template operator()<Types>(), ...);
}
auto index = 0uz;
([&]<class Type>() {
this->addCompileTimeTest(std::format("{} [type {}]", this->testName, index++));
}.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 IsSkipped Indicates whether the test execution is bypassed.
* @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<bool IsSkipped = false, class ValuesContainer = std::tuple<>>
struct ParameterizedTestBuilder final: TestBuilderBase<ParameterizedTestBuilder<IsSkipped, ValuesContainer>, IsSkipped>
{
using Base = TestBuilderBase<ParameterizedTestBuilder<IsSkipped, ValuesContainer>, IsSkipped>;
ValuesContainer values; ///< Discrete values tuple or range of values.
ParameterizedTestBuilder(TestSuite& suite, std::string name, ValuesContainer valuesContainer, std::chrono::seconds timeout = std::chrono::seconds{10}, std::string skipReason = {}):
Base{suite, std::move(name), timeout, std::move(skipReason)},
values{std::move(valuesContainer)}
{}
template<bool Condition>
[[nodiscard]] inline auto rebind(std::string message) -> ParameterizedTestBuilder<Condition, ValuesContainer>
{
return ParameterizedTestBuilder<Condition, ValuesContainer>{this->parentSuite, std::move(this->testName), std::move(values), this->testTimeout, std::move(message)};
}
/**
* @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;
TestSuite::forEachParameterValue(values, [&](const auto& value) {
this->addTest(TestSuite::formatParameterName(this->testName, value, index), [function, value](std::stop_token token) {
if constexpr (requires { function(value); })
function(value);
else if constexpr (requires { function(value, token); })
function(value, token);
}, this->testTimeout);
});
}
};
/**
* @brief Builder for registering compile-time tests parameterized over non-type template values.
* @tparam IsSkipped Indicates whether the test execution is bypassed.
* @tparam Values Non-type template values list.
*/
template<bool IsSkipped = false, auto... Values>
struct ConstexprValuesTestBuilder final: TestBuilderBase<ConstexprValuesTestBuilder<IsSkipped, Values...>, IsSkipped>
{
using Base = TestBuilderBase<ConstexprValuesTestBuilder<IsSkipped, Values...>, IsSkipped>;
using Base::Base;
template<bool Condition>
[[nodiscard]] inline auto rebind(std::string message) -> ConstexprValuesTestBuilder<Condition, Values...>
{
return ConstexprValuesTestBuilder<Condition, Values...>{this->parentSuite, std::move(this->testName), this->testTimeout, std::move(message)};
}
/**
* @brief Evaluates compile-time test predicates for each non-type value via static assertions.
* @tparam Predicate Constexpr invocable accepting non-type template parameter or function argument.
*/
template<auto Predicate>
inline auto constexprTest() -> void
{
if constexpr (not IsSkipped)
{
auto evaluateValue = []<auto Value> {
if constexpr (requires { Predicate.template operator()<Value>(); })
{
if constexpr (not std::is_void_v<decltype(Predicate.template operator()<Value>())>)
static_assert(Predicate.template operator()<Value>(), "Compile-time value test assertion evaluated to false");
else
static_assert((Predicate.template operator()<Value>(), true), "Compile-time value test failed");
}
else
{
if constexpr (not std::is_void_v<decltype(Predicate(Value))>)
static_assert(Predicate(Value), "Compile-time value test assertion evaluated to false");
else
static_assert((Predicate(Value), true), "Compile-time value test failed");
}
};
(evaluateValue.template operator()<Values>(), ...);
}
auto index = 0uz;
auto registerValue = [&]<auto Value>() {
this->addCompileTimeTest(TestSuite::formatParameterName(this->testName, Value, index));
};
(registerValue.template operator()<Values>(), ...);
}
};
/**
* @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.
* @tparam IsSkipped Indicates whether the test execution is bypassed.
*
* @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)
*/
template<bool IsSkipped = false>
struct TestBuilder final: TestBuilderBase<TestBuilder<IsSkipped>, IsSkipped>
{
using Base = TestBuilderBase<TestBuilder<IsSkipped>, IsSkipped>;
using Base::Base;
template<bool Condition>
[[nodiscard]] inline auto rebind(std::string message) -> TestBuilder<Condition>
{
return TestBuilder<Condition>{this->parentSuite, std::move(this->testName), this->testTimeout, std::move(message)};
}
/**
* @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<IsSkipped, Types...>
{
return TypedTestBuilder<IsSkipped, Types...>{this->parentSuite, std::move(this->testName), this->testTimeout, this->skipMessage};
}
/**
* @brief Converts this test into a compile-time value-parameterized test across non-type template values.
* @tparam Values Non-type values to instantiate the compile-time test with.
* @return ConstexprValuesTestBuilder instance.
*/
template<auto... Values>
[[nodiscard]] inline auto forValues() -> ConstexprValuesTestBuilder<IsSkipped, Values...>
{
return ConstexprValuesTestBuilder<IsSkipped, Values...>{this->parentSuite, std::move(this->testName), this->testTimeout, this->skipMessage};
}
/**
* @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)
{
auto container = TestSuite::makeValuesContainer(std::forward<Values>(values)...);
return ParameterizedTestBuilder<IsSkipped, decltype(container)>{
this->parentSuite, std::move(this->testName), std::move(container), this->testTimeout, this->skipMessage};
}
/**
* @brief Evaluates a test predicate at compile time via static_assert and registers it as a test.
* @tparam Predicate Constexpr invocable returning a boolean or performing static assertions.
*/
template<auto Predicate>
inline auto constexprTest() -> void
{
if constexpr (not IsSkipped)
{
if constexpr (not std::is_void_v<decltype(Predicate())>)
static_assert(Predicate(), "Compile-time test assertion evaluated to false");
else
static_assert((Predicate(), true), "Compile-time test failed");
}
this->addCompileTimeTest(std::move(this->testName));
}
/**
* @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
{
this->addTest(std::move(this->testName), std::forward<decltype(function)>(function), this->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.
* @tparam IsSkipped Indicates whether the test execution is bypassed.
*
* @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)
*/
template<bool IsSkipped = false>
struct FuzzTestBuilder final: TestBuilderBase<FuzzTestBuilder<IsSkipped>, IsSkipped>
{
using Base = TestBuilderBase<FuzzTestBuilder<IsSkipped>, IsSkipped>;
std::size_t testIterations; ///< Number of randomized iterations to execute.
std::uint64_t testSeed{Math::DeterministicRandomEngine::defaultSeed}; ///< Deterministic pseudo-random number generator initial seed.
FuzzTestBuilder(TestSuite& suite, std::string name, std::size_t iterations, std::uint64_t seed = Math::DeterministicRandomEngine::defaultSeed, std::chrono::seconds timeout = std::chrono::seconds{10}, std::string skipReason = {}):
Base{suite, std::move(name), timeout, std::move(skipReason)},
testIterations{iterations},
testSeed{seed}
{}
template<bool Condition>
[[nodiscard]] inline auto rebind(std::string message) -> FuzzTestBuilder<Condition>
{
return FuzzTestBuilder<Condition>{this->parentSuite, std::move(this->testName), testIterations, testSeed, this->testTimeout, std::move(message)};
}
/**
* @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
{
this->addTest(std::move(this->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);
}
}, this->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<false>
{
return TestBuilder<false>{*this, 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<false>
{
return FuzzTestBuilder<false>{*this, std::move(name), iterations};
}
/**
* @brief Returns the collection of registered test cases in this suite.
* @return Read-only reference to the list of test cases.
*/
[[nodiscard]] inline auto testCases() const noexcept -> const std::vector<TestCase>&
{
return tests;
}
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 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);
auto parseBooleanOption = [](std::string_view value) -> bool {
return std::ranges::empty(value) or value == "1" or value == "true";
};
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 = parseBooleanOption(parameterValue);
else if (parameterName == "detail" or parameterName == "d")
settings.detail = parseBooleanOption(parameterValue);
else if (parameterName == "fail-fast")
settings.failFast = parseBooleanOption(parameterValue);
else if (parameterName == "chrono" or parameterName == "c")
settings.chrono = parseBooleanOption(parameterValue);
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});
}
}