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
|
# ==================================================================================================================== #
# _____ ____ _ _ ____ _ #
# _ __ _ _| ____| _ \ / \ / \ | _ \ ___ _ __ ___ _ __| |_ ___ #
# | '_ \| | | | _| | | | |/ _ \ / _ \ | |_) / _ \ '_ \ / _ \| '__| __/ __| #
# | |_) | |_| | |___| |_| / ___ \ / ___ \ _| _ < __/ |_) | (_) | | | |_\__ \ #
# | .__/ \__, |_____|____/_/ \_\/_/ \_(_)_| \_\___| .__/ \___/|_| \__|___/ #
# |_| |___/ |_| #
# ==================================================================================================================== #
# Authors: #
# Patrick Lehmann #
# #
# License: #
# ==================================================================================================================== #
# Copyright 2021-2026 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 #
# ==================================================================================================================== #
#
"""
Abstract data model of code coverage, the common model every report format is converted to.
The model has two hierarchies over the same lines:
* The **physical** hierarchy - :class:`CoverageSummary`, :class:`Directory`, :class:`File` - is built from the file
paths a report names. A file holds its executable lines; every format has them.
* The **logical** hierarchy holds the language units a report names - :class:`Package`, :class:`Module`,
:class:`SourceFile`, :class:`Class`, :class:`Function`, :class:`Method` -, each spanning its file from a first to a
last :class:`Line`, so both hierarchies count the same lines.
A :class:`Line` and a :class:`Branch` carry a :class:`LineCoverageStatus` and - if the report says - a count: how
often the line ran, or the branch was taken. :meth:`CoverageSummary.Aggregate` computes the counters of every file,
directory and unit.
The report formats have models of their own, which convert to this one:
.. seealso::
:mod:`pyEDAA.Reports.CodeCoverage.Cobertura`
|rarr| The Cobertura XML format, as written e.g. by coverage.py (``coverage xml``) or gcovr (``--cobertura``).
:mod:`pyEDAA.Reports.CodeCoverage.CoveragePy`
|rarr| coverage.py's JSON format (``coverage json``).
:mod:`pyEDAA.Reports.CodeCoverage.GHDL`
|rarr| GHDL's JSON coverage file (``ghdl -r --coverage``).
:mod:`pyEDAA.Reports.CodeCoverage.UCIS`
|rarr| The XML interchange format of the Accellera UCIS standard, as written e.g. by pyucis (``pyucis convert``).
:mod:`pyEDAA.Reports.CodeCoverage.Gcov`
|rarr| GCC's gcov JSON format (``gcov --json-format``).
:mod:`pyEDAA.Reports.CodeCoverage.LCOV`
|rarr| lcov's tracefile format, as written e.g. by lcov (``lcov --capture``) or llvm-cov
(``llvm-cov export -format=lcov``).
:mod:`pyEDAA.Reports.CodeCoverage.JaCoCo`
|rarr| JaCoCo's XML format, as written e.g. by Gradle's task ``jacocoTestReport``.
:mod:`pyEDAA.Reports.CodeCoverage.AldecUCDB`
|rarr| Aldec's UCDB XML format, as exported by ``acdb2xml`` of Riviera-PRO or Active-HDL.
:mod:`pyEDAA.Reports.CodeCoverage.QuestaSim`
|rarr| QuestaSim's code coverage report XML (``vcover report -xml -details``).
:mod:`pyEDAA.Reports.CodeCoverage.LLVM`
|rarr| LLVM's JSON code coverage export (``llvm-cov export``), e.g. of Clang's source-based code coverage.
"""
from __future__ import annotations
from datetime import timedelta
from enum import Enum
from pathlib import Path
from typing import Callable, ClassVar, Generator, Iterable, Optional as Nullable
from pyTooling.Common import getFullyQualifiedName, getTypeName
from pyTooling.Decorators import export, readonly
from pyTooling.Exceptions import AlreadyInHierarchyError, DuplicateElementError
from pyTooling.MetaClasses import ExtendedType, abstractclass, abstractmethod
from pyEDAA.Reports import ReportException
@export
class CodeCoverageError(ReportException):
"""Base-exception of the code coverage data model and its report formats."""
@export
class AlreadyInCoverageReportError(CodeCoverageError, AlreadyInHierarchyError):
"""The exception is raised when an element is added to an element, but it already has a parent."""
@export
class DuplicateDirectoryError(CodeCoverageError, DuplicateElementError):
"""The exception is raised when a directory already contains a directory or a file of the same name."""
@export
class DuplicateFileError(CodeCoverageError, DuplicateElementError):
"""The exception is raised when a directory or a report already contains a file or a directory of the same name."""
@export
class DuplicateUnitError(CodeCoverageError, DuplicateElementError):
"""The exception is raised when a unit or the report's root already contains a unit of the same name."""
@export
class DuplicateLineError(CodeCoverageError, DuplicateElementError):
"""The exception is raised when a file already has a line of the same number."""
@export
class LineCoverageStatus(Enum):
"""The coverage state of a line, a branch or a unit, as a report states it."""
Unknown = 0 #: The report doesn't say.
Uncovered = 1 #: The line never ran, the branch was never taken, the unit was never called.
PartiallyCovered = 2 #: The line ran, but not all of its branches were taken.
Covered = 3 #: The line ran, the branch was taken, the unit was called.
Excluded = 4 #: Excluded from the measurement, e.g. by a pragma comment.
@export
class Base(metaclass=ExtendedType, slots=True):
"""
Base-class of every element of the code coverage model: a reference to the element containing it, and to the report's
root.
"""
_PARENT_TYPE: ClassVar[tuple[type, ...]] #: The types a parent may have; assigned by each class having a parent.
_parent: Nullable[Base] #: The element containing this one, or ``None``.
_root: Nullable[CoverageSummary] #: The report's root, or ``None`` while the element isn't part of a report.
def __init__(self, *, parent: Nullable[Base] = None) -> None:
"""
Initialize an element with its parent and the parent's root.
The parent doesn't list the element yet: the class setting the field the parent stores it by - a name, a line
number - adds it with ``parent._AddElement(self)``.
:param parent: Optional, the element containing this one. Default: ``None``.
:raises TypeError: If parameter ``parent`` isn't of a type this class declares in :attr:`_PARENT_TYPE`.
"""
if parent is None:
self._parent = None
self._root = None
elif not isinstance(parent, self._PARENT_TYPE):
typeNames = " or ".join(f"'{parentType.__name__}'" for parentType in self._PARENT_TYPE)
ex = TypeError(f"Parameter 'parent' is not of type {typeNames}.")
ex.add_note(f"Got type '{getFullyQualifiedName(parent)}'.")
raise ex
else:
self._parent = parent
self._root = parent._root
@property
def Parent(self) -> Nullable[Base]:
"""
Property to access the element containing this one (:attr:`_parent`).
Assigning a parent adds this element to it, and sets the parent's root as the root of this element and of every
element below it.
:returns: The parent, or ``None``.
:raises ValueError: If ``None`` is assigned.
:raises TypeError: If the assigned parent isn't of a type this class declares in
:attr:`_PARENT_TYPE`.
:raises TypeError: If a parent is assigned to a :class:`CoverageSummary`, which has no parent.
:raises AlreadyInCoverageReportError: If the element already has a parent.
:raises DuplicateDirectoryError: If the assigned parent already contains a directory of this name.
:raises DuplicateFileError: If the assigned parent already contains a file of this name.
:raises DuplicateUnitError: If the assigned parent already contains a unit of this name.
:raises DuplicateLineError: If the assigned parent already contains a line of this line number.
"""
return self._parent
@Parent.setter
def Parent(self, parent: Base) -> None:
if parent is None:
raise ValueError("Parameter 'parent' is None.")
elif not isinstance(parent, self._PARENT_TYPE):
typeNames = " or ".join(f"'{parentType.__name__}'" for parentType in self._PARENT_TYPE)
ex = TypeError(f"Parameter 'parent' is not of type {typeNames}.")
ex.add_note(f"Got type '{getFullyQualifiedName(parent)}'.")
raise ex
elif self._parent is not None:
raise AlreadyInCoverageReportError(f"{getTypeName(self)} already has a parent.")
parent._AddElement(self)
self._parent = parent
self._SetRoot(parent._root)
@readonly
def Root(self) -> Nullable[CoverageSummary]:
"""
Read-only property to access the report's root (:attr:`_root`).
The root is maintained by :attr:`Parent`: assigning a parent sets it for this element and every element below it.
:returns: The root, or ``None`` while the element isn't part of a report.
"""
return self._root
def _SetRoot(self, root: Nullable[CoverageSummary]) -> None:
"""
Set the report's root of this element.
A class with child elements extends it to set the root of its children too.
:param root: The report's root, or ``None`` while the element isn't part of a report.
"""
self._root = root
@export
class BaseWithStatus(Base):
"""
Base-class of the elements with a coverage state and a count: lines, branches and units.
"""
_status: LineCoverageStatus #: The coverage state.
_coverageCount: Nullable[int] #: How often it ran, was taken or was called, if the report says.
def __init__(self, status: LineCoverageStatus, coverageCount: Nullable[int], *, parent: Nullable[Base]) -> None:
"""
Initialize the parent, the coverage state and the count.
A count of ``0`` is uncovered, a positive count covered.
:param status: The coverage state.
:param coverageCount: How often the line ran, the branch was taken or the unit was called; ``None``, if the report
doesn't say.
:param parent: The element containing this one, or ``None``.
:raises TypeError: If parameter ``parent`` isn't of a type the class declares in :attr:`_PARENT_TYPE`.
:raises ValueError: If parameter ``status`` is ``None``.
:raises TypeError: If parameter ``status`` isn't of type :class:`LineCoverageStatus`.
:raises TypeError: If parameter ``coverageCount`` isn't of type :class:`int`.
:raises ValueError: If parameter ``coverageCount`` is negative.
:raises ValueError: If parameter ``coverageCount`` contradicts parameter ``status``.
"""
super().__init__(parent=parent)
if status is None:
raise ValueError("Parameter 'status' is None.")
elif not isinstance(status, LineCoverageStatus):
ex = TypeError("Parameter 'status' is not of type 'LineCoverageStatus'.")
ex.add_note(f"Got type '{getFullyQualifiedName(status)}'.")
raise ex
if coverageCount is not None:
if not isinstance(coverageCount, int):
ex = TypeError("Parameter 'coverageCount' is not of type 'int'.")
ex.add_note(f"Got type '{getFullyQualifiedName(coverageCount)}'.")
raise ex
elif coverageCount < 0:
ex = ValueError("Parameter 'coverageCount' is negative.")
ex.add_note(f"Got value '{coverageCount}'.")
raise ex
elif (coverageCount == 0 and status in (LineCoverageStatus.Covered, LineCoverageStatus.PartiallyCovered)) or \
(coverageCount > 0 and status is LineCoverageStatus.Uncovered):
ex = ValueError("Parameter 'coverageCount' contradicts parameter 'status'.")
ex.add_note(f"Got count '{coverageCount}' for status '{status.name}'.")
raise ex
self._status = status
self._coverageCount = coverageCount
@readonly
def Status(self) -> LineCoverageStatus:
"""
Read-only property to access the coverage state (:attr:`_status`).
:returns: The coverage state; :attr:`LineCoverageStatus.Unknown`, if the report doesn't say.
"""
return self._status
@readonly
def CoverageCount(self) -> Nullable[int]:
"""
Read-only property to access how often it ran, was taken or was called (:attr:`_coverageCount`).
:returns: The count, or ``None`` if the report doesn't say.
"""
return self._coverageCount
@export
class CoverageCountersMixin(metaclass=ExtendedType, mixin=True):
"""
A mixin-class adding the counters of lines and branches, computed from the lines of a file or a unit, or summed over
a directory's children.
The counters are zero until :meth:`BaseWithPath.Aggregate` - of a directory or a file - or :meth:`Unit.Aggregate`
computed them.
"""
_totalLines: int #: Number of executable lines, without the excluded ones.
_coveredLines: int #: Number of executable lines, which ran.
_excludedLines: int #: Number of lines excluded from the measurement.
_partialLines: int #: Number of lines, which ran without taking all their branches.
_totalBranches: int #: Number of branches.
_coveredBranches: int #: Number of branches, which were taken.
def __init__(self) -> None:
"""
Initialize the counters to zero.
"""
self._ResetCounters()
def _ResetCounters(self) -> None:
"""
Set the counters to zero.
"""
self._totalLines = 0
self._coveredLines = 0
self._excludedLines = 0
self._partialLines = 0
self._totalBranches = 0
self._coveredBranches = 0
def _CountLines(self, lines: Iterable[Line]) -> None:
"""
Set the counters to the counts of lines.
A line's covered branches are those its :meth:`Line.Aggregate` computed.
:param lines: The lines.
"""
self._ResetCounters()
for line in lines:
if line._status is LineCoverageStatus.Excluded:
self._excludedLines += 1
continue
self._totalLines += 1
self._totalBranches += len(line._branches)
self._coveredBranches += line._coveredBranches
if line._status is LineCoverageStatus.Covered:
self._coveredLines += 1
elif line._status is LineCoverageStatus.PartiallyCovered:
self._coveredLines += 1
self._partialLines += 1
@readonly
def TotalLines(self) -> int:
"""
Read-only property to access the number of executable lines, without the excluded ones (:attr:`_totalLines`).
:returns: The number of executable lines.
"""
return self._totalLines
@readonly
def CoveredLines(self) -> int:
"""
Read-only property to access the number of executable lines, which ran (:attr:`_coveredLines`).
:returns: The number of covered lines, including the partially covered ones.
"""
return self._coveredLines
@readonly
def MissingLines(self) -> int:
"""
Read-only property to return the number of executable lines, which never ran.
:returns: :attr:`TotalLines` minus :attr:`CoveredLines`.
"""
return self._totalLines - self._coveredLines
@readonly
def ExcludedLines(self) -> int:
"""
Read-only property to access the number of lines excluded from the measurement (:attr:`_excludedLines`).
:returns: The number of excluded lines.
"""
return self._excludedLines
@readonly
def PartialLines(self) -> int:
"""
Read-only property to access the number of lines, which ran without taking all their branches
(:attr:`_partialLines`).
:returns: The number of partially covered lines.
"""
return self._partialLines
@readonly
def TotalBranches(self) -> int:
"""
Read-only property to access the number of branches (:attr:`_totalBranches`).
:returns: The number of branches.
"""
return self._totalBranches
@readonly
def CoveredBranches(self) -> int:
"""
Read-only property to access the number of branches, which were taken (:attr:`_coveredBranches`).
:returns: The number of covered branches.
"""
return self._coveredBranches
@readonly
def MissingBranches(self) -> int:
"""
Read-only property to return the number of branches, which were never taken.
:returns: :attr:`TotalBranches` minus :attr:`CoveredBranches`.
"""
return self._totalBranches - self._coveredBranches
@readonly
def LineCoverage(self) -> float:
"""
Read-only property to return the line coverage: the ratio of covered to executable lines.
:returns: The line coverage in range 0.0..1.0; ``1.0`` if there is no executable line.
"""
return 1.0 if self._totalLines == 0 else self._coveredLines / self._totalLines
@readonly
def BranchCoverage(self) -> float:
"""
Read-only property to return the branch coverage: the ratio of taken branches to all branches.
:returns: The branch coverage in range 0.0..1.0; ``1.0`` if there is no branch.
"""
return 1.0 if self._totalBranches == 0 else self._coveredBranches / self._totalBranches
@readonly
def Coverage(self) -> float:
"""
Read-only property to return the combined coverage of lines and branches, as coverage.py computes it.
:returns: Covered lines plus taken branches, divided by executable lines plus branches, in range 0.0..1.0;
``1.0`` if there is neither.
"""
total = self._totalLines + self._totalBranches
return 1.0 if total == 0 else (self._coveredLines + self._coveredBranches) / total
def _AggregateCounters(self, other: CoverageCountersMixin) -> None:
"""
Add the counters of another directory, file or unit to this one's.
:param other: The other directory, file or unit, aggregated.
"""
self._totalLines += other._totalLines
self._coveredLines += other._coveredLines
self._excludedLines += other._excludedLines
self._partialLines += other._partialLines
self._totalBranches += other._totalBranches
self._coveredBranches += other._coveredBranches
@export
class BaseWithPath(Base, CoverageCountersMixin):
"""
Base-class of the physical hierarchy - directories and source files -: a name, a path below the report's root, and
the counters.
Its parent is the :class:`Directory` containing it.
"""
_name: str #: Name of the directory or file.
def __init__(self, name: str, *, parent: Nullable[Directory]) -> None:
"""
Initialize the parent, the name and the counters.
:param name: Name of the directory or file.
:param parent: The directory containing this one, or ``None``.
:raises TypeError: If parameter ``parent`` isn't of type :class:`Directory`.
:raises ValueError: If parameter ``name`` is ``None``.
:raises TypeError: If parameter ``name`` isn't of type :class:`str`.
:raises ValueError: If parameter ``name`` is empty.
"""
super().__init__(parent=parent)
CoverageCountersMixin.__init__(self)
if name is None:
raise ValueError("Parameter 'name' is None.")
elif not isinstance(name, str):
ex = TypeError("Parameter 'name' is not of type 'str'.")
ex.add_note(f"Got type '{getFullyQualifiedName(name)}'.")
raise ex
elif name == "":
raise ValueError("Parameter 'name' is empty.")
self._name = name
@readonly
def Name(self) -> str:
"""
Read-only property to access the name of the directory or file (:attr:`_name`).
:returns: The name.
"""
return self._name
@readonly
def Path(self) -> Path:
"""
Read-only property to return the path below the root: the names of the parent directories and the own name.
A file ``Counter.vhdl`` in a directory ``src`` has the path ``src/Counter.vhdl``.
:returns: The path; the name, if there is no parent.
"""
if self._parent is None:
return Path(self._name)
return self._parent.Path / self._name
@abstractmethod
def Aggregate(self) -> None:
"""
Compute the counters.
"""
@export
class Directory(BaseWithPath):
"""
A directory: its directories and source files, and their summed counters.
"""
_PARENT_TYPE: ClassVar[tuple[type, ...]] #: A directory is in a directory; assigned below the class.
_directories: dict[str, Directory] #: The directories in this directory, by name.
_files: dict[str, File] #: The source files in this directory, by name.
def __init__(self, name: str, *, parent: Nullable[Directory] = None) -> None:
"""
Initialize a directory, and add it to its parent directory.
:param name: Name of the directory.
:param parent: Optional, the directory containing this one. Default: ``None``.
:raises TypeError: If parameter ``parent`` isn't of type :class:`Directory`.
:raises ValueError: If parameter ``name`` is ``None``.
:raises TypeError: If parameter ``name`` isn't of type :class:`str`.
:raises ValueError: If parameter ``name`` is empty.
:raises DuplicateDirectoryError: If the parent directory already contains a file or directory of this name.
"""
super().__init__(name, parent=parent)
self._directories = {}
self._files = {}
if parent is not None:
parent._AddElement(self)
def _AddElement(self, element: Directory | File) -> None:
"""
Add a directory or file, which names this directory as its parent.
:param element: The directory or file.
:raises DuplicateDirectoryError: If this directory already contains a directory of this name.
:raises DuplicateFileError: If this directory already contains a file of this name.
"""
if isinstance(element, Directory):
elements = self._directories
exception = DuplicateDirectoryError
else:
elements = self._files
exception = DuplicateFileError
if element._name in self._directories or element._name in self._files:
raise exception(f"Directory '{self.Path.as_posix()}' already contains '{element._name}'.")
elements[element._name] = element
def _SetRoot(self, root: Nullable[CoverageSummary]) -> None:
"""
Set the report's root of this directory, and of the directories and files in it.
:param root: The report's root, or ``None`` while the directory isn't part of a report.
"""
super()._SetRoot(root)
for directory in self._directories.values():
directory._SetRoot(root)
for file in self._files.values():
file._SetRoot(root)
@readonly
def Directories(self) -> dict[str, Directory]:
"""
Read-only property to access the directories in this directory (:attr:`_directories`).
:returns: The directories, by name.
"""
return self._directories
@readonly
def Files(self) -> dict[str, File]:
"""
Read-only property to access the source files in this directory (:attr:`_files`).
:returns: The files, by name.
"""
return self._files
@readonly
def FileCount(self) -> int:
"""
Read-only property to return the number of source files in this directory and below.
:returns: The number of files.
"""
return len(self._files) + sum(directory.FileCount for directory in self._directories.values())
def GetOrAddFile(self, path: Path | str) -> File:
"""
Return the source file at a path below this directory, adding it and the directories on its way, if missing.
A backslash in a string path separates directories too, as a report written on Windows has them.
:param path: The file's path relative to this directory, e.g. ``src/Counter.vhdl``.
:returns: The file.
:raises ValueError: If parameter ``path`` is ``None``.
:raises TypeError: If parameter ``path`` isn't of type :class:`~pathlib.Path` or :class:`str`.
:raises ValueError: If parameter ``path`` names no file.
:raises CodeCoverageError: If a part of the path is a file instead of a directory, or the file's name is a
directory's.
"""
if path is None:
raise ValueError("Parameter 'path' is None.")
elif isinstance(path, str):
path = Path(path.replace("\\", "/"))
elif not isinstance(path, Path):
ex = TypeError("Parameter 'path' is not of type 'Path' or 'str'.")
ex.add_note(f"Got type '{getFullyQualifiedName(path)}'.")
raise ex
parts = [part for part in path.parts if part not in ("", ".", path.anchor)]
if len(parts) == 0:
ex = ValueError("Parameter 'path' names no file.")
ex.add_note(f"Got path '{path}'.")
raise ex
directory = self
for part in parts[:-1]:
if part in directory._files:
raise CodeCoverageError(f"'{(directory.Path / part).as_posix()}' is a file, not a directory.")
elif (subdirectory := directory._directories.get(part)) is None:
subdirectory = Directory(part, parent=directory)
directory = subdirectory
if (file := directory._files.get(parts[-1])) is None:
file = File(parts[-1], parent=directory)
return file
def IterateFiles(self, predicate: Nullable[Callable[[File], bool]] = None) -> Generator[File, None, None]:
"""
Iterate all or selected source files in this directory and below.
A directory's files come before its directories' files, each in the order they were added. If parameter
``predicate`` is not None, the given filter function is used to skip files in the generator.
:param predicate: Optional, filter function accepting any file and returning a boolean. Default: ``None``.
:returns: A generator of the files.
"""
if predicate is None:
yield from self._files.values()
for directory in self._directories.values():
yield from directory.IterateFiles()
else:
for file in self._files.values():
if predicate(file):
yield file
for directory in self._directories.values():
yield from directory.IterateFiles(predicate)
def Aggregate(self) -> None:
"""
Aggregate the directories and files in this directory, then sum their counters.
"""
self._ResetCounters()
for child in (*self._directories.values(), *self._files.values()):
child.Aggregate()
self._AggregateCounters(child)
def __repr__(self) -> str:
"""
Return a representation of the directory for debugging.
A directory ``src`` of 3 files reads ``<Directory src: 3 files, 75.0%>``.
:returns: The directory's path, its number of files and its line coverage.
"""
return f"<Directory {self.Path.as_posix()}: {self.FileCount} files, {self.LineCoverage:.1%}>"
Directory._PARENT_TYPE = (Directory, )
@export
class CoverageSummary(Directory):
"""
The root of a code coverage report: the directory the report's file paths are relative to, and the top-level units
of the logical hierarchy.
It is its own root.
"""
_sourceDirectories: list[Path] #: The directories the report names as where the sources were, if any.
_units: dict[str, Unit] #: The top-level units, by name.
def __init__(self, name: str, *, sourceDirectories: Nullable[Iterable[Path]] = None) -> None:
"""
Initialize the root of a code coverage report.
:param name: Name of the report, e.g. of the project measured.
:param sourceDirectories: Optional, the directories the report names as where the sources were. Default: none.
:raises ValueError: If parameter ``name`` is ``None``.
:raises TypeError: If parameter ``name`` isn't of type :class:`str`.
:raises ValueError: If parameter ``name`` is empty.
:raises TypeError: If parameter ``sourceDirectories`` isn't iterable.
:raises TypeError: If parameter ``sourceDirectories`` contains an element not of type :class:`~pathlib.Path`.
"""
super().__init__(name)
self._root = self
self._sourceDirectories = []
self._units = {}
if sourceDirectories is not None:
if not isinstance(sourceDirectories, Iterable):
ex = TypeError("Parameter 'sourceDirectories' is not iterable.")
ex.add_note(f"Got type '{getFullyQualifiedName(sourceDirectories)}'.")
raise ex
for sourceDirectory in sourceDirectories:
if not isinstance(sourceDirectory, Path):
ex = TypeError("Parameter 'sourceDirectories' contains an element not of type 'Path'.")
ex.add_note(f"Got type '{getFullyQualifiedName(sourceDirectory)}'.")
raise ex
self._sourceDirectories.append(sourceDirectory)
@Base.Parent.setter
def Parent(self, parent: None) -> None:
ex = TypeError(f"A '{getFullyQualifiedName(self)}' has no parent.")
ex.add_note(f"Got type '{getFullyQualifiedName(parent)}'.")
raise ex
def _AddElement(self, element: Directory | File | Unit) -> None:
"""
Add a top-level unit, directory or file, which names the report's root as its parent.
:param element: The unit, directory or file.
:raises DuplicateUnitError: If the root already contains a unit of this name.
:raises DuplicateDirectoryError: If the root already contains a directory of this name.
:raises DuplicateFileError: If the root already contains a file of this name.
"""
if not isinstance(element, Unit):
super()._AddElement(element)
elif element._name in self._units:
raise DuplicateUnitError(f"Unit '{element._name}' is added twice to '{self._name}'.")
else:
self._units[element._name] = element
@readonly
def Path(self) -> Path:
"""
Read-only property to return the path below the root, which is the root's own: ``.``.
So the paths of the directories and files below are relative to the root, without its name.
:returns: ``.``
"""
return Path(".")
@readonly
def SourceDirectories(self) -> list[Path]:
"""
Read-only property to access the directories the report names as where the sources were
(:attr:`_sourceDirectories`).
They are the paths on the machine the coverage was measured on, so they may not exist where the report is read.
:returns: The source directories; empty, if the report names none.
"""
return self._sourceDirectories
@readonly
def Units(self) -> dict[str, Unit]:
"""
Read-only property to access the top-level units of the logical hierarchy (:attr:`_units`).
:returns: The units, by name.
"""
return self._units
def IterateUnits(self, predicate: Nullable[Callable[[Unit], bool]] = None) -> Generator[Unit, None, None]:
"""
Iterate all or selected units of the logical hierarchy.
A unit comes before its units, each level in the order the units were added. If parameter ``predicate`` is not None,
the given filter function is used to skip units in the generator. A skipped unit's units are still iterated.
:param predicate: Optional, filter function accepting any unit and returning a boolean. Default: ``None``.
:returns: A generator of the units.
"""
for unit in self._units.values():
yield from unit.IterateUnits(predicate)
def Aggregate(self) -> None:
"""
Aggregate the physical hierarchy - directories and files -, then the units of the logical hierarchy.
"""
super().Aggregate()
for unit in self._units.values():
unit.Aggregate()
@export
class File(BaseWithPath):
"""
A source file: the coverage of its executable lines, and the units of the logical hierarchy it holds.
The lines are a list indexed by line number: index 0 is unused, and a line the report doesn't list - a comment, a
declaration - is ``None``. Lines are iterated in order, and looked up without hashing.
"""
_PARENT_TYPE: ClassVar[tuple[type, ...]] = (Directory, ) #: A file is in a directory.
_lines: list[Nullable[Line]] #: The executable lines by line number; ``None`` at index 0 and for gaps.
_lastLineNumber: int #: The last line number the report lists; ``0``, if it lists none.
_units: list[Unit] #: The units naming this file, in the order they were added.
def __init__(self, name: str, *, lines: Nullable[Iterable[Line]] = None, parent: Nullable[Directory] = None) -> None:
"""
Initialize a source file, and add it to its directory.
:param name: Name of the file.
:param lines: Optional, the executable lines. Default: ``None``.
:param parent: Optional, the directory containing the file. Default: ``None``.
:raises TypeError: If parameter ``parent`` isn't of type :class:`Directory`.
:raises ValueError: If parameter ``name`` is ``None``.
:raises TypeError: If parameter ``name`` isn't of type :class:`str`.
:raises ValueError: If parameter ``name`` is empty.
:raises DuplicateFileError: If the directory already contains a file or directory of this name.
:raises TypeError: If parameter ``lines`` isn't iterable.
:raises TypeError: If parameter ``lines`` contains an element not of type :class:`Line`.
:raises DuplicateLineError: If two lines have the same number.
"""
super().__init__(name, parent=parent)
self._units = []
if parent is not None:
parent._AddElement(self)
if lines is None:
self._lines = [None]
self._lastLineNumber = 0
elif not isinstance(lines, Iterable):
ex = TypeError("Parameter 'lines' is not iterable.")
ex.add_note(f"Got type '{getFullyQualifiedName(lines)}'.")
raise ex
else:
# check the lines and find the last line number, then allocate the list once at its final size
lineList = []
lastLineNumber = 0
for line in lines:
if not isinstance(line, Line):
ex = TypeError("Parameter 'lines' contains an element not of type 'Line'.")
ex.add_note(f"Got type '{getFullyQualifiedName(line)}'.")
raise ex
lineList.append(line)
if line._lineNumber > lastLineNumber:
lastLineNumber = line._lineNumber
fileLines = [None] * (lastLineNumber + 1)
for line in lineList:
lineNumber = line._lineNumber
if fileLines[lineNumber] is not None:
raise DuplicateLineError(f"Line {lineNumber} of file '{self.Path.as_posix()}' is added twice.")
fileLines[lineNumber] = line
line._parent = self
line._SetRoot(self._root)
self._lines = fileLines
self._lastLineNumber = lastLineNumber
def _AddElement(self, line: Line) -> None:
"""
Add a line, which names this file as its parent.
:param line: The line.
:raises DuplicateLineError: If the file already has a line of this number.
"""
lineNumber = line._lineNumber
if (gap := lineNumber - len(self._lines)) >= 0:
if gap > 0:
self._lines.extend([None] * gap)
self._lines.append(line)
elif self._lines[lineNumber] is None:
self._lines[lineNumber] = line
else:
raise DuplicateLineError(f"Line {lineNumber} of file '{self.Path.as_posix()}' is added twice.")
if lineNumber > self._lastLineNumber:
self._lastLineNumber = lineNumber
def _SetRoot(self, root: Nullable[CoverageSummary]) -> None:
"""
Set the report's root of this file, and of its lines.
:param root: The report's root, or ``None`` while the file isn't part of a report.
"""
super()._SetRoot(root)
for line in self.IterateLines():
line._SetRoot(root)
@readonly
def Lines(self) -> list[Nullable[Line]]:
"""
Read-only property to access the executable lines (:attr:`_lines`).
The list ends at the last line the report lists. To iterate only the listed lines, use :meth:`IterateLines`.
:returns: The lines, indexed by line number; ``None`` for index 0 and for a line the report doesn't list.
"""
return self._lines
@readonly
def LastLineNumber(self) -> int:
"""
Read-only property to access the number of the last line the report lists (:attr:`_lastLineNumber`).
:returns: The line number; ``0``, if the report lists no line.
"""
return self._lastLineNumber
def GetLine(self, lineNumber: int) -> Nullable[Line]:
"""
Return the line of a line number.
:param lineNumber: The line number, counted from 1.
:returns: The line, or ``None`` if the report doesn't list it.
:raises ValueError: If parameter ``lineNumber`` is ``None``.
:raises TypeError: If parameter ``lineNumber`` isn't of type :class:`int`.
:raises ValueError: If parameter ``lineNumber`` is less than 1.
:raises ValueError: If parameter ``lineNumber`` is beyond the last line the report lists (:attr:`LastLineNumber`).
"""
if lineNumber is None:
raise ValueError("Parameter 'lineNumber' is None.")
elif not isinstance(lineNumber, int):
ex = TypeError("Parameter 'lineNumber' is not of type 'int'.")
ex.add_note(f"Got type '{getFullyQualifiedName(lineNumber)}'.")
raise ex
elif lineNumber < 1:
ex = ValueError("Parameter 'lineNumber' is less than 1.")
ex.add_note(f"Got value '{lineNumber}'.")
raise ex
elif lineNumber > self._lastLineNumber:
ex = ValueError(f"Parameter 'lineNumber' is beyond the last line of file '{self.Path.as_posix()}'.")
ex.add_note(f"Got value '{lineNumber}' for {self._lastLineNumber} lines.")
raise ex from IndexError(f"Index {lineNumber} is out of range 1..{self._lastLineNumber}.")
return self._lines[lineNumber]
@readonly
def Units(self) -> list[Unit]:
"""
Read-only property to access the units naming this file (:attr:`_units`).
A Python file is named by its module, its classes and its functions.
:returns: The units.
"""
return self._units
def IterateLines(
self,
startLine: Nullable[Line] = None,
endLine: Nullable[Line] = None
) -> Generator[Line, None, None]:
"""
Iterate the executable lines of this file from a first to a last line, both included, by line number.
:param startLine: Optional, the first line. Default: ``None``, the file's first line.
:param endLine: Optional, the last line. Default: ``None``, the file's last line.
:returns: A generator of the lines.
:raises TypeError: If parameter ``startLine`` isn't of type :class:`Line`.
:raises ValueError: If parameter ``startLine`` isn't a line of this file.
:raises TypeError: If parameter ``endLine`` isn't of type :class:`Line`.
:raises ValueError: If parameter ``endLine`` isn't a line of this file.
"""
if startLine is None:
first = 1
elif not isinstance(startLine, Line):
ex = TypeError("Parameter 'startLine' is not of type 'Line'.")
ex.add_note(f"Got type '{getFullyQualifiedName(startLine)}'.")
raise ex
elif startLine._parent is not self:
raise ValueError(f"Parameter 'startLine' is not a line of file '{self.Path.as_posix()}'.")
else:
first = startLine._lineNumber
if endLine is None:
last = self._lastLineNumber
elif not isinstance(endLine, Line):
ex = TypeError("Parameter 'endLine' is not of type 'Line'.")
ex.add_note(f"Got type '{getFullyQualifiedName(endLine)}'.")
raise ex
elif endLine._parent is not self:
raise ValueError(f"Parameter 'endLine' is not a line of file '{self.Path.as_posix()}'.")
else:
last = endLine._lineNumber
for lineNumber in range(first, last + 1):
if (line := self._lines[lineNumber]) is not None:
yield line
def Aggregate(self) -> None:
"""
Aggregate the file's lines, then compute the counters from them.
"""
lines = list(self.IterateLines())
for line in lines:
line.Aggregate()
self._CountLines(lines)
def __repr__(self) -> str:
"""
Return a representation of the file for debugging.
A file ``src/Counter.vhdl`` reads ``<File src/Counter.vhdl: 80.0%>``.
:returns: The file's path and line coverage.
"""
return f"<File {self.Path.as_posix()}: {self.LineCoverage:.1%}>"
@export
class Line(BaseWithStatus):
"""
The coverage of an executable line: its coverage state, how often it ran - if the report says -, and its branches.
A report lists only executable lines; a line it doesn't list - a comment, a declaration - has no :class:`Line`. Its
parent is the :class:`File` it is in.
"""
_PARENT_TYPE: ClassVar[tuple[type, ...]] = (File, ) #: A line is in a file.
_lineNumber: int #: Line number, counted from 1.
_branches: list[Branch] #: The branches starting at this line.
_coveredBranches: int #: Number of branches, which were taken; zero until :meth:`Aggregate` computed it.
def __init__(
self,
lineNumber: int,
status: LineCoverageStatus,
coverageCount: Nullable[int] = None,
branches: Nullable[Iterable[Branch]] = None,
*,
parent: Nullable[File] = None
) -> None:
"""
Initialize a line's coverage, and add it to its file.
:param lineNumber: Line number, counted from 1.
:param status: Coverage state of the line.
:param coverageCount: Optional, how often the line ran, if the report says. Default: ``None``.
:param branches: Optional, the branches starting at this line. Default: ``None``.
:param parent: Optional, the file the line is in. Default: ``None``.
:raises TypeError: If parameter ``parent`` isn't of type :class:`File`.
:raises ValueError: If parameter ``status`` is ``None``.
:raises TypeError: If parameter ``status`` isn't of type :class:`LineCoverageStatus`.
:raises TypeError: If parameter ``coverageCount`` isn't of type :class:`int`.
:raises ValueError: If parameter ``coverageCount`` is negative.
:raises ValueError: If parameter ``coverageCount`` contradicts parameter ``status``.
:raises ValueError: If parameter ``lineNumber`` is ``None``.
:raises TypeError: If parameter ``lineNumber`` isn't of type :class:`int`.
:raises ValueError: If parameter ``lineNumber`` is less than 1.
:raises DuplicateLineError: If the file already has a line of this number.
:raises TypeError: If parameter ``branches`` isn't iterable.
:raises TypeError: If parameter ``branches`` contains an element not of type :class:`Branch`.
"""
super().__init__(status, coverageCount, parent=parent)
if lineNumber is None:
raise ValueError("Parameter 'lineNumber' is None.")
elif not isinstance(lineNumber, int):
ex = TypeError("Parameter 'lineNumber' is not of type 'int'.")
ex.add_note(f"Got type '{getFullyQualifiedName(lineNumber)}'.")
raise ex
elif lineNumber < 1:
ex = ValueError("Parameter 'lineNumber' is less than 1.")
ex.add_note(f"Got value '{lineNumber}'.")
raise ex
self._lineNumber = lineNumber
self._branches = []
self._coveredBranches = 0
if parent is not None:
parent._AddElement(self)
if branches is not None:
if not isinstance(branches, Iterable):
ex = TypeError("Parameter 'branches' is not iterable.")
ex.add_note(f"Got type '{getFullyQualifiedName(branches)}'.")
raise ex
for branch in branches:
if not isinstance(branch, Branch):
ex = TypeError("Parameter 'branches' contains an element not of type 'Branch'.")
ex.add_note(f"Got type '{getFullyQualifiedName(branch)}'.")
raise ex
branch._parent = self
branch._root = self._root
self._branches.append(branch)
def _AddElement(self, branch: Branch) -> None:
"""
Add a branch, which names this line as its parent.
:param branch: The branch.
"""
self._branches.append(branch)
def _SetRoot(self, root: Nullable[CoverageSummary]) -> None:
"""
Set the report's root of this line, and of its branches.
:param root: The report's root, or ``None`` while the line isn't part of a report.
"""
super()._SetRoot(root)
for branch in self._branches:
branch._SetRoot(root)
@readonly
def LineNumber(self) -> int:
"""
Read-only property to access the line number (:attr:`_lineNumber`).
:returns: The line number, counted from 1.
"""
return self._lineNumber
@readonly
def Branches(self) -> list[Branch]:
"""
Read-only property to access the branches starting at this line (:attr:`_branches`).
:returns: The branches; empty for a line, which doesn't branch.
"""
return self._branches
@readonly
def CoveredBranches(self) -> int:
"""
Read-only property to access the number of this line's branches, which were taken (:attr:`_coveredBranches`).
:returns: The number of branches with state :attr:`LineCoverageStatus.Covered`; zero until :meth:`Aggregate`
computed it.
"""
return self._coveredBranches
def Aggregate(self) -> None:
"""
Compute the number of this line's branches, which were taken.
"""
self._coveredBranches = sum(1 for branch in self._branches if branch._status is LineCoverageStatus.Covered)
def __repr__(self) -> str:
"""
Return a representation of the line's coverage for debugging.
Line 12 with one of two branches taken reads ``<Line 12: PartiallyCovered (1/2 branches)>``.
:returns: The line number, the state and the branches.
"""
branches = f" ({self.CoveredBranches}/{len(self._branches)} branches)" if len(self._branches) > 0 else ""
return f"<Line {self._lineNumber}: {self._status.name}{branches}>"
@export
class Branch(BaseWithStatus):
"""
A branch of a line: whether it was taken, how often - if the report says -, and where it goes - if the report says.
Its parent is the :class:`Line` it starts at.
"""
_PARENT_TYPE: ClassVar[tuple[type, ...]] = (Line, ) #: A branch starts at a line.
_target: Nullable[Line] #: The line the branch goes to, if the report says.
def __init__(
self,
status: LineCoverageStatus,
coverageCount: Nullable[int] = None,
target: Nullable[Line] = None,
*,
parent: Nullable[Line] = None
) -> None:
"""
Initialize a branch, and add it to its line.
:param status: Whether the branch was taken.
:param coverageCount: Optional, how often the branch was taken, if the report says. Default: ``None``.
:param target: Optional, the line the branch goes to, if the report says; ``None`` for an exit of a function.
Default: ``None``.
:param parent: Optional, the line the branch starts at. Default: ``None``.
:raises TypeError: If parameter ``parent`` isn't of type :class:`Line`.
:raises ValueError: If parameter ``status`` is ``None``.
:raises TypeError: If parameter ``status`` isn't of type :class:`LineCoverageStatus`.
:raises TypeError: If parameter ``coverageCount`` isn't of type :class:`int`.
:raises ValueError: If parameter ``coverageCount`` is negative.
:raises ValueError: If parameter ``coverageCount`` contradicts parameter ``status``.
:raises TypeError: If parameter ``target`` isn't of type :class:`Line`.
"""
super().__init__(status, coverageCount, parent=parent)
if target is not None and not isinstance(target, Line):
ex = TypeError("Parameter 'target' is not of type 'Line'.")
ex.add_note(f"Got type '{getFullyQualifiedName(target)}'.")
raise ex
self._target = target
if parent is not None:
parent._AddElement(self)
@readonly
def Target(self) -> Nullable[Line]:
"""
Read-only property to access the line the branch goes to (:attr:`_target`).
:returns: The line, or ``None`` if the report doesn't say or the branch exits the function.
"""
return self._target
@export
class Unit(BaseWithStatus, CoverageCountersMixin):
"""
Base-class of the logical hierarchy: a language unit - a package, a module, a class, a function, a method -, the
units it contains, and the lines it spans.
Its parent is the :class:`Unit` containing it, or the report's :class:`CoverageSummary`. A unit spans the lines of
its file from its first to its last line - a language construct wraps the constructs nested in it -, so the
physical and the logical hierarchy count the same lines. A unit without lines, e.g. a package of several files,
counts the lines of the units it contains, each line once.
"""
_PARENT_TYPE: ClassVar[tuple[type, ...]] #: A unit is in a unit or the report's root; assigned below the class.
_name: str #: Name of the unit.
_units: dict[str, Unit] #: The units this one contains, by name.
_file: Nullable[File] #: The source file the unit is in, if the report says.
_startLine: Nullable[Line] #: The unit's first line, if the report says.
_endLine: Nullable[Line] #: The unit's last line, if the report says.
def __init__(
self,
name: str,
*,
file: Nullable[File] = None,
startLine: Nullable[Line] = None,
endLine: Nullable[Line] = None,
status: LineCoverageStatus = LineCoverageStatus.Unknown,
coverageCount: Nullable[int] = None,
parent: Nullable[Unit | CoverageSummary] = None
) -> None:
"""
Initialize a unit, and add it to its file and to the unit or report containing it.
:param name: Name of the unit.
:param file: Optional, the source file the unit is in. Default: ``None``.
:param startLine: Optional, the unit's first line. Default: ``None``.
:param endLine: Optional, the unit's last line. Default: ``None``.
:param status: Optional, whether the unit was called. Default: :attr:`LineCoverageStatus.Unknown`.
:param coverageCount: Optional, how often the unit was called. Default: ``None``.
:param parent: Optional, the unit or report containing this unit. Default: ``None``.
:raises TypeError: If parameter ``parent`` isn't of type :class:`Unit` or :class:`CoverageSummary`.
:raises ValueError: If parameter ``status`` is ``None``.
:raises TypeError: If parameter ``status`` isn't of type :class:`LineCoverageStatus`.
:raises TypeError: If parameter ``coverageCount`` isn't of type :class:`int`.
:raises ValueError: If parameter ``coverageCount`` is negative.
:raises ValueError: If parameter ``coverageCount`` contradicts parameter ``status``.
:raises ValueError: If parameter ``name`` is ``None``.
:raises TypeError: If parameter ``name`` isn't of type :class:`str`.
:raises ValueError: If parameter ``name`` is empty.
:raises TypeError: If parameter ``file`` isn't of type :class:`File`.
:raises TypeError: If parameter ``startLine`` isn't of type :class:`Line`.
:raises ValueError: If parameter ``startLine`` isn't a line of parameter ``file``.
:raises TypeError: If parameter ``endLine`` isn't of type :class:`Line`.
:raises ValueError: If parameter ``endLine`` isn't a line of parameter ``file``.
:raises ValueError: If parameter ``endLine`` is before parameter ``startLine``.
:raises DuplicateUnitError: If the parent already contains a unit of this name.
"""
super().__init__(status, coverageCount, parent=parent)
CoverageCountersMixin.__init__(self)
if name is None:
raise ValueError("Parameter 'name' is None.")
elif not isinstance(name, str):
ex = TypeError("Parameter 'name' is not of type 'str'.")
ex.add_note(f"Got type '{getFullyQualifiedName(name)}'.")
raise ex
elif name == "":
raise ValueError("Parameter 'name' is empty.")
if file is not None and not isinstance(file, File):
ex = TypeError("Parameter 'file' is not of type 'File'.")
ex.add_note(f"Got type '{getFullyQualifiedName(file)}'.")
raise ex
if startLine is not None:
if not isinstance(startLine, Line):
ex = TypeError("Parameter 'startLine' is not of type 'Line'.")
ex.add_note(f"Got type '{getFullyQualifiedName(startLine)}'.")
raise ex
elif startLine._parent is not file:
raise ValueError("Parameter 'startLine' is not a line of parameter 'file'.")
if endLine is not None:
if not isinstance(endLine, Line):
ex = TypeError("Parameter 'endLine' is not of type 'Line'.")
ex.add_note(f"Got type '{getFullyQualifiedName(endLine)}'.")
raise ex
elif endLine._parent is not file:
raise ValueError("Parameter 'endLine' is not a line of parameter 'file'.")
elif startLine is not None and endLine._lineNumber < startLine._lineNumber:
ex = ValueError("Parameter 'endLine' is before parameter 'startLine'.")
ex.add_note(f"Got lines {startLine._lineNumber} to {endLine._lineNumber}.")
raise ex
self._name = name
self._units = {}
self._file = file
self._startLine = startLine
self._endLine = endLine
if parent is not None:
parent._AddElement(self)
if file is not None:
file._units.append(self)
def _AddElement(self, unit: Unit) -> None:
"""
Add a unit, which names this unit as its parent.
:param unit: The unit.
:raises DuplicateUnitError: If this unit already contains a unit of this name.
"""
if unit._name in self._units:
raise DuplicateUnitError(f"Unit '{unit._name}' is added twice to '{self._name}'.")
self._units[unit._name] = unit
def _SetRoot(self, root: Nullable[CoverageSummary]) -> None:
"""
Set the report's root of this unit, and of the units it contains.
:param root: The report's root, or ``None`` while the unit isn't part of a report.
"""
super()._SetRoot(root)
for unit in self._units.values():
unit._SetRoot(root)
@readonly
def Name(self) -> str:
"""
Read-only property to access the unit's name (:attr:`_name`).
:returns: The name.
"""
return self._name
@readonly
def QualifiedName(self) -> str:
"""
Read-only property to return the names of the units from the top down to this one, joined by ``.``.
A method ``Area`` of a class ``Circle`` in a module ``myPackage.Shapes`` has the qualified name
``myPackage.Shapes.Circle.Area``.
:returns: The qualified name.
"""
if isinstance(self._parent, Unit):
return f"{self._parent.QualifiedName}.{self._name}"
return self._name
@readonly
def Units(self) -> dict[str, Unit]:
"""
Read-only property to access the units this one contains (:attr:`_units`).
:returns: The units, by name.
"""
return self._units
@readonly
def File(self) -> Nullable[File]:
"""
Read-only property to access the source file the unit is in (:attr:`_file`).
:returns: The file, or ``None`` if the report doesn't say.
"""
return self._file
@readonly
def StartLine(self) -> Nullable[Line]:
"""
Read-only property to access the unit's first line (:attr:`_startLine`).
:returns: The line of the unit's file, or ``None`` if the report doesn't say.
"""
return self._startLine
@readonly
def EndLine(self) -> Nullable[Line]:
"""
Read-only property to access the unit's last line (:attr:`_endLine`).
:returns: The line of the unit's file, or ``None`` if the report doesn't say.
"""
return self._endLine
def IterateLines(self) -> Generator[Line, None, None]:
"""
Iterate the executable lines of this unit's file from its first to its last line, both included.
:returns: A generator of the lines; nothing, if the unit has no file, or no first or last line.
"""
if self._file is not None and self._startLine is not None and self._endLine is not None:
yield from self._file.IterateLines(self._startLine, self._endLine)
def IterateUnits(self, predicate: Nullable[Callable[[Unit], bool]] = None) -> Generator[Unit, None, None]:
"""
Iterate this unit and the units it contains, all or selected ones.
This unit comes first, then the units it contains, each level in the order the units were added. If parameter
``predicate`` is not None, the given filter function is used to skip units in the generator. A skipped unit's units
are still iterated.
:param predicate: Optional, filter function accepting any unit and returning a boolean. Default: ``None``.
:returns: A generator of the units.
"""
if predicate is None:
yield self
for unit in self._units.values():
yield from unit.IterateUnits()
else:
if predicate(self):
yield self
for unit in self._units.values():
yield from unit.IterateUnits(predicate)
def Aggregate(self) -> None:
"""
Aggregate the units this one contains, then compute the counters from the lines this unit spans.
A unit without first and last line counts the lines the units below it span, each line once. The lines are
aggregated by their files - :meth:`CoverageSummary.Aggregate` does that first.
"""
for unit in self._units.values():
unit.Aggregate()
if self._startLine is not None and self._endLine is not None:
self._CountLines(self.IterateLines())
else:
lines: dict[int, Line] = {}
for unit in self.IterateUnits():
lines.update((id(line), line) for line in unit.IterateLines())
self._CountLines(lines.values())
def __repr__(self) -> str:
"""
Return a representation of the unit for debugging.
A method ``Area`` of class ``Circle`` in module ``Shapes`` reads ``<Function Shapes.Circle.Area: 100.0%>``.
:returns: The unit's kind, qualified name and line coverage.
"""
return f"<{getTypeName(self)} {self.QualifiedName}: {self.LineCoverage:.1%}>"
Unit._PARENT_TYPE = (Unit, CoverageSummary)
@export
class Package(Unit):
"""
A package: a unit grouping modules.
Python and Java have packages, VHDL has libraries.
"""
@export
class Module(Unit):
"""
A module: a unit of a package.
A Python module is one, and so are a VHDL package and a VHDL entity.
"""
@export
class SourceFile(Unit):
"""
A source file as a unit, where the file is the language's unit.
A C translation unit is one, and so is a Bash or TCL script.
"""
@export
class Class(Unit):
"""
A class.
Python, Java and C++ have classes.
"""
@export
class Function(Unit):
"""
A function.
Python and C have functions, VHDL has functions and procedures.
"""
@export
class Method(Unit):
"""A method of a class."""
@export
@abstractclass
class Document(metaclass=ExtendedType, slots=True):
"""
A code coverage report file, which is read in two steps: analyzed, then converted.
A format's document derives from this class and mixes in the root of the format's model.
"""
_path: Path #: Path to the report file.
_analysisDuration: Nullable[timedelta] #: Duration of :meth:`Analyze`, or ``None`` before it ran.
_conversionDuration: Nullable[timedelta] #: Duration of :meth:`Convert`, or ``None`` before it ran.
def __init__(self, reportFile: Path) -> None:
"""
Initialize the report file.
:param reportFile: Path to the report file.
"""
self._path = reportFile
self._analysisDuration = None
self._conversionDuration = None
@readonly
def ReportFile(self) -> Path:
"""
Read-only property to access the path to the report file (:attr:`_path`).
:returns: The report file's path.
"""
return self._path
@readonly
def AnalysisDuration(self) -> Nullable[timedelta]:
"""
Read-only property to access the duration of :meth:`Analyze`: reading, parsing and validating the file
(:attr:`_analysisDuration`).
:returns: The duration, or ``None`` if the file wasn't analyzed yet.
"""
return self._analysisDuration
@readonly
def ModelConversionDuration(self) -> Nullable[timedelta]:
"""
Read-only property to access the duration of :meth:`Convert`: building the report format's model
(:attr:`_conversionDuration`).
:returns: The duration, or ``None`` if the content wasn't converted yet.
"""
return self._conversionDuration
@abstractmethod
def Analyze(self) -> None:
"""
Read, parse and validate the report file.
"""
@abstractmethod
def Convert(self) -> None:
"""
Convert the analyzed content to the report format's model.
"""
@abstractmethod
def ToCoverageSummary(self) -> CoverageSummary:
"""
Convert the report format's model to the common code coverage model, and aggregate it.
:returns: The report's root of the common model.
"""
|