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
|
# ==================================================================================================================== #
# _____ ____ _ _ ____ _ #
# _ __ _ _| ____| _ \ / \ / \ | _ \ ___ _ __ ___ _ __| |_ ___ #
# | '_ \| | | | _| | | | |/ _ \ / _ \ | |_) / _ \ '_ \ / _ \| '__| __/ __| #
# | |_) | |_| | |___| |_| / ___ \ / ___ \ _| _ < __/ |_) | (_) | | | |_\__ \ #
# | .__/ \__, |_____|____/_/ \_\/_/ \_(_)_| \_\___| .__/ \___/|_| \__|___/ #
# |_| |___/ |_| #
# ==================================================================================================================== #
# Authors: #
# Patrick Lehmann #
# #
# License: #
# ==================================================================================================================== #
# Copyright 2024-2026 Electronic Design Automation Abstraction (EDA²) #
# Copyright 2023-2023 Patrick Lehmann - Bötzingen, Germany #
# #
# 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 code documentation coverage data model for Python code.**
"""
from pathlib import Path
from typing import Optional as Nullable, Iterable, Dict, Union, Tuple, List
from docstr_coverage import analyze, ResultCollection
from docstr_coverage.result_collection import FileCount
from pyTooling.Decorators import export, readonly
from pyTooling.MetaClasses import ExtendedType
from pyEDAA.Reports.DocumentationCoverage import Class, Module, Package, CoverageState, DocCoverageException
@export
class Coverage(metaclass=ExtendedType, mixin=True):
"""
This base-class for :class:`ClassCoverage` and :class:`AggregatedCoverage` represents a basic set of documentation coverage metrics.
Besides the *total* number of coverable items, it distinguishes items as *excluded*, *ignored*, and *expected*. |br|
Expected items are further distinguished into *covered* and *uncovered* items. |br|
If no item is expected, then *coverage* is always 100 |%|.
All coverable items
total = excluded + ignored + expected
All expected items
expected = covered + uncovered
Coverage [0.00..1.00]
coverage = covered / expected
"""
_total: int
_excluded: int
_ignored: int
_expected: int
_covered: int
_uncovered: int
_coverage: float
def __init__(self) -> None:
self._total = 0
self._excluded = 0
self._ignored = 0
self._expected = 0
self._covered = 0
self._uncovered = 0
self._coverage = -1.0
@readonly
def Total(self) -> int:
"""
Read-only property to access the total number of documentable items.
:returns: Total number of items.
"""
return self._total
@readonly
def Excluded(self) -> int:
"""
Read-only property to access the number of items excluded from the analysis.
:returns: Number of excluded items.
"""
return self._excluded
@readonly
def Ignored(self) -> int:
"""
Read-only property to access the number of items ignored by the analysis.
:returns: Number of ignored items.
"""
return self._ignored
@readonly
def Expected(self) -> int:
"""
Read-only property to access the number of items expected to be documented.
:returns: Number of expected items.
"""
return self._expected
@readonly
def Covered(self) -> int:
"""
Read-only property to access the number of documented items.
:returns: Number of covered items.
"""
return self._covered
@readonly
def Uncovered(self) -> int:
"""
Read-only property to access the number of undocumented items.
:returns: Number of uncovered items.
"""
return self._uncovered
@readonly
def Coverage(self) -> float:
"""
Read-only property to access the ratio of covered to expected items.
:returns: Documentation coverage in the range 0.0 to 1.0.
"""
return self._coverage
def CalculateCoverage(self) -> None:
self._uncovered = self._expected - self._covered
if self._expected != 0:
self._coverage = self._covered / self._expected
else:
self._coverage = 1.0
def _CountCoverage(self, iterator: Iterable[CoverageState]) -> Tuple[int, int, int, int, int]:
total = 0
excluded = 0
ignored = 0
expected = 0
covered = 0
for coverageState in iterator:
if coverageState is CoverageState.Unknown:
raise Exception(f"")
total += 1
if CoverageState.Excluded in coverageState:
excluded += 1
elif CoverageState.Ignored in coverageState:
ignored += 1
expected += 1
if CoverageState.Covered in coverageState:
covered += 1
return total, excluded, ignored, expected, covered
@export
class AggregatedCoverage(Coverage, mixin=True):
"""
This base-class for :class:`ModuleCoverage` and :class:`PackageCoverage` represents an extended set of documentation coverage metrics, especially with aggregated metrics.
As inherited from :class:`~Coverage`, it provides the *total* number of coverable items, which are distinguished into
*excluded*, *ignored*, and *expected* items. |br|
Expected items are further distinguished into *covered* and *uncovered* items. |br|
If no item is expected, then *coverage* and *aggregated coverage* are always 100 |%|.
In addition, all previously mentioned metrics are collected as *aggregated...*, too. |br|
All coverable items
total = excluded + ignored + expected
All expected items
expected = covered + uncovered
Coverage [0.00..1.00]
coverage = covered / expected
"""
_file: Path
_aggregatedTotal: int
_aggregatedExcluded: int
_aggregatedIgnored: int
_aggregatedExpected: int
_aggregatedCovered: int
_aggregatedUncovered: int
_aggregatedCoverage: float
def __init__(self, file: Path) -> None:
super().__init__()
self._file = file
@readonly
def File(self) -> Path:
"""
Read-only property to access the file this coverage was computed from.
:returns: Path to the analyzed file.
"""
return self._file
@readonly
def AggregatedTotal(self) -> int:
"""
Read-only property to access the total number of documentable items, including all children.
:returns: Aggregated total number of items.
"""
return self._aggregatedTotal
@readonly
def AggregatedExcluded(self) -> int:
"""
Read-only property to access the number of excluded items, including all children.
:returns: Aggregated number of excluded items.
"""
return self._aggregatedExcluded
@readonly
def AggregatedIgnored(self) -> int:
"""
Read-only property to access the number of ignored items, including all children.
:returns: Aggregated number of ignored items.
"""
return self._aggregatedIgnored
@readonly
def AggregatedExpected(self) -> int:
"""
Read-only property to access the number of expected items, including all children.
:returns: Aggregated number of expected items.
"""
return self._aggregatedExpected
@readonly
def AggregatedCovered(self) -> int:
"""
Read-only property to access the number of documented items, including all children.
:returns: Aggregated number of covered items.
"""
return self._aggregatedCovered
@readonly
def AggregatedUncovered(self) -> int:
"""
Read-only property to access the number of undocumented items, including all children.
:returns: Aggregated number of uncovered items.
"""
return self._aggregatedUncovered
@readonly
def AggregatedCoverage(self) -> float:
"""
Read-only property to access the coverage ratio, including all children.
:returns: Aggregated documentation coverage in the range 0.0 to 1.0.
"""
return self._aggregatedCoverage
def Aggregate(self) -> None:
if self._aggregatedExpected != 0:
self._aggregatedCoverage = self._aggregatedCovered / self._aggregatedExpected
else:
self._aggregatedCoverage = 1.0
@export
class ClassCoverage(Class, Coverage):
"""
This class represents the class documentation coverage for Python classes.
"""
_fields: Dict[str, CoverageState]
_methods: Dict[str, CoverageState]
_classes: Dict[str, "ClassCoverage"]
def __init__(self, name: str, parent: Union["PackageCoverage", "ClassCoverage", None] = None) -> None:
super().__init__(name, parent)
Coverage.__init__(self)
if parent is not None:
parent._classes[name] = self
self._fields = {}
self._methods = {}
self._classes = {}
@readonly
def Fields(self) -> Dict[str, CoverageState]:
"""
Read-only property to access the coverage states of the class' fields.
:returns: Dictionary of field names and their coverage states.
"""
return self._fields
@readonly
def Methods(self) -> Dict[str, CoverageState]:
"""
Read-only property to access the coverage states of the class' methods.
:returns: Dictionary of method names and their coverage states.
"""
return self._methods
@readonly
def Classes(self) -> Dict[str, "ClassCoverage"]:
"""
Read-only property to access the class' nested classes.
:returns: Dictionary of class names and their coverage.
"""
return self._classes
def CalculateCoverage(self) -> None:
for cls in self._classes.values():
cls.CalculateCoverage()
self._total, self._excluded, self._ignored, self._expected, self._covered = \
self._CountCoverage(zip(
self._fields.values(),
self._methods.values()
))
super().CalculateCoverage()
def __str__(self) -> str:
return f"<ClassCoverage - tot:{self._total}, ex:{self._excluded}, ig:{self._ignored}, exp:{self._expected}, cov:{self._covered}, un:{self._uncovered} => {self._coverage:.1%}>"
@export
class ModuleCoverage(Module, AggregatedCoverage):
"""
This class represents the module documentation coverage for Python modules.
"""
_variables: Dict[str, CoverageState]
_functions: Dict[str, CoverageState]
_classes: Dict[str, ClassCoverage]
def __init__(self, name: str, file: Path, parent: Nullable["PackageCoverage"] = None) -> None:
super().__init__(name, parent)
AggregatedCoverage.__init__(self, file)
if parent is not None:
parent._modules[name] = self
self._file = file
self._variables = {}
self._functions = {}
self._classes = {}
@readonly
def Variables(self) -> Dict[str, CoverageState]:
"""
Read-only property to access the coverage states of the module's variables.
:returns: Dictionary of variable names and their coverage states.
"""
return self._variables
@readonly
def Functions(self) -> Dict[str, CoverageState]:
"""
Read-only property to access the coverage states of the module's functions.
:returns: Dictionary of function names and their coverage states.
"""
return self._functions
@readonly
def Classes(self) -> Dict[str, ClassCoverage]:
"""
Read-only property to access the module's classes.
:returns: Dictionary of class names and their coverage.
"""
return self._classes
def CalculateCoverage(self) -> None:
for cls in self._classes.values():
cls.CalculateCoverage()
self._total, self._excluded, self._ignored, self._expected, self._covered = \
self._CountCoverage(zip(
self._variables.values(),
self._functions.values()
))
super().CalculateCoverage()
def Aggregate(self) -> None:
self._aggregatedTotal = self._total
self._aggregatedExcluded = self._excluded
self._aggregatedIgnored = self._ignored
self._aggregatedExpected = self._expected
self._aggregatedCovered = self._covered
self._aggregatedUncovered = self._uncovered
for cls in self._classes.values():
self._aggregatedTotal += cls._total
self._aggregatedExcluded += cls._excluded
self._aggregatedIgnored += cls._ignored
self._aggregatedExpected += cls._expected
self._aggregatedCovered += cls._covered
self._aggregatedUncovered += cls._uncovered
super().Aggregate()
def __str__(self) -> str:
return f"<ModuleCoverage - tot:{self._total}|{self._aggregatedTotal}, ex:{self._excluded}|{self._aggregatedExcluded}, ig:{self._ignored}|{self._aggregatedIgnored}, exp:{self._expected}|{self._aggregatedExpected}, cov:{self._covered}|{self._aggregatedCovered}, un:{self._uncovered}|{self._aggregatedUncovered} => {self._coverage:.1%}|{self._aggregatedCoverage:.1%}>"
@export
class PackageCoverage(Package, AggregatedCoverage):
"""
This class represents the package documentation coverage for Python packages.
"""
_fileCount: int
_variables: Dict[str, CoverageState]
_functions: Dict[str, CoverageState]
_classes: Dict[str, ClassCoverage]
_modules: Dict[str, ModuleCoverage]
_packages: Dict[str, "PackageCoverage"]
def __init__(self, name: str, file: Path, parent: Nullable["PackageCoverage"] = None) -> None:
super().__init__(name, parent)
AggregatedCoverage.__init__(self, file)
if parent is not None:
parent._packages[name] = self
self._file = file
self._fileCount = 1
self._variables = {}
self._functions = {}
self._classes = {}
self._modules = {}
self._packages = {}
@readonly
def FileCount(self) -> int:
"""
Read-only property to access the number of Python files in this package.
:returns: Number of files.
"""
return self._fileCount
@readonly
def Variables(self) -> Dict[str, CoverageState]:
"""
Read-only property to access the coverage states of the package's variables.
:returns: Dictionary of variable names and their coverage states.
"""
return self._variables
@readonly
def Functions(self) -> Dict[str, CoverageState]:
"""
Read-only property to access the coverage states of the package's functions.
:returns: Dictionary of function names and their coverage states.
"""
return self._functions
@readonly
def Classes(self) -> Dict[str, ClassCoverage]:
"""
Read-only property to access the package's classes.
:returns: Dictionary of class names and their coverage.
"""
return self._classes
@readonly
def Modules(self) -> Dict[str, ModuleCoverage]:
"""
Read-only property to access the package's modules.
:returns: Dictionary of module names and their coverage.
"""
return self._modules
@readonly
def Packages(self) -> Dict[str, "PackageCoverage"]:
"""
Read-only property to access the package's sub-packages.
:returns: Dictionary of package names and their coverage.
"""
return self._packages
def __getitem__(self, key: str) -> Union["PackageCoverage", ModuleCoverage]:
try:
return self._modules[key]
except KeyError:
return self._packages[key]
def CalculateCoverage(self) -> None:
for cls in self._classes.values():
cls.CalculateCoverage()
for mod in self._modules.values():
mod.CalculateCoverage()
for pkg in self._packages.values():
pkg.CalculateCoverage()
self._total, self._excluded, self._ignored, self._expected, self._covered = \
self._CountCoverage(zip(
self._variables.values(),
self._functions.values()
))
super().CalculateCoverage()
def Aggregate(self) -> None:
self._fileCount = len(self._modules) + 1
self._aggregatedTotal = self._total
self._aggregatedExcluded = self._excluded
self._aggregatedIgnored = self._ignored
self._aggregatedExpected = self._expected
self._aggregatedCovered = self._covered
self._aggregatedUncovered = self._uncovered
for pkg in self._packages.values():
pkg.Aggregate()
self._fileCount += pkg._fileCount
self._aggregatedTotal += pkg._total
self._aggregatedExcluded += pkg._excluded
self._aggregatedIgnored += pkg._ignored
self._aggregatedExpected += pkg._expected
self._aggregatedCovered += pkg._covered
self._aggregatedUncovered += pkg._uncovered
for mod in self._modules.values():
mod.Aggregate()
self._aggregatedTotal += mod._total
self._aggregatedExcluded += mod._excluded
self._aggregatedIgnored += mod._ignored
self._aggregatedExpected += mod._expected
self._aggregatedCovered += mod._covered
self._aggregatedUncovered += mod._uncovered
super().Aggregate()
def __str__(self) -> str:
return f"<PackageCoverage - tot:{self._total}|{self._aggregatedTotal}, ex:{self._excluded}|{self._aggregatedExcluded}, ig:{self._ignored}|{self._aggregatedIgnored}, exp:{self._expected}|{self._aggregatedExpected}, cov:{self._covered}|{self._aggregatedCovered}, un:{self._uncovered}|{self._aggregatedUncovered} => {self._coverage:.1%}|{self._aggregatedCoverage:.1%}>"
@export
class DocStrCoverageError(DocCoverageException):
pass
@export
class DocStrCoverage(metaclass=ExtendedType):
"""
A wrapper class for the docstr_coverage package and it's analyzer producing a documentation coverage model.
"""
_packageName: str
_searchDirectory: Path
_moduleFiles: List[Path]
_coverageReport: ResultCollection
def __init__(self, packageName: str, directory: Path) -> None:
if not directory.exists():
raise DocStrCoverageError(f"Package source directory '{directory}' does not exist.") from FileNotFoundError(f"Directory '{directory}' does not exist.")
self._searchDirectory = directory
self._packageName = packageName
self._moduleFiles = [file for file in directory.glob("**/*.py")]
@readonly
def SearchDirectories(self) -> Path:
"""
Read-only property to access the directory the analysis searches for Python files.
:returns: Path to the search directory.
"""
return self._searchDirectory
@readonly
def PackageName(self) -> str:
"""
Read-only property to access the name of the analyzed package.
:returns: Name of the package.
"""
return self._packageName
@readonly
def ModuleFiles(self) -> List[Path]:
"""
Read-only property to access the Python files found in the search directory.
:returns: List of module file paths.
"""
return self._moduleFiles
@readonly
def CoverageReport(self) -> ResultCollection:
"""
Read-only property to access the raw report produced by ``docstr_coverage``.
:returns: The analyzer's result collection.
"""
return self._coverageReport
def Analyze(self) -> ResultCollection:
self._coverageReport: ResultCollection = analyze(self._moduleFiles, show_progress=False)
return self._coverageReport
def Convert(self) -> PackageCoverage:
rootPackageCoverage = PackageCoverage(self._packageName, self._searchDirectory / "__init__.py")
for key, value in self._coverageReport.files():
path: Path = key.relative_to(self._searchDirectory)
perFileResult: FileCount = value.count_aggregate()
moduleName = path.stem
modulePath = path.parent.parts
currentCoverageObject: AggregatedCoverage = rootPackageCoverage
for packageName in modulePath:
try:
currentCoverageObject = currentCoverageObject[packageName]
except KeyError:
currentCoverageObject = PackageCoverage(packageName, path, currentCoverageObject)
if moduleName != "__init__":
currentCoverageObject = ModuleCoverage(moduleName, path, currentCoverageObject)
currentCoverageObject._expected = perFileResult.needed
currentCoverageObject._covered = perFileResult.found
currentCoverageObject._uncovered = perFileResult.missing
if currentCoverageObject._expected != 0:
currentCoverageObject._coverage = currentCoverageObject._covered / currentCoverageObject._expected
else:
currentCoverageObject._coverage = 1.0
if currentCoverageObject._uncovered != currentCoverageObject._expected - currentCoverageObject._covered:
currentCoverageObject._coverage = -2.0
return rootPackageCoverage
|