-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathut
More file actions
1457 lines (1288 loc) · 52.8 KB
/
Copy pathut
File metadata and controls
1457 lines (1288 loc) · 52.8 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
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// <!--
// The MIT License (MIT)
//
// Copyright (c) 2024 Kris Jusiak <kris@jusiak.net>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
#if 0
// -->
[Overview](#Overview) / [Examples](#Examples) / [API](#API) / [FAQ](#FAQ) / [Resources](#Resources)
## UT: C++20 Unit-Testing library
> "If you liked it then you `"should have put a"_test` on it", Beyonce rule
[](https://opensource.org/license/mit)
[](https://github.com/qlibs/ut/releases)
[](https://godbolt.org/z/3qT4vc9nY)
[](https://godbolt.org/z/MG5cjnsbM)
> https://en.wikipedia.org/wiki/Unit_testing
### Features
- Single header (https://raw.githubusercontent.com/qlibs/ut/main/ut) / C++20 module (https://raw.githubusercontent.com/qlibs/ut/main/ut.cppm)
- Compile-time first (executes tests at compile-time and/or run-time)
- Detects memory leaks and UBs at compile-time*
- Explicit by design (no implicit conversions, narrowing, epsilon-less floating point comparisions, ...)
- Minimal [API](#api)
- Reflection integration (optional via https://github.com/qlibs/reflect)
- Compiles cleanly with ([`-fno-exceptions -fno-rtti -Wall -Wextra -Werror -pedantic -pedantic-errors`](https://godbolt.org/z/ceK6qsx68))
- Fast compilation times (see [compilation times](#comp))
- Fast run-time execution (see [performance](#perf))
- Verifies itself upon include (can be disabled with `-DNTEST` - see [FAQ](https://github.com/qlibs/.github/blob/main/profile/NTEST.md))
> \*Based on the `constexpr` ability of given compiler/standard
### Requirements
- C++20 ([gcc-12+, clang-16+](https://en.cppreference.com/w/cpp/compiler_support))
### Overview
> Hello world (https://godbolt.org/z/MG5cjnsbM)
```cpp
#include <ut>
#include <iostream> // output at run-time
constexpr auto sum(auto... args) { return (args + ...); }
int main() {
using namespace ut;
"sum"_test = [] {
expect(sum(1) == 1_i);
expect(sum(1, 2) == 3_i);
expect(sum(1, 2, 3) == 6_i);
};
}
```
```sh
$CXX example.cpp -std=c++20 -o example && ./example
PASSED: tests: 1 (1 passed, 0 failed, 1 compile-time), asserts: 3 (3 passed, 0 failed)
```
> Execution model (https://godbolt.org/z/31Gc151Mf)
```cpp
static_assert(("sum"_test = [] { // compile-time only
expect(sum(1, 2, 3) == 6_i);
}));
int main() {
"sum"_test = [] { // compile time and run-time
expect(sum(1, 2, 3) == 5_i);
};
"sum"_test = [] constexpr { // compile-time and run-time
expect(sum(1, 2, 3) == 6_i);
};
"sum"_test = [] mutable { // run-time only
expect(sum(1, 2, 3) == 6_i);
};
"sum"_test = [] consteval { // compile-time only
expect(sum(1, 2, 3) == 6_i);
};
}
```
> Note: `UT_RUN_TIME, UT_COMPILE_TIME` can be used instead of `mutable, consteval`.
```sh
$CXX example.cpp -std=c++20 # -DUT_COMPILE_TIME_ONLY
ut:156:25: error: static_assert((test(), "[FAILED]"));
example.cpp:13:44: note:"sum"_test
example.cpp:14:5: note: in call to 'expect.operator()<ut::eq<int, int>>({6, 5})'
```
```sh
$CXX example.cpp -std=c++20 -o example -DUT_RUN_TIME_ONLY && ./example
example.cpp:14:FAILED:"sum": 6 == 5
FAILED: tests: 3 (2 passed, 1 failed, 0 compile-time), asserts: 2 (1 passed, 1 failed)
```
> Constant evaluation (https://godbolt.org/z/6E86YdbdT)
```cpp
constexpr auto test() {
if consteval { return 42; } else { return 87; }
}
int main() {
"compile-time"_test = [] consteval {
expect(42_i == test());
};
"run-time"_test = [] mutable {
expect(87_i == test());
};
}
```
```sh
$CXX example.cpp -std=c++20 -o example && ./example
PASSED: tests: 2 (2 passed, 0 failed, 1 compile-time), asserts: 1 (1 passed, 0 failed)
```
> Suites/Sub-tests (https://godbolt.org/z/1oT3Gre93)
```cpp
ut::suite test_suite = [] {
"vector [sub-tests]"_test = [] {
std::vector<int> v(5);
expect(v.size() == 5_ul);
expect(v.capacity() >= 5_ul);
"resizing bigger changes size and capacity"_test = [=] {
mut(v).resize(10);
expect(v.size() == 10_ul);
expect(v.capacity() >= 10_ul);
};
};
};
int main() { }
```
```sh
$CXX example.cpp -std=c++20 -o example && ./example
PASSED: tests: 2 (2 passed, 0 failed, 1 compile-time), asserts: 4 (4 passed, 0 failed)
```
> Assertions (https://godbolt.org/z/79M7o355a)
```cpp
int main() {
"expect"_test = [] {
"different ways"_test = [] {
expect(42_i == 42);
expect(eq(42, 42)) << "same as expect(42_i == 42)";
expect(_i(42) == 42) << "same as expect(42_i == 42)";
};
"floating point"_test = [] {
expect((4.2 == 4.2_d)(.01)) << "floating point comparison with .01 epsilon precision";
};
"fatal"_test = [] mutable { // at run-time
std::vector<int> v{1};
expect[v.size() > 1_ul] << "fatal, aborts further execution";
expect(v[1] == 42_i); // not executed
};
"compile-time expression"_test = [] {
expect(constant<42 == 42_i>) << "requires compile-time expression";
};
};
}
```
```sh
$CXX example.cpp -std=c++20 -o example && ./example
example.cpp:21:FAILED:"fatal": 1 > 1
FAILED: tests: 3 (2 passed, 1 failed, 3 compile-time), asserts: 5 (4 passed, 1 failed)
```
> Errors/Checks (https://godbolt.org/z/Tvnce9j4d)
```cpp
int main() {
"leak"_test = [] {
new int; // compile-time error
};
"ub"_test = [] {
int* i{};
*i = 42; // compile-time error
};
"errors"_test = [] {
expect(42_i == short(42)); // [ERROR] Comparision of different types is not allowed
expect(42 == 42); // [ERROR] Expression required: expect(42_i == 42)
expect(4.2 == 4.2_d); // [ERROR] Epsilon is required: expect((4.2 == 4.2_d)(.01))
};
}
```
### Examples
> Reflection integration (https://godbolt.org/z/v8GG4hfbW)
```cpp
int main() {
struct foo { int a; int b; };
struct bar { int a; int b; };
"reflection"_test = [] {
auto f = foo{.a=1, .b=2};
expect(eq(foo{1, 2}, f));
expect(members(foo{1, 2}) == members(f));
expect(names(foo{}) == names(bar{}));
};
};
```
```sh
$CXX example.cpp -std=c++20 -o example && ./example
PASSED: tests: 1 (1 passed, 0 failed, 1 compile-time), asserts: 3 (3 passed, 0 failed)
```
> Custom configuration (https://godbolt.org/z/6MrEEvqja)
```cpp
struct outputter {
template<ut::events::mode Mode>
constexpr auto on(const ut::events::test_begin<Mode>&) { }
template<ut::events::mode Mode>
constexpr auto on(const ut::events::test_end<Mode>&) { }
template<class TExpr>
constexpr auto on(const ut::events::assert_pass<TExpr>&) { }
template<class TExpr>
constexpr auto on(const ut::events::assert_fail<TExpr>&) { }
constexpr auto on(const ut::events::fatal&) { }
constexpr auto on(const ut::events::summary&) { }
template<class TMsg>
constexpr auto on(const ut::events::log<TMsg>&) { }
};
struct custom_config {
::outputter outputter{};
ut::reporter<decltype(outputter)> reporter{outputter};
ut::runner<decltype(reporter)> runner{reporter};
const char* current_test_name{}; // optional
};
template<>
auto ut::cfg<ut::override> = custom_config{};
int main() {
"config"_test = [] mutable {
expect(42 == 43_i); // no output
};
};
```
```sh
$CXX example.cpp -std=c++20 -o example && ./example
echo $? # 139 # no output
```
<a name="comp"></a>
### Compilation times
> Include - no iostream (https://raw.githubusercontent.com/qlibs/ut/main/ut)
```cpp
time $CXX -x c++ -std=c++20 ut -c -DNTEST # 0.028s
time $CXX -x c++ -std=c++20 ut -c # 0.049s
```
> Benchmark - 100 tests, 1000 asserts (https://godbolt.org/z/zs5Ee3E7o)
```cpp
[ut]: time $CXX benchmark.cpp -std=c++20 # 0m0.813s
[ut]: time $CXX benchmark.cpp -std=c++20 -DNTEST # 0m0.758s
-------------------------------------------------------------------------
[ut] https://github.com/qlibs/ut/releases/tag/v2.1.6
```
<a name="perf"></a>
### Performance
> Benchmark - 100 tests, 1000 asserts (https://godbolt.org/z/xKx45s4xq)
```cpp
time ./benchmark # 0m0.002s (-O3)
time ./benchmark # 0m0.013s (-g)
```
> X86-64 assembly -O3 (https://godbolt.org/z/rqbsafaE6)
```cpp
int main() {
"sum"_test = [] {
expect(42_i == 42);
};
}
```
```cpp
main:
mov rax, qword ptr [rip + cfg<ut::override>+136]
inc dword ptr [rax + 24]
mov ecx, dword ptr [rax + 8]
mov edx, dword ptr [rax + 92]
lea esi, [rdx + 1]
mov dword ptr [rax + 92], esi
mov dword ptr [rax + 4*rdx + 28], ecx
mov rax, qword ptr [rax]
lea rcx, [rip + .L.str]
mov qword ptr [rax + 8], rcx
mov dword ptr [rax + 16], 6
lea rcx, [rip + template parameter object for fixed_string
mov qword ptr [rax + 24], rcx
inc dword ptr [rip + ut::cfg<ut::override>+52]
mov rax, qword ptr [rip + ut::cfg<ut::override>+136]
mov ecx, dword ptr [rax + 8]
mov edx, dword ptr [rax + 92]
dec edx
mov dword ptr [rax + 92], edx
xor esi, esi
cmp ecx, dword ptr [rax + 4*rdx + 28]
sete sil
inc dword ptr [rax + 4*rsi + 16]
xor eax, eax
ret
```
### API
```cpp
/**
* Assert definition
* @code
* expect(42 == 42_i);
* expect(42 == 42_i) << "log";
* expect[42 == 42_i]; // fatal assertion, aborts further execution
* @endcode
*/
inline constexpr struct {
constexpr auto operator()(auto expr);
constexpr auto operator[](auto expr);
} expect{};
```
```cpp
/**
* Test suite definition
* @code
* suite test_suite = [] { ... };
* @encode
*/
struct suite;
```
```cpp
/**
* Test definition
* @code
* "foo"_test = [] { ... }; // compile-time and run-time
* "foo"_test = [] mutable { ... }; // run-time only
* "foo"_test = [] constval { ... }; // compile-time only
* @endcode
*/
template<fixed_string Str>
[[nodiscard]] constexpr auto operator""_test();
```
```cpp
/**
* Compile time expression
* @code
* expect(constant<42_i == 42>); // forces compile-time evaluation and run-time check
* auto i = 0;
* expect(constant<i == 42_i>); // compile-time error
* @encode
*/
template<auto Expr> inline constexpr auto constant;
```
```cpp
/**
* Allows mutating object (by default lambdas are immutable)
* @code
* "foo"_test = [] {
* int i = 0;
* "sub"_test = [i] {
* mut(i) = 42;
* };
* expect(i == 42_i);
* };
* @endcode
*/
template<class T> [[nodiscard]] constexpr auto& mut(const T&);
```
```cpp
template<class TLhs, class TRhs> struct eq; // equal
template<class TLhs, class TRhs> struct neq; // not equal
template<class TLhs, class TRhs> struct gt; // greater
template<class TLhs, class TRhs> struct ge; // greater equal
template<class TLhs, class TRhs> struct lt; // less
template<class TLhs, class TRhs> struct le; // less equal
template<class TLhs, class TRhs> struct nt; // not
```
```cpp
constexpr auto operator==(const auto& lhs, const auto& rhs) -> decltype(eq{lhs, rhs});
constexpr auto operator!=(const auto& lhs, const auto& rhs) -> decltype(neq{lhs, rhs});
constexpr auto operator> (const auto& lhs, const auto& rhs) -> decltype(gt{lhs, rhs});
constexpr auto operator>=(const auto& lhs, const auto& rhs) -> decltype(ge{lhs, rhs});
constexpr auto operator< (const auto& lhs, const auto& rhs) -> decltype(lt{lhs, rhs});
constexpr auto operator<=(const auto& lhs, const auto& rhs) -> decltype(le{lhs, rhs});
constexpr auto operator! (const auto& t) -> decltype(nt{t});
```
```cpp
struct _b; // bool (true_b = _b{true}, false_b = _b{false})
struct _c; // char
struct _sc; // signed char
struct _s; // short
struct _i; // int
struct _l; // long
struct _ll; // long long
struct _u; // unsigned
struct _uc; // unsigned char
struct _us; // unsigned short
struct _ul; // unsigned long
struct _ull; // unsigned long long
struct _f; // float
struct _d; // double
struct _ld; // long double
struct _i8; // int8_t
struct _i16; // int16_t
struct _i32; // int32_t
struct _i64; // int64_t
struct _u8; // uint8_t
struct _u16; // uint16_t
struct _u32; // uint32_t
struct _u64; // uint64_t
struct _string; // const char*
```
```cpp
constexpr auto operator""_i(auto value) -> decltype(_i(value));
constexpr auto operator""_s(auto value) -> decltype(_s(value));
constexpr auto operator""_c(auto value) -> decltype(_c(value));
constexpr auto operator""_sc(auto value) -> decltype(_sc(value));
constexpr auto operator""_l(auto value) -> decltype(_l(value));
constexpr auto operator""_ll(auto value) -> decltype(_ll(value));
constexpr auto operator""_u(auto value) -> decltype(_u(value));
constexpr auto operator""_uc(auto value) -> decltype(_uc(value));
constexpr auto operator""_us(auto value) -> decltype(_us(value));
constexpr auto operator""_ul(auto value) -> decltype(_ul(value));
constexpr auto operator""_ull(auto value) -> decltype(_ull(value));
constexpr auto operator""_f(auto value) -> decltype(_f(value));
constexpr auto operator""_d(auto value) -> decltype(_d(value));
constexpr auto operator""_ld(auto value) -> decltype(_ld(value));
constexpr auto operator""_i8(auto value) -> decltype(_i8(value));
constexpr auto operator""_i16(auto value) -> decltype(_i16(value));
constexpr auto operator""_i32(auto value) -> decltype(_i32(value));
constexpr auto operator""_i64(auto value) -> decltype(_i64(value));
constexpr auto operator""_u8(auto value) -> decltype(_u8(value));
constexpr auto operator""_u16(auto value) -> decltype(_u16(value));
constexpr auto operator""_u32(auto value) -> decltype(_u32(value));
constexpr auto operator""_u64(auto value) -> decltype(_u64(value));
```
```cpp
template<fixed_string Str>
[[nodiscard]] constexpr auto operator""_s() -> decltype(_string(Str));
```
> Configuration
```cpp
namespace events {
enum class mode {
run_time,
compile_time
};
template<class T>
struct run {
T test{};
const char* file_name{};
int line{};
const char* name{};
const char* filter{};
};
template<mode Mode>
struct test_end {
const char* file_name{};
int line{};
const char* name{};
enum { FAILED, PASSED, COMPILE_TIME } result{};
};
template<class TExpr>
struct assert_pass {
const char* file_name{};
int line{};
TExpr expr{};
};
template<class TExpr>
struct assert_fail {
const char* file_name{};
int line{};
TExpr expr{};
};
struct fatal { };
template<class TMsg>
struct log {
const TMsg& msg;
bool result{};
};
struct summary {
enum { FAILED, PASSED, COMPILE_TIME };
unsigned asserts[2]{}; /* FAILED, PASSED */
unsigned tests[3]{}; /* FAILED, PASSED, COMPILE_TIME */
};
} // namespace events
```
```cpp
struct outputter {
template<events::mode Mode> constexpr auto on(const events::test_begin<Mode>&);
constexpr auto on(const events::test_begin<events::mode::run_time>& event);
template<events::mode Mode> constexpr auto on(const events::test_end<Mode>&);
template<class TExpr> constexpr auto on(const events::assert_pass<TExpr>&);
template<class TExpr> constexpr auto on(const events::assert_fail<TExpr>&);
constexpr auto on(const events::fatal&);
template<class TMsg> constexpr auto on(const events::log<TMsg>&);
constexpr auto on(const events::summary& event);
};
```
```cpp
struct reporter {
constexpr auto on(const events::test_begin<events::mode::run_time>&);
constexpr auto on(const events::test_end<events::mode::run_time>&);
constexpr auto on(const events::test_begin<events::mode::compile_time>&);
constexpr auto on(const events::test_end<events::mode::compile_time>&);
template<class TExpr> constexpr auto on(const events::assert_pass<TExpr>&);
template<class TExpr> constexpr auto on(const events::assert_fail<TExpr>&);
constexpr auto on(const events::fatal& event);
};
```
```cpp
struct runner {
template<class Test> constexpr auto on(Test test) -> bool;
};
```
```cpp
/**
* Customization point to override the default configuration
* @code
* template<class... Ts> auto ut::cfg<ut::override, Ts...> = my_config{};
* @endcode
*/
struct override { }; /// to override configuration by users
struct default_cfg; /// default configuration
template <class...> inline auto cfg = default_cfg{};
```
```cpp
#define UT_RUN_TIME // [mutable] Marks test at run-time only
#define UT_COMPILE_TIME // [consteval] Marks test as compile-time only
```
```cpp
#define UT_RUN_TIME_ONLY // If defined tests will be executed
// at run-time + static_assert tests
#define UT_COMPILE_TIME_ONLY // If defined only compile-time tests
// will be executed
```
```cpp
env:UT_FILTER // If UT_FILTER environment variable is set
// only tests which match regex will be executed
```
### FAQ
> - How to disable running tests at compile-time?
>
> When `-DNTEST` is defined static_asserts tests wont be executed upon include.
> Note: Use with caution as disabling tests means that there are no gurantees upon include that given compiler/env combination works as expected.
>
> - Similar projects?
> [ut](https://github.com/boost-ext/ut), [catch2](https://github.com/catchorg/Catch2), [googletest](https://github.com/google/googletest), [gunit](https://github.com/cpp-testing/GUnit), [boost.test](https://www.boost.org/doc/libs/latest/libs/test/doc/html/index.html)
### Resources
> - "unit"_test: Implementing a Macro-free Unit Testing Framework from Scratch in C++20 - https://www.youtube.com/watch?v=-qAXShy1xiE
> - Future of Testing With C++20 - https://www.youtube.com/watch?v=KlU0cb_tbuw
> - Towards Painless Testing - https://www.youtube.com/watch?v=NVrZjT5lW5o
### License
> - [MIT](LICENSE)
<!--
#endif
#pragma once
#define UT_RUN_TIME mutable
#define UT_COMPILE_TIME consteval
extern "C" char *getenv(const char *) throw();
namespace ut::inline v2_1_6 {
namespace type_traits {
template<class, class> inline constexpr auto is_same_v = false;
template<class T> inline constexpr auto is_same_v<T, T> = true;
template<class T> inline constexpr auto is_floating_point_v = false;
template<> inline constexpr auto is_floating_point_v<float> = true;
template<> inline constexpr auto is_floating_point_v<double> = true;
template<> inline constexpr auto is_floating_point_v<long double> = true;
template<class> inline constexpr auto is_mutable_lambda_v = false;
template<class R, class B, class... Ts> inline constexpr auto is_mutable_lambda_v<R (B::*)(Ts...)> = true;
template<class Fn> inline constexpr auto has_capture_lambda_v = sizeof(Fn) > 1ul;
} // type_traits
namespace utility {
template<class T> T&& declval();
template<class T, class...> struct type_identity { using type = T; };
template<unsigned Size> struct fixed_string {
constexpr fixed_string(const char(&str)[Size]) { for (auto i = 0u; i < Size; ++i) { storage[i] = str[i]; } }
[[nodiscard]] constexpr auto operator[](const auto i) const { return storage[i]; }
[[nodiscard]] constexpr auto data() const { return storage; }
[[nodiscard]] static constexpr auto size() { return Size; }
constexpr friend auto operator<<(auto& os, const fixed_string& fs) -> decltype(auto) { return os << fs.storage; }
char storage[Size]{};
};
[[nodiscard]] constexpr auto match(const auto pattern, const auto str) -> bool {
if (not bool(pattern)) { return true; }
if (not *pattern) { return not *str; }
if (not *str) {
return pattern[0] == '*' ? match(&pattern[1], str) : false;
}
if (pattern[0] != '?' and pattern[0] != '*' and pattern[0] != str[0]) {
return false;
}
if (pattern[0] == '*') {
auto tmp = str;
auto i = 0u;
while (tmp++) {
if (match(&pattern[1], &str[i++])) {
return true;
}
}
return false;
}
return match(&pattern[1], &str[1]);
}
} // utility
namespace events {
enum class mode { run_time, compile_time };
template<class T>
struct run { T test{}; const char* file_name{}; int line{}; const char* name{}; const char* filter{}; };
template<mode Mode> struct test_begin { const char* file_name{}; int line{}; const char* name{}; };
template<mode Mode> struct test_end { const char* file_name{}; int line{}; const char* name{}; enum { FAILED, PASSED, COMPILE_TIME } result{}; };
template<class TExpr> struct assert_pass { const char* file_name{}; int line{}; TExpr expr{}; };
template<class TExpr> struct assert_fail { const char* file_name{}; int line{}; TExpr expr{}; };
struct fatal { };
template<class TMsg> struct log { const TMsg& msg; bool result{}; };
struct summary { enum { FAILED, PASSED, COMPILE_TIME }; unsigned asserts[2]{}; /* FAILED, PASSED */ unsigned tests[3]{}; /* FAILED, PASSED, COMPILE_TIME */ };
} // namespace events
template<class TOStream>
class outputter {
public:
template<events::mode Mode> constexpr auto on(const events::test_begin<Mode>&) { }
constexpr auto on(const events::test_begin<events::mode::run_time>& event) { current_test = event; }
template<events::mode Mode> constexpr auto on(const events::test_end<Mode>&) { }
template<class TExpr> constexpr auto on(const events::assert_pass<TExpr>&) { }
template<class TExpr> constexpr auto on(const events::assert_fail<TExpr>& event) {
if (!__builtin_is_constant_evaluated()) {
if (initial_new_line == '\n') { os << initial_new_line; } else { initial_new_line = '\n'; }
os << event.file_name << ':' << event.line << ':' << "FAILED:" << '\"' << current_test.name << "\": " << event.expr;
}
}
constexpr auto on(const events::fatal&) { }
template<class TMsg> constexpr auto on(const events::log<TMsg>& event) {
if (!__builtin_is_constant_evaluated() && !event.result) {
os << ' ' << event.msg;
}
}
constexpr auto on(const events::summary& event) {
if (!__builtin_is_constant_evaluated()) {
if (event.asserts[events::summary::FAILED] || event.tests[events::summary::FAILED]) {
os << "\nFAILED: ";
} else {
os << "PASSED: ";
}
os << "tests: " << (event.tests[events::summary::PASSED] + event.tests[events::summary::FAILED]) << " ("
<< event.tests[events::summary::PASSED] << " passed, "
<< event.tests[events::summary::FAILED] << " failed, "
<< event.tests[events::summary::COMPILE_TIME] << " compile-time), "
<< "asserts: " << (event.asserts[events::summary::PASSED] + event.asserts[events::summary::FAILED]) << " ("
<< event.asserts[events::summary::PASSED] << " passed, "
<< event.asserts[events::summary::FAILED] << " failed)\n";
}
}
TOStream& os;
events::test_begin<events::mode::run_time> current_test{};
char initial_new_line{};
};
template<class TOutputter, auto MaxDepth = 16u>
struct reporter {
constexpr auto on(const events::test_begin<events::mode::run_time>& event) {
asserts_failed[current++] = summary.asserts[events::summary::FAILED];
outputter.on(event);
}
constexpr auto on(const events::test_end<events::mode::run_time>& event) {
const auto result = summary.asserts[events::summary::FAILED] == asserts_failed[--current];
++summary.tests[result];
events::test_end<events::mode::run_time> te{event};
te.result = static_cast<decltype(te.result)>(result);
outputter.on(te);
}
constexpr auto on(const events::test_begin<events::mode::compile_time>&) {
++summary.tests[events::summary::COMPILE_TIME];
}
constexpr auto on(const events::test_end<events::mode::compile_time>&) { }
template<class TExpr> constexpr auto on(const events::assert_pass<TExpr>& event) {
++summary.asserts[events::summary::PASSED];
outputter.on(event);
}
template<class TExpr> constexpr auto on(const events::assert_fail<TExpr>& event) {
++summary.asserts[events::summary::FAILED];
outputter.on(event);
}
constexpr auto on(const events::fatal& event) {
++summary.tests[events::summary::FAILED];
outputter.on(event);
outputter.on(summary);
__builtin_abort();
}
#ifndef UT_COMPILE_TIME_ONLY
~reporter() { // non constexpr
outputter.on(summary);
if (summary.asserts[events::summary::FAILED]) {
__builtin_abort();
}
}
#endif
TOutputter& outputter;
events::summary summary{};
unsigned asserts_failed[MaxDepth]{};
unsigned current{};
};
template<class TReporter>
struct runner {
template<class Test> constexpr auto on(events::run<Test> run) -> bool {
if (__builtin_is_constant_evaluated()) {
if constexpr (!type_traits::is_mutable_lambda_v<decltype(&Test::operator())>) {
run.test();
return true;
} else {
return false;
}
} else {
#ifndef UT_RUN_TIME_ONLY
if constexpr (!type_traits::is_mutable_lambda_v<decltype(&Test::operator())> && !type_traits::has_capture_lambda_v<Test>) {
reporter.on(events::test_begin<events::mode::compile_time>{run.file_name, run.line, run.name});
static_assert((run.test(), R"([FAILED] Compile-time expectation failed. The error below should indicate the issue. If it's not an assertion it might be that the std and/or compiler don't support running the test at compile-time. In such case mark the test as `mutable` or `UT_RUN_TIME` to force run-time only execution. For example: `"run-time"_test = [] mutable { ... }`.)"));
reporter.on(events::test_end<events::mode::compile_time>{run.file_name, run.line, run.name});
}
#endif
#ifndef UT_COMPILE_TIME_ONLY
if (utility::match(run.filter, run.name)) {
reporter.on(events::test_begin<events::mode::run_time>{run.file_name, run.line, run.name});
run.test();
reporter.on(events::test_end<events::mode::run_time>{run.file_name, run.line, run.name});
}
#endif
}
return true;
}
TReporter& reporter;
};
} // namespace ut
namespace std { // iosfwd
template<class> struct char_traits;
template<class, class> class basic_ostream;
extern basic_ostream<char, char_traits<char>> clog; // only used if defined
} // namespace std
namespace ut::inline v2_1_6 {
namespace detail {
struct stream {
friend constexpr decltype(auto) operator<<([[maybe_unused]] auto& os, [[maybe_unused]] const auto& t) {
#ifdef UT_COMPILE_TIME_ONLY
return os;
#else
static_assert(requires { std::clog << t; }, "[ERROR] No output supported: Consider #include <iostream> | ut::cfg<ut::override> = custom_cfg{} | #define UT_COMPILE_TIME_ONLY");
return (std::clog << t);
#endif
}
};
} // namespace detail
template<class...>
struct default_cfg {
detail::stream stream{};
ut::outputter<decltype(stream)> outputter{stream};
ut::reporter<decltype(outputter)> reporter{outputter};
ut::runner<decltype(reporter)> runner{reporter};
const char* current_test_name{};
};
struct override { };
/**
* Customization point to override the default configuration
*
* @code
* template<class... Ts> auto ut::cfg<ut::override, Ts...> = my_config{};
* @endcode
*/
template <class... Ts> inline default_cfg<Ts...> cfg{};
namespace detail {
template<class... Ts>
[[nodiscard]] constexpr auto& cfg(Ts&&...) {
return ut::cfg<typename utility::type_identity<override, Ts...>::type>;
}
void failed(); /// fail in constexpr context
} // namespace detail
inline constexpr struct {
constexpr auto operator()(auto expr, const char* file_name = __builtin_FILE(), int line = __builtin_LINE()) const {
if constexpr (constexpr auto supported = type_traits::is_same_v<bool, decltype(expr)> || !requires { static_cast<bool>(expr); }; supported) {
static_assert(!supported, "[ERROR] Expression required - `expect(lhs == rhs)`. For example: `expect(3_i == sum(1, 2))`.");
} else {
bool result{};
if (result = static_cast<bool>(expr); __builtin_is_constant_evaluated()) {
if (!result) { detail::failed(); }
} else if (result) {
detail::cfg(expr).reporter.on(events::assert_pass{file_name, line, expr});
} else {
detail::cfg(expr).reporter.on(events::assert_fail{file_name, line, expr});
}
return log{result};
}
}
struct fatal_expr {
constexpr fatal_expr(auto expr, const char* file_name = __builtin_FILE(), int line = __builtin_LINE()) {
if constexpr (constexpr auto supported = type_traits::is_same_v<bool, decltype(expr)> || !requires { static_cast<bool>(expr); }; supported) {
static_assert(!supported, "[ERROR] Expression required - `expect[lhs == rhs]`. For example: `expect[3_i == sum(1, 2)]`.");
} else {
if (result = static_cast<bool>(expr); __builtin_is_constant_evaluated()) {
if (!result) { detail::failed(); }
} else if (result) {
detail::cfg(expr).reporter.on(events::assert_pass{file_name, line, expr});
} else {
detail::cfg(expr).reporter.on(events::assert_fail{file_name, line, expr});
}
}
}
bool result{};
};
constexpr auto operator[](fatal_expr e) const { return fatal_log{e.result}; } /// multiple and/or default parameters requires C++23
private:
struct log {
template<class TMsg> constexpr const auto& operator<<(const TMsg& msg) const {
detail::cfg(msg).outputter.on(events::log<TMsg>{msg, result});
return *this;
}
bool result{};
};
template<auto tag = []{}>
struct fatal_log {
template<class TMsg> constexpr const auto& operator<<(const TMsg& msg) const {
detail::cfg(msg).outputter.on(events::log<TMsg>{msg, result});
return *this;
}
constexpr ~fatal_log() {
detail::cfg(tag).reporter.on(events::fatal{});
}
bool result{};
};
} expect{};
struct suite {
template<class Test> suite(Test test) { test(); } /// not constexpr
};
namespace detail {
template<utility::fixed_string Name>
struct test {
struct run {
template<class T> constexpr run(T test, const char* file_name = __builtin_FILE(), int line = __builtin_LINE())
: result{[&] {
if (__builtin_is_constant_evaluated()) {
return cfg(test).runner.on(events::run{test, file_name, line, Name.data()});
} else {
if constexpr (requires { cfg(test).current_test_name; }) {
cfg(test).current_test_name = Name.data();
}
return cfg(test).runner.on(events::run{test, file_name, line, Name.data(), getenv("UT_FILTER")});
}
}()}
{ }
bool result{};
};
constexpr auto operator=(run test) const { return test.result; }
};
} // namespace detail
template<utility::fixed_string Str>
[[nodiscard]] constexpr auto operator""_test() { return detail::test<Str>{}; }
template<auto Expr> inline constexpr auto constant = Expr;
template<class T> [[nodiscard]] constexpr auto& mut(const T& t) { return const_cast<T&>(t); }
template<class TLhs, class TRhs> struct eq {
constexpr eq(const TLhs& lhs, const TRhs& rhs) : lhs{lhs}, rhs{rhs} { }
static_assert(type_traits::is_same_v<TLhs, TRhs>, "[ERROR] Comparision of different types is not allowed.");
[[nodiscard]] constexpr explicit operator bool() const { return false; }
const TLhs& lhs; const TRhs& rhs;
};
template<class T> struct eq<T, T> {
constexpr eq(const T& lhs, const T& rhs) : lhs{lhs}, rhs{rhs}, result{lhs == rhs} { }
constexpr friend auto operator<<(auto& os, const eq& expr) -> decltype(auto) { return (os << expr.lhs << " == " << expr.rhs); }
[[nodiscard]] constexpr explicit operator bool() const { return result; }
T lhs; T rhs; bool result{};
};
template<class T> requires type_traits::is_floating_point_v<T> struct eq<T, T> {
constexpr eq(const T& lhs, const T& rhs) : lhs{lhs}, rhs{rhs} { }
constexpr friend auto operator<<(auto& os, const eq& expr) -> decltype(auto) { return (os << expr.lhs << " == " << expr.rhs); }
[[nodiscard]] constexpr explicit operator bool() const {
static_assert(!type_traits::is_floating_point_v<T>, "[ERROR] Epsilon is required - `expect((lhs == rhs)(epsilon))`. For example: `expect((4.2_f == sum(4.f, .2f))(.01f))`.");
return {};
}
struct epsilon {
constexpr epsilon(const T& lhs, const T& rhs, const T e) : lhs{lhs}, rhs{rhs}, e{e}, result{(lhs < rhs ? rhs - lhs : lhs - rhs) < e} { }
[[nodiscard]] constexpr explicit operator bool() const { return result; }
constexpr friend auto operator<<(auto& os, const epsilon& expr) -> decltype(auto) { return (os << "(" << expr.lhs << " == " << expr.rhs << ")(" << expr.e <<")"); }
T lhs; T rhs; T e; bool result{};
};
[[nodiscard]] constexpr auto operator()(T e) const { return epsilon{lhs, rhs, e}; }
T lhs; T rhs;
};
template<class TLhs, class TRhs>
requires requires(TLhs lhs, TRhs rhs) { lhs[0]; rhs[0]; lhs.size(); rhs.size(); }
struct eq<TLhs, TRhs> {