pyEDAA.Reports.Unittesting

pyEDAA/Reports/Unittesting/__init__.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
# ==================================================================================================================== #
#              _____ ____    _        _      ____                       _                                              #
#  _ __  _   _| ____|  _ \  / \      / \    |  _ \ ___ _ __   ___  _ __| |_ ___                                        #
# | '_ \| | | |  _| | | | |/ _ \    / _ \   | |_) / _ \ '_ \ / _ \| '__| __/ __|                                       #
# | |_) | |_| | |___| |_| / ___ \  / ___ \ _|  _ <  __/ |_) | (_) | |  | |_\__ \                                       #
# | .__/ \__, |_____|____/_/   \_\/_/   \_(_)_| \_\___| .__/ \___/|_|   \__|___/                                       #
# |_|    |___/                                        |_|                                                              #
# ==================================================================================================================== #
# Authors:                                                                                                             #
#   Patrick Lehmann                                                                                                    #
#                                                                                                                      #
# License:                                                                                                             #
# ==================================================================================================================== #
# Copyright 2024-2025 Electronic Design Automation Abstraction (EDA²)                                                  #
#                                                                                                                      #
# Licensed under the Apache License, Version 2.0 (the "License");                                                      #
# you may not use this file except in compliance with the License.                                                     #
# You may obtain a copy of the License at                                                                              #
#                                                                                                                      #
#   http://www.apache.org/licenses/LICENSE-2.0                                                                         #
#                                                                                                                      #
# Unless required by applicable law or agreed to in writing, software                                                  #
# distributed under the License is distributed on an "AS IS" BASIS,                                                    #
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.                                             #
# See the License for the specific language governing permissions and                                                  #
# limitations under the License.                                                                                       #
#                                                                                                                      #
# SPDX-License-Identifier: Apache-2.0                                                                                  #
# ==================================================================================================================== #
#
"""
The pyEDAA.Reports.Unittesting package implements a hierarchy of test entities. These are test cases, test suites and a
test summary provided as a class hierarchy. Test cases are the leaf elements in the hierarchy and abstract an
individual test run. Test suites are used to group multiple test cases or other test suites. The root element is a test
summary. When such a summary is stored in a file format like Ant + JUnit4 XML, a file format specific document is
derived from a summary class.

**Data Model**

.. mermaid::

	 graph TD;
		 doc[Document]
		 sum[Summary]
		 ts1[Testsuite]
		 ts2[Testsuite]
		 ts21[Testsuite]
		 tc11[Testcase]
		 tc12[Testcase]
		 tc13[Testcase]
		 tc21[Testcase]
		 tc22[Testcase]
		 tc211[Testcase]
		 tc212[Testcase]
		 tc213[Testcase]

		 doc:::root -.-> sum:::summary
		 sum --> ts1:::suite
		 sum --> ts2:::suite
		 ts2 --> ts21:::suite
		 ts1 --> tc11:::case
		 ts1 --> tc12:::case
		 ts1 --> tc13:::case
		 ts2 --> tc21:::case
		 ts2 --> tc22:::case
		 ts21 --> tc211:::case
		 ts21 --> tc212:::case
		 ts21 --> tc213:::case

		 classDef root fill:#4dc3ff
		 classDef summary fill:#80d4ff
		 classDef suite fill:#b3e6ff
		 classDef case fill:#eeccff
"""
from datetime              import timedelta, datetime
from enum                  import Flag, IntEnum
from pathlib               import Path
from sys                   import version_info
from typing                import Optional as Nullable, Dict, Iterable, Any, Tuple, Generator, Union, List, Generic, TypeVar, Mapping

from pyTooling.Common      import getFullyQualifiedName
from pyTooling.Decorators  import export, readonly
from pyTooling.MetaClasses import ExtendedType, abstractmethod
from pyTooling.Tree        import Node

from pyEDAA.Reports        import ReportException


@export
class UnittestException(ReportException):
	"""Base-exception for all unit test related exceptions."""


@export
class AlreadyInHierarchyException(UnittestException):
	"""
	A unit test exception raised if the element is already part of a hierarchy.

	This exception is caused by an inconsistent data model. Elements added to the hierarchy should be part of the same
	hierarchy should occur only once in the hierarchy.

	.. hint::

	   This is usually caused by a non-None parent reference.
	"""


@export
class DuplicateTestsuiteException(UnittestException):
	"""
	A unit test exception raised on duplicate test suites (by name).

	This exception is raised, if a child test suite with same name already exist in the test suite.

	.. hint::

	   Test suite names need to be unique per parent element (test suite or test summary).
	"""


@export
class DuplicateTestcaseException(UnittestException):
	"""
	A unit test exception raised on duplicate test cases (by name).

	This exception is raised, if a child test case with same name already exist in the test suite.

	.. hint::

	   Test case names need to be unique per parent element (test suite).
	"""


@export
class TestcaseStatus(Flag):
	"""A flag enumeration describing the status of a test case."""
	Unknown =    0                         #: Testcase status is uninitialized and therefore unknown.
	Excluded =   1                         #: Testcase was permanently excluded / disabled
	Skipped =    2                         #: Testcase was temporarily skipped (e.g. based on a condition)
	Weak =       4                         #: No assertions were recorded.
	Passed =     8                         #: A passed testcase, because all assertions were successful.
	Failed =    16                         #: A failed testcase due to at least one failed assertion.

	Mask = Excluded | Skipped | Weak | Passed | Failed

	Inverted = 128                         #: To mark inverted results
	UnexpectedPassed = Failed | Inverted
	ExpectedFailed =   Passed | Inverted

	Warned =  1024                         #: Runtime warning
	Errored = 2048                         #: Runtime error (mostly caught exceptions)
	Aborted = 4096                         #: Uncaught runtime exception

	SetupError =     8192                  #: Preparation / compilation error
	TearDownError = 16384                  #: Cleanup error / resource release error
	Inconsistent = 32768                   #: Dataset is inconsistent

	Flags = Warned | Errored | Aborted | SetupError | TearDownError | Inconsistent

	# TODO: timed out ?
	# TODO: some passed (if merged, mixed results of passed and failed)

	def __matmul__(self, other: "TestcaseStatus") -> "TestcaseStatus":
		s = self & self.Mask
		o = other & self.Mask
		if s is self.Excluded:
			resolved = self.Excluded if o is self.Excluded else self.Unknown
		elif s is self.Skipped:
			resolved = self.Unknown if (o is self.Unknown) or (o is self.Excluded) else o
		elif s is self.Weak:
			resolved = self.Weak if o is self.Weak else self.Unknown
		elif s is self.Passed:
			if o is self.Failed:
				resolved = self.Failed
			else:
				resolved = self.Passed if (o is self.Skipped) or (o is self.Passed) else self.Unknown
		elif s is self.Failed:
			resolved = self.Failed if (o is self.Skipped) or (o is self.Passed) or (o is self.Failed) else self.Unknown
		else:
			resolved = self.Unknown

		resolved |= (self & self.Flags) | (other & self.Flags)
		return resolved


@export
class TestsuiteStatus(Flag):
	"""A flag enumeration describing the status of a test suite."""
	Unknown =    0
	Excluded =   1                         #: Testcase was permanently excluded / disabled
	Skipped =    2                         #: Testcase was temporarily skipped (e.g. based on a condition)
	Empty =      4                         #: No tests in suite
	Passed =     8                         #: Passed testcase, because all assertions succeeded
	Failed =    16                         #: Failed testcase due to failing assertions

	Mask = Excluded | Skipped | Empty | Passed | Failed

	Inverted = 128                         #: To mark inverted results
	UnexpectedPassed = Failed | Inverted
	ExpectedFailed =   Passed | Inverted

	Warned =  1024                         #: Runtime warning
	Errored = 2048                         #: Runtime error (mostly caught exceptions)
	Aborted = 4096                         #: Uncaught runtime exception

	SetupError =     8192                  #: Preparation / compilation error
	TearDownError = 16384                  #: Cleanup error / resource release error

	Flags = Warned | Errored | Aborted | SetupError | TearDownError


@export
class TestsuiteKind(IntEnum):
	"""Enumeration describing the kind of test suite."""
	Root = 0       #: Root element of the hierarchy.
	Logical = 1    #: Represents a logical unit.
	Namespace = 2  #: Represents a namespace.
	Package = 3    #: Represents a package.
	Module = 4     #: Represents a module.
	Class = 5      #: Represents a class.


@export
class IterationScheme(Flag):
	"""
	A flag enumeration for selecting the test suite iteration scheme.

	When a test entity hierarchy is (recursively) iterated, this iteration scheme describes how to iterate the hierarchy
	and what elements to return as a result.
	"""
	Unknown =           0    #: Neutral element.
	IncludeSelf =       1    #: Also include the element itself.
	IncludeTestsuites = 2    #: Include test suites into the result.
	IncludeTestcases =  4    #: Include test cases into the result.

	Recursive =         8    #: Iterate recursively.

	PreOrder =         16    #: Iterate in pre-order (top-down: current node, then child element left-to-right).
	PostOrder =        32    #: Iterate in pre-order (bottom-up: child element left-to-right, then current node).

	Default =          IncludeTestsuites | Recursive | IncludeTestcases | PreOrder  #: Recursively iterate all test entities in pre-order.
	TestsuiteDefault = IncludeTestsuites | Recursive | PreOrder                     #: Recursively iterate only test suites in pre-order.
	TestcaseDefault =  IncludeTestcases  | Recursive | PreOrder                     #: Recursively iterate only test cases in pre-order.


TestsuiteType = TypeVar("TestsuiteType", bound="Testsuite")
TestcaseAggregateReturnType = Tuple[int, int, int, timedelta]
TestsuiteAggregateReturnType = Tuple[int, int, int, int, int, int, int, int, int, int, int, timedelta]


@export
class Base(metaclass=ExtendedType, slots=True):
	"""
	Base-class for all test entities (test cases, test suites, ...).

	It provides a reference to the parent test entity, so bidirectional referencing can be used in the test entity
	hierarchy.

	Every test entity has a name to identity it. It's also used in the parent's child element dictionaries to identify the
	child. |br|
	E.g. it's used as a test case name in the dictionary of test cases in a test suite.

	Every test entity has fields for time tracking. If known, a start time and a test duration can be set. For more
	details, a setup duration and teardown duration can be added. All durations are summed up in a total duration field.

	As tests can have warnings and errors or even fail, these messages are counted and aggregated in the test entity
	hierarchy.

	Every test entity offers an internal dictionary for annotations. |br|
	This feature is for example used by Ant + JUnit4's XML property fields.
	"""

	_parent: Nullable["TestsuiteBase"]
	_name:   str

	_startTime:        Nullable[datetime]
	_setupDuration:    Nullable[timedelta]
	_testDuration:     Nullable[timedelta]
	_teardownDuration: Nullable[timedelta]
	_totalDuration:    Nullable[timedelta]

	_warningCount: int
	_errorCount:   int
	_fatalCount:   int

	_dict:         Dict[str, Any]

	def __init__(
		self,
		name: str,
		startTime: Nullable[datetime] = None,
		setupDuration: Nullable[timedelta] = None,
		testDuration: Nullable[timedelta] = None,
		teardownDuration: Nullable[timedelta] = None,
		totalDuration:  Nullable[timedelta] = None,
		warningCount: int = 0,
		errorCount: int = 0,
		fatalCount: int = 0,
		keyValuePairs: Nullable[Mapping[str, Any]] = None,
		parent: Nullable["TestsuiteBase"] = None
	):
		"""
		Initializes the fields of the base-class.

		:param name:               Name of the test entity.
		:param startTime:          Time when the test entity was started.
		:param setupDuration:      Duration it took to set up the entity.
		:param testDuration:       Duration of the entity's test run.
		:param teardownDuration:   Duration it took to tear down the entity.
		:param totalDuration:      Total duration of the entity's execution (setup + test + teardown).
		:param warningCount:       Count of encountered warnings.
		:param errorCount:         Count of encountered errors.
		:param fatalCount:         Count of encountered fatal errors.
		:param keyValuePairs:      Mapping of key-value pairs to initialize the test entity with.
		:param parent:             Reference to the parent test entity.
		:raises TypeError:         If parameter 'parent' is not a TestsuiteBase.
		:raises ValueError:        If parameter 'name' is None.
		:raises TypeError:         If parameter 'name' is not a string.
		:raises ValueError:        If parameter 'name' is empty.
		:raises TypeError:         If parameter 'testDuration' is not a timedelta.
		:raises TypeError:         If parameter 'setupDuration' is not a timedelta.
		:raises TypeError:         If parameter 'teardownDuration' is not a timedelta.
		:raises TypeError:         If parameter 'totalDuration' is not a timedelta.
		:raises TypeError:         If parameter 'warningCount' is not an integer.
		:raises TypeError:         If parameter 'errorCount' is not an integer.
		:raises TypeError:         If parameter 'fatalCount' is not an integer.
		:raises TypeError:         If parameter 'keyValuePairs' is not a Mapping.
		:raises ValueError:        If parameter 'totalDuration' is not consistent.
		"""

		if parent is not None and not isinstance(parent, TestsuiteBase):
			ex = TypeError(f"Parameter 'parent' is not of type 'TestsuiteBase'.")
			if version_info >= (3, 11):  # pragma: no cover
				ex.add_note(f"Got type '{getFullyQualifiedName(parent)}'.")
			raise ex

		if name is None:
			raise ValueError(f"Parameter 'name' is None.")
		elif not isinstance(name, str):
			ex = TypeError(f"Parameter 'name' is not of type 'str'.")
			if version_info >= (3, 11):  # pragma: no cover
				ex.add_note(f"Got type '{getFullyQualifiedName(name)}'.")
			raise ex
		elif name.strip() == "":
			raise ValueError(f"Parameter 'name' is empty.")

		self._parent = parent
		self._name = name

		if testDuration is not None and not isinstance(testDuration, timedelta):
			ex = TypeError(f"Parameter 'testDuration' is not of type 'timedelta'.")
			if version_info >= (3, 11):  # pragma: no cover
				ex.add_note(f"Got type '{getFullyQualifiedName(testDuration)}'.")
			raise ex

		if setupDuration is not None and not isinstance(setupDuration, timedelta):
			ex = TypeError(f"Parameter 'setupDuration' is not of type 'timedelta'.")
			if version_info >= (3, 11):  # pragma: no cover
				ex.add_note(f"Got type '{getFullyQualifiedName(setupDuration)}'.")
			raise ex

		if teardownDuration is not None and not isinstance(teardownDuration, timedelta):
			ex = TypeError(f"Parameter 'teardownDuration' is not of type 'timedelta'.")
			if version_info >= (3, 11):  # pragma: no cover
				ex.add_note(f"Got type '{getFullyQualifiedName(teardownDuration)}'.")
			raise ex

		if totalDuration is not None and not isinstance(totalDuration, timedelta):
			ex = TypeError(f"Parameter 'totalDuration' is not of type 'timedelta'.")
			if version_info >= (3, 11):  # pragma: no cover
				ex.add_note(f"Got type '{getFullyQualifiedName(totalDuration)}'.")
			raise ex

		if testDuration is not None:
			if setupDuration is not None:
				if teardownDuration is not None:
					if totalDuration is not None:
						if totalDuration < (setupDuration + testDuration + teardownDuration):
							raise ValueError(f"Parameter 'totalDuration' can not be less than the sum of setup, test and teardown durations.")
					else:  # no total
						totalDuration = setupDuration + testDuration + teardownDuration
				# no teardown
				elif totalDuration is not None:
					if totalDuration < (setupDuration + testDuration):
						raise ValueError(f"Parameter 'totalDuration' can not be less than the sum of setup and test durations.")
				# no teardown, no total
				else:
					totalDuration = setupDuration + testDuration
			# no setup
			elif teardownDuration is not None:
				if totalDuration is not None:
					if totalDuration < (testDuration + teardownDuration):
						raise ValueError(f"Parameter 'totalDuration' can not be less than the sum of test and teardown durations.")
				else:  # no setup, no total
					totalDuration = testDuration + teardownDuration
			# no setup, no teardown
			elif totalDuration is not None:
				if totalDuration < testDuration:
					raise ValueError(f"Parameter 'totalDuration' can not be less than test durations.")
			else:  # no setup, no teardown, no total
				totalDuration = testDuration
		# no test
		elif totalDuration is not None:
			testDuration = totalDuration
			if setupDuration is not None:
				testDuration -= setupDuration
			if teardownDuration is not None:
				testDuration -= teardownDuration

		self._startTime = startTime
		self._setupDuration = setupDuration
		self._testDuration = testDuration
		self._teardownDuration = teardownDuration
		self._totalDuration = totalDuration

		if not isinstance(warningCount, int):
			ex = TypeError(f"Parameter 'warningCount' is not of type 'int'.")
			if version_info >= (3, 11):  # pragma: no cover
				ex.add_note(f"Got type '{getFullyQualifiedName(warningCount)}'.")
			raise ex

		if not isinstance(errorCount, int):
			ex = TypeError(f"Parameter 'errorCount' is not of type 'int'.")
			if version_info >= (3, 11):  # pragma: no cover
				ex.add_note(f"Got type '{getFullyQualifiedName(errorCount)}'.")
			raise ex

		if not isinstance(fatalCount, int):
			ex = TypeError(f"Parameter 'fatalCount' is not of type 'int'.")
			if version_info >= (3, 11):  # pragma: no cover
				ex.add_note(f"Got type '{getFullyQualifiedName(fatalCount)}'.")
			raise ex

		self._warningCount = warningCount
		self._errorCount = errorCount
		self._fatalCount = fatalCount

		if keyValuePairs is not None and not isinstance(keyValuePairs, Mapping):
			ex = TypeError(f"Parameter 'keyValuePairs' is not a mapping.")
			if version_info >= (3, 11):  # pragma: no cover
				ex.add_note(f"Got type '{getFullyQualifiedName(keyValuePairs)}'.")
			raise ex

		self._dict = {} if keyValuePairs is None else {k: v for k, v in keyValuePairs}

	# QUESTION: allow Parent as setter?
	@readonly
	def Parent(self) -> Nullable["TestsuiteBase"]:
		"""
		Read-only property returning the reference to the parent test entity.

		:return: Reference to the parent entity.
		"""
		return self._parent

	@readonly
	def Name(self) -> str:
		"""
		Read-only property returning the test entity's name.

		:return:
		"""
		return self._name

	@readonly
	def StartTime(self) -> Nullable[datetime]:
		"""
		Read-only property returning the time when the test entity was started.

		:return: Time when the test entity was started.
		"""
		return self._startTime

	@readonly
	def SetupDuration(self) -> Nullable[timedelta]:
		"""
		Read-only property returning the duration of the test entity's setup.

		:return: Duration it took to set up the entity.
		"""
		return self._setupDuration

	@readonly
	def TestDuration(self) -> Nullable[timedelta]:
		"""
		Read-only property returning the duration of a test entities run.

		This duration is excluding setup and teardown durations. In case setup and/or teardown durations are unknown or not
		distinguishable, assign setup and teardown durations with zero.

		:return: Duration of the entity's test run.
		"""
		return self._testDuration

	@readonly
	def TeardownDuration(self) -> Nullable[timedelta]:
		"""
		Read-only property returning the duration of the test entity's teardown.

		:return: Duration it took to tear down the entity.
		"""
		return self._teardownDuration

	@readonly
	def TotalDuration(self) -> Nullable[timedelta]:
		"""
		Read-only property returning the total duration of a test entity run.

		this duration includes setup and teardown durations.

		:return: Total duration of the entity's execution (setup + test + teardown)
		"""
		return self._totalDuration

	@readonly
	def WarningCount(self) -> int:
		"""
		Read-only property returning the number of encountered warnings.

		:return: Count of encountered warnings.
		"""
		return self._warningCount

	@readonly
	def ErrorCount(self) -> int:
		"""
		Read-only property returning the number of encountered errors.

		:return: Count of encountered errors.
		"""
		return self._errorCount

	@readonly
	def FatalCount(self) -> int:
		"""
		Read-only property returning the number of encountered fatal errors.

		:return: Count of encountered fatal errors.
		"""
		return self._fatalCount

	def __len__(self) -> int:
		"""
		Returns the number of annotated key-value pairs.

		:return: Number of annotated key-value pairs.
		"""
		return len(self._dict)

	def __getitem__(self, key: str) -> Any:
		"""
		Access a key-value pair by key.

		:param key: Name if the key-value pair.
		:return:    Value of the accessed key.
		"""
		return self._dict[key]

	def __setitem__(self, key: str, value: Any) -> None:
		"""
		Set the value of a key-value pair by key.

		If the pair doesn't exist yet, it's created.

		:param key:   Key of the key-value pair.
		:param value: Value of the key-value pair.
		"""
		self._dict[key] = value

	def __delitem__(self, key: str) -> None:
		"""
		Delete a key-value pair by key.

		:param key: Name if the key-value pair.
		"""
		del self._dict[key]

	def __contains__(self, key: str) -> bool:
		"""
		Returns True, if a key-value pairs was annotated by this key.

		:param key: Name of the key-value pair.
		:return:    True, if the pair was annotated.
		"""
		return key in self._dict

	def __iter__(self) -> Generator[Tuple[str, Any], None, None]:
		"""
		Iterate all annotated key-value pairs.

		:return: A generator of key-value pair tuples (key, value).
		"""
		yield from self._dict.items()

	@abstractmethod
	def Aggregate(self, strict: bool = True):
		"""
		Aggregate all test entities in the hierarchy.

		:return:
		"""

	@abstractmethod
	def __str__(self) -> str:
		"""
		Formats the test entity as human-readable incl. some statistics.
		"""


@export
class Testcase(Base):
	"""
	A testcase is the leaf-entity in the test entity hierarchy representing an individual test run.

	Test cases are grouped by test suites in the test entity hierarchy. The root of the hierarchy is a test summary.

	Every test case has an overall status like unknown, skipped, failed or passed.

	In addition to all features from its base-class, test cases provide additional statistics for passed and failed
	assertions (checks) as well as a sum thereof.
	"""

	_status:               TestcaseStatus
	_assertionCount:       Nullable[int]
	_failedAssertionCount: Nullable[int]
	_passedAssertionCount: Nullable[int]

	def __init__(
		self,
		name: str,
		startTime: Nullable[datetime] = None,
		setupDuration: Nullable[timedelta] = None,
		testDuration: Nullable[timedelta] = None,
		teardownDuration: Nullable[timedelta] = None,
		totalDuration:  Nullable[timedelta] = None,
		status: TestcaseStatus = TestcaseStatus.Unknown,
		assertionCount: Nullable[int] = None,
		failedAssertionCount: Nullable[int] = None,
		passedAssertionCount: Nullable[int] = None,
		warningCount: int = 0,
		errorCount: int = 0,
		fatalCount: int = 0,
		keyValuePairs: Nullable[Mapping[str, Any]] = None,
		parent: Nullable["Testsuite"] = None
	):
		"""
		Initializes the fields of a test case.

		:param name:                 Name of the test entity.
		:param startTime:            Time when the test entity was started.
		:param setupDuration:        Duration it took to set up the entity.
		:param testDuration:         Duration of the entity's test run.
		:param teardownDuration:     Duration it took to tear down the entity.
		:param totalDuration:        Total duration of the entity's execution (setup + test + teardown)
		:param status:               Status of the test case.
		:param assertionCount:       Number of assertions within the test.
		:param failedAssertionCount: Number of failed assertions within the test.
		:param passedAssertionCount: Number of passed assertions within the test.
		:param warningCount:         Count of encountered warnings.
		:param errorCount:           Count of encountered errors.
		:param fatalCount:           Count of encountered fatal errors.
		:param keyValuePairs:        Mapping of key-value pairs to initialize the test case.
		:param parent:               Reference to the parent test suite.
		:raises TypeError:           If parameter 'parent' is not a Testsuite.
		:raises ValueError:          If parameter 'assertionCount' is not consistent.
		"""

		if parent is not None:
			if not isinstance(parent, Testsuite):
				ex = TypeError(f"Parameter 'parent' is not of type 'Testsuite'.")
				if version_info >= (3, 11):  # pragma: no cover
					ex.add_note(f"Got type '{getFullyQualifiedName(parent)}'.")
				raise ex

			parent._testcases[name] = self

		super().__init__(
			name,
			startTime,
			setupDuration,
			testDuration,
			teardownDuration,
			totalDuration,
			warningCount,
			errorCount,
			fatalCount,
			keyValuePairs,
			parent
		)

		if not isinstance(status, TestcaseStatus):
			ex = TypeError(f"Parameter 'status' is not of type 'TestcaseStatus'.")
			if version_info >= (3, 11):  # pragma: no cover
				ex.add_note(f"Got type '{getFullyQualifiedName(status)}'.")
			raise ex

		self._status = status

		if assertionCount is not None and not isinstance(assertionCount, int):
			ex = TypeError(f"Parameter 'assertionCount' is not of type 'int'.")
			if version_info >= (3, 11):  # pragma: no cover
				ex.add_note(f"Got type '{getFullyQualifiedName(assertionCount)}'.")
			raise ex

		if failedAssertionCount is not None and not isinstance(failedAssertionCount, int):
			ex = TypeError(f"Parameter 'failedAssertionCount' is not of type 'int'.")
			if version_info >= (3, 11):  # pragma: no cover
				ex.add_note(f"Got type '{getFullyQualifiedName(failedAssertionCount)}'.")
			raise ex

		if passedAssertionCount is not None and not isinstance(passedAssertionCount, int):
			ex = TypeError(f"Parameter 'passedAssertionCount' is not of type 'int'.")
			if version_info >= (3, 11):  # pragma: no cover
				ex.add_note(f"Got type '{getFullyQualifiedName(passedAssertionCount)}'.")
			raise ex

		self._assertionCount = assertionCount
		if assertionCount is not None:
			if failedAssertionCount is not None:
				self._failedAssertionCount = failedAssertionCount

				if passedAssertionCount is not None:
					if passedAssertionCount + failedAssertionCount != assertionCount:
						raise ValueError(f"passed assertion count ({passedAssertionCount}) + failed assertion count ({failedAssertionCount} != assertion count ({assertionCount}")

					self._passedAssertionCount = passedAssertionCount
				else:
					self._passedAssertionCount = assertionCount - failedAssertionCount
			elif passedAssertionCount is not None:
				self._passedAssertionCount = passedAssertionCount
				self._failedAssertionCount = assertionCount - passedAssertionCount
			else:
				raise ValueError(f"Neither passed assertion count nor failed assertion count are provided.")
		elif failedAssertionCount is not None:
			self._failedAssertionCount = failedAssertionCount

			if passedAssertionCount is not None:
				self._passedAssertionCount = passedAssertionCount
				self._assertionCount = passedAssertionCount + failedAssertionCount
			else:
				raise ValueError(f"Passed assertion count is mandatory, if failed assertion count is provided instead of assertion count.")
		elif passedAssertionCount is not None:
			raise ValueError(f"Assertion count or failed assertion count is mandatory, if passed assertion count is provided.")
		else:
			self._passedAssertionCount = None
			self._failedAssertionCount = None

	@readonly
	def Status(self) -> TestcaseStatus:
		"""
		Read-only property returning the status of the test case.

		:return: The test case's status.
		"""
		return self._status

	@readonly
	def AssertionCount(self) -> int:
		"""
		Read-only property returning the number of assertions (checks) in a test case.

		:return: Number of assertions.
		"""
		if self._assertionCount is None:
			return 0
		return self._assertionCount

	@readonly
	def FailedAssertionCount(self) -> int:
		"""
		Read-only property returning the number of failed assertions (failed checks) in a test case.

		:return: Number of assertions.
		"""
		return self._failedAssertionCount

	@readonly
	def PassedAssertionCount(self) -> int:
		"""
		Read-only property returning the number of passed assertions (successful checks) in a test case.

		:return: Number of passed assertions.
		"""
		return self._passedAssertionCount

	def Copy(self) -> "Testcase":
		return self.__class__(
			self._name,
			self._startTime,
			self._setupDuration,
			self._testDuration,
			self._teardownDuration,
			self._totalDuration,
			self._status,
			self._warningCount,
			self._errorCount,
			self._fatalCount,
		)

	def Aggregate(self, strict: bool = True) -> TestcaseAggregateReturnType:
		if self._status is TestcaseStatus.Unknown:
			if self._assertionCount is None:
				self._status = TestcaseStatus.Passed
			elif self._assertionCount == 0:
				self._status = TestcaseStatus.Weak
			elif self._failedAssertionCount == 0:
				self._status = TestcaseStatus.Passed
			else:
				self._status = TestcaseStatus.Failed

			if self._warningCount > 0:
				self._status |= TestcaseStatus.Warned

			if self._errorCount > 0:
				self._status |= TestcaseStatus.Errored

			if self._fatalCount > 0:
				self._status |= TestcaseStatus.Aborted

				if strict:
					self._status = self._status & ~TestcaseStatus.Passed | TestcaseStatus.Failed

			# TODO: check for setup errors
			# TODO: check for teardown errors

		totalDuration = timedelta() if self._totalDuration is None else self._totalDuration

		return self._warningCount, self._errorCount, self._fatalCount, totalDuration

	def __str__(self) -> str:
		"""
		Formats the test case as human-readable incl. statistics.

		:pycode:`f"<Testcase {}: {} - assert/pass/fail:{}/{}/{} - warn/error/fatal:{}/{}/{} - setup/test/teardown:{}/{}/{}>"`

		:return: Human-readable summary of a test case object.
		"""
		return (
			f"<Testcase {self._name}: {self._status.name} -"
			f" assert/pass/fail:{self._assertionCount}/{self._passedAssertionCount}/{self._failedAssertionCount} -"
			f" warn/error/fatal:{self._warningCount}/{self._errorCount}/{self._fatalCount} -"
			f" setup/test/teardown:{self._setupDuration:.3f}/{self._testDuration:.3f}/{self._teardownDuration:.3f}>"
		)


@export
class TestsuiteBase(Base, Generic[TestsuiteType]):
	"""
	Base-class for all test suites and for test summaries.

	A test suite is a mid-level grouping element in the test entity hierarchy, whereas the test summary is the root
	element in that hierarchy. While a test suite groups other test suites and test cases, a test summary can only group
	test suites. Thus, a test summary contains no test cases.
	"""

	_kind:       TestsuiteKind
	_status:     TestsuiteStatus
	_testsuites: Dict[str, TestsuiteType]

	_tests:        int
	_inconsistent: int
	_excluded:     int
	_skipped:      int
	_errored:      int
	_weak:         int
	_failed:       int
	_passed:       int

	def __init__(
		self,
		name: str,
		kind: TestsuiteKind = TestsuiteKind.Logical,
		startTime: Nullable[datetime] = None,
		setupDuration: Nullable[timedelta] = None,
		testDuration: Nullable[timedelta] = None,
		teardownDuration: Nullable[timedelta] = None,
		totalDuration:  Nullable[timedelta] = None,
		status: TestsuiteStatus = TestsuiteStatus.Unknown,
		warningCount: int = 0,
		errorCount: int = 0,
		fatalCount: int = 0,
		testsuites: Nullable[Iterable[TestsuiteType]] = None,
		keyValuePairs: Nullable[Mapping[str, Any]] = None,
		parent: Nullable["Testsuite"] = None
	):
		"""
		Initializes the based-class fields of a test suite or test summary.

		:param name:               Name of the test entity.
		:param kind:               Kind of the test entity.
		:param startTime:          Time when the test entity was started.
		:param setupDuration:      Duration it took to set up the entity.
		:param testDuration:       Duration of all tests listed in the test entity.
		:param teardownDuration:   Duration it took to tear down the entity.
		:param totalDuration:      Total duration of the entity's execution (setup + test + teardown)
		:param status:             Overall status of the test entity.
		:param warningCount:       Count of encountered warnings incl. warnings from sub-elements.
		:param errorCount:         Count of encountered errors incl. errors from sub-elements.
		:param fatalCount:         Count of encountered fatal errors incl. fatal errors from sub-elements.
		:param testsuites:         List of test suites to initialize the test entity with.
		:param keyValuePairs:      Mapping of key-value pairs to initialize the test entity with.
		:param parent:             Reference to the parent test entity.
		:raises TypeError:         If parameter 'parent' is not a TestsuiteBase.
		:raises TypeError:         If parameter 'testsuites' is not iterable.
		:raises TypeError:         If element in parameter 'testsuites' is not a Testsuite.
		:raises AlreadyInHierarchyException: If a test suite in parameter 'testsuites' is already part of a test entity hierarchy.
		:raises DuplicateTestsuiteException: If a test suite in parameter 'testsuites' is already listed (by name) in the list of test suites.
		"""
		if parent is not None:
			if not isinstance(parent, TestsuiteBase):
				ex = TypeError(f"Parameter 'parent' is not of type 'TestsuiteBase'.")
				if version_info >= (3, 11):  # pragma: no cover
					ex.add_note(f"Got type '{getFullyQualifiedName(parent)}'.")
				raise ex

			parent._testsuites[name] = self

		super().__init__(
			name,
			startTime,
			setupDuration,
			testDuration,
			teardownDuration,
			totalDuration,
			warningCount,
			errorCount,
			fatalCount,
			keyValuePairs,
			parent
		)

		self._kind = kind
		self._status = status

		self._testsuites = {}
		if testsuites is not None:
			if not isinstance(testsuites, Iterable):
				ex = TypeError(f"Parameter 'testsuites' is not iterable.")
				if version_info >= (3, 11):  # pragma: no cover
					ex.add_note(f"Got type '{getFullyQualifiedName(testsuites)}'.")
				raise ex

			for testsuite in testsuites:
				if not isinstance(testsuite, Testsuite):
					ex = TypeError(f"Element of parameter 'testsuites' is not of type 'Testsuite'.")
					if version_info >= (3, 11):  # pragma: no cover
						ex.add_note(f"Got type '{getFullyQualifiedName(testsuite)}'.")
					raise ex

				if testsuite._parent is not None:
					raise AlreadyInHierarchyException(f"Testsuite '{testsuite._name}' is already part of a testsuite hierarchy.")

				if testsuite._name in self._testsuites:
					raise DuplicateTestsuiteException(f"Testsuite already contains a testsuite with same name '{testsuite._name}'.")

				testsuite._parent = self
				self._testsuites[testsuite._name] = testsuite

		self._status = TestsuiteStatus.Unknown
		self._tests =        0
		self._inconsistent = 0
		self._excluded =     0
		self._skipped =      0
		self._errored =      0
		self._weak =         0
		self._failed =       0
		self._passed =       0

	@readonly
	def Kind(self) -> TestsuiteKind:
		"""
		Read-only property returning the kind of the test suite.

		Test suites are used to group test cases. This grouping can be due to language/framework specifics like tests
		grouped by a module file or namespace. Others might be just logically grouped without any relation to a programming
		language construct.

		Test summaries always return kind ``Root``.

		:return: Kind of the test suite.
		"""
		return self._kind

	@readonly
	def Status(self) -> TestsuiteStatus:
		"""
		Read-only property returning the aggregated overall status of the test suite.

		:return: Overall status of the test suite.
		"""
		return self._status

	@readonly
	def Testsuites(self) -> Dict[str, TestsuiteType]:
		"""
		Read-only property returning a reference to the internal dictionary of test suites.

		:return: Reference to the dictionary of test suite.
		"""
		return self._testsuites

	@readonly
	def TestsuiteCount(self) -> int:
		"""
		Read-only property returning the number of all test suites in the test suite hierarchy.

		:return: Number of test suites.
		"""
		return 1 + sum(testsuite.TestsuiteCount for testsuite in self._testsuites.values())

	@readonly
	def TestcaseCount(self) -> int:
		"""
		Read-only property returning the number of all test cases in the test entity hierarchy.

		:return: Number of test cases.
		"""
		return sum(testsuite.TestcaseCount for testsuite in self._testsuites.values())

	@readonly
	def AssertionCount(self) -> int:
		"""
		Read-only property returning the number of all assertions in all test cases in the test entity hierarchy.

		:return: Number of assertions in all test cases.
		"""
		return sum(ts.AssertionCount for ts in self._testsuites.values())

	@readonly
	def FailedAssertionCount(self) -> int:
		"""
		Read-only property returning the number of all failed assertions in all test cases in the test entity hierarchy.

		:return: Number of failed assertions in all test cases.
		"""
		raise NotImplementedError()
		# return self._assertionCount - (self._warningCount + self._errorCount + self._fatalCount)

	@readonly
	def PassedAssertionCount(self) -> int:
		"""
		Read-only property returning the number of all passed assertions in all test cases in the test entity hierarchy.

		:return: Number of passed assertions in all test cases.
		"""
		raise NotImplementedError()
		# return self._assertionCount - (self._warningCount + self._errorCount + self._fatalCount)

	@readonly
	def Tests(self) -> int:
		return self._tests

	@readonly
	def Inconsistent(self) -> int:
		"""
		Read-only property returning the number of inconsistent tests in the test suite hierarchy.

		:return: Number of inconsistent tests.
		"""
		return self._inconsistent

	@readonly
	def Excluded(self) -> int:
		"""
		Read-only property returning the number of excluded tests in the test suite hierarchy.

		:return: Number of excluded tests.
		"""
		return self._excluded

	@readonly
	def Skipped(self) -> int:
		"""
		Read-only property returning the number of skipped tests in the test suite hierarchy.

		:return: Number of skipped tests.
		"""
		return self._skipped

	@readonly
	def Errored(self) -> int:
		"""
		Read-only property returning the number of tests with errors in the test suite hierarchy.

		:return: Number of errored tests.
		"""
		return self._errored

	@readonly
	def Weak(self) -> int:
		"""
		Read-only property returning the number of weak tests in the test suite hierarchy.

		:return: Number of weak tests.
		"""
		return self._weak

	@readonly
	def Failed(self) -> int:
		"""
		Read-only property returning the number of failed tests in the test suite hierarchy.

		:return: Number of failed tests.
		"""
		return self._failed

	@readonly
	def Passed(self) -> int:
		"""
		Read-only property returning the number of passed tests in the test suite hierarchy.

		:return: Number of passed tests.
		"""
		return self._passed

	@readonly
	def WarningCount(self) -> int:
		raise NotImplementedError()
		# return self._warningCount

	@readonly
	def ErrorCount(self) -> int:
		raise NotImplementedError()
		# return self._errorCount

	@readonly
	def FatalCount(self) -> int:
		raise NotImplementedError()
		# return self._fatalCount

	def Aggregate(self, strict: bool = True) -> TestsuiteAggregateReturnType:
		tests = 0
		inconsistent = 0
		excluded = 0
		skipped = 0
		errored = 0
		weak = 0
		failed = 0
		passed = 0

		warningCount = 0
		errorCount = 0
		fatalCount = 0

		totalDuration = timedelta()

		for testsuite in self._testsuites.values():
			t, i, ex, s, e, w, f, p, wc, ec, fc, td = testsuite.Aggregate(strict)
			tests += t
			inconsistent += i
			excluded += ex
			skipped += s
			errored += e
			weak += w
			failed += f
			passed += p

			warningCount += wc
			errorCount += ec
			fatalCount += fc

			totalDuration += td

		return tests, inconsistent, excluded, skipped, errored, weak, failed, passed, warningCount, errorCount, fatalCount, totalDuration

	def AddTestsuite(self, testsuite: TestsuiteType) -> None:
		"""
		Add a test suite to the list of test suites.

		:param testsuite:   The test suite to add.
		:raises ValueError: If parameter 'testsuite' is None.
		:raises TypeError:  If parameter 'testsuite' is not a Testsuite.
		:raises AlreadyInHierarchyException: If parameter 'testsuite' is already part of a test entity hierarchy.
		:raises DuplicateTestcaseException:  If parameter 'testsuite' is already listed (by name) in the list of test suites.
		"""
		if testsuite is None:
			raise ValueError("Parameter 'testsuite' is None.")
		elif not isinstance(testsuite, Testsuite):
			ex = TypeError(f"Parameter 'testsuite' is not of type 'Testsuite'.")
			if version_info >= (3, 11):  # pragma: no cover
				ex.add_note(f"Got type '{getFullyQualifiedName(testsuite)}'.")
			raise ex

		if testsuite._parent is not None:
			raise AlreadyInHierarchyException(f"Testsuite '{testsuite._name}' is already part of a testsuite hierarchy.")

		if testsuite._name in self._testsuites:
			raise DuplicateTestsuiteException(f"Testsuite already contains a testsuite with same name '{testsuite._name}'.")

		testsuite._parent = self
		self._testsuites[testsuite._name] = testsuite

	def AddTestsuites(self, testsuites: Iterable[TestsuiteType]) -> None:
		"""
		Add a list of test suites to the list of test suites.

		:param testsuites:  List of test suites to add.
		:raises ValueError: If parameter 'testsuites' is None.
		:raises TypeError:  If parameter 'testsuites' is not iterable.
		"""
		if testsuites is None:
			raise ValueError("Parameter 'testsuites' is None.")
		elif not isinstance(testsuites, Iterable):
			ex = TypeError(f"Parameter 'testsuites' is not iterable.")
			if version_info >= (3, 11):  # pragma: no cover
				ex.add_note(f"Got type '{getFullyQualifiedName(testsuites)}'.")
			raise ex

		for testsuite in testsuites:
			self.AddTestsuite(testsuite)

	@abstractmethod
	def Iterate(self, scheme: IterationScheme = IterationScheme.Default) -> Generator[Union[TestsuiteType, Testcase], None, None]:
		pass

	def IterateTestsuites(self, scheme: IterationScheme = IterationScheme.TestsuiteDefault) -> Generator[TestsuiteType, None, None]:
		return self.Iterate(scheme)

	def IterateTestcases(self, scheme: IterationScheme = IterationScheme.TestcaseDefault) -> Generator[Testcase, None, None]:
		return self.Iterate(scheme)

	def ToTree(self) -> Node:
		rootNode = Node(value=self._name)

		def convertTestcase(testcase: Testcase, parentNode: Node) -> None:
			_ = Node(value=testcase._name, parent=parentNode)

		def convertTestsuite(testsuite: Testsuite, parentNode: Node) -> None:
			testsuiteNode = Node(value=testsuite._name, parent=parentNode)

			for ts in testsuite._testsuites.values():
				convertTestsuite(ts, testsuiteNode)

			for tc in testsuite._testcases.values():
				convertTestcase(tc, testsuiteNode)

		for testsuite in self._testsuites.values():
			convertTestsuite(testsuite, rootNode)

		return rootNode


@export
class Testsuite(TestsuiteBase[TestsuiteType]):
	"""
	A testsuite is a mid-level element in the test entity hierarchy representing a group of tests.

	Test suites contain test cases and optionally other test suites. Test suites can be grouped by test suites to form a
	hierarchy of test entities. The root of the hierarchy is a test summary.
	"""

	_testcases: Dict[str, "Testcase"]

	def __init__(
		self,
		name: str,
		kind: TestsuiteKind = TestsuiteKind.Logical,
		startTime: Nullable[datetime] = None,
		setupDuration: Nullable[timedelta] = None,
		testDuration: Nullable[timedelta] = None,
		teardownDuration: Nullable[timedelta] = None,
		totalDuration:  Nullable[timedelta] = None,
		status: TestsuiteStatus = TestsuiteStatus.Unknown,
		warningCount: int = 0,
		errorCount: int = 0,
		fatalCount: int = 0,
		testsuites: Nullable[Iterable[TestsuiteType]] = None,
		testcases: Nullable[Iterable["Testcase"]] = None,
		keyValuePairs: Nullable[Mapping[str, Any]] = None,
		parent: Nullable[TestsuiteType] = None
	):
		"""
		Initializes the fields of a test suite.

		:param name:               Name of the test suite.
		:param kind:               Kind of the test suite.
		:param startTime:          Time when the test suite was started.
		:param setupDuration:      Duration it took to set up the test suite.
		:param testDuration:       Duration of all tests listed in the test suite.
		:param teardownDuration:   Duration it took to tear down the test suite.
		:param totalDuration:      Total duration of the entity's execution (setup + test + teardown)
		:param status:             Overall status of the test suite.
		:param warningCount:       Count of encountered warnings incl. warnings from sub-elements.
		:param errorCount:         Count of encountered errors incl. errors from sub-elements.
		:param fatalCount:         Count of encountered fatal errors incl. fatal errors from sub-elements.
		:param testsuites:         List of test suites to initialize the test suite with.
		:param testcases:          List of test cases to initialize the test suite with.
		:param keyValuePairs:      Mapping of key-value pairs to initialize the test suite with.
		:param parent:             Reference to the parent test entity.
		:raises TypeError:         If parameter 'testcases' is not iterable.
		:raises TypeError:         If element in parameter 'testcases' is not a Testcase.
		:raises AlreadyInHierarchyException: If a test case in parameter 'testcases' is already part of a test entity hierarchy.
		:raises DuplicateTestcaseException:  If a test case in parameter 'testcases' is already listed (by name) in the list of test cases.
		"""
		super().__init__(
			name,
			kind,
			startTime,
			setupDuration,
			testDuration,
			teardownDuration,
			totalDuration,
			status,
			warningCount,
			errorCount,
			fatalCount,
			testsuites,
			keyValuePairs,
			parent
		)

		# self._testDuration = testDuration

		self._testcases = {}
		if testcases is not None:
			if not isinstance(testcases, Iterable):
				ex = TypeError(f"Parameter 'testcases' is not iterable.")
				if version_info >= (3, 11):  # pragma: no cover
					ex.add_note(f"Got type '{getFullyQualifiedName(testcases)}'.")
				raise ex

			for testcase in testcases:
				if not isinstance(testcase, Testcase):
					ex = TypeError(f"Element of parameter 'testcases' is not of type 'Testcase'.")
					if version_info >= (3, 11):  # pragma: no cover
						ex.add_note(f"Got type '{getFullyQualifiedName(testcase)}'.")
					raise ex

				if testcase._parent is not None:
					raise AlreadyInHierarchyException(f"Testcase '{testcase._name}' is already part of a testsuite hierarchy.")

				if testcase._name in self._testcases:
					raise DuplicateTestcaseException(f"Testsuite already contains a testcase with same name '{testcase._name}'.")

				testcase._parent = self
				self._testcases[testcase._name] = testcase

	@readonly
	def Testcases(self) -> Dict[str, "Testcase"]:
		"""
		Read-only property returning a reference to the internal dictionary of test cases.

		:return: Reference to the dictionary of test cases.
		"""
		return self._testcases

	@readonly
	def TestcaseCount(self) -> int:
		"""
		Read-only property returning the number of all test cases in the test entity hierarchy.

		:return: Number of test cases.
		"""
		return super().TestcaseCount + len(self._testcases)

	@readonly
	def AssertionCount(self) -> int:
		return super().AssertionCount + sum(tc.AssertionCount for tc in self._testcases.values())

	def Copy(self) -> "Testsuite":
		return self.__class__(
			self._name,
			self._startTime,
			self._setupDuration,
			self._teardownDuration,
			self._totalDuration,
			self._status,
			self._warningCount,
			self._errorCount,
			self._fatalCount
		)

	def Aggregate(self, strict: bool = True) -> TestsuiteAggregateReturnType:
		tests, inconsistent, excluded, skipped, errored, weak, failed, passed, warningCount, errorCount, fatalCount, totalDuration = super().Aggregate()

		for testcase in self._testcases.values():
			wc, ec, fc, td = testcase.Aggregate(strict)

			tests += 1

			warningCount += wc
			errorCount +=   ec
			fatalCount +=   fc

			totalDuration += td

			status = testcase._status
			if status is TestcaseStatus.Unknown:
				raise UnittestException(f"Found testcase '{testcase._name}' with state 'Unknown'.")
			elif TestcaseStatus.Inconsistent in status:
				inconsistent += 1
			elif status is TestcaseStatus.Excluded:
				excluded += 1
			elif status is TestcaseStatus.Skipped:
				skipped += 1
			elif status is TestcaseStatus.Errored:
				errored += 1
			elif status is TestcaseStatus.Weak:
				weak += 1
			elif status is TestcaseStatus.Passed:
				passed += 1
			elif status is TestcaseStatus.Failed:
				failed += 1
			elif status & TestcaseStatus.Mask is not TestcaseStatus.Unknown:
				raise UnittestException(f"Found testcase '{testcase._name}' with unsupported state '{status}'.")
			else:
				raise UnittestException(f"Internal error for testcase '{testcase._name}', field '_status' is '{status}'.")

		self._tests = tests
		self._inconsistent = inconsistent
		self._excluded = excluded
		self._skipped = skipped
		self._errored = errored
		self._weak = weak
		self._failed = failed
		self._passed = passed

		self._warningCount = warningCount
		self._errorCount = errorCount
		self._fatalCount = fatalCount

		if self._totalDuration is None:
			self._totalDuration = totalDuration

		if errored > 0:
			self._status = TestsuiteStatus.Errored
		elif failed > 0:
			self._status = TestsuiteStatus.Failed
		elif tests == 0:
			self._status = TestsuiteStatus.Empty
		elif tests - skipped == passed:
			self._status = TestsuiteStatus.Passed
		elif tests == skipped:
			self._status = TestsuiteStatus.Skipped
		else:
			self._status = TestsuiteStatus.Unknown

		return tests, inconsistent, excluded, skipped, errored, weak, failed, passed, warningCount, errorCount, fatalCount, totalDuration

	def AddTestcase(self, testcase: "Testcase") -> None:
		"""
		Add a test case to the list of test cases.

		:param testcase:    The test case to add.
		:raises ValueError: If parameter 'testcase' is None.
		:raises TypeError:  If parameter 'testcase' is not a Testcase.
		:raises AlreadyInHierarchyException: If parameter 'testcase' is already part of a test entity hierarchy.
		:raises DuplicateTestcaseException:  If parameter 'testcase' is already listed (by name) in the list of test cases.
		"""
		if testcase is None:
			raise ValueError("Parameter 'testcase' is None.")
		elif not isinstance(testcase, Testcase):
			ex = TypeError(f"Parameter 'testcase' is not of type 'Testcase'.")
			if version_info >= (3, 11):  # pragma: no cover
				ex.add_note(f"Got type '{getFullyQualifiedName(testcase)}'.")
			raise ex

		if testcase._parent is not None:
			raise ValueError(f"Testcase '{testcase._name}' is already part of a testsuite hierarchy.")

		if testcase._name in self._testcases:
			raise DuplicateTestcaseException(f"Testsuite already contains a testcase with same name '{testcase._name}'.")

		testcase._parent = self
		self._testcases[testcase._name] = testcase

	def AddTestcases(self, testcases: Iterable["Testcase"]) -> None:
		"""
		Add a list of test cases to the list of test cases.

		:param testcases:   List of test cases to add.
		:raises ValueError: If parameter 'testcases' is None.
		:raises TypeError:  If parameter 'testcases' is not iterable.
		"""
		if testcases is None:
			raise ValueError("Parameter 'testcases' is None.")
		elif not isinstance(testcases, Iterable):
			ex = TypeError(f"Parameter 'testcases' is not iterable.")
			if version_info >= (3, 11):  # pragma: no cover
				ex.add_note(f"Got type '{getFullyQualifiedName(testcases)}'.")
			raise ex

		for testcase in testcases:
			self.AddTestcase(testcase)

	def Iterate(self, scheme: IterationScheme = IterationScheme.Default) -> Generator[Union[TestsuiteType, Testcase], None, None]:
		assert IterationScheme.PreOrder | IterationScheme.PostOrder not in scheme

		if IterationScheme.PreOrder in scheme:
			if IterationScheme.IncludeSelf | IterationScheme.IncludeTestsuites in scheme:
				yield self

			if IterationScheme.IncludeTestcases in scheme:
				for testcase in self._testcases.values():
					yield testcase

		for testsuite in self._testsuites.values():
			yield from testsuite.Iterate(scheme | IterationScheme.IncludeSelf)

		if IterationScheme.PostOrder in scheme:
			if IterationScheme.IncludeTestcases in scheme:
				for testcase in self._testcases.values():
					yield testcase

			if IterationScheme.IncludeSelf | IterationScheme.IncludeTestsuites in scheme:
				yield self

	def __str__(self) -> str:
		return (
			f"<Testsuite {self._name}: {self._status.name} -"
			# f" assert/pass/fail:{self._assertionCount}/{self._passedAssertionCount}/{self._failedAssertionCount} -"
			f" warn/error/fatal:{self._warningCount}/{self._errorCount}/{self._fatalCount}>"
		)


@export
class TestsuiteSummary(TestsuiteBase[TestsuiteType]):
	"""
	A testsuite summary is the root element in the test entity hierarchy representing a summary of all test suites and cases.

	The testsuite summary contains test suites, which in turn can contain test suites and test cases.
	"""

	def __init__(
		self,
		name: str,
		startTime: Nullable[datetime] = None,
		setupDuration: Nullable[timedelta] = None,
		testDuration: Nullable[timedelta] = None,
		teardownDuration: Nullable[timedelta] = None,
		totalDuration:  Nullable[timedelta] = None,
		status: TestsuiteStatus = TestsuiteStatus.Unknown,
		warningCount: int = 0,
		errorCount: int = 0,
		fatalCount: int = 0,
		testsuites: Nullable[Iterable[TestsuiteType]] = None,
		keyValuePairs: Nullable[Mapping[str, Any]] = None,
		parent: Nullable[TestsuiteType] = None
	):
		"""
		Initializes the fields of a test summary.

		:param name:               Name of the test summary.
		:param startTime:          Time when the test summary was started.
		:param setupDuration:      Duration it took to set up the test summary.
		:param testDuration:       Duration of all tests listed in the test summary.
		:param teardownDuration:   Duration it took to tear down the test summary.
		:param totalDuration:      Total duration of the entity's execution (setup + test + teardown)
		:param status:             Overall status of the test summary.
		:param warningCount:       Count of encountered warnings incl. warnings from sub-elements.
		:param errorCount:         Count of encountered errors incl. errors from sub-elements.
		:param fatalCount:         Count of encountered fatal errors incl. fatal errors from sub-elements.
		:param testsuites:         List of test suites to initialize the test summary with.
		:param keyValuePairs:      Mapping of key-value pairs to initialize the test summary with.
		:param parent:             Reference to the parent test summary.
		"""
		super().__init__(
			name,
			TestsuiteKind.Root,
			startTime,
			setupDuration,
			testDuration,
			teardownDuration,
			totalDuration,
			status,
			warningCount,
			errorCount,
			fatalCount,
			testsuites,
			keyValuePairs,
			parent
		)

	def Aggregate(self, strict: bool = True) -> TestsuiteAggregateReturnType:
		tests, inconsistent, excluded, skipped, errored, weak, failed, passed, warningCount, errorCount, fatalCount, totalDuration = super().Aggregate(strict)

		self._tests = tests
		self._inconsistent = inconsistent
		self._excluded = excluded
		self._skipped = skipped
		self._errored = errored
		self._weak = weak
		self._failed = failed
		self._passed = passed

		self._warningCount = warningCount
		self._errorCount = errorCount
		self._fatalCount = fatalCount

		if self._totalDuration is None:
			self._totalDuration = totalDuration

		if errored > 0:
			self._status = TestsuiteStatus.Errored
		elif failed > 0:
			self._status = TestsuiteStatus.Failed
		elif tests == 0:
			self._status = TestsuiteStatus.Empty
		elif tests - skipped == passed:
			self._status = TestsuiteStatus.Passed
		elif tests == skipped:
			self._status = TestsuiteStatus.Skipped
		elif tests == excluded:
			self._status = TestsuiteStatus.Excluded
		else:
			self._status = TestsuiteStatus.Unknown

		return tests, inconsistent, excluded, skipped, errored, weak, failed, passed, warningCount, errorCount, fatalCount, totalDuration

	def Iterate(self, scheme: IterationScheme = IterationScheme.Default) -> Generator[Union[TestsuiteType, Testcase], None, None]:
		if IterationScheme.IncludeSelf | IterationScheme.IncludeTestsuites | IterationScheme.PreOrder in scheme:
			yield self

		for testsuite in self._testsuites.values():
			yield from testsuite.IterateTestsuites(scheme | IterationScheme.IncludeSelf)

		if IterationScheme.IncludeSelf | IterationScheme.IncludeTestsuites | IterationScheme.PostOrder in scheme:
			yield self

	def __str__(self) -> str:
		return (
			f"<TestsuiteSummary {self._name}: {self._status.name} -"
			# f" assert/pass/fail:{self._assertionCount}/{self._passedAssertionCount}/{self._failedAssertionCount} -"
			f" warn/error/fatal:{self._warningCount}/{self._errorCount}/{self._fatalCount}>"
		)


@export
class Document(metaclass=ExtendedType, mixin=True):
	"""A mixin-class representing a unit test summary document (file)."""

	_path:             Path

	_analysisDuration: float  #: TODO: replace by Timer; should be timedelta?
	_modelConversion:  float  #: TODO: replace by Timer; should be timedelta?

	def __init__(self, reportFile: Path, analyzeAndConvert: bool = False):
		self._path = reportFile

		self._analysisDuration = -1.0
		self._modelConversion = -1.0

		if analyzeAndConvert:
			self.Analyze()
			self.Convert()

	@readonly
	def Path(self) -> Path:
		"""
		Read-only property returning the path to the file of this document.

		:return: The document's path to the file.
		"""
		return self._path

	@readonly
	def AnalysisDuration(self) -> timedelta:
		"""
		Read-only property returning analysis duration.

		.. note::

		   This includes usually the duration to validate and parse the file format, but it excludes the time to convert the
		   content to the test entity hierarchy.

		:return: Duration to analyze the document.
		"""
		return timedelta(seconds=self._analysisDuration)

	@readonly
	def ModelConversionDuration(self) -> timedelta:
		"""
		Read-only property returning conversion duration.

		.. note::

		   This includes usually the duration to convert the document's content to the test entity hierarchy. It might also
		   include the duration to (re-)aggregate all states and statistics in the hierarchy.

		:return: Duration to convert the document.
		"""
		return timedelta(seconds=self._modelConversion)

	@abstractmethod
	def Analyze(self) -> None:
		"""Analyze and validate the document's content."""

	# @abstractmethod
	# def Write(self, path: Nullable[Path] = None, overwrite: bool = False):
	# 	pass

	@abstractmethod
	def Convert(self):
		"""Convert the document's content to an instance of the test entity hierarchy."""


@export
class Merged(metaclass=ExtendedType, mixin=True):
	"""A mixin-class representing a merged test entity."""

	_mergedCount: int

	def __init__(self, mergedCount: int = 1):
		self._mergedCount = mergedCount

	@readonly
	def MergedCount(self) -> int:
		return self._mergedCount


@export
class Combined(metaclass=ExtendedType, mixin=True):
	_combinedCount: int

	def __init__(self, combinedCound: int = 1):
		self._combinedCount = combinedCound

	@readonly
	def CombinedCount(self) -> int:
		return self._combinedCount


@export
class MergedTestcase(Testcase, Merged):
	_mergedTestcases: List[Testcase]

	def __init__(
		self,
		testcase: Testcase,
		parent: Nullable["Testsuite"] = None
	):
		if testcase is None:
			raise ValueError(f"Parameter 'testcase' is None.")

		super().__init__(
			testcase._name,
			testcase._startTime,
			testcase._setupDuration, testcase._testDuration, testcase._teardownDuration, testcase._totalDuration,
			TestcaseStatus.Unknown,
			testcase._assertionCount, testcase._failedAssertionCount, testcase._passedAssertionCount,
			testcase._warningCount, testcase._errorCount, testcase._fatalCount,
			parent
		)
		Merged.__init__(self)

		self._mergedTestcases = [testcase]

	@readonly
	def Status(self) -> TestcaseStatus:
		if self._status is TestcaseStatus.Unknown:
			status = self._mergedTestcases[0]._status
			for mtc in self._mergedTestcases[1:]:
				status @= mtc._status

			self._status = status

		return self._status

	@readonly
	def SummedAssertionCount(self) -> int:
		return sum(tc._assertionCount for tc in self._mergedTestcases)

	@readonly
	def SummedPassedAssertionCount(self) -> int:
		return sum(tc._passedAssertionCount for tc in self._mergedTestcases)

	@readonly
	def SummedFailedAssertionCount(self) -> int:
		return sum(tc._failedAssertionCount for tc in self._mergedTestcases)

	def Aggregate(self, strict: bool = True) -> TestcaseAggregateReturnType:
		firstMTC = self._mergedTestcases[0]

		status =        firstMTC._status
		warningCount =  firstMTC._warningCount
		errorCount =    firstMTC._errorCount
		fatalCount =    firstMTC._fatalCount
		totalDuration = firstMTC._totalDuration

		for mtc in self._mergedTestcases[1:]:
			status @=       mtc._status
			warningCount += mtc._warningCount
			errorCount +=   mtc._errorCount
			fatalCount +=   mtc._fatalCount

		self._status = status

		return warningCount, errorCount, fatalCount, totalDuration

	def Merge(self, tc: Testcase) -> None:
		self._mergedCount += 1

		self._mergedTestcases.append(tc)

		self._warningCount += tc._warningCount
		self._errorCount += tc._errorCount
		self._fatalCount += tc._fatalCount

	def ToTestcase(self) -> Testcase:
		return Testcase(
			self._name,
			self._startTime,
			self._setupDuration,
			self._testDuration,
			self._teardownDuration,
			self._totalDuration,
			self._status,
			self._assertionCount,
			self._failedAssertionCount,
			self._passedAssertionCount,
			self._warningCount,
			self._errorCount,
			self._fatalCount
		)


@export
class MergedTestsuite(Testsuite, Merged):
	def __init__(
		self,
		testsuite: Testsuite,
		addTestsuites: bool = False,
		addTestcases: bool = False,
		parent: Nullable["Testsuite"] = None
	):
		if testsuite is None:
			raise ValueError(f"Parameter 'testsuite' is None.")

		super().__init__(
			testsuite._name,
			testsuite._kind,
			testsuite._startTime,
			testsuite._setupDuration, testsuite._testDuration, testsuite._teardownDuration, testsuite._totalDuration,
			TestsuiteStatus.Unknown,
			testsuite._warningCount, testsuite._errorCount, testsuite._fatalCount,
			parent
		)
		Merged.__init__(self)

		if addTestsuites:
			for ts in testsuite._testsuites.values():
				mergedTestsuite = MergedTestsuite(ts, addTestsuites, addTestcases)
				self.AddTestsuite(mergedTestsuite)

		if addTestcases:
			for tc in testsuite._testcases.values():
				mergedTestcase = MergedTestcase(tc)
				self.AddTestcase(mergedTestcase)

	def Merge(self, testsuite: Testsuite) -> None:
		self._mergedCount += 1

		for ts in testsuite._testsuites.values():
			if ts._name in self._testsuites:
				self._testsuites[ts._name].Merge(ts)
			else:
				mergedTestsuite = MergedTestsuite(ts, addTestsuites=True, addTestcases=True)
				self.AddTestsuite(mergedTestsuite)

		for tc in testsuite._testcases.values():
			if tc._name in self._testcases:
				self._testcases[tc._name].Merge(tc)
			else:
				mergedTestcase = MergedTestcase(tc)
				self.AddTestcase(mergedTestcase)

	def ToTestsuite(self) -> Testsuite:
		testsuite = Testsuite(
			self._name,
			self._kind,
			self._startTime,
			self._setupDuration,
			self._testDuration,
			self._teardownDuration,
			self._totalDuration,
			self._status,
			self._warningCount,
			self._errorCount,
			self._fatalCount,
			testsuites=(ts.ToTestsuite() for ts in self._testsuites.values()),
			testcases=(tc.ToTestcase() for tc in self._testcases.values())
		)

		testsuite._tests = self._tests
		testsuite._excluded = self._excluded
		testsuite._inconsistent = self._inconsistent
		testsuite._skipped = self._skipped
		testsuite._errored = self._errored
		testsuite._weak = self._weak
		testsuite._failed = self._failed
		testsuite._passed = self._passed

		return testsuite


@export
class MergedTestsuiteSummary(TestsuiteSummary, Merged):
	_mergedFiles: Dict[Path, TestsuiteSummary]

	def __init__(self, name: str) -> None:
		super().__init__(name)
		Merged.__init__(self, mergedCount=0)

		self._mergedFiles = {}

	def Merge(self, testsuiteSummary: TestsuiteSummary) -> None:
		# if summary.File in self._mergedFiles:
		# 	raise

		# FIXME: a summary is not necessarily a file
		self._mergedCount += 1
		self._mergedFiles[testsuiteSummary._name] = testsuiteSummary

		for testsuite in testsuiteSummary._testsuites.values():
			if testsuite._name in self._testsuites:
				self._testsuites[testsuite._name].Merge(testsuite)
			else:
				mergedTestsuite = MergedTestsuite(testsuite, addTestsuites=True, addTestcases=True)
				self.AddTestsuite(mergedTestsuite)

	def ToTestsuiteSummary(self) -> TestsuiteSummary:
		testsuiteSummary = TestsuiteSummary(
			self._name,
			self._startTime,
			self._setupDuration,
			self._testDuration,
			self._teardownDuration,
			self._totalDuration,
			self._status,
			self._warningCount,
			self._errorCount,
			self._fatalCount,
			testsuites=(ts.ToTestsuite() for ts in self._testsuites.values())
		)

		testsuiteSummary._tests = self._tests
		testsuiteSummary._excluded = self._excluded
		testsuiteSummary._inconsistent = self._inconsistent
		testsuiteSummary._skipped = self._skipped
		testsuiteSummary._errored = self._errored
		testsuiteSummary._weak = self._weak
		testsuiteSummary._failed = self._failed
		testsuiteSummary._passed = self._passed

		return testsuiteSummary