Compare commits

...

1008 Commits

Author SHA1 Message Date
fd89c33aae Refactor and clean up HK and Local Pool Modules 2024-11-15 16:28:41 +01:00
21d5800bfa Merge pull request 'fix formatting' (#42) from auto-formatting into main
Reviewed-on: KSat/fsfw#42
2024-11-15 10:55:26 +01:00
036ab2e40d
fix formatting 2024-11-15 10:52:31 +01:00
c740721e34 Merge pull request 'Space Packet Parser CRC Check' (#41) from meier/space-packet-crc-check into main
Reviewed-on: KSat/fsfw#41
2024-11-15 10:21:28 +01:00
Jakob Meier
a95ca7d4eb run auto formatter 2024-11-15 10:13:15 +01:00
Jakob Meier
3b68a3ed1d added optional crc check to space packet parsing 2024-11-15 10:11:19 +01:00
Jakob Meier
d34db0a3be moved length check parse data of pdu header reader 2024-11-15 10:02:33 +01:00
e830cb5bdd Merge pull request 'cond code to string converter' (#40) from cond-code-string-converter into main
Reviewed-on: KSat/fsfw#40
2024-11-11 15:04:56 +01:00
393773ffe7
cond code to string converter 2024-11-11 15:03:17 +01:00
ed91a839be Merge pull request 'added missing include' (#39) from missing-include into main
Reviewed-on: KSat/fsfw#39
2024-11-11 11:08:52 +01:00
7b01b6655f
added missing include 2024-11-11 11:07:24 +01:00
2cefd4095e Merge pull request 'add option to add Catch2 for library users' (#38) from add-catch2-option into main
Reviewed-on: KSat/fsfw#38
2024-11-08 18:06:22 +01:00
847228911f
add option to add Catch2 for library users 2024-11-08 18:04:36 +01:00
f90241bdd6 Merge pull request 'only add Catch2 conditionally' (#36) from only-add-catch2-conditionally into main
Reviewed-on: KSat/fsfw#36
2024-10-29 17:05:35 +01:00
4514ba1f66 only add Catch2 conditionally 2024-10-29 16:12:38 +01:00
766c2fa90d Merge pull request 'vendor Catch2 and ETL' (#35) from vendor-dependencies into main
Reviewed-on: KSat/fsfw#35
2024-10-29 10:51:57 +01:00
5173292491
vendor Catch2 and ETL 2024-10-29 10:49:46 +01:00
3915e0d641 Merge pull request 'Filesystem and CFDP updates' (#34) from filesystem-api-update into main
Reviewed-on: KSat/fsfw#34
2024-10-29 10:26:43 +01:00
20819dd99a Filesystem and CFDP updates 2024-10-25 18:29:22 +02:00
a1b6e2ff89
improve filesystem API 2024-04-17 21:52:31 +02:00
8c87dafd5d
FreeRTOS clock fix 2024-04-17 20:56:07 +02:00
5ff161b70a
print fix for SOURCE 2024-04-17 20:49:57 +02:00
9a1e82de2a Merge remote-tracking branch 'eive/fdir-fix-fresh-dhb' into develop 2024-04-17 20:47:49 +02:00
e9b4fc9825 Merge branch 'develop' into fdir-fix-fresh-dhb 2024-04-17 20:47:33 +02:00
0660457c92
check for FDIR failures 2024-04-17 12:11:07 +02:00
7c9b9e4cd8
initialize FDIR component properly 2024-04-17 12:08:08 +02:00
3b0ee7ca31
i forgot to push.. 2024-04-17 10:07:09 +02:00
fb2e480705 did i forgot to push? 2024-04-16 13:58:10 +02:00
b8ae646060 this include might be missing 2024-04-16 13:53:35 +02:00
f307a86d9a
improve linux interface 2024-04-11 13:11:51 +02:00
8b21dd276d Merge pull request 'implement relative timeshift' (#173) from time-service-relative-timeshift into develop
Reviewed-on: eive/fsfw#173
Reviewed-by: Marius Eggert <eggertm@irs.uni-stuttgart.de>
2024-04-09 13:31:13 +02:00
e00da212cd Merge branch 'develop' into time-service-relative-timeshift 2024-04-09 11:11:59 +02:00
a229748aa4 distinct clock dump events 2024-04-09 10:57:00 +02:00
e6e3753324 Merge pull request 're-work some FDIR logic' (#172) from improve-dev-fdir into develop
Reviewed-on: eive/fsfw#172
2024-04-09 10:47:32 +02:00
94bd1ba2ab fix comment blocks 2024-04-08 13:38:14 +02:00
e12a8cfa29 make this change downwards compatible 2024-04-08 13:31:21 +02:00
efbcddc2e5 improvements for time service 2024-04-08 13:26:55 +02:00
31d4b85523 some optimizations 2024-04-08 13:14:20 +02:00
aff6bb673b
make marius the happies man alive 2024-04-08 10:34:28 +02:00
f8e3777c43
more fixes 2024-04-03 16:23:21 +02:00
0e2fa8dc83
lets not forget error handling 2024-04-03 16:19:40 +02:00
0cfe559b93
implement relative timeshift 2024-04-03 16:15:07 +02:00
c5159fb645
optimize docs 2024-04-03 12:52:32 +02:00
203c0bac5c
re-work some FDIR logic 2024-04-03 12:47:11 +02:00
6b70614762 Merge pull request 'Missing Initialization of FDIR in FreshDeviceHandlerBase' (#33) from meier/debug into develop
Reviewed-on: KSat/fsfw#33
2024-03-29 12:50:43 +01:00
Jakob Meier
cc99d987a7 updated changelog 2024-03-27 12:14:19 +01:00
Jakob Meier
babb02ebb6 run auto formatter 2024-03-27 12:13:01 +01:00
Jakob Meier
41cdf3c1e8 removed debug message from object manager again 2024-03-27 12:12:36 +01:00
Jakob Meier
383995939c disabled fsfw cpp ostream again 2024-03-27 12:11:42 +01:00
Jakob Meier
ede89de552 Merge branch 'develop' into meier/debug 2024-03-27 10:37:02 +01:00
a8f8c1496c yeah, that's why i hate c++ 2024-03-26 15:27:33 +01:00
Jakob Meier
8aa539e67f typo 2024-03-25 15:25:18 +01:00
0bd88a2689
I hate C++, this is awful 2024-03-21 16:10:45 +01:00
008ded64b1 Merge pull request 'Shared ring buffer improvements' (#32) from small-ring-bug-fix into develop
Reviewed-on: KSat/fsfw#32
2024-03-19 19:06:25 +01:00
a3eb81f1de added locked write helper method 2024-03-19 18:55:13 +01:00
24d41e7863 just a small form fix 2024-03-19 17:38:35 +01:00
43ea29cb84 Merge pull request 'Function to prevent Quaternion Sign Jump' (#171) from quat-no-sign-jump into develop
Reviewed-on: eive/fsfw#171
Reviewed-by: Robin Müller <muellerr@irs.uni-stuttgart.de>
2024-03-18 10:59:19 +01:00
Jakob Meier
63a00b8b4f initialize fdir instance in constructor of FreshDeviceHandlerBase 2024-03-14 16:19:44 +01:00
27c8a97d45 added function to prevent quaternion sign jump 2024-03-13 16:59:14 +01:00
47b21caf5f Merge pull request 'Removed duplicate Code' (#170) from cleanup into develop
Reviewed-on: eive/fsfw#170
Reviewed-by: Robin Müller <muellerr@irs.uni-stuttgart.de>
2024-03-06 10:54:12 +01:00
2673070204 actually do something with this rtval 2024-03-06 09:41:02 +01:00
518a07d05b removed duplicate code 2024-03-05 14:29:47 +01:00
Jakob Meier
3f2d83d95c added debug print out 2024-03-01 10:50:55 +01:00
516357d855 Merge pull request 'Expand Globalfunctions' (#168) from expand-globalfunctions into develop
Reviewed-on: eive/fsfw#168
Reviewed-by: Robin Müller <muellerr@irs.uni-stuttgart.de>
2024-02-27 12:50:28 +01:00
ac28b7e00d Merge branch 'develop' into expand-globalfunctions 2024-02-26 13:57:04 +01:00
0d4a862c1a Merge pull request 'Increase configurability of PusServiceBase' (#169) from psb-update into develop
Reviewed-on: eive/fsfw#169
Reviewed-by: Marius Eggert <eggertm@irs.uni-stuttgart.de>
2024-02-26 13:56:46 +01:00
b2576d3422 why are we ignoring usec 2024-02-23 11:33:20 +01:00
bccaf4a9ea capital 2024-02-23 11:31:11 +01:00
7d4e77843b frmt 2024-02-23 11:09:59 +01:00
cd2cd61ba5 Increase configurability of PusServiceBase 2024-02-13 15:57:43 +01:00
90f3f8ef1f removed printout 2024-02-12 14:51:54 +01:00
9894935e99 time systems 2024-02-12 14:42:58 +01:00
a3a6c0720c fixes 2024-02-12 14:36:14 +01:00
d5a52eadbb i should have done this ages ago 2024-02-12 14:20:04 +01:00
b5e7179af1 Merge pull request 'Rotation from Quaternions' (#167) from rotation-from-quaternions into develop
Reviewed-on: eive/fsfw#167
Reviewed-by: Robin Müller <muellerr@irs.uni-stuttgart.de>
2024-01-29 14:11:08 +01:00
5879eb7f7b rotation from quaternions 2024-01-26 11:06:05 +01:00
a4943f1cf0 Merge pull request 'Bump FSFW' (#31) from bump-fsfw into develop
Reviewed-on: KSat/fsfw#31
2023-12-18 13:16:28 +01:00
4a3135e1bd
little fix 2023-12-18 11:21:06 +01:00
e350bf6cec
Merge remote-tracking branch 'eive/develop' into bump-fsfw 2023-12-18 11:03:06 +01:00
e64e8b274d Merge pull request 'check whether map is full on insert' (#166) from insert-full-check into develop
Reviewed-on: eive/fsfw#166
Reviewed-by: Marius Eggert <eggertm@irs.uni-stuttgart.de>
2023-12-12 17:53:14 +01:00
48bcce65b1 check whether map is full on insert 2023-12-12 11:24:35 +01:00
7105e199c6 Merge pull request 'SLERP for antiparallel Quaternions' (#165) from slerp-fix-antiparallel-quaternions into develop
Reviewed-on: eive/fsfw#165
Reviewed-by: Robin Müller <muellerr@irs.uni-stuttgart.de>
2023-12-06 10:41:02 +01:00
94de483836 small fix 2023-12-06 09:26:22 +01:00
c648229c99 Merge pull request 'SLERP' (#163) from slerp into develop
Reviewed-on: eive/fsfw#163
Reviewed-by: Robin Müller <muellerr@irs.uni-stuttgart.de>
2023-12-05 09:25:48 +01:00
5b661551a8 fixes 2023-12-04 17:52:24 +01:00
3978524181 Merge branch 'develop' into slerp 2023-11-29 15:19:09 +01:00
7187f2b5cd Merge pull request 'TLE turns too old after just 7 Days' (#164) from tle-too-old into develop
Reviewed-on: eive/fsfw#164
2023-11-29 15:17:39 +01:00
8e367abb47 Merge branch 'develop' into tle-too-old 2023-11-29 15:17:19 +01:00
b28174db24 Merge pull request 'Fresh DHB pre-queue check hook' (#162) from fresh-dhb-pre-queue-hook into develop
Reviewed-on: eive/fsfw#162
Reviewed-by: Marius Eggert <eggertm@irs.uni-stuttgart.de>
2023-11-29 14:18:23 +01:00
c906acd659 tle turns too old after just 7 days 2023-11-29 09:48:11 +01:00
8dfc84c0b5 smoll fix 2023-11-27 10:52:47 +01:00
74775bb59d slerp 2023-11-27 10:38:25 +01:00
c02d9e009e docs improvements and fix 2023-11-21 17:40:06 +01:00
0021aa29f5 pre-queue hook 2023-11-21 17:37:02 +01:00
41d67bff63 Merge pull request 'New simpler DHB' (#161) from new-dhb into develop
Reviewed-on: eive/fsfw#161
Reviewed-by: Ulrich Mohr <mohr@irs.uni-stuttgart.de>
2023-11-16 11:02:44 +01:00
8d7bb51d44
add missing call to perform HK op 2023-11-15 11:39:04 +01:00
7673d8b396
add paramHelper 2023-11-15 10:03:56 +01:00
91b194d8eb Merge branch 'new-dhb' of https://egit.irs.uni-stuttgart.de/eive/fsfw into new-dhb 2023-11-14 11:48:20 +01:00
698897bfc5 default args 2023-11-14 11:48:17 +01:00
d554062b86
trigger event default arguments 2023-11-13 15:32:42 +01:00
bf7fac071c add mode setters 2023-11-09 17:18:33 +01:00
35be7da353
some more docs 2023-11-09 11:28:59 +01:00
18cc870c8e
add FDIR handling 2023-11-09 11:04:45 +01:00
133ca51d18
visibility changes 2023-11-09 10:45:21 +01:00
0a40391a75
thats the baseline 2023-11-09 10:36:45 +01:00
cc3e64e70d Merge pull request 'CFDP SOURCE handler' (#157) from cfdp-source-handler into develop
Reviewed-on: eive/fsfw#157
Reviewed-by: Marius Eggert <eggertm@irs.uni-stuttgart.de>
2023-10-19 10:59:53 +02:00
6021257a87
unittest fix 2023-10-19 10:21:18 +02:00
63c238005e Merge remote-tracking branch 'origin/develop' into cfdp-source-handler 2023-10-11 12:57:14 +02:00
0f604b35c6 improved readability 2023-10-09 09:26:56 +02:00
e3a815444e checkModeCommand to protected 2023-09-29 15:26:43 +02:00
19093866ee rtval for non op soc 2023-09-29 14:27:54 +02:00
Mikael
f28ba61b02 Added opCode to performControlOperation 2023-09-18 16:01:03 +02:00
Mikael
cfd4b1655a Disabled debug flag, now for real 2023-09-15 13:59:57 +02:00
mikael.senger
5cfc69a570 diseable CCSDS Debug 2023-09-14 19:26:46 +02:00
497f947237
add missing 0 termination 2023-09-14 15:04:54 +02:00
5bd020193b
initialize result 2023-09-11 15:38:46 +02:00
420c0625a5
result was not stored properly 2023-09-11 15:38:06 +02:00
mikael.senger
38d8fe772b disable debug flag 2023-09-07 14:33:13 +02:00
42a0b15303
hardcore bug 2023-09-06 20:49:53 +02:00
c199cbedaa
some improvements, remove debugging stuff 2023-09-06 13:40:18 +02:00
c4e18cc2f3
what was i thinking here? 2023-09-06 11:45:02 +02:00
c143198494
debugging 2023-09-06 10:11:09 +02:00
448fbd0d38
this should be less confusing, saner defaults 2023-09-05 16:04:48 +02:00
470f589bde
need to rework this fsm.. but works now 2023-09-04 11:01:55 +02:00
33fccaaa54 Merge pull request 'fix serialize buffer adapter' (#30) from fix-serialize-buffer-adapter into develop
Reviewed-on: KSat/fsfw#30
2023-09-01 14:06:05 +02:00
23bcfe0173
fix serialize buffer adapter 2023-09-01 12:10:41 +02:00
ec0c0a1cdd
actually a useful event printout 2023-08-31 17:12:23 +02:00
dfcfb035be
fix some retval duplications 2023-08-31 15:09:22 +02:00
6e53582dc9
split up CFDP retval domains 2023-08-31 14:59:09 +02:00
fb1500e041
continue 2023-08-30 11:34:38 +02:00
ea2e58249d
API improvements 2023-08-30 11:18:49 +02:00
9ef63825f3
optimization 2023-08-16 13:15:34 +02:00
073cb4b3d5
adaptions for reserved message handling 2023-08-16 13:10:21 +02:00
3c6102fb97
forward declare SerialBufferAdapter<size_t> 2023-08-15 18:49:31 +02:00
734767045a
Merge remote-tracking branch 'upstream/development' into develop 2023-08-15 18:44:23 +02:00
12f8cc5fc2
remove more obsolete code 2023-08-15 18:06:50 +02:00
1e78d6ce66 Merge remote-tracking branch 'eive/develop' into remove-diagnostic-hk 2023-08-15 18:00:51 +02:00
845f040f13
remove diagnostic HK 2023-08-15 18:00:37 +02:00
8c11685240
introduce handling for full target queue 2023-08-14 21:19:35 +02:00
cb1aaea6cd
add more checks 2023-08-14 21:04:22 +02:00
22df8f6147
fix the tests 2023-08-14 21:01:29 +02:00
60dcacf432
further tweaks for both CFDP handlers 2023-08-14 20:47:27 +02:00
b39e1c7e07 Merge remote-tracking branch 'origin/develop' into cfdp-source-handler 2023-08-14 15:59:13 +02:00
036667a969
type improvements 2023-08-14 15:58:01 +02:00
67c38f327e
rename source file 2023-08-14 13:54:11 +02:00
e1816ed230
that should be all indications 2023-08-14 13:45:13 +02:00
5ff464252f
added some user checks 2023-08-14 13:40:25 +02:00
cd8d64830c
more checks 2023-08-14 13:33:47 +02:00
b7056a7467
additional checks 2023-08-14 13:24:22 +02:00
0fc2c7b5e9
oops 2023-08-14 13:19:48 +02:00
eae7c44874
reset error count 2023-08-14 13:19:32 +02:00
e4aae75747
more checks 2023-08-14 12:19:55 +02:00
b094ba145f
multi file segment works 2023-08-14 12:15:35 +02:00
15629abf19
the joys of UB or whatever that crap was 2023-08-14 12:13:29 +02:00
7aeb25e064
unittest for transfer with 2 segments 2023-08-14 11:26:57 +02:00
d246ce34d0 Merge pull request 'Change TLE validity duration' (#159) from spg4-tle-too-old into develop
Reviewed-on: eive/fsfw#159
Reviewed-by: Robin Müller <muellerr@irs.uni-stuttgart.de>
2023-08-14 10:09:00 +02:00
796c7a9e37 tle is too old after 30 days now 2023-08-09 11:42:11 +02:00
7c875f1067
unittest for small file transfer done 2023-08-04 15:17:53 +02:00
e8451cac31
add one test condition 2023-08-04 14:21:36 +02:00
8ddd6eb18d
some improvements for test 2023-08-03 17:44:30 +02:00
6c6b552059
start small file transfer test 2023-08-03 17:43:03 +02:00
9a1437980f
add empty stubs 2023-08-03 15:50:27 +02:00
12e52a92f2
empty file transfer test done 2023-08-03 15:49:23 +02:00
dffce43e6b
metadata PDU seems to be correct 2023-08-03 15:30:38 +02:00
daf75547a4
insidious bug 2023-08-03 15:13:26 +02:00
0cccf26021
should not be problematic but somehow is.. 2023-08-03 14:34:21 +02:00
c075f27e20
start verifying metadata PDU 2023-08-03 13:57:55 +02:00
3167988951
continue source handler 2023-08-03 13:03:58 +02:00
a856f91c67
nice 2023-07-27 17:15:01 +02:00
f49e607881
finally it works 2023-07-27 15:07:14 +02:00
0f208ec75a
seems to work well 2023-07-27 14:55:46 +02:00
5679b139ad
reserved message unittest working 2023-07-26 18:20:32 +02:00
947f2b8685
add some additional API 2023-07-26 17:47:27 +02:00
291c75c01f
test put request 2023-07-26 17:29:35 +02:00
fde277cd06
start adding dedicated put request handler 2023-07-26 17:17:51 +02:00
bb186fc965
more bugfixes 2023-07-26 16:58:58 +02:00
e8bf8b9575
looking good 2023-07-26 16:36:21 +02:00
8f5a8b13d3
parsing finally works 2023-07-26 16:25:42 +02:00
314cba363f
contnue msg parser unittest 2023-07-25 16:16:35 +02:00
244e2d0737
start adding message parser unittests 2023-07-25 13:58:22 +02:00
8f0974d83e
finished reserved msg creator function 2023-07-24 18:07:20 +02:00
8581f9a6f3
start implementing reserved message creator 2023-07-24 18:01:25 +02:00
844c90a625
constructor fix 2023-07-24 16:42:13 +02:00
437851db3e
naming 2023-07-24 16:40:44 +02:00
e8b9897ee3
even better name 2023-07-24 16:40:25 +02:00
33df8e8cc5
this parser should do the job 2023-07-24 16:38:11 +02:00
52fc0958f7
iniitalize field 2023-07-24 11:58:06 +02:00
66704dc571
getting tricky again.. 2023-07-24 11:57:33 +02:00
0943863ec6
need to think about that parser again.. 2023-07-24 11:35:26 +02:00
2585028e75
put request serializable now 2023-07-24 11:33:37 +02:00
7bf7336d4a
almost done 2023-07-24 11:15:50 +02:00
b0b6c68720
we already have CFDP messages 2023-07-24 11:05:11 +02:00
a1f36a0dd8
put request 2023-07-24 10:58:18 +02:00
e4665c9394
continue with the msg to user / put request architecture 2023-07-24 10:52:38 +02:00
98cbf38432
this is going to be complex.. 2023-07-24 10:11:16 +02:00
5d3f00da7f
that should do the job 2023-07-24 10:06:45 +02:00
69fd6d0f6a
lets see how we can do this 2023-07-21 16:35:05 +02:00
045054fce0
start implementing metadata parser 2023-07-21 16:12:17 +02:00
4c9e731113 Merge branch 'cfdp-source-handler' of https://egit.irs.uni-stuttgart.de/eive/fsfw into cfdp-source-handler 2023-07-21 16:09:59 +02:00
e00e198ff1
this seems to work 2023-07-21 16:09:52 +02:00
9c8434d856
LOOKING GOOOD 2023-07-19 23:43:40 +02:00
42c215ef70
some additional notes 2023-07-19 23:24:43 +02:00
273fd3ebfd
added sequence count provider abstraction 2023-07-19 23:22:55 +02:00
6c9c4ee047
add EOF impl 2023-07-19 14:06:15 +02:00
1bfb695b41
some minor tweaks 2023-07-19 14:02:03 +02:00
1561b9a247
implemented fle data PDUs 2023-07-19 13:44:52 +02:00
896b7a7358
start FD PDU handling 2023-07-19 00:12:14 +02:00
8e62143ac8
continue impl 2023-07-18 09:38:46 +02:00
1d97327f79
start implementing metadata PDU generation 2023-07-17 18:56:10 +02:00
5e9d402598
getFileSize API for fsfw 2023-07-17 16:40:44 +02:00
b53c48863f
start introducing FSM result 2023-07-17 15:21:22 +02:00
4dc6398fd5
continue source FSM 2023-07-17 15:11:51 +02:00
8fcc4eab60
some internal state handling 2023-07-17 15:03:08 +02:00
972dc7e19e
continue source handler 2023-07-17 14:54:45 +02:00
06ef498a18
start implementing put request function 2023-07-17 14:48:37 +02:00
6322a31566
some fixes 2023-07-17 13:43:48 +02:00
95b77ed826
put request support baseline 2023-07-17 13:28:32 +02:00
3b1da85229
start setting up source handler 2023-07-17 11:37:20 +02:00
1cbcfc08ff
reorder includes 2023-07-17 10:46:12 +02:00
d575da8540 Merge pull request 'Small tweak to allow immediate HK generation' (#158) from small-hk-tweak into develop
Reviewed-on: eive/fsfw#158
Reviewed-by: Marius Eggert <eggertm@irs.uni-stuttgart.de>
2023-07-17 10:37:39 +02:00
ca27cef2ee
Merge branch 'small-hk-tweak' into cfdp-source-handler 2023-07-17 10:37:03 +02:00
62ace649a7
fix unittest 2023-07-17 10:35:35 +02:00
aac74fae38
shared cmake file 2023-07-17 10:34:19 +02:00
a26b0c38ac
small tweak to allow immediate HK generation 2023-07-17 10:31:02 +02:00
f44110a7f5
share the FSFW Param block 2023-07-17 10:25:09 +02:00
35712070cf
source handler 2023-07-17 10:15:06 +02:00
1b79713430 Merge branch 'cfdp-source-handler' of https://egit.irs.uni-stuttgart.de/eive/fsfw into cfdp-source-handler 2023-07-17 09:53:51 +02:00
a6cc5171da
continue source handler 2023-07-17 09:53:23 +02:00
9994c46e47 Merge branch 'develop' into cfdp-source-handler 2023-07-14 16:01:51 +02:00
cf927ecee7
added bare structure of FSM 2023-07-14 15:56:38 +02:00
42e74d22cc Merge pull request 'countdown based HK generation' (#156) from hk-generation-countdown-based into develop
Reviewed-on: eive/fsfw#156
Reviewed-by: Marius Eggert <eggertm@irs.uni-stuttgart.de>
2023-07-11 17:35:10 +02:00
36caa58043 Merge branch 'develop' into hk-generation-countdown-based 2023-07-11 17:34:24 +02:00
988e07f0be
countdown 2023-07-11 15:40:43 +02:00
4ecd9eb62e Merge pull request 'important bugfix for PUS TM creator' (#751) from bugfix-tm-creator into development
Reviewed-on: #751
2023-07-10 21:36:49 +02:00
fb89d7a3b6 important bugfix for PUS TM creator 2023-07-10 17:47:05 +02:00
88e8665280
important bugfix for PUS TM creator 2023-07-10 17:45:02 +02:00
9c8b1c697b
added back missing function 2023-07-10 14:20:02 +02:00
110cb903a6
countdown based HK generation 2023-07-10 14:14:31 +02:00
7e1fb04f8a
possible Apple CLang fixes 2023-07-04 16:51:29 +02:00
7f2411358d
fix shadowing warning 2023-06-30 15:52:30 +02:00
f0ee7772e8 Merge pull request 'EIVE upstream' (#29) from use-eive-upstream into develop
Reviewed-on: KSat/fsfw#29
2023-06-30 15:44:39 +02:00
4fc06a1eaf
fixes for SOURCE 2023-06-30 15:20:25 +02:00
a196c3387e
Merge remote-tracking branch 'eive/develop' into use-eive-upstream 2023-06-30 15:02:53 +02:00
f8fae1ac62
fix variable shadowing 2023-06-30 14:59:24 +02:00
1b23aa4246
bugfixes and improvements for dest handler 2023-06-30 12:01:18 +02:00
7d713219c5
continue source handler 2023-06-30 11:59:22 +02:00
1be09a2310
the C++ tooling is shit 2023-06-30 11:48:25 +02:00
7add782470
start CFDP source handler 2023-06-30 11:36:19 +02:00
8da89eba80 Merge pull request 'add API to set msg counter' (#155) from pus-msg-counter-mutable into develop
Reviewed-on: eive/fsfw#155
Reviewed-by: Marius Eggert <eggertm@irs.uni-stuttgart.de>
2023-06-28 13:19:28 +02:00
7e8845f2c2 Merge remote-tracking branch 'origin/develop' into pus-msg-counter-mutable 2023-06-26 18:12:36 +02:00
6aff3250c2 Merge pull request 'Internal Error Reporter Configurability' (#154) from internal-error-reporter-set into develop
Reviewed-on: eive/fsfw#154
2023-06-26 18:10:06 +02:00
c3572e31a8
add API to set msg counter 2023-06-25 12:35:50 +02:00
2293e7f2bb
typo 2023-06-22 16:12:41 +02:00
a85a38c882
some thnings are configurable now 2023-06-22 16:08:29 +02:00
0f76cdb3ba
typo 2023-06-20 20:36:03 +02:00
268c2e87c9 Merge pull request 'max value calc fix' (#153) from max-value-fix-v2 into develop
Reviewed-on: eive/fsfw#153
2023-06-20 18:20:00 +02:00
87f94a252f Merge branch 'develop' into max-value-fix-v2 2023-06-20 18:19:19 +02:00
c7037d417a nullptr check for optional argument 2023-06-20 11:54:15 +02:00
f80c5980ea max value calc fix 2023-06-19 17:04:45 +02:00
ad01642fee Merge pull request 'specify truncate flag explicitely' (#151) from specify-truncate-flag-explicitely into develop
Reviewed-on: eive/fsfw#151
Reviewed-by: Marius Eggert <eggertm@irs.uni-stuttgart.de>
2023-06-19 09:32:19 +02:00
f2947bc78e
specify truncate flag explicitely 2023-06-18 19:04:36 +02:00
0a977ea688 Merge pull request 'make number of parallel cmds configurable' (#149) from make-srv3-num-parallel-cmds-configurable into develop
Reviewed-on: eive/fsfw#149
2023-06-14 03:37:02 +02:00
74b164b1da make number of parallel cmds configurable 2023-06-13 08:09:04 +02:00
5322de0599 Merge pull request 'Pull CFPD bugfix in dev branch' (#147) from pull-cfdp-fix-into-dev-branch into obsw-v3.0.0-dev
Reviewed-on: eive/fsfw#147
2023-06-09 13:41:29 +02:00
9a4bf51006 Merge branch 'develop' into obsw-v3.0.0-dev 2023-06-09 13:11:30 +02:00
3a70229510 Merge pull request 'configurable queue depth' (#146) from service-8-configurable-queue-depth into obsw-v3.0.0-dev
Reviewed-on: eive/fsfw#146
2023-06-09 13:03:17 +02:00
b3beedad9f Merge branch 'obsw-v3.0.0-dev' into service-8-configurable-queue-depth 2023-06-09 13:03:08 +02:00
efe217a197 Merge pull request 'Rework L3GD20H Config' (#143) from gyr-config-rework into obsw-v3.0.0-dev
Reviewed-on: eive/fsfw#143
2023-06-09 13:01:23 +02:00
b442ca09b9 configurable queue depth 2023-06-07 13:46:46 +02:00
146c3471d0 Merge pull request 'fixes for GCC13' (#750) from mohr/GCC13 into development
Reviewed-on: #750
2023-06-02 13:40:35 +02:00
1816c3f623 Merge pull request 'CFDP bugfix' (#749) from eive/fsfw:cfdp-bugfix-unittest-fixes into development
Reviewed-on: #749
2023-06-02 13:30:54 +02:00
d03d5aa74c fixing host osal for GCC13 2023-06-02 12:02:37 +02:00
26e97ddf89 overload vs override clarification for GCC13; Also, cmake-format 2023-06-02 11:33:20 +02:00
be3a57a795 bump ETL and Catch2 version 2023-06-01 17:54:38 +02:00
13b97abf0d fixing build failure for master and development branch 2023-06-01 17:06:19 +02:00
64922367e4 Merge pull request 'FSFW Update' (#28) from fsfw_update into develop
Reviewed-on: KSat/fsfw#28
2023-05-28 23:43:21 +02:00
cb6eed134b
add printf support 2023-05-26 17:03:27 +02:00
f95c373076 Merge pull request 'TCP/IP server fixes and improvements' (#747) from eive/fsfw:tcpip_server_fixes_improvements into development
Reviewed-on: #747
2023-05-25 16:04:28 +02:00
e03731bcf8 Merge pull request 'event manager improvements' (#741) from eive/fsfw:event_manager_improvements into development
Reviewed-on: #741
2023-05-25 15:46:42 +02:00
9fe8579377
CFDP bugfix 2023-05-25 15:11:56 +02:00
f42a16748d
fix shadowing issue 2023-05-25 15:06:04 +02:00
e8095f82c6 Merge remote-tracking branch 'upstream/development' into fsfw_update 2023-05-25 15:04:43 +02:00
9372b2a575
Merge remote-tracking branch 'upstream/development' into develop 2023-05-25 15:03:54 +02:00
2714e588d7
improvements 2023-05-25 15:01:53 +02:00
e905288adc
Merge remote-tracking branch 'upstream/development' into tcpip_server_fixes_improvements 2023-05-25 15:00:42 +02:00
3805ea50a7
remove unused constant 2023-05-25 14:58:18 +02:00
699bd694cd Merge branch 'development' into event_manager_improvements 2023-05-25 14:44:22 +02:00
0b39ab383f
comment 2023-05-25 13:22:38 +02:00
aafa53148e Merge pull request 'CFDP Bugfix' (#144) from cfdp-bugfix-unittest-fixes into develop
Reviewed-on: eive/fsfw#144
Reviewed-by: Marius Eggert <eggertm@irs.uni-stuttgart.de>
2023-05-22 10:40:44 +02:00
e0adb3325f
werks 2023-05-22 10:37:26 +02:00
82eaf4412f
get rid of obsolete serializer 2023-05-16 15:43:31 +02:00
4391823f01
changelog 2023-05-15 16:14:36 +02:00
1a77e6bb09
proper floating point comparison 2023-05-15 16:13:05 +02:00
cae131edcf
CFDP and unittest bugfixes 2023-05-15 16:02:55 +02:00
4518fec65c CHANGELOG 2023-05-08 15:25:47 +02:00
dac1aacab2 Merge pull request 'Update Power Switch IF' (#743) from eive/fsfw:update_power_switch_if into development
Reviewed-on: #743
2023-05-08 15:00:47 +02:00
0042f92fdf Merge pull request 'bump ETL version' (#748) from KSat/fsfw:bump_etl_dep into development
Reviewed-on: #748
2023-05-08 14:53:02 +02:00
656faf8169 Merge remote-tracking branch 'upstream/development' into update_power_switch_if 2023-05-08 14:44:27 +02:00
f84431e965 Merge pull request 'bugfix and changelog for Linux getUptime' (#745) from eive/fsfw:important_bugfix_linux_get_uptime into development
Reviewed-on: #745
2023-05-08 14:29:55 +02:00
0cec9ebb73 Merge pull request 'small tweak for version getter' (#744) from eive/fsfw:small_version_getter_tweak into development
Reviewed-on: #744
2023-05-08 14:13:06 +02:00
a440b7c394 Merge pull request 'add CFDP subsystem ID' (#742) from eive/fsfw:add_cfdp_subsystem_id into development
Reviewed-on: #742
2023-05-08 14:09:04 +02:00
bbfc1b2b34 Merge pull request 'FixedArrayList compile time assert' (#740) from eive/fsfw:container_additional_assert into development
Reviewed-on: #740
2023-05-08 14:04:56 +02:00
025b379e8b
bump ETL version 2023-05-04 14:04:55 +02:00
52c3246416
update ETL version 2023-05-04 14:01:18 +02:00
b673cdfb50 Merge remote-tracking branch 'upstream/development' into fsfw_update 2023-05-04 12:37:18 +02:00
258f0d3313 use both LPFs 2023-04-19 15:25:14 +02:00
5eb9ee8bc1
DHB fdir: event queue depth confgurable 2023-04-14 21:22:24 +02:00
7f61d17cee
even better event manager printout 2023-04-14 21:08:44 +02:00
ffa2fa477f Merge pull request 'move CFDP handler' (#142) from move_cfdp_handler into develop
Reviewed-on: eive/fsfw#142
2023-04-11 16:50:46 +02:00
894d1e3b87
move CFDP handler 2023-04-11 16:36:54 +02:00
285d327b97
clean up spi retval defs 2023-04-07 17:42:44 +02:00
e97fa5ac84
add skip directive for retvals 2023-04-07 11:03:46 +02:00
5a9304765f
accepts action commands without ipc data 2023-04-06 22:34:57 +02:00
6650c293da
change collection interval is public now 2023-04-04 15:59:26 +02:00
9fca7581dd Merge branch 'develop' of https://egit.irs.uni-stuttgart.de/eive/fsfw into develop 2023-04-04 01:52:29 +02:00
4af90f99f3
changelog 2023-04-04 01:52:26 +02:00
94cdf67a80
make health functions virtual 2023-04-04 01:51:58 +02:00
7966ede11b
add O_SYNC flag for UioMapper 2023-04-03 21:57:18 +02:00
7a392dc33a
new register function 2023-04-03 18:54:35 +02:00
1e3c89b672
i dont think ths needs to be public 2023-04-03 17:59:14 +02:00
e2e87b149d
initialize switch state list 2023-04-03 14:31:45 +02:00
4f632e2c68
ctrl base bugfix 2023-03-28 19:37:47 +02:00
314f0fa2cd
start power switch component in undefined mode 2023-03-28 15:27:48 +02:00
b31e1037fb
HK service configurable queue depth 2023-03-26 20:05:10 +02:00
b814e7198f Merge pull request 'Allow creating regular threads' (#140) from allow_creating_regular_threads into develop
Reviewed-on: eive/fsfw#140
2023-03-24 14:15:53 +01:00
6328b70d7b Merge branch 'develop' into allow_creating_regular_threads 2023-03-24 14:15:39 +01:00
a937b457f9
this is so confusing 2023-03-24 14:10:47 +01:00
4415dc24e1
fix host OSAL 2023-03-24 13:25:34 +01:00
e704295cce
default value 2023-03-24 11:58:23 +01:00
d16b3c7e67
try to do this cleanly 2023-03-24 11:53:41 +01:00
3b86545725 Merge pull request 'add BUSY retval' (#141) from busy_retval_dhb_com into develop
Reviewed-on: eive/fsfw#141
2023-03-24 11:35:09 +01:00
cf6150cc18
add BUSY retval 2023-03-24 00:57:44 +01:00
bfb5c2ff03 Merge branch 'develop' into allow_creating_regular_threads 2023-03-23 18:45:49 +01:00
bf02061d47 Merge pull request 'use RR sched instead of FIFO for Linux RT' (#139) from use_rr_sched into develop
Reviewed-on: eive/fsfw#139
2023-03-23 18:45:09 +01:00
2c4e110254 Merge branch 'develop' into use_rr_sched 2023-03-23 18:44:59 +01:00
7ed75ea87b Merge remote-tracking branch 'origin/develop' into allow_creating_regular_threads 2023-03-23 18:44:06 +01:00
db4587bb59
allow creating regular threads 2023-03-23 18:29:17 +01:00
33ac395072
use RR sched instead of FIFO for Linux RT 2023-03-23 15:42:14 +01:00
f8a7c1d4ed
rename namespace 2023-03-22 01:03:49 +01:00
341437df13
add flush functions for serial helpers 2023-03-21 20:20:13 +01:00
227524a21d
transition source submode is tricky 2023-03-20 15:49:09 +01:00
c35a0a8541
TCP/IP server fixes and improvements 2023-03-15 12:40:44 +01:00
0f81d5e458
Merge remote-tracking branch 'upstream/development' into container_additional_assert 2023-03-15 12:34:36 +01:00
e0a072859b
Merge remote-tracking branch 'upstream/development' into event_manager_improvements 2023-03-15 12:33:57 +01:00
b50f092939
Merge remote-tracking branch 'upstream/development' into update_power_switch_if 2023-03-15 12:33:08 +01:00
2f90e12179
Merge remote-tracking branch 'upstream/development' into important_bugfix_linux_get_uptime 2023-03-15 12:32:25 +01:00
8b77fac099 Merge pull request 'health service fixes and changelog' (#746) from eive/fsfw:health_service_fixes into development
Reviewed-on: #746
2023-03-15 12:29:31 +01:00
47503824d7
health service fixes and changelog 2023-03-15 12:27:39 +01:00
5e3f5c4121
fuse update 2023-03-15 12:25:39 +01:00
1f36c082ef
bugfix and changelog for Linux getUptime 2023-03-15 12:21:50 +01:00
aa84e93603
small tweak for version getter 2023-03-15 12:17:36 +01:00
8f63a0e747
changelog 2023-03-15 12:15:21 +01:00
6fc8f756a7
update power switch IF 2023-03-15 12:13:55 +01:00
067cb7d0f8
update catch factory 2023-03-15 12:11:22 +01:00
d98ed40e3d
add CFDP subsystem ID 2023-03-15 12:09:30 +01:00
2c17af4ef8
changelog 2023-03-15 12:06:13 +01:00
110fb43b9c
event manager improvements 2023-03-15 12:05:22 +01:00
b057250bfb
changelog 2023-03-15 11:53:12 +01:00
066dd0d397
changelog 2023-03-15 11:52:20 +01:00
f735c2e9d4
assert size larger than 0 2023-03-15 11:51:51 +01:00
43fd0b2f59
resolve some more merge conflicts 2023-03-15 11:48:50 +01:00
d0607824ad
Merge remote-tracking branch 'upstream/development' into develop 2023-03-15 11:40:48 +01:00
cf27954a86
changelog 2023-03-14 19:55:01 +01:00
f84e3284ab
just hardcode spill option to true 2023-03-14 19:54:21 +01:00
5250423d1d Merge pull request 'Periodic HK helper simplification' (#136) from periodic_hk_helper_simplification into develop
Reviewed-on: eive/fsfw#136
2023-03-14 18:27:14 +01:00
522bd41d6e
changelog 2023-03-14 18:26:44 +01:00
c61c85280b
remove more code 2023-03-14 18:26:04 +01:00
afbe5e1f65
Merge remote-tracking branch 'origin/develop' into periodic_hk_helper_simplification 2023-03-14 18:23:57 +01:00
4c88ab80c8 Merge pull request 'Pool Manager spill to higher pools option' (#135) from pool_manager_spilling_opt into develop
Reviewed-on: eive/fsfw#135
2023-03-14 18:22:31 +01:00
5ba69b169f
changelog 2023-03-14 18:22:00 +01:00
40405fe6c7
add spill option 2023-03-14 18:21:16 +01:00
aac32e763c
some compile fixes 2023-03-14 18:20:17 +01:00
bf980d74c0
HK helper simplification 2023-03-14 17:40:39 +01:00
b6b9d1d790
make dataset enable idempotent 2023-03-14 16:49:46 +01:00
0973ba6bf2 Merge pull request 'basic faulty cb for power switcher component' (#134) from feature_power_switch_faulty_cb into develop
Reviewed-on: eive/fsfw#134
2023-03-14 14:15:11 +01:00
1cfebb5d47 Merge branch 'develop' into feature_power_switch_faulty_cb 2023-03-14 14:14:50 +01:00
0b0a0299bc
power switch IF improvements 2023-03-14 13:45:03 +01:00
8382d61b92
possible fix for power switch component 2023-03-14 11:44:13 +01:00
7208343b6d
basic faulty cb for power switcher component 2023-03-13 16:01:13 +01:00
9a8d775eb1
optimization for cmd executor 2023-03-12 20:49:34 +01:00
4d6f6e6b23
event manager queue depth configurable 2023-03-10 14:58:20 +01:00
55f6825a03 Revert "Modes: reusing submode for mode mask, more unittests"
This reverts commit f0bddfcb21.
2023-03-10 14:50:16 +01:00
c162acb7df Merge branch 'develop' of https://egit.irs.uni-stuttgart.de/eive/fsfw into develop 2023-03-10 14:23:51 +01:00
87462afe6d
better error printout for i2c write error 2023-03-10 14:23:40 +01:00
a8de395ea0 Merge pull request 'Modes: reusing submode for mode mask, more unittests' (#133) from mohr/submode_mask into develop
Reviewed-on: eive/fsfw#133
Reviewed-by: Robin Müller <muellerr@irs.uni-stuttgart.de>
2023-03-10 11:22:11 +01:00
f0bddfcb21 Modes: reusing submode for mode mask, more unittests 2023-03-09 16:43:45 +01:00
23d9b44b3e Merge pull request 'exceptionless host filesystem' (#132) from avoid_exceptions into develop
Reviewed-on: eive/fsfw#132
2023-03-08 14:55:18 +01:00
26e4445189
exceptionless host filesystem 2023-03-08 14:47:03 +01:00
9ee3cdf729 Merge pull request 'OFF -> NORMAL: Set transition source modes' (#131) from off_to_normal_transition_sources into develop
Reviewed-on: eive/fsfw#131
2023-03-08 01:24:54 +01:00
1b7493f945
OFF -> NORMAL: Set transition source modes 2023-03-08 01:18:11 +01:00
7f6ba5f40b Merge pull request 'Feature: Allowed Submodes Mask for Mode List Entry' (#130) from feature_allow_submodes_mode_list_entry into develop
Reviewed-on: eive/fsfw#130
Reviewed-by: Steffen Gaisser <gaisser@irs.uni-stuttgart.de>
2023-03-07 17:20:47 +01:00
070b48ada2
review improvements 2023-03-07 17:15:34 +01:00
d9a139e1ef Merge remote-tracking branch 'origin/develop' into feature_allow_submodes_mode_list_entry 2023-03-07 16:31:28 +01:00
c80a3752d9
afmt 2023-03-07 16:31:08 +01:00
af58c414fc
bugfix in submode check logic 2023-03-07 16:29:10 +01:00
4c48668125
add copy and assignment ctor for mode definition 2023-03-07 16:03:28 +01:00
2745b2080d
allow submode mask now 2023-03-07 13:55:40 +01:00
e9d9f44605
added length check 2023-03-06 14:01:45 +01:00
2c5af91db1 Merge pull request 'new monotonic clock API' (#128) from feature_monotonic_clock_api into develop
Reviewed-on: eive/fsfw#128
Reviewed-by: Marius Eggert <eggertm@irs.uni-stuttgart.de>
2023-03-04 11:47:37 +01:00
5cd7b98ba7
more todo docs 2023-03-04 11:38:16 +01:00
a39f1271ec
return FAILED for win 2023-03-04 11:32:32 +01:00
bbf0d7a0d2
add basic impl (no windows) for host 2023-03-04 11:31:54 +01:00
04ee3c7362
renaming 2023-03-04 11:04:55 +01:00
95dab69b35
new monotonic clock API 2023-03-04 11:03:22 +01:00
33de15205b Merge pull request 'configurable queue depth' (#127) from feature_configurable_queue_depth_tcpip_servers into develop
Reviewed-on: eive/fsfw#127
2023-03-03 16:33:29 +01:00
4d353a1ad2
remove obsolete constant 2023-03-03 16:36:30 +01:00
6006c97e48
configurable queue depth 2023-03-03 15:45:44 +01:00
6e17e45506 Merge pull request 'timeval: Use system clock' (#126) from feature_timeval_use_sysclock into develop
Reviewed-on: eive/fsfw#126
2023-03-03 15:25:38 +01:00
64537d442a extneded and fixed countdown unittests 2023-03-03 14:54:52 +01:00
78cf00315d use sys clock for Countdown 2023-03-03 14:30:35 +01:00
245886c555
add lock context for pool manager 2023-03-02 15:33:49 +01:00
f84097543e
allow passing context to mutex guard 2023-03-02 15:20:59 +01:00
511d07c0c7
refactored MGM device code 2023-02-26 21:26:24 +01:00
cf735143fe
update for SPI/gyro dev handler code 2023-02-26 14:54:35 +01:00
bdfe31dba4 Merge branch 'mueller/pus-15-tm-storage' into develop 2023-02-24 19:03:21 +01:00
216f603d62 Merge remote-tracking branch 'origin/develop' into mueller/pus-15-tm-storage 2023-02-24 16:56:32 +01:00
174a6aa862 Merge pull request 'use timeval instead of uptime for stopwatch' (#125) from stopwatch-fix into develop
Reviewed-on: eive/fsfw#125
Reviewed-by: Robin Müller <muellerr@irs.uni-stuttgart.de>
2023-02-24 16:51:28 +01:00
c2d9370aa1 Merge branch 'develop' into stopwatch-fix 2023-02-24 16:51:08 +01:00
893b434728
allow dest handler to handle folder destinations 2023-02-24 16:49:23 +01:00
6eba84566d use timeval instead of uptime 2023-02-24 16:39:49 +01:00
f0415a97b1
some fixes and improvements 2023-02-24 15:49:05 +01:00
abcf1b29b2
execution complete 2023-02-24 14:50:36 +01:00
d373c45d36 Merge branch 'develop' into mueller/pus-15-tm-storage 2023-02-22 15:45:54 +01:00
bd208038dd
printout fixes 2023-02-22 15:45:39 +01:00
206af00c8b Merge remote-tracking branch 'origin/develop' into mueller/pus-15-tm-storage 2023-02-21 11:14:19 +01:00
2efff4d2c5
missing include 2023-02-21 02:59:13 +01:00
2a0c244468
add pus 15 store ID 2023-02-20 16:10:21 +01:00
e1711f0345 Merge remote-tracking branch 'origin/develop' into mueller/pus-15-tm-storage 2023-02-20 15:04:13 +01:00
c327985222
printout tweak 2023-02-20 15:02:00 +01:00
b45206ccd6 Merge remote-tracking branch 'origin/develop' into mueller/pus-15-tm-storage 2023-02-20 13:33:10 +01:00
c8469ca647 a lot of bug potential here 2023-02-18 14:03:19 +01:00
2d6622b8b8 wtf is this interface 2023-02-18 13:51:24 +01:00
5f9eb01d94
better naming 2023-02-18 13:46:51 +01:00
3568bdbecf
lets see if this fixes the issue 2023-02-18 13:45:49 +01:00
fcd84b59ae how the hell does this break anything 2023-02-18 13:37:39 +01:00
e3c968096b i2c small improvements 2023-02-18 13:07:38 +01:00
c745c0c8b4 Merge remote-tracking branch 'origin/develop' into mueller/pus-15-tm-storage 2023-02-17 13:18:09 +01:00
be015b4c66
service 11: cast to fix warning 2023-02-17 12:07:50 +01:00
dae5e988fd Merge remote-tracking branch 'origin/develop' into mueller/pus-15-tm-storage 2023-02-17 11:52:23 +01:00
a6d707a7db
SubsystemBase: Add function to update child modes 2023-02-17 02:04:17 +01:00
fe41d73895
remove obsolete mode 2023-02-16 17:57:03 +01:00
70b785984c Merge remote-tracking branch 'origin/develop' into mueller/pus-15-tm-storage 2023-02-14 17:33:59 +01:00
9de6c4b3aa
printout corrections 2023-02-14 14:33:02 +01:00
d256ede8c1
fix cppcheck lint 2023-02-14 10:33:22 +01:00
f0b8457ba2
bugfix for SPI
- Set transfer length to 0 for failed transfers
2023-02-13 13:51:52 +01:00
dac2d210b5
updates for thermal module in DHB 2023-02-13 00:36:54 +01:00
8b4f73a97b
better error msg 2023-02-12 21:07:11 +01:00
7fae6cbd6d
added missing CS unlock 2023-02-12 20:06:32 +01:00
d302ba7185
afmt 2023-02-10 13:51:16 +01:00
14a92b3d89
typo 2023-02-09 18:28:16 +01:00
e4fd424d66
Merge branch 'possible_tc_sched_fixes' into develop 2023-02-09 18:25:44 +01:00
341a66c265
changelog 2023-02-09 18:22:00 +01:00
b9b076aa4c logic error 2023-02-09 18:18:25 +01:00
d93486a340 that time margin check is possible broken 2023-02-09 18:18:05 +01:00
820a7f059c
logic error 2023-02-09 18:13:58 +01:00
f4d188c36f
that time margin check is possible broken 2023-02-09 18:12:43 +01:00
1841f92944
important bugfix for thermal set 2023-02-09 17:17:42 +01:00
b279985859
refactor DHB: Bugfix for thermal module 2023-02-09 16:42:38 +01:00
6ce80ea6c5
Merge branch 'possible_tcpip_bridge_fixes' into develop 2023-02-08 21:27:26 +01:00
6f05d6b7b0
possiible leak fixes 2023-02-08 20:38:32 +01:00
7f907fb9d3 Merge remote-tracking branch 'origin/develop' into mueller/pus-15-tm-storage 2023-02-08 17:17:33 +01:00
84bbef0167
make it consistent 2023-02-08 09:27:14 +01:00
88b2b0e005
Merge branch 'mode_service_fixes' into develop 2023-02-08 09:26:38 +01:00
84dc7ac0ce
bump changelog 2023-02-08 01:31:32 +01:00
ec12ab5daa
mode service fixes 2023-02-08 01:20:28 +01:00
69c94645df
add back HAL section 2023-02-07 12:36:01 +01:00
37e850c5a7
use upstream changelog 2023-02-07 12:31:19 +01:00
a1567de9e8 Merge branch 'develop' into mueller/pus-15-tm-storage 2023-02-07 12:21:35 +01:00
2646707d3f Merge branch 'cmakelists_update' into develop 2023-02-07 12:18:49 +01:00
06e30684fe
Merge remote-tracking branch 'upstream/development' into develop 2023-02-07 12:14:31 +01:00
06dca7608a
time stamper empty ctor 2023-02-07 12:06:34 +01:00
6af5274b68 Merge remote-tracking branch 'origin/develop' into mueller/pus-15-tm-storage 2023-02-07 10:51:17 +01:00
38789e053b
Merge branch 'bugfix_dhb_set_datapool_entries_invalid' into develop 2023-02-03 16:05:29 +01:00
e11eabdbcf
bugfix in setNormalDataPoolEntriesInvalid
Do not forget to call read and write to actually update the
validity state
2023-02-03 15:58:26 +01:00
3250bbf269
changelog update 2023-02-02 18:34:24 +01:00
a78fe0a7f3 Merge pull request 'RM3100 Z-Value fix' (#123) from RM3100-fix into develop
Reviewed-on: eive/fsfw#123
Reviewed-by: Robin Müller <muellerr@irs.uni-stuttgart.de>
2023-02-02 18:33:13 +01:00
acfc1cbf21 bump changelog 2023-02-02 18:31:40 +01:00
d17ec02cf0 fixed Z value calculation 2023-02-02 18:26:08 +01:00
f2461cd7e9
helper method for commanding mode 2023-02-02 16:22:29 +01:00
01cc619e67
Merge branch 'bugfix_pus_packets_seq_flags' into develop 2023-02-01 20:52:08 +01:00
2339712373
set sequence flags for PUS TMTC to unsegmented 2023-02-01 20:46:48 +01:00
d9d253d3bb
small but important bugfix for health service 2023-02-01 19:58:27 +01:00
bd586f6564 Merge branch 'updates_fixes_pus_time_service' into develop 2023-02-01 18:42:18 +01:00
5f481739d8
Merge branch 'updates_fixes_pus_time_service' into develop 2023-02-01 18:39:51 +01:00
7ee83e4e5d
service 9 update
- fix time info event
- add time dump subservice
2023-02-01 18:10:07 +01:00
64787f85ca update changelog 2023-02-01 17:42:06 +01:00
1cacceddad
beatufil 2023-02-01 17:33:24 +01:00
5c35b8e3cd
proper announce all impl 2023-02-01 17:07:38 +01:00
7766b24a1d
re-order fields in TcpConfig 2023-01-30 14:24:28 +01:00
9a4ae550ab Merge branch 'develop' of https://egit.irs.uni-stuttgart.de/eive/fsfw into develop 2023-01-30 14:07:10 +01:00
c64b9b3e71
allow using SO_REUSEADDR and SO_REUSEPORT on TCP server 2023-01-30 14:05:39 +01:00
226818886f
improve srv20 error messages 2023-01-28 14:31:32 +01:00
da12495335
connect mode tree parent: make health helper optional 2023-01-27 15:08:24 +01:00
0cc3231ceb Merge remote-tracking branch 'origin/develop' into mueller/pus-15-tm-storage 2023-01-23 14:20:38 +01:00
049e3b431d
small tweak for printout 2023-01-23 11:31:00 +01:00
bd189518b6
small tweak, gain factory was always them same 2023-01-20 11:10:05 +01:00
accaf855ee Merge remote-tracking branch 'upstream/service_11_bugfixes' into develop 2023-01-13 11:19:17 +01:00
75fa7caf25
Merge remote-tracking branch 'upstream/development' into develop 2023-01-13 11:19:09 +01:00
041d1b8795 Merge remote-tracking branch 'origin/develop' into mueller/pus-15-tm-storage 2023-01-11 09:17:57 +01:00
5bb66c9723 remove duplicate printout 2023-01-10 11:55:54 +01:00
a486559313 Merge remote-tracking branch 'upstream/development' into fsfw_update 2022-12-22 13:46:17 +01:00
2aa4af6974
make function public 2022-12-14 13:50:57 +01:00
75fc7a056d Merge remote-tracking branch 'origin/develop' into mueller/pus-15-tm-storage 2022-12-12 09:02:04 +01:00
05cad893a2 introduce error counter to avoid spam 2022-12-06 10:05:23 +01:00
1b005d706a Merge remote-tracking branch 'origin/develop' into mueller/pus-15-tm-storage 2022-12-01 16:40:39 +01:00
5b0ea91222
statically assert MAX_SIZE > 0 2022-11-29 23:24:29 +01:00
e68f54b9bd Merge remote-tracking branch 'origin/develop' into mueller/pus-15-tm-storage 2022-11-28 11:37:15 +01:00
8eb869e073
run black 2022-11-28 11:21:36 +01:00
46a1c2bace
remove data wrapper 2022-11-28 08:35:10 +01:00
2643ff194c
Merge remote-tracking branch 'upstream/development' into develop 2022-11-28 08:34:04 +01:00
296bc56e2a Merge remote-tracking branch 'origin/develop' into mueller/pus-15-tm-storage 2022-11-24 15:16:34 +01:00
160ff799ac
small fix to allow teardown handling 2022-11-17 15:09:08 +01:00
c5f91926c9
remove includes 2022-11-15 10:54:47 +01:00
be4a87535d
remove data wrapper 2022-11-15 10:54:11 +01:00
99927b8e95
afmt 2022-11-15 10:53:38 +01:00
5e5eb82830
make warning switch protected 2022-11-15 10:53:14 +01:00
686dc97234
this is better / more correct 2022-11-15 10:52:47 +01:00
1f58ba1f9b
update changelog 2022-11-15 09:58:15 +01:00
002845108d Merge remote-tracking branch 'upstream/development' into develop_update 2022-11-14 15:05:47 +01:00
2b6a33e718
afmt 2022-11-11 14:13:46 +01:00
61fd5d1b62
impl function to generate ASCII timestamp sec accuracy 2022-11-11 14:12:42 +01:00
046dbe1deb
Merge branch 'develop' into mueller/pus-15-tm-storage 2022-11-11 11:38:32 +01:00
e03e7f5260
Merge branch 'mueller/refactor_serial_linux' into develop 2022-11-11 11:37:55 +01:00
0303c1a885
remove file 2022-11-11 11:31:22 +01:00
4d2802a470
Merge remote-tracking branch 'origin/develop' into mueller/pus-15-tm-storage 2022-11-11 11:29:29 +01:00
39946bff58
some renaming and tweaks for linux serial driver 2022-11-10 17:31:11 +01:00
2a203ae13d
this not crash 2022-11-10 16:15:28 +01:00
6ca1a5c796
fix unittests 2022-11-10 16:11:05 +01:00
194b3e100a
fix compiler error for fixed array list copy ctor 2022-11-10 15:53:18 +01:00
177c39dd53
helper interface implementations 2022-11-10 15:38:34 +01:00
530a261e14
dedicated header file for container retvals 2022-11-10 15:12:18 +01:00
31defac17c
bugfix in map packet extraction 2022-11-09 14:06:59 +01:00
ce387deee7
first improvements and fixes 2022-11-09 13:49:12 +01:00
72793abfd3
Merge remote-tracking branch 'upstream/development' into mueller/test_update 2022-11-09 13:42:52 +01:00
0e8f5ddd26
added missing const specifier 2022-11-08 11:07:56 +01:00
672fca5169
extend uart helper a bit 2022-11-04 11:08:23 +01:00
84b9d1ce21 Merge pull request 'dhb2normal' (#115) from eive/dhb2normal into develop
Reviewed-on: eive/fsfw#115
2022-11-03 15:32:26 +01:00
e5b5c7d253
higher default MQ depth for events, printout tweak 2022-11-03 10:33:52 +01:00
9a0cc64be3 Merge branch 'develop' into eive/dhb2normal 2022-11-03 10:12:19 +01:00
00f1c5bbe9
missing replacements 2022-11-03 10:12:05 +01:00
8a61af779d Merge remote-tracking branch 'origin/develop' into eive/dhb2normal 2022-11-03 10:10:47 +01:00
6efa482eb0
use uniform uart api 2022-11-03 10:10:36 +01:00
f0fa1bf477 Merge remote-tracking branch 'origin/develop' into eive/dhb2normal 2022-11-03 10:08:35 +01:00
91ebf98c28
add new ping with data TC 2022-11-02 19:35:22 +01:00
e1d4209fbe missing fifo pop command 2022-11-02 16:07:00 +01:00
e302c89f74 health helper dtor bugfix 2022-11-02 15:48:13 +01:00
a38279f813 Merge branch 'develop' into eive/dhb2normal 2022-11-02 10:47:25 +01:00
7600ed1ea7 Merge pull request 'Improve Subsystem DHB logic' (#112) from mueller/improve-ss-dhb-logic into develop
Reviewed-on: eive/fsfw#112
2022-11-02 10:32:25 +01:00
61ab770d9d Merge branch 'develop' into mueller/improve-ss-dhb-logic 2022-11-02 10:31:43 +01:00
033676ad3b
smaller fixes for DHB 2022-10-28 10:30:48 +02:00
e2eeccce50
Merge remote-tracking branch 'upstream/mohr/dhb2normal' into mohr/dhb2normal 2022-10-28 10:17:37 +02:00
f805667779
afmt 2022-10-28 10:16:59 +02:00
af06969905
Merge remote-tracking branch 'upstream/mohr/dhb2normal' into mohr/dhb2normal 2022-10-28 10:15:40 +02:00
2461209169
Merge remote-tracking branch 'upstream/development' into develop 2022-10-28 10:10:20 +02:00
852f27cec2 Merge remote-tracking branch 'origin/develop' into mueller/improve-ss-dhb-logic 2022-10-27 16:58:30 +02:00
226dc4d8b7
UIO mapper can handle symlinks now 2022-10-27 14:01:35 +02:00
fa01798ebb Merge remote-tracking branch 'origin/develop' into mueller/improve-ss-dhb-logic 2022-10-27 08:30:30 +02:00
1b7e94d718 this api works as well 2022-10-26 18:26:48 +02:00
60ff411721 improvements for HAL com IFs 2022-10-26 17:06:24 +02:00
bddc7a7ca6 minimal first version 2022-10-26 13:22:16 +02:00
819a2bfac4
add prototype for new ToAscii CCSDSTime function 2022-10-25 18:20:48 +02:00
1f05e6b297
fs retval 2022-10-25 11:30:44 +02:00
b0c5a49b50
iter not a member anymore, more bugfixes 2022-10-24 14:24:57 +02:00
096af44e39
needs some fixing 2022-10-24 10:56:01 +02:00
56e8e5a8b3
dont know if I am going to need this 2022-10-24 10:39:43 +02:00
11422a658c Merge remote-tracking branch 'origin/develop' into mueller/improve-ss-dhb-logic 2022-10-21 15:35:27 +02:00
754b71a35f Merge pull request 'Update CFDP components' (#113) from mueller/update-cfdp-components into develop
Reviewed-on: eive/fsfw#113
2022-10-21 15:27:40 +02:00
2de9e25ceb Merge remote-tracking branch 'upstream/mueller/new-cfdp-update-with-handlers' into mueller/update-cfdp-components 2022-10-21 11:21:26 +02:00
ec7566fb8c Merge remote-tracking branch 'origin/develop' into mueller/improve-ss-dhb-logic 2022-10-20 16:59:53 +02:00
73454c629c
oh god 2022-10-20 16:05:45 +02:00
0c5c2f6c4f
important bugfix for i2c device com IF 2022-10-20 14:24:03 +02:00
009700ce80
remove info printout 2022-10-17 17:29:10 +02:00
1e43296f2b
missing validity check 2022-10-17 17:24:46 +02:00
1aa062df7f
const specifier for AcceptsTelemetryIF 2022-10-17 16:27:41 +02:00
14a8924a83
size check bugfix 2022-10-17 14:01:21 +02:00
9f81926aec
some more basic error handling 2022-10-17 12:22:01 +02:00
79c38b45df
events for FSFW specific errors 2022-10-17 12:20:26 +02:00
e893e73f86
add first CFDP events 2022-10-17 12:19:31 +02:00
1d6ccfe5ab
Service 200: Add mode announcement support 2022-10-10 11:06:58 +02:00
221df7ece6
allow recursive mode announcements 2022-10-10 10:46:29 +02:00
7f180ac1fa
Merge remote-tracking branch 'origin/develop' into mueller/improve-ss-dhb-logic 2022-10-10 10:29:08 +02:00
692be9df8d DHB bugfix and addition 2022-10-06 16:57:47 +02:00
8195587604 Merge branch 'mueller/uart-helper-module' into mueller/simplify-dle-parser 2022-10-06 11:14:54 +02:00
40e7b2dc31
new uart helper module 2022-10-06 11:14:00 +02:00
1c53b60442
small additional tweak 2022-10-04 23:04:28 +02:00
d1630cdc4c
something is wrong 2022-10-04 21:17:35 +02:00
49747fc8a4
some bugfixes 2022-10-04 20:51:58 +02:00
cfc00d0260
try to do this in a simpler way 2022-10-04 18:38:20 +02:00
1eceef4645
move retvals 2022-09-30 15:05:32 +02:00
acab5f6bce
added missing health and mode helper init 2022-09-30 14:14:45 +02:00
10dd855244
expose child itself in interface 2022-09-30 13:30:07 +02:00
f824004897
need to fix all of these TODOs 2022-09-29 19:39:37 +02:00
7c5308429c
this seems to work 2022-09-29 19:21:24 +02:00
f78344b8fb Merge remote-tracking branch 'origin/develop' into mueller/improve-ss-dhb-logic 2022-09-29 17:46:54 +02:00
b9d0ff8fb7
DHB bug 2022-09-29 17:20:18 +02:00
77f7fa2ef1
typo 2022-09-29 16:48:23 +02:00
78314ad966
this makes a bit more sense 2022-09-29 16:47:23 +02:00
227535c461
formatting and smaller stuff 2022-09-29 16:46:55 +02:00
c47bed0760 small important bugfix for DLE parser 2022-09-28 17:04:11 +02:00
9927dbb2e4 Merge branch 'windows-tweaks' into develop 2022-09-28 10:06:08 +02:00
14a48fe41d
better comment 2022-09-28 09:56:20 +02:00
c932e51818 Merge branch 'windows-tweaks' into develop 2022-09-28 00:03:51 +02:00
2ca8d72e83
another small windows tweak 2022-09-28 00:03:12 +02:00
03e1a93250
last windows tweak 2022-09-27 23:57:58 +02:00
6d2f44a432
tweaks to make windows build again 2022-09-27 21:46:11 +02:00
808e3e0462
remove unused variable 2022-09-16 18:54:48 +02:00
79ab0c4aa5 Merge branch 'mueller/smaller-tweaks' into develop 2022-09-16 18:24:39 +02:00
c5b24f2516
fixes and tweaks 2022-09-16 18:08:20 +02:00
bdbe0cc9da pass message queue externally 2022-09-16 16:28:41 +02:00
e2c1158337
pass message queue externally 2022-09-16 16:27:57 +02:00
95aac7dc8d Merge pull request 'CFDP FSFW Integration' (#111) from cfdp-integration into develop
Reviewed-on: eive/fsfw#111
2022-09-16 11:11:20 +02:00
3d2fc28468
Merge remote-tracking branch 'upstream/mueller/new-cfdp-update-with-handlers' into cfdp-integration 2022-09-16 11:10:35 +02:00
1898b4f2db Merge remote-tracking branch 'upstream/development' into update-from-upstream 2022-09-16 11:06:05 +02:00
c38088c64b
adaptions for enum renaming 2022-09-15 18:44:00 +02:00
7eb63d6d79 Merge branch 'mueller/cfdp-update-without-handlers' into mueller/new-cfdp-update-with-handlers 2022-09-15 18:41:29 +02:00
1d54507517 Merge pull request 'merge upstream development' (#110) from mohr/merge-upstream into develop
Reviewed-on: eive/fsfw#110
Reviewed-by: Robin Müller <muellerr@irs.uni-stuttgart.de>
2022-09-15 18:34:50 +02:00
ef9ed95fd1 Merge branch 'develop' into mohr/merge-upstream 2022-09-15 18:34:37 +02:00
ed68268c0c
generic cfdp handler wrapper 2022-09-15 16:53:04 +02:00
c549914efb
include helpers 2022-09-15 16:50:06 +02:00
753d5ff39e
adaptions for enum renaming 2022-09-15 16:47:09 +02:00
36ca35da77 Merge branch 'mueller/cfdp-update-without-handlers' into mueller/new-cfdp-update-with-handlers 2022-09-15 16:46:25 +02:00
4fb7375492 Merge branch 'mueller/cfdp-update-without-handlers' into mueller/new-cfdp-update-with-handlers 2022-09-15 16:21:32 +02:00
47df9e8b5b Merge branch 'mueller/cfdp-update-without-handlers' into mueller/new-cfdp-update-with-handlers 2022-09-15 16:03:06 +02:00
7e0a5d5a9e printout tweak 2022-09-15 13:40:37 +02:00
ee1c6a3f04
better error printout 2022-09-15 13:37:10 +02:00
86aafe4422 Merge branch 'mueller/cfdp-update-without-handlers' into mueller/new-cfdp-update-with-handlers 2022-09-15 11:02:46 +02:00
dbaeed83af Merge branch 'mueller/cfdp-update-without-handlers' into mueller/new-cfdp-update-with-handlers 2022-09-14 19:48:25 +02:00
385a0ffd73
add CFDP handlers manually 2022-09-14 19:29:43 +02:00
bd594123a2 Merge remote-tracking branch 'upstream/development' into mohr/merge-upstream 2022-09-14 12:54:15 +02:00
cf8fe7ea72
more simplfications 2022-09-01 10:51:09 +02:00
496dac89e4
important bugfix for TCP TMTC server 2022-08-31 22:47:58 +02:00
cfca27542a
small fix which allows sending action reply immediately 2022-08-31 16:26:18 +02:00
2fa76d3663 Merge remote-tracking branch 'upstream/mueller/dhb-handle-device-tm-2' into develop 2022-08-31 00:02:52 +02:00
726f44cafe
Merge remote-tracking branch 'upstream/mueller/dhb-handle-device-tm-2' into develop 2022-08-30 23:53:16 +02:00
141dcb1f14
Merge remote-tracking branch 'upstream/mueller/data-wrapper' into develop 2022-08-30 16:05:25 +02:00
6ebd6a965b
Merge remote-tracking branch 'upstream/mueller/data-wrapper' into develop 2022-08-30 16:05:02 +02:00
20f0707813 remove newline 2022-08-30 16:04:45 +02:00
8d1777fa0c
additional tests 2022-08-30 16:02:50 +02:00
21ac86619e
now its getting interesting 2022-08-30 15:52:34 +02:00
eedf57624f
Merge remote-tracking branch 'upstream/mueller/dhb-handle-device-tm' into develop 2022-08-30 15:40:52 +02:00
ae40543e3a
this is annoying 2022-08-30 15:16:54 +02:00
efd2994dc5
dump compiler erorrs.. 2022-08-30 14:59:59 +02:00
3ebebbd493 Merge branch 'develop' into mueller/data-wrapper-update 2022-08-30 14:54:20 +02:00
a8c066dccc Merge remote-tracking branch 'upstream/mueller/refactor-local-pool-api' into develop 2022-08-30 14:54:03 +02:00
4d17f1c4bb
Merge remote-tracking branch 'upstream/mueller/refactor-tmtc-stack' into develop 2022-08-30 14:53:38 +02:00
d4ed528426
Merge remote-tracking branch 'upstream/mueller/data-wrapper' into mueller/data-wrapper-update 2022-08-30 14:52:09 +02:00
e10e71cee9
Merge branch 'mueller/data-wrapper' into mueller/dhb-handle-device-tm 2022-08-30 14:42:13 +02:00
d675a789a2
update changelog 2022-08-30 14:41:37 +02:00
6b8c83be29
update changelog 2022-08-30 14:40:02 +02:00
093052604a Merge branch 'mueller/data-wrapper' into mueller/dhb-handle-device-tm 2022-08-30 14:03:45 +02:00
192255df1c
additional test 2022-08-30 14:03:33 +02:00
bdd79d060d
basic data wrapper unittests 2022-08-30 14:02:58 +02:00
3a47062f2a
refactored dhb TM handler 2022-08-30 13:39:21 +02:00
9a590a3fcd
additional safety check 2022-08-29 12:01:44 +02:00
2a75440b32
allow device tm in raw format 2022-08-27 01:01:29 +02:00
f5866ddace
missing replacements 2022-08-24 17:25:45 +02:00
f91ad84bdc
Merge remote-tracking branch 'upstream/mueller/refactor-tmtc-stack' into mueller/refactor-tmtc-stack-retval-merged 2022-08-24 17:13:41 +02:00
7881f5bab8
important bugfix for verif reporter 2022-08-18 11:19:42 +02:00
34c714eb17 Merge branch 'mueller/tmtc-stack-refactoring' into develop 2022-08-16 17:49:06 +02:00
7205885357
added additional API for HK subscription params 2022-08-16 17:47:56 +02:00
42c5881c50 Merge pull request 'TMTC Stack Refactoring' (#106) from mueller/tmtc-stack-refactoring into develop
Reviewed-on: eive/fsfw#106
2022-08-16 17:30:16 +02:00
cdd0ca70ed Merge branch 'develop' into mueller/tmtc-stack-refactoring 2022-08-16 17:29:48 +02:00
e3648b6e30 Merge remote-tracking branch 'upstream/mueller/refactor-tmtc-stack' into mueller/tmtc-stack-refactoring 2022-08-16 17:25:22 +02:00
d815f422c3
improve verif reporter API 2022-08-16 17:09:22 +02:00
d975958120 Merge remote-tracking branch 'upstream/development' into develop 2022-08-16 11:26:59 +02:00
c57e95c698 Merge remote-tracking branch 'upstream/mueller/refactor-tmtc-stack' into mueller/tmtc-stack-refactoring 2022-08-15 19:18:46 +02:00
4d82d0e4c1
update source sequence counter code 2022-08-15 17:24:48 +02:00
007f958a0b
fsfw fixes for merge 2022-08-15 11:38:52 +02:00
d022ce82c5
Merge remote-tracking branch 'upstream/mueller/refactor-tmtc-stack' into mueller/tmtc-stack-refactoring 2022-08-15 11:30:09 +02:00
b28091e05b Merge remote-tracking branch 'upstream/mueller/expand-serialize-if' into develop 2022-08-15 11:25:07 +02:00
f4c4f9946c
printout preproc block 2022-08-15 11:18:53 +02:00
7f89022f5b
Merge branch 'mueller/group-mgm-data' into develop 2022-08-15 10:50:10 +02:00
fdcfd89ed2
add some Linux HAL options 2022-08-12 12:55:31 +02:00
03fa77e2b3
get current uptime correctly 2022-08-12 12:29:10 +02:00
8970a7379a
Merge remote-tracking branch 'upstream/development' into mueller/update-from-upstream 2022-08-12 12:21:50 +02:00
904ae2cc0e Merge remote-tracking branch 'origin/irini' into develop 2022-07-08 16:34:24 +02:00
4a2012ac30 Merge branch 'irini' into develop 2022-07-08 16:31:57 +02:00
0b17a2e74e Merge branch 'mueller/tc-packet-pus-improvement' into develop 2022-07-05 17:55:31 +02:00
ec1d64e061 Merge remote-tracking branch 'upstream/development' into mueller/tc-packet-pus-improvement 2022-07-05 17:55:23 +02:00
a16b77daf0
re-ordered absstract methods a bit 2022-07-05 17:04:24 +02:00
830b907910 Merge remote-tracking branch 'upstream/development' into develop 2022-07-05 15:12:30 +02:00
b762f97bfb Merge remote-tracking branch 'upstream/development' into develop 2022-07-05 15:12:19 +02:00
6a62cf7f1e Merge pull request 'Update FSFW from upstream' (#102) from mueller/update-from-upstream into develop
Reviewed-on: eive/fsfw#102
Reviewed-by: Jakob Meier <meierj@irs.uni-stuttgart.de>
2022-07-04 13:04:00 +02:00
c5eb09314f
delete run configs 2022-07-04 11:04:37 +02:00
682abd1b5b
new clion folder in misc for .run configs 2022-07-04 10:55:09 +02:00
a4247cd723
Merge remote-tracking branch 'upstream/development' into mueller/update-from-upstream 2022-07-04 10:53:52 +02:00
39881e7671 Merge pull request 'some form updates' (#100) from mueller/afmt-gen-tweaks into develop
Reviewed-on: eive/fsfw#100
2022-06-21 10:37:03 +02:00
5abbf42e9f
some form updates 2022-06-21 00:49:58 +02:00
Irini Kosmidou
1910a7838c compile DleParser 2022-06-20 11:04:06 +02:00
Irini Kosmidou
ba3a99466a Merge remote-tracking branch 'origin/develop' into irini 2022-06-20 11:03:12 +02:00
438efe074e Merge pull request 'LocalDataPoolManager Warning Text' (#99) from meier/eive-debug-info into develop
Reviewed-on: eive/fsfw#99
Reviewed-by: Robin Müller <muellerr@irs.uni-stuttgart.de>
2022-06-20 09:35:31 +02:00
1759700b6a Merge branch 'develop' into meier/eive-debug-info 2022-06-20 09:35:14 +02:00
c7618294ac Merge pull request 'HK Generation for L3GD20, LIS3MDL, RM3100' (#97) from meier/device-hk into develop
Reviewed-on: eive/fsfw#97
Reviewed-by: Robin Müller <muellerr@irs.uni-stuttgart.de>
2022-06-20 09:34:16 +02:00
af890c6218 corrected warning text 2022-06-16 07:55:57 +02:00
7f3e5e42bb Merge branch 'develop' into meier/device-hk 2022-06-16 07:44:58 +02:00
5bd3abed8b Merge branch 'development' into mueller/tc-packet-pus-improvement 2022-06-13 16:45:45 +02:00
eb46f0c473
pus version in config is constexpr now 2022-06-13 16:45:09 +02:00
15d69e64f3
renamed new class, small tweak 2022-06-13 16:20:37 +02:00
d74bcbb1f8 Merge branch 'mueller/tc-packet-pus-improvement' of https://egit.irs.uni-stuttgart.de/KSat/fsfw into mueller/tc-packet-pus-improvement 2022-06-13 16:14:37 +02:00
c00cb1680d
removed unneeded function 2022-06-13 16:14:30 +02:00
7109422e2c Merge branch 'development' into mueller/tc-packet-pus-improvement 2022-06-13 16:13:42 +02:00
efd12544df
this should get the job done 2022-06-13 16:13:15 +02:00
cda81fc841 enable hk 2022-06-03 18:05:38 +02:00
b9fbb4fd4c Merge branch 'development' into mueller/tc-packet-pus-improvement 2022-05-27 15:15:39 +02:00
5a69c1f8b9 Merge pull request 'DHB Mode Off disable pending commands' (#95) from meier/dhb-disable-pending-commands into develop
Reviewed-on: eive/fsfw#95
Reviewed-by: Robin Müller <muellerr@irs.uni-stuttgart.de>
2022-05-27 14:40:36 +02:00
1d1d91f591 Merge branch 'develop' into meier/dhb-disable-pending-commands 2022-05-27 14:40:18 +02:00
043b8b5b3f Merge pull request 'FixedTimeSlotTaskBase Bugfix' (#96) from meier/FixedTimeSlotTaskBase-BugFix into develop
Reviewed-on: eive/fsfw#96
Reviewed-by: Robin Müller <muellerr@irs.uni-stuttgart.de>
2022-05-27 14:38:04 +02:00
Jakob Meier
95a64e1da3 wrong initialization order 2022-05-27 13:04:21 +02:00
Jakob Meier
ab68817e9a removed debugging printout 2022-05-26 02:06:05 +02:00
Jakob Meier
36652e6fce Merge branch 'develop' into meier/dhb-disable-pending-commands 2022-05-26 02:04:33 +02:00
Jakob Meier
3749f31ab4 disable pending commands and replies in MODE_OFF transition 2022-05-26 02:03:39 +02:00
ebbe08639c Merge pull request 'TaskIF refactoring continued' (#91) from mueller/task-if-refactoring-eive into develop
Reviewed-on: eive/fsfw#91
Reviewed-by: Jakob.Meier <meierj@irs.uni-stuttgart.de>
2022-05-25 16:11:22 +02:00
d286fc1855 Merge pull request 'service 3 and local HK man improvements' (#92) from mueller/hk-improvements into develop
Reviewed-on: eive/fsfw#92
Reviewed-by: Jakob.Meier <meierj@irs.uni-stuttgart.de>
2022-05-25 16:10:32 +02:00
cf35cca923
Merge remote-tracking branch 'origin/develop' into mueller/task-if-refactoring-eive 2022-05-25 15:41:07 +02:00
2058817ba5 Merge branch 'mueller/task-if-refactoring-eive' of https://egit.irs.uni-stuttgart.de/eive/fsfw into mueller/task-if-refactoring-eive 2022-05-25 15:38:20 +02:00
c328891030 Merge remote-tracking branch 'origin/develop' into mueller/task-if-refactoring-eive 2022-05-25 15:38:14 +02:00
76a459a02c Merge pull request 'use better type for stored limit' (#93) from mueller/tmtc-bridge-tweaks into develop
Reviewed-on: eive/fsfw#93
Reviewed-by: Jakob.Meier <meierj@irs.uni-stuttgart.de>
2022-05-25 15:24:57 +02:00
fbec1b3dc9 Merge pull request 'Update from upstream' (#94) from mueller/update-from-upstream into develop
Reviewed-on: eive/fsfw#94
Reviewed-by: Jakob.Meier <meierj@irs.uni-stuttgart.de>
2022-05-25 15:24:18 +02:00
c4fa7281ae
Merge remote-tracking branch 'upstream/development' into mueller/update-from-upstream 2022-05-25 14:44:21 +02:00
ac62443f31
use better type for stored limit 2022-05-25 14:30:58 +02:00
8cfe848dfe
service 3 and local HK man improvements 2022-05-25 14:30:00 +02:00
af7c6c57a3 Merge branch 'develop' into mueller/task-if-refactoring-eive 2022-05-25 10:30:23 +02:00
c835525196
added cast for PUS11 2022-05-25 09:56:32 +02:00
24069dfd78
removed [[maybe_unused]] 2022-05-24 16:22:27 +02:00
40cc557978
Merge remote-tracking branch 'upstream/mueller/task-if-refactoring' into mueller/task-if-refactoring-eive 2022-05-24 15:42:08 +02:00
4b128d2435 Merge pull request 'TaskIF refactor SPI refactor' (#89) from mueller/task-if-refactor-spi-refactor into develop
Reviewed-on: eive/fsfw#89
2022-05-23 16:22:40 +02:00
f35b0ffbbd
Merge remote-tracking branch 'origin/develop' into mueller/task-if-refactor-spi-refactor 2022-05-23 16:10:49 +02:00
9368ae81e5 Merge branch 'development' into mueller/tc-packet-pus-improvement 2022-05-23 15:56:26 +02:00
b8b7756a3e
fix host OSAL 2022-05-22 14:32:48 +02:00
4cc108f3a1
Merge branch 'develop' of https://egit.irs.uni-stuttgart.de/eive/fsfw into develop 2022-05-20 20:53:48 +02:00
c0292f072e
warning printout correction 2022-05-20 20:52:36 +02:00
336ad9b7be Merge pull request 'PUS TC11 bugfix and upstream updates' (#88) from mueller/tc-11-tweaks-eive into develop
Reviewed-on: eive/fsfw#88
2022-05-20 17:35:07 +02:00
942bfafaa3
Merge remote-tracking branch 'upstream/mueller/tc-11-tweaks' into mueller/tc-11-tweaks-eive 2022-05-20 15:39:40 +02:00
3a16290707
refactored and tested hosted and linux task IF 2022-05-19 00:44:34 +02:00
08f1ebf9fc
continued refactoring 2022-05-18 23:45:38 +02:00
64e7d4bb5e
continued refactoring 2022-05-18 18:15:31 +02:00
1886da0d3f
refactoring host osal 2022-05-18 15:42:18 +02:00
b47eb0a7ff
minor bugfix 2022-05-18 14:40:54 +02:00
b1e30ae9ff
minor bugfix 2022-05-18 14:39:37 +02:00
86ca4f246b new base class for periodic tasks 2022-05-18 14:34:08 +02:00
e87b5a0207
new base class for periodic tasks 2022-05-18 14:32:35 +02:00
d504589c3c Merge remote-tracking branch 'upstream/development' into mueller/task-if-refactoring 2022-05-18 13:20:39 +02:00
7b3de87364
removed some changes which belong in separate PR 2022-05-18 13:19:43 +02:00
e758f0be2e Merge pull request 'TaskIF refactoring and SPI refactoring' (#86) from mueller/task-if-refactor-spi-refactor into develop
Reviewed-on: eive/fsfw#86
2022-05-17 20:25:54 +02:00
18b342e94b vector as core container is ok 2022-05-17 18:12:37 +02:00
f9c42d3583
vector as core container is ok 2022-05-17 18:12:05 +02:00
d267a3651b Merge remote-tracking branch 'origin/develop' into mueller/task-if-refactor-spi-refactor 2022-05-17 17:51:42 +02:00
e8023886f6
made auto-formatter even more usable 2022-05-17 13:31:56 +02:00
14a1b4a7ac
made auto-formatter even more re-usable 2022-05-17 13:31:33 +02:00
e49de9422a Merge branch 'mueller/tcp-server-cache-client-addr' into develop 2022-05-17 13:20:55 +02:00
618f76ae78
improved TcPacketPus API 2022-05-17 10:14:34 +02:00
ee2f8d6956 Merge pull request 'Update FSFW from Upstream' (#27) from mueller/update-from-upstream into develop
Reviewed-on: KSat/fsfw#27
2022-05-17 10:06:58 +02:00
0ea044c203 Merge pull request 'Update from upstream' (#85) from mueller/update-from-upstream into develop
Reviewed-on: eive/fsfw#85
2022-05-16 22:08:28 +02:00
4b323053ec
Merge remote-tracking branch 'upstream/development' into mueller/update-from-upstream 2022-05-16 15:27:58 +02:00
55ed7ab93e
important fix 2022-05-14 16:58:28 +02:00
bcd19045cc
refactored SPI mutex handling 2022-05-14 11:33:43 +02:00
dba08fed7a
refactor task IF 2022-05-14 09:40:31 +02:00
7df1922633
refactor task IF 2022-05-14 09:38:59 +02:00
4841d5d92d
doc update 2022-05-13 17:24:55 +02:00
ac78a79ca2 Merge pull request 'Command Executor Improvements' (#83) from mueller/cmd-executer-improvements into develop
Reviewed-on: eive/fsfw#83
2022-05-13 14:57:18 +02:00
bf7388c059 Merge pull request 'HealthIF extensions and upstream updates' (#82) from mueller/health-if-extension-eive into develop
Reviewed-on: eive/fsfw#82
2022-05-13 14:56:50 +02:00
c2de911efa Merge branch 'develop' into mueller/cmd-executer-improvements 2022-05-13 11:22:53 +02:00
fc2b709148
resolve merge conflict 2022-05-12 20:48:50 +02:00
02473a0cd7
Merge remote-tracking branch 'origin/develop' into mueller/health-if-extension-eive 2022-05-12 20:11:45 +02:00
ab45aa1296
HasHealthIF additions 2022-05-12 20:06:10 +02:00
c0ff84bb9d Merge pull request 'SPI refactoring' (#80) from mueller/spi-cache-spi-dev-in-com-if into develop
Reviewed-on: eive/fsfw#80
2022-05-11 16:28:08 +02:00
d1ff32bf96
reset read vec values, add getter function 2022-05-11 16:12:24 +02:00
dafcaa6007 Merge remote-tracking branch 'origin/develop' into mueller/spi-cache-spi-dev-in-com-if 2022-05-11 15:44:45 +02:00
5eb52133ac Merge pull request 'sequence count init value' (#81) from meier/sequenceCount into develop
Reviewed-on: eive/fsfw#81
2022-05-11 15:43:49 +02:00
025e7647d3 Merge branch 'develop' into meier/sequenceCount 2022-05-11 15:43:35 +02:00
0a97077a0e
hotfix 2022-05-11 15:42:52 +02:00
Jakob Meier
bc994595da sequence count init value 2022-05-11 14:31:49 +02:00
ab2d7ca98f
update changelog and docs 2022-05-11 11:29:28 +02:00
56e4fca06f
Some improvements
- Rename mutex to csMutex to better represent its purpose
- Move the empty transfer to update the line polarity to separate function
2022-05-11 11:24:06 +02:00
e06c457743
Cache SPI device name in ComIF
- Architecturally, this makes a lot more sense because
  each ComIF should be responsible for one SPI bus
2022-05-11 11:11:39 +02:00
5941c21adf
Merge remote-tracking branch 'origin/develop' into mueller/spi-speed-mode-getter 2022-05-11 10:58:13 +02:00
0e880de0d0
update changelog 2022-05-11 10:54:39 +02:00
29c3a43760
getter functions for speed and mode 2022-05-11 10:54:13 +02:00
d72b212fa6
cmakelists.txt hotfix 2022-05-06 10:36:01 +02:00
43f0841d0a Merge pull request 'Fixed Seq Task use warning' (#78) from mueller/fixed-seq-task-use-warning into eive/develop
Reviewed-on: eive/fsfw#78
2022-05-05 13:10:07 +02:00
9e5fb64d0e Merge branch 'eive/develop' into mueller/fixed-seq-task-use-warning 2022-05-05 12:31:12 +02:00
71f704c980
remove the dot 2022-05-05 12:29:46 +02:00
a72cc487df Merge pull request 'DHB Reply Timeout' (#74) from meier/develop into eive/develop
Reviewed-on: eive/fsfw#74
2022-05-05 12:28:48 +02:00
de2d4da161 Merge branch 'eive/develop' into meier/develop 2022-05-05 12:28:34 +02:00
Jakob Meier
19bd26d998 Merge branch 'meier/develop' of https://egit.irs.uni-stuttgart.de/eive/fsfw into meier/develop 2022-05-05 09:15:23 +02:00
f59b05c86c
use warning instead of error 2022-05-05 02:00:41 +02:00
80cb0e682f Merge pull request 'Update GPIO API' (#76) from mueller/update-gpio-api into eive/develop
Reviewed-on: eive/fsfw#76
2022-05-04 14:03:28 +02:00
8ee26f81f9 dedicated returnvalue for line get failure 2022-05-04 10:36:32 +02:00
3556eca8e8 error check on line getter 2022-05-04 10:33:55 +02:00
a9041b84a3 update read gpio API 2022-05-04 10:27:20 +02:00
83d9dbc052 Merge pull request 'improved i2c error printout' (#75) from mueller/i2c-error-handling-improvement into eive/develop
Reviewed-on: eive/fsfw#75
2022-05-03 16:50:48 +02:00
2220120d54
improved i2c error printout 2022-05-03 16:43:15 +02:00
15eb22f9ee Merge remote-tracking branch 'origin/eive/develop' into meier/develop 2022-05-03 13:03:44 +02:00
7f6c8b8b12
Merge remote-tracking branch 'upstream/development' into eive/develop 2022-05-02 16:15:27 +02:00
Jakob Meier
789668ae50 Merge branch 'eive/develop' into meier/develop 2022-05-02 14:45:23 +02:00
7760b3063e Merge pull request 'New Subsystem adder functions' (#73) from mueller/new-ss-adder-functions-eive into eive/develop
Reviewed-on: eive/fsfw#73
2022-04-30 17:00:34 +02:00
Jakob Meier
d04f88bee0 Merge branch 'eive/develop' into mueller/new-ss-adder-functions-eive 2022-04-30 16:59:48 +02:00
e867d09111 Merge pull request 'Update from upstream' (#72) from mueller/update-from-upstream into eive/develop
Reviewed-on: eive/fsfw#72
2022-04-30 16:55:35 +02:00
Jakob Meier
43aad11859 space packet bugfix 2022-04-29 07:43:52 +02:00
3225a8e350
added option to change initial submode 2022-04-28 16:48:14 +02:00
1c4ea6dd0d Merge branch 'eive/develop' into mueller/new-ss-adder-functions-eive 2022-04-28 14:34:20 +02:00
e2eb4bfea4 Merge remote-tracking branch 'upstream/development' into mueller/update-from-upstream 2022-04-28 14:30:08 +02:00
Jakob Meier
41682aab3f Merge branch 'eive/develop' into meier/develop 2022-04-28 11:45:27 +02:00
d61fe7db93 Merge pull request 'Update FSFW' (#70) from mueller/update-fsfw into eive/develop
Reviewed-on: eive/fsfw#70
2022-04-27 07:48:56 +02:00
c1be1fe232
update CMakeLists.txt etl handling 2022-04-26 20:06:26 +02:00
ec2e274f22
find_package call for Catch2 quiet 2022-04-26 16:31:45 +02:00
c5a7b98a7d
name correction 2022-04-26 16:24:14 +02:00
6a8da303fb
exporting etl target 2022-04-26 14:06:30 +02:00
3d047f9629
trying to export ETL lib 2022-04-26 11:15:24 +02:00
1739edd9b0
warning fix for modern compilers 2022-04-26 10:32:37 +02:00
466a3639a5
Merge remote-tracking branch 'upstream/development' into mueller/update-fsfw 2022-04-26 10:02:43 +02:00
Jakob Meier
900ef5b912 option to use coutdwon object to time out replies 2022-04-26 09:07:03 +02:00
280b641cbc Merge pull request 'mueller/extend-version-class-fork' (#69) from mueller/extend-version-class-fork into eive/develop
Reviewed-on: eive/fsfw#69
2022-04-22 20:06:49 +02:00
24ef96d1b8 Merge branch 'eive/develop' into mueller/extend-version-class-fork 2022-04-22 16:04:55 +02:00
befaca78c6 Merge pull request 'space packet default length' (#66) from meier/develop into eive/develop
Reviewed-on: eive/fsfw#66
2022-04-21 14:30:34 +02:00
af4f002a25 Merge branch 'eive/develop' into meier/develop 2022-04-21 14:30:11 +02:00
Jakob Meier
9f7b9be800 space packet default length 0 2022-04-21 14:24:20 +02:00
2c0f3b52e9 Merge pull request 'Space Packet Default Length' (#65) from meier/develop into eive/develop
Reviewed-on: eive/fsfw#65
2022-04-21 14:11:09 +02:00
aa1ea33647 Merge pull request 'LIS3 handler nullptr check' (#64) from mueller/lis3-handler-nullptr-check into eive/develop
Reviewed-on: eive/fsfw#64
2022-04-21 13:55:06 +02:00
9798b6b4ab Merge pull request 'Merge upstream and apply auto-formatter' (#63) from merge-upstream into eive/develop
Reviewed-on: eive/fsfw#63
2022-04-21 13:54:20 +02:00
f0d7eaf35a Merge branch 'merge-upstream' into mueller/lis3-handler-nullptr-check 2022-04-21 10:38:43 +02:00
b128ef9da9
Merge remote-tracking branch 'upstream/development' into merge-upstream 2022-04-21 10:37:01 +02:00
085213c60f
add nullptr check 2022-04-21 10:30:46 +02:00
Jakob Meier
613dbe9592 default argument 2022-04-21 09:33:06 +02:00
e949368b06 Merge pull request 'uart cookie API change' (#62) from mueller/uart-com-if-tweaks into eive/develop
Reviewed-on: eive/fsfw#62
2022-04-13 15:04:03 +02:00
4d49cb6a3c Merge pull request 'added DLE parser' (#61) from mueller/dle-parser into eive/develop
Reviewed-on: eive/fsfw#61
2022-04-13 15:03:27 +02:00
e0c9bf5871 Merge branch 'mueller/dle-parser' into irini 2022-04-13 15:00:39 +02:00
935a8e13a5
uart cookie API change 2022-04-13 14:57:43 +02:00
5ff88129b8
added DLE parser 2022-04-13 14:45:36 +02:00
ce17be63f4 Merge pull request 'Pool Entry Update V2' (#60) from mueller/pool-entry-update-v2 into eive/develop
Reviewed-on: eive/fsfw#60
2022-04-12 19:28:01 +02:00
2734d9d758 Merge pull request 'fix compiler warnings' (#59) from mueller/compiler-warning-fixes-upstream into eive/develop
Reviewed-on: eive/fsfw#59
2022-04-12 19:27:37 +02:00
c45328b34d Merge branch 'eive/develop' into mueller/compiler-warning-fixes-upstream 2022-04-11 16:03:52 +02:00
478b305fbe fix compiler warnings 2022-04-11 16:02:20 +02:00
28e93696df Merge pull request 'IPC Pass Arbitrary Args to MQ IF' (#58) from mueller/ipc-pass-arbitrary-args-to-mq-eive into eive/develop
Reviewed-on: eive/fsfw#58
2022-04-11 14:55:54 +02:00
942d1e5e4b
Merge remote-tracking branch 'origin/eive/develop' into mueller/ipc-pass-arbitrary-args-to-mq-eive 2022-04-11 14:40:43 +02:00
6ce09e968d Merge pull request 'Update from FSFW upstream' (#56) from mueller/update-from-upstream into eive/develop
Reviewed-on: eive/fsfw#56
2022-04-11 09:03:08 +02:00
290db6ccad
Merge remote-tracking branch 'upstream/development' into mueller/update-from-upstream 2022-04-11 08:51:55 +02:00
94ed582297 Merge branch 'eive/develop' of https://egit.irs.uni-stuttgart.de/eive/fsfw into eive/develop 2022-04-07 19:47:49 +02:00
47ced1efac
pool entry takes const T* now 2022-04-07 19:47:37 +02:00
85a6e4b129 Merge pull request 'improve clock error handler' (#55) from mueller/clock-update into eive/develop
Reviewed-on: eive/fsfw#55
2022-04-07 19:29:49 +02:00
f94bc02b6c Merge branch 'eive/develop' into mueller/clock-update 2022-04-07 17:36:04 +02:00
5bda877d97
improve clock error handler 2022-04-07 17:23:06 +02:00
51e7f1c2f2 Merge pull request 'FSFW Update' (#54) from mueller/clock-update into eive/develop
Reviewed-on: eive/fsfw#54
2022-04-07 11:33:06 +02:00
a11d7455df Merge branch 'eive/develop' into mueller/master 2022-04-07 11:04:47 +02:00
4dc903fe20 Merge pull request 'Pool Entry Update' (#53) from mueller/pool-entry-update into eive/develop
Reviewed-on: eive/fsfw#53
2022-04-07 11:04:29 +02:00
3325cc18fc Merge branch 'eive/develop' into mueller/pool-entry-update 2022-04-07 11:03:56 +02:00
43917d98c0 Merge branch 'mueller/master' of https://egit.irs.uni-stuttgart.de/eive/fsfw into mueller/master 2022-04-07 11:01:49 +02:00
e3ffcae3e0
emit warning in linux clock 2022-04-07 11:01:39 +02:00
0677de39aa
make reporting setter public 2022-04-07 00:15:42 +02:00
aded4fae1e
printout improvement 2022-04-04 20:34:31 +02:00
7df51f7202 Merge pull request 'add power switcher component' (#52) from mueller/power-switcher-component into eive/develop
Reviewed-on: eive/fsfw#52
2022-04-04 15:51:18 +02:00
7530c44849 Merge branch 'eive/develop' into mueller/pool-entry-update 2022-04-04 15:46:10 +02:00
e4c6a69f77
this should also zero-init the pool entries 2022-04-04 15:44:03 +02:00
761a0c9bac
new pool ctor which only takes len 2022-04-04 15:39:02 +02:00
518666f822
add power switcher component 2022-04-01 17:01:56 +02:00
318cd8e244 Merge pull request 'Update FSFW' (#51) from mueller/master into eive/develop
Reviewed-on: eive/fsfw#51
2022-04-01 14:51:31 +02:00
1bc7a91869
apply auto-formatter 2022-04-01 14:08:29 +02:00
8e26e287c3 Merge remote-tracking branch 'origin/eive/develop' into mueller/master 2022-04-01 14:07:26 +02:00
ce2f7c4fdf Merge pull request 'DHB and CommandActionHelper changes' (#50) from meier/develop into eive/develop
Reviewed-on: eive/fsfw#50
2022-04-01 14:07:05 +02:00
b3d2d440d7 Merge remote-tracking branch 'origin/eive/develop' into mueller/master 2022-03-31 16:13:47 +02:00
Jakob Meier
fbf9626fde Merge branch 'eive/develop' into meier/dhbAlternativeReply 2022-03-31 15:04:55 +02:00
29cf8c9009 fix in getReplyLength 2022-03-31 11:42:39 +02:00
61d0815de8 Merge pull request 'Refactor Power Module' (#49) from mueller/refactor-power-switch-if-etc-eive into eive/develop
Reviewed-on: eive/fsfw#49
2022-03-31 09:01:24 +02:00
127fbeb980 Merge branch 'mueller/refactor-power-switch-if-etc' into mueller/refactor-power-switch-if-etc-eive 2022-03-30 17:41:55 +02:00
c2581ff4f5 Merge remote-tracking branch 'origin/eive/develop' into mueller/master 2022-03-30 13:12:11 +02:00
7b6f68c509
Merge remote-tracking branch 'origin/eive/develop' into mueller/refactor-power-switch-if-etc-eive 2022-03-30 12:14:57 +02:00
Jakob Meier
532607bf8f extended command info 2022-03-30 09:21:03 +02:00
Jakob Meier
a230dc4313 command action default arguments 2022-03-30 09:20:46 +02:00
3ea9f999b7
apply auto-formatter 2022-03-28 12:59:51 +02:00
79f3c7324a
tweaks for dummy power switcher 2022-03-28 12:59:32 +02:00
60972228ef
reworked power switch interface 2022-03-28 12:47:09 +02:00
6ea1eabb2d
small order change in DHB 2022-03-28 12:21:25 +02:00
283a37dccc Merge pull request 'meier/gpioClass' (#47) from meier/gpioClass into eive/develop
Reviewed-on: eive/fsfw#47
2022-03-28 10:22:32 +02:00
acf0cdfba3 Merge branch 'eive/develop' into meier/gpioClass 2022-03-28 10:22:11 +02:00
a01002aa5d Merge pull request 'meier/seqCount' (#46) from meier/seqCount into eive/develop
Reviewed-on: eive/fsfw#46
2022-03-28 10:21:48 +02:00
Jakob Meier
b52f19254b class to abstract gpio handling 2022-03-28 09:12:29 +02:00
79615e47e4 Merge branch 'eive/develop' into meier/seqCount 2022-03-25 15:48:42 +01:00
e6130263ef Merge pull request 'Update FSFW' (#45) from mueller/master into eive/develop
Reviewed-on: eive/fsfw#45
2022-03-25 14:56:19 +01:00
6895dbcc81 Merge remote-tracking branch 'origin/eive/develop' into mueller/master 2022-03-25 14:39:22 +01:00
4b5e3e70f7
add option to directly check switch state 2022-03-22 20:35:04 +01:00
bbe21e7e89
doc additions 2022-03-22 16:14:23 +01:00
2823420c46
more docs 2022-03-22 16:10:20 +01:00
6dd6f28db0
added active function 2022-03-22 15:55:18 +01:00
d791fc87b7
some improvements for PowerSwitcher 2022-03-22 15:49:04 +01:00
16f2fa9327
Merge remote-tracking branch 'upstream/development' into mueller/master 2022-03-21 10:12:06 +01:00
927041209b
added override specifiers 2022-03-21 09:12:56 +01:00
Jakob Meier
bac8b40880 Merge branch 'eive/develop' into meier/seqCount 2022-03-17 20:02:29 +01:00
Jakob Meier
caf78835b2 added -- operator 2022-03-17 20:00:17 +01:00
b6ed45a85c
small form fix 2022-03-17 19:59:16 +01:00
ddc1cdb1f5
additional docs 2022-03-17 19:22:24 +01:00
543daaa95a
various tweaks and improvements 2022-03-17 19:19:02 +01:00
38c87fdeb2
Merge remote-tracking branch 'upstream/development' into eive/develop 2022-03-17 09:47:20 +01:00
5ca5fe4040
Merge remote-tracking branch 'upstream/development' into eive/develop 2022-03-14 17:50:27 +01:00
Jakob Meier
1b7e0371c3 fixed merge conflict 2022-03-14 15:25:17 +01:00
Jakob Meier
d4ade5e885 sequence count operator overloading 2022-03-14 15:01:17 +01:00
fec5f83f4f
minor event changes 2022-03-11 14:25:01 +01:00
17262a1da9
Merge branch 'mueller/version-getter-upstream' into mueller/master 2022-03-10 09:59:18 +01:00
b5d6b9745f
undef major and minor 2022-03-10 09:56:23 +01:00
60639f56dc Merge branch 'mueller/version-getter' into mueller/master 2022-03-10 09:47:32 +01:00
3aa0bbde68
Merge branch 'mueller/version-getter-upstream' into mueller/version-getter 2022-03-10 09:47:10 +01:00
97bc71a3ff
added tests 2022-03-10 09:34:29 +01:00
06577ed78a Merge branch 'mueller/version-getter' into mueller/master 2022-03-09 19:11:57 +01:00
b27f3b84aa
getter not required anymore 2022-03-09 19:10:05 +01:00
9509847b84 Merge branch 'mueller/version-getter' into mueller/master 2022-03-09 19:05:30 +01:00
45b51f9ac8
improved version.h 2022-03-09 19:05:07 +01:00
d5ff6da40b Merge pull request 'function to get fsfw version' (#43) from mueller/version-getter into eive/develop
Reviewed-on: eive/fsfw#43
2022-03-08 12:04:13 +01:00
e498136273 Merge pull request 'call setTimeout' (#44) from mueller/countdown-improvement into eive/develop
Reviewed-on: eive/fsfw#44
2022-03-08 12:03:13 +01:00
47d158156b
call setTimeout 2022-03-08 11:52:33 +01:00
d63c01b96f
set timeout in countdown ctor 2022-03-08 11:50:47 +01:00
3b497dbb8d Merge branch 'mueller/version-getter' into mueller/master 2022-03-08 10:16:56 +01:00
bf733162eb Merge remote-tracking branch 'origin/eive/develop' into mueller/master 2022-03-08 10:15:54 +01:00
73f0b9c0dc Merge pull request 'define FSFW_DISABLE_PRINTOUT in any case' (#42) from mueller/define-fsfw-disabled-printout into eive/develop
Reviewed-on: eive/fsfw#42
2022-03-08 10:11:45 +01:00
b5e55f64b0 Merge pull request 'Another HasModesIF improvement' (#41) from mueller/master into eive/develop
Reviewed-on: eive/fsfw#41
2022-03-08 10:11:05 +01:00
7ca6d1a695
function to get fsfw version 2022-03-08 10:05:18 +01:00
cc3210f366 Merge branch 'eive/develop' into mueller/define-fsfw-disabled-printout 2022-03-08 09:57:43 +01:00
155d66e534 define FSFW_DISABLE_PRINTOUT in any case 2022-03-08 09:57:11 +01:00
d4c76a7e46 Merge branch 'mueller/master' of https://egit.irs.uni-stuttgart.de/eive/fsfw into mueller/master 2022-03-08 09:56:39 +01:00
dba3c27b99
define FSFW_DISABLE_PRINTOUT in any case 2022-03-08 09:56:24 +01:00
202cfc6dbb Merge branch 'eive/develop' into mueller/master 2022-03-08 09:47:37 +01:00
84f95e8d76
this is better 2022-03-08 09:45:58 +01:00
6de4798805 Merge pull request 'better name of invalid mode retval' (#40) from mueller/master into eive/develop
Reviewed-on: eive/fsfw#40
2022-03-08 09:37:58 +01:00
82a645deba Merge branch 'eive/develop' into mueller/master 2022-03-08 09:36:25 +01:00
8b1c277c58
better name of invalid mode retval 2022-03-08 09:34:22 +01:00
5f23f709cc Merge pull request 'Update for Assembly Base' (#38) from mueller/master into eive/develop
Reviewed-on: eive/fsfw#38
2022-03-08 07:53:04 +01:00
a7cb2d4354
small test device handler fixes 2022-03-07 15:54:56 +01:00
7571987a1d
Merge branch 'eive/develop' into mueller/master 2022-03-07 15:43:52 +01:00
d6c1041133
Merge remote-tracking branch 'upstream/development' into eive/develop 2022-03-07 15:34:11 +01:00
3c53e2c259
renamed some ModeIF definitions 2022-03-05 03:01:43 +01:00
45f0d7fd45
docs 2022-03-04 18:06:57 +01:00
aebab4c73c
Merge remote-tracking branch 'upstream/development' into mueller/master 2022-03-04 15:08:45 +01:00
c3c2e1c0dd
Merge remote-tracking branch 'upstream/development' into eive/develop 2022-03-04 15:08:07 +01:00
4e6c1cb72a
docs 2022-03-04 00:55:41 +01:00
e2eb6a46b6
Merge branch 'eive/develop' into mueller/master 2022-03-03 13:43:15 +01:00
75c56280ad Merge pull request 'GPIO HAL Updates' (#36) from mueller/gpio-hal-updates into eive/develop
Reviewed-on: eive/fsfw#36
2022-03-03 09:44:42 +01:00
0ccaf27fcb
better printout for parameter code 2022-03-01 19:43:21 +01:00
e05e203c83
fix merge conflict 2022-02-28 15:50:27 +01:00
ac036b2a70
Merge remote-tracking branch 'origin/eive/develop' into mueller/gpio-hal-updates 2022-02-28 15:49:11 +01:00
2d9216ba19
Merge branch 'mueller/gpio-hal-updates' into mueller/master 2022-02-28 15:37:03 +01:00
2fed161eff
Merge branch 'eive/develop' into mueller/gpio-hal-updates 2022-02-28 15:34:48 +01:00
4cf2a384f3
Merge remote-tracking branch 'upstream/development' into mueller/gpio-hal-updates 2022-02-28 15:22:32 +01:00
27267b7cb0
Merge remote-tracking branch 'upstream/development' into mueller/gpio-hal-updates 2022-02-28 15:21:39 +01:00
505e00c067 Merge remote-tracking branch 'origin/eive/develop' into mueller/master 2022-02-28 15:17:29 +01:00
68225586d2 some fixes 2022-02-28 15:16:43 +01:00
6d825a1aa6
some fixes 2022-02-28 15:16:24 +01:00
fa73ad6731 Merge branch 'mueller/gpio-hal-updates' into mueller/master 2022-02-28 15:01:41 +01:00
331aa9442d
some updates 2022-02-28 14:56:37 +01:00
28b28b5684
Merge branch 'mueller/gpio-hal-updates' into mueller/master 2022-02-28 14:48:27 +01:00
afd3a942e2
use enum class 2022-02-28 14:46:12 +01:00
729bcc4aaf Merge remote-tracking branch 'upstream/development' into mueller/gpio-hal-updates 2022-02-28 14:39:35 +01:00
6e0b90696d Merge pull request 'initial submode' (#35) from meier/dhbInitialSubmode into eive/develop
Reviewed-on: eive/fsfw#35
2022-02-28 13:23:26 +01:00
Jakob Meier
eacb4ac407 initial submode 2022-02-25 14:41:43 +01:00
09c1918c1f Merge pull request 'Update FSFW' (#34) from mueller/master into eive/develop
Reviewed-on: eive/fsfw#34
2022-02-25 11:38:11 +01:00
123f2ff360
removed unnecessary warning 2022-02-25 11:10:48 +01:00
7ce2c1b624 Merge branch 'development' into mueller/gpio-hal-updates 2022-02-23 11:02:02 +01:00
4747e54c5d no default values for srv5 params 2022-02-22 20:08:19 +01:00
2e230daa14 additional comment 2022-02-22 18:59:50 +01:00
e909c6b6f7 Merge branch 'mueller/spi-update-clock-polarity' into mueller/master 2022-02-22 18:59:06 +01:00
d88d7c938f update spi clock polarity
- Perform an empty SPI transfer after setting speed and mode
2022-02-22 18:58:20 +01:00
389641f8fd
display run commands 2022-02-22 14:00:34 +01:00
b440c30223
update changelog 2022-02-22 11:26:11 +01:00
3966b656e9
apply .clang format 2022-02-22 11:15:01 +01:00
3a5881a0cb
more time 2022-02-22 11:10:02 +01:00
1e982ec00b
updated for windows compatibility 2022-02-22 11:00:39 +01:00
701135e2a6
applied clang format 2022-02-22 10:17:56 +01:00
19f8e41c7f Merge pull request 'Update FSFW' (#33) from mueller/master into eive/develop
Reviewed-on: eive/fsfw#33
2022-02-21 11:00:17 +01:00
c4a055986c
Merge remote-tracking branch 'origin/eive/develop' into mueller/master 2022-02-21 10:37:53 +01:00
d74a373f1d
make periodic printout run time configurable 2022-02-19 16:41:30 +01:00
cf69af4e7e
passing mqArgs to all mq ctor calls 2022-02-19 16:14:02 +01:00
508979d32d cache mq args 2022-02-18 14:52:25 +01:00
0d66569687 this is a bit cleaner 2022-02-18 14:07:41 +01:00
a5871ed0b1 added void* args to queue factory and mq ctor 2022-02-18 14:00:06 +01:00
a12e98d948 update event mngr printout 2022-02-18 13:39:42 +01:00
bd05afbddd printout improvements 2022-02-18 13:09:18 +01:00
b3482eba24 error check in event manager 2022-02-17 20:41:47 +01:00
9e92afbf07 bugfix in test task 2022-02-16 18:54:55 +01:00
0d6d44f72f Merge remote-tracking branch 'upstream/development' into mueller/master 2022-02-15 17:08:29 +01:00
81f5b0c3bf
Merge branch 'mueller/dhb-docs' into mueller/master 2022-02-10 14:03:28 +01:00
062e93fd88
started DHB docs 2022-02-10 13:53:01 +01:00
c20bf31d5d Merge pull request 'meier/halAdjustments' (#32) from meier/halAdjustments into eive/develop
Reviewed-on: eive/fsfw#32
2022-02-07 11:03:09 +01:00
Jakob Meier
3c06d2dbbb run clang format script 2022-02-05 18:11:23 +01:00
Jakob Meier
018d814f29 adapt to develop 2022-02-05 17:12:42 +01:00
Jakob Meier
c0648a789b merged develop 2022-02-05 17:07:06 +01:00
Jakob Meier
9579e94a71 option to exclude libgpiod from build 2022-02-05 16:09:23 +01:00
Jakob Meier
235fd79dfb added missing baudrates 2022-02-05 16:08:28 +01:00
83635d3667 Merge pull request 'Fix for event definitions' (#31) from mueller/fix-events into eive/develop
Reviewed-on: eive/fsfw#31
2022-02-03 18:20:48 +01:00
581ae4c990 another include removed 2022-02-03 17:37:29 +01:00
32a9e0c704
another include removed 2022-02-03 17:37:11 +01:00
940c53eba6 removed HK switch helper from cmake file 2022-02-03 17:34:15 +01:00
0d4bd856bd
removed HK switch helper from cmake file 2022-02-03 17:33:46 +01:00
b7f6a6961b
delete switch helper, some other fixes 2022-02-03 17:14:11 +01:00
a910a05541
parser is not perfect.. 2022-02-03 17:09:58 +01:00
973996e102
more fixes 2022-02-03 17:08:30 +01:00
b3aee76d91
fixes for event definitoons for parser 2022-02-03 17:06:18 +01:00
b3151a0ba0
added i2c wiretapping 2022-02-03 13:37:28 +01:00
fca48257b7
zero initialize array 2022-02-03 12:02:08 +01:00
8f95b03e6a
fixes warning for good 2022-02-03 11:13:26 +01:00
527dba9a9d Merge branch 'mueller/comp-branch' into mueller/master 2022-02-02 20:15:20 +01:00
22cd38fffd
this should work for c++11 2022-02-02 20:05:46 +01:00
1a518109d0 Merge branch 'mueller/comp-branch' into mueller/master 2022-02-02 19:49:03 +01:00
8030d9ac1b
this fixes the warning 2022-02-02 19:47:58 +01:00
992c05df56
added cpp printout preprocessor guards 2022-02-02 17:52:09 +01:00
6698d283b6
device wants hard reboot event added 2022-02-02 16:04:36 +01:00
33386550cf
add uio subdir 2022-02-02 12:17:42 +01:00
3a65c0db91
use C++ casts 2022-02-02 12:13:42 +01:00
41614303d7
renamed variable 2022-02-02 12:11:39 +01:00
783176848a
include fixes 2022-02-02 12:10:39 +01:00
07cb980e06
apply clang script 2022-02-02 12:05:03 +01:00
d8c5bd125e
All EIVE changes 2022-02-02 12:02:58 +01:00
2252 changed files with 969760 additions and 7568 deletions

View File

@ -4,4 +4,5 @@ IndentWidth: 2
---
Language: Cpp
ColumnLimit: 100
ReflowComments: true
---

4
.gitignore vendored
View File

@ -1,8 +1,8 @@
# PyCharm and CLion
/.idea/*
.idea/*
!/.idea/runConfigurations
!/.idea/cmake.xml
!/.idea/codeStyles
# !/.idea/codeStyles
# Eclipse
.cproject

8
.idea/cmake.xml generated Normal file
View File

@ -0,0 +1,8 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="CMakeSharedSettings">
<configurations>
<configuration PROFILE_NAME="Debug Test" ENABLED="true" CONFIG_NAME="Debug" GENERATION_OPTIONS="-DFSFW_OSAL=host -DFSFW_BUILD_TESTS=ON" NO_GENERATOR="true" />
</configurations>
</component>
</project>

View File

@ -1,14 +0,0 @@
<component name="ProjectCodeStyleConfiguration">
<code_scheme name="Project" version="173">
<clangFormatSettings>
<option name="ENABLED" value="true" />
</clangFormatSettings>
<codeStyleSettings language="CMake">
<indentOptions>
<option name="INDENT_SIZE" value="2" />
<option name="CONTINUATION_INDENT_SIZE" value="0" />
<option name="TAB_SIZE" value="2" />
</indentOptions>
</codeStyleSettings>
</code_scheme>
</component>

View File

@ -1,5 +0,0 @@
<component name="ProjectCodeStyleConfiguration">
<state>
<option name="USE_PER_PROJECT_SETTINGS" value="true" />
</state>
</component>

View File

@ -8,6 +8,62 @@ and this project adheres to [Semantic Versioning](http://semver.org/).
# [unreleased]
## Fixes
- FreshDeviceHandlerBase did not initialize the fdirInstance
- The `PusTmCreator` API only accepted 255 bytes of source data. It can now accept source
data with a size limited only by the size of `size_t`.
- Important bugfix in CFDP PDU header format: The entity length field and the transaction sequence
number fields stored the actual length of the field instead of the length minus 1 like specified
in the CFDP standard.
- PUS Health Service: Size check for set health command.
Perform operation completion for announce health command.
https://egit.irs.uni-stuttgart.de/fsfw/fsfw/pulls/746
- Linux OSAL `getUptime` fix: Check validity of `/proc/uptime` file before reading uptime.
https://egit.irs.uni-stuttgart.de/fsfw/fsfw/pulls/745
- Small tweak for version getter
https://egit.irs.uni-stuttgart.de/fsfw/fsfw/pulls/744
## Added
- add CFDP subsystem ID
https://egit.irs.uni-stuttgart.de/fsfw/fsfw/pulls/742
- `PusTmZcWriter` now exposes API to set message counter field.
- Relative timeshift in the PUS time service.
- CFDP support for PDU checksums
## Changed
- Complete refactoring of HK subsystem. Replaced local data pool manager by periodic HK
helper. The shared pool and the periodic HK generation are now distinct concepts.
- Improved File System Abstraction to be more in line with normal filesystems.
- CFDP implementation was improved, has now even less dependencies on other FSFW components
and allows one inserted packet per state machine call.
- The PUS time service now dumps the time before setting a new time and after having set the
time.
- HK generation is now countdown based.
- Bump ETL version to 20.35.14
https://egit.irs.uni-stuttgart.de/fsfw/fsfw/pulls/748
- Renamed `PCDU_2` subsystem ID to `POWER_SWITCH_IF`.
https://egit.irs.uni-stuttgart.de/fsfw/fsfw/pulls/743
- Add new `PowerSwitchIF::SWITCH_UNKNOWN` returnvalue.
https://egit.irs.uni-stuttgart.de/fsfw/fsfw/pulls/743
- Assert that `FixedArrayList` is larger than 0 at compile time.
https://egit.irs.uni-stuttgart.de/fsfw/fsfw/pulls/740
- Health functions are virtual now.
- PUS Service Base request queue depth and maximum number of handled packets per cycle is now
configurable.
- Switched to vendored versions for both the Embedded Template Library (ETL) and the
Catch2 unittesting library.
## Added
- `EventManager`: Add function to print all listeners.
## Changed
- `EventManager`: Queue depth is configurable now
# [v6.0.0] 2023-02-10
## Fixes
@ -82,6 +138,8 @@ and this project adheres to [Semantic Versioning](http://semver.org/).
## Added
- `CServiceHealthCommanding`: Add announce all health info implementation
PR: https://egit.irs.uni-stuttgart.de/eive/fsfw/pulls/122
- Empty constructor for `CdsShortTimeStamper` which does not do an object manager registration.
PR: https://egit.irs.uni-stuttgart.de/fsfw/fsfw/pulls/730
- `Service9TimeManagement`: Add `DUMP_TIME` (129) subservice.

View File

@ -66,23 +66,6 @@ endif()
set(FSFW_SOURCES_DIR "${CMAKE_SOURCE_DIR}/src/fsfw")
set(FSFW_ETL_LIB_NAME etl)
set(FSFW_ETL_LINK_TARGET etl::etl)
set(FSFW_ETL_LIB_MAJOR_VERSION
20
CACHE STRING "ETL library major version requirement")
set(FSFW_ETL_LIB_VERSION
${FSFW_ETL_LIB_MAJOR_VERSION}.28.0
CACHE STRING "ETL library exact version requirement")
set(FSFW_ETL_LINK_TARGET etl::etl)
set(FSFW_CATCH2_LIB_MAJOR_VERSION
3
CACHE STRING "Catch2 library major version requirement")
set(FSFW_CATCH2_LIB_VERSION
v${FSFW_CATCH2_LIB_MAJOR_VERSION}.1.0
CACHE STRING "Catch2 library exact version requirement")
# Keep this off by default for now. See PR:
# https://egit.irs.uni-stuttgart.de/fsfw/fsfw/pulls/616 for information which
# keeping this on by default is problematic
@ -107,6 +90,7 @@ endif()
option(FSFW_BUILD_TESTS
"Build unittest binary in addition to static library. Requires Catch2"
OFF)
option(FSFW_ADD_CATCH2 "Add Catch2 unittest framework dependency" OFF)
option(FSFW_CICD_BUILD "Build for CI/CD. This can disable problematic test" OFF)
option(FSFW_BUILD_DOCS "Build documentation with Sphinx and Doxygen" OFF)
if(FSFW_BUILD_TESTS)
@ -152,23 +136,6 @@ if(FSFW_BUILD_TESTS)
STATUS
"${MSG_PREFIX} Building the FSFW unittests in addition to the static library"
)
# Check whether the user has already installed Catch2 first
find_package(Catch2 ${FSFW_CATCH2_LIB_MAJOR_VERSION} QUIET)
# Not installed, so use FetchContent to download and provide Catch2
if(NOT Catch2_FOUND)
message(
STATUS
"${MSG_PREFIX} Catch2 installation not found. Downloading Catch2 library with FetchContent."
)
include(FetchContent)
FetchContent_Declare(
Catch2
GIT_REPOSITORY https://github.com/catchorg/Catch2.git
GIT_TAG ${FSFW_CATCH2_LIB_VERSION})
list(APPEND FSFW_FETCH_CONTENT_TARGETS Catch2)
endif()
set(FSFW_CONFIG_PATH unittests/testcfg)
configure_file(unittests/testcfg/FSFWConfig.h.in FSFWConfig.h)
@ -190,42 +157,11 @@ if(FSFW_BUILD_TESTS)
endif()
endif()
message(
STATUS
"${MSG_PREFIX} Finding and/or providing etl library with version ${FSFW_ETL_LIB_MAJOR_VERSION}"
)
# Check whether the user has already installed ETL first
find_package(${FSFW_ETL_LIB_NAME} ${FSFW_ETL_LIB_MAJOR_VERSION} QUIET)
# Not installed, so use FetchContent to download and provide etl
if(NOT ${FSFW_ETL_LIB_NAME}_FOUND)
message(
STATUS
"${MSG_PREFIX} ETL installation not found. Downloading ETL with FetchContent."
)
include(FetchContent)
FetchContent_Declare(
${FSFW_ETL_LIB_NAME}
GIT_REPOSITORY https://github.com/ETLCPP/etl
GIT_TAG ${FSFW_ETL_LIB_VERSION})
list(APPEND FSFW_FETCH_CONTENT_TARGETS ${FSFW_ETL_LIB_NAME})
endif()
# The documentation for FetchContent recommends declaring all the dependencies
# before making them available. We make all declared dependency available here
# after their declaration
if(FSFW_FETCH_CONTENT_TARGETS)
FetchContent_MakeAvailable(${FSFW_FETCH_CONTENT_TARGETS})
if(TARGET ${FSFW_ETL_LIB_NAME})
add_library(${FSFW_ETL_LINK_TARGET} ALIAS ${FSFW_ETL_LIB_NAME})
endif()
if(TARGET Catch2)
# Fixes regression -preview4, to be confirmed in later releases Related
# GitHub issue: https://github.com/catchorg/Catch2/issues/2417
set_target_properties(Catch2 PROPERTIES DEBUG_POSTFIX "")
endif()
endif()
set(FSFW_CORE_INC_PATH "inc")
@ -466,7 +402,7 @@ target_compile_options(${LIB_FSFW_NAME} PRIVATE ${FSFW_WARNING_FLAGS}
${COMPILER_FLAGS})
target_link_libraries(${LIB_FSFW_NAME} PRIVATE ${FSFW_ADDITIONAL_LINK_LIBS})
target_link_libraries(${LIB_FSFW_NAME} PUBLIC ${FSFW_ETL_LINK_TARGET})
target_link_libraries(${LIB_FSFW_NAME} PUBLIC etl::etl)
string(
CONCAT

2
NOTICE
View File

@ -21,3 +21,5 @@ their own copyright notices and license terms:
under contrib/:
* sgp4: sgp4 code developed by david vallado under public domain, see https://www.celestrak.com/publications/AIAA/2006-6753/
* etl: Embedded Template Library (ETL) with own license
* Catch2: Unittest library with own license

View File

@ -105,6 +105,14 @@ add and link against the FSFW library in general.
5. It should now be possible use the FSFW as a static library from the user code.
## Current dependencies
This library currently has the following vendored dependencies:
- [Embedded Template Library (etl) v20.39.4](https://github.com/ETLCPP/etl/releases/tag/20.39.4)
- [Catch2 v3.7.1](https://github.com/catchorg/Catch2/releases/tag/v3.7.1)
- sgp4 propagator
## Building the unittests
The FSFW also has unittests which use the [Catch2 library](https://github.com/catchorg/Catch2).

View File

@ -97,7 +97,7 @@ pipeline {
sh 'rsync -r --delete docs/sphinx/* buildfix@documentation.irs.uni-stuttgart.de:/fsfw/development'
}
}
dir(BUILDDIR) {
dir(BUILDDIR_LINUX) {
sshagent(credentials: ['documentation-buildfix']) {
sh 'rsync -r --delete fsfw-tests_coverage/* buildfix@documentation.irs.uni-stuttgart.de:/fsfw/coverage/development'
}
@ -116,7 +116,7 @@ pipeline {
sh 'rsync -r --delete docs/sphinx/* buildfix@documentation.irs.uni-stuttgart.de:/fsfw/master'
}
}
dir(BUILDDIR) {
dir(BUILDDIR_LINUX) {
sshagent(credentials: ['documentation-buildfix']) {
sh 'rsync -r --delete fsfw-tests_coverage/* buildfix@documentation.irs.uni-stuttgart.de:/fsfw/coverage/master'
}

View File

@ -9,3 +9,8 @@ if(FSFW_ADD_SGP4_PROPAGATOR)
${CMAKE_CURRENT_SOURCE_DIR}/sgp4
)
endif()
add_subdirectory(etl-20.39.4)
if(FSFW_BUILD_TESTS OR FSFW_ADD_CATCH2)
add_subdirectory(Catch2-3.7.1)
endif()

View File

@ -0,0 +1,11 @@
build --enable_platform_specific_config
build:gcc9 --cxxopt=-std=c++2a
build:gcc11 --cxxopt=-std=c++2a
build:clang13 --cxxopt=-std=c++17
build:vs2019 --cxxopt=/std:c++17
build:vs2022 --cxxopt=/std:c++17
build:windows --config=vs2022
build:linux --config=gcc11
build:macos --cxxopt=-std=c++2b

View File

@ -0,0 +1,45 @@
---
Language: Cpp
Standard: c++14
# Note that we cannot use IncludeIsMainRegex functionality, because it
# does not support includes in angle brackets (<>)
SortIncludes: true
IncludeBlocks: Regroup
IncludeCategories:
- Regex: <catch2/.*\.hpp>
Priority: 1
- Regex: <.*/.*\.hpp>
Priority: 2
- Regex: <.*>
Priority: 3
AllowShortBlocksOnASingleLine: Always
AllowShortEnumsOnASingleLine: false
AllowShortFunctionsOnASingleLine: All
AllowShortIfStatementsOnASingleLine: WithoutElse
AllowShortLambdasOnASingleLine: Inline
AccessModifierOffset: "-4"
AlignEscapedNewlines: Left
AllowAllConstructorInitializersOnNextLine: "true"
BinPackArguments: "false"
BinPackParameters: "false"
BreakConstructorInitializers: AfterColon
ConstructorInitializerAllOnOneLineOrOnePerLine: "true"
DerivePointerAlignment: "false"
FixNamespaceComments: "true"
IndentCaseLabels: "false"
IndentPPDirectives: AfterHash
IndentWidth: "4"
NamespaceIndentation: All
PointerAlignment: Left
SpaceBeforeCtorInitializerColon: "false"
SpaceInEmptyParentheses: "false"
SpacesInParentheses: "true"
TabWidth: "4"
UseTab: Never
AlwaysBreakTemplateDeclarations: Yes
SpaceAfterTemplateKeyword: true
SortUsingDeclarations: true
ReflowComments: true

View File

@ -0,0 +1,81 @@
---
# Note: Alas, `Checks` is a string, not an array.
# Comments in the block string are not parsed and are passed in the value.
# They must thus be delimited by ',' from either side - then they are
# harmless. It's terrible, but it works.
Checks: >-
clang-diagnostic-*,
clang-analyzer-*,
-clang-analyzer-optin.core.EnumCastOutOfRange,
bugprone-*,
-bugprone-unchecked-optional-access,
,# This is ridiculous, as it triggers on constants,
-bugprone-implicit-widening-of-multiplication-result,
-bugprone-easily-swappable-parameters,
,# Is not really useful, has false positives, triggers for no-noexcept move constructors ...,
-bugprone-exception-escape,
-bugprone-narrowing-conversions,
-bugprone-chained-comparison,# RIP decomposers,
modernize-*,
-modernize-avoid-c-arrays,
-modernize-use-auto,
-modernize-use-emplace,
-modernize-use-nullptr,# it went crazy with three-way comparison operators,
-modernize-use-trailing-return-type,
-modernize-return-braced-init-list,
-modernize-concat-nested-namespaces,
-modernize-use-nodiscard,
-modernize-use-default-member-init,
-modernize-type-traits,# we need to support C++14,
-modernize-deprecated-headers,
,# There's a lot of these and most of them are probably not useful,
-modernize-pass-by-value,
performance-*,
-performance-enum-size,
portability-*,
readability-*,
-readability-braces-around-statements,
-readability-container-size-empty,
-readability-convert-member-functions-to-static,
-readability-else-after-return,
-readability-function-cognitive-complexity,
-readability-function-size,
-readability-identifier-length,
-readability-implicit-bool-conversion,
-readability-isolate-declaration,
-readability-magic-numbers,
-readability-named-parameter,
-readability-qualified-auto,
-readability-redundant-access-specifiers,
-readability-simplify-boolean-expr,
-readability-static-definition-in-anonymous-namespace,
-readability-uppercase-literal-suffix,
-readability-use-anyofallof,
-readability-avoid-return-with-void-value,
,# time hogs,
-bugprone-throw-keyword-missing,
-modernize-replace-auto-ptr,
-readability-identifier-naming,
,# We cannot use this until clang-tidy supports custom unique_ptr,
-bugprone-use-after-move,
,# Doesn't recognize unevaluated context in CATCH_MOVE and CATCH_FORWARD,
-bugprone-macro-repeated-side-effects,
WarningsAsErrors: >-
clang-analyzer-core.*,
clang-analyzer-cplusplus.*,
clang-analyzer-security.*,
clang-analyzer-unix.*,
performance-move-const-arg,
performance-unnecessary-value-param,
readability-duplicate-include,
HeaderFilterRegex: '.*\.(c|cxx|cpp)$'
FormatStyle: none
CheckOptions: {}
...

View File

@ -0,0 +1,94 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import re
from cpt.packager import ConanMultiPackager
from cpt.ci_manager import CIManager
from cpt.printer import Printer
class BuilderSettings(object):
@property
def username(self):
""" Set catchorg as package's owner
"""
return os.getenv("CONAN_USERNAME", "catchorg")
@property
def login_username(self):
""" Set Bintray login username
"""
return os.getenv("CONAN_LOGIN_USERNAME", "horenmar")
@property
def upload(self):
""" Set Catch2 repository to be used on upload.
The upload server address could be customized by env var
CONAN_UPLOAD. If not defined, the method will check the branch name.
Only devel or CONAN_STABLE_BRANCH_PATTERN will be accepted.
The devel branch will be pushed to testing channel, because it does
not match the stable pattern. Otherwise it will upload to stable
channel.
"""
return os.getenv("CONAN_UPLOAD", "https://api.bintray.com/conan/catchorg/catch2")
@property
def upload_only_when_stable(self):
""" Force to upload when running over tag branch
"""
return os.getenv("CONAN_UPLOAD_ONLY_WHEN_STABLE", "True").lower() in ["true", "1", "yes"]
@property
def stable_branch_pattern(self):
""" Only upload the package the branch name is like a tag
"""
return os.getenv("CONAN_STABLE_BRANCH_PATTERN", r"v\d+\.\d+\.\d+")
@property
def reference(self):
""" Read project version from branch create Conan reference
"""
return os.getenv("CONAN_REFERENCE", "catch2/{}".format(self._version))
@property
def channel(self):
""" Default Conan package channel when not stable
"""
return os.getenv("CONAN_CHANNEL", "testing")
@property
def _version(self):
""" Get version name from cmake file
"""
pattern = re.compile(r"project\(Catch2 LANGUAGES CXX VERSION (\d+\.\d+\.\d+)\)")
version = "latest"
with open("CMakeLists.txt") as file:
for line in file:
result = pattern.search(line)
if result:
version = result.group(1)
return version
@property
def _branch(self):
""" Get branch name from CI manager
"""
printer = Printer(None)
ci_manager = CIManager(printer)
return ci_manager.get_branch()
if __name__ == "__main__":
settings = BuilderSettings()
builder = ConanMultiPackager(
reference=settings.reference,
channel=settings.channel,
upload=settings.upload,
upload_only_when_stable=False,
stable_branch_pattern=settings.stable_branch_pattern,
login_username=settings.login_username,
username=settings.username,
test_folder=os.path.join(".conan", "test_package"))
builder.add()
builder.run()

View File

@ -0,0 +1,8 @@
cmake_minimum_required(VERSION 3.15)
project(PackageTest CXX)
find_package(Catch2 CONFIG REQUIRED)
add_executable(test_package test_package.cpp)
target_link_libraries(test_package Catch2::Catch2WithMain)
target_compile_features(test_package PRIVATE cxx_std_14)

View File

@ -0,0 +1,40 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from conan import ConanFile
from conan.tools.cmake import CMake, cmake_layout
from conan.tools.build import can_run
from conan.tools.files import save, load
import os
class TestPackageConan(ConanFile):
settings = "os", "compiler", "build_type", "arch"
generators = "CMakeToolchain", "CMakeDeps", "VirtualRunEnv"
test_type = "explicit"
def requirements(self):
self.requires(self.tested_reference_str)
def layout(self):
cmake_layout(self)
def generate(self):
save(self, os.path.join(self.build_folder, "package_folder"),
self.dependencies[self.tested_reference_str].package_folder)
save(self, os.path.join(self.build_folder, "license"),
self.dependencies[self.tested_reference_str].license)
def build(self):
cmake = CMake(self)
cmake.configure()
cmake.build()
def test(self):
if can_run(self):
cmd = os.path.join(self.cpp.build.bindir, "test_package")
self.run(cmd, env="conanrun")
package_folder = load(self, os.path.join(self.build_folder, "package_folder"))
license = load(self, os.path.join(self.build_folder, "license"))
assert os.path.isfile(os.path.join(package_folder, "licenses", "LICENSE.txt"))
assert license == 'BSL-1.0'

View File

@ -0,0 +1,13 @@
#include <catch2/catch_test_macros.hpp>
int Factorial( int number ) {
return number <= 1 ? 1 : Factorial( number - 1 ) * number;
}
TEST_CASE( "Factorial Tests", "[single-file]" ) {
REQUIRE( Factorial(0) == 1 );
REQUIRE( Factorial(1) == 1 );
REQUIRE( Factorial(2) == 2 );
REQUIRE( Factorial(3) == 6 );
REQUIRE( Factorial(10) == 3628800 );
}

View File

@ -0,0 +1,22 @@
# This sets the default behaviour, overriding core.autocrlf
* text=auto
# All source files should have unix line-endings in the repository,
# but convert to native line-endings on checkout
*.cpp text
*.h text
*.hpp text
# Windows specific files should retain windows line-endings
*.sln text eol=crlf
# Keep executable scripts with LFs so they can be run after being
# checked out on Windows
*.py text eol=lf
# Keep the single include header with LFs to make sure it is uploaded,
# hashed etc with LF
single_include/**/*.hpp eol=lf
# Also keep the LICENCE file with LFs for the same reason
LICENCE.txt eol=lf

View File

@ -0,0 +1,2 @@
github: "horenmar"
custom: "https://www.paypal.me/horenmar"

View File

@ -0,0 +1,29 @@
---
name: Bug report
about: Create an issue that documents a bug
title: ''
labels: ''
assignees: ''
---
**Describe the bug**
A clear and concise description of what the bug is.
**Expected behavior**
A clear and concise description of what you expected to happen.
**Reproduction steps**
Steps to reproduce the bug.
<!-- Usually this means a small and self-contained piece of code that uses Catch and specifying compiler flags if relevant. -->
**Platform information:**
<!-- Fill in any extra information that might be important for your issue. -->
- OS: **Windows NT**
- Compiler+version: **GCC v2.9.5**
- Catch version: **v1.2.3**
**Additional context**
Add any other context about the problem here.

View File

@ -0,0 +1,14 @@
---
name: Feature request
about: Create an issue that requests a feature or other improvement
title: ''
labels: ''
assignees: ''
---
**Description**
Describe the feature/change you request and why do you want it.
**Additional context**
Add any other context or screenshots about the feature request here.

View File

@ -0,0 +1,28 @@
<!--
Please do not submit pull requests changing the `version.hpp`
or the single-include `catch.hpp` file, these are changed
only when a new release is made.
Before submitting a PR you should probably read the contributor documentation
at docs/contributing.md. It will tell you how to properly test your changes.
-->
## Description
<!--
Describe the what and the why of your pull request. Remember that these two
are usually a bit different. As an example, if you have made various changes
to decrease the number of new strings allocated, that's what. The why probably
was that you have a large set of tests and found that this speeds them up.
-->
## GitHub Issues
<!--
If this PR was motivated by some existing issues, reference them here.
If it is a simple bug-fix, please also add a line like 'Closes #123'
to your commit message, so that it is automatically closed.
If it is not, don't, as it might take several iterations for a feature
to be done properly. If in doubt, leave it open and reference it in the
PR itself, so that maintainers can decide.
-->

View File

@ -0,0 +1,24 @@
name: Bazel build
on: [push, pull_request]
jobs:
build_and_test_ubuntu:
name: Linux Ubuntu 22.04 Bazel build <GCC 11.2.0>
runs-on: ubuntu-22.04
strategy:
matrix:
compilation_mode: [fastbuild, dbg, opt]
steps:
- uses: actions/checkout@v4
- name: Mount bazel cache
uses: actions/cache@v3
with:
path: "/home/runner/.cache/bazel"
key: bazel-ubuntu22-gcc11
- name: Build Catch2
run: |
bazelisk build --compilation_mode=${{matrix.compilation_mode}} //...

View File

@ -0,0 +1,44 @@
name: Linux builds (meson)
on: [push, pull_request]
jobs:
build:
name: meson ${{matrix.cxx}}, C++${{matrix.std}}, ${{matrix.build_type}}
runs-on: ubuntu-22.04
strategy:
matrix:
cxx:
- g++-11
- clang++-11
build_type: [debug, release]
std: [14, 17]
include:
- cxx: clang++-11
other_pkgs: clang-11
steps:
- uses: actions/checkout@v4
- name: Prepare environment
run: |
sudo apt-get update
sudo apt-get install -y meson ninja-build ${{matrix.other_pkgs}}
- name: Configure build
env:
CXX: ${{matrix.cxx}}
CXXFLAGS: -std=c++${{matrix.std}} ${{matrix.cxxflags}}
# Note: $GITHUB_WORKSPACE is distinct from ${{runner.workspace}}.
# This is important
run: |
meson -Dbuildtype=${{matrix.build_type}} ${{runner.workspace}}/meson-build
- name: Build tests + lib
working-directory: ${{runner.workspace}}/meson-build
run: ninja
- name: Run tests
working-directory: ${{runner.workspace}}/meson-build
run: |
meson test --verbose

View File

@ -0,0 +1,154 @@
# The builds in this file are more complex (e.g. they need custom CMake
# configuration) and thus are unsuitable to the simple build matrix
# approach used in simple-builds
name: Linux builds (complex)
on: [push, pull_request]
jobs:
build:
name: ${{matrix.build_description}}, ${{matrix.cxx}}, C++${{matrix.std}} ${{matrix.build_type}}
runs-on: ubuntu-20.04
strategy:
matrix:
# We add builds one by one in this case, because there are no
# dimensions that are shared across the builds
include:
# Single surrogate header build
- cxx: clang++-10
build_description: Surrogates build
build_type: Debug
std: 14
other_pkgs: clang-10
cmake_configurations: -DCATCH_BUILD_SURROGATES=ON
# Extras and examples with gcc-7
- cxx: g++-7
build_description: Extras + Examples
build_type: Debug
std: 14
other_pkgs: g++-7
cmake_configurations: -DCATCH_BUILD_EXTRA_TESTS=ON -DCATCH_BUILD_EXAMPLES=ON -DCATCH_ENABLE_CMAKE_HELPER_TESTS=ON
- cxx: g++-7
build_description: Extras + Examples
build_type: Release
std: 14
other_pkgs: g++-7
cmake_configurations: -DCATCH_BUILD_EXTRA_TESTS=ON -DCATCH_BUILD_EXAMPLES=ON -DCATCH_ENABLE_CMAKE_HELPER_TESTS=ON
# Extras and examples with Clang-10
- cxx: clang++-10
build_description: Extras + Examples
build_type: Debug
std: 17
other_pkgs: clang-10
cmake_configurations: -DCATCH_BUILD_EXTRA_TESTS=ON -DCATCH_BUILD_EXAMPLES=ON -DCATCH_ENABLE_CMAKE_HELPER_TESTS=ON
- cxx: clang++-10
build_description: Extras + Examples
build_type: Release
std: 17
other_pkgs: clang-10
cmake_configurations: -DCATCH_BUILD_EXTRA_TESTS=ON -DCATCH_BUILD_EXAMPLES=ON -DCATCH_ENABLE_CMAKE_HELPER_TESTS=ON
# Configure tests with Clang-10
- cxx: clang++-10
build_description: CMake configuration tests
build_type: Debug
std: 14
other_pkgs: clang-10
cmake_configurations: -DCATCH_ENABLE_CONFIGURE_TESTS=ON
# Valgrind test Clang-10
- cxx: clang++-10
build_description: Valgrind tests
build_type: Debug
std: 14
other_pkgs: clang-10 valgrind
cmake_configurations: -DMEMORYCHECK_COMMAND=`which valgrind` -DMEMORYCHECK_COMMAND_OPTIONS="-q --track-origins=yes --leak-check=full --num-callers=50 --show-leak-kinds=definite --error-exitcode=1"
other_ctest_args: -T memcheck -LE uses-python
steps:
- uses: actions/checkout@v4
- name: Prepare environment
run: |
sudo apt-get update
sudo apt-get install -y ninja-build ${{matrix.other_pkgs}}
- name: Configure build
working-directory: ${{runner.workspace}}
env:
CXX: ${{matrix.cxx}}
CXXFLAGS: ${{matrix.cxxflags}}
# Note: $GITHUB_WORKSPACE is distinct from ${{runner.workspace}}.
# This is important
run: |
cmake -Bbuild -H$GITHUB_WORKSPACE \
-DCMAKE_BUILD_TYPE=${{matrix.build_type}} \
-DCMAKE_CXX_STANDARD=${{matrix.std}} \
-DCMAKE_CXX_STANDARD_REQUIRED=ON \
-DCMAKE_CXX_EXTENSIONS=OFF \
-DCATCH_DEVELOPMENT_BUILD=ON \
${{matrix.cmake_configurations}} \
-G Ninja
- name: Build tests + lib
working-directory: ${{runner.workspace}}/build
run: ninja
- name: Run tests
env:
CTEST_OUTPUT_ON_FAILURE: 1
working-directory: ${{runner.workspace}}/build
run: ctest -C ${{matrix.build_type}} -j `nproc` ${{matrix.other_ctest_args}}
clang-tidy:
name: clang-tidy ${{matrix.version}}, ${{matrix.build_description}}, C++${{matrix.std}} ${{matrix.build_type}}
runs-on: ubuntu-22.04
strategy:
matrix:
include:
- version: "15"
build_description: all
build_type: Debug
std: 17
other_pkgs: ''
cmake_configurations: -DCATCH_BUILD_EXAMPLES=ON -DCATCH_ENABLE_CMAKE_HELPER_TESTS=ON
steps:
- uses: actions/checkout@v4
- name: Prepare environment
run: |
sudo apt-get update
sudo apt-get install -y ninja-build clang-${{matrix.version}} clang-tidy-${{matrix.version}} ${{matrix.other_pkgs}}
- name: Configure build
working-directory: ${{runner.workspace}}
env:
CXX: clang++-${{matrix.version}}
CXXFLAGS: ${{matrix.cxxflags}}
# Note: $GITHUB_WORKSPACE is distinct from ${{runner.workspace}}.
# This is important
run: |
clangtidy="clang-tidy-${{matrix.version}};-use-color"
# Use a dummy compiler/linker/ar/ranlib to effectively disable the
# compilation and only run clang-tidy.
cmake -Bbuild -H$GITHUB_WORKSPACE \
-DCMAKE_BUILD_TYPE=${{matrix.build_type}} \
-DCMAKE_CXX_STANDARD=${{matrix.std}} \
-DCMAKE_CXX_STANDARD_REQUIRED=ON \
-DCMAKE_CXX_EXTENSIONS=OFF \
-DCATCH_DEVELOPMENT_BUILD=ON \
-DCMAKE_CXX_CLANG_TIDY="$clangtidy" \
-DCMAKE_CXX_COMPILER_LAUNCHER=/usr/bin/true \
-DCMAKE_AR=/usr/bin/true \
-DCMAKE_CXX_COMPILER_AR=/usr/bin/true \
-DCMAKE_RANLIB=/usr/bin/true \
-DCMAKE_CXX_LINK_EXECUTABLE=/usr/bin/true \
${{matrix.cmake_configurations}} \
-G Ninja
- name: Run clang-tidy
working-directory: ${{runner.workspace}}/build
run: ninja

View File

@ -0,0 +1,123 @@
name: Linux builds (basic)
on: [push, pull_request]
jobs:
build:
name: ${{matrix.cxx}}, C++${{matrix.std}}, ${{matrix.build_type}}
runs-on: ubuntu-20.04
strategy:
matrix:
cxx:
- g++-5
- g++-6
- g++-7
- g++-8
- g++-9
- g++-10
- clang++-6.0
- clang++-7
- clang++-8
- clang++-9
- clang++-10
build_type: [Debug, Release]
std: [14]
include:
- cxx: g++-5
other_pkgs: g++-5
- cxx: g++-6
other_pkgs: g++-6
- cxx: g++-7
other_pkgs: g++-7
- cxx: g++-8
other_pkgs: g++-8
- cxx: g++-9
other_pkgs: g++-9
- cxx: g++-10
other_pkgs: g++-10
- cxx: clang++-6.0
other_pkgs: clang-6.0
- cxx: clang++-7
other_pkgs: clang-7
- cxx: clang++-8
other_pkgs: clang-8
- cxx: clang++-9
other_pkgs: clang-9
- cxx: clang++-10
other_pkgs: clang-10
# Clang 6 + C++17
# does not work with the default libstdc++ version thanks
# to a disagreement on variant implementation.
# - cxx: clang++-6.0
# build_type: Debug
# std: 17
# other_pkgs: clang-6.0
# - cxx: clang++-6.0
# build_type: Release
# std: 17
# other_pkgs: clang-6.0
# Clang 10 + C++17
- cxx: clang++-10
build_type: Debug
std: 17
other_pkgs: clang-10
- cxx: clang++-10
build_type: Release
std: 17
other_pkgs: clang-10
- cxx: clang++-10
build_type: Debug
std: 20
other_pkgs: clang-10
- cxx: clang++-10
build_type: Release
std: 20
other_pkgs: clang-10
- cxx: g++-10
build_type: Debug
std: 20
other_pkgs: g++-10
- cxx: g++-10
build_type: Release
std: 20
other_pkgs: g++-10
steps:
- uses: actions/checkout@v4
- name: Add repositories for older GCC
run: |
sudo apt-add-repository 'deb http://azure.archive.ubuntu.com/ubuntu/ bionic main'
sudo apt-add-repository 'deb http://azure.archive.ubuntu.com/ubuntu/ bionic universe'
if: ${{ matrix.cxx == 'g++-5' || matrix.cxx == 'g++-6' }}
- name: Prepare environment
run: |
sudo apt-get update
sudo apt-get install -y ninja-build ${{matrix.other_pkgs}}
- name: Configure build
working-directory: ${{runner.workspace}}
env:
CXX: ${{matrix.cxx}}
CXXFLAGS: ${{matrix.cxxflags}}
# Note: $GITHUB_WORKSPACE is distinct from ${{runner.workspace}}.
# This is important
run: |
cmake -Bbuild -H$GITHUB_WORKSPACE \
-DCMAKE_BUILD_TYPE=${{matrix.build_type}} \
-DCMAKE_CXX_STANDARD=${{matrix.std}} \
-DCMAKE_CXX_STANDARD_REQUIRED=ON \
-DCMAKE_CXX_EXTENSIONS=OFF \
-DCATCH_DEVELOPMENT_BUILD=ON \
-G Ninja
- name: Build tests + lib
working-directory: ${{runner.workspace}}/build
run: ninja
- name: Run tests
env:
CTEST_OUTPUT_ON_FAILURE: 1
working-directory: ${{runner.workspace}}/build
run: ctest -C ${{matrix.build_type}} -j `nproc`

View File

@ -0,0 +1,44 @@
name: M1 Mac builds
on: [push, pull_request]
jobs:
build:
runs-on: macos-14
strategy:
matrix:
cxx:
- clang++
build_type: [Debug, Release]
std: [14, 17]
include:
- build_type: Debug
examples: ON
extra_tests: ON
steps:
- uses: actions/checkout@v4
- name: Configure build
working-directory: ${{runner.workspace}}
env:
CXX: ${{matrix.cxx}}
CXXFLAGS: ${{matrix.cxxflags}}
run: |
cmake -Bbuild -H$GITHUB_WORKSPACE \
-DCMAKE_BUILD_TYPE=${{matrix.build_type}} \
-DCMAKE_CXX_STANDARD=${{matrix.std}} \
-DCMAKE_CXX_STANDARD_REQUIRED=ON \
-DCATCH_DEVELOPMENT_BUILD=ON \
-DCATCH_BUILD_EXAMPLES=${{matrix.examples}} \
-DCATCH_BUILD_EXTRA_TESTS=${{matrix.examples}}
- name: Build tests + lib
working-directory: ${{runner.workspace}}/build
run: make -j `sysctl -n hw.ncpu`
- name: Run tests
env:
CTEST_OUTPUT_ON_FAILURE: 1
working-directory: ${{runner.workspace}}/build
run: ctest -C ${{matrix.build_type}} -j `sysctl -n hw.ncpu`

View File

@ -0,0 +1,44 @@
name: Mac builds
on: [push, pull_request]
jobs:
build:
runs-on: macos-12
strategy:
matrix:
cxx:
- clang++
build_type: [Debug, Release]
std: [14, 17]
include:
- build_type: Debug
examples: ON
extra_tests: ON
steps:
- uses: actions/checkout@v4
- name: Configure build
working-directory: ${{runner.workspace}}
env:
CXX: ${{matrix.cxx}}
CXXFLAGS: ${{matrix.cxxflags}}
run: |
cmake -Bbuild -H$GITHUB_WORKSPACE \
-DCMAKE_BUILD_TYPE=${{matrix.build_type}} \
-DCMAKE_CXX_STANDARD=${{matrix.std}} \
-DCMAKE_CXX_STANDARD_REQUIRED=ON \
-DCATCH_DEVELOPMENT_BUILD=ON \
-DCATCH_BUILD_EXAMPLES=${{matrix.examples}} \
-DCATCH_BUILD_EXTRA_TESTS=${{matrix.examples}}
- name: Build tests + lib
working-directory: ${{runner.workspace}}/build
run: make -j `sysctl -n hw.ncpu`
- name: Run tests
env:
CTEST_OUTPUT_ON_FAILURE: 1
working-directory: ${{runner.workspace}}/build
run: ctest -C ${{matrix.build_type}} -j `sysctl -n hw.ncpu`

View File

@ -0,0 +1,31 @@
name: Package Manager Builds
on: [push, pull_request]
jobs:
conan_builds:
name: Conan ${{matrix.conan_version}}
runs-on: ubuntu-20.04
strategy:
matrix:
conan_version:
- '1.63'
- '2.1'
include:
# Conan 1 has default profiles installed
- conan_version: '1.63'
profile_generate: 'false'
steps:
- uses: actions/checkout@v4
- name: Install conan
run: pip install conan==${{matrix.conan_version}}
- name: Setup conan profiles
if: matrix.profile_generate != 'false'
run: conan profile detect
- name: Run conan package create
run: conan create . -tf .conan/test_package

View File

@ -0,0 +1,36 @@
name: Check header guards
on: [push, pull_request]
jobs:
build:
# Set the type of machine to run on
runs-on: ubuntu-20.04
steps:
- name: Checkout source code
uses: actions/checkout@v4
- name: Setup Dependencies
uses: actions/setup-python@v2
with:
python-version: '3.7'
- name: Install checkguard
run: pip install guardonce
- name: Check that include guards are properly named
run: |
wrong_files=$(checkguard -r src/catch2/ -p "name | append _INCLUDED | upper")
if [[ $wrong_files ]]; then
echo "Files with wrong header guard:"
echo $wrong_files
exit 1
fi
- name: Check that there are no duplicated filenames
run: |
./tools/scripts/checkDuplicateFilenames.py
- name: Check that all source files have the correct license header
run: |
./tools/scripts/checkLicense.py

View File

@ -0,0 +1,37 @@
name: Windows builds (basic)
on: [push, pull_request]
jobs:
build:
name: ${{matrix.os}}, ${{matrix.std}}, ${{matrix.build_type}}, ${{matrix.platform}}
runs-on: ${{matrix.os}}
strategy:
matrix:
os: [windows-2019, windows-2022]
platform: [Win32, x64]
build_type: [Debug, Release]
std: [14, 17]
steps:
- uses: actions/checkout@v4
- name: Configure build
working-directory: ${{runner.workspace}}
run: |
cmake -S $Env:GITHUB_WORKSPACE `
-B ${{runner.workspace}}/build `
-DCMAKE_CXX_STANDARD=${{matrix.std}} `
-A ${{matrix.platform}} `
--preset all-tests
- name: Build tests
working-directory: ${{runner.workspace}}
run: cmake --build build --config ${{matrix.build_type}} --parallel %NUMBER_OF_PROCESSORS%
shell: cmd
- name: Run tests
working-directory: ${{runner.workspace}}/build
env:
CTEST_OUTPUT_ON_FAILURE: 1
run: ctest -C ${{matrix.build_type}} -j %NUMBER_OF_PROCESSORS%
shell: cmd

View File

@ -0,0 +1,40 @@
*.build
!meson.build
*.pbxuser
*.mode1v3
*.ncb
*.suo
Debug
Release
*.user
*.xcuserstate
.DS_Store
xcuserdata
CatchSelfTest.xcscheme
Breakpoints.xcbkptlist
UpgradeLog.XML
Resources/DWARF
projects/Generated
*.pyc
DerivedData
*.xccheckout
Build
.idea
.vs
.vscode
cmake-build-*
benchmark-dir
.conan/test_package/build
**/CMakeUserPresets.json
bazel-*
MODULE.bazel.lock
build-fuzzers
debug-build
.vscode
msvc-sln*
# Currently we use Doxygen for dep graphs and the full docs are only slowly
# being filled in, so we definitely do not want git to deal with the docs.
docs/doxygen
*.cache
compile_commands.json
**/*.unapproved.txt

View File

@ -0,0 +1,95 @@
load("@bazel_skylib//rules:expand_template.bzl", "expand_template")
expand_template(
name = "catch_user_config",
out = "catch2/catch_user_config.hpp",
substitutions = {
"@CATCH_CONFIG_CONSOLE_WIDTH@": "80",
"@CATCH_CONFIG_DEFAULT_REPORTER@": "console",
"#cmakedefine CATCH_CONFIG_ANDROID_LOGWRITE": "",
"#cmakedefine CATCH_CONFIG_BAZEL_SUPPORT": "#define CATCH_CONFIG_BAZEL_SUPPORT",
"#cmakedefine CATCH_CONFIG_COLOUR_WIN32": "",
"#cmakedefine CATCH_CONFIG_COUNTER": "",
"#cmakedefine CATCH_CONFIG_CPP11_TO_STRING": "",
"#cmakedefine CATCH_CONFIG_CPP17_BYTE": "",
"#cmakedefine CATCH_CONFIG_CPP17_OPTIONAL": "",
"#cmakedefine CATCH_CONFIG_CPP17_STRING_VIEW": "",
"#cmakedefine CATCH_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS": "",
"#cmakedefine CATCH_CONFIG_CPP17_VARIANT": "",
"#cmakedefine CATCH_CONFIG_DISABLE_EXCEPTIONS_CUSTOM_HANDLER": "",
"#cmakedefine CATCH_CONFIG_DISABLE_EXCEPTIONS": "",
"#cmakedefine CATCH_CONFIG_DISABLE_STRINGIFICATION": "",
"#cmakedefine CATCH_CONFIG_DISABLE": "",
"#cmakedefine CATCH_CONFIG_ENABLE_ALL_STRINGMAKERS": "",
"#cmakedefine CATCH_CONFIG_ENABLE_OPTIONAL_STRINGMAKER": "",
"#cmakedefine CATCH_CONFIG_ENABLE_PAIR_STRINGMAKER": "",
"#cmakedefine CATCH_CONFIG_ENABLE_TUPLE_STRINGMAKER": "",
"#cmakedefine CATCH_CONFIG_ENABLE_VARIANT_STRINGMAKER": "",
"#cmakedefine CATCH_CONFIG_EXPERIMENTAL_REDIRECT": "",
"#cmakedefine CATCH_CONFIG_FALLBACK_STRINGIFIER @CATCH_CONFIG_FALLBACK_STRINGIFIER@": "",
"#cmakedefine CATCH_CONFIG_FAST_COMPILE": "",
"#cmakedefine CATCH_CONFIG_GETENV": "",
"#cmakedefine CATCH_CONFIG_GLOBAL_NEXTAFTER": "",
"#cmakedefine CATCH_CONFIG_NO_ANDROID_LOGWRITE": "",
"#cmakedefine CATCH_CONFIG_NO_COLOUR_WIN32": "",
"#cmakedefine CATCH_CONFIG_NO_COUNTER": "",
"#cmakedefine CATCH_CONFIG_NO_CPP11_TO_STRING": "",
"#cmakedefine CATCH_CONFIG_NO_CPP17_BYTE": "",
"#cmakedefine CATCH_CONFIG_NO_CPP17_OPTIONAL": "",
"#cmakedefine CATCH_CONFIG_NO_CPP17_STRING_VIEW": "",
"#cmakedefine CATCH_CONFIG_NO_CPP17_UNCAUGHT_EXCEPTIONS": "",
"#cmakedefine CATCH_CONFIG_NO_CPP17_VARIANT": "",
"#cmakedefine CATCH_CONFIG_NO_GETENV": "",
"#cmakedefine CATCH_CONFIG_NO_GLOBAL_NEXTAFTER": "",
"#cmakedefine CATCH_CONFIG_NO_POSIX_SIGNALS": "",
"#cmakedefine CATCH_CONFIG_NO_USE_ASYNC": "",
"#cmakedefine CATCH_CONFIG_NO_EXPERIMENTAL_STATIC_ANALYSIS_SUPPORT": "",
"#cmakedefine CATCH_CONFIG_NO_WCHAR": "",
"#cmakedefine CATCH_CONFIG_NO_WINDOWS_SEH": "",
"#cmakedefine CATCH_CONFIG_NOSTDOUT": "",
"#cmakedefine CATCH_CONFIG_POSIX_SIGNALS": "",
"#cmakedefine CATCH_CONFIG_PREFIX_ALL": "",
"#cmakedefine CATCH_CONFIG_PREFIX_MESSAGES": "",
"#cmakedefine CATCH_CONFIG_SHARED_LIBRARY": "",
"#cmakedefine CATCH_CONFIG_EXPERIMENTAL_STATIC_ANALYSIS_SUPPORT": "",
"#cmakedefine CATCH_CONFIG_USE_ASYNC": "",
"#cmakedefine CATCH_CONFIG_WCHAR": "",
"#cmakedefine CATCH_CONFIG_WINDOWS_CRTDBG": "",
"#cmakedefine CATCH_CONFIG_WINDOWS_SEH": "",
},
template = "src/catch2/catch_user_config.hpp.in",
)
# Generated header library, modifies the include prefix to account for
# generation path so that we can include <catch2/catch_user_config.hpp>
# correctly.
cc_library(
name = "catch2_generated",
hdrs = ["catch2/catch_user_config.hpp"],
include_prefix = ".", # to manipulate -I of dependenices
visibility = ["//visibility:public"],
)
# Static library, without main.
cc_library(
name = "catch2",
srcs = glob(
["src/catch2/**/*.cpp"],
exclude = ["src/catch2/internal/catch_main.cpp"],
),
hdrs = glob(["src/catch2/**/*.hpp"]),
includes = ["src/"],
linkstatic = True,
visibility = ["//visibility:public"],
deps = [":catch2_generated"],
)
# Static library, with main.
cc_library(
name = "catch2_main",
srcs = ["src/catch2/internal/catch_main.cpp"],
includes = ["src/"],
linkstatic = True,
visibility = ["//visibility:public"],
deps = [":catch2"],
)

View File

@ -0,0 +1,10 @@
@PACKAGE_INIT@
# Avoid repeatedly including the targets
if(NOT TARGET Catch2::Catch2)
# Provide path for scripts
list(APPEND CMAKE_MODULE_PATH "${CMAKE_CURRENT_LIST_DIR}")
include(${CMAKE_CURRENT_LIST_DIR}/Catch2Targets.cmake)
endif()

View File

@ -0,0 +1,89 @@
# Copyright Catch2 Authors
# Distributed under the Boost Software License, Version 1.0.
# (See accompanying file LICENSE.txt or copy at
# https://www.boost.org/LICENSE_1_0.txt)
# SPDX-License-Identifier: BSL-1.0
##
# This file contains options that are materialized into the Catch2
# compiled library. All of them default to OFF, as even the positive
# forms correspond to the user _forcing_ them to ON, while being OFF
# means that Catch2 can use its own autodetection.
#
# For detailed docs look into docs/configuration.md
macro(AddOverridableConfigOption OptionBaseName)
option(CATCH_CONFIG_${OptionBaseName} "Read docs/configuration.md for details" OFF)
option(CATCH_CONFIG_NO_${OptionBaseName} "Read docs/configuration.md for details" OFF)
mark_as_advanced(CATCH_CONFIG_${OptionBaseName} CATCH_CONFIG_NO_${OptionBaseName})
endmacro()
macro(AddConfigOption OptionBaseName)
option(CATCH_CONFIG_${OptionBaseName} "Read docs/configuration.md for details" OFF)
mark_as_advanced(CATCH_CONFIG_${OptionBaseName})
endmacro()
set(_OverridableOptions
"ANDROID_LOGWRITE"
"BAZEL_SUPPORT"
"COLOUR_WIN32"
"COUNTER"
"CPP11_TO_STRING"
"CPP17_BYTE"
"CPP17_OPTIONAL"
"CPP17_STRING_VIEW"
"CPP17_UNCAUGHT_EXCEPTIONS"
"CPP17_VARIANT"
"GLOBAL_NEXTAFTER"
"POSIX_SIGNALS"
"USE_ASYNC"
"WCHAR"
"WINDOWS_SEH"
"GETENV"
"EXPERIMENTAL_STATIC_ANALYSIS_SUPPORT"
)
foreach(OptionName ${_OverridableOptions})
AddOverridableConfigOption(${OptionName})
endforeach()
set(_OtherConfigOptions
"DISABLE_EXCEPTIONS"
"DISABLE_EXCEPTIONS_CUSTOM_HANDLER"
"DISABLE"
"DISABLE_STRINGIFICATION"
"ENABLE_ALL_STRINGMAKERS"
"ENABLE_OPTIONAL_STRINGMAKER"
"ENABLE_PAIR_STRINGMAKER"
"ENABLE_TUPLE_STRINGMAKER"
"ENABLE_VARIANT_STRINGMAKER"
"EXPERIMENTAL_REDIRECT"
"FAST_COMPILE"
"NOSTDOUT"
"PREFIX_ALL"
"PREFIX_MESSAGES"
"WINDOWS_CRTDBG"
)
foreach(OptionName ${_OtherConfigOptions})
AddConfigOption(${OptionName})
endforeach()
if(DEFINED BUILD_SHARED_LIBS)
set(CATCH_CONFIG_SHARED_LIBRARY ${BUILD_SHARED_LIBS})
else()
set(CATCH_CONFIG_SHARED_LIBRARY "")
endif()
set(CATCH_CONFIG_DEFAULT_REPORTER "console" CACHE STRING "Read docs/configuration.md for details. The name of the reporter should be without quotes.")
set(CATCH_CONFIG_CONSOLE_WIDTH "80" CACHE STRING "Read docs/configuration.md for details. Must form a valid integer literal.")
mark_as_advanced(CATCH_CONFIG_SHARED_LIBRARY CATCH_CONFIG_DEFAULT_REPORTER CATCH_CONFIG_CONSOLE_WIDTH)
# There is no good way to both turn this into a CMake cache variable,
# and keep reasonable default semantics inside the project. Thus we do
# not define it and users have to provide it as an outside variable.
#set(CATCH_CONFIG_FALLBACK_STRINGIFIER "" CACHE STRING "Read docs/configuration.md for details.")

View File

@ -0,0 +1,122 @@
# Copyright Catch2 Authors
# Distributed under the Boost Software License, Version 1.0.
# (See accompanying file LICENSE.txt or copy at
# https://www.boost.org/LICENSE_1_0.txt)
# SPDX-License-Identifier: BSL-1.0
include(CheckCXXCompilerFlag)
function(add_cxx_flag_if_supported_to_targets flagname targets)
string(MAKE_C_IDENTIFIER ${flagname} flag_identifier )
check_cxx_compiler_flag("${flagname}" HAVE_FLAG_${flag_identifier})
if (HAVE_FLAG_${flag_identifier})
foreach(target ${targets})
target_compile_options(${target} PRIVATE ${flagname})
endforeach()
endif()
endfunction()
# Assumes that it is only called for development builds, where warnings
# and Werror is desired, so it also enables Werror.
function(add_warnings_to_targets targets)
LIST(LENGTH targets TARGETS_LEN)
# For now we just assume 2 possibilities: msvc and msvc-like compilers,
# and other.
if (MSVC)
foreach(target ${targets})
# Force MSVC to consider everything as encoded in utf-8
target_compile_options( ${target} PRIVATE /utf-8 )
# Enable Werror equivalent
if (CATCH_ENABLE_WERROR)
target_compile_options( ${target} PRIVATE /WX )
endif()
# MSVC is currently handled specially
if ( CMAKE_CXX_COMPILER_ID MATCHES "MSVC" )
STRING(REGEX REPLACE "/W[0-9]" "/W4" CMAKE_CXX_FLAGS ${CMAKE_CXX_FLAGS}) # override default warning level
target_compile_options( ${target} PRIVATE /w44265 /w44061 /w44062 /w45038 )
endif()
endforeach()
endif()
if (NOT MSVC)
set(CHECKED_WARNING_FLAGS
"-Wabsolute-value"
"-Wall"
"-Wcall-to-pure-virtual-from-ctor-dtor"
"-Wcast-align"
"-Wcatch-value"
"-Wdangling"
"-Wdeprecated"
"-Wdeprecated-register"
"-Wexceptions"
"-Wexit-time-destructors"
"-Wextra"
"-Wextra-semi"
"-Wfloat-equal"
"-Wglobal-constructors"
"-Winit-self"
"-Wmisleading-indentation"
"-Wmismatched-new-delete"
"-Wmismatched-return-types"
"-Wmismatched-tags"
"-Wmissing-braces"
"-Wmissing-declarations"
"-Wmissing-noreturn"
"-Wmissing-prototypes"
"-Wmissing-variable-declarations"
"-Wnon-virtual-dtor"
"-Wnull-dereference"
"-Wold-style-cast"
"-Woverloaded-virtual"
"-Wparentheses"
"-Wpedantic"
"-Wredundant-decls"
"-Wreorder"
"-Wreturn-std-move"
"-Wshadow"
"-Wstrict-aliasing"
"-Wsubobject-linkage"
"-Wsuggest-destructor-override"
"-Wsuggest-override"
"-Wundef"
"-Wuninitialized"
"-Wunneeded-internal-declaration"
"-Wunreachable-code-aggressive"
"-Wunused"
"-Wunused-function"
"-Wunused-parameter"
"-Wvla"
"-Wweak-vtables"
# This is a useful warning, but our tests sometimes rely on
# functions being present, but not picked (e.g. various checks
# for stringification implementation ordering).
# Ergo, we should use it every now and then, but we cannot
# enable it by default.
# "-Wunused-member-function"
)
foreach(warning ${CHECKED_WARNING_FLAGS})
add_cxx_flag_if_supported_to_targets(${warning} "${targets}")
endforeach()
if (CATCH_ENABLE_WERROR)
foreach(target ${targets})
# Enable Werror equivalent
target_compile_options( ${target} PRIVATE -Werror )
endforeach()
endif()
endif()
endfunction()
# Adds flags required for reproducible build to the target
# Currently only supports GCC and Clang
function(add_build_reproducibility_settings target)
# Make the build reproducible on versions of g++ and clang that supports -ffile-prefix-map
if((CMAKE_CXX_COMPILER_ID STREQUAL "GNU") OR (CMAKE_CXX_COMPILER_ID MATCHES "Clang"))
add_cxx_flag_if_supported_to_targets("-ffile-prefix-map=${CATCH_DIR}/=" "${target}")
endif()
endfunction()

View File

@ -0,0 +1,157 @@
# This file is part of CMake-codecov.
#
# Copyright (c)
# 2015-2017 RWTH Aachen University, Federal Republic of Germany
#
# See the LICENSE file in the package base directory for details
#
# Written by Alexander Haase, alexander.haase@rwth-aachen.de
#
# include required Modules
include(FindPackageHandleStandardArgs)
# Search for gcov binary.
set(CMAKE_REQUIRED_QUIET_SAVE ${CMAKE_REQUIRED_QUIET})
set(CMAKE_REQUIRED_QUIET ${codecov_FIND_QUIETLY})
get_property(ENABLED_LANGUAGES GLOBAL PROPERTY ENABLED_LANGUAGES)
foreach (LANG ${ENABLED_LANGUAGES})
# Gcov evaluation is dependent on the used compiler. Check gcov support for
# each compiler that is used. If gcov binary was already found for this
# compiler, do not try to find it again.
if (NOT GCOV_${CMAKE_${LANG}_COMPILER_ID}_BIN)
get_filename_component(COMPILER_PATH "${CMAKE_${LANG}_COMPILER}" PATH)
if ("${CMAKE_${LANG}_COMPILER_ID}" STREQUAL "GNU")
# Some distributions like OSX (homebrew) ship gcov with the compiler
# version appended as gcov-x. To find this binary we'll build the
# suggested binary name with the compiler version.
string(REGEX MATCH "^[0-9]+" GCC_VERSION
"${CMAKE_${LANG}_COMPILER_VERSION}")
find_program(GCOV_BIN NAMES gcov-${GCC_VERSION} gcov
HINTS ${COMPILER_PATH})
elseif ("${CMAKE_${LANG}_COMPILER_ID}" STREQUAL "Clang")
# Some distributions like Debian ship llvm-cov with the compiler
# version appended as llvm-cov-x.y. To find this binary we'll build
# the suggested binary name with the compiler version.
string(REGEX MATCH "^[0-9]+.[0-9]+" LLVM_VERSION
"${CMAKE_${LANG}_COMPILER_VERSION}")
# llvm-cov prior version 3.5 seems to be not working with coverage
# evaluation tools, but these versions are compatible with the gcc
# gcov tool.
if(LLVM_VERSION VERSION_GREATER 3.4)
find_program(LLVM_COV_BIN NAMES "llvm-cov-${LLVM_VERSION}"
"llvm-cov" HINTS ${COMPILER_PATH})
mark_as_advanced(LLVM_COV_BIN)
if (LLVM_COV_BIN)
find_program(LLVM_COV_WRAPPER "llvm-cov-wrapper" PATHS
${CMAKE_MODULE_PATH})
if (LLVM_COV_WRAPPER)
set(GCOV_BIN "${LLVM_COV_WRAPPER}" CACHE FILEPATH "")
# set additional parameters
set(GCOV_${CMAKE_${LANG}_COMPILER_ID}_ENV
"LLVM_COV_BIN=${LLVM_COV_BIN}" CACHE STRING
"Environment variables for llvm-cov-wrapper.")
mark_as_advanced(GCOV_${CMAKE_${LANG}_COMPILER_ID}_ENV)
endif ()
endif ()
endif ()
if (NOT GCOV_BIN)
# Fall back to gcov binary if llvm-cov was not found or is
# incompatible. This is the default on OSX, but may crash on
# recent Linux versions.
find_program(GCOV_BIN gcov HINTS ${COMPILER_PATH})
endif ()
endif ()
if (GCOV_BIN)
set(GCOV_${CMAKE_${LANG}_COMPILER_ID}_BIN "${GCOV_BIN}" CACHE STRING
"${LANG} gcov binary.")
if (NOT CMAKE_REQUIRED_QUIET)
message("-- Found gcov evaluation for "
"${CMAKE_${LANG}_COMPILER_ID}: ${GCOV_BIN}")
endif()
unset(GCOV_BIN CACHE)
endif ()
endif ()
endforeach ()
# Add a new global target for all gcov targets. This target could be used to
# generate the gcov files for the whole project instead of calling <TARGET>-gcov
# for each target.
if (NOT TARGET gcov)
add_custom_target(gcov)
endif (NOT TARGET gcov)
# This function will add gcov evaluation for target <TNAME>. Only sources of
# this target will be evaluated and no dependencies will be added. It will call
# Gcov on any source file of <TNAME> once and store the gcov file in the same
# directory.
function (add_gcov_target TNAME)
set(TDIR ${CMAKE_CURRENT_BINARY_DIR}/CMakeFiles/${TNAME}.dir)
# We don't have to check, if the target has support for coverage, thus this
# will be checked by add_coverage_target in Findcoverage.cmake. Instead we
# have to determine which gcov binary to use.
get_target_property(TSOURCES ${TNAME} SOURCES)
set(SOURCES "")
set(TCOMPILER "")
foreach (FILE ${TSOURCES})
codecov_path_of_source(${FILE} FILE)
if (NOT "${FILE}" STREQUAL "")
codecov_lang_of_source(${FILE} LANG)
if (NOT "${LANG}" STREQUAL "")
list(APPEND SOURCES "${FILE}")
set(TCOMPILER ${CMAKE_${LANG}_COMPILER_ID})
endif ()
endif ()
endforeach ()
# If no gcov binary was found, coverage data can't be evaluated.
if (NOT GCOV_${TCOMPILER}_BIN)
message(WARNING "No coverage evaluation binary found for ${TCOMPILER}.")
return()
endif ()
set(GCOV_BIN "${GCOV_${TCOMPILER}_BIN}")
set(GCOV_ENV "${GCOV_${TCOMPILER}_ENV}")
set(BUFFER "")
foreach(FILE ${SOURCES})
get_filename_component(FILE_PATH "${TDIR}/${FILE}" PATH)
# call gcov
add_custom_command(OUTPUT ${TDIR}/${FILE}.gcov
COMMAND ${GCOV_ENV} ${GCOV_BIN} ${TDIR}/${FILE}.gcno > /dev/null
DEPENDS ${TNAME} ${TDIR}/${FILE}.gcno
WORKING_DIRECTORY ${FILE_PATH}
)
list(APPEND BUFFER ${TDIR}/${FILE}.gcov)
endforeach()
# add target for gcov evaluation of <TNAME>
add_custom_target(${TNAME}-gcov DEPENDS ${BUFFER})
# add evaluation target to the global gcov target.
add_dependencies(gcov ${TNAME}-gcov)
endfunction (add_gcov_target)

View File

@ -0,0 +1,354 @@
# This file is part of CMake-codecov.
#
# Copyright (c)
# 2015-2017 RWTH Aachen University, Federal Republic of Germany
#
# See the LICENSE file in the package base directory for details
#
# Written by Alexander Haase, alexander.haase@rwth-aachen.de
#
# configuration
set(LCOV_DATA_PATH "${CMAKE_BINARY_DIR}/lcov/data")
set(LCOV_DATA_PATH_INIT "${LCOV_DATA_PATH}/init")
set(LCOV_DATA_PATH_CAPTURE "${LCOV_DATA_PATH}/capture")
set(LCOV_HTML_PATH "${CMAKE_BINARY_DIR}/lcov/html")
# Search for Gcov which is used by Lcov.
find_package(Gcov)
# This function will add lcov evaluation for target <TNAME>. Only sources of
# this target will be evaluated and no dependencies will be added. It will call
# geninfo on any source file of <TNAME> once and store the info file in the same
# directory.
#
# Note: This function is only a wrapper to define this function always, even if
# coverage is not supported by the compiler or disabled. This function must
# be defined here, because the module will be exited, if there is no coverage
# support by the compiler or it is disabled by the user.
function (add_lcov_target TNAME)
if (LCOV_FOUND)
# capture initial coverage data
lcov_capture_initial_tgt(${TNAME})
# capture coverage data after execution
lcov_capture_tgt(${TNAME})
endif ()
endfunction (add_lcov_target)
# include required Modules
include(FindPackageHandleStandardArgs)
# Search for required lcov binaries.
find_program(LCOV_BIN lcov)
find_program(GENINFO_BIN geninfo)
find_program(GENHTML_BIN genhtml)
find_package_handle_standard_args(lcov
REQUIRED_VARS LCOV_BIN GENINFO_BIN GENHTML_BIN
)
# enable genhtml C++ demangeling, if c++filt is found.
set(GENHTML_CPPFILT_FLAG "")
find_program(CPPFILT_BIN c++filt)
if (NOT CPPFILT_BIN STREQUAL "")
set(GENHTML_CPPFILT_FLAG "--demangle-cpp")
endif (NOT CPPFILT_BIN STREQUAL "")
# enable no-external flag for lcov, if available.
if (GENINFO_BIN AND NOT DEFINED GENINFO_EXTERN_FLAG)
set(FLAG "")
execute_process(COMMAND ${GENINFO_BIN} --help OUTPUT_VARIABLE GENINFO_HELP)
string(REGEX MATCH "external" GENINFO_RES "${GENINFO_HELP}")
if (GENINFO_RES)
set(FLAG "--no-external")
endif ()
set(GENINFO_EXTERN_FLAG "${FLAG}"
CACHE STRING "Geninfo flag to exclude system sources.")
endif ()
# If Lcov was not found, exit module now.
if (NOT LCOV_FOUND)
return()
endif (NOT LCOV_FOUND)
# Create directories to be used.
file(MAKE_DIRECTORY ${LCOV_DATA_PATH_INIT})
file(MAKE_DIRECTORY ${LCOV_DATA_PATH_CAPTURE})
set(LCOV_REMOVE_PATTERNS "")
# This function will merge lcov files to a single target file. Additional lcov
# flags may be set with setting LCOV_EXTRA_FLAGS before calling this function.
function (lcov_merge_files OUTFILE ...)
# Remove ${OUTFILE} from ${ARGV} and generate lcov parameters with files.
list(REMOVE_AT ARGV 0)
# Generate merged file.
string(REPLACE "${CMAKE_BINARY_DIR}/" "" FILE_REL "${OUTFILE}")
add_custom_command(OUTPUT "${OUTFILE}.raw"
COMMAND cat ${ARGV} > ${OUTFILE}.raw
DEPENDS ${ARGV}
COMMENT "Generating ${FILE_REL}"
)
add_custom_command(OUTPUT "${OUTFILE}"
COMMAND ${LCOV_BIN} --quiet -a ${OUTFILE}.raw --output-file ${OUTFILE}
--base-directory ${PROJECT_SOURCE_DIR} ${LCOV_EXTRA_FLAGS}
COMMAND ${LCOV_BIN} --quiet -r ${OUTFILE} ${LCOV_REMOVE_PATTERNS}
--output-file ${OUTFILE} ${LCOV_EXTRA_FLAGS}
DEPENDS ${OUTFILE}.raw
COMMENT "Post-processing ${FILE_REL}"
)
endfunction ()
# Add a new global target to generate initial coverage reports for all targets.
# This target will be used to generate the global initial info file, which is
# used to gather even empty report data.
if (NOT TARGET lcov-capture-init)
add_custom_target(lcov-capture-init)
set(LCOV_CAPTURE_INIT_FILES "" CACHE INTERNAL "")
endif (NOT TARGET lcov-capture-init)
# This function will add initial capture of coverage data for target <TNAME>,
# which is needed to get also data for objects, which were not loaded at
# execution time. It will call geninfo for every source file of <TNAME> once and
# store the info file in the same directory.
function (lcov_capture_initial_tgt TNAME)
# We don't have to check, if the target has support for coverage, thus this
# will be checked by add_coverage_target in Findcoverage.cmake. Instead we
# have to determine which gcov binary to use.
get_target_property(TSOURCES ${TNAME} SOURCES)
set(SOURCES "")
set(TCOMPILER "")
foreach (FILE ${TSOURCES})
codecov_path_of_source(${FILE} FILE)
if (NOT "${FILE}" STREQUAL "")
codecov_lang_of_source(${FILE} LANG)
if (NOT "${LANG}" STREQUAL "")
list(APPEND SOURCES "${FILE}")
set(TCOMPILER ${CMAKE_${LANG}_COMPILER_ID})
endif ()
endif ()
endforeach ()
# If no gcov binary was found, coverage data can't be evaluated.
if (NOT GCOV_${TCOMPILER}_BIN)
message(WARNING "No coverage evaluation binary found for ${TCOMPILER}.")
return()
endif ()
set(GCOV_BIN "${GCOV_${TCOMPILER}_BIN}")
set(GCOV_ENV "${GCOV_${TCOMPILER}_ENV}")
set(TDIR ${CMAKE_CURRENT_BINARY_DIR}/CMakeFiles/${TNAME}.dir)
set(GENINFO_FILES "")
foreach(FILE ${SOURCES})
# generate empty coverage files
set(OUTFILE "${TDIR}/${FILE}.info.init")
list(APPEND GENINFO_FILES ${OUTFILE})
add_custom_command(OUTPUT ${OUTFILE} COMMAND ${GCOV_ENV} ${GENINFO_BIN}
--quiet --base-directory ${PROJECT_SOURCE_DIR} --initial
--gcov-tool ${GCOV_BIN} --output-filename ${OUTFILE}
${GENINFO_EXTERN_FLAG} ${TDIR}/${FILE}.gcno
DEPENDS ${TNAME}
COMMENT "Capturing initial coverage data for ${FILE}"
)
endforeach()
# Concatenate all files generated by geninfo to a single file per target.
set(OUTFILE "${LCOV_DATA_PATH_INIT}/${TNAME}.info")
set(LCOV_EXTRA_FLAGS "--initial")
lcov_merge_files("${OUTFILE}" ${GENINFO_FILES})
add_custom_target(${TNAME}-capture-init ALL DEPENDS ${OUTFILE})
# add geninfo file generation to global lcov-geninfo target
add_dependencies(lcov-capture-init ${TNAME}-capture-init)
set(LCOV_CAPTURE_INIT_FILES "${LCOV_CAPTURE_INIT_FILES}"
"${OUTFILE}" CACHE INTERNAL ""
)
endfunction (lcov_capture_initial_tgt)
# This function will generate the global info file for all targets. It has to be
# called after all other CMake functions in the root CMakeLists.txt file, to get
# a full list of all targets that generate coverage data.
function (lcov_capture_initial)
# Skip this function (and do not create the following targets), if there are
# no input files.
if ("${LCOV_CAPTURE_INIT_FILES}" STREQUAL "")
return()
endif ()
# Add a new target to merge the files of all targets.
set(OUTFILE "${LCOV_DATA_PATH_INIT}/all_targets.info")
lcov_merge_files("${OUTFILE}" ${LCOV_CAPTURE_INIT_FILES})
add_custom_target(lcov-geninfo-init ALL DEPENDS ${OUTFILE}
lcov-capture-init
)
endfunction (lcov_capture_initial)
# Add a new global target to generate coverage reports for all targets. This
# target will be used to generate the global info file.
if (NOT TARGET lcov-capture)
add_custom_target(lcov-capture)
set(LCOV_CAPTURE_FILES "" CACHE INTERNAL "")
endif (NOT TARGET lcov-capture)
# This function will add capture of coverage data for target <TNAME>, which is
# needed to get also data for objects, which were not loaded at execution time.
# It will call geninfo for every source file of <TNAME> once and store the info
# file in the same directory.
function (lcov_capture_tgt TNAME)
# We don't have to check, if the target has support for coverage, thus this
# will be checked by add_coverage_target in Findcoverage.cmake. Instead we
# have to determine which gcov binary to use.
get_target_property(TSOURCES ${TNAME} SOURCES)
set(SOURCES "")
set(TCOMPILER "")
foreach (FILE ${TSOURCES})
codecov_path_of_source(${FILE} FILE)
if (NOT "${FILE}" STREQUAL "")
codecov_lang_of_source(${FILE} LANG)
if (NOT "${LANG}" STREQUAL "")
list(APPEND SOURCES "${FILE}")
set(TCOMPILER ${CMAKE_${LANG}_COMPILER_ID})
endif ()
endif ()
endforeach ()
# If no gcov binary was found, coverage data can't be evaluated.
if (NOT GCOV_${TCOMPILER}_BIN)
message(WARNING "No coverage evaluation binary found for ${TCOMPILER}.")
return()
endif ()
set(GCOV_BIN "${GCOV_${TCOMPILER}_BIN}")
set(GCOV_ENV "${GCOV_${TCOMPILER}_ENV}")
set(TDIR ${CMAKE_CURRENT_BINARY_DIR}/CMakeFiles/${TNAME}.dir)
set(GENINFO_FILES "")
foreach(FILE ${SOURCES})
# Generate coverage files. If no .gcda file was generated during
# execution, the empty coverage file will be used instead.
set(OUTFILE "${TDIR}/${FILE}.info")
list(APPEND GENINFO_FILES ${OUTFILE})
add_custom_command(OUTPUT ${OUTFILE}
COMMAND test -f "${TDIR}/${FILE}.gcda"
&& ${GCOV_ENV} ${GENINFO_BIN} --quiet --base-directory
${PROJECT_SOURCE_DIR} --gcov-tool ${GCOV_BIN}
--output-filename ${OUTFILE} ${GENINFO_EXTERN_FLAG}
${TDIR}/${FILE}.gcda
|| cp ${OUTFILE}.init ${OUTFILE}
DEPENDS ${TNAME} ${TNAME}-capture-init
COMMENT "Capturing coverage data for ${FILE}"
)
endforeach()
# Concatenate all files generated by geninfo to a single file per target.
set(OUTFILE "${LCOV_DATA_PATH_CAPTURE}/${TNAME}.info")
lcov_merge_files("${OUTFILE}" ${GENINFO_FILES})
add_custom_target(${TNAME}-geninfo DEPENDS ${OUTFILE})
# add geninfo file generation to global lcov-capture target
add_dependencies(lcov-capture ${TNAME}-geninfo)
set(LCOV_CAPTURE_FILES "${LCOV_CAPTURE_FILES}" "${OUTFILE}" CACHE INTERNAL
""
)
# Add target for generating html output for this target only.
file(MAKE_DIRECTORY ${LCOV_HTML_PATH}/${TNAME})
add_custom_target(${TNAME}-genhtml
COMMAND ${GENHTML_BIN} --quiet --sort --prefix ${PROJECT_SOURCE_DIR}
--baseline-file ${LCOV_DATA_PATH_INIT}/${TNAME}.info
--output-directory ${LCOV_HTML_PATH}/${TNAME}
--title "${CMAKE_PROJECT_NAME} - target ${TNAME}"
${GENHTML_CPPFILT_FLAG} ${OUTFILE}
DEPENDS ${TNAME}-geninfo ${TNAME}-capture-init
)
endfunction (lcov_capture_tgt)
# This function will generate the global info file for all targets. It has to be
# called after all other CMake functions in the root CMakeLists.txt file, to get
# a full list of all targets that generate coverage data.
function (lcov_capture)
# Skip this function (and do not create the following targets), if there are
# no input files.
if ("${LCOV_CAPTURE_FILES}" STREQUAL "")
return()
endif ()
# Add a new target to merge the files of all targets.
set(OUTFILE "${LCOV_DATA_PATH_CAPTURE}/all_targets.info")
lcov_merge_files("${OUTFILE}" ${LCOV_CAPTURE_FILES})
add_custom_target(lcov-geninfo DEPENDS ${OUTFILE} lcov-capture)
# Add a new global target for all lcov targets. This target could be used to
# generate the lcov html output for the whole project instead of calling
# <TARGET>-geninfo and <TARGET>-genhtml for each target. It will also be
# used to generate a html site for all project data together instead of one
# for each target.
if (NOT TARGET lcov)
file(MAKE_DIRECTORY ${LCOV_HTML_PATH}/all_targets)
add_custom_target(lcov
COMMAND ${GENHTML_BIN} --quiet --sort
--baseline-file ${LCOV_DATA_PATH_INIT}/all_targets.info
--output-directory ${LCOV_HTML_PATH}/all_targets
--title "${CMAKE_PROJECT_NAME}" --prefix "${PROJECT_SOURCE_DIR}"
${GENHTML_CPPFILT_FLAG} ${OUTFILE}
DEPENDS lcov-geninfo-init lcov-geninfo
)
endif ()
endfunction (lcov_capture)
# Add a new global target to generate the lcov html report for the whole project
# instead of calling <TARGET>-genhtml for each target (to create an own report
# for each target). Instead of the lcov target it does not require geninfo for
# all targets, so you have to call <TARGET>-geninfo to generate the info files
# the targets you'd like to have in your report or lcov-geninfo for generating
# info files for all targets before calling lcov-genhtml.
file(MAKE_DIRECTORY ${LCOV_HTML_PATH}/selected_targets)
if (NOT TARGET lcov-genhtml)
add_custom_target(lcov-genhtml
COMMAND ${GENHTML_BIN}
--quiet
--output-directory ${LCOV_HTML_PATH}/selected_targets
--title \"${CMAKE_PROJECT_NAME} - targets `find
${LCOV_DATA_PATH_CAPTURE} -name \"*.info\" ! -name
\"all_targets.info\" -exec basename {} .info \\\;`\"
--prefix ${PROJECT_SOURCE_DIR}
--sort
${GENHTML_CPPFILT_FLAG}
`find ${LCOV_DATA_PATH_CAPTURE} -name \"*.info\" ! -name
\"all_targets.info\"`
)
endif (NOT TARGET lcov-genhtml)

View File

@ -0,0 +1,258 @@
# This file is part of CMake-codecov.
#
# Copyright (c)
# 2015-2017 RWTH Aachen University, Federal Republic of Germany
#
# See the LICENSE file in the package base directory for details
#
# Written by Alexander Haase, alexander.haase@rwth-aachen.de
#
# Add an option to choose, if coverage should be enabled or not. If enabled
# marked targets will be build with coverage support and appropriate targets
# will be added. If disabled coverage will be ignored for *ALL* targets.
option(ENABLE_COVERAGE "Enable coverage build." OFF)
set(COVERAGE_FLAG_CANDIDATES
# gcc and clang
"-O0 -g -fprofile-arcs -ftest-coverage"
# gcc and clang fallback
"-O0 -g --coverage"
)
# Add coverage support for target ${TNAME} and register target for coverage
# evaluation. If coverage is disabled or not supported, this function will
# simply do nothing.
#
# Note: This function is only a wrapper to define this function always, even if
# coverage is not supported by the compiler or disabled. This function must
# be defined here, because the module will be exited, if there is no coverage
# support by the compiler or it is disabled by the user.
function (add_coverage TNAME)
# only add coverage for target, if coverage is support and enabled.
if (ENABLE_COVERAGE)
foreach (TNAME ${ARGV})
add_coverage_target(${TNAME})
endforeach ()
endif ()
endfunction (add_coverage)
# Add global target to gather coverage information after all targets have been
# added. Other evaluation functions could be added here, after checks for the
# specific module have been passed.
#
# Note: This function is only a wrapper to define this function always, even if
# coverage is not supported by the compiler or disabled. This function must
# be defined here, because the module will be exited, if there is no coverage
# support by the compiler or it is disabled by the user.
function (coverage_evaluate)
# add lcov evaluation
if (LCOV_FOUND)
lcov_capture_initial()
lcov_capture()
endif (LCOV_FOUND)
endfunction ()
# Exit this module, if coverage is disabled. add_coverage is defined before this
# return, so this module can be exited now safely without breaking any build-
# scripts.
if (NOT ENABLE_COVERAGE)
return()
endif ()
# Find the reuired flags foreach language.
set(CMAKE_REQUIRED_QUIET_SAVE ${CMAKE_REQUIRED_QUIET})
set(CMAKE_REQUIRED_QUIET ${codecov_FIND_QUIETLY})
get_property(ENABLED_LANGUAGES GLOBAL PROPERTY ENABLED_LANGUAGES)
foreach (LANG ${ENABLED_LANGUAGES})
# Coverage flags are not dependent on language, but the used compiler. So
# instead of searching flags foreach language, search flags foreach compiler
# used.
set(COMPILER ${CMAKE_${LANG}_COMPILER_ID})
if (NOT COVERAGE_${COMPILER}_FLAGS)
foreach (FLAG ${COVERAGE_FLAG_CANDIDATES})
if(NOT CMAKE_REQUIRED_QUIET)
message(STATUS "Try ${COMPILER} code coverage flag = [${FLAG}]")
endif()
set(CMAKE_REQUIRED_FLAGS "${FLAG}")
unset(COVERAGE_FLAG_DETECTED CACHE)
if (${LANG} STREQUAL "C")
include(CheckCCompilerFlag)
check_c_compiler_flag("${FLAG}" COVERAGE_FLAG_DETECTED)
elseif (${LANG} STREQUAL "CXX")
include(CheckCXXCompilerFlag)
check_cxx_compiler_flag("${FLAG}" COVERAGE_FLAG_DETECTED)
elseif (${LANG} STREQUAL "Fortran")
# CheckFortranCompilerFlag was introduced in CMake 3.x. To be
# compatible with older Cmake versions, we will check if this
# module is present before we use it. Otherwise we will define
# Fortran coverage support as not available.
include(CheckFortranCompilerFlag OPTIONAL
RESULT_VARIABLE INCLUDED)
if (INCLUDED)
check_fortran_compiler_flag("${FLAG}"
COVERAGE_FLAG_DETECTED)
elseif (NOT CMAKE_REQUIRED_QUIET)
message("-- Performing Test COVERAGE_FLAG_DETECTED")
message("-- Performing Test COVERAGE_FLAG_DETECTED - Failed"
" (Check not supported)")
endif ()
endif()
if (COVERAGE_FLAG_DETECTED)
set(COVERAGE_${COMPILER}_FLAGS "${FLAG}"
CACHE STRING "${COMPILER} flags for code coverage.")
mark_as_advanced(COVERAGE_${COMPILER}_FLAGS)
break()
else ()
message(WARNING "Code coverage is not available for ${COMPILER}"
" compiler. Targets using this compiler will be "
"compiled without it.")
endif ()
endforeach ()
endif ()
endforeach ()
set(CMAKE_REQUIRED_QUIET ${CMAKE_REQUIRED_QUIET_SAVE})
# Helper function to get the language of a source file.
function (codecov_lang_of_source FILE RETURN_VAR)
get_filename_component(FILE_EXT "${FILE}" EXT)
string(TOLOWER "${FILE_EXT}" FILE_EXT)
string(SUBSTRING "${FILE_EXT}" 1 -1 FILE_EXT)
get_property(ENABLED_LANGUAGES GLOBAL PROPERTY ENABLED_LANGUAGES)
foreach (LANG ${ENABLED_LANGUAGES})
list(FIND CMAKE_${LANG}_SOURCE_FILE_EXTENSIONS "${FILE_EXT}" TEMP)
if (NOT ${TEMP} EQUAL -1)
set(${RETURN_VAR} "${LANG}" PARENT_SCOPE)
return()
endif ()
endforeach()
set(${RETURN_VAR} "" PARENT_SCOPE)
endfunction ()
# Helper function to get the relative path of the source file destination path.
# This path is needed by FindGcov and FindLcov cmake files to locate the
# captured data.
function (codecov_path_of_source FILE RETURN_VAR)
string(REGEX MATCH "TARGET_OBJECTS:([^ >]+)" _source ${FILE})
# If expression was found, SOURCEFILE is a generator-expression for an
# object library. Currently we found no way to call this function automatic
# for the referenced target, so it must be called in the directoryso of the
# object library definition.
if (NOT "${_source}" STREQUAL "")
set(${RETURN_VAR} "" PARENT_SCOPE)
return()
endif ()
string(REPLACE "${CMAKE_CURRENT_BINARY_DIR}/" "" FILE "${FILE}")
if(IS_ABSOLUTE ${FILE})
file(RELATIVE_PATH FILE ${CMAKE_CURRENT_SOURCE_DIR} ${FILE})
endif()
# get the right path for file
string(REPLACE ".." "__" PATH "${FILE}")
set(${RETURN_VAR} "${PATH}" PARENT_SCOPE)
endfunction()
# Add coverage support for target ${TNAME} and register target for coverage
# evaluation.
function(add_coverage_target TNAME)
# Check if all sources for target use the same compiler. If a target uses
# e.g. C and Fortran mixed and uses different compilers (e.g. clang and
# gfortran) this can trigger huge problems, because different compilers may
# use different implementations for code coverage.
get_target_property(TSOURCES ${TNAME} SOURCES)
set(TARGET_COMPILER "")
set(ADDITIONAL_FILES "")
foreach (FILE ${TSOURCES})
# If expression was found, FILE is a generator-expression for an object
# library. Object libraries will be ignored.
string(REGEX MATCH "TARGET_OBJECTS:([^ >]+)" _file ${FILE})
if ("${_file}" STREQUAL "")
codecov_lang_of_source(${FILE} LANG)
if (LANG)
list(APPEND TARGET_COMPILER ${CMAKE_${LANG}_COMPILER_ID})
list(APPEND ADDITIONAL_FILES "${FILE}.gcno")
list(APPEND ADDITIONAL_FILES "${FILE}.gcda")
endif ()
endif ()
endforeach ()
list(REMOVE_DUPLICATES TARGET_COMPILER)
list(LENGTH TARGET_COMPILER NUM_COMPILERS)
if (NUM_COMPILERS GREATER 1)
message(WARNING "Can't use code coverage for target ${TNAME}, because "
"it will be compiled by incompatible compilers. Target will be "
"compiled without code coverage.")
return()
elseif (NUM_COMPILERS EQUAL 0)
message(WARNING "Can't use code coverage for target ${TNAME}, because "
"it uses an unknown compiler. Target will be compiled without "
"code coverage.")
return()
elseif (NOT DEFINED "COVERAGE_${TARGET_COMPILER}_FLAGS")
# A warning has been printed before, so just return if flags for this
# compiler aren't available.
return()
endif()
# enable coverage for target
set_property(TARGET ${TNAME} APPEND_STRING
PROPERTY COMPILE_FLAGS " ${COVERAGE_${TARGET_COMPILER}_FLAGS}")
set_property(TARGET ${TNAME} APPEND_STRING
PROPERTY LINK_FLAGS " ${COVERAGE_${TARGET_COMPILER}_FLAGS}")
# Add gcov files generated by compiler to clean target.
set(CLEAN_FILES "")
foreach (FILE ${ADDITIONAL_FILES})
codecov_path_of_source(${FILE} FILE)
list(APPEND CLEAN_FILES "CMakeFiles/${TNAME}.dir/${FILE}")
endforeach()
set_directory_properties(PROPERTIES ADDITIONAL_MAKE_CLEAN_FILES
"${CLEAN_FILES}")
add_gcov_target(${TNAME})
add_lcov_target(${TNAME})
endfunction(add_coverage_target)
# Include modules for parsing the collected data and output it in a readable
# format (like gcov and lcov).
find_package(Gcov)
find_package(Lcov)

View File

@ -0,0 +1,10 @@
includedir=@CMAKE_INSTALL_FULL_INCLUDEDIR@
libdir=@CMAKE_INSTALL_FULL_LIBDIR@
pkg_version=@Catch2_VERSION@
Name: Catch2-With-Main
Description: A modern, C++-native test framework for C++14 and above (links in default main)
Version: ${pkg_version}
Requires: catch2 = ${pkg_version}
Cflags: -I${includedir}
Libs: -L${libdir} -lCatch2Main

View File

@ -0,0 +1,11 @@
prefix=@CMAKE_INSTALL_PREFIX@
exec_prefix=${prefix}
includedir=@CMAKE_INSTALL_FULL_INCLUDEDIR@
libdir=@CMAKE_INSTALL_FULL_LIBDIR@
Name: Catch2
Description: A modern, C++-native, test framework for C++14 and above
URL: https://github.com/catchorg/Catch2
Version: @Catch2_VERSION@
Cflags: -I${includedir}
Libs: -L${libdir} -lCatch2

View File

@ -0,0 +1,56 @@
#!/bin/sh
# This file is part of CMake-codecov.
#
# Copyright (c)
# 2015-2017 RWTH Aachen University, Federal Republic of Germany
#
# See the LICENSE file in the package base directory for details
#
# Written by Alexander Haase, alexander.haase@rwth-aachen.de
#
if [ -z "$LLVM_COV_BIN" ]
then
echo "LLVM_COV_BIN not set!" >& 2
exit 1
fi
# Get LLVM version to find out.
LLVM_VERSION=$($LLVM_COV_BIN -version | grep -i "LLVM version" \
| sed "s/^\([A-Za-z ]*\)\([0-9]\).\([0-9]\).*$/\2.\3/g")
if [ "$1" = "-v" ]
then
echo "llvm-cov-wrapper $LLVM_VERSION"
exit 0
fi
if [ -n "$LLVM_VERSION" ]
then
MAJOR=$(echo $LLVM_VERSION | cut -d'.' -f1)
MINOR=$(echo $LLVM_VERSION | cut -d'.' -f2)
if [ $MAJOR -eq 3 ] && [ $MINOR -le 4 ]
then
if [ -f "$1" ]
then
filename=$(basename "$1")
extension="${filename##*.}"
case "$extension" in
"gcno") exec $LLVM_COV_BIN --gcno="$1" ;;
"gcda") exec $LLVM_COV_BIN --gcda="$1" ;;
esac
fi
fi
if [ $MAJOR -eq 3 ] && [ $MINOR -le 5 ]
then
exec $LLVM_COV_BIN $@
fi
fi
exec $LLVM_COV_BIN gcov $@

View File

@ -0,0 +1,201 @@
cmake_minimum_required(VERSION 3.10)
# detect if Catch is being bundled,
# disable testsuite in that case
if(NOT DEFINED PROJECT_NAME)
set(NOT_SUBPROJECT ON)
else()
set(NOT_SUBPROJECT OFF)
endif()
option(CATCH_INSTALL_DOCS "Install documentation alongside library" ON)
option(CATCH_INSTALL_EXTRAS "Install extras (CMake scripts, debugger helpers) alongside library" ON)
option(CATCH_DEVELOPMENT_BUILD "Build tests, enable warnings, enable Werror, etc" OFF)
option(CATCH_ENABLE_REPRODUCIBLE_BUILD "Add compiler flags for improving build reproducibility" ON)
include(CMakeDependentOption)
cmake_dependent_option(CATCH_BUILD_TESTING "Build the SelfTest project" ON "CATCH_DEVELOPMENT_BUILD" OFF)
cmake_dependent_option(CATCH_BUILD_EXAMPLES "Build code examples" OFF "CATCH_DEVELOPMENT_BUILD" OFF)
cmake_dependent_option(CATCH_BUILD_EXTRA_TESTS "Build extra tests" OFF "CATCH_DEVELOPMENT_BUILD" OFF)
cmake_dependent_option(CATCH_BUILD_FUZZERS "Build fuzzers" OFF "CATCH_DEVELOPMENT_BUILD" OFF)
cmake_dependent_option(CATCH_ENABLE_COVERAGE "Generate coverage for codecov.io" OFF "CATCH_DEVELOPMENT_BUILD" OFF)
cmake_dependent_option(CATCH_ENABLE_WERROR "Enables Werror during build" ON "CATCH_DEVELOPMENT_BUILD" OFF)
cmake_dependent_option(CATCH_BUILD_SURROGATES "Enable generating and building surrogate TUs for the main headers" OFF "CATCH_DEVELOPMENT_BUILD" OFF)
cmake_dependent_option(CATCH_ENABLE_CONFIGURE_TESTS "Enable CMake configuration tests. WARNING: VERY EXPENSIVE" OFF "CATCH_DEVELOPMENT_BUILD" OFF)
cmake_dependent_option(CATCH_ENABLE_CMAKE_HELPER_TESTS "Enable CMake helper tests. WARNING: VERY EXPENSIVE" OFF "CATCH_DEVELOPMENT_BUILD" OFF)
# Catch2's build breaks if done in-tree. You probably should not build
# things in tree anyway, but we can allow projects that include Catch2
# as a subproject to build in-tree as long as it is not in our tree.
if (CMAKE_BINARY_DIR STREQUAL CMAKE_CURRENT_SOURCE_DIR)
message(FATAL_ERROR "Building in-source is not supported! Create a build dir and remove ${CMAKE_SOURCE_DIR}/CMakeCache.txt")
endif()
project(Catch2
VERSION 3.7.1 # CML version placeholder, don't delete
LANGUAGES CXX
# HOMEPAGE_URL is not supported until CMake version 3.12, which
# we do not target yet.
# HOMEPAGE_URL "https://github.com/catchorg/Catch2"
DESCRIPTION "A modern, C++-native, unit test framework."
)
# Provide path for scripts. We first add path to the scripts we don't use,
# but projects including us might, and set the path up to parent scope.
# Then we also add path that we use to configure the project, but is of
# no use to top level projects.
list(APPEND CMAKE_MODULE_PATH "${CMAKE_CURRENT_LIST_DIR}/extras")
if (NOT NOT_SUBPROJECT)
set(CMAKE_MODULE_PATH "${CMAKE_MODULE_PATH}" PARENT_SCOPE)
endif()
list(APPEND CMAKE_MODULE_PATH "${CMAKE_CURRENT_LIST_DIR}/CMake")
include(GNUInstallDirs)
include(CMakePackageConfigHelpers)
include(CatchConfigOptions)
if(CATCH_DEVELOPMENT_BUILD)
include(CTest)
endif()
# This variable is used in some subdirectories, so we need it here, rather
# than later in the install block
set(CATCH_CMAKE_CONFIG_DESTINATION "${CMAKE_INSTALL_LIBDIR}/cmake/Catch2")
# We have some Windows builds that test `wmain` entry point,
# and we need this change to be present in all binaries that
# are built during these tests, so this is required here, before
# the subdirectories are added.
if(CATCH_TEST_USE_WMAIN)
set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} /ENTRY:wmainCRTStartup")
endif()
# Basic paths
set(CATCH_DIR ${CMAKE_CURRENT_SOURCE_DIR})
set(SOURCES_DIR ${CATCH_DIR}/src/catch2)
set(SELF_TEST_DIR ${CATCH_DIR}/tests/SelfTest)
# We need to bring-in the variables defined there to this scope
add_subdirectory(src)
# Build tests only if requested
if (BUILD_TESTING AND CATCH_BUILD_TESTING AND NOT_SUBPROJECT)
find_package(PythonInterp 3 REQUIRED)
if (NOT PYTHONINTERP_FOUND)
message(FATAL_ERROR "Python not found, but required for tests")
endif()
add_subdirectory(tests)
endif()
if(CATCH_BUILD_EXAMPLES)
add_subdirectory(examples)
endif()
if(CATCH_BUILD_EXTRA_TESTS)
add_subdirectory(tests/ExtraTests)
endif()
if(CATCH_BUILD_FUZZERS)
add_subdirectory(fuzzing)
endif()
if (CATCH_DEVELOPMENT_BUILD)
add_warnings_to_targets("${CATCH_WARNING_TARGETS}")
endif()
# Only perform the installation steps when Catch is not being used as
# a subproject via `add_subdirectory`, or the destinations will break,
# see https://github.com/catchorg/Catch2/issues/1373
if (NOT_SUBPROJECT)
configure_package_config_file(
${CMAKE_CURRENT_LIST_DIR}/CMake/Catch2Config.cmake.in
${CMAKE_CURRENT_BINARY_DIR}/Catch2Config.cmake
INSTALL_DESTINATION
${CATCH_CMAKE_CONFIG_DESTINATION}
)
write_basic_package_version_file(
"${CMAKE_CURRENT_BINARY_DIR}/Catch2ConfigVersion.cmake"
COMPATIBILITY
SameMajorVersion
)
install(
FILES
"${CMAKE_CURRENT_BINARY_DIR}/Catch2Config.cmake"
"${CMAKE_CURRENT_BINARY_DIR}/Catch2ConfigVersion.cmake"
DESTINATION
${CATCH_CMAKE_CONFIG_DESTINATION}
)
# Install documentation
if(CATCH_INSTALL_DOCS)
install(
DIRECTORY
docs/
DESTINATION
"${CMAKE_INSTALL_DOCDIR}"
PATTERN "doxygen" EXCLUDE
)
endif()
if(CATCH_INSTALL_EXTRAS)
# Install CMake scripts
install(
FILES
"extras/ParseAndAddCatchTests.cmake"
"extras/Catch.cmake"
"extras/CatchAddTests.cmake"
"extras/CatchShardTests.cmake"
"extras/CatchShardTestsImpl.cmake"
DESTINATION
${CATCH_CMAKE_CONFIG_DESTINATION}
)
# Install debugger helpers
install(
FILES
"extras/gdbinit"
"extras/lldbinit"
DESTINATION
${CMAKE_INSTALL_DATAROOTDIR}/Catch2
)
endif()
## Provide some pkg-config integration
set(PKGCONFIG_INSTALL_DIR
"${CMAKE_INSTALL_DATAROOTDIR}/pkgconfig"
CACHE PATH "Path where catch2.pc is installed"
)
configure_file(
${CMAKE_CURRENT_SOURCE_DIR}/CMake/catch2.pc.in
${CMAKE_CURRENT_BINARY_DIR}/catch2.pc
@ONLY
)
configure_file(
${CMAKE_CURRENT_SOURCE_DIR}/CMake/catch2-with-main.pc.in
${CMAKE_CURRENT_BINARY_DIR}/catch2-with-main.pc
@ONLY
)
install(
FILES
"${CMAKE_CURRENT_BINARY_DIR}/catch2.pc"
"${CMAKE_CURRENT_BINARY_DIR}/catch2-with-main.pc"
DESTINATION
${PKGCONFIG_INSTALL_DIR}
)
# CPack/CMake started taking the package version from project version 3.12
# So we need to set the version manually for older CMake versions
if(${CMAKE_VERSION} VERSION_LESS "3.12.0")
set(CPACK_PACKAGE_VERSION ${PROJECT_VERSION})
endif()
set(CPACK_PACKAGE_CONTACT "https://github.com/catchorg/Catch2/")
include( CPack )
endif()

View File

@ -0,0 +1,26 @@
{
"version": 3,
"configurePresets": [
{
"name": "basic-tests",
"displayName": "Basic development build",
"description": "Enables development build with basic tests that are cheap to build and run",
"cacheVariables": {
"CATCH_DEVELOPMENT_BUILD": "ON"
}
},
{
"name": "all-tests",
"inherits": "basic-tests",
"displayName": "Full development build",
"description": "Enables development build with examples and ALL tests",
"cacheVariables": {
"CATCH_BUILD_EXAMPLES": "ON",
"CATCH_BUILD_EXTRA_TESTS": "ON",
"CATCH_BUILD_SURROGATES": "ON",
"CATCH_ENABLE_CONFIGURE_TESTS": "ON",
"CATCH_ENABLE_CMAKE_HELPER_TESTS": "ON"
}
}
]
}

View File

@ -0,0 +1,46 @@
# Contributor Covenant Code of Conduct
## Our Pledge
In the interest of fostering an open and welcoming environment, we as contributors and maintainers pledge to making participation in our project and our community a harassment-free experience for everyone, regardless of age, body size, disability, ethnicity, gender identity and expression, level of experience, nationality, personal appearance, race, religion, or sexual identity and orientation.
## Our Standards
Examples of behavior that contributes to creating a positive environment include:
* Using welcoming and inclusive language
* Being respectful of differing viewpoints and experiences
* Gracefully accepting constructive criticism
* Focusing on what is best for the community
* Showing empathy towards other community members
Examples of unacceptable behavior by participants include:
* The use of sexualized language or imagery and unwelcome sexual attention or advances
* Trolling, insulting/derogatory comments, and personal or political attacks
* Public or private harassment
* Publishing others' private information, such as a physical or electronic address, without explicit permission
* Other conduct which could reasonably be considered inappropriate in a professional setting
## Our Responsibilities
Project maintainers are responsible for clarifying the standards of acceptable behavior and are expected to take appropriate and fair corrective action in response to any instances of unacceptable behavior.
Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, or to ban temporarily or permanently any contributor for other behaviors that they deem inappropriate, threatening, offensive, or harmful.
## Scope
This Code of Conduct applies both within project spaces and in public spaces when an individual is representing the project or its community. Examples of representing a project or community include using an official project e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. Representation of a project may be further defined and clarified by project maintainers.
## Enforcement
Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting the project team at github@philnash.me. The project team will review and investigate all complaints, and will respond in a way that it deems appropriate to the circumstances. The project team is obligated to maintain confidentiality with regard to the reporter of an incident. Further details of specific enforcement policies may be posted separately.
Project maintainers who do not follow or enforce the Code of Conduct in good faith may face temporary or permanent repercussions as determined by other members of the project's leadership.
## Attribution
This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, available at [http://contributor-covenant.org/version/1/4][version]
[homepage]: http://contributor-covenant.org
[version]: http://contributor-covenant.org/version/1/4/

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,23 @@
Boost Software License - Version 1.0 - August 17th, 2003
Permission is hereby granted, free of charge, to any person or organization
obtaining a copy of the software and accompanying documentation covered by
this license (the "Software") to use, reproduce, display, distribute,
execute, and transmit the Software, and to prepare derivative works of the
Software, and to permit third-parties to whom the Software is furnished to
do so, all subject to the following:
The copyright notices in the Software and this entire statement, including
the above license grant, this restriction and the following disclaimer,
must be included in all copies of the Software, in whole or in part, and
all derivative works of the Software, unless such copies or derivative
works are solely in the form of machine-executable object code generated by
a source language processor.
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, TITLE AND NON-INFRINGEMENT. IN NO EVENT
SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.

View File

@ -0,0 +1,3 @@
module(name = "catch2")
bazel_dep(name = "bazel_skylib", version = "1.7.1")

View File

@ -0,0 +1,103 @@
<a id="top"></a>
![Catch2 logo](data/artwork/catch2-logo-small-with-background.png)
[![Github Releases](https://img.shields.io/github/release/catchorg/catch2.svg)](https://github.com/catchorg/catch2/releases)
[![Linux build status](https://github.com/catchorg/Catch2/actions/workflows/linux-simple-builds.yml/badge.svg)](https://github.com/catchorg/Catch2/actions/workflows/linux-simple-builds.yml)
[![Linux build status](https://github.com/catchorg/Catch2/actions/workflows/linux-other-builds.yml/badge.svg)](https://github.com/catchorg/Catch2/actions/workflows/linux-other-builds.yml)
[![MacOS build status](https://github.com/catchorg/Catch2/actions/workflows/mac-builds.yml/badge.svg)](https://github.com/catchorg/Catch2/actions/workflows/mac-builds.yml)
[![Build Status](https://ci.appveyor.com/api/projects/status/github/catchorg/Catch2?svg=true&branch=devel)](https://ci.appveyor.com/project/catchorg/catch2)
[![Code Coverage](https://codecov.io/gh/catchorg/Catch2/branch/devel/graph/badge.svg)](https://codecov.io/gh/catchorg/Catch2)
[![Try online](https://img.shields.io/badge/try-online-blue.svg)](https://godbolt.org/z/EdoY15q9G)
[![Join the chat in Discord: https://discord.gg/4CWS9zD](https://img.shields.io/badge/Discord-Chat!-brightgreen.svg)](https://discord.gg/4CWS9zD)
## What is Catch2?
Catch2 is mainly a unit testing framework for C++, but it also
provides basic micro-benchmarking features, and simple BDD macros.
Catch2's main advantage is that using it is both simple and natural.
Test names do not have to be valid identifiers, assertions look like
normal C++ boolean expressions, and sections provide a nice and local way
to share set-up and tear-down code in tests.
**Example unit test**
```cpp
#include <catch2/catch_test_macros.hpp>
#include <cstdint>
uint32_t factorial( uint32_t number ) {
return number <= 1 ? number : factorial(number-1) * number;
}
TEST_CASE( "Factorials are computed", "[factorial]" ) {
REQUIRE( factorial( 1) == 1 );
REQUIRE( factorial( 2) == 2 );
REQUIRE( factorial( 3) == 6 );
REQUIRE( factorial(10) == 3'628'800 );
}
```
**Example microbenchmark**
```cpp
#include <catch2/catch_test_macros.hpp>
#include <catch2/benchmark/catch_benchmark.hpp>
#include <cstdint>
uint64_t fibonacci(uint64_t number) {
return number < 2 ? number : fibonacci(number - 1) + fibonacci(number - 2);
}
TEST_CASE("Benchmark Fibonacci", "[!benchmark]") {
REQUIRE(fibonacci(5) == 5);
REQUIRE(fibonacci(20) == 6'765);
BENCHMARK("fibonacci 20") {
return fibonacci(20);
};
REQUIRE(fibonacci(25) == 75'025);
BENCHMARK("fibonacci 25") {
return fibonacci(25);
};
}
```
_Note that benchmarks are not run by default, so you need to run it explicitly
with the `[!benchmark]` tag._
## Catch2 v3 has been released!
You are on the `devel` branch, where the v3 version is being developed.
v3 brings a bunch of significant changes, the big one being that Catch2
is no longer a single-header library. Catch2 now behaves as a normal
library, with multiple headers and separately compiled implementation.
The documentation is slowly being updated to take these changes into
account, but this work is currently still ongoing.
For migrating from the v2 releases to v3, you should look at [our
documentation](docs/migrate-v2-to-v3.md#top). It provides a simple
guidelines on getting started, and collects most common migration
problems.
For the previous major version of Catch2 [look into the `v2.x` branch
here on GitHub](https://github.com/catchorg/Catch2/tree/v2.x).
## How to use it
This documentation comprises these three parts:
* [Why do we need yet another C++ Test Framework?](docs/why-catch.md#top)
* [Tutorial](docs/tutorial.md#top) - getting started
* [Reference section](docs/Readme.md#top) - all the details
## More
* Issues and bugs can be raised on the [Issue tracker on GitHub](https://github.com/catchorg/Catch2/issues)
* For discussion or questions please use [our Discord](https://discord.gg/4CWS9zD)
* See who else is using Catch2 in [Open Source Software](docs/opensource-users.md#top)
or [commercially](docs/commercial-users.md#top).

View File

@ -0,0 +1,19 @@
# Security Policy
## Supported Versions
* Versions 1.x (branch Catch1.x) are no longer supported.
* Versions 2.x (branch v2.x) are currently supported.
* `devel` branch serves for stable-ish development and is supported,
but branches `devel-*` are considered short lived and are not supported separately.
## Reporting a Vulnerability
Due to its nature as a _unit_ test framework, Catch2 shouldn't interact
with untrusted inputs and there shouldn't be many security vulnerabilities
in it.
However, if you find one you send email to martin <dot> horenovsky <at>
gmail <dot> com. If you want to encrypt the email, my pgp key is
`E29C 46F3 B8A7 5028 6079 3B7D ECC9 C20E 314B 2360`.

View File

@ -0,0 +1,16 @@
workspace(name = "catch2")
load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive")
http_archive(
name = "bazel_skylib",
sha256 = "bc283cdfcd526a52c3201279cda4bc298652efa898b10b4db0837dc51652756f",
urls = [
"https://mirror.bazel.build/github.com/bazelbuild/bazel-skylib/releases/download/1.7.1/bazel-skylib-1.7.1.tar.gz",
"https://github.com/bazelbuild/bazel-skylib/releases/download/1.7.1/bazel-skylib-1.7.1.tar.gz",
],
)
load("@bazel_skylib//:workspace.bzl", "bazel_skylib_workspace")
bazel_skylib_workspace()

View File

@ -0,0 +1,83 @@
version: "{build}-{branch}"
# If we ever get a backlog larger than clone_depth, builds will fail
# spuriously. I do not think we will ever get 20 deep commits deep though.
clone_depth: 20
# We want to build everything, except for branches that are explicitly
# for messing around with Github Actions.
branches:
except:
- /devel-gha.+/
# We need a more up to date pip because Python 2.7 is EOL soon
init:
- set PATH=C:\Python35;C:\Python35\Scripts;%PATH%
install:
- ps: if (($env:CONFIGURATION) -eq "Debug" -And ($env:coverage) -eq "1" ) { pip --disable-pip-version-check install codecov }
# This removes our changes to PATH. Keep this step last!
- ps: if (($env:CONFIGURATION) -eq "Debug" -And ($env:coverage) -eq "1" ) { .\tools\misc\installOpenCppCoverage.ps1 }
before_build:
# We need to modify PATH again, because it was reset since the "init" step
- set PATH=C:\Python35;C:\Python35\Scripts;%PATH%
- set CXXFLAGS=%additional_flags%
# If we are building examples/extra-tests, we need to regenerate the amalgamated files
- cmd: if "%examples%"=="1" ( python .\tools\scripts\generateAmalgamatedFiles.py )
# Indirection because appveyor doesn't handle multiline batch scripts properly
# https://stackoverflow.com/questions/37627248/how-to-split-a-command-over-multiple-lines-in-appveyor-yml/37647169#37647169
# https://help.appveyor.com/discussions/questions/3888-multi-line-cmd-or-powershell-warning-ignore
- cmd: .\tools\misc\appveyorBuildConfigurationScript.bat
# build with MSBuild
build:
project: Build\Catch2.sln # path to Visual Studio solution or project
parallel: true # enable MSBuild parallel builds
verbosity: normal # MSBuild verbosity level {quiet|minimal|normal|detailed}
test_script:
- set CTEST_OUTPUT_ON_FAILURE=1
- cmd: .\tools\misc\appveyorTestRunScript.bat
# Sadly we cannot use the standard "dimensions" based approach towards
# specifying the different builds, as there is no way to add one-offs
# builds afterwards. This means that we will painfully specify each
# build explicitly.
environment:
matrix:
- FLAVOR: VS 2019 x64 Debug Coverage Examples
APPVEYOR_BUILD_WORKER_IMAGE: Visual Studio 2019
examples: 1
coverage: 1
platform: x64
configuration: Debug
- FLAVOR: VS 2019 x64 Debug WMain
APPVEYOR_BUILD_WORKER_IMAGE: Visual Studio 2019
wmain: 1
additional_flags: "/D_UNICODE /DUNICODE"
platform: x64
configuration: Debug
- FLAVOR: VS 2019 x64 Debug Latest Strict
APPVEYOR_BUILD_WORKER_IMAGE: Visual Studio 2019
additional_flags: "/permissive- /std:c++latest"
platform: x64
configuration: Debug
- FLAVOR: VS 2017 x64 Debug
APPVEYOR_BUILD_WORKER_IMAGE: Visual Studio 2017
platform: x64
configuration: Debug
- FLAVOR: VS 2017 x64 Release Coverage
APPVEYOR_BUILD_WORKER_IMAGE: Visual Studio 2017
coverage: 1
platform: x64
configuration: Debug

View File

@ -0,0 +1,22 @@
coverage:
precision: 2
round: nearest
range: "60...90"
status:
project:
default:
threshold: 2%
patch:
default:
target: 80%
ignore:
- "**/external/clara.hpp"
- "tests"
codecov:
branch: devel
max_report_age: off
comment:
layout: "diff"

View File

@ -0,0 +1,129 @@
#!/usr/bin/env python
from conan import ConanFile
from conan.tools.cmake import CMake, CMakeToolchain, CMakeDeps, cmake_layout
from conan.tools.files import copy, rmdir
from conan.tools.build import check_min_cppstd
from conan.tools.scm import Version
from conan.errors import ConanInvalidConfiguration
import os
import re
required_conan_version = ">=1.53.0"
class CatchConan(ConanFile):
name = "catch2"
description = "A modern, C++-native, framework for unit-tests, TDD and BDD"
topics = ("conan", "catch2", "unit-test", "tdd", "bdd")
url = "https://github.com/catchorg/Catch2"
homepage = url
license = "BSL-1.0"
version = "latest"
settings = "os", "compiler", "build_type", "arch"
extension_properties = {"compatibility_cppstd": False}
options = {
"shared": [True, False],
"fPIC": [True, False],
}
default_options = {
"shared": False,
"fPIC": True,
}
@property
def _min_cppstd(self):
return "14"
@property
def _compilers_minimum_version(self):
return {
"gcc": "7",
"Visual Studio": "15",
"msvc": "191",
"clang": "5",
"apple-clang": "10",
}
def set_version(self):
pattern = re.compile(r"\w*VERSION (\d+\.\d+\.\d+) # CML version placeholder, don't delete")
with open("CMakeLists.txt") as file:
for line in file:
result = pattern.search(line)
if result:
self.version = result.group(1)
self.output.info(f'Using version: {self.version}')
def export(self):
copy(self, "LICENSE.txt", src=self.recipe_folder, dst=self.export_folder)
def export_sources(self):
copy(self, "CMakeLists.txt", src=self.recipe_folder, dst=self.export_sources_folder)
copy(self, "src/*", src=self.recipe_folder, dst=self.export_sources_folder)
copy(self, "extras/*", src=self.recipe_folder, dst=self.export_sources_folder)
copy(self, "CMake/*", src=self.recipe_folder, dst=self.export_sources_folder)
def config_options(self):
if self.settings.os == "Windows":
del self.options.fPIC
def configure(self):
if self.options.shared:
self.options.rm_safe("fPIC")
def layout(self):
cmake_layout(self)
def validate(self):
if self.settings.compiler.get_safe("cppstd"):
check_min_cppstd(self, self._min_cppstd)
# INFO: Conan 1.x does not specify cppstd by default, so we need to check the compiler version instead.
minimum_version = self._compilers_minimum_version.get(str(self.settings.compiler), False)
if minimum_version and Version(self.settings.compiler.version) < minimum_version:
raise ConanInvalidConfiguration(f"{self.ref} requires C++{self._min_cppstd}, which your compiler doesn't support")
def generate(self):
tc = CMakeToolchain(self)
tc.cache_variables["BUILD_TESTING"] = False
tc.cache_variables["CATCH_INSTALL_DOCS"] = False
tc.cache_variables["CATCH_INSTALL_EXTRAS"] = True
tc.generate()
deps = CMakeDeps(self)
deps.generate()
def build(self):
cmake = CMake(self)
cmake.configure()
cmake.build()
def package(self):
copy(self, "LICENSE.txt", src=str(self.recipe_folder), dst=os.path.join(self.package_folder, "licenses"))
cmake = CMake(self)
cmake.install()
rmdir(self, os.path.join(self.package_folder, "share"))
rmdir(self, os.path.join(self.package_folder, "lib", "cmake"))
copy(self, "*.cmake", src=os.path.join(self.export_sources_folder, "extras"),
dst=os.path.join(self.package_folder, "lib", "cmake", "Catch2"))
def package_info(self):
lib_suffix = "d" if self.settings.build_type == "Debug" else ""
self.cpp_info.set_property("cmake_file_name", "Catch2")
self.cpp_info.set_property("cmake_target_name", "Catch2::Catch2WithMain")
self.cpp_info.set_property("pkg_config_name", "catch2-with-main")
# Catch2
self.cpp_info.components["catch2base"].set_property("cmake_file_name", "Catch2::Catch2")
self.cpp_info.components["catch2base"].set_property("cmake_target_name", "Catch2::Catch2")
self.cpp_info.components["catch2base"].set_property("pkg_config_name", "catch2")
self.cpp_info.components["catch2base"].libs = ["Catch2" + lib_suffix]
self.cpp_info.components["catch2base"].builddirs.append("lib/cmake/Catch2")
# Catch2WithMain
self.cpp_info.components["catch2main"].set_property("cmake_file_name", "Catch2::Catch2WithMain")
self.cpp_info.components["catch2main"].set_property("cmake_target_name", "Catch2::Catch2WithMain")
self.cpp_info.components["catch2main"].set_property("pkg_config_name", "catch2-with-main")
self.cpp_info.components["catch2main"].libs = ["Catch2Main" + lib_suffix]
self.cpp_info.components["catch2main"].requires = ["catch2base"]

Binary file not shown.

After

Width:  |  Height:  |  Size: 10 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 33 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 25 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 20 KiB

View File

@ -0,0 +1,43 @@
<a id="top"></a>
# Reference
To get the most out of Catch2, start with the [tutorial](tutorial.md#top).
Once you're up and running consider the following reference material.
**Writing tests:**
* [Assertion macros](assertions.md#top)
* [Matchers (asserting complex properties)](matchers.md#top)
* [Comparing floating point numbers](comparing-floating-point-numbers.md#top)
* [Logging macros](logging.md#top)
* [Test cases and sections](test-cases-and-sections.md#top)
* [Test fixtures](test-fixtures.md#top)
* [Explicitly skipping, passing, and failing tests at runtime](skipping-passing-failing.md#top)
* [Reporters (output customization)](reporters.md#top)
* [Event Listeners](event-listeners.md#top)
* [Data Generators (value parameterized tests)](generators.md#top)
* [Other macros](other-macros.md#top)
* [Micro benchmarking](benchmarks.md#top)
**Fine tuning:**
* [Supplying your own main()](own-main.md#top)
* [Compile-time configuration](configuration.md#top)
* [String Conversions](tostring.md#top)
**Running:**
* [Command line](command-line.md#top)
**Odds and ends:**
* [Frequently Asked Questions (FAQ)](faq.md#top)
* [Best practices and other tips](usage-tips.md#top)
* [CMake integration](cmake-integration.md#top)
* [Tooling integration (CI, test runners, other)](ci-and-misc.md#top)
* [Known limitations](limitations.md#top)
**Other:**
* [Why Catch2?](why-catch.md#top)
* [Migrating from v2 to v3](migrate-v2-to-v3.md#top)
* [Open Source Projects using Catch2](opensource-users.md#top)
* [Commercial Projects using Catch2](commercial-users.md#top)
* [Contributing](contributing.md#top)
* [Release Notes](release-notes.md#top)
* [Deprecations and incoming changes](deprecations.md#top)

View File

@ -0,0 +1,182 @@
<a id="top"></a>
# Assertion Macros
**Contents**<br>
[Natural Expressions](#natural-expressions)<br>
[Floating point comparisons](#floating-point-comparisons)<br>
[Exceptions](#exceptions)<br>
[Matcher expressions](#matcher-expressions)<br>
[Thread Safety](#thread-safety)<br>
[Expressions with commas](#expressions-with-commas)<br>
Most test frameworks have a large collection of assertion macros to capture all possible conditional forms (```_EQUALS```, ```_NOTEQUALS```, ```_GREATER_THAN``` etc).
Catch is different. Because it decomposes natural C-style conditional expressions most of these forms are reduced to one or two that you will use all the time. That said there is a rich set of auxiliary macros as well. We'll describe all of these here.
Most of these macros come in two forms:
## Natural Expressions
The ```REQUIRE``` family of macros tests an expression and aborts the test case if it fails.
The ```CHECK``` family are equivalent but execution continues in the same test case even if the assertion fails. This is useful if you have a series of essentially orthogonal assertions and it is useful to see all the results rather than stopping at the first failure.
* **REQUIRE(** _expression_ **)** and
* **CHECK(** _expression_ **)**
Evaluates the expression and records the result. If an exception is thrown, it is caught, reported, and counted as a failure. These are the macros you will use most of the time.
Examples:
```
CHECK( str == "string value" );
CHECK( thisReturnsTrue() );
REQUIRE( i == 42 );
```
Expressions prefixed with `!` cannot be decomposed. If you have a type
that is convertible to bool and you want to assert that it evaluates to
false, use the two forms below:
* **REQUIRE_FALSE(** _expression_ **)** and
* **CHECK_FALSE(** _expression_ **)**
Note that there is no reason to use these forms for plain bool variables,
because there is no added value in decomposing them.
Example:
```cpp
Status ret = someFunction();
REQUIRE_FALSE(ret); // ret must evaluate to false, and Catch2 will print
// out the value of ret if possibly
```
### Other limitations
Note that expressions containing either of the binary logical operators,
`&&` or `||`, cannot be decomposed and will not compile. The reason behind
this is that it is impossible to overload `&&` and `||` in a way that
keeps their short-circuiting semantics, and expression decomposition
relies on overloaded operators to work.
Simple example of an issue with overloading binary logical operators
is a common pointer idiom, `p && p->foo == 2`. Using the built-in `&&`
operator, `p` is only dereferenced if it is not null. With overloaded
`&&`, `p` is always dereferenced, thus causing a segfault if
`p == nullptr`.
If you want to test expression that contains `&&` or `||`, you have two
options.
1) Enclose it in parentheses. Parentheses force evaluation of the expression
before the expression decomposition can touch it, and thus it cannot
be used.
2) Rewrite the expression. `REQUIRE(a == 1 && b == 2)` can always be split
into `REQUIRE(a == 1); REQUIRE(b == 2);`. Alternatively, if this is a
common pattern in your tests, think about using [Matchers](#matcher-expressions).
instead. There is no simple rewrite rule for `||`, but I generally
believe that if you have `||` in your test expression, you should rethink
your tests.
## Floating point comparisons
Comparing floating point numbers is complex, and [so it has its own
documentation page](comparing-floating-point-numbers.md#top).
## Exceptions
* **REQUIRE_NOTHROW(** _expression_ **)** and
* **CHECK_NOTHROW(** _expression_ **)**
Expects that no exception is thrown during evaluation of the expression.
* **REQUIRE_THROWS(** _expression_ **)** and
* **CHECK_THROWS(** _expression_ **)**
Expects that an exception (of any type) is be thrown during evaluation of the expression.
* **REQUIRE_THROWS_AS(** _expression_, _exception type_ **)** and
* **CHECK_THROWS_AS(** _expression_, _exception type_ **)**
Expects that an exception of the _specified type_ is thrown during evaluation of the expression. Note that the _exception type_ is extended with `const&` and you should not include it yourself.
* **REQUIRE_THROWS_WITH(** _expression_, _string or string matcher_ **)** and
* **CHECK_THROWS_WITH(** _expression_, _string or string matcher_ **)**
Expects that an exception is thrown that, when converted to a string, matches the _string_ or _string matcher_ provided (see next section for Matchers).
e.g.
```cpp
REQUIRE_THROWS_WITH( openThePodBayDoors(), ContainsSubstring( "afraid" ) && ContainsSubstring( "can't do that" ) );
REQUIRE_THROWS_WITH( dismantleHal(), "My mind is going" );
```
* **REQUIRE_THROWS_MATCHES(** _expression_, _exception type_, _matcher for given exception type_ **)** and
* **CHECK_THROWS_MATCHES(** _expression_, _exception type_, _matcher for given exception type_ **)**
Expects that exception of _exception type_ is thrown and it matches provided matcher (see the [documentation for Matchers](matchers.md#top)).
_Please note that the `THROW` family of assertions expects to be passed a single expression, not a statement or series of statements. If you want to check a more complicated sequence of operations, you can use a C++11 lambda function._
```cpp
REQUIRE_NOTHROW([&](){
int i = 1;
int j = 2;
auto k = i + j;
if (k == 3) {
throw 1;
}
}());
```
## Matcher expressions
To support Matchers a slightly different form is used. Matchers have [their own documentation](matchers.md#top).
* **REQUIRE_THAT(** _lhs_, _matcher expression_ **)** and
* **CHECK_THAT(** _lhs_, _matcher expression_ **)**
Matchers can be composed using `&&`, `||` and `!` operators.
## Thread Safety
Currently assertions in Catch are not thread safe.
For more details, along with workarounds, see the section on [the limitations page](limitations.md#thread-safe-assertions).
## Expressions with commas
Because the preprocessor parses code using different rules than the
compiler, multiple-argument assertions (e.g. `REQUIRE_THROWS_AS`) have
problems with commas inside the provided expressions. As an example
`REQUIRE_THROWS_AS(std::pair<int, int>(1, 2), std::invalid_argument);`
will fail to compile, because the preprocessor sees 3 arguments provided,
but the macro accepts only 2. There are two possible workarounds.
1) Use typedef:
```cpp
using int_pair = std::pair<int, int>;
REQUIRE_THROWS_AS(int_pair(1, 2), std::invalid_argument);
```
This solution is always applicable, but makes the meaning of the code
less clear.
2) Parenthesize the expression:
```cpp
TEST_CASE_METHOD((Fixture<int, int>), "foo", "[bar]") {
SUCCEED();
}
```
This solution is not always applicable, because it might require extra
changes on the Catch's side to work.
---
[Home](Readme.md#top)

View File

@ -0,0 +1,251 @@
<a id="top"></a>
# Authoring benchmarks
> [Introduced](https://github.com/catchorg/Catch2/issues/1616) in Catch2 2.9.0.
Writing benchmarks is not easy. Catch simplifies certain aspects but you'll
always need to take care about various aspects. Understanding a few things about
the way Catch runs your code will be very helpful when writing your benchmarks.
First off, let's go over some terminology that will be used throughout this
guide.
- *User code*: user code is the code that the user provides to be measured.
- *Run*: one run is one execution of the user code. Sometimes also referred
to as an _iteration_.
- *Sample*: one sample is one data point obtained by measuring the time it takes
to perform a certain number of runs. One sample can consist of more than one
run if the clock available does not have enough resolution to accurately
measure a single run. All samples for a given benchmark execution are obtained
with the same number of runs.
## Execution procedure
Now I can explain how a benchmark is executed in Catch. There are three main
steps, though the first does not need to be repeated for every benchmark.
1. *Environmental probe*: before any benchmarks can be executed, the clock's
resolution is estimated. A few other environmental artifacts are also estimated
at this point, like the cost of calling the clock function, but they almost
never have any impact in the results.
2. *Estimation*: the user code is executed a few times to obtain an estimate of
the amount of runs that should be in each sample. This also has the potential
effect of bringing relevant code and data into the caches before the actual
measurement starts.
3. *Measurement*: all the samples are collected sequentially by performing the
number of runs estimated in the previous step for each sample.
This already gives us one important rule for writing benchmarks for Catch: the
benchmarks must be repeatable. The user code will be executed several times, and
the number of times it will be executed during the estimation step cannot be
known beforehand since it depends on the time it takes to execute the code.
User code that cannot be executed repeatedly will lead to bogus results or
crashes.
## Benchmark specification
Benchmarks can be specified anywhere inside a Catch test case.
There is a simple and a slightly more advanced version of the `BENCHMARK` macro.
Let's have a look how a naive Fibonacci implementation could be benchmarked:
```c++
std::uint64_t Fibonacci(std::uint64_t number) {
return number < 2 ? 1 : Fibonacci(number - 1) + Fibonacci(number - 2);
}
```
Now the most straight forward way to benchmark this function, is just adding a `BENCHMARK` macro to our test case:
```c++
TEST_CASE("Fibonacci") {
CHECK(Fibonacci(0) == 1);
// some more asserts..
CHECK(Fibonacci(5) == 8);
// some more asserts..
// now let's benchmark:
BENCHMARK("Fibonacci 20") {
return Fibonacci(20);
};
BENCHMARK("Fibonacci 25") {
return Fibonacci(25);
};
BENCHMARK("Fibonacci 30") {
return Fibonacci(30);
};
BENCHMARK("Fibonacci 35") {
return Fibonacci(35);
};
}
```
There's a few things to note:
- As `BENCHMARK` expands to a lambda expression it is necessary to add a semicolon after
the closing brace (as opposed to the first experimental version).
- The `return` is a handy way to avoid the compiler optimizing away the benchmark code.
Running this already runs the benchmarks and outputs something similar to:
```
-------------------------------------------------------------------------------
Fibonacci
-------------------------------------------------------------------------------
C:\path\to\Catch2\Benchmark.tests.cpp(10)
...............................................................................
benchmark name samples iterations est run time
mean low mean high mean
std dev low std dev high std dev
-------------------------------------------------------------------------------
Fibonacci 20 100 416439 83.2878 ms
2 ns 2 ns 2 ns
0 ns 0 ns 0 ns
Fibonacci 25 100 400776 80.1552 ms
3 ns 3 ns 3 ns
0 ns 0 ns 0 ns
Fibonacci 30 100 396873 79.3746 ms
17 ns 17 ns 17 ns
0 ns 0 ns 0 ns
Fibonacci 35 100 145169 87.1014 ms
468 ns 464 ns 473 ns
21 ns 15 ns 34 ns
```
### Advanced benchmarking
The simplest use case shown above, takes no arguments and just runs the user code that needs to be measured.
However, if using the `BENCHMARK_ADVANCED` macro and adding a `Catch::Benchmark::Chronometer` argument after
the macro, some advanced features are available. The contents of the simple benchmarks are invoked once per run,
while the blocks of the advanced benchmarks are invoked exactly twice:
once during the estimation phase, and another time during the execution phase.
```c++
BENCHMARK("simple"){ return long_computation(); };
BENCHMARK_ADVANCED("advanced")(Catch::Benchmark::Chronometer meter) {
set_up();
meter.measure([] { return long_computation(); });
};
```
These advanced benchmarks no longer consist entirely of user code to be measured.
In these cases, the code to be measured is provided via the
`Catch::Benchmark::Chronometer::measure` member function. This allows you to set up any
kind of state that might be required for the benchmark but is not to be included
in the measurements, like making a vector of random integers to feed to a
sorting algorithm.
A single call to `Catch::Benchmark::Chronometer::measure` performs the actual measurements
by invoking the callable object passed in as many times as necessary. Anything
that needs to be done outside the measurement can be done outside the call to
`measure`.
The callable object passed in to `measure` can optionally accept an `int`
parameter.
```c++
meter.measure([](int i) { return long_computation(i); });
```
If it accepts an `int` parameter, the sequence number of each run will be passed
in, starting with 0. This is useful if you want to measure some mutating code,
for example. The number of runs can be known beforehand by calling
`Catch::Benchmark::Chronometer::runs`; with this one can set up a different instance to be
mutated by each run.
```c++
std::vector<std::string> v(meter.runs());
std::fill(v.begin(), v.end(), test_string());
meter.measure([&v](int i) { in_place_escape(v[i]); });
```
Note that it is not possible to simply use the same instance for different runs
and resetting it between each run since that would pollute the measurements with
the resetting code.
It is also possible to just provide an argument name to the simple `BENCHMARK` macro to get
the same semantics as providing a callable to `meter.measure` with `int` argument:
```c++
BENCHMARK("indexed", i){ return long_computation(i); };
```
### Constructors and destructors
All of these tools give you a lot mileage, but there are two things that still
need special handling: constructors and destructors. The problem is that if you
use automatic objects they get destroyed by the end of the scope, so you end up
measuring the time for construction and destruction together. And if you use
dynamic allocation instead, you end up including the time to allocate memory in
the measurements.
To solve this conundrum, Catch provides class templates that let you manually
construct and destroy objects without dynamic allocation and in a way that lets
you measure construction and destruction separately.
```c++
BENCHMARK_ADVANCED("construct")(Catch::Benchmark::Chronometer meter) {
std::vector<Catch::Benchmark::storage_for<std::string>> storage(meter.runs());
meter.measure([&](int i) { storage[i].construct("thing"); });
};
BENCHMARK_ADVANCED("destroy")(Catch::Benchmark::Chronometer meter) {
std::vector<Catch::Benchmark::destructable_object<std::string>> storage(meter.runs());
for(auto&& o : storage)
o.construct("thing");
meter.measure([&](int i) { storage[i].destruct(); });
};
```
`Catch::Benchmark::storage_for<T>` objects are just pieces of raw storage suitable for `T`
objects. You can use the `Catch::Benchmark::storage_for::construct` member function to call a constructor and
create an object in that storage. So if you want to measure the time it takes
for a certain constructor to run, you can just measure the time it takes to run
this function.
When the lifetime of a `Catch::Benchmark::storage_for<T>` object ends, if an actual object was
constructed there it will be automatically destroyed, so nothing leaks.
If you want to measure a destructor, though, we need to use
`Catch::Benchmark::destructable_object<T>`. These objects are similar to
`Catch::Benchmark::storage_for<T>` in that construction of the `T` object is manual, but
it does not destroy anything automatically. Instead, you are required to call
the `Catch::Benchmark::destructable_object::destruct` member function, which is what you
can use to measure the destruction time.
### The optimizer
Sometimes the optimizer will optimize away the very code that you want to
measure. There are several ways to use results that will prevent the optimiser
from removing them. You can use the `volatile` keyword, or you can output the
value to standard output or to a file, both of which force the program to
actually generate the value somehow.
Catch adds a third option. The values returned by any function provided as user
code are guaranteed to be evaluated and not optimised out. This means that if
your user code consists of computing a certain value, you don't need to bother
with using `volatile` or forcing output. Just `return` it from the function.
That helps with keeping the code in a natural fashion.
Here's an example:
```c++
// may measure nothing at all by skipping the long calculation since its
// result is not used
BENCHMARK("no return"){ long_calculation(); };
// the result of long_calculation() is guaranteed to be computed somehow
BENCHMARK("with return"){ return long_calculation(); };
```
However, there's no other form of control over the optimizer whatsoever. It is
up to you to write a benchmark that actually measures what you want and doesn't
just measure the time to do a whole bunch of nothing.
To sum up, there are two simple rules: whatever you would do in handwritten code
to control optimization still works in Catch; and Catch makes return values
from user code into observable effects that can't be optimized away.
<i>Adapted from nonius' documentation.</i>

View File

@ -0,0 +1,110 @@
<a id="top"></a>
# Tooling integration (CI, test runners and so on)
**Contents**<br>
[Continuous Integration systems](#continuous-integration-systems)<br>
[Bazel test runner integration](#bazel-test-runner-integration)<br>
[Low-level tools](#low-level-tools)<br>
[CMake](#cmake)<br>
This page talks about Catch2's integration with other related tooling,
like Continuous Integration and 3rd party test runners.
## Continuous Integration systems
Probably the most important aspect to using Catch with a build server is the use of different reporters. Catch comes bundled with three reporters that should cover the majority of build servers out there - although adding more for better integration with some is always a possibility (currently we also offer TeamCity, TAP, Automake and SonarQube reporters).
Two of these reporters are built in (XML and JUnit) and the third (TeamCity) is included as a separate header. It's possible that the other two may be split out in the future too - as that would make the core of Catch smaller for those that don't need them.
### XML Reporter
```-r xml```
The XML Reporter writes in an XML format that is specific to Catch.
The advantage of this format is that it corresponds well to the way Catch works (especially the more unusual features, such as nested sections) and is a fully streaming format - that is it writes output as it goes, without having to store up all its results before it can start writing.
The disadvantage is that, being specific to Catch, no existing build servers understand the format natively. It can be used as input to an XSLT transformation that could convert it to, say, HTML - although this loses the streaming advantage, of course.
### JUnit Reporter
```-r junit```
The JUnit Reporter writes in an XML format that mimics the JUnit ANT schema.
The advantage of this format is that the JUnit Ant schema is widely understood by most build servers and so can usually be consumed with no additional work.
The disadvantage is that this schema was designed to correspond to how JUnit works - and there is a significant mismatch with how Catch works. Additionally the format is not streamable (because opening elements hold counts of failed and passing tests as attributes) - so the whole test run must complete before it can be written.
### TeamCity Reporter
```-r teamcity```
The TeamCity Reporter writes TeamCity service messages to stdout. In order to be able to use this reporter an additional header must also be included.
Being specific to TeamCity this is the best reporter to use with it - but it is completely unsuitable for any other purpose. It is a streaming format (it writes as it goes) - although test results don't appear in the TeamCity interface until the completion of a suite (usually the whole test run).
### Automake Reporter
```-r automake```
The Automake Reporter writes out the [meta tags](https://www.gnu.org/software/automake/manual/html_node/Log-files-generation-and-test-results-recording.html#Log-files-generation-and-test-results-recording) expected by automake via `make check`.
### TAP (Test Anything Protocol) Reporter
```-r tap```
Because of the incremental nature of Catch's test suites and ability to run specific tests, our implementation of TAP reporter writes out the number of tests in a suite last.
### SonarQube Reporter
```-r sonarqube```
[SonarQube Generic Test Data](https://docs.sonarqube.org/latest/analysis/generic-test/) XML format for tests metrics.
## Bazel test runner integration
Catch2 understands some of the environment variables Bazel uses to control
test execution. Specifically it understands
* JUnit output path via `XML_OUTPUT_FILE`
* Test filtering via `TESTBRIDGE_TEST_ONLY`
* Test sharding via `TEST_SHARD_INDEX`, `TEST_TOTAL_SHARDS`, and `TEST_SHARD_STATUS_FILE`
> Support for `XML_OUTPUT_FILE` was [introduced](https://github.com/catchorg/Catch2/pull/2399) in Catch2 3.0.1
> Support for `TESTBRIDGE_TEST_ONLY` and sharding was introduced in Catch2 3.2.0
This integration is enabled via either a [compile time configuration
option](configuration.md#bazel-support), or via `BAZEL_TEST` environment
variable set to "1".
> Support for `BAZEL_TEST` was [introduced](https://github.com/catchorg/Catch2/pull/2459) in Catch2 3.1.0
## Low-level tools
### CodeCoverage module (GCOV, LCOV...)
If you are using GCOV tool to get testing coverage of your code, and are not sure how to integrate it with CMake and Catch, there should be an external example over at https://github.com/claremacrae/catch_cmake_coverage
### pkg-config
Catch2 provides a rudimentary pkg-config integration, by registering itself
under the name `catch2`. This means that after Catch2 is installed, you
can use `pkg-config` to get its include path: `pkg-config --cflags catch2`.
### gdb and lldb scripts
Catch2's `extras` folder also contains two simple debugger scripts,
`gdbinit` for `gdb` and `lldbinit` for `lldb`. If loaded into their
respective debugger, these will tell it to step over Catch2's internals
when stepping through code.
## CMake
[As it has been getting kinda long, the documentation of Catch2's
integration with CMake has been moved to its own page.](cmake-integration.md#top)
---
[Home](Readme.md#top)

View File

@ -0,0 +1,432 @@
<a id="top"></a>
# CMake integration
**Contents**<br>
[CMake targets](#cmake-targets)<br>
[Automatic test registration](#automatic-test-registration)<br>
[CMake project options](#cmake-project-options)<br>
[`CATCH_CONFIG_*` customization options in CMake](#catch_config_-customization-options-in-cmake)<br>
[Installing Catch2 from git repository](#installing-catch2-from-git-repository)<br>
[Installing Catch2 from vcpkg](#installing-catch2-from-vcpkg)<br>
[Installing Catch2 from Bazel](#installing-catch2-from-bazel)<br>
Because we use CMake to build Catch2, we also provide a couple of
integration points for our users.
1) Catch2 exports a (namespaced) CMake target
2) Catch2's repository contains CMake scripts for automatic registration
of `TEST_CASE`s in CTest
## CMake targets
Catch2's CMake build exports two targets, `Catch2::Catch2`, and
`Catch2::Catch2WithMain`. If you do not need custom `main` function,
you should be using the latter (and only the latter). Linking against
it will add the proper include paths and link your target together with
2 static libraries that implement Catch2 and its main respectively.
If you need custom `main`, you should link only against `Catch2::Catch2`.
This means that if Catch2 has been installed on the system, it should
be enough to do
```cmake
find_package(Catch2 3 REQUIRED)
# These tests can use the Catch2-provided main
add_executable(tests test.cpp)
target_link_libraries(tests PRIVATE Catch2::Catch2WithMain)
# These tests need their own main
add_executable(custom-main-tests test.cpp test-main.cpp)
target_link_libraries(custom-main-tests PRIVATE Catch2::Catch2)
```
These targets are also provided when Catch2 is used as a subdirectory.
Assuming Catch2 has been cloned to `lib/Catch2`, you only need to replace
the `find_package` call with `add_subdirectory(lib/Catch2)` and the snippet
above still works.
Another possibility is to use [FetchContent](https://cmake.org/cmake/help/latest/module/FetchContent.html):
```cmake
Include(FetchContent)
FetchContent_Declare(
Catch2
GIT_REPOSITORY https://github.com/catchorg/Catch2.git
GIT_TAG v3.4.0 # or a later release
)
FetchContent_MakeAvailable(Catch2)
add_executable(tests test.cpp)
target_link_libraries(tests PRIVATE Catch2::Catch2WithMain)
```
## Automatic test registration
Catch2's repository also contains three CMake scripts that help users
with automatically registering their `TEST_CASE`s with CTest. They
can be found in the `extras` folder, and are
1) `Catch.cmake` (and its dependency `CatchAddTests.cmake`)
2) `ParseAndAddCatchTests.cmake` (deprecated)
3) `CatchShardTests.cmake` (and its dependency `CatchShardTestsImpl.cmake`)
If Catch2 has been installed in system, both of these can be used after
doing `find_package(Catch2 REQUIRED)`. Otherwise you need to add them
to your CMake module path.
<a id="catch_discover_tests"></a>
### `Catch.cmake` and `CatchAddTests.cmake`
`Catch.cmake` provides function `catch_discover_tests` to get tests from
a target. This function works by running the resulting executable with
`--list-test-names-only` flag, and then parsing the output to find all
existing tests.
#### Usage
```cmake
cmake_minimum_required(VERSION 3.5)
project(baz LANGUAGES CXX VERSION 0.0.1)
find_package(Catch2 REQUIRED)
add_executable(tests test.cpp)
target_link_libraries(tests PRIVATE Catch2::Catch2)
include(CTest)
include(Catch)
catch_discover_tests(tests)
```
When using `FetchContent`, `include(Catch)` will fail unless
`CMAKE_MODULE_PATH` is explicitly updated to include the extras
directory.
```cmake
# ... FetchContent ...
#
list(APPEND CMAKE_MODULE_PATH ${catch2_SOURCE_DIR}/extras)
include(CTest)
include(Catch)
catch_discover_tests(tests)
```
#### Customization
`catch_discover_tests` can be given several extra arguments:
```cmake
catch_discover_tests(target
[TEST_SPEC arg1...]
[EXTRA_ARGS arg1...]
[WORKING_DIRECTORY dir]
[TEST_PREFIX prefix]
[TEST_SUFFIX suffix]
[PROPERTIES name1 value1...]
[TEST_LIST var]
[REPORTER reporter]
[OUTPUT_DIR dir]
[OUTPUT_PREFIX prefix]
[OUTPUT_SUFFIX suffix]
[DISCOVERY_MODE <POST_BUILD|PRE_TEST>]
)
```
* `TEST_SPEC arg1...`
Specifies test cases, wildcarded test cases, tags and tag expressions to
pass to the Catch executable alongside the `--list-test-names-only` flag.
* `EXTRA_ARGS arg1...`
Any extra arguments to pass on the command line to each test case.
* `WORKING_DIRECTORY dir`
Specifies the directory in which to run the discovered test cases. If this
option is not provided, the current binary directory is used.
* `TEST_PREFIX prefix`
Specifies a _prefix_ to be added to the name of each discovered test case.
This can be useful when the same test executable is being used in multiple
calls to `catch_discover_tests()`, with different `TEST_SPEC` or `EXTRA_ARGS`.
* `TEST_SUFFIX suffix`
Same as `TEST_PREFIX`, except it specific the _suffix_ for the test names.
Both `TEST_PREFIX` and `TEST_SUFFIX` can be specified at the same time.
* `PROPERTIES name1 value1...`
Specifies additional properties to be set on all tests discovered by this
invocation of `catch_discover_tests`.
* `TEST_LIST var`
Make the list of tests available in the variable `var`, rather than the
default `<target>_TESTS`. This can be useful when the same test
executable is being used in multiple calls to `catch_discover_tests()`.
Note that this variable is only available in CTest.
* `REPORTER reporter`
Use the specified reporter when running the test case. The reporter will
be passed to the test runner as `--reporter reporter`.
* `OUTPUT_DIR dir`
If specified, the parameter is passed along as
`--out dir/<test_name>` to test executable. The actual file name is the
same as the test name. This should be used instead of
`EXTRA_ARGS --out foo` to avoid race conditions writing the result output
when using parallel test execution.
* `OUTPUT_PREFIX prefix`
May be used in conjunction with `OUTPUT_DIR`.
If specified, `prefix` is added to each output file name, like so
`--out dir/prefix<test_name>`.
* `OUTPUT_SUFFIX suffix`
May be used in conjunction with `OUTPUT_DIR`.
If specified, `suffix` is added to each output file name, like so
`--out dir/<test_name>suffix`. This can be used to add a file extension to
the output file name e.g. ".xml".
* `DISCOVERY_MODE mode`
If specified allows control over when test discovery is performed.
For a value of `POST_BUILD` (default) test discovery is performed at build time.
For a value of `PRE_TEST` test discovery is delayed until just prior to test
execution (useful e.g. in cross-compilation environments).
``DISCOVERY_MODE`` defaults to the value of the
``CMAKE_CATCH_DISCOVER_TESTS_DISCOVERY_MODE`` variable if it is not passed when
calling ``catch_discover_tests``. This provides a mechanism for globally
selecting a preferred test discovery behavior.
### `ParseAndAddCatchTests.cmake`
⚠ This script is [deprecated](https://github.com/catchorg/Catch2/pull/2120)
in Catch2 2.13.4 and superseded by the above approach using `catch_discover_tests`.
See [#2092](https://github.com/catchorg/Catch2/issues/2092) for details.
`ParseAndAddCatchTests` works by parsing all implementation files
associated with the provided target, and registering them via CTest's
`add_test`. This approach has some limitations, such as the fact that
commented-out tests will be registered anyway. More serious, only a
subset of the assertion macros currently available in Catch can be
detected by this script and tests with any macros that cannot be
parsed are *silently ignored*.
#### Usage
```cmake
cmake_minimum_required(VERSION 3.5)
project(baz LANGUAGES CXX VERSION 0.0.1)
find_package(Catch2 REQUIRED)
add_executable(tests test.cpp)
target_link_libraries(tests PRIVATE Catch2::Catch2)
include(CTest)
include(ParseAndAddCatchTests)
ParseAndAddCatchTests(tests)
```
#### Customization
`ParseAndAddCatchTests` provides some customization points:
* `PARSE_CATCH_TESTS_VERBOSE` -- When `ON`, the script prints debug
messages. Defaults to `OFF`.
* `PARSE_CATCH_TESTS_NO_HIDDEN_TESTS` -- When `ON`, hidden tests (tests
tagged with either of `[.]` or `[.foo]`) will not be registered.
Defaults to `OFF`.
* `PARSE_CATCH_TESTS_ADD_FIXTURE_IN_TEST_NAME` -- When `ON`, adds fixture
class name to the test name in CTest. Defaults to `ON`.
* `PARSE_CATCH_TESTS_ADD_TARGET_IN_TEST_NAME` -- When `ON`, adds target
name to the test name in CTest. Defaults to `ON`.
* `PARSE_CATCH_TESTS_ADD_TO_CONFIGURE_DEPENDS` -- When `ON`, adds test
file to `CMAKE_CONFIGURE_DEPENDS`. This means that the CMake configuration
step will be re-ran when the test files change, letting new tests be
automatically discovered. Defaults to `OFF`.
Optionally, one can specify a launching command to run tests by setting the
variable `OptionalCatchTestLauncher` before calling `ParseAndAddCatchTests`. For
instance to run some tests using `MPI` and other sequentially, one can write
```cmake
set(OptionalCatchTestLauncher ${MPIEXEC} ${MPIEXEC_NUMPROC_FLAG} ${NUMPROC})
ParseAndAddCatchTests(mpi_foo)
unset(OptionalCatchTestLauncher)
ParseAndAddCatchTests(bar)
```
### `CatchShardTests.cmake`
> `CatchShardTests.cmake` was introduced in Catch2 3.1.0.
`CatchShardTests.cmake` provides a function
`catch_add_sharded_tests(TEST_BINARY)` that splits tests from `TEST_BINARY`
into multiple shards. The tests in each shard and their order is randomized,
and the seed changes every invocation of CTest.
Currently there are 3 customization points for this script:
* SHARD_COUNT - number of shards to split target's tests into
* REPORTER - reporter spec to use for tests
* TEST_SPEC - test spec used for filtering tests
Example usage:
```
include(CatchShardTests)
catch_add_sharded_tests(foo-tests
SHARD_COUNT 4
REPORTER "xml::out=-"
TEST_SPEC "A"
)
catch_add_sharded_tests(tests
SHARD_COUNT 8
REPORTER "xml::out=-"
TEST_SPEC "B"
)
```
This registers total of 12 CTest tests (4 + 8 shards) to run shards
from `foo-tests` test binary, filtered by a test spec.
_Note that this script is currently a proof-of-concept for reseeding
shards per CTest run, and thus does not support (nor does it currently
aim to support) all customization points from
[`catch_discover_tests`](#catch_discover_tests)._
## CMake project options
Catch2's CMake project also provides some options for other projects
that consume it. These are:
* `BUILD_TESTING` -- When `ON` and the project is not used as a subproject,
Catch2's test binary will be built. Defaults to `ON`.
* `CATCH_INSTALL_DOCS` -- When `ON`, Catch2's documentation will be
included in the installation. Defaults to `ON`.
* `CATCH_INSTALL_EXTRAS` -- When `ON`, Catch2's extras folder (the CMake
scripts mentioned above, debugger helpers) will be included in the
installation. Defaults to `ON`.
* `CATCH_DEVELOPMENT_BUILD` -- When `ON`, configures the build for development
of Catch2. This means enabling test projects, warnings and so on.
Defaults to `OFF`.
Enabling `CATCH_DEVELOPMENT_BUILD` also enables further configuration
customization options:
* `CATCH_BUILD_TESTING` -- When `ON`, Catch2's SelfTest project will be
built. Defaults to `ON`. Note that Catch2 also obeys `BUILD_TESTING` CMake
variable, so _both_ of them need to be `ON` for the SelfTest to be built,
and either of them can be set to `OFF` to disable building SelfTest.
* `CATCH_BUILD_EXAMPLES` -- When `ON`, Catch2's usage examples will be
built. Defaults to `OFF`.
* `CATCH_BUILD_EXTRA_TESTS` -- When `ON`, Catch2's extra tests will be
built. Defaults to `OFF`.
* `CATCH_BUILD_FUZZERS` -- When `ON`, Catch2 fuzzing entry points will
be built. Defaults to `OFF`.
* `CATCH_ENABLE_WERROR` -- When `ON`, adds `-Werror` or equivalent flag
to the compilation. Defaults to `ON`.
* `CATCH_BUILD_SURROGATES` -- When `ON`, each header in Catch2 will be
compiled separately to ensure that they are self-sufficient.
Defaults to `OFF`.
## `CATCH_CONFIG_*` customization options in CMake
> CMake support for `CATCH_CONFIG_*` options was introduced in Catch2 3.0.1
Due to the new separate compilation model, all the options from the
[Compile-time configuration docs](configuration.md#top) can also be set
through Catch2's CMake. To set them, define the option you want as `ON`,
e.g. `-DCATCH_CONFIG_NOSTDOUT=ON`.
Note that setting the option to `OFF` doesn't disable it. To force disable
an option, you need to set the `_NO_` form of it to `ON`, e.g.
`-DCATCH_CONFIG_NO_COLOUR_WIN32=ON`.
To summarize the configuration option behaviour with an example:
| `-DCATCH_CONFIG_COLOUR_WIN32` | `-DCATCH_CONFIG_NO_COLOUR_WIN32` | Result |
|-------------------------------|----------------------------------|-------------|
| `ON` | `ON` | error |
| `ON` | `OFF` | force-on |
| `OFF` | `ON` | force-off |
| `OFF` | `OFF` | auto-detect |
## Installing Catch2 from git repository
If you cannot install Catch2 from a package manager (e.g. Ubuntu 16.04
provides catch only in version 1.2.0) you might want to install it from
the repository instead. Assuming you have enough rights, you can just
install it to the default location, like so:
```
$ git clone https://github.com/catchorg/Catch2.git
$ cd Catch2
$ cmake -B build -S . -DBUILD_TESTING=OFF
$ sudo cmake --build build/ --target install
```
If you do not have superuser rights, you will also need to specify
[CMAKE_INSTALL_PREFIX](https://cmake.org/cmake/help/latest/variable/CMAKE_INSTALL_PREFIX.html)
when configuring the build, and then modify your calls to
[find_package](https://cmake.org/cmake/help/latest/command/find_package.html)
accordingly.
## Installing Catch2 from vcpkg
Alternatively, you can build and install Catch2 using [vcpkg](https://github.com/microsoft/vcpkg/) dependency manager:
```
git clone https://github.com/Microsoft/vcpkg.git
cd vcpkg
./bootstrap-vcpkg.sh
./vcpkg integrate install
./vcpkg install catch2
```
The catch2 port in vcpkg is kept up to date by microsoft team members and community contributors.
If the version is out of date, please [create an issue or pull request](https://github.com/Microsoft/vcpkg) on the vcpkg repository.
## Installing Catch2 from Bazel
Catch2 is now a supported module in the Bazel Central Registry. You only need to add one line to your MODULE.bazel file;
please see https://registry.bazel.build/modules/catch2 for the latest supported version.
You can then add `catch2_main` to each of your C++ test build rules as follows:
```
cc_test(
name = "example_test",
srcs = ["example_test.cpp"],
deps = [
":example",
"@catch2//:catch2_main",
],
)
```
---
[Home](Readme.md#top)

View File

@ -0,0 +1,648 @@
<a id="top"></a>
# Command line
**Contents**<br>
[Specifying which tests to run](#specifying-which-tests-to-run)<br>
[Choosing a reporter to use](#choosing-a-reporter-to-use)<br>
[Breaking into the debugger](#breaking-into-the-debugger)<br>
[Showing results for successful tests](#showing-results-for-successful-tests)<br>
[Aborting after a certain number of failures](#aborting-after-a-certain-number-of-failures)<br>
[Listing available tests, tags or reporters](#listing-available-tests-tags-or-reporters)<br>
[Sending output to a file](#sending-output-to-a-file)<br>
[Naming a test run](#naming-a-test-run)<br>
[Eliding assertions expected to throw](#eliding-assertions-expected-to-throw)<br>
[Make whitespace visible](#make-whitespace-visible)<br>
[Warnings](#warnings)<br>
[Reporting timings](#reporting-timings)<br>
[Load test names to run from a file](#load-test-names-to-run-from-a-file)<br>
[Specify the order test cases are run](#specify-the-order-test-cases-are-run)<br>
[Specify a seed for the Random Number Generator](#specify-a-seed-for-the-random-number-generator)<br>
[Identify framework and version according to the libIdentify standard](#identify-framework-and-version-according-to-the-libidentify-standard)<br>
[Wait for key before continuing](#wait-for-key-before-continuing)<br>
[Skip all benchmarks](#skip-all-benchmarks)<br>
[Specify the number of benchmark samples to collect](#specify-the-number-of-benchmark-samples-to-collect)<br>
[Specify the number of resamples for bootstrapping](#specify-the-number-of-resamples-for-bootstrapping)<br>
[Specify the confidence-interval for bootstrapping](#specify-the-confidence-interval-for-bootstrapping)<br>
[Disable statistical analysis of collected benchmark samples](#disable-statistical-analysis-of-collected-benchmark-samples)<br>
[Specify the amount of time in milliseconds spent on warming up each test](#specify-the-amount-of-time-in-milliseconds-spent-on-warming-up-each-test)<br>
[Usage](#usage)<br>
[Specify the section to run](#specify-the-section-to-run)<br>
[Filenames as tags](#filenames-as-tags)<br>
[Override output colouring](#override-output-colouring)<br>
[Test Sharding](#test-sharding)<br>
[Allow running the binary without tests](#allow-running-the-binary-without-tests)<br>
[Output verbosity](#output-verbosity)<br>
Catch works quite nicely without any command line options at all - but for those times when you want greater control the following options are available.
Click one of the following links to take you straight to that option - or scroll on to browse the available options.
<a href="#specifying-which-tests-to-run"> ` <test-spec> ...`</a><br />
<a href="#usage"> ` -h, -?, --help`</a><br />
<a href="#showing-results-for-successful-tests"> ` -s, --success`</a><br />
<a href="#breaking-into-the-debugger"> ` -b, --break`</a><br />
<a href="#eliding-assertions-expected-to-throw"> ` -e, --nothrow`</a><br />
<a href="#invisibles"> ` -i, --invisibles`</a><br />
<a href="#sending-output-to-a-file"> ` -o, --out`</a><br />
<a href="#choosing-a-reporter-to-use"> ` -r, --reporter`</a><br />
<a href="#naming-a-test-run"> ` -n, --name`</a><br />
<a href="#aborting-after-a-certain-number-of-failures"> ` -a, --abort`</a><br />
<a href="#aborting-after-a-certain-number-of-failures"> ` -x, --abortx`</a><br />
<a href="#warnings"> ` -w, --warn`</a><br />
<a href="#reporting-timings"> ` -d, --durations`</a><br />
<a href="#input-file"> ` -f, --input-file`</a><br />
<a href="#run-section"> ` -c, --section`</a><br />
<a href="#filenames-as-tags"> ` -#, --filenames-as-tags`</a><br />
</br>
<a href="#listing-available-tests-tags-or-reporters"> ` --list-tests`</a><br />
<a href="#listing-available-tests-tags-or-reporters"> ` --list-tags`</a><br />
<a href="#listing-available-tests-tags-or-reporters"> ` --list-reporters`</a><br />
<a href="#listing-available-tests-tags-or-reporters"> ` --list-listeners`</a><br />
<a href="#order"> ` --order`</a><br />
<a href="#rng-seed"> ` --rng-seed`</a><br />
<a href="#libidentify"> ` --libidentify`</a><br />
<a href="#wait-for-keypress"> ` --wait-for-keypress`</a><br />
<a href="#skip-benchmarks"> ` --skip-benchmarks`</a><br />
<a href="#benchmark-samples"> ` --benchmark-samples`</a><br />
<a href="#benchmark-resamples"> ` --benchmark-resamples`</a><br />
<a href="#benchmark-confidence-interval"> ` --benchmark-confidence-interval`</a><br />
<a href="#benchmark-no-analysis"> ` --benchmark-no-analysis`</a><br />
<a href="#benchmark-warmup-time"> ` --benchmark-warmup-time`</a><br />
<a href="#colour-mode"> ` --colour-mode`</a><br />
<a href="#test-sharding"> ` --shard-count`</a><br />
<a href="#test-sharding"> ` --shard-index`</a><br />
<a href=#no-tests-override> ` --allow-running-no-tests`</a><br />
<a href=#output-verbosity> ` --verbosity`</a><br />
</br>
<a id="specifying-which-tests-to-run"></a>
## Specifying which tests to run
<pre>&lt;test-spec> ...</pre>
By providing a test spec, you filter which tests will be run. If you call
Catch2 without any test spec, then it will run all non-hidden test
cases. A test case is hidden if it has the `[!benchmark]` tag, any tag
with a dot at the start, e.g. `[.]` or `[.foo]`.
There are three basic test specs that can then be combined into more
complex specs:
* Full test name, e.g. `"Test 1"`.
This allows only test cases whose name is "Test 1".
* Wildcarded test name, e.g. `"*Test"`, or `"Test*"`, or `"*Test*"`.
This allows any test case whose name ends with, starts with, or contains
in the middle the string "Test". Note that the wildcard can only be at
the start or end.
* Tag name, e.g. `[some-tag]`.
This allows any test case tagged with "[some-tag]". Remember that some
tags are special, e.g. those that start with "." or with "!".
You can also combine the basic test specs to create more complex test
specs. You can:
* Concatenate specs to apply all of them, e.g. `[some-tag][other-tag]`.
This allows test cases that are tagged with **both** "[some-tag]" **and**
"[other-tag]". A test case with just "[some-tag]" will not pass the filter,
nor will test case with just "[other-tag]".
* Comma-join specs to apply any of them, e.g. `[some-tag],[other-tag]`.
This allows test cases that are tagged with **either** "[some-tag]" **or**
"[other-tag]". A test case with both will obviously also pass the filter.
Note that commas take precendence over simple concatenation. This means
that `[a][b],[c]` accepts tests that are tagged with either both "[a]" and
"[b]", or tests that are tagged with just "[c]".
* Negate the spec by prepending it with `~`, e.g. `~[some-tag]`.
This rejects any test case that is tagged with "[some-tag]". Note that
rejection takes precedence over other filters.
Note that negations always binds to the following _basic_ test spec.
This means that `~[foo][bar]` negates only the "[foo]" tag and not the
"[bar]" tag.
Note that when Catch2 is deciding whether to include a test, first it
checks whether the test matches any negative filters. If it does,
the test is rejected. After that, the behaviour depends on whether there
are positive filters as well. If there are no positive filters, all
remaining non-hidden tests are included. If there are positive filters,
only tests that match the positive filters are included.
You can also match test names with special characters by escaping them
with a backslash (`"\"`), e.g. a test named `"Do A, then B"` is matched
by `"Do A\, then B"` test spec. Backslash also escapes itself.
### Examples
Given these TEST_CASEs,
```
TEST_CASE("Test 1") {}
TEST_CASE("Test 2", "[.foo]") {}
TEST_CASE("Test 3", "[.bar]") {}
TEST_CASE("Test 4", "[.][foo][bar]") {}
```
this is the result of these filters
```
./tests # Selects only the first test, others are hidden
./tests "Test 1" # Selects only the first test, other do not match
./tests ~"Test 1" # Selects no tests. Test 1 is rejected, other tests are hidden
./tests "Test *" # Selects all tests.
./tests [bar] # Selects tests 3 and 4. Other tests are not tagged [bar]
./tests ~[foo] # Selects test 1, because it is the only non-hidden test without [foo] tag
./tests [foo][bar] # Selects test 4.
./tests [foo],[bar] # Selects tests 2, 3, 4.
./tests ~[foo][bar] # Selects test 3. 2 and 4 are rejected due to having [foo] tag
./tests ~"Test 2"[foo] # Selects test 4, because test 2 is explicitly rejected
./tests [foo][bar],"Test 1" # Selects tests 1 and 4.
./tests "Test 1*" # Selects test 1, wildcard can match zero characters
```
_Note: Using plain asterisk on a command line can cause issues with shell
expansion. Make sure that the asterisk is passed to Catch2 and is not
interpreted by the shell._
<a id="choosing-a-reporter-to-use"></a>
## Choosing a reporter to use
<pre>-r, --reporter &lt;reporter[::key=value]*&gt;</pre>
Reporters are how the output from Catch2 (results of assertions, tests,
benchmarks and so on) is formatted and written out. The default reporter
is called the "Console" reporter and is intended to provide relatively
verbose and human-friendly output.
Reporters are also individually configurable. To pass configuration options
to the reporter, you append `::key=value` to the reporter specification
as many times as you want, e.g. `--reporter xml::out=someFile.xml` or
`--reporter custom::colour-mode=ansi::Xoption=2`.
The keys must either be prefixed by "X", in which case they are not parsed
by Catch2 and are only passed down to the reporter, or one of options
hardcoded into Catch2. Currently there are only 2,
["out"](#sending-output-to-a-file), and ["colour-mode"](#colour-mode).
_Note that the reporter might still check the X-prefixed options for
validity, and throw an error if they are wrong._
> Support for passing arguments to reporters through the `-r`, `--reporter` flag was introduced in Catch2 3.0.1
There are multiple built-in reporters, you can see what they do by using the
[`--list-reporters`](command-line.md#listing-available-tests-tags-or-reporters)
flag. If you need a reporter providing custom format outside of the already
provided ones, look at the ["write your own reporter" part of the reporter
documentation](reporters.md#writing-your-own-reporter).
This option may be passed multiple times to use multiple (different)
reporters at the same time. See the [reporter documentation](reporters.md#multiple-reporters)
for details on what the resulting behaviour is. Also note that at most one
reporter can be provided without the output-file part of reporter spec.
This reporter will use the "default" output destination, based on
the [`-o`, `--out`](#sending-output-to-a-file) option.
> Support for using multiple different reporters at the same time was [introduced](https://github.com/catchorg/Catch2/pull/2183) in Catch2 3.0.1
_Note: There is currently no way to escape `::` in the reporter spec,
and thus the reporter names, or configuration keys and values, cannot
contain `::`. As `::` in paths is relatively obscure (unlike ':'), we do
not consider this an issue._
<a id="breaking-into-the-debugger"></a>
## Breaking into the debugger
<pre>-b, --break</pre>
Under most debuggers Catch2 is capable of automatically breaking on a test
failure. This allows the user to see the current state of the test during
failure.
<a id="showing-results-for-successful-tests"></a>
## Showing results for successful tests
<pre>-s, --success</pre>
Usually you only want to see reporting for failed tests. Sometimes it's useful to see *all* the output (especially when you don't trust that that test you just added worked first time!).
To see successful, as well as failing, test results just pass this option. Note that each reporter may treat this option differently. The Junit reporter, for example, logs all results regardless.
<a id="aborting-after-a-certain-number-of-failures"></a>
## Aborting after a certain number of failures
<pre>-a, --abort
-x, --abortx [&lt;failure threshold>]
</pre>
If a ```REQUIRE``` assertion fails the test case aborts, but subsequent test cases are still run.
If a ```CHECK``` assertion fails even the current test case is not aborted.
Sometimes this results in a flood of failure messages and you'd rather just see the first few. Specifying ```-a``` or ```--abort``` on its own will abort the whole test run on the first failed assertion of any kind. Use ```-x``` or ```--abortx``` followed by a number to abort after that number of assertion failures.
<a id="listing-available-tests-tags-or-reporters"></a>
## Listing available tests, tags or reporters
```
--list-tests
--list-tags
--list-reporters
--list-listeners
```
> The `--list*` options became customizable through reporters in Catch2 3.0.1
> The `--list-listeners` option was added in Catch2 3.0.1
`--list-tests` lists all registered tests matching specified test spec.
Usually this listing also includes tags, and potentially also other
information, like source location, based on verbosity and reporter's design.
`--list-tags` lists all tags from registered tests matching specified test
spec. Usually this also includes number of tests cases they match and
similar information.
`--list-reporters` lists all available reporters and their descriptions.
`--list-listeners` lists all registered listeners and their descriptions.
The [`--verbosity` argument](#output-verbosity) modifies the level of detail provided by the default `--list*` options
as follows:
| Option | `normal` (default) | `quiet` | `high` |
|--------------------|---------------------------------|---------------------|-----------------------------------------|
| `--list-tests` | Test names and tags | Test names only | Same as `normal`, plus source code line |
| `--list-tags` | Tags and counts | Same as `normal` | Same as `normal` |
| `--list-reporters` | Reporter names and descriptions | Reporter names only | Same as `normal` |
| `--list-listeners` | Listener names and descriptions | Same as `normal` | Same as `normal` |
<a id="sending-output-to-a-file"></a>
## Sending output to a file
<pre>-o, --out &lt;filename&gt;
</pre>
Use this option to send all output to a file, instead of stdout. You can
use `-` as the filename to explicitly send the output to stdout (this is
useful e.g. when using multiple reporters).
> Support for `-` as the filename was introduced in Catch2 3.0.1
Filenames starting with "%" (percent symbol) are reserved by Catch2 for
meta purposes, e.g. using `%debug` as the filename opens stream that
writes to platform specific debugging/logging mechanism.
Catch2 currently recognizes 3 meta streams:
* `%debug` - writes to platform specific debugging/logging output
* `%stdout` - writes to stdout
* `%stderr` - writes to stderr
> Support for `%stdout` and `%stderr` was introduced in Catch2 3.0.1
<a id="naming-a-test-run"></a>
## Naming a test run
<pre>-n, --name &lt;name for test run></pre>
If a name is supplied it will be used by the reporter to provide an overall name for the test run. This can be useful if you are sending to a file, for example, and need to distinguish different test runs - either from different Catch executables or runs of the same executable with different options. If not supplied the name is defaulted to the name of the executable.
<a id="eliding-assertions-expected-to-throw"></a>
## Eliding assertions expected to throw
<pre>-e, --nothrow</pre>
Skips all assertions that test that an exception is thrown, e.g. ```REQUIRE_THROWS```.
These can be a nuisance in certain debugging environments that may break when exceptions are thrown (while this is usually optional for handled exceptions, it can be useful to have enabled if you are trying to track down something unexpected).
Sometimes exceptions are expected outside of one of the assertions that tests for them (perhaps thrown and caught within the code-under-test). The whole test case can be skipped when using ```-e``` by marking it with the ```[!throws]``` tag.
When running with this option any throw checking assertions are skipped so as not to contribute additional noise. Be careful if this affects the behaviour of subsequent tests.
<a id="invisibles"></a>
## Make whitespace visible
<pre>-i, --invisibles</pre>
If a string comparison fails due to differences in whitespace - especially leading or trailing whitespace - it can be hard to see what's going on.
This option transforms tabs and newline characters into ```\t``` and ```\n``` respectively when printing.
<a id="warnings"></a>
## Warnings
<pre>-w, --warn &lt;warning name></pre>
You can think of Catch2's warnings as the equivalent of `-Werror` (`/WX`)
flag for C++ compilers. It turns some suspicious occurrences, like a section
without assertions, into errors. Because these might be intended, warnings
are not enabled by default, but user can opt in.
You can enable multiple warnings at the same time.
There are currently two warnings implemented:
```
NoAssertions // Fail test case / leaf section if no assertions
// (e.g. `REQUIRE`) is encountered.
UnmatchedTestSpec // Fail test run if any of the CLI test specs did
// not match any tests.
```
> `UnmatchedTestSpec` was introduced in Catch2 3.0.1.
<a id="reporting-timings"></a>
## Reporting timings
<pre>-d, --durations &lt;yes/no></pre>
When set to ```yes``` Catch will report the duration of each test case, in seconds with millisecond precision. Note that it does this regardless of whether a test case passes or fails. Note, also, the certain reporters (e.g. Junit) always report test case durations regardless of this option being set or not.
<pre>-D, --min-duration &lt;value></pre>
> `--min-duration` was [introduced](https://github.com/catchorg/Catch2/pull/1910) in Catch2 2.13.0
When set, Catch will report the duration of each test case that took more
than &lt;value> seconds, in seconds with millisecond precision. This option is overridden by both
`-d yes` and `-d no`, so that either all durations are reported, or none
are.
<a id="input-file"></a>
## Load test names to run from a file
<pre>-f, --input-file &lt;filename></pre>
Provide the name of a file that contains a list of test case names,
one per line. Blank lines are skipped.
A useful way to generate an initial instance of this file is to combine
the [`--list-tests`](#listing-available-tests-tags-or-reporters) flag with
the [`--verbosity quiet`](#output-verbosity) option. You can also
use test specs to filter this list down to what you want first.
<a id="order"></a>
## Specify the order test cases are run
<pre>--order &lt;decl|lex|rand&gt;</pre>
Test cases are ordered one of three ways:
### decl
Declaration order (this is the default order if no --order argument is provided).
Tests in the same translation unit are sorted using their declaration orders,
different TUs are sorted in an implementation (linking) dependent order.
### lex
Lexicographic order. Tests are sorted by their name, their tags are ignored.
### rand
Randomly ordered. The order is dependent on Catch2's random seed (see
[`--rng-seed`](#rng-seed)), and is subset invariant. What this means
is that as long as the random seed is fixed, running only some tests
(e.g. via tag) does not change their relative order.
> The subset stability was introduced in Catch2 v2.12.0
Since the random order was made subset stable, we promise that given
the same random seed, the order of test cases will be the same across
different platforms, as long as the tests were compiled against identical
version of Catch2. We reserve the right to change the relative order
of tests cases between Catch2 versions, but it is unlikely to happen often.
<a id="rng-seed"></a>
## Specify a seed for the Random Number Generator
<pre>--rng-seed &lt;'time'|'random-device'|number&gt;</pre>
Sets the seed for random number generators used by Catch2. These are used
e.g. to shuffle tests when user asks for tests to be in random order.
Using `time` as the argument asks Catch2 generate the seed through call
to `std::time(nullptr)`. This provides very weak randomness and multiple
runs of the binary can generate the same seed if they are started close
to each other.
Using `random-device` asks for `std::random_device` to be used instead.
If your implementation provides working `std::random_device`, it should
be preferred to using `time`. Catch2 uses `std::random_device` by default.
<a id="libidentify"></a>
## Identify framework and version according to the libIdentify standard
<pre>--libidentify</pre>
See [The LibIdentify repo for more information and examples](https://github.com/janwilmans/LibIdentify).
<a id="wait-for-keypress"></a>
## Wait for key before continuing
<pre>--wait-for-keypress &lt;never|start|exit|both&gt;</pre>
Will cause the executable to print a message and wait until the return/ enter key is pressed before continuing -
either before running any tests, after running all tests - or both, depending on the argument.
<a id="skip-benchmarks"></a>
## Skip all benchmarks
<pre>--skip-benchmarks</pre>
> [Introduced](https://github.com/catchorg/Catch2/issues/2408) in Catch2 3.0.1.
This flag tells Catch2 to skip running all benchmarks. Benchmarks in this
case mean code blocks in `BENCHMARK` and `BENCHMARK_ADVANCED` macros, not
test cases with the `[!benchmark]` tag.
<a id="benchmark-samples"></a>
## Specify the number of benchmark samples to collect
<pre>--benchmark-samples &lt;# of samples&gt;</pre>
> [Introduced](https://github.com/catchorg/Catch2/issues/1616) in Catch2 2.9.0.
When running benchmarks a number of "samples" is collected. This is the base data for later statistical analysis.
Per sample a clock resolution dependent number of iterations of the user code is run, which is independent of the number of samples. Defaults to 100.
<a id="benchmark-resamples"></a>
## Specify the number of resamples for bootstrapping
<pre>--benchmark-resamples &lt;# of resamples&gt;</pre>
> [Introduced](https://github.com/catchorg/Catch2/issues/1616) in Catch2 2.9.0.
After the measurements are performed, statistical [bootstrapping] is performed
on the samples. The number of resamples for that bootstrapping is configurable
but defaults to 100000. Due to the bootstrapping it is possible to give
estimates for the mean and standard deviation. The estimates come with a lower
bound and an upper bound, and the confidence interval (which is configurable but
defaults to 95%).
[bootstrapping]: http://en.wikipedia.org/wiki/Bootstrapping_%28statistics%29
<a id="benchmark-confidence-interval"></a>
## Specify the confidence-interval for bootstrapping
<pre>--benchmark-confidence-interval &lt;confidence-interval&gt;</pre>
> [Introduced](https://github.com/catchorg/Catch2/issues/1616) in Catch2 2.9.0.
The confidence-interval is used for statistical bootstrapping on the samples to
calculate the upper and lower bounds of mean and standard deviation.
Must be between 0 and 1 and defaults to 0.95.
<a id="benchmark-no-analysis"></a>
## Disable statistical analysis of collected benchmark samples
<pre>--benchmark-no-analysis</pre>
> [Introduced](https://github.com/catchorg/Catch2/issues/1616) in Catch2 2.9.0.
When this flag is specified no bootstrapping or any other statistical analysis is performed.
Instead the user code is only measured and the plain mean from the samples is reported.
<a id="benchmark-warmup-time"></a>
## Specify the amount of time in milliseconds spent on warming up each test
<pre>--benchmark-warmup-time</pre>
> [Introduced](https://github.com/catchorg/Catch2/pull/1844) in Catch2 2.11.2.
Configure the amount of time spent warming up each test.
<a id="usage"></a>
## Usage
<pre>-h, -?, --help</pre>
Prints the command line arguments to stdout
<a id="run-section"></a>
## Specify the section to run
<pre>-c, --section &lt;section name&gt;</pre>
To limit execution to a specific section within a test case, use this option one or more times.
To narrow to sub-sections use multiple instances, where each subsequent instance specifies a deeper nesting level.
E.g. if you have:
<pre>
TEST_CASE( "Test" ) {
SECTION( "sa" ) {
SECTION( "sb" ) {
/*...*/
}
SECTION( "sc" ) {
/*...*/
}
}
SECTION( "sd" ) {
/*...*/
}
}
</pre>
Then you can run `sb` with:
<pre>./MyExe Test -c sa -c sb</pre>
Or run just `sd` with:
<pre>./MyExe Test -c sd</pre>
To run all of `sa`, including `sb` and `sc` use:
<pre>./MyExe Test -c sa</pre>
There are some limitations of this feature to be aware of:
- Code outside of sections being skipped will still be executed - e.g. any set-up code in the TEST_CASE before the
start of the first section.</br>
- At time of writing, wildcards are not supported in section names.
- If you specify a section without narrowing to a test case first then all test cases will be executed
(but only matching sections within them).
<a id="filenames-as-tags"></a>
## Filenames as tags
<pre>-#, --filenames-as-tags</pre>
This option adds an extra tag to all test cases. The tag is `#` followed
by the unqualified filename the test case is defined in, with the _last_
extension stripped out.
For example, tests within the file `tests\SelfTest\UsageTests\BDD.tests.cpp`
will be given the `[#BDD.tests]` tag.
<a id="colour-mode"></a>
## Override output colouring
<pre>--colour-mode &lt;ansi|win32|none|default&gt;</pre>
> The `--colour-mode` option replaced the old `--colour` option in Catch2 3.0.1
Catch2 support two different ways of colouring terminal output, and by
default it attempts to make a good guess on which implementation to use
(and whether to even use it, e.g. Catch2 tries to avoid writing colour
codes when writing the results into a file).
`--colour-mode` allows the user to explicitly select what happens.
* `--colour-mode ansi` tells Catch2 to always use ANSI colour codes, even
when writing to a file
* `--colour-mode win32` tells Catch2 to use colour implementation based
on Win32 terminal API
* `--colour-mode none` tells Catch2 to disable colours completely
* `--colour-mode default` lets Catch2 decide
`--colour-mode default` is the default setting.
<a id="test-sharding"></a>
## Test Sharding
<pre>--shard-count <#number of shards>, --shard-index <#shard index to run></pre>
> [Introduced](https://github.com/catchorg/Catch2/pull/2257) in Catch2 3.0.1.
When `--shard-count <#number of shards>` is used, the tests to execute
will be split evenly in to the given number of sets, identified by indices
starting at 0. The tests in the set given by
`--shard-index <#shard index to run>` will be executed. The default shard
count is `1`, and the default index to run is `0`.
_Shard index must be less than number of shards. As the name suggests,
it is treated as an index of the shard to run._
Sharding is useful when you want to split test execution across multiple
processes, as is done with the [Bazel test sharding](https://docs.bazel.build/versions/main/test-encyclopedia.html#test-sharding).
<a id="no-tests-override"></a>
## Allow running the binary without tests
<pre>--allow-running-no-tests</pre>
> Introduced in Catch2 3.0.1.
By default, Catch2 test binaries return non-0 exit code if no tests were run,
e.g. if the binary was compiled with no tests, the provided test spec matched no
tests, or all tests [were skipped at runtime](skipping-passing-failing.md#top). This flag
overrides that, so a test run with no tests still returns 0.
## Output verbosity
```
-v, --verbosity <quiet|normal|high>
```
Changing verbosity might change how many details Catch2's reporters output.
However, you should consider changing the verbosity level as a _suggestion_.
Not all reporters support all verbosity levels, e.g. because the reporter's
format cannot meaningfully change. In that case, the verbosity level is
ignored.
Verbosity defaults to _normal_.
---
[Home](Readme.md#top)

View File

@ -0,0 +1,23 @@
<a id="top"></a>
# Commercial users of Catch2
Catch2 is also widely used in proprietary code bases. This page contains
some of them that are willing to share this information.
If you want to add your organisation, please check that there is no issue
with you sharing this fact.
- Bloomberg
- [Bloomlife](https://bloomlife.com)
- [Inscopix Inc.](https://www.inscopix.com/)
- Locksley.CZ
- [Makimo](https://makimo.pl/)
- NASA
- [Nexus Software Systems](https://nexwebsites.com)
- [UX3D](https://ux3d.io)
- [King](https://king.com)
---
[Home](Readme.md#top)

View File

@ -0,0 +1,192 @@
<a id="top"></a>
# Comparing floating point numbers with Catch2
If you are not deeply familiar with them, floating point numbers can be
unintuitive. This also applies to comparing floating point numbers for
(in)equality.
This page assumes that you have some understanding of both FP, and the
meaning of different kinds of comparisons, and only goes over what
functionality Catch2 provides to help you with comparing floating point
numbers. If you do not have this understanding, we recommend that you first
study up on floating point numbers and their comparisons, e.g. by [reading
this blog post](https://codingnest.com/the-little-things-comparing-floating-point-numbers/).
## Floating point matchers
```
#include <catch2/matchers/catch_matchers_floating_point.hpp>
```
[Matchers](matchers.md#top) are the preferred way of comparing floating
point numbers in Catch2. We provide 3 of them:
* `WithinAbs(double target, double margin)`,
* `WithinRel(FloatingPoint target, FloatingPoint eps)`, and
* `WithinULP(FloatingPoint target, uint64_t maxUlpDiff)`.
> `WithinRel` matcher was introduced in Catch2 2.10.0
As with all matchers, you can combine multiple floating point matchers
in a single assertion. For example, to check that some computation matches
a known good value within 0.1% or is close enough (no different to 5
decimal places) to zero, we would write this assertion:
```cpp
REQUIRE_THAT( computation(input),
Catch::Matchers::WithinRel(expected, 0.001)
|| Catch::Matchers::WithinAbs(0, 0.000001) );
```
### WithinAbs
`WithinAbs` creates a matcher that accepts floating point numbers whose
difference with `target` is less-or-equal to the `margin`. Since `float`
can be converted to `double` without losing precision, only `double`
overload exists.
```cpp
REQUIRE_THAT(1.0, WithinAbs(1.2, 0.2));
REQUIRE_THAT(0.f, !WithinAbs(1.0, 0.5));
// Notice that infinity == infinity for WithinAbs
REQUIRE_THAT(INFINITY, WithinAbs(INFINITY, 0));
```
### WithinRel
`WithinRel` creates a matcher that accepts floating point numbers that
are _approximately equal_ to the `target` with a tolerance of `eps.`
Specifically, it matches if
`|arg - target| <= eps * max(|arg|, |target|)` holds. If you do not
specify `eps`, `std::numeric_limits<FloatingPoint>::epsilon * 100`
is used as the default.
```cpp
// Notice that WithinRel comparison is symmetric, unlike Approx's.
REQUIRE_THAT(1.0, WithinRel(1.1, 0.1));
REQUIRE_THAT(1.1, WithinRel(1.0, 0.1));
// Notice that inifnity == infinity for WithinRel
REQUIRE_THAT(INFINITY, WithinRel(INFINITY));
```
### WithinULP
`WithinULP` creates a matcher that accepts floating point numbers that
are no more than `maxUlpDiff`
[ULPs](https://en.wikipedia.org/wiki/Unit_in_the_last_place)
away from the `target` value. The short version of what this means
is that there is no more than `maxUlpDiff - 1` representable floating
point numbers between the argument for matching and the `target` value.
When using the ULP matcher in Catch2, it is important to keep in mind
that Catch2 interprets ULP distance slightly differently than
e.g. `std::nextafter` does.
Catch2's ULP calculation obeys these relations:
* `ulpDistance(-x, x) == 2 * ulpDistance(x, 0)`
* `ulpDistance(-0, 0) == 0` (due to the above)
* `ulpDistance(DBL_MAX, INFINITY) == 1`
* `ulpDistancE(NaN, x) == infinity`
**Important**: The WithinULP matcher requires the platform to use the
[IEEE-754](https://en.wikipedia.org/wiki/IEEE_754) representation for
floating point numbers.
```cpp
REQUIRE_THAT( -0.f, WithinULP( 0.f, 0 ) );
```
## `Approx`
```
#include <catch2/catch_approx.hpp>
```
**We strongly recommend against using `Approx` when writing new code.**
You should be using floating point matchers instead.
Catch2 provides one more way to handle floating point comparisons. It is
`Approx`, a special type with overloaded comparison operators, that can
be used in standard assertions, e.g.
```cpp
REQUIRE(0.99999 == Catch::Approx(1));
```
`Approx` supports four comparison operators, `==`, `!=`, `<=`, `>=`, and can
also be used with strong typedefs over `double`s. It can be used for both
relative and margin comparisons by using its three customization points.
Note that the semantics of this is always that of an _or_, so if either
the relative or absolute margin comparison passes, then the whole comparison
passes.
The downside to `Approx` is that it has a couple of issues that we cannot
fix without breaking backwards compatibility. Because Catch2 also provides
complete set of matchers that implement different floating point comparison
methods, `Approx` is left as-is, is considered deprecated, and should
not be used in new code.
The issues are
* All internal computation is done in `double`s, leading to slightly
different results if the inputs were floats.
* `Approx`'s relative margin comparison is not symmetric. This means
that `Approx( 10 ).epsilon(0.1) != 11.1` but `Approx( 11.1 ).epsilon(0.1) == 10`.
* By default, `Approx` only uses relative margin comparison. This means
that `Approx(0) == X` only passes for `X == 0`.
### Approx details
If you still want/need to know more about `Approx`, read on.
Catch2 provides a UDL for `Approx`; `_a`. It resides in the `Catch::literals`
namespace, and can be used like this:
```cpp
using namespace Catch::literals;
REQUIRE( performComputation() == 2.1_a );
```
`Approx` has three customization points for the comparison:
* **epsilon** - epsilon sets the coefficient by which a result
can differ from `Approx`'s value before it is rejected.
_Defaults to `std::numeric_limits<float>::epsilon()*100`._
```cpp
Approx target = Approx(100).epsilon(0.01);
100.0 == target; // Obviously true
200.0 == target; // Obviously still false
100.5 == target; // True, because we set target to allow up to 1% difference
```
* **margin** - margin sets the absolute value by which
a result can differ from `Approx`'s value before it is rejected.
_Defaults to `0.0`._
```cpp
Approx target = Approx(100).margin(5);
100.0 == target; // Obviously true
200.0 == target; // Obviously still false
104.0 == target; // True, because we set target to allow absolute difference of at most 5
```
* **scale** - scale is used to change the magnitude of `Approx` for the relative check.
_By default, set to `0.0`._
Scale could be useful if the computation leading to the result worked
on a different scale than is used by the results. Approx's scale is added
to Approx's value when computing the allowed relative margin from the
Approx's value.
---
[Home](Readme.md#top)

View File

@ -0,0 +1,296 @@
<a id="top"></a>
# Compile-time configuration
**Contents**<br>
[Prefixing Catch macros](#prefixing-catch-macros)<br>
[Terminal colour](#terminal-colour)<br>
[Console width](#console-width)<br>
[stdout](#stdout)<br>
[Fallback stringifier](#fallback-stringifier)<br>
[Default reporter](#default-reporter)<br>
[Bazel support](#bazel-support)<br>
[C++11 toggles](#c11-toggles)<br>
[C++17 toggles](#c17-toggles)<br>
[Other toggles](#other-toggles)<br>
[Enabling stringification](#enabling-stringification)<br>
[Disabling exceptions](#disabling-exceptions)<br>
[Overriding Catch's debug break (`-b`)](#overriding-catchs-debug-break--b)<br>
[Static analysis support](#static-analysis-support)<br>
Catch2 is designed to "just work" as much as possible, and most of the
configuration options below are changed automatically during compilation,
according to the detected environment. However, this detection can also
be overridden by users, using macros documented below, and/or CMake options
with the same name.
## Prefixing Catch macros
CATCH_CONFIG_PREFIX_ALL // Prefix all macros with CATCH_
CATCH_CONFIG_PREFIX_MESSAGES // Prefix only INFO, UNSCOPED_INFO, WARN and CAPTURE
To keep test code clean and uncluttered Catch uses short macro names (e.g. ```TEST_CASE``` and ```REQUIRE```). Occasionally these may conflict with identifiers from platform headers or the system under test. In this case the above identifier can be defined. This will cause all the Catch user macros to be prefixed with ```CATCH_``` (e.g. ```CATCH_TEST_CASE``` and ```CATCH_REQUIRE```).
## Terminal colour
CATCH_CONFIG_COLOUR_WIN32 // Force enables compiling colouring impl based on Win32 console API
CATCH_CONFIG_NO_COLOUR_WIN32 // Force disables ...
Yes, Catch2 uses the british spelling of colour.
Catch2 attempts to autodetect whether the Win32 console colouring API,
`SetConsoleTextAttribute`, is available, and if it is available it compiles
in a console colouring implementation that uses it.
This option can be used to override Catch2's autodetection and force the
compilation either ON or OFF.
## Console width
CATCH_CONFIG_CONSOLE_WIDTH = x // where x is a number
Catch formats output intended for the console to fit within a fixed number of characters. This is especially important as indentation is used extensively and uncontrolled line wraps break this.
By default a console width of 80 is assumed but this can be controlled by defining the above identifier to be a different value.
## stdout
CATCH_CONFIG_NOSTDOUT
To support platforms that do not provide `std::cout`, `std::cerr` and
`std::clog`, Catch does not use them directly, but rather calls
`Catch::cout`, `Catch::cerr` and `Catch::clog`. You can replace their
implementation by defining `CATCH_CONFIG_NOSTDOUT` and implementing
them yourself, their signatures are:
std::ostream& cout();
std::ostream& cerr();
std::ostream& clog();
[You can see an example of replacing these functions here.](
../examples/231-Cfg-OutputStreams.cpp)
## Fallback stringifier
By default, when Catch's stringification machinery has to stringify
a type that does not specialize `StringMaker`, does not overload `operator<<`,
is not an enumeration and is not a range, it uses `"{?}"`. This can be
overridden by defining `CATCH_CONFIG_FALLBACK_STRINGIFIER` to name of a
function that should perform the stringification instead.
All types that do not provide `StringMaker` specialization or `operator<<`
overload will be sent to this function (this includes enums and ranges).
The provided function must return `std::string` and must accept any type,
e.g. via overloading.
_Note that if the provided function does not handle a type and this type
requires to be stringified, the compilation will fail._
## Default reporter
Catch's default reporter can be changed by defining macro
`CATCH_CONFIG_DEFAULT_REPORTER` to string literal naming the desired
default reporter.
This means that defining `CATCH_CONFIG_DEFAULT_REPORTER` to `"console"`
is equivalent with the out-of-the-box experience.
## Bazel support
Compiling Catch2 with `CATCH_CONFIG_BAZEL_SUPPORT` force-enables Catch2's
support for Bazel's environment variables (normally Catch2 looks for
`BAZEL_TEST=1` env var first).
This can be useful if you are using older versions of Bazel, that do not
yet have `BAZEL_TEST` env var support.
> `CATCH_CONFIG_BAZEL_SUPPORT` was [introduced](https://github.com/catchorg/Catch2/pull/2399) in Catch2 3.0.1.
> `CATCH_CONFIG_BAZEL_SUPPORT` was [deprecated](https://github.com/catchorg/Catch2/pull/2459) in Catch2 3.1.0.
## C++11 toggles
CATCH_CONFIG_CPP11_TO_STRING // Use `std::to_string`
Because we support platforms whose standard library does not contain
`std::to_string`, it is possible to force Catch to use a workaround
based on `std::stringstream`. On platforms other than Android,
the default is to use `std::to_string`. On Android, the default is to
use the `stringstream` workaround. As always, it is possible to override
Catch's selection, by defining either `CATCH_CONFIG_CPP11_TO_STRING` or
`CATCH_CONFIG_NO_CPP11_TO_STRING`.
## C++17 toggles
CATCH_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS // Override std::uncaught_exceptions (instead of std::uncaught_exception) support detection
CATCH_CONFIG_CPP17_STRING_VIEW // Override std::string_view support detection (Catch provides a StringMaker specialization by default)
CATCH_CONFIG_CPP17_VARIANT // Override std::variant support detection (checked by CATCH_CONFIG_ENABLE_VARIANT_STRINGMAKER)
CATCH_CONFIG_CPP17_OPTIONAL // Override std::optional support detection (checked by CATCH_CONFIG_ENABLE_OPTIONAL_STRINGMAKER)
CATCH_CONFIG_CPP17_BYTE // Override std::byte support detection (Catch provides a StringMaker specialization by default)
> `CATCH_CONFIG_CPP17_STRING_VIEW` was [introduced](https://github.com/catchorg/Catch2/issues/1376) in Catch2 2.4.1.
Catch contains basic compiler/standard detection and attempts to use
some C++17 features whenever appropriate. This automatic detection
can be manually overridden in both directions, that is, a feature
can be enabled by defining the macro in the table above, and disabled
by using `_NO_` in the macro, e.g. `CATCH_CONFIG_NO_CPP17_UNCAUGHT_EXCEPTIONS`.
## Other toggles
CATCH_CONFIG_COUNTER // Use __COUNTER__ to generate unique names for test cases
CATCH_CONFIG_WINDOWS_SEH // Enable SEH handling on Windows
CATCH_CONFIG_FAST_COMPILE // Sacrifices some (rather minor) features for compilation speed
CATCH_CONFIG_POSIX_SIGNALS // Enable handling POSIX signals
CATCH_CONFIG_WINDOWS_CRTDBG // Enable leak checking using Windows's CRT Debug Heap
CATCH_CONFIG_DISABLE_STRINGIFICATION // Disable stringifying the original expression
CATCH_CONFIG_DISABLE // Disables assertions and test case registration
CATCH_CONFIG_WCHAR // Enables use of wchart_t
CATCH_CONFIG_EXPERIMENTAL_REDIRECT // Enables the new (experimental) way of capturing stdout/stderr
CATCH_CONFIG_USE_ASYNC // Force parallel statistical processing of samples during benchmarking
CATCH_CONFIG_ANDROID_LOGWRITE // Use android's logging system for debug output
CATCH_CONFIG_GLOBAL_NEXTAFTER // Use nextafter{,f,l} instead of std::nextafter
CATCH_CONFIG_GETENV // System has a working `getenv`
> [`CATCH_CONFIG_ANDROID_LOGWRITE`](https://github.com/catchorg/Catch2/issues/1743) and [`CATCH_CONFIG_GLOBAL_NEXTAFTER`](https://github.com/catchorg/Catch2/pull/1739) were introduced in Catch2 2.10.0
> `CATCH_CONFIG_GETENV` was [introduced](https://github.com/catchorg/Catch2/pull/2562) in Catch2 3.2.0
Currently Catch enables `CATCH_CONFIG_WINDOWS_SEH` only when compiled with MSVC, because some versions of MinGW do not have the necessary Win32 API support.
`CATCH_CONFIG_POSIX_SIGNALS` is on by default, except when Catch is compiled under `Cygwin`, where it is disabled by default (but can be force-enabled by defining `CATCH_CONFIG_POSIX_SIGNALS`).
`CATCH_CONFIG_GETENV` is on by default, except when Catch2 is compiled for
platforms that lacks working `std::getenv` (currently Windows UWP and
Playstation).
`CATCH_CONFIG_WINDOWS_CRTDBG` is off by default. If enabled, Windows's
CRT is used to check for memory leaks, and displays them after the tests
finish running. This option only works when linking against the default
main, and must be defined for the whole library build.
`CATCH_CONFIG_WCHAR` is on by default, but can be disabled. Currently
it is only used in support for DJGPP cross-compiler.
With the exception of `CATCH_CONFIG_EXPERIMENTAL_REDIRECT`,
these toggles can be disabled by using `_NO_` form of the toggle,
e.g. `CATCH_CONFIG_NO_WINDOWS_SEH`.
### `CATCH_CONFIG_FAST_COMPILE`
This compile-time flag speeds up compilation of assertion macros by ~20%,
by disabling the generation of assertion-local try-catch blocks for
non-exception family of assertion macros ({`REQUIRE`,`CHECK`}{``,`_FALSE`, `_THAT`}).
This disables translation of exceptions thrown under these assertions, but
should not lead to false negatives.
`CATCH_CONFIG_FAST_COMPILE` has to be either defined, or not defined,
in all translation units that are linked into single test binary.
### `CATCH_CONFIG_DISABLE_STRINGIFICATION`
This toggle enables a workaround for VS 2017 bug. For details see [known limitations](limitations.md#visual-studio-2017----raw-string-literal-in-assert-fails-to-compile).
### `CATCH_CONFIG_DISABLE`
This toggle removes most of Catch from given file. This means that `TEST_CASE`s are not registered and assertions are turned into no-ops. Useful for keeping tests within implementation files (ie for functions with internal linkage), instead of in external files.
This feature is considered experimental and might change at any point.
_Inspired by Doctest's `DOCTEST_CONFIG_DISABLE`_
## Enabling stringification
By default, Catch does not stringify some types from the standard library. This is done to avoid dragging in various standard library headers by default. However, Catch does contain these and can be configured to provide them, using these macros:
CATCH_CONFIG_ENABLE_PAIR_STRINGMAKER // Provide StringMaker specialization for std::pair
CATCH_CONFIG_ENABLE_TUPLE_STRINGMAKER // Provide StringMaker specialization for std::tuple
CATCH_CONFIG_ENABLE_VARIANT_STRINGMAKER // Provide StringMaker specialization for std::variant, std::monostate (on C++17)
CATCH_CONFIG_ENABLE_OPTIONAL_STRINGMAKER // Provide StringMaker specialization for std::optional (on C++17)
CATCH_CONFIG_ENABLE_ALL_STRINGMAKERS // Defines all of the above
> `CATCH_CONFIG_ENABLE_VARIANT_STRINGMAKER` was [introduced](https://github.com/catchorg/Catch2/issues/1380) in Catch2 2.4.1.
> `CATCH_CONFIG_ENABLE_OPTIONAL_STRINGMAKER` was [introduced](https://github.com/catchorg/Catch2/issues/1510) in Catch2 2.6.0.
## Disabling exceptions
> Introduced in Catch2 2.4.0.
By default, Catch2 uses exceptions to signal errors and to abort tests
when an assertion from the `REQUIRE` family of assertions fails. We also
provide an experimental support for disabling exceptions. Catch2 should
automatically detect when it is compiled with exceptions disabled, but
it can be forced to compile without exceptions by defining
CATCH_CONFIG_DISABLE_EXCEPTIONS
Note that when using Catch2 without exceptions, there are 2 major
limitations:
1) If there is an error that would normally be signalled by an exception,
the exception's message will instead be written to `Catch::cerr` and
`std::terminate` will be called.
2) If an assertion from the `REQUIRE` family of macros fails,
`std::terminate` will be called after the active reporter returns.
There is also a customization point for the exact behaviour of what
happens instead of exception being thrown. To use it, define
CATCH_CONFIG_DISABLE_EXCEPTIONS_CUSTOM_HANDLER
and provide a definition for this function:
```cpp
namespace Catch {
[[noreturn]]
void throw_exception(std::exception const&);
}
```
## Overriding Catch's debug break (`-b`)
> [Introduced](https://github.com/catchorg/Catch2/pull/1846) in Catch2 2.11.2.
You can override Catch2's break-into-debugger code by defining the
`CATCH_BREAK_INTO_DEBUGGER()` macro. This can be used if e.g. Catch2 does
not know your platform, or your platform is misdetected.
The macro will be used as is, that is, `CATCH_BREAK_INTO_DEBUGGER();`
must compile and must break into debugger.
## Static analysis support
> Introduced in Catch2 3.4.0.
Some parts of Catch2, e.g. `SECTION`s, can be hard for static analysis
tools to reason about. Catch2 can change its internals to help static
analysis tools reason about the tests.
Catch2 automatically detects some static analysis tools (initial
implementation checks for clang-tidy and Coverity), but you can override
its detection (in either direction) via
```
CATCH_CONFIG_EXPERIMENTAL_STATIC_ANALYSIS_SUPPORT // force enables static analysis help
CATCH_CONFIG_NO_EXPERIMENTAL_STATIC_ANALYSIS_SUPPORT // force disables static analysis help
```
_As the name suggests, this is currently experimental, and thus we provide
no backwards compatibility guarantees._
**DO NOT ENABLE THIS FOR BUILDS YOU INTEND TO RUN.** The changed internals
are not meant to be runnable, only "scannable".
---
[Home](Readme.md#top)

View File

@ -0,0 +1,342 @@
<a id="top"></a>
# Contributing to Catch2
**Contents**<br>
[Using Git(Hub)](#using-github)<br>
[Testing your changes](#testing-your-changes)<br>
[Writing documentation](#writing-documentation)<br>
[Writing code](#writing-code)<br>
[CoC](#coc)<br>
So you want to contribute something to Catch2? That's great! Whether it's
a bug fix, a new feature, support for additional compilers - or just
a fix to the documentation - all contributions are very welcome and very
much appreciated. Of course so are bug reports, other comments, and
questions, but generally it is a better idea to ask questions in our
[Discord](https://discord.gg/4CWS9zD), than in the issue tracker.
This page covers some guidelines and helpful tips for contributing
to the codebase itself.
## Using Git(Hub)
Ongoing development happens in the `devel` branch for Catch2 v3, and in
`v2.x` for maintenance updates to the v2 versions.
Commits should be small and atomic. A commit is atomic when, after it is
applied, the codebase, tests and all, still works as expected. Small
commits are also preferred, as they make later operations with git history,
whether it is bisecting, reverting, or something else, easier.
_When submitting a pull request please do not include changes to the
amalgamated distribution files. This means do not include them in your
git commits!_
When addressing review comments in a MR, please do not rebase/squash the
commits immediately. Doing so makes it harder to review the new changes,
slowing down the process of merging a MR. Instead, when addressing review
comments, you should append new commits to the branch and only squash
them into other commits when the MR is ready to be merged. We recommend
creating new commits with `git commit --fixup` (or `--squash`) and then
later squashing them with `git rebase --autosquash` to make things easier.
## Testing your changes
_Note: Running Catch2's tests requires Python3_
Catch2 has multiple layers of tests that are then run as part of our CI.
The most obvious one are the unit tests compiled into the `SelfTest`
binary. These are then used in "Approval tests", which run (almost) all
tests from `SelfTest` through a specific reporter and then compare the
generated output with a known good output ("Baseline"). By default, new
tests should be placed here.
To configure a Catch2 build with just the basic tests, use the `basic-tests`
preset, like so:
```
# Assuming you are in Catch2's root folder
cmake -B basic-test-build -S . -DCMAKE_BUILD_TYPE=Debug --preset basic-tests
```
However, not all tests can be written as plain unit tests. For example,
checking that Catch2 orders tests randomly when asked to, and that this
random ordering is subset-invariant, is better done as an integration
test using an external check script. Catch2 integration tests are written
using CTest, either as a direct command invocation + pass/fail regex,
or by delegating the check to a Python script.
Catch2 is slowly gaining more and more types of tests, currently Catch2
project also has buildable examples, "ExtraTests", and CMake config tests.
Examples present a small and self-contained snippets of code that
use Catch2's facilities for specific purpose. Currently they are assumed
passing if they compile.
ExtraTests then are expensive tests, that we do not want to run all the
time. This can be either because they take a long time to run, or because
they take a long time to compile, e.g. because they test compile time
configuration and require separate compilation.
Finally, CMake config tests test that you set Catch2's compile-time
configuration options through CMake, using CMake options of the same name.
These test categories can be enabled one by one, by passing
`-DCATCH_BUILD_EXAMPLES=ON`, `-DCATCH_BUILD_EXTRA_TESTS=ON`, and
`-DCATCH_ENABLE_CONFIGURE_TESTS=ON` when configuring the build.
Catch2 also provides a preset that promises to enable _all_ test types,
`all-tests`.
The snippet below will build & run all tests, in `Debug` compilation mode.
<!-- snippet: catch2-build-and-test -->
<a id='snippet-catch2-build-and-test'></a>
```sh
# 1. Regenerate the amalgamated distribution (some tests are built against it)
./tools/scripts/generateAmalgamatedFiles.py
# 2. Configure the full test build
cmake -B debug-build -S . -DCMAKE_BUILD_TYPE=Debug --preset all-tests
# 3. Run the actual build
cmake --build debug-build
# 4. Run the tests using CTest
ctest -j 4 --output-on-failure -C Debug --test-dir debug-build
```
<sup><a href='/tools/scripts/buildAndTest.sh#L6-L19' title='File snippet `catch2-build-and-test` was extracted from'>snippet source</a> | <a href='#snippet-catch2-build-and-test' title='Navigate to start of snippet `catch2-build-and-test`'>anchor</a></sup>
<!-- endSnippet -->
For convenience, the above commands are in the script `tools/scripts/buildAndTest.sh`, and can be run like this:
```bash
cd Catch2
./tools/scripts/buildAndTest.sh
```
A Windows version of the script is available at `tools\scripts\buildAndTest.cmd`.
If you added new tests, you will likely see `ApprovalTests` failure.
After you check that the output difference is expected, you should
run `tools/scripts/approve.py` to confirm them, and include these changes
in your commit.
## Writing documentation
If you have added new feature to Catch2, it needs documentation, so that
other people can use it as well. This section collects some technical
information that you will need for updating Catch2's documentation, and
possibly some generic advise as well.
### Technicalities
First, the technicalities:
* If you have introduced a new document, there is a simple template you
should use. It provides you with the top anchor mentioned to link to
(more below), and also with a backlink to the top of the documentation:
```markdown
<a id="top"></a>
# Cool feature
> [Introduced](https://github.com/catchorg/Catch2/pull/123456) in Catch2 X.Y.Z
Text that explains how to use the cool feature.
---
[Home](Readme.md#top)
```
* Crosslinks to different pages should target the `top` anchor, like this
`[link to contributing](contributing.md#top)`.
* We introduced version tags to the documentation, which show users in
which version a specific feature was introduced. This means that newly
written documentation should be tagged with a placeholder, that will
be replaced with the actual version upon release. There are 2 styles
of placeholders used through the documentation, you should pick one that
fits your text better (if in doubt, take a look at the existing version
tags for other features).
* `> [Introduced](link-to-issue-or-PR) in Catch2 X.Y.Z` - this
placeholder is usually used after a section heading
* `> X (Y and Z) was [introduced](link-to-issue-or-PR) in Catch2 X.Y.Z`
- this placeholder is used when you need to tag a subpart of something,
e.g. a list
* For pages with more than 4 subheadings, we provide a table of contents
(ToC) at the top of the page. Because GitHub markdown does not support
automatic generation of ToC, it has to be handled semi-manually. Thus,
if you've added a new subheading to some page, you should add it to the
ToC. This can be done either manually, or by running the
`updateDocumentToC.py` script in the `scripts/` folder.
### Contents
Now, for some content tips:
* Usage examples are good. However, having large code snippets inline
can make the documentation less readable, and so the inline snippets
should be kept reasonably short. To provide more complex compilable
examples, consider adding new .cpp file to `examples/`.
* Don't be afraid to introduce new pages. The current documentation
tends towards long pages, but a lot of that is caused by legacy, and
we know that some of the pages are overly big and unfocused.
* When adding information to an existing page, please try to keep your
formatting, style and changes consistent with the rest of the page.
* Any documentation has multiple different audiences, that desire
different information from the text. The 3 basic user-types to try and
cover are:
* A beginner to Catch2, who requires closer guidance for the usage of Catch2.
* Advanced user of Catch2, who want to customize their usage.
* Experts, looking for full reference of Catch2's capabilities.
## Writing code
If want to contribute code, this section contains some simple rules
and tips on things like code formatting, code constructions to avoid,
and so on.
### C++ standard version
Catch2 currently targets C++14 as the minimum supported C++ version.
Features from higher language versions should be used only sparingly,
when the benefits from using them outweigh the maintenance overhead.
Example of good use of polyfilling features is our use of `conjunction`,
where if available we use `std::conjunction` and otherwise provide our
own implementation. The reason it is good is that the surface area for
maintenance is quite small, and `std::conjunction` can directly use
compiler built-ins, thus providing significant compilation benefits.
Example of bad use of polyfilling features would be to keep around two
sets of metaprogramming in the stringification implementation, once
using C++14 compliant TMP and once using C++17's `if constexpr`. While
the C++17 would provide significant compilation speedups, the maintenance
cost would be too high.
### Formatting
To make code formatting simpler for the contributors, Catch2 provides
its own config for `clang-format`. However, because it is currently
impossible to replicate existing Catch2's formatting in clang-format,
using it to reformat a whole file would cause massive diffs. To keep
the size of your diffs reasonable, you should only use clang-format
on the newly changed code.
### Code constructs to watch out for
This section is a (sadly incomplete) listing of various constructs that
are problematic and are not always caught by our CI infrastructure.
#### Naked exceptions and exceptions-related function
If you are throwing an exception, it should be done via `CATCH_ERROR`
or `CATCH_RUNTIME_ERROR` in `internal/catch_enforce.hpp`. These macros will handle
the differences between compilation with or without exceptions for you.
However, some platforms (IAR) also have problems with exceptions-related
functions, such as `std::current_exceptions`. We do not have IAR in our
CI, but luckily there should not be too many reasons to use these.
However, if you do, they should be kept behind a
`CATCH_CONFIG_DISABLE_EXCEPTIONS` macro.
#### Avoid `std::move` and `std::forward`
`std::move` and `std::forward` provide nice semantic name for a specific
`static_cast`. However, being function templates they have surprisingly
high cost during compilation, and can also have a negative performance
impact for low-optimization builds.
You should be using `CATCH_MOVE` and `CATCH_FORWARD` macros from
`internal/catch_move_and_forward.hpp` instead. They expand into the proper
`static_cast`, and avoid the overhead of `std::move` and `std::forward`.
#### Unqualified usage of functions from C's stdlib
If you are using a function from C's stdlib, please include the header
as `<cfoo>` and call the function qualified. The common knowledge that
there is no difference is wrong, QNX and VxWorks won't compile if you
include the header as `<cfoo>` and call the function unqualified.
#### User-Defined Literals (UDL) for Catch2' types
Due to messy standardese and ... not great ... implementation of
`-Wreserved-identifier` in Clang, avoid declaring UDLs as
```cpp
Approx operator "" _a(long double);
```
and instead declare them as
```cpp
Approx operator ""_a(long double);
```
Notice that the second version does not have a space between the `""` and
the literal suffix.
### New source file template
If you are adding new source file, there is a template you should use.
Specifically, every source file should start with the licence header:
```cpp
// Copyright Catch2 Authors
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE.txt or copy at
// https://www.boost.org/LICENSE_1_0.txt)
// SPDX-License-Identifier: BSL-1.0
```
The include guards for header files should follow the pattern `{FILENAME}_INCLUDED`.
This means that for file `catch_matchers_foo.hpp`, the include guard should
be `CATCH_MATCHERS_FOO_HPP_INCLUDED`, for `catch_generators_bar.hpp`, the include
guard should be `CATCH_GENERATORS_BAR_HPP_INCLUDED`, and so on.
### Adding new `CATCH_CONFIG` option
When adding new `CATCH_CONFIG` option, there are multiple places to edit:
* `CMake/CatchConfigOptions.cmake` - this is used to generate the
configuration options in CMake, so that CMake frontends know about them.
* `docs/configuration.md` - this is where the options are documented
* `src/catch2/catch_user_config.hpp.in` - this is template for generating
`catch_user_config.hpp` which contains the materialized configuration
* `BUILD.bazel` - Bazel does not have configuration support like CMake,
and all expansions need to be done manually
* other files as needed, e.g. `catch2/internal/catch_config_foo.hpp`
for the logic that guards the configuration
## CoC
This project has a [CoC](../CODE_OF_CONDUCT.md). Please adhere to it
while contributing to Catch2.
-----------
_This documentation will always be in-progress as new information comes
up, but we are trying to keep it as up to date as possible._
---
[Home](Readme.md#top)

View File

@ -0,0 +1,53 @@
<a id="top"></a>
# Deprecations and incoming changes
This page documents current deprecations and upcoming planned changes
inside Catch2. The difference between these is that a deprecated feature
will be removed, while a planned change to a feature means that the
feature will behave differently, but will still be present. Obviously,
either of these is a breaking change, and thus will not happen until
at least the next major release.
### `ParseAndAddCatchTests.cmake`
The CMake/CTest integration using `ParseAndAddCatchTests.cmake` is deprecated,
as it can be replaced by `Catch.cmake` that provides the function
`catch_discover_tests` to get tests directly from a CMake target via the
command line interface instead of parsing C++ code with regular expressions.
### `CATCH_CONFIG_BAZEL_SUPPORT`
Catch2 supports writing the Bazel JUnit XML output file when it is aware
that is within a bazel testing environment. Originally there was no way
to accurately probe the environment for this information so the flag
`CATCH_CONFIG_BAZEL_SUPPORT` was added. This now deprecated. Bazel has now had a change
where it will export `BAZEL_TEST=1` for purposes like the above. Catch2
will now instead inspect the environment instead of relying on build configuration.
### `IEventLister::skipTest( TestCaseInfo const& testInfo )`
This event (including implementations in derived classes such as `ReporterBase`)
is deprecated and will be removed in the next major release. It is currently
invoked for all test cases that are not going to be executed due to the test run
being aborted (when using `--abort` or `--abortx`). It is however
**NOT** invoked for test cases that are [explicitly skipped using the `SKIP`
macro](skipping-passing-failing.md#top).
### Non-const function for `TEST_CASE_METHOD`
> Deprecated in Catch2 vX.Y.Z
Currently, the member function generated for `TEST_CASE_METHOD` is
not `const` qualified. In the future, the generated member function will
be `const` qualified, just as `TEST_CASE_PERSISTENT_FIXTURE` does.
If you are mutating the fixture instance from within the test case, and
want to keep doing so in the future, mark the mutated members as `mutable`.
---
[Home](Readme.md#top)

View File

@ -0,0 +1,44 @@
<a id="top"></a>
# Event Listeners
An event listener is a bit like a reporter, in that it responds to various
reporter events in Catch2, but it is not expected to write any output.
Instead, an event listener performs actions within the test process, such
as performing global initialization (e.g. of a C library), or cleaning out
in-memory logs if they are not needed (the test case passed).
Unlike reporters, each registered event listener is always active. Event
listeners are always notified before reporter(s).
To write your own event listener, you should derive from `Catch::TestEventListenerBase`,
as it provides empty stubs for all reporter events, allowing you to
only override events you care for. Afterwards you have to register it
with Catch2 using `CATCH_REGISTER_LISTENER` macro, so that Catch2 knows
about it and instantiates it before running tests.
Example event listener:
```cpp
#include <catch2/reporters/catch_reporter_event_listener.hpp>
#include <catch2/reporters/catch_reporter_registrars.hpp>
class testRunListener : public Catch::EventListenerBase {
public:
using Catch::EventListenerBase::EventListenerBase;
void testRunStarting(Catch::TestRunInfo const&) override {
lib_foo_init();
}
};
CATCH_REGISTER_LISTENER(testRunListener)
```
_Note that you should not use any assertion macros within a Listener!_
[You can find the list of events that the listeners can react to on its
own page](reporter-events.md#top).
---
[Home](Readme.md#top)

View File

@ -0,0 +1,113 @@
<a id="top"></a>
# Frequently Asked Questions (FAQ)
**Contents**<br>
[How do I run global setup/teardown only if tests will be run?](#how-do-i-run-global-setupteardown-only-if-tests-will-be-run)<br>
[How do I clean up global state between running different tests?](#how-do-i-clean-up-global-state-between-running-different-tests)<br>
[Why cannot I derive from the built-in reporters?](#why-cannot-i-derive-from-the-built-in-reporters)<br>
[What is Catch2's ABI stability policy?](#what-is-catch2s-abi-stability-policy)<br>
[What is Catch2's API stability policy?](#what-is-catch2s-api-stability-policy)<br>
[Does Catch2 support running tests in parallel?](#does-catch2-support-running-tests-in-parallel)<br>
[Can I compile Catch2 into a dynamic library?](#can-i-compile-catch2-into-a-dynamic-library)<br>
[What repeatability guarantees does Catch2 provide?](#what-repeatability-guarantees-does-catch2-provide)<br>
[My build cannot find `catch2/catch_user_config.hpp`, how can I fix it?](#my-build-cannot-find-catch2catch_user_confighpp-how-can-i-fix-it)<br>
## How do I run global setup/teardown only if tests will be run?
Write a custom [event listener](event-listeners.md#top) and place the
global setup/teardown code into the `testRun*` events.
## How do I clean up global state between running different tests?
Write a custom [event listener](event-listeners.md#top) and place the
cleanup code into either `testCase*` or `testCasePartial*` events,
depending on how often the cleanup needs to happen.
## Why cannot I derive from the built-in reporters?
They are not made to be overridden, in that we do not attempt to maintain
a consistent internal state if a member function is overridden, and by
forbidding users from using them as a base class, we can refactor them
as needed later.
## What is Catch2's ABI stability policy?
Catch2 provides no ABI stability guarantees whatsoever. Catch2 provides
rich C++ interface, and trying to freeze its ABI would take a lot of
pointless work.
Catch2 is not designed to be distributed as dynamic library, and you
should really be able to compile everything with the same compiler binary.
## What is Catch2's API stability policy?
Catch2 follows [semver](https://semver.org/) to the best of our ability.
This means that we will not knowingly make backwards-incompatible changes
without incrementing the major version number.
## Does Catch2 support running tests in parallel?
Not natively, no. We see running tests in parallel as the job of an
external test runner, that can also run them in separate processes,
support test execution timeouts and so on.
However, Catch2 provides some tools that make the job of external test
runners easier. [See the relevant section in our page on best
practices](usage-tips.md#parallel-tests).
## Can I compile Catch2 into a dynamic library?
Yes, Catch2 supports the [standard CMake `BUILD_SHARED_LIBS`
option](https://cmake.org/cmake/help/latest/variable/BUILD_SHARED_LIBS.html).
However, the dynamic library support is provided as-is. Catch2 does not
provide API export annotations, and so you can only use it as a dynamic
library on platforms that default to public visibility, or with tooling
support to force export Catch2's API.
## What repeatability guarantees does Catch2 provide?
There are two places where it is meaningful to talk about Catch2's
repeatability guarantees without taking into account user-provided
code. First one is in the test case shuffling, and the second one is
the output from random generators.
Test case shuffling is repeatable across different platforms since v2.12.0,
and it is also generally repeatable across versions, but we might break
it from time to time. E.g. we broke repeatability with previous versions
in v2.13.4 so that test cases with similar names are shuffled better.
Since Catch2 3.5.0 the random generators use custom distributions,
that should be repeatable across different platforms, with few caveats.
For details see the section on random generators in the [Generator
documentation](generators.md#random-number-generators-details).
Before this version, random generators relied on distributions from
platform's stdlib. We thus can provide no extra guarantee on top of the
ones given by your platform. **Important: `<random>`'s distributions
are not specified to be repeatable across different platforms.**
## My build cannot find `catch2/catch_user_config.hpp`, how can I fix it?
`catch2/catch_user_config.hpp` is a generated header that contains user
compile time configuration. It is generated by CMake/Meson/Bazel during
build. If you are not using either of these, your three options are to
1) Build Catch2 separately using build tool that will generate the header
2) Use the amalgamated files to build Catch2
3) Use CMake to configure a build. This will generate the header and you
can copy it into your own checkout of Catch2.
---
[Home](Readme.md#top)

View File

@ -0,0 +1,280 @@
<a id="top"></a>
# Data Generators
> Introduced in Catch2 2.6.0.
Data generators (also known as _data driven/parametrized test cases_)
let you reuse the same set of assertions across different input values.
In Catch2, this means that they respect the ordering and nesting
of the `TEST_CASE` and `SECTION` macros, and their nested sections
are run once per each value in a generator.
This is best explained with an example:
```cpp
TEST_CASE("Generators") {
auto i = GENERATE(1, 3, 5);
REQUIRE(is_odd(i));
}
```
The "Generators" `TEST_CASE` will be entered 3 times, and the value of
`i` will be 1, 3, and 5 in turn. `GENERATE`s can also be used multiple
times at the same scope, in which case the result will be a cartesian
product of all elements in the generators. This means that in the snippet
below, the test case will be run 6 (2\*3) times.
```cpp
TEST_CASE("Generators") {
auto i = GENERATE(1, 2);
auto j = GENERATE(3, 4, 5);
}
```
There are 2 parts to generators in Catch2, the `GENERATE` macro together
with the already provided generators, and the `IGenerator<T>` interface
that allows users to implement their own generators.
## Combining `GENERATE` and `SECTION`.
`GENERATE` can be seen as an implicit `SECTION`, that goes from the place
`GENERATE` is used, to the end of the scope. This can be used for various
effects. The simplest usage is shown below, where the `SECTION` "one"
runs 4 (2\*2) times, and `SECTION` "two" is run 6 times (2\*3).
```cpp
TEST_CASE("Generators") {
auto i = GENERATE(1, 2);
SECTION("one") {
auto j = GENERATE(-3, -2);
REQUIRE(j < i);
}
SECTION("two") {
auto k = GENERATE(4, 5, 6);
REQUIRE(i != k);
}
}
```
The specific order of the `SECTION`s will be "one", "one", "two", "two",
"two", "one"...
The fact that `GENERATE` introduces a virtual `SECTION` can also be used
to make a generator replay only some `SECTION`s, without having to
explicitly add a `SECTION`. As an example, the code below reports 3
assertions, because the "first" section is run once, but the "second"
section is run twice.
```cpp
TEST_CASE("GENERATE between SECTIONs") {
SECTION("first") { REQUIRE(true); }
auto _ = GENERATE(1, 2);
SECTION("second") { REQUIRE(true); }
}
```
This can lead to surprisingly complex test flows. As an example, the test
below will report 14 assertions:
```cpp
TEST_CASE("Complex mix of sections and generates") {
auto i = GENERATE(1, 2);
SECTION("A") {
SUCCEED("A");
}
auto j = GENERATE(3, 4);
SECTION("B") {
SUCCEED("B");
}
auto k = GENERATE(5, 6);
SUCCEED();
}
```
> The ability to place `GENERATE` between two `SECTION`s was [introduced](https://github.com/catchorg/Catch2/issues/1938) in Catch2 2.13.0.
## Provided generators
Catch2's provided generator functionality consists of three parts,
* `GENERATE` macro, that serves to integrate generator expression with
a test case,
* 2 fundamental generators
* `SingleValueGenerator<T>` -- contains only single element
* `FixedValuesGenerator<T>` -- contains multiple elements
* 5 generic generators that modify other generators
* `FilterGenerator<T, Predicate>` -- filters out elements from a generator
for which the predicate returns "false"
* `TakeGenerator<T>` -- takes first `n` elements from a generator
* `RepeatGenerator<T>` -- repeats output from a generator `n` times
* `MapGenerator<T, U, Func>` -- returns the result of applying `Func`
on elements from a different generator
* `ChunkGenerator<T>` -- returns chunks (inside `std::vector`) of n elements from a generator
* 4 specific purpose generators
* `RandomIntegerGenerator<Integral>` -- generates random Integrals from range
* `RandomFloatGenerator<Float>` -- generates random Floats from range
* `RangeGenerator<T>(first, last)` -- generates all values inside a `[first, last)` arithmetic range
* `IteratorGenerator<T>` -- copies and returns values from an iterator range
> `ChunkGenerator<T>`, `RandomIntegerGenerator<Integral>`, `RandomFloatGenerator<Float>` and `RangeGenerator<T>` were introduced in Catch2 2.7.0.
> `IteratorGenerator<T>` was introduced in Catch2 2.10.0.
The generators also have associated helper functions that infer their
type, making their usage much nicer. These are
* `value(T&&)` for `SingleValueGenerator<T>`
* `values(std::initializer_list<T>)` for `FixedValuesGenerator<T>`
* `table<Ts...>(std::initializer_list<std::tuple<Ts...>>)` for `FixedValuesGenerator<std::tuple<Ts...>>`
* `filter(predicate, GeneratorWrapper<T>&&)` for `FilterGenerator<T, Predicate>`
* `take(count, GeneratorWrapper<T>&&)` for `TakeGenerator<T>`
* `repeat(repeats, GeneratorWrapper<T>&&)` for `RepeatGenerator<T>`
* `map(func, GeneratorWrapper<T>&&)` for `MapGenerator<T, U, Func>` (map `U` to `T`, deduced from `Func`)
* `map<T>(func, GeneratorWrapper<U>&&)` for `MapGenerator<T, U, Func>` (map `U` to `T`)
* `chunk(chunk-size, GeneratorWrapper<T>&&)` for `ChunkGenerator<T>`
* `random(IntegerOrFloat a, IntegerOrFloat b)` for `RandomIntegerGenerator` or `RandomFloatGenerator`
* `range(Arithmetic start, Arithmetic end)` for `RangeGenerator<Arithmetic>` with a step size of `1`
* `range(Arithmetic start, Arithmetic end, Arithmetic step)` for `RangeGenerator<Arithmetic>` with a custom step size
* `from_range(InputIterator from, InputIterator to)` for `IteratorGenerator<T>`
* `from_range(Container const&)` for `IteratorGenerator<T>`
> `chunk()`, `random()` and both `range()` functions were introduced in Catch2 2.7.0.
> `from_range` has been introduced in Catch2 2.10.0
> `range()` for floating point numbers has been introduced in Catch2 2.11.0
And can be used as shown in the example below to create a generator
that returns 100 odd random number:
```cpp
TEST_CASE("Generating random ints", "[example][generator]") {
SECTION("Deducing functions") {
auto i = GENERATE(take(100, filter([](int i) { return i % 2 == 1; }, random(-100, 100))));
REQUIRE(i > -100);
REQUIRE(i < 100);
REQUIRE(i % 2 == 1);
}
}
```
Apart from registering generators with Catch2, the `GENERATE` macro has
one more purpose, and that is to provide simple way of generating trivial
generators, as seen in the first example on this page, where we used it
as `auto i = GENERATE(1, 2, 3);`. This usage converted each of the three
literals into a single `SingleValueGenerator<int>` and then placed them all in
a special generator that concatenates other generators. It can also be
used with other generators as arguments, such as `auto i = GENERATE(0, 2,
take(100, random(300, 3000)));`. This is useful e.g. if you know that
specific inputs are problematic and want to test them separately/first.
**For safety reasons, you cannot use variables inside the `GENERATE` macro.
This is done because the generator expression _will_ outlive the outside
scope and thus capturing references is dangerous. If you need to use
variables inside the generator expression, make sure you thought through
the lifetime implications and use `GENERATE_COPY` or `GENERATE_REF`.**
> `GENERATE_COPY` and `GENERATE_REF` were introduced in Catch2 2.7.1.
You can also override the inferred type by using `as<type>` as the first
argument to the macro. This can be useful when dealing with string literals,
if you want them to come out as `std::string`:
```cpp
TEST_CASE("type conversion", "[generators]") {
auto str = GENERATE(as<std::string>{}, "a", "bb", "ccc");
REQUIRE(str.size() > 0);
}
```
### Random number generators: details
> This section applies from Catch2 3.5.0. Before that, random generators
> were a thin wrapper around distributions from `<random>`.
All of the `random(a, b)` generators in Catch2 currently generate uniformly
distributed number in closed interval \[a; b\]. This is different from
`std::uniform_real_distribution`, which should return numbers in interval
\[a; b) (but due to rounding can end up returning b anyway), but the
difference is intentional, so that `random(a, a)` makes sense. If there is
enough interest from users, we can provide API to pick any of CC, CO, OC,
or OO ranges.
Unlike `std::uniform_int_distribution`, Catch2's generators also support
various single-byte integral types, such as `char` or `bool`.
#### Reproducibility
Given the same seed, the output from the integral generators is fully
reproducible across different platforms.
For floating point generators, the situation is much more complex.
Generally Catch2 only promises reproducibility (or even just correctness!)
on platforms that obey the IEEE-754 standard. Furthermore, reproducibility
only applies between binaries that perform floating point math in the
same way, e.g. if you compile a binary targetting the x87 FPU and another
one targetting SSE2 for floating point math, their results will vary.
Similarly, binaries compiled with compiler flags that relax the IEEE-754
adherence, e.g. `-ffast-math`, might provide different results than those
compiled for strict IEEE-754 adherence.
Finally, we provide zero guarantees on the reproducibility of generating
`long double`s, as the internals of `long double` varies across different
platforms.
## Generator interface
You can also implement your own generators, by deriving from the
`IGenerator<T>` interface:
```cpp
template<typename T>
struct IGenerator : GeneratorUntypedBase {
// via GeneratorUntypedBase:
// Attempts to move the generator to the next element.
// Returns true if successful (and thus has another element that can be read)
virtual bool next() = 0;
// Precondition:
// The generator is either freshly constructed or the last call to next() returned true
virtual T const& get() const = 0;
// Returns user-friendly string showing the current generator element
// Does not have to be overridden, IGenerator provides default implementation
virtual std::string stringifyImpl() const;
};
```
However, to be able to use your custom generator inside `GENERATE`, it
will need to be wrapped inside a `GeneratorWrapper<T>`.
`GeneratorWrapper<T>` is a value wrapper around a
`Catch::Detail::unique_ptr<IGenerator<T>>`.
For full example of implementing your own generator, look into Catch2's
examples, specifically
[Generators: Create your own generator](../examples/300-Gen-OwnGenerator.cpp).
### Handling empty generators
The generator interface assumes that a generator always has at least one
element. This is not always true, e.g. if the generator depends on an external
datafile, the file might be missing.
There are two ways to handle this, depending on whether you want this
to be an error or not.
* If empty generator **is** an error, throw an exception in constructor.
* If empty generator **is not** an error, use the [`SKIP`](skipping-passing-failing.md#skipping-test-cases-at-runtime) in constructor.
---
[Home](Readme.md#top)

View File

@ -0,0 +1,191 @@
<a id="top"></a>
# Known limitations
Over time, some limitations of Catch2 emerged. Some of these are due
to implementation details that cannot be easily changed, some of these
are due to lack of development resources on our part, and some of these
are due to plain old 3rd party bugs.
## Implementation limits
### Sections nested in loops
If you are using `SECTION`s inside loops, you have to create them with
different name per loop's iteration. The recommended way to do so is to
incorporate the loop's counter into section's name, like so:
```cpp
TEST_CASE( "Looped section" ) {
for (char i = '0'; i < '5'; ++i) {
SECTION(std::string("Looped section ") + i) {
SUCCEED( "Everything is OK" );
}
}
}
```
or with a `DYNAMIC_SECTION` macro (that was made for exactly this purpose):
```cpp
TEST_CASE( "Looped section" ) {
for (char i = '0'; i < '5'; ++i) {
DYNAMIC_SECTION( "Looped section " << i) {
SUCCEED( "Everything is OK" );
}
}
}
```
### Tests might be run again if last section fails
If the last section in a test fails, it might be run again. This is because
Catch2 discovers `SECTION`s dynamically, as they are about to run, and
if the last section in test case is aborted during execution (e.g. via
the `REQUIRE` family of macros), Catch2 does not know that there are no
more sections in that test case and must run the test case again.
### MinGW/CygWin compilation (linking) is extremely slow
Compiling Catch2 with MinGW can be exceedingly slow, especially during
the linking step. As far as we can tell, this is caused by deficiencies
in its default linker. If you can tell MinGW to instead use lld, via
`-fuse-ld=lld`, the link time should drop down to reasonable length
again.
## Features
This section outlines some missing features, what is their status and their possible workarounds.
### Thread safe assertions
Catch2's assertion macros are not thread safe. This does not mean that
you cannot use threads inside Catch's test, but that only single thread
can interact with Catch's assertions and other macros.
This means that this is ok
```cpp
std::vector<std::thread> threads;
std::atomic<int> cnt{ 0 };
for (int i = 0; i < 4; ++i) {
threads.emplace_back([&]() {
++cnt; ++cnt; ++cnt; ++cnt;
});
}
for (auto& t : threads) { t.join(); }
REQUIRE(cnt == 16);
```
because only one thread passes the `REQUIRE` macro and this is not
```cpp
std::vector<std::thread> threads;
std::atomic<int> cnt{ 0 };
for (int i = 0; i < 4; ++i) {
threads.emplace_back([&]() {
++cnt; ++cnt; ++cnt; ++cnt;
CHECK(cnt == 16);
});
}
for (auto& t : threads) { t.join(); }
REQUIRE(cnt == 16);
```
We currently do not plan to support thread-safe assertions.
### Process isolation in a test
Catch does not support running tests in isolated (forked) processes. While this might in the future, the fact that Windows does not support forking and only allows full-on process creation and the desire to keep code as similar as possible across platforms, mean that this is likely to take significant development time, that is not currently available.
### Running multiple tests in parallel
Catch2 keeps test execution in one process strictly serial, and there
are no plans to change this. If you find yourself with a test suite
that takes too long to run and you want to make it parallel, you have
to run multiple processes side by side.
There are 2 basic ways to do that,
* you can split your tests into multiple binaries, and run those binaries
in parallel
* you can run the same test binary multiple times, but run a different
subset of the tests in each process
There are multiple ways to achieve the latter, the easiest way is to use
[test sharding](command-line.md#test-sharding).
## 3rd party bugs
This section outlines known bugs in 3rd party components (this means compilers, standard libraries, standard runtimes).
### Visual Studio 2017 -- raw string literal in assert fails to compile
There is a known bug in Visual Studio 2017 (VC 15), that causes compilation
error when preprocessor attempts to stringize a raw string literal
(`#` preprocessor directive is applied to it). This snippet is sufficient
to trigger the compilation error:
```cpp
#include <catch2/catch_test_macros.hpp>
TEST_CASE("test") {
CHECK(std::string(R"("\)") == "\"\\");
}
```
Catch2 provides a workaround, by letting the user disable stringification
of the original expression by defining `CATCH_CONFIG_DISABLE_STRINGIFICATION`,
like so:
```cpp
#define CATCH_CONFIG_DISABLE_STRINGIFICATION
#include <catch2/catch_test_macros.hpp>
TEST_CASE("test") {
CHECK(std::string(R"("\)") == "\"\\");
}
```
_Do note that this changes the output:_
```
catchwork\test1.cpp(6):
PASSED:
CHECK( Disabled by CATCH_CONFIG_DISABLE_STRINGIFICATION )
with expansion:
""\" == ""\"
```
### Clang/G++ -- skipping leaf sections after an exception
Some versions of `libc++` and `libstdc++` (or their runtimes) have a bug with `std::uncaught_exception()` getting stuck returning `true` after rethrow, even if there are no active exceptions. One such case is this snippet, which skipped the sections "a" and "b", when compiled against `libcxxrt` from the master branch
```cpp
#include <catch2/catch_test_macros.hpp>
TEST_CASE("a") {
CHECK_THROWS(throw 3);
}
TEST_CASE("b") {
int i = 0;
SECTION("a") { i = 1; }
SECTION("b") { i = 2; }
CHECK(i > 0);
}
```
If you are seeing a problem like this, i.e. weird test paths that trigger only under Clang with `libc++`, or only under very specific version of `libstdc++`, it is very likely you are seeing this. The only known workaround is to use a fixed version of your standard library.
### Visual Studio 2022 -- can't compile assertion with the spaceship operator
[The C++ standard requires that `std::foo_ordering` is only comparable with
a literal 0](https://eel.is/c++draft/cmp#categories.pre-3). There are
multiple strategies a stdlib implementation can take to achieve this, and
MSVC's STL has changed the strategy they use between two releases of VS 2022.
With the new strategy, `REQUIRE((a <=> b) == 0)` no longer compiles under
MSVC. Note that Catch2 can compile code using MSVC STL's new strategy,
but only when compiled with a C++20 conforming compiler. MSVC is currently
not conformant enough, but `clang-cl` will compile the assertion above
using MSVC STL without problem.
This change got in with MSVC v19.37](https://godbolt.org/z/KG9obzdvE).

View File

@ -0,0 +1,47 @@
<a id="top"></a>
# List of examples
## Already available
- Test Case: [Single-file](../examples/010-TestCase.cpp)
- Test Case: [Multiple-file 1](../examples/020-TestCase-1.cpp), [2](../examples/020-TestCase-2.cpp)
- Assertion: [REQUIRE, CHECK](../examples/030-Asn-Require-Check.cpp)
- Fixture: [Sections](../examples/100-Fix-Section.cpp)
- Fixture: [Class-based fixtures](../examples/110-Fix-ClassFixture.cpp)
- Fixture: [Persistent fixtures](../examples/111-Fix-PersistentFixture.cpp)
- BDD: [SCENARIO, GIVEN, WHEN, THEN](../examples/120-Bdd-ScenarioGivenWhenThen.cpp)
- Listener: [Listeners](../examples/210-Evt-EventListeners.cpp)
- Configuration: [Provide your own output streams](../examples/231-Cfg-OutputStreams.cpp)
- Generators: [Create your own generator](../examples/300-Gen-OwnGenerator.cpp)
- Generators: [Use map to convert types in GENERATE expression](../examples/301-Gen-MapTypeConversion.cpp)
- Generators: [Run test with a table of input values](../examples/302-Gen-Table.cpp)
- Generators: [Use variables in generator expressions](../examples/310-Gen-VariablesInGenerators.cpp)
- Generators: [Use custom variable capture in generator expressions](../examples/311-Gen-CustomCapture.cpp)
## Planned
- Assertion: [REQUIRE_THAT and Matchers](../examples/040-Asn-RequireThat.cpp)
- Assertion: [REQUIRE_NO_THROW](../examples/050-Asn-RequireNoThrow.cpp)
- Assertion: [REQUIRE_THROWS](../examples/050-Asn-RequireThrows.cpp)
- Assertion: [REQUIRE_THROWS_AS](../examples/070-Asn-RequireThrowsAs.cpp)
- Assertion: [REQUIRE_THROWS_WITH](../examples/080-Asn-RequireThrowsWith.cpp)
- Assertion: [REQUIRE_THROWS_MATCHES](../examples/090-Asn-RequireThrowsMatches.cpp)
- Floating point: [Approx - Comparisons](../examples/130-Fpt-Approx.cpp)
- Logging: [CAPTURE - Capture expression](../examples/140-Log-Capture.cpp)
- Logging: [INFO - Provide information with failure](../examples/150-Log-Info.cpp)
- Logging: [WARN - Issue warning](../examples/160-Log-Warn.cpp)
- Logging: [FAIL, FAIL_CHECK - Issue message and force failure/continue](../examples/170-Log-Fail.cpp)
- Logging: [SUCCEED - Issue message and continue](../examples/180-Log-Succeed.cpp)
- Report: [User-defined type](../examples/190-Rpt-ReportUserDefinedType.cpp)
- Report: [User-defined reporter](../examples/202-Rpt-UserDefinedReporter.cpp)
- Report: [Automake reporter](../examples/205-Rpt-AutomakeReporter.cpp)
- Report: [TAP reporter](../examples/206-Rpt-TapReporter.cpp)
- Report: [Multiple reporter](../examples/208-Rpt-MultipleReporters.cpp)
- Configuration: [Provide your own main()](../examples/220-Cfg-OwnMain.cpp)
- Configuration: [Compile-time configuration](../examples/230-Cfg-CompileTimeConfiguration.cpp)
- Configuration: [Run-time configuration](../examples/240-Cfg-RunTimeConfiguration.cpp)
---
[Home](Readme.md#top)

View File

@ -0,0 +1,163 @@
<a id="top"></a>
# Logging macros
Additional messages can be logged during a test case. Note that the messages logged with `INFO` are scoped and thus will not be reported if failure occurs in scope preceding the message declaration. An example:
```cpp
TEST_CASE("Foo") {
INFO("Test case start");
for (int i = 0; i < 2; ++i) {
INFO("The number is " << i);
CHECK(i == 0);
}
}
TEST_CASE("Bar") {
INFO("Test case start");
for (int i = 0; i < 2; ++i) {
INFO("The number is " << i);
CHECK(i == i);
}
CHECK(false);
}
```
When the `CHECK` fails in the "Foo" test case, then two messages will be printed.
```
Test case start
The number is 1
```
When the last `CHECK` fails in the "Bar" test case, then only one message will be printed: `Test case start`.
## Logging without local scope
> [Introduced](https://github.com/catchorg/Catch2/issues/1522) in Catch2 2.7.0.
`UNSCOPED_INFO` is similar to `INFO` with two key differences:
- Lifetime of an unscoped message is not tied to its own scope.
- An unscoped message can be reported by the first following assertion only, regardless of the result of that assertion.
In other words, lifetime of `UNSCOPED_INFO` is limited by the following assertion (or by the end of test case/section, whichever comes first) whereas lifetime of `INFO` is limited by its own scope.
These differences make this macro useful for reporting information from helper functions or inner scopes. An example:
```cpp
void print_some_info() {
UNSCOPED_INFO("Info from helper");
}
TEST_CASE("Baz") {
print_some_info();
for (int i = 0; i < 2; ++i) {
UNSCOPED_INFO("The number is " << i);
}
CHECK(false);
}
TEST_CASE("Qux") {
INFO("First info");
UNSCOPED_INFO("First unscoped info");
CHECK(false);
INFO("Second info");
UNSCOPED_INFO("Second unscoped info");
CHECK(false);
}
```
"Baz" test case prints:
```
Info from helper
The number is 0
The number is 1
```
With "Qux" test case, two messages will be printed when the first `CHECK` fails:
```
First info
First unscoped info
```
"First unscoped info" message will be cleared after the first `CHECK`, while "First info" message will persist until the end of the test case. Therefore, when the second `CHECK` fails, three messages will be printed:
```
First info
Second info
Second unscoped info
```
## Streaming macros
All these macros allow heterogeneous sequences of values to be streaming using the insertion operator (```<<```) in the same way that std::ostream, std::cout, etc support it.
E.g.:
```c++
INFO( "The number is " << i );
```
(Note that there is no initial ```<<``` - instead the insertion sequence is placed in parentheses.)
These macros come in three forms:
**INFO(** _message expression_ **)**
The message is logged to a buffer, but only reported with next assertions that are logged. This allows you to log contextual information in case of failures which is not shown during a successful test run (for the console reporter, without -s). Messages are removed from the buffer at the end of their scope, so may be used, for example, in loops.
_Note that in Catch2 2.x.x `INFO` can be used without a trailing semicolon as there is a trailing semicolon inside macro.
This semicolon will be removed with next major version. It is highly advised to use a trailing semicolon after `INFO` macro._
**UNSCOPED_INFO(** _message expression_ **)**
> [Introduced](https://github.com/catchorg/Catch2/issues/1522) in Catch2 2.7.0.
Similar to `INFO`, but messages are not limited to their own scope: They are removed from the buffer after each assertion, section or test case, whichever comes first.
**WARN(** _message expression_ **)**
The message is always reported but does not fail the test.
**SUCCEED(** _message expression_ **)**
The message is reported and the test case succeeds.
**FAIL(** _message expression_ **)**
The message is reported and the test case fails.
**FAIL_CHECK(** _message expression_ **)**
AS `FAIL`, but does not abort the test
## Quickly capture value of variables or expressions
**CAPTURE(** _expression1_, _expression2_, ... **)**
Sometimes you just want to log a value of variable, or expression. For
convenience, we provide the `CAPTURE` macro, that can take a variable,
or an expression, and prints out that variable/expression and its value
at the time of capture.
e.g. `CAPTURE( theAnswer );` will log message "theAnswer := 42", while
```cpp
int a = 1, b = 2, c = 3;
CAPTURE( a, b, c, a + b, c > b, a == 1);
```
will log a total of 6 messages:
```
a := 1
b := 2
c := 3
a + b := 3
c > b := true
a == 1 := true
```
You can also capture expressions that use commas inside parentheses
(e.g. function calls), brackets, or braces (e.g. initializers). To
properly capture expression that contains template parameters list
(in other words, it contains commas between angle brackets), you need
to enclose the expression inside parentheses:
`CAPTURE( (std::pair<int, int>{1, 2}) );`
---
[Home](Readme.md#top)

View File

@ -0,0 +1,476 @@
<a id="top"></a>
# Matchers
**Contents**<br>
[Using Matchers](#using-matchers)<br>
[Built-in matchers](#built-in-matchers)<br>
[Writing custom matchers (old style)](#writing-custom-matchers-old-style)<br>
[Writing custom matchers (new style)](#writing-custom-matchers-new-style)<br>
Matchers, as popularized by the [Hamcrest](https://en.wikipedia.org/wiki/Hamcrest)
framework are an alternative way to write assertions, useful for tests
where you work with complex types or need to assert more complex
properties. Matchers are easily composable and users can write their
own and combine them with the Catch2-provided matchers seamlessly.
## Using Matchers
Matchers are most commonly used in tandem with the `REQUIRE_THAT` or
`CHECK_THAT` macros. The `REQUIRE_THAT` macro takes two arguments,
the first one is the input (object/value) to test, the second argument
is the matcher itself.
For example, to assert that a string ends with the "as a service"
substring, you can write the following assertion
```cpp
using Catch::Matchers::EndsWith;
REQUIRE_THAT( getSomeString(), EndsWith("as a service") );
```
Individual matchers can also be combined using the C++ logical
operators, that is `&&`, `||`, and `!`, like so:
```cpp
using Catch::Matchers::EndsWith;
using Catch::Matchers::ContainsSubstring;
REQUIRE_THAT( getSomeString(),
EndsWith("as a service") && ContainsSubstring("web scale"));
```
The example above asserts that the string returned from `getSomeString`
_both_ ends with the suffix "as a service" _and_ contains the string
"web scale" somewhere.
Both of the string matchers used in the examples above live in the
`catch_matchers_string.hpp` header, so to compile the code above also
requires `#include <catch2/matchers/catch_matchers_string.hpp>`.
### Combining operators and lifetimes
**IMPORTANT**: The combining operators do not take ownership of the
matcher objects being combined.
This means that if you store combined matcher object, you have to ensure
that the individual matchers being combined outlive the combined matcher.
Note that the negation matcher from `!` also counts as combining matcher
for this.
Explained on an example, this is fine
```cpp
CHECK_THAT(value, WithinAbs(0, 2e-2) && !WithinULP(0., 1));
```
and so is this
```cpp
auto is_close_to_zero = WithinAbs(0, 2e-2);
auto is_zero = WithinULP(0., 1);
CHECK_THAT(value, is_close_to_zero && !is_zero);
```
but this is not
```cpp
auto is_close_to_zero = WithinAbs(0, 2e-2);
auto is_zero = WithinULP(0., 1);
auto is_close_to_but_not_zero = is_close_to_zero && !is_zero;
CHECK_THAT(a_value, is_close_to_but_not_zero); // UAF
```
because `!is_zero` creates a temporary instance of Negation matcher,
which the `is_close_to_but_not_zero` refers to. After the line ends,
the temporary is destroyed and the combined `is_close_to_but_not_zero`
matcher now refers to non-existent object, so using it causes use-after-free.
## Built-in matchers
Every matcher provided by Catch2 is split into 2 parts, a factory
function that lives in the `Catch::Matchers` namespace, and the actual
matcher type that is in some deeper namespace and should not be used by
the user. In the examples above, we used `Catch::Matchers::Contains`.
This is the factory function for the
`Catch::Matchers::StdString::ContainsMatcher` type that does the actual
matching.
Out of the box, Catch2 provides the following matchers:
### `std::string` matchers
Catch2 provides 5 different matchers that work with `std::string`,
* `StartsWith(std::string str, CaseSensitive)`,
* `EndsWith(std::string str, CaseSensitive)`,
* `ContainsSubstring(std::string str, CaseSensitive)`,
* `Equals(std::string str, CaseSensitive)`, and
* `Matches(std::string str, CaseSensitive)`.
The first three should be fairly self-explanatory, they succeed if
the argument starts with `str`, ends with `str`, or contains `str`
somewhere inside it.
The `Equals` matcher matches a string if (and only if) the argument
string is equal to `str`.
Finally, the `Matches` matcher performs an ECMAScript regex match using
`str` against the argument string. It is important to know that
the match is performed against the string as a whole, meaning that
the regex `"abc"` will not match input string `"abcd"`. To match
`"abcd"`, you need to use e.g. `"abc.*"` as your regex.
The second argument sets whether the matching should be case-sensitive
or not. By default, it is case-sensitive.
> `std::string` matchers live in `catch2/matchers/catch_matchers_string.hpp`
### Vector matchers
_Vector matchers have been deprecated in favour of the generic
range matchers with the same functionality._
Catch2 provides 5 built-in matchers that work on `std::vector`.
These are
* `Contains` which checks whether a specified vector is present in the result
* `VectorContains` which checks whether a specified element is present in the result
* `Equals` which checks whether the result is exactly equal (order matters) to a specific vector
* `UnorderedEquals` which checks whether the result is equal to a specific vector under a permutation
* `Approx` which checks whether the result is "approx-equal" (order matters, but comparison is done via `Approx`) to a specific vector
> Approx matcher was [introduced](https://github.com/catchorg/Catch2/issues/1499) in Catch2 2.7.2.
An example usage:
```cpp
std::vector<int> some_vec{ 1, 2, 3 };
REQUIRE_THAT(some_vec, Catch::Matchers::UnorderedEquals(std::vector<int>{ 3, 2, 1 }));
```
This assertions will pass, because the elements given to the matchers
are a permutation of the ones in `some_vec`.
> vector matchers live in `catch2/matchers/catch_matchers_vector.hpp`
### Floating point matchers
Catch2 provides 4 matchers that target floating point numbers. These
are:
* `WithinAbs(double target, double margin)`,
* `WithinULP(FloatingPoint target, uint64_t maxUlpDiff)`, and
* `WithinRel(FloatingPoint target, FloatingPoint eps)`.
* `IsNaN()`
> `WithinRel` matcher was introduced in Catch2 2.10.0
> `IsNaN` matcher was introduced in Catch2 3.3.2.
The first three serve to compare two floating pointe numbers. For more
details about how they work, read [the docs on comparing floating point
numbers](comparing-floating-point-numbers.md#floating-point-matchers).
`IsNaN` then does exactly what it says on the tin. It matches the input
if it is a NaN (Not a Number). The advantage of using it over just plain
`REQUIRE(std::isnan(x))`, is that if the check fails, with `REQUIRE` you
won't see the value of `x`, but with `REQUIRE_THAT(x, IsNaN())`, you will.
### Miscellaneous matchers
Catch2 also provides some matchers and matcher utilities that do not
quite fit into other categories.
The first one of them is the `Predicate(Callable pred, std::string description)`
matcher. It creates a matcher object that calls `pred` for the provided
argument. The `description` argument allows users to set what the
resulting matcher should self-describe as if required.
Do note that you will need to explicitly specify the type of the
argument, like in this example:
```cpp
REQUIRE_THAT("Hello olleH",
Predicate<std::string>(
[] (std::string const& str) -> bool { return str.front() == str.back(); },
"First and last character should be equal")
);
```
> the predicate matcher lives in `catch2/matchers/catch_matchers_predicate.hpp`
The other miscellaneous matcher utility is exception matching.
#### Matching exceptions
Because exceptions are a bit special, Catch2 has a separate macro for them.
The basic form is
```
REQUIRE_THROWS_MATCHES(expr, ExceptionType, Matcher)
```
and it checks that the `expr` throws an exception, that exception is derived
from the `ExceptionType` type, and then `Matcher::match` is called on
the caught exception.
> `REQUIRE_THROWS_MATCHES` macro lives in `catch2/matchers/catch_matchers.hpp`
For one-off checks you can use the `Predicate` matcher above, e.g.
```cpp
REQUIRE_THROWS_MATCHES(parse(...),
parse_error,
Predicate<parse_error>([] (parse_error const& err) -> bool { return err.line() == 1; })
);
```
but if you intend to thoroughly test your error reporting, I recommend
defining a specialized matcher.
Catch2 also provides 2 built-in matchers for checking the error message
inside an exception (it must be derived from `std::exception`):
* `Message(std::string message)`.
* `MessageMatches(Matcher matcher)`.
> `MessageMatches` was [introduced](https://github.com/catchorg/Catch2/pull/2570) in Catch2 3.3.0
`Message` checks that the exception's
message, as returned from `what` is exactly equal to `message`.
`MessageMatches` applies the provided matcher on the exception's
message, as returned from `what`. This is useful in conjunctions with the `std::string` matchers (e.g. `StartsWith`)
Example use:
```cpp
REQUIRE_THROWS_MATCHES(throwsDerivedException(), DerivedException, Message("DerivedException::what"));
REQUIRE_THROWS_MATCHES(throwsDerivedException(), DerivedException, MessageMatches(StartsWith("DerivedException")));
```
> the exception message matchers live in `catch2/matchers/catch_matchers_exception.hpp`
### Generic range Matchers
> Generic range matchers were introduced in Catch2 3.0.1
Catch2 also provides some matchers that use the new style matchers
definitions to handle generic range-like types. These are:
* `IsEmpty()`
* `SizeIs(size_t target_size)`
* `SizeIs(Matcher size_matcher)`
* `Contains(T&& target_element, Comparator = std::equal_to<>{})`
* `Contains(Matcher element_matcher)`
* `AllMatch(Matcher element_matcher)`
* `AnyMatch(Matcher element_matcher)`
* `NoneMatch(Matcher element_matcher)`
* `AllTrue()`, `AnyTrue()`, `NoneTrue()`
* `RangeEquals(TargetRangeLike&&, Comparator = std::equal_to<>{})`
* `UnorderedRangeEquals(TargetRangeLike&&, Comparator = std::equal_to<>{})`
> `IsEmpty`, `SizeIs`, `Contains` were introduced in Catch2 3.0.1
> `All/Any/NoneMatch` were introduced in Catch2 3.0.1
> `All/Any/NoneTrue` were introduced in Catch2 3.1.0
> `RangeEquals` and `UnorderedRangeEquals` matchers were [introduced](https://github.com/catchorg/Catch2/pull/2377) in Catch2 3.3.0
`IsEmpty` should be self-explanatory. It successfully matches objects
that are empty according to either `std::empty`, or ADL-found `empty`
free function.
`SizeIs` checks range's size. If constructed with `size_t` arg, the
matchers accepts ranges whose size is exactly equal to the arg. If
constructed from another matcher, then the resulting matcher accepts
ranges whose size is accepted by the provided matcher.
`Contains` accepts ranges that contain specific element. There are
again two variants, one that accepts the desired element directly,
in which case a range is accepted if any of its elements is equal to
the target element. The other variant is constructed from a matcher,
in which case a range is accepted if any of its elements is accepted
by the provided matcher.
`AllMatch`, `NoneMatch`, and `AnyMatch` match ranges for which either
all, none, or any of the contained elements matches the given matcher,
respectively.
`AllTrue`, `NoneTrue`, and `AnyTrue` match ranges for which either
all, none, or any of the contained elements are `true`, respectively.
It works for ranges of `bool`s and ranges of elements (explicitly)
convertible to `bool`.
`RangeEquals` compares the range that the matcher is constructed with
(the "target range") against the range to be tested, element-wise. The
match succeeds if all elements from the two ranges compare equal (using
`operator==` by default). The ranges do not need to be the same type,
and the element types do not need to be the same, as long as they are
comparable. (e.g. you may compare `std::vector<int>` to `std::array<char>`).
`UnorderedRangeEquals` is similar to `RangeEquals`, but the order
does not matter. For example "1, 2, 3" would match "3, 2, 1", but not
"1, 1, 2, 3" As with `RangeEquals`, `UnorderedRangeEquals` compares
the individual elements using `operator==` by default.
Both `RangeEquals` and `UnorderedRangeEquals` optionally accept a
predicate which can be used to compare the containers element-wise.
To check a container elementwise against a given matcher, use
`AllMatch`.
## Writing custom matchers (old style)
The old style of writing matchers has been introduced back in Catch
Classic. To create an old-style matcher, you have to create your own
type that derives from `Catch::Matchers::MatcherBase<ArgT>`, where
`ArgT` is the type your matcher works for. Your type has to override
two methods, `bool match(ArgT const&) const`,
and `std::string describe() const`.
As the name suggests, `match` decides whether the provided argument
is matched (accepted) by the matcher. `describe` then provides a
human-oriented description of what the matcher does.
We also recommend that you create factory function, just like Catch2
does, but that is mostly useful for template argument deduction for
templated matchers (assuming you do not have CTAD available).
To combine these into an example, let's say that you want to write
a matcher that decides whether the provided argument is a number
within certain range. We will call it `IsBetweenMatcher<T>`:
```c++
#include <catch2/catch_test_macros.hpp>
#include <catch2/matchers/catch_matchers.hpp>
// ...
template <typename T>
class IsBetweenMatcher : public Catch::Matchers::MatcherBase<T> {
T m_begin, m_end;
public:
IsBetweenMatcher(T begin, T end) : m_begin(begin), m_end(end) {}
bool match(T const& in) const override {
return in >= m_begin && in <= m_end;
}
std::string describe() const override {
std::ostringstream ss;
ss << "is between " << m_begin << " and " << m_end;
return ss.str();
}
};
template <typename T>
IsBetweenMatcher<T> IsBetween(T begin, T end) {
return { begin, end };
}
// ...
TEST_CASE("Numbers are within range") {
// infers `double` for the argument type of the matcher
CHECK_THAT(3., IsBetween(1., 10.));
// infers `int` for the argument type of the matcher
CHECK_THAT(100, IsBetween(1, 10));
}
```
Obviously, the code above can be improved somewhat, for example you
might want to `static_assert` over the fact that `T` is an arithmetic
type... or generalize the matcher to cover any type for which the user
can provide a comparison function object.
Note that while any matcher written using the old style can also be
written using the new style, combining old style matchers should
generally compile faster. Also note that you can combine old and new
style matchers arbitrarily.
> `MatcherBase` lives in `catch2/matchers/catch_matchers.hpp`
## Writing custom matchers (new style)
> New style matchers were introduced in Catch2 3.0.1
To create a new-style matcher, you have to create your own type that
derives from `Catch::Matchers::MatcherGenericBase`. Your type has to
also provide two methods, `bool match( ... ) const` and overridden
`std::string describe() const`.
Unlike with old-style matchers, there are no requirements on how
the `match` member function takes its argument. This means that the
argument can be taken by value or by mutating reference, but also that
the matcher's `match` member function can be templated.
This allows you to write more complex matcher, such as a matcher that
can compare one range-like (something that responds to `begin` and
`end`) object to another, like in the following example:
```cpp
#include <catch2/catch_test_macros.hpp>
#include <catch2/matchers/catch_matchers_templated.hpp>
// ...
template<typename Range>
struct EqualsRangeMatcher : Catch::Matchers::MatcherGenericBase {
EqualsRangeMatcher(Range const& range):
range{ range }
{}
template<typename OtherRange>
bool match(OtherRange const& other) const {
using std::begin; using std::end;
return std::equal(begin(range), end(range), begin(other), end(other));
}
std::string describe() const override {
return "Equals: " + Catch::rangeToString(range);
}
private:
Range const& range;
};
template<typename Range>
auto EqualsRange(const Range& range) -> EqualsRangeMatcher<Range> {
return EqualsRangeMatcher<Range>{range};
}
TEST_CASE("Combining templated matchers", "[matchers][templated]") {
std::array<int, 3> container{{ 1,2,3 }};
std::array<int, 3> a{{ 1,2,3 }};
std::vector<int> b{ 0,1,2 };
std::list<int> c{ 4,5,6 };
REQUIRE_THAT(container, EqualsRange(a) || EqualsRange(b) || EqualsRange(c));
}
```
Do note that while you can rewrite any matcher from the old style to
a new style matcher, combining new style matchers is more expensive
in terms of compilation time. Also note that you can combine old style
and new style matchers arbitrarily.
> `MatcherGenericBase` lives in `catch2/matchers/catch_matchers_templated.hpp`
---
[Home](Readme.md#top)

View File

@ -0,0 +1,98 @@
<a id="top"></a>
# Migrating from v2 to v3
v3 is the next major version of Catch2 and brings three significant changes:
* Catch2 is now split into multiple headers
* Catch2 is now compiled as a static library
* C++14 is the minimum required C++ version
There are many reasons why we decided to go from the old single-header
distribution model to a more standard library distribution model. The
big one is compile-time performance, but moving over to a split header
distribution model also improves the future maintainability and
extendability of the codebase. For example v3 adds a new kind of matchers
without impacting the compilation times of users that do not use matchers
in their tests. The new model is also more friendly towards package
managers, such as vcpkg and Conan.
The result of this move is a significant improvement in compilation
times, e.g. the inclusion overhead of Catch2 in the common case has been
reduced by roughly 80%. The improved ease of maintenance also led to
various runtime performance improvements and the introduction of new features.
For details, look at [the release notes of 3.0.1](release-notes.md#301).
_Note that we still provide one header + one translation unit (TU)
distribution but do not consider it the primarily supported option. You
should also expect that the compilation times will be worse if you use
this option._
## How to migrate projects from v2 to v3
To migrate to v3, there are two basic approaches to do so.
1. Use `catch_amalgamated.hpp` and `catch_amalgamated.cpp`.
2. Build Catch2 as a proper (static) library, and move to piecewise headers
Doing 1 means downloading the [amalgamated header](/extras/catch_amalgamated.hpp)
and the [amalgamated sources](/extras/catch_amalgamated.cpp) from `extras`,
dropping them into your test project, and rewriting your includes from
`<catch2/catch.hpp>` to `"catch_amalgamated.hpp"` (or something similar,
based on how you set up your paths).
The disadvantage of using this approach are increased compilation times,
at least compared to the second approach, but it does let you avoid
dealing with consuming libraries in your build system of choice.
However, we recommend doing 2, and taking extra time to migrate to v3
properly. This lets you reap the benefits of significantly improved
compilation times in the v3 version. The basic steps to do so are:
1. Change your CMakeLists.txt to link against `Catch2WithMain` target if
you use Catch2's default main. (If you do not, keep linking against
the `Catch2` target.). If you use pkg-config, change `pkg-config catch2` to
`pkg-config catch2-with-main`.
2. Delete TU with `CATCH_CONFIG_RUNNER` or `CATCH_CONFIG_MAIN` defined,
as it is no longer needed.
3. Change `#include <catch2/catch.hpp>` to `#include <catch2/catch_all.hpp>`
4. Check that everything compiles. You might have to modify namespaces,
or perform some other changes (see the
[Things that can break during porting](#things-that-can-break-during-porting)
section for the most common things).
5. Start migrating your test TUs from including `<catch2/catch_all.hpp>`
to piecemeal includes. You will likely want to start by including
`<catch2/catch_test_macros.hpp>`, and then go from there. (see
[other notes](#other-notes) for further ideas)
## Other notes
* The main test include is now `<catch2/catch_test_macros.hpp>`
* Big "subparts" like Matchers, or Generators, have their own folder, and
also their own "big header", so if you just want to include all matchers,
you can include `<catch2/matchers/catch_matchers_all.hpp>`,
or `<catch2/generators/catch_generators_all.hpp>`
## Things that can break during porting
* The namespaces of Matchers were flattened and cleaned up.
Matchers are no longer declared deep within an internal namespace and
then brought up into `Catch` namespace. All Matchers now live in the
`Catch::Matchers` namespace.
* The `Contains` string matcher was renamed to `ContainsSubstring`.
* The reporter interfaces changed in a breaking manner.
If you are using a custom reporter or listener, you will likely need to
modify them to conform to the new interfaces. Unlike before in v2,
the [interfaces](reporters.md#top) and the [events](reporter-events.md#top)
are now documented.
---
[Home](Readme.md#top)

View File

@ -0,0 +1,159 @@
<a id="top"></a>
# Open Source projects using Catch2
Catch2 is great for open source. It is licensed under the [Boost Software
License (BSL)](../LICENSE.txt), has no further dependencies and supports
two file distribution.
As a result, Catch2 is used for testing in many different Open Source
projects. This page lists at least some of them, even though it will
obviously never be complete (and does not have the ambition to be
complete). Note that the list below is intended to be in alphabetical
order, to avoid implications of relative importance of the projects.
_Please only add projects here if you are their maintainer, or have the
maintainer's explicit consent._
## Libraries & Frameworks
### [accessorpp](https://github.com/wqking/accessorpp)
C++ library for implementing property and data binding.
### [alpaka](https://github.com/alpaka-group/alpaka)
A header-only C++14 abstraction library for accelerator development.
### [ApprovalTests.cpp](https://github.com/approvals/ApprovalTests.cpp)
C++11 implementation of Approval Tests, for quick, convenient testing of legacy code.
### [args](https://github.com/Taywee/args)
A simple header-only C++ argument parser library.
### [Azmq](https://github.com/zeromq/azmq)
Boost Asio style bindings for ZeroMQ.
### [Cataclysm: Dark Days Ahead](https://github.com/CleverRaven/Cataclysm-DDA)
Post-apocalyptic survival RPG.
### [ChaiScript](https://github.com/ChaiScript/ChaiScript)
A, header-only, embedded scripting language designed from the ground up to directly target C++ and take advantage of modern C++ development techniques.
### [ChakraCore](https://github.com/Microsoft/ChakraCore)
The core part of the Chakra JavaScript engine that powers Microsoft Edge.
### [Clara](https://github.com/philsquared/Clara)
A, single-header-only, type-safe, command line parser - which also prints formatted usage strings.
### [Couchbase-lite-core](https://github.com/couchbase/couchbase-lite-core)
The next-generation core storage and query engine for Couchbase Lite.
### [cppcodec](https://github.com/tplgy/cppcodec)
Header-only C++11 library to encode/decode base64, base64url, base32, base32hex and hex (a.k.a. base16) as specified in RFC 4648, plus Crockford's base32.
### [DtCraft](https://github.com/twhuang-uiuc/DtCraft)
A High-performance Cluster Computing Engine.
### [eventpp](https://github.com/wqking/eventpp)
C++ event library for callbacks, event dispatcher, and event queue. With eventpp you can easily implement signal and slot mechanism, publisher and subscriber pattern, or observer pattern.
### [forest](https://github.com/xorz57/forest)
Template Library of Tree Data Structures.
### [Fuxedo](https://github.com/fuxedo/fuxedo)
Open source Oracle Tuxedo-like XATMI middleware for C and C++.
### [HIP CPU Runtime](https://github.com/ROCm-Developer-Tools/HIP-CPU)
A header-only library that allows CPUs to execute unmodified HIP code. It is generic and does not assume a particular CPU vendor or architecture.
### [Inja](https://github.com/pantor/inja)
A header-only template engine for modern C++.
### [LLAMA](https://github.com/alpaka-group/llama)
A C++17 template header-only library for the abstraction of memory access patterns.
### [libcluon](https://github.com/chrberger/libcluon)
A single-header-only library written in C++14 to glue distributed software components (UDP, TCP, shared memory) supporting natively Protobuf, LCM/ZCM, MsgPack, and JSON for dynamic message transformations in-between.
### [MNMLSTC Core](https://github.com/mnmlstc/core)
A small and easy to use C++11 library that adds a functionality set that will be available in C++14 and later, as well as some useful additions.
### [nanodbc](https://github.com/lexicalunit/nanodbc/)
A small C++ library wrapper for the native C ODBC API.
### [Nonius](https://github.com/libnonius/nonius)
A header-only framework for benchmarking small snippets of C++ code.
### [OpenALpp](https://github.com/Laguna1989/OpenALpp)
A modern OOP C++14 audio library built on OpenAL for Windows, Linux and web (emscripten).
### [polymorphic_value](https://github.com/jbcoe/polymorphic_value)
A polymorphic value-type for C++.
### [Ppconsul](https://github.com/oliora/ppconsul)
A C++ client library for Consul. Consul is a distributed tool for discovering and configuring services in your infrastructure.
### [Reactive-Extensions/ RxCpp](https://github.com/Reactive-Extensions/RxCpp)
A library of algorithms for values-distributed-in-time.
### [SFML](https://github.com/SFML/SFML)
Simple and Fast Multimedia Library.
### [SOCI](https://github.com/SOCI/soci)
The C++ Database Access Library.
### [TextFlowCpp](https://github.com/philsquared/textflowcpp)
A small, single-header-only, library for wrapping and composing columns of text.
### [thor](https://github.com/xorz57/thor)
Wrapper Library for CUDA.
### [toml++](https://github.com/marzer/tomlplusplus)
A header-only TOML parser and serializer for modern C++.
### [Trompeloeil](https://github.com/rollbear/trompeloeil)
A thread-safe header-only mocking framework for C++14.
### [wxWidgets](https://www.wxwidgets.org/)
Cross-Platform C++ GUI Library.
### [xmlwrapp](https://github.com/vslavik/xmlwrapp)
C++ XML parsing library using libxml2.
## Applications & Tools
### [App Mesh](https://github.com/laoshanxi/app-mesh)
A high available cloud native micro-service application management platform implemented by modern C++.
### [ArangoDB](https://github.com/arangodb/arangodb)
ArangoDB is a native multi-model database with flexible data models for documents, graphs, and key-values.
### [Cytopia](https://github.com/CytopiaTeam/Cytopia)
Cytopia is a free, open source retro pixel-art city building game with a big focus on mods. It utilizes a custom isometric rendering engine based on SDL2.
### [d-SEAMS](https://github.com/d-SEAMS/seams-core)
Open source molecular dynamics simulation structure analysis suite of tools in modern C++.
### [Giada - Your Hardcore Loop Machine](https://github.com/monocasual/giada)
Minimal, open-source and cross-platform audio tool for live music production.
### [MAME](https://github.com/mamedev/mame)
MAME originally stood for Multiple Arcade Machine Emulator.
### [Newsbeuter](https://github.com/akrennmair/newsbeuter)
Newsbeuter is an open-source RSS/Atom feed reader for text terminals.
### [PopHead](https://github.com/SPC-Some-Polish-Coders/PopHead)
A 2D, Zombie, RPG game which is being made on our own engine.
### [raspigcd](https://github.com/pantadeusz/raspigcd)
Low level CLI app and library for execution of GCODE on Raspberry Pi without any additional microcontrollers (just RPi + Stepsticks).
### [SpECTRE](https://github.com/sxs-collaboration/spectre)
SpECTRE is a code for multi-scale, multi-physics problems in astrophysics and gravitational physics.
### [Standardese](https://github.com/foonathan/standardese)
Standardese aims to be a nextgen Doxygen.
---
[Home](Readme.md#top)

View File

@ -0,0 +1,131 @@
<a id="top"></a>
# Other macros
This page serves as a reference for macros that are not documented
elsewhere. For now, these macros are separated into 2 rough categories,
"assertion related macros" and "test case related macros".
## Assertion related macros
* `CHECKED_IF` and `CHECKED_ELSE`
`CHECKED_IF( expr )` is an `if` replacement, that also applies Catch2's
stringification machinery to the _expr_ and records the result. As with
`if`, the block after a `CHECKED_IF` is entered only if the expression
evaluates to `true`. `CHECKED_ELSE( expr )` work similarly, but the block
is entered only if the _expr_ evaluated to `false`.
> `CHECKED_X` macros were changed to not count as failure in Catch2 3.0.1.
Example:
```cpp
int a = ...;
int b = ...;
CHECKED_IF( a == b ) {
// This block is entered when a == b
} CHECKED_ELSE ( a == b ) {
// This block is entered when a != b
}
```
* `CHECK_NOFAIL`
`CHECK_NOFAIL( expr )` is a variant of `CHECK` that does not fail the test
case if _expr_ evaluates to `false`. This can be useful for checking some
assumption, that might be violated without the test necessarily failing.
Example output:
```
main.cpp:6:
FAILED - but was ok:
CHECK_NOFAIL( 1 == 2 )
main.cpp:7:
PASSED:
CHECK( 2 == 2 )
```
* `SUCCEED`
`SUCCEED( msg )` is mostly equivalent with `INFO( msg ); REQUIRE( true );`.
In other words, `SUCCEED` is for cases where just reaching a certain line
means that the test has been a success.
Example usage:
```cpp
TEST_CASE( "SUCCEED showcase" ) {
int I = 1;
SUCCEED( "I is " << I );
}
```
* `STATIC_REQUIRE` and `STATIC_CHECK`
> `STATIC_REQUIRE` was [introduced](https://github.com/catchorg/Catch2/issues/1362) in Catch2 2.4.2.
`STATIC_REQUIRE( expr )` is a macro that can be used the same way as a
`static_assert`, but also registers the success with Catch2, so it is
reported as a success at runtime. The whole check can also be deferred
to the runtime, by defining `CATCH_CONFIG_RUNTIME_STATIC_REQUIRE` before
including the Catch2 header.
Example:
```cpp
TEST_CASE("STATIC_REQUIRE showcase", "[traits]") {
STATIC_REQUIRE( std::is_void<void>::value );
STATIC_REQUIRE_FALSE( std::is_void<int>::value );
}
```
> `STATIC_CHECK` was [introduced](https://github.com/catchorg/Catch2/pull/2318) in Catch2 3.0.1.
`STATIC_CHECK( expr )` is equivalent to `STATIC_REQUIRE( expr )`, with the
difference that when `CATCH_CONFIG_RUNTIME_STATIC_REQUIRE` is defined, it
becomes equivalent to `CHECK` instead of `REQUIRE`.
Example:
```cpp
TEST_CASE("STATIC_CHECK showcase", "[traits]") {
STATIC_CHECK( std::is_void<void>::value );
STATIC_CHECK_FALSE( std::is_void<int>::value );
}
```
## Test case related macros
* `REGISTER_TEST_CASE`
`REGISTER_TEST_CASE( function, description )` let's you register
a `function` as a test case. The function has to have `void()` signature,
the description can contain both name and tags.
Example:
```cpp
REGISTER_TEST_CASE( someFunction, "ManuallyRegistered", "[tags]" );
```
_Note that the registration still has to happen before Catch2's session
is initiated. This means that it either needs to be done in a global
constructor, or before Catch2's session is created in user's own main._
* `DYNAMIC_SECTION`
> Introduced in Catch2 2.3.0.
`DYNAMIC_SECTION` is a `SECTION` where the user can use `operator<<` to
create the final name for that section. This can be useful with e.g.
generators, or when creating a `SECTION` dynamically, within a loop.
Example:
```cpp
TEST_CASE( "looped SECTION tests" ) {
int a = 1;
for( int b = 0; b < 10; ++b ) {
DYNAMIC_SECTION( "b is currently: " << b ) {
CHECK( b > a );
}
}
}
```

View File

@ -0,0 +1,132 @@
<a id="top"></a>
# Supplying main() yourself
**Contents**<br>
[Let Catch2 take full control of args and config](#let-catch2-take-full-control-of-args-and-config)<br>
[Amending the Catch2 config](#amending-the-catch2-config)<br>
[Adding your own command line options](#adding-your-own-command-line-options)<br>
[Version detection](#version-detection)<br>
The easiest way to use Catch2 is to use its own `main` function, and let
it handle the command line arguments. This is done by linking against
Catch2Main library, e.g. through the [CMake target](cmake-integration.md#cmake-targets),
or pkg-config files.
If you want to provide your own `main`, then you should link against
the static library (target) only, without the main part. You will then
have to write your own `main` and call into Catch2 test runner manually.
Below are some basic recipes on what you can do supplying your own main.
## Let Catch2 take full control of args and config
This is useful if you just need to have code that executes before/after
Catch2 runs tests.
```cpp
#include <catch2/catch_session.hpp>
int main( int argc, char* argv[] ) {
// your setup ...
int result = Catch::Session().run( argc, argv );
// your clean-up...
return result;
}
```
_Note that if you only want to run some set up before tests are run, it
might be simpler to use [event listeners](event-listeners.md#top) instead._
## Amending the Catch2 config
If you want Catch2 to process command line arguments, but also want to
programmatically change the resulting configuration of Catch2 run,
you can do it in two ways:
```c++
int main( int argc, char* argv[] ) {
Catch::Session session; // There must be exactly one instance
// writing to session.configData() here sets defaults
// this is the preferred way to set them
int returnCode = session.applyCommandLine( argc, argv );
if( returnCode != 0 ) // Indicates a command line error
return returnCode;
// writing to session.configData() or session.Config() here
// overrides command line args
// only do this if you know you need to
int numFailed = session.run();
// numFailed is clamped to 255 as some unices only use the lower 8 bits.
// This clamping has already been applied, so just return it here
// You can also do any post run clean-up here
return numFailed;
}
```
If you want full control of the configuration, don't call `applyCommandLine`.
## Adding your own command line options
You can add new command line options to Catch2, by composing the premade
CLI parser (called Clara), and add your own options.
```cpp
int main( int argc, char* argv[] ) {
Catch::Session session; // There must be exactly one instance
int height = 0; // Some user variable you want to be able to set
// Build a new parser on top of Catch2's
using namespace Catch::Clara;
auto cli
= session.cli() // Get Catch2's command line parser
| Opt( height, "height" ) // bind variable to a new option, with a hint string
["-g"]["--height"] // the option names it will respond to
("how high?"); // description string for the help output
// Now pass the new composite back to Catch2 so it uses that
session.cli( cli );
// Let Catch2 (using Clara) parse the command line
int returnCode = session.applyCommandLine( argc, argv );
if( returnCode != 0 ) // Indicates a command line error
return returnCode;
// if set on the command line then 'height' is now set at this point
if( height > 0 )
std::cout << "height: " << height << std::endl;
return session.run();
}
```
See the [Clara documentation](https://github.com/catchorg/Clara/blob/master/README.md)
for more details on how to use the Clara parser.
## Version detection
Catch2 provides a triplet of macros providing the header's version,
* `CATCH_VERSION_MAJOR`
* `CATCH_VERSION_MINOR`
* `CATCH_VERSION_PATCH`
these macros expand into a single number, that corresponds to the appropriate
part of the version. As an example, given single header version v2.3.4,
the macros would expand into `2`, `3`, and `4` respectively.
---
[Home](Readme.md#top)

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,66 @@
<a id="top"></a>
# How to release
When enough changes have accumulated, it is time to release new version of Catch. This document describes the process in doing so, that no steps are forgotten. Note that all referenced scripts can be found in the `tools/scripts/` directory.
## Necessary steps
These steps are necessary and have to be performed before each new release. They serve to make sure that the new release is correct and linked-to from the standard places.
### Testing
All of the tests are currently run in our CI setup based on TravisCI and
AppVeyor. As long as the last commit tested green, the release can
proceed.
### Incrementing version number
Catch uses a variant of [semantic versioning](http://semver.org/), with breaking API changes (and thus major version increments) being very rare. Thus, the release will usually increment the patch version, when it only contains couple of bugfixes, or minor version, when it contains new functionality, or larger changes in implementation of current functionality.
After deciding which part of version number should be incremented, you can use one of the `*Release.py` scripts to perform the required changes to Catch.
This will take care of generating the single include header, updating
version numbers everywhere and pushing the new version to Wandbox.
### Release notes
Once a release is ready, release notes need to be written. They should summarize changes done since last release. For rough idea of expected notes see previous releases. Once written, release notes should be added to `docs/release-notes.md`.
### Commit and push update to GitHub
After version number is incremented, single-include header is regenerated and release notes are updated, changes should be committed and pushed to GitHub.
### Release on GitHub
After pushing changes to GitHub, GitHub release *needs* to be created.
Tag version and release title should be same as the new version,
description should contain the release notes for the current release.
We also attach the two amalgamated files as "binaries".
Since 2.5.0, the release tag and the "binaries" (amalgamated files) should
be PGP signed.
#### Signing a tag
To create a signed tag, use `git tag -s <VERSION>`, where `<VERSION>`
is the version being released, e.g. `git tag -s v2.6.0`.
Use the version name as the short message and the release notes as
the body (long) message.
#### Signing the amalgamated files
This will create ASCII-armored signatures for the two amalgamated files
that are uploaded to the GitHub release:
```
gpg --armor --output extras/catch_amalgamated.hpp.asc --detach-sig extras/catch_amalgamated.hpp
gpg --armor --output extras/catch_amalgamated.cpp.asc --detach-sig extras/catch_amalgamated.cpp
```
_GPG does not support signing multiple files in single invocation._

View File

@ -0,0 +1,175 @@
<a id="top"></a>
# Reporter events
**Contents**<br>
[Test running events](#test-running-events)<br>
[Benchmarking events](#benchmarking-events)<br>
[Listings events](#listings-events)<br>
[Miscellaneous events](#miscellaneous-events)<br>
Reporter events are one of the customization points for user code. They
are used by [reporters](reporters.md#top) to customize Catch2's output,
and by [event listeners](event-listeners.md#top) to perform in-process
actions under some conditions.
There are currently 21 reporter events in Catch2, split between 4 distinct
event groups:
* test running events (10 events)
* benchmarking (4 events)
* listings (3 events)
* miscellaneous (4 events)
## Test running events
Test running events are always paired so that for each `fooStarting` event,
there is a `fooEnded` event. This means that the 10 test running events
consist of 5 pairs of events:
* `testRunStarting` and `testRunEnded`,
* `testCaseStarting` and `testCaseEnded`,
* `testCasePartialStarting` and `testCasePartialEnded`,
* `sectionStarting` and `sectionEnded`,
* `assertionStarting` and `assertionEnded`
### `testRun` events
```cpp
void testRunStarting( TestRunInfo const& testRunInfo );
void testRunEnded( TestRunStats const& testRunStats );
```
The `testRun` events bookend the entire test run. `testRunStarting` is
emitted before the first test case is executed, and `testRunEnded` is
emitted after all the test cases have been executed.
### `testCase` events
```cpp
void testCaseStarting( TestCaseInfo const& testInfo );
void testCaseEnded( TestCaseStats const& testCaseStats );
```
The `testCase` events bookend one _full_ run of a specific test case.
Individual runs through a test case, e.g. due to `SECTION`s or `GENERATE`s,
are handled by a different event.
### `testCasePartial` events
> Introduced in Catch2 3.0.1
```cpp
void testCasePartialStarting( TestCaseInfo const& testInfo, uint64_t partNumber );
void testCasePartialEnded(TestCaseStats const& testCaseStats, uint64_t partNumber );
```
`testCasePartial` events bookend one _partial_ run of a specific test case.
This means that for any given test case, these events can be emitted
multiple times, e.g. due to multiple leaf sections.
In regards to nesting with `testCase` events, `testCasePartialStarting`
will never be emitted before the corresponding `testCaseStarting`, and
`testCasePartialEnded` will always be emitted before the corresponding
`testCaseEnded`.
### `section` events
```cpp
void sectionStarting( SectionInfo const& sectionInfo );
void sectionEnded( SectionStats const& sectionStats );
```
`section` events are emitted only for active `SECTION`s, that is, sections
that are entered. Sections that are skipped in this test case run-through
do not cause events to be emitted.
_Note that test cases always contain one implicit section. The event for
this section is emitted after the corresponding `testCasePartialStarting`
event._
### `assertion` events
```cpp
void assertionStarting( AssertionInfo const& assertionInfo );
void assertionEnded( AssertionStats const& assertionStats );
```
The `assertionStarting` event is emitted before the expression in the
assertion is captured or evaluated and `assertionEnded` is emitted
afterwards. This means that given assertion like `REQUIRE(a + b == c + d)`,
Catch2 first emits `assertionStarting` event, then `a + b` and `c + d`
are evaluated, then their results are captured, the comparison is evaluated,
and then `assertionEnded` event is emitted.
## Benchmarking events
> [Introduced](https://github.com/catchorg/Catch2/issues/1616) in Catch2 2.9.0.
```cpp
void benchmarkPreparing( StringRef name ) override;
void benchmarkStarting( BenchmarkInfo const& benchmarkInfo ) override;
void benchmarkEnded( BenchmarkStats<> const& benchmarkStats ) override;
void benchmarkFailed( StringRef error ) override;
```
Due to the benchmark lifecycle being bit more complicated, the benchmarking
events have their own category, even though they could be seen as parallel
to the `assertion*` events. You should expect running a benchmark to
generate at least 2 of the events above.
To understand the explanation below, you should read the [benchmarking
documentation](benchmarks.md#top) first.
* `benchmarkPreparing` event is sent after the environmental probe
finishes, but before the user code is first estimated.
* `benchmarkStarting` event is sent after the user code is estimated,
but has not been benchmarked yet.
* `benchmarkEnded` event is sent after the user code has been benchmarked,
and contains the benchmarking results.
* `benchmarkFailed` event is sent if either the estimation or the
benchmarking itself fails.
## Listings events
> Introduced in Catch2 3.0.1.
Listings events are events that correspond to the test binary being
invoked with `--list-foo` flag.
There are currently 3 listing events, one for reporters, one for tests,
and one for tags. Note that they are not exclusive to each other.
```cpp
void listReporters( std::vector<ReporterDescription> const& descriptions );
void listTests( std::vector<TestCaseHandle> const& tests );
void listTags( std::vector<TagInfo> const& tagInfos );
```
## Miscellaneous events
```cpp
void reportInvalidTestSpec( StringRef unmatchedSpec );
void fatalErrorEncountered( StringRef error );
void noMatchingTestCases( StringRef unmatchedSpec );
```
These are one-off events that do not neatly fit into other categories.
`reportInvalidTestSpec` is sent for each [test specification command line
argument](command-line.md#specifying-which-tests-to-run) that wasn't
parsed into a valid spec.
`fatalErrorEncountered` is sent when Catch2's POSIX signal handling
or Windows SE handler is called into with a fatal signal/exception.
`noMatchingTestCases` is sent for each user provided test specification
that did not match any registered tests.
---
[Home](Readme.md#top)

View File

@ -0,0 +1,213 @@
<a id="top"></a>
# Reporters
Reporters are a customization point for most of Catch2's output, e.g.
formatting and writing out [assertions (whether passing or failing),
sections, test cases, benchmarks, and so on](reporter-events.md#top).
Catch2 comes with a bunch of reporters by default (currently 9), and
you can also write your own reporter. Because multiple reporters can
be active at the same time, your own reporters do not even have to handle
all reporter event, just the ones you are interested in, e.g. benchmarks.
## Using different reporters
You can see which reporters are available by running the test binary
with `--list-reporters`. You can then pick one of them with the [`-r`,
`--reporter` option](command-line.md#choosing-a-reporter-to-use), followed
by the name of the desired reporter, like so:
```
--reporter xml
```
You can also select multiple reporters to be used at the same time.
In that case you should read the [section on using multiple
reporters](#multiple-reporters) to avoid any surprises from doing so.
<a id="multiple-reporters"></a>
## Using multiple reporters
> Support for having multiple parallel reporters was [introduced](https://github.com/catchorg/Catch2/pull/2183) in Catch2 3.0.1
Catch2 supports using multiple reporters at the same time while having
them write into different destinations. The two main uses of this are
* having both human-friendly and machine-parseable (e.g. in JUnit format)
output from one run of binary
* having "partial" reporters that are highly specialized, e.g. having one
reporter that writes out benchmark results as markdown tables and does
nothing else, while also having standard testing output separately
Specifying multiple reporter looks like this:
```
--reporter JUnit::out=result-junit.xml --reporter console::out=-::colour-mode=ansi
```
This tells Catch2 to use two reporters, `JUnit` reporter that writes
its machine-readable XML output to file `result-junit.xml`, and the
`console` reporter that writes its user-friendly output to stdout and
uses ANSI colour codes for colouring the output.
Using multiple reporters (or one reporter and one-or-more [event
listeners](event-listeners.md#top)) can have surprisingly complex semantics
when using customization points provided to reporters by Catch2, namely
capturing stdout/stderr from test cases.
As long as at least one reporter (or listener) asks Catch2 to capture
stdout/stderr, captured stdout and stderr will be available to all
reporters and listeners.
Because this might be surprising to the users, if at least one active
_reporter_ is non-capturing, then Catch2 tries to roughly emulate
non-capturing behaviour by printing out the captured stdout/stderr
just before `testCasePartialEnded` event is sent out to the active
reporters and listeners. This means that stdout/stderr is no longer
printed out from tests as it is being written, but instead it is written
out in batch after each runthrough of a test case is finished.
## Writing your own reporter
You can also write your own custom reporter and tell Catch2 to use it.
When writing your reporter, you have two options:
* Derive from `Catch::ReporterBase`. When doing this, you will have
to provide handling for all [reporter events](reporter-events.md#top).
* Derive from one of the provided [utility reporter bases in
Catch2](#utility-reporter-bases).
Generally we recommend doing the latter, as it is less work.
Apart from overriding handling of the individual reporter events, reporters
have access to some extra customization points, described below.
### Utility reporter bases
Catch2 currently provides two utility reporter bases:
* `Catch::StreamingReporterBase`
* `Catch::CumulativeReporterBase`
`StreamingReporterBase` is useful for reporters that can format and write
out the events as they come in. It provides (usually empty) implementation
for all reporter events, and if you let it handle the relevant events,
it also handles storing information about active test run and test case.
`CumulativeReporterBase` is a base for reporters that need to see the whole
test run, before they can start writing the output, such as the JUnit
and SonarQube reporters. This post-facto approach requires the assertions
to be stringified when it is finished, so that the assertion can be written
out later. Because the stringification can be expensive, and not all
cumulative reporters need the assertions, this base provides customization
point to change whether the assertions are saved or not, separate for
passing and failing assertions.
_Generally we recommend that if you override a member function from either
of the bases, you call into the base's implementation first. This is not
necessarily in all cases, but it is safer and easier._
Writing your own reporter then looks like this:
```cpp
#include <catch2/reporters/catch_reporter_streaming_base.hpp>
#include <catch2/catch_test_case_info.hpp>
#include <catch2/reporters/catch_reporter_registrars.hpp>
#include <iostream>
class PartialReporter : public Catch::StreamingReporterBase {
public:
using StreamingReporterBase::StreamingReporterBase;
static std::string getDescription() {
return "Reporter for testing TestCasePartialStarting/Ended events";
}
void testCasePartialStarting(Catch::TestCaseInfo const& testInfo,
uint64_t partNumber) override {
std::cout << "TestCaseStartingPartial: " << testInfo.name << '#' << partNumber << '\n';
}
void testCasePartialEnded(Catch::TestCaseStats const& testCaseStats,
uint64_t partNumber) override {
std::cout << "TestCasePartialEnded: " << testCaseStats.testInfo->name << '#' << partNumber << '\n';
}
};
CATCH_REGISTER_REPORTER("partial", PartialReporter)
```
This create a simple reporter that responds to `testCasePartial*` events,
and calls itself "partial" reporter, so it can be invoked with
`--reporter partial` command line flag.
### `ReporterPreferences`
Each reporter instance contains instance of `ReporterPreferences`, a type
that holds flags for the behaviour of Catch2 when this reporter run.
Currently there are two customization options:
* `shouldRedirectStdOut` - whether the reporter wants to handle
writes to stdout/stderr from user code, or not. This is useful for
reporters that output machine-parseable output, e.g. the JUnit
reporter, or the XML reporter.
* `shouldReportAllAssertions` - whether the reporter wants to handle
`assertionEnded` events for passing assertions as well as failing
assertions. Usually reporters do not report successful assertions
and don't need them for their output, but sometimes the desired output
format includes passing assertions even without the `-s` flag.
### Per-reporter configuration
> Per-reporter configuration was introduced in Catch2 3.0.1
Catch2 supports some configuration to happen per reporter. The configuration
options fall into one of two categories:
* Catch2-recognized options
* Reporter-specific options
The former is a small set of universal options that Catch2 handles for
the reporters, e.g. output file or console colour mode. The latter are
options that the reporters have to handle themselves, but the keys and
values can be arbitrary strings, as long as they don't contain `::`. This
allows writing reporters that can be significantly customized at runtime.
Reporter-specific options always have to be prefixed with "X" (large
letter X).
### Other expected functionality of a reporter
When writing a custom reporter, there are few more things that you should
keep in mind. These are not important for correctness, but they are
important for the reporter to work _nicely_.
* Catch2 provides a simple verbosity option for users. There are three
verbosity levels, "quiet", "normal", and "high", and if it makes sense
for reporter's output format, it should respond to these by changing
what, and how much, it writes out.
* Catch2 operates with an rng-seed. Knowing what seed a test run had
is important if you want to replicate it, so your reporter should
report the rng-seed, if at all possible given the target output format.
* Catch2 also operates with test filters, or test specs. If a filter
is present, you should also report the filter, if at all possible given
the target output format.
---
[Home](Readme.md#top)

View File

@ -0,0 +1,135 @@
<a id="top"></a>
# Explicitly skipping, passing, and failing tests at runtime
## Skipping Test Cases at Runtime
> [Introduced](https://github.com/catchorg/Catch2/pull/2360) in Catch2 3.3.0.
In some situations it may not be possible to meaningfully execute a test case,
for example when the system under test is missing certain hardware capabilities.
If the required conditions can only be determined at runtime, it often
doesn't make sense to consider such a test case as either passed or failed,
because it simply cannot run at all.
To properly express such scenarios, Catch2 provides a way to explicitly
_skip_ test cases, using the `SKIP` macro:
```
SKIP( [streamable expression] )
```
Example usage:
```c++
TEST_CASE("copy files between drives") {
if(getNumberOfHardDrives() < 2) {
SKIP("at least two hard drives required");
}
// ...
}
```
This test case is then reported as _skipped_ instead of _passed_ or _failed_.
The `SKIP` macro behaves similarly to an explicit [`FAIL`](#passing-and-failing-test-cases),
in that it is the last expression that will be executed:
```c++
TEST_CASE("my test") {
printf("foo");
SKIP();
printf("bar"); // not printed
}
```
However a failed assertion _before_ a `SKIP` still causes the entire
test case to fail:
```c++
TEST_CASE("failing test") {
CHECK(1 == 2);
SKIP();
}
```
### Interaction with Sections and Generators
Sections, nested sections as well as specific outputs from [generators](generators.md#top)
can all be individually skipped, with the rest executing as usual:
```c++
TEST_CASE("complex test case") {
int value = GENERATE(2, 4, 6);
SECTION("a") {
SECTION("a1") { CHECK(value < 8); }
SECTION("a2") {
if (value == 4) {
SKIP();
}
CHECK(value % 2 == 0);
}
}
}
```
This test case will report 5 passing assertions; one for each of the three
values in section `a1`, and then two in section `a2`, from values 2 and 4.
Note that as soon as one section is skipped, the entire test case will
be reported as _skipped_ (unless there is a failing assertion, in which
case the test is handled as _failed_ instead).
Note that if all test cases in a run are skipped, Catch2 returns a non-zero
exit code, same as it does if no test cases have run. This behaviour can
be overridden using the [--allow-running-no-tests](command-line.md#no-tests-override)
flag.
### `SKIP` inside generators
You can also use the `SKIP` macro inside generator's constructor to handle
cases where the generator is empty, but you do not want to fail the test
case.
## Passing and failing test cases
Test cases can also be explicitly passed or failed, without the use of
assertions, and with a specific message. This can be useful to handle
complex preconditions/postconditions and give useful error messages
when they fail.
* `SUCCEED( [streamable expression] )`
`SUCCEED` is morally equivalent with `INFO( [streamable expression] ); REQUIRE( true );`.
Note that it does not stop further test execution, so it cannot be used
to guard failing assertions from being executed.
_In practice, `SUCCEED` is usually used as a test placeholder, to avoid
[failing a test case due to missing assertions](command-line.md#warnings)._
```cpp
TEST_CASE( "SUCCEED showcase" ) {
int I = 1;
SUCCEED( "I is " << I );
// ... execution continues here ...
}
```
* `FAIL( [streamable expression] )`
`FAIL` is morally equivalent with `INFO( [streamable expression] ); REQUIRE( false );`.
_In practice, `FAIL` is usually used to stop executing test that is currently
known to be broken, but has to be fixed later._
```cpp
TEST_CASE( "FAIL showcase" ) {
FAIL( "This test case causes segfault, which breaks CI." );
// ... this will not be executed ...
}
```
---
[Home](Readme.md#top)

View File

@ -0,0 +1,346 @@
<a id="top"></a>
# Test cases and sections
**Contents**<br>
[Tags](#tags)<br>
[Tag aliases](#tag-aliases)<br>
[BDD-style test cases](#bdd-style-test-cases)<br>
[Type parametrised test cases](#type-parametrised-test-cases)<br>
[Signature based parametrised test cases](#signature-based-parametrised-test-cases)<br>
While Catch fully supports the traditional, xUnit, style of class-based fixtures containing test case methods this is not the preferred style.
Instead Catch provides a powerful mechanism for nesting test case sections within a test case. For a more detailed discussion see the [tutorial](tutorial.md#test-cases-and-sections).
Test cases and sections are very easy to use in practice:
* **TEST_CASE(** _test name_ \[, _tags_ \] **)**
* **SECTION(** _section name_, \[, _section description_ \] **)**
_test name_ and _section name_ are free form, quoted, strings.
The optional _tags_ argument is a quoted string containing one or more
tags enclosed in square brackets, and are discussed below.
_section description_ can be used to provide long form description
of a section while keeping the _section name_ short for use with the
[`-c` command line parameter](command-line.md#specify-the-section-to-run).
**The combination of test names and tags must be unique within the Catch2
executable.**
For examples see the [Tutorial](tutorial.md#top)
## Tags
Tags allow an arbitrary number of additional strings to be associated with a test case. Test cases can be selected (for running, or just for listing) by tag - or even by an expression that combines several tags. At their most basic level they provide a simple way to group several related tests together.
As an example - given the following test cases:
TEST_CASE( "A", "[widget]" ) { /* ... */ }
TEST_CASE( "B", "[widget]" ) { /* ... */ }
TEST_CASE( "C", "[gadget]" ) { /* ... */ }
TEST_CASE( "D", "[widget][gadget]" ) { /* ... */ }
The tag expression, ```"[widget]"``` selects A, B & D. ```"[gadget]"``` selects C & D. ```"[widget][gadget]"``` selects just D and ```"[widget],[gadget]"``` selects all four test cases.
For more detail on command line selection see [the command line docs](command-line.md#specifying-which-tests-to-run)
Tag names are not case sensitive and can contain any ASCII characters.
This means that tags `[tag with spaces]` and `[I said "good day"]`
are both allowed tags and can be filtered on. However, escapes are not
supported and `[\]]` is not a valid tag.
The same tag can be specified multiple times for a single test case,
but only one of the instances of identical tags will be kept. Which one
is kept is functionally random.
### Special Tags
All tag names beginning with non-alphanumeric characters are reserved by Catch. Catch defines a number of "special" tags, which have meaning to the test runner itself. These special tags all begin with a symbol character. Following is a list of currently defined special tags and their meanings.
* `[.]` - causes test cases to be skipped from the default list (i.e. when no test cases have been explicitly selected through tag expressions or name wildcards). The hide tag is often combined with another, user, tag (for example `[.][integration]` - so all integration tests are excluded from the default run but can be run by passing `[integration]` on the command line). As a short-cut you can combine these by simply prefixing your user tag with a `.` - e.g. `[.integration]`.
* `[!throws]` - lets Catch know that this test is likely to throw an exception even if successful. This causes the test to be excluded when running with `-e` or `--nothrow`.
* `[!mayfail]` - doesn't fail the test if any given assertion fails (but still reports it). This can be useful to flag a work-in-progress, or a known issue that you don't want to immediately fix but still want to track in your tests.
* `[!shouldfail]` - like `[!mayfail]` but *fails* the test if it *passes*. This can be useful if you want to be notified of accidental, or third-party, fixes.
* `[!nonportable]` - Indicates that behaviour may vary between platforms or compilers.
* `[#<filename>]` - these tags are added to test cases when you run Catch2
with [`-#` or `--filenames-as-tags`](command-line.md#filenames-as-tags).
* `[@<alias>]` - tag aliases all begin with `@` (see below).
* `[!benchmark]` - this test case is actually a benchmark. Currently this only serves to hide the test case by default, to avoid the execution time costs.
## Tag aliases
Between tag expressions and wildcarded test names (as well as combinations of the two) quite complex patterns can be constructed to direct which test cases are run. If a complex pattern is used often it is convenient to be able to create an alias for the expression. This can be done, in code, using the following form:
CATCH_REGISTER_TAG_ALIAS( <alias string>, <tag expression> )
Aliases must begin with the `@` character. An example of a tag alias is:
CATCH_REGISTER_TAG_ALIAS( "[@nhf]", "[failing]~[.]" )
Now when `[@nhf]` is used on the command line this matches all tests that are tagged `[failing]`, but which are not also hidden.
## BDD-style test cases
In addition to Catch's take on the classic style of test cases, Catch supports an alternative syntax that allow tests to be written as "executable specifications" (one of the early goals of [Behaviour Driven Development](http://dannorth.net/introducing-bdd/)). This set of macros map on to ```TEST_CASE```s and ```SECTION```s, with a little internal support to make them smoother to work with.
* **SCENARIO(** _scenario name_ \[, _tags_ \] **)**
This macro maps onto ```TEST_CASE``` and works in the same way, except that the test case name will be prefixed by "Scenario: "
* **GIVEN(** _something_ **)**
* **WHEN(** _something_ **)**
* **THEN(** _something_ **)**
These macros map onto ```SECTION```s except that the section names are the _something_ texts prefixed by
"given: ", "when: " or "then: " respectively. These macros also map onto the AAA or A<sup>3</sup> test pattern
(standing either for [Assemble-Activate-Assert](http://wiki.c2.com/?AssembleActivateAssert) or
[Arrange-Act-Assert](http://wiki.c2.com/?ArrangeActAssert)), and in this context, the macros provide both code
documentation and reporting of these parts of a test case without the need for extra comments or code to do so.
Semantically, a `GIVEN` clause may have multiple _independent_ `WHEN` clauses within it. This allows a test
to have, e.g., one set of "given" objects and multiple subtests using those objects in various ways in each
of the `WHEN` clauses without repeating the initialisation from the `GIVEN` clause. When there are _dependent_
clauses -- such as a second `WHEN` clause that should only happen _after_ the previous `WHEN` clause has been
executed and validated -- there are additional macros starting with `AND_`:
* **AND_GIVEN(** _something_ **)**
* **AND_WHEN(** _something_ **)**
* **AND_THEN(** _something_ **)**
These are used to chain ```GIVEN```s, ```WHEN```s and ```THEN```s together. The `AND_*` clause is placed
_inside_ the clause on which it depends. There can be multiple _independent_ clauses that are all _dependent_
on a single outer clause.
```cpp
SCENARIO( "vector can be sized and resized" ) {
GIVEN( "An empty vector" ) {
auto v = std::vector<std::string>{};
// Validate assumption of the GIVEN clause
THEN( "The size and capacity start at 0" ) {
REQUIRE( v.size() == 0 );
REQUIRE( v.capacity() == 0 );
}
// Validate one use case for the GIVEN object
WHEN( "push_back() is called" ) {
v.push_back("hullo");
THEN( "The size changes" ) {
REQUIRE( v.size() == 1 );
REQUIRE( v.capacity() >= 1 );
}
}
}
}
```
This code will result in two runs through the scenario:
```
Scenario : vector can be sized and resized
Given : An empty vector
Then : The size and capacity start at 0
Scenario : vector can be sized and resized
Given : An empty vector
When : push_back() is called
Then : The size changes
```
See also [runnable example on godbolt](https://godbolt.org/z/eY5a64r99),
with a more complicated (and failing) example.
> `AND_GIVEN` was [introduced](https://github.com/catchorg/Catch2/issues/1360) in Catch2 2.4.0.
When any of these macros are used the console reporter recognises them and formats the test case header such that the Givens, Whens and Thens are aligned to aid readability.
Other than the additional prefixes and the formatting in the console reporter these macros behave exactly as ```TEST_CASE```s and ```SECTION```s. As such there is nothing enforcing the correct sequencing of these macros - that's up to the programmer!
## Type parametrised test cases
In addition to `TEST_CASE`s, Catch2 also supports test cases parametrised
by types, in the form of `TEMPLATE_TEST_CASE`,
`TEMPLATE_PRODUCT_TEST_CASE` and `TEMPLATE_LIST_TEST_CASE`. These macros
are defined in the `catch_template_test_macros.hpp` header, so compiling
the code examples below also requires
`#include <catch2/catch_template_test_macros.hpp>`.
* **TEMPLATE_TEST_CASE(** _test name_ , _tags_, _type1_, _type2_, ..., _typen_ **)**
> [Introduced](https://github.com/catchorg/Catch2/issues/1437) in Catch2 2.5.0.
_test name_ and _tag_ are exactly the same as they are in `TEST_CASE`,
with the difference that the tag string must be provided (however, it
can be empty). _type1_ through _typen_ is the list of types for which
this test case should run, and, inside the test code, the current type
is available as the `TestType` type.
Because of limitations of the C++ preprocessor, if you want to specify
a type with multiple template parameters, you need to enclose it in
parentheses, e.g. `std::map<int, std::string>` needs to be passed as
`(std::map<int, std::string>)`.
Example:
```cpp
TEMPLATE_TEST_CASE( "vectors can be sized and resized", "[vector][template]", int, std::string, (std::tuple<int,float>) ) {
std::vector<TestType> v( 5 );
REQUIRE( v.size() == 5 );
REQUIRE( v.capacity() >= 5 );
SECTION( "resizing bigger changes size and capacity" ) {
v.resize( 10 );
REQUIRE( v.size() == 10 );
REQUIRE( v.capacity() >= 10 );
}
SECTION( "resizing smaller changes size but not capacity" ) {
v.resize( 0 );
REQUIRE( v.size() == 0 );
REQUIRE( v.capacity() >= 5 );
SECTION( "We can use the 'swap trick' to reset the capacity" ) {
std::vector<TestType> empty;
empty.swap( v );
REQUIRE( v.capacity() == 0 );
}
}
SECTION( "reserving smaller does not change size or capacity" ) {
v.reserve( 0 );
REQUIRE( v.size() == 5 );
REQUIRE( v.capacity() >= 5 );
}
}
```
* **TEMPLATE_PRODUCT_TEST_CASE(** _test name_ , _tags_, (_template-type1_, _template-type2_, ..., _template-typen_), (_template-arg1_, _template-arg2_, ..., _template-argm_) **)**
> [Introduced](https://github.com/catchorg/Catch2/issues/1468) in Catch2 2.6.0.
_template-type1_ through _template-typen_ is list of template
types which should be combined with each of _template-arg1_ through
_template-argm_, resulting in _n * m_ test cases. Inside the test case,
the resulting type is available under the name of `TestType`.
To specify more than 1 type as a single _template-type_ or _template-arg_,
you must enclose the types in an additional set of parentheses, e.g.
`((int, float), (char, double))` specifies 2 template-args, each
consisting of 2 concrete types (`int`, `float` and `char`, `double`
respectively). You can also omit the outer set of parentheses if you
specify only one type as the full set of either the _template-types_,
or the _template-args_.
Example:
```cpp
template< typename T>
struct Foo {
size_t size() {
return 0;
}
};
TEMPLATE_PRODUCT_TEST_CASE("A Template product test case", "[template][product]", (std::vector, Foo), (int, float)) {
TestType x;
REQUIRE(x.size() == 0);
}
```
You can also have different arities in the _template-arg_ packs:
```cpp
TEMPLATE_PRODUCT_TEST_CASE("Product with differing arities", "[template][product]", std::tuple, (int, (int, double), (int, double, float))) {
TestType x;
REQUIRE(std::tuple_size<TestType>::value >= 1);
}
```
* **TEMPLATE_LIST_TEST_CASE(** _test name_, _tags_, _type list_ **)**
> [Introduced](https://github.com/catchorg/Catch2/issues/1627) in Catch2 2.9.0.
_type list_ is a generic list of types on which test case should be instantiated.
List can be `std::tuple`, `boost::mpl::list`, `boost::mp11::mp_list` or anything with
`template <typename...>` signature.
This allows you to reuse the _type list_ in multiple test cases.
Example:
```cpp
using MyTypes = std::tuple<int, char, float>;
TEMPLATE_LIST_TEST_CASE("Template test case with test types specified inside std::tuple", "[template][list]", MyTypes)
{
REQUIRE(sizeof(TestType) > 0);
}
```
## Signature based parametrised test cases
> [Introduced](https://github.com/catchorg/Catch2/issues/1609) in Catch2 2.8.0.
In addition to [type parametrised test cases](#type-parametrised-test-cases) Catch2 also supports
signature base parametrised test cases, in form of `TEMPLATE_TEST_CASE_SIG` and `TEMPLATE_PRODUCT_TEST_CASE_SIG`.
These test cases have similar syntax like [type parametrised test cases](#type-parametrised-test-cases), with one
additional positional argument which specifies the signature. These macros are defined in the
`catch_template_test_macros.hpp` header, so compiling the code examples below also requires
`#include <catch2/catch_template_test_macros.hpp>`.
### Signature
Signature has some strict rules for these tests cases to work properly:
* signature with multiple template parameters e.g. `typename T, size_t S` must have this format in test case declaration
`((typename T, size_t S), T, S)`
* signature with variadic template arguments e.g. `typename T, size_t S, typename...Ts` must have this format in test case declaration
`((typename T, size_t S, typename...Ts), T, S, Ts...)`
* signature with single non type template parameter e.g. `int V` must have this format in test case declaration `((int V), V)`
* signature with single type template parameter e.g. `typename T` should not be used as it is in fact `TEMPLATE_TEST_CASE`
Currently Catch2 support up to 11 template parameters in signature
### Examples
* **TEMPLATE_TEST_CASE_SIG(** _test name_ , _tags_, _signature_, _type1_, _type2_, ..., _typen_ **)**
Inside `TEMPLATE_TEST_CASE_SIG` test case you can use the names of template parameters as defined in _signature_.
```cpp
TEMPLATE_TEST_CASE_SIG("TemplateTestSig: arrays can be created from NTTP arguments", "[vector][template][nttp]",
((typename T, int V), T, V), (int,5), (float,4), (std::string,15), ((std::tuple<int, float>), 6)) {
std::array<T, V> v;
REQUIRE(v.size() > 1);
}
```
* **TEMPLATE_PRODUCT_TEST_CASE_SIG(** _test name_ , _tags_, _signature_, (_template-type1_, _template-type2_, ..., _template-typen_), (_template-arg1_, _template-arg2_, ..., _template-argm_) **)**
```cpp
template<typename T, size_t S>
struct Bar {
size_t size() { return S; }
};
TEMPLATE_PRODUCT_TEST_CASE_SIG("A Template product test case with array signature", "[template][product][nttp]", ((typename T, size_t S), T, S), (std::array, Bar), ((int, 9), (float, 42))) {
TestType x;
REQUIRE(x.size() > 0);
}
```
---
[Home](Readme.md#top)

View File

@ -0,0 +1,291 @@
<a id="top"></a>
# Test fixtures
**Contents**<br>
[Non-Templated test fixtures](#non-templated-test-fixtures)<br>
[Templated test fixtures](#templated-test-fixtures)<br>
[Signature-based parameterised test fixtures](#signature-based-parametrised-test-fixtures)<br>
[Template fixtures with types specified in template type lists](#template-fixtures-with-types-specified-in-template-type-lists)<br>
## Non-Templated test fixtures
Although Catch2 allows you to group tests together as
[sections within a test case](test-cases-and-sections.md), it can still
be convenient, sometimes, to group them using a more traditional test.
Catch2 fully supports this too with 3 different macros for
non-templated test fixtures. They are:
| Macro | Description |
|----------|-------------|
|1. `TEST_CASE_METHOD(className, ...)`| Creates a uniquely named class which inherits from the class specified by `className`. The test function will be a member of this derived class. An instance of the derived class will be created for every partial run of the test case. |
|2. `METHOD_AS_TEST_CASE(member-function, ...)`| Uses `member-function` as the test function. An instance of the class will be created for each partial run of the test case. |
|3. `TEST_CASE_PERSISTENT_FIXTURE(className, ...)`| Creates a uniquely named class which inherits from the class specified by `className`. The test function will be a member of this derived class. An instance of the derived class will be created at the start of the test run. That instance will be destroyed once the entire test case has ended. |
### 1. `TEST_CASE_METHOD`
You define a `TEST_CASE_METHOD` test fixture as a simple structure:
```c++
class UniqueTestsFixture {
private:
static int uniqueID;
protected:
DBConnection conn;
public:
UniqueTestsFixture() : conn(DBConnection::createConnection("myDB")) {
}
protected:
int getID() {
return ++uniqueID;
}
};
int UniqueTestsFixture::uniqueID = 0;
TEST_CASE_METHOD(UniqueTestsFixture, "Create Employee/No Name", "[create]") {
REQUIRE_THROWS(conn.executeSQL("INSERT INTO employee (id, name) VALUES (?, ?)", getID(), ""));
}
TEST_CASE_METHOD(UniqueTestsFixture, "Create Employee/Normal", "[create]") {
REQUIRE(conn.executeSQL("INSERT INTO employee (id, name) VALUES (?, ?)", getID(), "Joe Bloggs"));
}
```
The two test cases here will create uniquely-named derived classes of
UniqueTestsFixture and thus can access the `getID()` protected method
and `conn` member variables. This ensures that both the test cases
are able to create a DBConnection using the same method
(DRY principle) and that any ID's created are unique such that the
order that tests are executed does not matter.
### 2. `METHOD_AS_TEST_CASE`
`METHOD_AS_TEST_CASE` lets you register a member function of a class
as a Catch2 test case. The class will be separately instantiated
for each method registered in this way.
```cpp
class TestClass {
std::string s;
public:
TestClass()
:s( "hello" )
{}
void testCase() {
REQUIRE( s == "hello" );
}
};
METHOD_AS_TEST_CASE( TestClass::testCase, "Use class's method as a test case", "[class]" )
```
This type of fixture is similar to [TEST_CASE_METHOD](#1-test_case_method) except in this
case it will directly use the provided class to create an object rather than a derived
class.
### 3. `TEST_CASE_PERSISTENT_FIXTURE`
> [Introduced](https://github.com/catchorg/Catch2/pull/2885) in Catch2 3.7.0
`TEST_CASE_PERSISTENT_FIXTURE` behaves in the same way as
[TEST_CASE_METHOD](#1-test_case_method) except that there will only be
one instance created throughout the entire run of a test case. To
demonstrate this have a look at the following example:
```cpp
class ClassWithExpensiveSetup {
public:
ClassWithExpensiveSetup() {
// expensive construction
std::this_thread::sleep_for( std::chrono::seconds( 2 ) );
}
~ClassWithExpensiveSetup() noexcept {
// expensive destruction
std::this_thread::sleep_for( std::chrono::seconds( 1 ) );
}
int getInt() const { return 42; }
};
struct MyFixture {
mutable int myInt = 0;
ClassWithExpensiveSetup expensive;
};
TEST_CASE_PERSISTENT_FIXTURE( MyFixture, "Tests with MyFixture" ) {
const int val = myInt++;
SECTION( "First partial run" ) {
const auto otherValue = expensive.getInt();
REQUIRE( val == 0 );
REQUIRE( otherValue == 42 );
}
SECTION( "Second partial run" ) { REQUIRE( val == 1 ); }
}
```
This example demonstates two possible use-cases of this fixture type:
1. Improve test run times by reducing the amount of expensive and
redundant setup and tear-down required.
2. Reusing results from the previous partial run, in the current
partial run.
This test case will be executed twice as there are two leaf sections.
On the first run `val` will be `0` and on the second run `val` will be
`1`. This demonstrates that we were able to use the results of the
previous partial run in subsequent partial runs.
Additionally, we are simulating an expensive object using
`std::this_thread::sleep_for`, but real world use-cases could be:
1. Creating a D3D12/Vulkan device
2. Connecting to a database
3. Loading a file.
The fixture object (`MyFixture`) will be constructed just before the
test case begins, and it will be destroyed just after the test case
ends. Therefore, this expensive object will only be created and
destroyed once during the execution of this test case. If we had used
`TEST_CASE_METHOD`, `MyFixture` would have been created and destroyed
twice during the execution of this test case.
NOTE: The member function which runs the test case is `const`. Therefore
if you want to mutate any member of the fixture it must be marked as
`mutable` as shown in this example. This is to make it clear that
the initial state of the fixture is intended to mutate during the
execution of the test case.
## Templated test fixtures
Catch2 also provides `TEMPLATE_TEST_CASE_METHOD` and
`TEMPLATE_PRODUCT_TEST_CASE_METHOD` that can be used together
with templated fixtures and templated template fixtures to perform
tests for multiple different types. Unlike `TEST_CASE_METHOD`,
`TEMPLATE_TEST_CASE_METHOD` and `TEMPLATE_PRODUCT_TEST_CASE_METHOD` do
require the tag specification to be non-empty, as it is followed by
further macro arguments.
Also note that, because of limitations of the C++ preprocessor, if you
want to specify a type with multiple template parameters, you need to
enclose it in parentheses, e.g. `std::map<int, std::string>` needs to be
passed as `(std::map<int, std::string>)`.
In the case of `TEMPLATE_PRODUCT_TEST_CASE_METHOD`, if a member of the
type list should consist of more than single type, it needs to be enclosed
in another pair of parentheses, e.g. `(std::map, std::pair)` and
`((int, float), (char, double))`.
Example:
```cpp
template< typename T >
struct Template_Fixture {
Template_Fixture(): m_a(1) {}
T m_a;
};
TEMPLATE_TEST_CASE_METHOD(Template_Fixture,
"A TEMPLATE_TEST_CASE_METHOD based test run that succeeds",
"[class][template]",
int, float, double) {
REQUIRE( Template_Fixture<TestType>::m_a == 1 );
}
template<typename T>
struct Template_Template_Fixture {
Template_Template_Fixture() {}
T m_a;
};
template<typename T>
struct Foo_class {
size_t size() {
return 0;
}
};
TEMPLATE_PRODUCT_TEST_CASE_METHOD(Template_Template_Fixture,
"A TEMPLATE_PRODUCT_TEST_CASE_METHOD based test succeeds",
"[class][template]",
(Foo_class, std::vector),
int) {
REQUIRE( Template_Template_Fixture<TestType>::m_a.size() == 0 );
}
```
_While there is an upper limit on the number of types you can specify
in single `TEMPLATE_TEST_CASE_METHOD` or `TEMPLATE_PRODUCT_TEST_CASE_METHOD`,
the limit is very high and should not be encountered in practice._
## Signature-based parameterised test fixtures
> [Introduced](https://github.com/catchorg/Catch2/issues/1609) in Catch2 2.8.0.
Catch2 also provides `TEMPLATE_TEST_CASE_METHOD_SIG` and `TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG` to support
fixtures using non-type template parameters. These test cases work similar to `TEMPLATE_TEST_CASE_METHOD` and `TEMPLATE_PRODUCT_TEST_CASE_METHOD`,
with additional positional argument for [signature](test-cases-and-sections.md#signature-based-parametrised-test-cases).
Example:
```cpp
template <int V>
struct Nttp_Fixture{
int value = V;
};
TEMPLATE_TEST_CASE_METHOD_SIG(
Nttp_Fixture,
"A TEMPLATE_TEST_CASE_METHOD_SIG based test run that succeeds",
"[class][template][nttp]",
((int V), V),
1, 3, 6) {
REQUIRE(Nttp_Fixture<V>::value > 0);
}
template<typename T>
struct Template_Fixture_2 {
Template_Fixture_2() {}
T m_a;
};
template< typename T, size_t V>
struct Template_Foo_2 {
size_t size() { return V; }
};
TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG(
Template_Fixture_2,
"A TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG based test run that succeeds",
"[class][template][product][nttp]",
((typename T, size_t S), T, S),
(std::array, Template_Foo_2),
((int,2), (float,6))) {
REQUIRE(Template_Fixture_2<TestType>{}.m_a.size() >= 2);
}
```
## Template fixtures with types specified in template type lists
Catch2 also provides `TEMPLATE_LIST_TEST_CASE_METHOD` to support template fixtures with types specified in
template type lists like `std::tuple`, `boost::mpl::list` or `boost::mp11::mp_list`. This test case works the same as `TEMPLATE_TEST_CASE_METHOD`,
only difference is the source of types. This allows you to reuse the template type list in multiple test cases.
Example:
```cpp
using MyTypes = std::tuple<int, char, double>;
TEMPLATE_LIST_TEST_CASE_METHOD(Template_Fixture,
"Template test case method with test types specified inside std::tuple",
"[class][template][list]",
MyTypes) {
REQUIRE( Template_Fixture<TestType>::m_a == 1 );
}
```
---
[Home](Readme.md#top)

View File

@ -0,0 +1,132 @@
<a id="top"></a>
# String conversions
**Contents**<br>
[operator << overload for std::ostream](#operator--overload-for-stdostream)<br>
[Catch::StringMaker specialisation](#catchstringmaker-specialisation)<br>
[Catch::is_range specialisation](#catchis_range-specialisation)<br>
[Exceptions](#exceptions)<br>
[Enums](#enums)<br>
[Floating point precision](#floating-point-precision)<br>
Catch needs to be able to convert types you use in assertions and logging expressions into strings (for logging and reporting purposes).
Most built-in or std types are supported out of the box but there are two ways that you can tell Catch how to convert your own types (or other, third-party types) into strings.
## operator << overload for std::ostream
This is the standard way of providing string conversions in C++ - and the chances are you may already provide this for your own purposes. If you're not familiar with this idiom it involves writing a free function of the form:
```cpp
std::ostream& operator << ( std::ostream& os, T const& value ) {
os << convertMyTypeToString( value );
return os;
}
```
(where ```T``` is your type and ```convertMyTypeToString``` is where you'll write whatever code is necessary to make your type printable - it doesn't have to be in another function).
You should put this function in the same namespace as your type, or the global namespace, and have it declared before including Catch's header.
## Catch::StringMaker specialisation
If you don't want to provide an ```operator <<``` overload, or you want to convert your type differently for testing purposes, you can provide a specialization for `Catch::StringMaker<T>`:
```cpp
namespace Catch {
template<>
struct StringMaker<T> {
static std::string convert( T const& value ) {
return convertMyTypeToString( value );
}
};
}
```
## Catch::is_range specialisation
As a fallback, Catch attempts to detect if the type can be iterated
(`begin(T)` and `end(T)` are valid) and if it can be, it is stringified
as a range. For certain types this can lead to infinite recursion, so
it can be disabled by specializing `Catch::is_range` like so:
```cpp
namespace Catch {
template<>
struct is_range<T> {
static const bool value = false;
};
}
```
## Exceptions
By default all exceptions deriving from `std::exception` will be translated to strings by calling the `what()` method. For exception types that do not derive from `std::exception` - or if `what()` does not return a suitable string - use `CATCH_TRANSLATE_EXCEPTION`. This defines a function that takes your exception type, by reference, and returns a string. It can appear anywhere in the code - it doesn't have to be in the same translation unit. For example:
```cpp
CATCH_TRANSLATE_EXCEPTION( MyType const& ex ) {
return ex.message();
}
```
## Enums
> Introduced in Catch2 2.8.0.
Enums that already have a `<<` overload for `std::ostream` will convert to strings as expected.
If you only need to convert enums to strings for test reporting purposes you can provide a `StringMaker` specialisations as any other type.
However, as a convenience, Catch provides the `REGISTER_ENUM` helper macro that will generate the `StringMaker` specialisation for you with minimal code.
Simply provide it the (qualified) enum name, followed by all the enum values, and you're done!
E.g.
```cpp
enum class Fruits { Banana, Apple, Mango };
CATCH_REGISTER_ENUM( Fruits, Fruits::Banana, Fruits::Apple, Fruits::Mango )
TEST_CASE() {
REQUIRE( Fruits::Mango == Fruits::Apple );
}
```
... or if the enum is in a namespace:
```cpp
namespace Bikeshed {
enum class Colours { Red, Green, Blue };
}
// Important!: This macro must appear at top level scope - not inside a namespace
// You can fully qualify the names, or use a using if you prefer
CATCH_REGISTER_ENUM( Bikeshed::Colours,
Bikeshed::Colours::Red,
Bikeshed::Colours::Green,
Bikeshed::Colours::Blue )
TEST_CASE() {
REQUIRE( Bikeshed::Colours::Red == Bikeshed::Colours::Blue );
}
```
## Floating point precision
> [Introduced](https://github.com/catchorg/Catch2/issues/1614) in Catch2 2.8.0.
Catch provides a built-in `StringMaker` specialization for both `float`
and `double`. By default, it uses what we think is a reasonable precision,
but you can customize it by modifying the `precision` static variable
inside the `StringMaker` specialization, like so:
```cpp
Catch::StringMaker<float>::precision = 15;
const float testFloat1 = 1.12345678901234567899f;
const float testFloat2 = 1.12345678991234567899f;
REQUIRE(testFloat1 == testFloat2);
```
This assertion will fail and print out the `testFloat1` and `testFloat2`
to 15 decimal places.
---
[Home](Readme.md#top)

View File

@ -0,0 +1,228 @@
<a id="top"></a>
# Tutorial
**Contents**<br>
[Getting Catch2](#getting-catch2)<br>
[Writing tests](#writing-tests)<br>
[Test cases and sections](#test-cases-and-sections)<br>
[BDD style testing](#bdd-style-testing)<br>
[Data and Type driven tests](#data-and-type-driven-tests)<br>
[Next steps](#next-steps)<br>
## Getting Catch2
Ideally you should be using Catch2 through its [CMake integration](cmake-integration.md#top).
Catch2 also provides pkg-config files and two file (header + cpp)
distribution, but this documentation will assume you are using CMake. If
you are using the two file distribution instead, remember to replace
the included header with `catch_amalgamated.hpp` ([step by step instructions](migrate-v2-to-v3.md#how-to-migrate-projects-from-v2-to-v3)).
## Writing tests
Let's start with a really simple example ([code](../examples/010-TestCase.cpp)). Say you have written a function to calculate factorials and now you want to test it (let's leave aside TDD for now).
```c++
unsigned int Factorial( unsigned int number ) {
return number <= 1 ? number : Factorial(number-1)*number;
}
```
```c++
#include <catch2/catch_test_macros.hpp>
unsigned int Factorial( unsigned int number ) {
return number <= 1 ? number : Factorial(number-1)*number;
}
TEST_CASE( "Factorials are computed", "[factorial]" ) {
REQUIRE( Factorial(1) == 1 );
REQUIRE( Factorial(2) == 2 );
REQUIRE( Factorial(3) == 6 );
REQUIRE( Factorial(10) == 3628800 );
}
```
This will compile to a complete executable which responds to [command line arguments](command-line.md#top). If you just run it with no arguments it will execute all test cases (in this case there is just one), report any failures, report a summary of how many tests passed and failed and return the number of failed tests (useful for if you just want a yes/ no answer to: "did it work").
Anyway, as the tests above as written will pass, but there is a bug.
The problem is that `Factorial(0)` should return 1 (due to [its
definition](https://en.wikipedia.org/wiki/Factorial#Factorial_of_zero)).
Let's add that as an assertion to the test case:
```c++
TEST_CASE( "Factorials are computed", "[factorial]" ) {
REQUIRE( Factorial(0) == 1 );
REQUIRE( Factorial(1) == 1 );
REQUIRE( Factorial(2) == 2 );
REQUIRE( Factorial(3) == 6 );
REQUIRE( Factorial(10) == 3628800 );
}
```
After another compile & run cycle, we will see a test failure. The output
will look something like:
```
Example.cpp:9: FAILED:
REQUIRE( Factorial(0) == 1 )
with expansion:
0 == 1
```
Note that the output contains both the original expression,
`REQUIRE( Factorial(0) == 1 )` and the actual value returned by the call
to the `Factorial` function: `0`.
We can fix this bug by slightly modifying the `Factorial` function to:
```c++
unsigned int Factorial( unsigned int number ) {
return number > 1 ? Factorial(number-1)*number : 1;
}
```
### What did we do here?
Although this was a simple test it's been enough to demonstrate a few
things about how Catch2 is used. Let's take a moment to consider those
before we move on.
* We introduce test cases with the `TEST_CASE` macro. This macro takes
one or two string arguments - a free form test name and, optionally,
one or more tags (for more see [Test cases and Sections](#test-cases-and-sections)).
* The test automatically self-registers with the test runner, and user
does not have do anything more to ensure that it is picked up by the test
framework. _Note that you can run specific test, or set of tests,
through the [command line](command-line.md#top)._
* The individual test assertions are written using the `REQUIRE` macro.
It accepts a boolean expression, and uses expression templates to
internally decompose it, so that it can be individually stringified
on test failure.
On the last point, note that there are more testing macros available,
because not all useful checks can be expressed as a simple boolean
expression. As an example, checking that an expression throws an exception
is done with the `REQUIRE_THROWS` macro. More on that later.
## Test cases and sections
Like most test frameworks, Catch2 supports a class-based fixture mechanism,
where individual tests are methods on class and setup/teardown can be
done in constructor/destructor of the type.
However, their use in Catch2 is rare, because idiomatic Catch2 tests
instead use _sections_ to share setup and teardown code between test code.
This is best explained through an example ([code](../examples/100-Fix-Section.cpp)):
```c++
TEST_CASE( "vectors can be sized and resized", "[vector]" ) {
// This setup will be done 4 times in total, once for each section
std::vector<int> v( 5 );
REQUIRE( v.size() == 5 );
REQUIRE( v.capacity() >= 5 );
SECTION( "resizing bigger changes size and capacity" ) {
v.resize( 10 );
REQUIRE( v.size() == 10 );
REQUIRE( v.capacity() >= 10 );
}
SECTION( "resizing smaller changes size but not capacity" ) {
v.resize( 0 );
REQUIRE( v.size() == 0 );
REQUIRE( v.capacity() >= 5 );
}
SECTION( "reserving bigger changes capacity but not size" ) {
v.reserve( 10 );
REQUIRE( v.size() == 5 );
REQUIRE( v.capacity() >= 10 );
}
SECTION( "reserving smaller does not change size or capacity" ) {
v.reserve( 0 );
REQUIRE( v.size() == 5 );
REQUIRE( v.capacity() >= 5 );
}
}
```
For each `SECTION` the `TEST_CASE` is **executed from the start**. This means
that each section is entered with a freshly constructed vector `v`, that
we know has size 5 and capacity at least 5, because the two assertions
are also checked before the section is entered. This behaviour may not be
ideal for tests where setup is expensive. Each run through a test case will
execute one, and only one, leaf section.
Section can also be nested, in which case the parent section can be
entered multiple times, once for each leaf section. Nested sections are
most useful when you have multiple tests that share part of the set up.
To continue on the vector example above, you could add a check that
`std::vector::reserve` does not remove unused excess capacity, like this:
```cpp
SECTION( "reserving bigger changes capacity but not size" ) {
v.reserve( 10 );
REQUIRE( v.size() == 5 );
REQUIRE( v.capacity() >= 10 );
SECTION( "reserving down unused capacity does not change capacity" ) {
v.reserve( 7 );
REQUIRE( v.size() == 5 );
REQUIRE( v.capacity() >= 10 );
}
}
```
Another way to look at sections is that they are a way to define a tree
of paths through the test. Each section represents a node, and the final
tree is walked in depth-first manner, with each path only visiting only
one leaf node.
There is no practical limit on nesting sections, as long as your compiler
can handle them, but keep in mind that overly nested sections can become
unreadable. From experience, having section nest more than 3 levels is
usually very hard to follow and not worth the removed duplication.
## BDD style testing
Catch2 also provides some basic support for BDD-style testing. There are
macro aliases for `TEST_CASE` and `SECTIONS` that you can use so that
the resulting tests read as BDD spec. `SCENARIO` acts as a `TEST_CASE`
with "Scenario: " name prefix. Then there are `GIVEN`, `WHEN`, `THEN`
(and their variants with `AND_` prefix), which act as a `SECTION`,
similarly prefixed with the macro name.
For more details on the macros look at the [test cases and
sections](test-cases-and-sections.md#top) part of the reference docs,
or at the [vector example done with BDD macros](../examples/120-Bdd-ScenarioGivenWhenThen.cpp).
## Data and Type driven tests
Test cases in Catch2 can also be driven by types, input data, or both
at the same time.
For more details look into the Catch2 reference, either at the
[type parametrized test cases](test-cases-and-sections.md#type-parametrised-test-cases),
or [data generators](generators.md#top).
## Next steps
This page is a brief introduction to get you up and running with Catch2,
and to show the basic features of Catch2. The features mentioned here
can get you quite far, but there are many more. However, you can read
about these as you go, in the ever-growing [reference section](Readme.md#top)
of the documentation.
---
[Home](Readme.md#top)

View File

@ -0,0 +1,100 @@
<a id="top"></a>
# Best practices and other tips on using Catch2
## Running tests
Your tests should be run in a manner roughly equivalent with:
```
./tests --order rand --warn NoAssertions
```
Notice that all the tests are run in a large batch, their relative order
is randomized, and that you ask Catch2 to fail test whose leaf-path
does not contain an assertion.
The reason I recommend running all your tests in the same process is that
this exposes your tests to interference from their runs. This can be both
positive interference, where the changes in global state from previous
test allow later tests to pass, but also negative interference, where
changes in global state from previous test causes later tests to fail.
In my experience, interference, especially destructive interference,
usually comes from errors in the code under test, rather than the tests
themselves. This means that by allowing interference to happen, our tests
can find these issues. Obviously, to shake out interference coming from
different orderings of tests, the test order also need to be shuffled
between runs.
However, running all tests in a single batch eventually becomes impractical
as they will take too long to run, and you will want to run your tests
in parallel.
<a id="parallel-tests"></a>
## Running tests in parallel
There are multiple ways of running tests in parallel, with various level
of structure. If you are using CMake and CTest, then we provide a helper
function [`catch_discover_tests`](cmake-integration.md#automatic-test-registration)
that registers each Catch2 `TEST_CASE` as a single CTest test, which
is then run in a separate process. This is an easy way to set up parallel
tests if you are already using CMake & CTest to run your tests, but you
will lose the advantage of running tests in batches.
Catch2 also supports [splitting tests in a binary into multiple
shards](command-line.md#test-sharding). This can be used by any test
runner to run batches of tests in parallel. Do note that when selecting
on the number of shards, you should have more shards than there are cores,
to avoid issues with long-running tests getting accidentally grouped in
the same shard, and causing long-tailed execution time.
**Note that naively composing sharding and random ordering of tests will break.**
Invoking Catch2 test executable like this
```text
./tests --order rand --shard-index 0 --shard-count 3
./tests --order rand --shard-index 1 --shard-count 3
./tests --order rand --shard-index 2 --shard-count 3
```
does not guarantee covering all tests inside the executable, because
each invocation will have its own random seed, thus it will have its own
random order of tests and thus the partitioning of tests into shards will
be different as well.
To do this properly, you need the individual shards to share the random
seed, e.g.
```text
./tests --order rand --shard-index 0 --shard-count 3 --rng-seed 0xBEEF
./tests --order rand --shard-index 1 --shard-count 3 --rng-seed 0xBEEF
./tests --order rand --shard-index 2 --shard-count 3 --rng-seed 0xBEEF
```
Catch2 actually provides a helper to automatically register multiple shards
as CTest tests, with shared random seed that changes each CTest invocation.
For details look at the documentation of
[`CatchShardTests.cmake` CMake script](cmake-integration.md#catchshardtestscmake).
## Organizing tests into binaries
Both overly large and overly small test binaries can cause issues. Overly
large test binaries have to be recompiled and relinked often, and the
link times are usually also long. Overly small test binaries in turn pay
significant overhead from linking against Catch2 more often per compiled
test case, and also make it hard/impossible to run tests in batches.
Because there is no hard and fast rule for the right size of a test binary,
I recommend having 1:1 correspondence between libraries in project and test
binaries. (At least if it is possible, in some cases it is not.) Having
a test binary for each library in project keeps related tests together,
and makes tests easy to navigate by reflecting the project's organizational
structure.
---
[Home](Readme.md#top)

View File

@ -0,0 +1,59 @@
<a id="top"></a>
# Why do we need yet another C++ test framework?
Good question. For C++ there are quite a number of established frameworks,
including (but not limited to),
[Google Test](http://code.google.com/p/googletest/),
[Boost.Test](http://www.boost.org/doc/libs/1_49_0/libs/test/doc/html/index.html),
[CppUnit](http://sourceforge.net/apps/mediawiki/cppunit/index.php?title=Main_Page),
[Cute](http://www.cute-test.com), and
[many, many more](http://en.wikipedia.org/wiki/List_of_unit_testing_frameworks#C.2B.2B).
So what does Catch2 bring to the party that differentiates it from these? Apart from the catchy name, of course.
## Key Features
* Quick and easy to get started. Just download two files, add them into your project and you're away.
* No external dependencies. As long as you can compile C++14 and have the C++ standard library available.
* Write test cases as, self-registering, functions (or methods, if you prefer).
* Divide test cases into sections, each of which is run in isolation (eliminates the need for fixtures).
* Use BDD-style Given-When-Then sections as well as traditional unit test cases.
* Only one core assertion macro for comparisons. Standard C/C++ operators are used for the comparison - yet the full expression is decomposed and lhs and rhs values are logged.
* Tests are named using free-form strings - no more couching names in legal identifiers.
## Other core features
* Tests can be tagged for easily running ad-hoc groups of tests.
* Failures can (optionally) break into the debugger on common platforms.
* Output is through modular reporter objects. Basic textual and XML reporters are included. Custom reporters can easily be added.
* JUnit xml output is supported for integration with third-party tools, such as CI servers.
* A default main() function is provided, but you can supply your own for complete control (e.g. integration into your own test runner GUI).
* A command line parser is provided and can still be used if you choose to provide your own main() function.
* Alternative assertion macro(s) report failures but don't abort the test case
* Good set of facilities for floating point comparisons (`Catch::Approx` and full set of matchers)
* Internal and friendly macros are isolated so name clashes can be managed
* Data generators (data driven test support)
* Hamcrest-style Matchers for testing complex properties
* Microbenchmarking support
## Who else is using Catch2?
A whole lot of people. According to [the 2022 JetBrains C++ ecosystem survey](https://www.jetbrains.com/lp/devecosystem-2022/cpp/#Which-unit-testing-frameworks-do-you-regularly-use),
about 12% of C++ programmers use Catch2 for unit testing, making it the
second most popular unit testing framework.
You can also take a look at the (incomplete) list of [open source projects](opensource-users.md#top)
or the (very incomplete) list of [commercial users of Catch2](commercial-users.md#top)
for some idea on who else also uses Catch2.
---
See the [tutorial](tutorial.md#top) to get more of a taste of using
Catch2 in practice.
---
[Home](Readme.md#top)

View File

@ -0,0 +1,41 @@
// Copyright Catch2 Authors
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE.txt or copy at
// https://www.boost.org/LICENSE_1_0.txt)
// SPDX-License-Identifier: BSL-1.0
// 010-TestCase.cpp
// And write tests in the same file:
#include <catch2/catch_test_macros.hpp>
static int Factorial( int number ) {
return number <= 1 ? number : Factorial( number - 1 ) * number; // fail
// return number <= 1 ? 1 : Factorial( number - 1 ) * number; // pass
}
TEST_CASE( "Factorial of 0 is 1 (fail)", "[single-file]" ) {
REQUIRE( Factorial(0) == 1 );
}
TEST_CASE( "Factorials of 1 and higher are computed (pass)", "[single-file]" ) {
REQUIRE( Factorial(1) == 1 );
REQUIRE( Factorial(2) == 2 );
REQUIRE( Factorial(3) == 6 );
REQUIRE( Factorial(10) == 3628800 );
}
// Compile & run:
// - g++ -std=c++14 -Wall -I$(CATCH_SINGLE_INCLUDE) -o 010-TestCase 010-TestCase.cpp && 010-TestCase --success
// - cl -EHsc -I%CATCH_SINGLE_INCLUDE% 010-TestCase.cpp && 010-TestCase --success
// Expected compact output (all assertions):
//
// prompt> 010-TestCase --reporter compact --success
// 010-TestCase.cpp:14: failed: Factorial(0) == 1 for: 0 == 1
// 010-TestCase.cpp:18: passed: Factorial(1) == 1 for: 1 == 1
// 010-TestCase.cpp:19: passed: Factorial(2) == 2 for: 2 == 2
// 010-TestCase.cpp:20: passed: Factorial(3) == 6 for: 6 == 6
// 010-TestCase.cpp:21: passed: Factorial(10) == 3628800 for: 3628800 (0x375f00) == 3628800 (0x375f00)
// Failed 1 test case, failed 1 assertion.

View File

@ -0,0 +1,37 @@
// Copyright Catch2 Authors
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE.txt or copy at
// https://www.boost.org/LICENSE_1_0.txt)
// SPDX-License-Identifier: BSL-1.0
// 020-TestCase-1.cpp
#include <catch2/catch_test_macros.hpp>
TEST_CASE( "1: All test cases reside in other .cpp files (empty)", "[multi-file:1]" ) {
}
// ^^^
// Normally no TEST_CASEs in this file.
// Here just to show there are two source files via option --list-tests.
// Compile & run:
// - g++ -std=c++14 -Wall -I$(CATCH_SINGLE_INCLUDE) -c 020-TestCase-1.cpp
// - g++ -std=c++14 -Wall -I$(CATCH_SINGLE_INCLUDE) -o 020-TestCase TestCase-1.o 020-TestCase-2.cpp && 020-TestCase --success
//
// - cl -EHsc -I%CATCH_SINGLE_INCLUDE% -c 020-TestCase-1.cpp
// - cl -EHsc -I%CATCH_SINGLE_INCLUDE% -Fe020-TestCase.exe 020-TestCase-1.obj 020-TestCase-2.cpp && 020-TestCase --success
// Expected test case listing:
//
// prompt> 020-TestCase --list-tests *
// Matching test cases:
// 1: All test cases reside in other .cpp files (empty)
// [multi-file:1]
// 2: Factorial of 0 is computed (fail)
// [multi-file:2]
// 2: Factorials of 1 and higher are computed (pass)
// [multi-file:2]
// 3 matching test cases

View File

@ -0,0 +1,41 @@
// Copyright Catch2 Authors
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE.txt or copy at
// https://www.boost.org/LICENSE_1_0.txt)
// SPDX-License-Identifier: BSL-1.0
// 020-TestCase-2.cpp
// main() provided by Catch in file 020-TestCase-1.cpp.
#include <catch2/catch_test_macros.hpp>
static int Factorial( int number ) {
return number <= 1 ? number : Factorial( number - 1 ) * number; // fail
// return number <= 1 ? 1 : Factorial( number - 1 ) * number; // pass
}
TEST_CASE( "2: Factorial of 0 is 1 (fail)", "[multi-file:2]" ) {
REQUIRE( Factorial(0) == 1 );
}
TEST_CASE( "2: Factorials of 1 and higher are computed (pass)", "[multi-file:2]" ) {
REQUIRE( Factorial(1) == 1 );
REQUIRE( Factorial(2) == 2 );
REQUIRE( Factorial(3) == 6 );
REQUIRE( Factorial(10) == 3628800 );
}
// Compile: see 020-TestCase-1.cpp
// Expected compact output (all assertions):
//
// prompt> 020-TestCase --reporter compact --success
// 020-TestCase-2.cpp:13: failed: Factorial(0) == 1 for: 0 == 1
// 020-TestCase-2.cpp:17: passed: Factorial(1) == 1 for: 1 == 1
// 020-TestCase-2.cpp:18: passed: Factorial(2) == 2 for: 2 == 2
// 020-TestCase-2.cpp:19: passed: Factorial(3) == 6 for: 6 == 6
// 020-TestCase-2.cpp:20: passed: Factorial(10) == 3628800 for: 3628800 (0x375f00) == 3628800 (0x375f00)
// Failed 1 test case, failed 1 assertion.

View File

@ -0,0 +1,82 @@
// Copyright Catch2 Authors
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE.txt or copy at
// https://www.boost.org/LICENSE_1_0.txt)
// SPDX-License-Identifier: BSL-1.0
// 030-Asn-Require-Check.cpp
// Catch has two natural expression assertion macro's:
// - REQUIRE() stops at first failure.
// - CHECK() continues after failure.
// There are two variants to support decomposing negated expressions:
// - REQUIRE_FALSE() stops at first failure.
// - CHECK_FALSE() continues after failure.
// main() provided by linkage to Catch2WithMain
#include <catch2/catch_test_macros.hpp>
static std::string one() {
return "1";
}
TEST_CASE( "Assert that something is true (pass)", "[require]" ) {
REQUIRE( one() == "1" );
}
TEST_CASE( "Assert that something is true (fail)", "[require]" ) {
REQUIRE( one() == "x" );
}
TEST_CASE( "Assert that something is true (stop at first failure)", "[require]" ) {
WARN( "REQUIRE stops at first failure:" );
REQUIRE( one() == "x" );
REQUIRE( one() == "1" );
}
TEST_CASE( "Assert that something is true (continue after failure)", "[check]" ) {
WARN( "CHECK continues after failure:" );
CHECK( one() == "x" );
REQUIRE( one() == "1" );
}
TEST_CASE( "Assert that something is false (stops at first failure)", "[require-false]" ) {
WARN( "REQUIRE_FALSE stops at first failure:" );
REQUIRE_FALSE( one() == "1" );
REQUIRE_FALSE( one() != "1" );
}
TEST_CASE( "Assert that something is false (continue after failure)", "[check-false]" ) {
WARN( "CHECK_FALSE continues after failure:" );
CHECK_FALSE( one() == "1" );
REQUIRE_FALSE( one() != "1" );
}
// Compile & run:
// - g++ -std=c++14 -Wall -I$(CATCH_SINGLE_INCLUDE) -o 030-Asn-Require-Check 030-Asn-Require-Check.cpp && 030-Asn-Require-Check --success
// - cl -EHsc -I%CATCH_SINGLE_INCLUDE% 030-Asn-Require-Check.cpp && 030-Asn-Require-Check --success
// Expected compact output (all assertions):
//
// prompt> 030-Asn-Require-Check.exe --reporter compact --success
// 030-Asn-Require-Check.cpp:20: passed: one() == "1" for: "1" == "1"
// 030-Asn-Require-Check.cpp:24: failed: one() == "x" for: "1" == "x"
// 030-Asn-Require-Check.cpp:28: warning: 'REQUIRE stops at first failure:'
// 030-Asn-Require-Check.cpp:30: failed: one() == "x" for: "1" == "x"
// 030-Asn-Require-Check.cpp:35: warning: 'CHECK continues after failure:'
// 030-Asn-Require-Check.cpp:37: failed: one() == "x" for: "1" == "x"
// 030-Asn-Require-Check.cpp:38: passed: one() == "1" for: "1" == "1"
// 030-Asn-Require-Check.cpp:42: warning: 'REQUIRE_FALSE stops at first failure:'
// 030-Asn-Require-Check.cpp:44: failed: !(one() == "1") for: !("1" == "1")
// 030-Asn-Require-Check.cpp:49: warning: 'CHECK_FALSE continues after failure:'
// 030-Asn-Require-Check.cpp:51: failed: !(one() == "1") for: !("1" == "1")
// 030-Asn-Require-Check.cpp:52: passed: !(one() != "1") for: !("1" != "1")
// Failed 5 test cases, failed 5 assertions.

View File

@ -0,0 +1,78 @@
// Copyright Catch2 Authors
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE.txt or copy at
// https://www.boost.org/LICENSE_1_0.txt)
// SPDX-License-Identifier: BSL-1.0
// 100-Fix-Section.cpp
// Catch has two ways to express fixtures:
// - Sections (this file)
// - Traditional class-based fixtures
// main() provided by linkage to Catch2WithMain
#include <catch2/catch_test_macros.hpp>
#include <vector>
TEST_CASE( "vectors can be sized and resized", "[vector]" ) {
// For each section, vector v is anew:
std::vector<int> v( 5 );
REQUIRE( v.size() == 5 );
REQUIRE( v.capacity() >= 5 );
SECTION( "resizing bigger changes size and capacity" ) {
v.resize( 10 );
REQUIRE( v.size() == 10 );
REQUIRE( v.capacity() >= 10 );
}
SECTION( "resizing smaller changes size but not capacity" ) {
v.resize( 0 );
REQUIRE( v.size() == 0 );
REQUIRE( v.capacity() >= 5 );
}
SECTION( "reserving bigger changes capacity but not size" ) {
v.reserve( 10 );
REQUIRE( v.size() == 5 );
REQUIRE( v.capacity() >= 10 );
}
SECTION( "reserving smaller does not change size or capacity" ) {
v.reserve( 0 );
REQUIRE( v.size() == 5 );
REQUIRE( v.capacity() >= 5 );
}
}
// Compile & run:
// - g++ -std=c++14 -Wall -I$(CATCH_SINGLE_INCLUDE) -o 100-Fix-Section 100-Fix-Section.cpp && 100-Fix-Section --success
// - cl -EHsc -I%CATCH_SINGLE_INCLUDE% 100-Fix-Section.cpp && 100-Fix-Section --success
// Expected compact output (all assertions):
//
// prompt> 100-Fix-Section.exe --reporter compact --success
// 100-Fix-Section.cpp:17: passed: v.size() == 5 for: 5 == 5
// 100-Fix-Section.cpp:18: passed: v.capacity() >= 5 for: 5 >= 5
// 100-Fix-Section.cpp:23: passed: v.size() == 10 for: 10 == 10
// 100-Fix-Section.cpp:24: passed: v.capacity() >= 10 for: 10 >= 10
// 100-Fix-Section.cpp:17: passed: v.size() == 5 for: 5 == 5
// 100-Fix-Section.cpp:18: passed: v.capacity() >= 5 for: 5 >= 5
// 100-Fix-Section.cpp:29: passed: v.size() == 0 for: 0 == 0
// 100-Fix-Section.cpp:30: passed: v.capacity() >= 5 for: 5 >= 5
// 100-Fix-Section.cpp:17: passed: v.size() == 5 for: 5 == 5
// 100-Fix-Section.cpp:18: passed: v.capacity() >= 5 for: 5 >= 5
// 100-Fix-Section.cpp:35: passed: v.size() == 5 for: 5 == 5
// 100-Fix-Section.cpp:36: passed: v.capacity() >= 10 for: 10 >= 10
// 100-Fix-Section.cpp:17: passed: v.size() == 5 for: 5 == 5
// 100-Fix-Section.cpp:18: passed: v.capacity() >= 5 for: 5 >= 5
// 100-Fix-Section.cpp:41: passed: v.size() == 5 for: 5 == 5
// 100-Fix-Section.cpp:42: passed: v.capacity() >= 5 for: 5 >= 5
// Passed 1 test case with 16 assertions.

View File

@ -0,0 +1,74 @@
// Copyright Catch2 Authors
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE.txt or copy at
// https://www.boost.org/LICENSE_1_0.txt)
// SPDX-License-Identifier: BSL-1.0
// 110-Fix-ClassFixture.cpp
// Catch has two ways to express fixtures:
// - Sections
// - Traditional class-based fixtures (this file)
// main() provided by linkage to Catch2WithMain
#include <catch2/catch_test_macros.hpp>
class DBConnection
{
public:
static DBConnection createConnection( std::string const & /*dbName*/ ) {
return DBConnection();
}
bool executeSQL( std::string const & /*query*/, int const /*id*/, std::string const & arg ) {
if ( arg.length() == 0 ) {
throw std::logic_error("empty SQL query argument");
}
return true; // ok
}
};
class UniqueTestsFixture
{
protected:
UniqueTestsFixture()
: conn( DBConnection::createConnection( "myDB" ) )
{}
int getID() {
return ++uniqueID;
}
protected:
DBConnection conn;
private:
static int uniqueID;
};
int UniqueTestsFixture::uniqueID = 0;
TEST_CASE_METHOD( UniqueTestsFixture, "Create Employee/No Name", "[create]" ) {
REQUIRE_THROWS( conn.executeSQL( "INSERT INTO employee (id, name) VALUES (?, ?)", getID(), "") );
}
TEST_CASE_METHOD( UniqueTestsFixture, "Create Employee/Normal", "[create]" ) {
REQUIRE( conn.executeSQL( "INSERT INTO employee (id, name) VALUES (?, ?)", getID(), "Joe Bloggs" ) );
}
// Compile & run:
// - g++ -std=c++14 -Wall -I$(CATCH_SINGLE_INCLUDE) -o 110-Fix-ClassFixture 110-Fix-ClassFixture.cpp && 110-Fix-ClassFixture --success
// - cl -EHsc -I%CATCH_SINGLE_INCLUDE% 110-Fix-ClassFixture.cpp && 110-Fix-ClassFixture --success
//
// Compile with pkg-config:
// - g++ -std=c++14 -Wall $(pkg-config catch2-with-main --cflags) -o 110-Fix-ClassFixture 110-Fix-ClassFixture.cpp $(pkg-config catch2-with-main --libs)
// Expected compact output (all assertions):
//
// prompt> 110-Fix-ClassFixture.exe --reporter compact --success
// 110-Fix-ClassFixture.cpp:47: passed: conn.executeSQL( "INSERT INTO employee (id, name) VALUES (?, ?)", getID(), "")
// 110-Fix-ClassFixture.cpp:51: passed: conn.executeSQL( "INSERT INTO employee (id, name) VALUES (?, ?)", getID(), "Joe Bloggs" ) for: true
// Passed both 2 test cases with 2 assertions.

View File

@ -0,0 +1,74 @@
// Copyright Catch2 Authors
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE.txt or copy at
// https://www.boost.org/LICENSE_1_0.txt)
// SPDX-License-Identifier: BSL-1.0
// Fixture.cpp
// Catch2 has three ways to express fixtures:
// - Sections
// - Traditional class-based fixtures that are created and destroyed on every
// partial run
// - Traditional class-based fixtures that are created at the start of a test
// case and destroyed at the end of a test case (this file)
// main() provided by linkage to Catch2WithMain
#include <catch2/catch_test_macros.hpp>
#include <thread>
class ClassWithExpensiveSetup {
public:
ClassWithExpensiveSetup() {
// Imagine some really expensive set up here.
// e.g.
// setting up a D3D12/Vulkan Device,
// connecting to a database,
// loading a file
// etc etc etc
std::this_thread::sleep_for( std::chrono::seconds( 2 ) );
}
~ClassWithExpensiveSetup() noexcept {
// We can do any clean up of the expensive class in the destructor
// e.g.
// destroy D3D12/Vulkan Device,
// disconnecting from a database,
// release file handle
// etc etc etc
std::this_thread::sleep_for( std::chrono::seconds( 1 ) );
}
int getInt() const { return 42; }
};
struct MyFixture {
// The test case member function is const.
// Therefore we need to mark any member of the fixture
// that needs to mutate as mutable.
mutable int myInt = 0;
ClassWithExpensiveSetup expensive;
};
// Only one object of type MyFixture will be instantiated for the run
// of this test case even though there are two leaf sections.
// This is useful if your test case requires an object that is
// expensive to create and could be reused for each partial run of the
// test case.
TEST_CASE_PERSISTENT_FIXTURE( MyFixture, "Tests with MyFixture" ) {
const int val = myInt++;
SECTION( "First partial run" ) {
const auto otherValue = expensive.getInt();
REQUIRE( val == 0 );
REQUIRE( otherValue == 42 );
}
SECTION( "Second partial run" ) { REQUIRE( val == 1 ); }
}

View File

@ -0,0 +1,81 @@
// Copyright Catch2 Authors
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE.txt or copy at
// https://www.boost.org/LICENSE_1_0.txt)
// SPDX-License-Identifier: BSL-1.0
// 120-Bdd-ScenarioGivenWhenThen.cpp
// main() provided by linkage with Catch2WithMain
#include <catch2/catch_test_macros.hpp>
SCENARIO( "vectors can be sized and resized", "[vector]" ) {
GIVEN( "A vector with some items" ) {
std::vector<int> v( 5 );
REQUIRE( v.size() == 5 );
REQUIRE( v.capacity() >= 5 );
WHEN( "the size is increased" ) {
v.resize( 10 );
THEN( "the size and capacity change" ) {
REQUIRE( v.size() == 10 );
REQUIRE( v.capacity() >= 10 );
}
}
WHEN( "the size is reduced" ) {
v.resize( 0 );
THEN( "the size changes but not capacity" ) {
REQUIRE( v.size() == 0 );
REQUIRE( v.capacity() >= 5 );
}
}
WHEN( "more capacity is reserved" ) {
v.reserve( 10 );
THEN( "the capacity changes but not the size" ) {
REQUIRE( v.size() == 5 );
REQUIRE( v.capacity() >= 10 );
}
}
WHEN( "less capacity is reserved" ) {
v.reserve( 0 );
THEN( "neither size nor capacity are changed" ) {
REQUIRE( v.size() == 5 );
REQUIRE( v.capacity() >= 5 );
}
}
}
}
// Compile & run:
// - g++ -std=c++14 -Wall -I$(CATCH_SINGLE_INCLUDE) -o 120-Bdd-ScenarioGivenWhenThen 120-Bdd-ScenarioGivenWhenThen.cpp && 120-Bdd-ScenarioGivenWhenThen --success
// - cl -EHsc -I%CATCH_SINGLE_INCLUDE% 120-Bdd-ScenarioGivenWhenThen.cpp && 120-Bdd-ScenarioGivenWhenThen --success
// Expected compact output (all assertions):
//
// prompt> 120-Bdd-ScenarioGivenWhenThen.exe --reporter compact --success
// 120-Bdd-ScenarioGivenWhenThen.cpp:12: passed: v.size() == 5 for: 5 == 5
// 120-Bdd-ScenarioGivenWhenThen.cpp:13: passed: v.capacity() >= 5 for: 5 >= 5
// 120-Bdd-ScenarioGivenWhenThen.cpp:19: passed: v.size() == 10 for: 10 == 10
// 120-Bdd-ScenarioGivenWhenThen.cpp:20: passed: v.capacity() >= 10 for: 10 >= 10
// 120-Bdd-ScenarioGivenWhenThen.cpp:12: passed: v.size() == 5 for: 5 == 5
// 120-Bdd-ScenarioGivenWhenThen.cpp:13: passed: v.capacity() >= 5 for: 5 >= 5
// 120-Bdd-ScenarioGivenWhenThen.cpp:27: passed: v.size() == 0 for: 0 == 0
// 120-Bdd-ScenarioGivenWhenThen.cpp:28: passed: v.capacity() >= 5 for: 5 >= 5
// 120-Bdd-ScenarioGivenWhenThen.cpp:12: passed: v.size() == 5 for: 5 == 5
// 120-Bdd-ScenarioGivenWhenThen.cpp:13: passed: v.capacity() >= 5 for: 5 >= 5
// 120-Bdd-ScenarioGivenWhenThen.cpp:35: passed: v.size() == 5 for: 5 == 5
// 120-Bdd-ScenarioGivenWhenThen.cpp:36: passed: v.capacity() >= 10 for: 10 >= 10
// 120-Bdd-ScenarioGivenWhenThen.cpp:12: passed: v.size() == 5 for: 5 == 5
// 120-Bdd-ScenarioGivenWhenThen.cpp:13: passed: v.capacity() >= 5 for: 5 >= 5
// 120-Bdd-ScenarioGivenWhenThen.cpp:43: passed: v.size() == 5 for: 5 == 5
// 120-Bdd-ScenarioGivenWhenThen.cpp:44: passed: v.capacity() >= 5 for: 5 >= 5
// Passed 1 test case with 16 assertions.

Some files were not shown because too many files have changed in this diff Show More