Coverage for pyEDAA/Reports/CodeCoverage/__init__.py: 96%
640 statements
« prev ^ index » next coverage.py v7.18.0, created at 2026-12-04 01:07 +0000
« prev ^ index » next coverage.py v7.18.0, created at 2026-12-04 01:07 +0000
1# ==================================================================================================================== #
2# _____ ____ _ _ ____ _ #
3# _ __ _ _| ____| _ \ / \ / \ | _ \ ___ _ __ ___ _ __| |_ ___ #
4# | '_ \| | | | _| | | | |/ _ \ / _ \ | |_) / _ \ '_ \ / _ \| '__| __/ __| #
5# | |_) | |_| | |___| |_| / ___ \ / ___ \ _| _ < __/ |_) | (_) | | | |_\__ \ #
6# | .__/ \__, |_____|____/_/ \_\/_/ \_(_)_| \_\___| .__/ \___/|_| \__|___/ #
7# |_| |___/ |_| #
8# ==================================================================================================================== #
9# Authors: #
10# Patrick Lehmann #
11# #
12# License: #
13# ==================================================================================================================== #
14# Copyright 2021-2026 Electronic Design Automation Abstraction (EDA²) #
15# #
16# Licensed under the Apache License, Version 2.0 (the "License"); #
17# you may not use this file except in compliance with the License. #
18# You may obtain a copy of the License at #
19# #
20# http://www.apache.org/licenses/LICENSE-2.0 #
21# #
22# Unless required by applicable law or agreed to in writing, software #
23# distributed under the License is distributed on an "AS IS" BASIS, #
24# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. #
25# See the License for the specific language governing permissions and #
26# limitations under the License. #
27# #
28# SPDX-License-Identifier: Apache-2.0 #
29# ==================================================================================================================== #
30#
31"""
32Abstract data model of code coverage, the common model every report format is converted to.
34The model has two hierarchies over the same lines:
36* The **physical** hierarchy - :class:`CoverageSummary`, :class:`Directory`, :class:`File` - is built from the file
37 paths a report names. A file holds its executable lines; every format has them.
38* The **logical** hierarchy holds the language units a report names - :class:`Package`, :class:`Module`,
39 :class:`SourceFile`, :class:`Class`, :class:`Function`, :class:`Method` -, each spanning its file from a first to a
40 last :class:`Line`, so both hierarchies count the same lines.
42A :class:`Line` and a :class:`Branch` carry a :class:`LineCoverageStatus` and - if the report says - a count: how
43often the line ran, or the branch was taken. :meth:`CoverageSummary.Aggregate` computes the counters of every file,
44directory and unit.
46The report formats have models of their own, which convert to this one:
48.. seealso::
50 :mod:`pyEDAA.Reports.CodeCoverage.Cobertura`
51 |rarr| The Cobertura XML format, as written e.g. by coverage.py (``coverage xml``) or gcovr (``--cobertura``).
52 :mod:`pyEDAA.Reports.CodeCoverage.CoveragePy`
53 |rarr| coverage.py's JSON format (``coverage json``).
54 :mod:`pyEDAA.Reports.CodeCoverage.GHDL`
55 |rarr| GHDL's JSON coverage file (``ghdl -r --coverage``).
56 :mod:`pyEDAA.Reports.CodeCoverage.UCIS`
57 |rarr| The XML interchange format of the Accellera UCIS standard, as written e.g. by pyucis (``pyucis convert``).
58 :mod:`pyEDAA.Reports.CodeCoverage.Gcov`
59 |rarr| GCC's gcov JSON format (``gcov --json-format``).
60 :mod:`pyEDAA.Reports.CodeCoverage.LCOV`
61 |rarr| lcov's tracefile format, as written e.g. by lcov (``lcov --capture``) or llvm-cov
62 (``llvm-cov export -format=lcov``).
63 :mod:`pyEDAA.Reports.CodeCoverage.JaCoCo`
64 |rarr| JaCoCo's XML format, as written e.g. by Gradle's task ``jacocoTestReport``.
65 :mod:`pyEDAA.Reports.CodeCoverage.AldecUCDB`
66 |rarr| Aldec's UCDB XML format, as exported by ``acdb2xml`` of Riviera-PRO or Active-HDL.
67 :mod:`pyEDAA.Reports.CodeCoverage.QuestaSim`
68 |rarr| QuestaSim's code coverage report XML (``vcover report -xml -details``).
69 :mod:`pyEDAA.Reports.CodeCoverage.LLVM`
70 |rarr| LLVM's JSON code coverage export (``llvm-cov export``), e.g. of Clang's source-based code coverage.
71"""
72from __future__ import annotations
74from datetime import timedelta
75from enum import Enum
76from pathlib import Path
77from typing import Callable, ClassVar, Generator, Iterable, Optional as Nullable
79from pyTooling.Common import getFullyQualifiedName, getTypeName
80from pyTooling.Decorators import export, readonly
81from pyTooling.Exceptions import AlreadyInHierarchyError, DuplicateElementError
82from pyTooling.MetaClasses import ExtendedType, abstractclass, abstractmethod
84from pyEDAA.Reports import ReportException
87@export
88class CodeCoverageError(ReportException):
89 """Base-exception of the code coverage data model and its report formats."""
92@export
93class AlreadyInCoverageReportError(CodeCoverageError, AlreadyInHierarchyError):
94 """The exception is raised when an element is added to an element, but it already has a parent."""
97@export
98class DuplicateDirectoryError(CodeCoverageError, DuplicateElementError):
99 """The exception is raised when a directory already contains a directory or a file of the same name."""
102@export
103class DuplicateFileError(CodeCoverageError, DuplicateElementError):
104 """The exception is raised when a directory or a report already contains a file or a directory of the same name."""
107@export
108class DuplicateUnitError(CodeCoverageError, DuplicateElementError):
109 """The exception is raised when a unit or the report's root already contains a unit of the same name."""
112@export
113class DuplicateLineError(CodeCoverageError, DuplicateElementError):
114 """The exception is raised when a file already has a line of the same number."""
117@export
118class LineCoverageStatus(Enum):
119 """The coverage state of a line, a branch or a unit, as a report states it."""
121 Unknown = 0 #: The report doesn't say.
122 Uncovered = 1 #: The line never ran, the branch was never taken, the unit was never called.
123 PartiallyCovered = 2 #: The line ran, but not all of its branches were taken.
124 Covered = 3 #: The line ran, the branch was taken, the unit was called.
125 Excluded = 4 #: Excluded from the measurement, e.g. by a pragma comment.
128@export
129class Base(metaclass=ExtendedType, slots=True):
130 """
131 Base-class of every element of the code coverage model: a reference to the element containing it, and to the report's
132 root.
133 """
135 _PARENT_TYPE: ClassVar[tuple[type, ...]] #: The types a parent may have; assigned by each class having a parent.
137 _parent: Nullable[Base] #: The element containing this one, or ``None``.
138 _root: Nullable[CoverageSummary] #: The report's root, or ``None`` while the element isn't part of a report.
140 def __init__(self, *, parent: Nullable[Base] = None) -> None:
141 """
142 Initialize an element with its parent and the parent's root.
144 The parent doesn't list the element yet: the class setting the field the parent stores it by - a name, a line
145 number - adds it with ``parent._AddElement(self)``.
147 :param parent: Optional, the element containing this one. Default: ``None``.
148 :raises TypeError: If parameter ``parent`` isn't of a type this class declares in :attr:`_PARENT_TYPE`.
149 """
150 if parent is None:
151 self._parent = None
152 self._root = None
153 elif not isinstance(parent, self._PARENT_TYPE):
154 typeNames = " or ".join(f"'{parentType.__name__}'" for parentType in self._PARENT_TYPE)
155 ex = TypeError(f"Parameter 'parent' is not of type {typeNames}.")
156 ex.add_note(f"Got type '{getFullyQualifiedName(parent)}'.")
157 raise ex
158 else:
159 self._parent = parent
160 self._root = parent._root
162 @property
163 def Parent(self) -> Nullable[Base]:
164 """
165 Property to access the element containing this one (:attr:`_parent`).
167 Assigning a parent adds this element to it, and sets the parent's root as the root of this element and of every
168 element below it.
170 :returns: The parent, or ``None``.
171 :raises ValueError: If ``None`` is assigned.
172 :raises TypeError: If the assigned parent isn't of a type this class declares in
173 :attr:`_PARENT_TYPE`.
174 :raises TypeError: If a parent is assigned to a :class:`CoverageSummary`, which has no parent.
175 :raises AlreadyInCoverageReportError: If the element already has a parent.
176 :raises DuplicateDirectoryError: If the assigned parent already contains a directory of this name.
177 :raises DuplicateFileError: If the assigned parent already contains a file of this name.
178 :raises DuplicateUnitError: If the assigned parent already contains a unit of this name.
179 :raises DuplicateLineError: If the assigned parent already contains a line of this line number.
180 """
181 return self._parent
183 @Parent.setter
184 def Parent(self, parent: Base) -> None:
185 if parent is None:
186 raise ValueError("Parameter 'parent' is None.")
187 elif not isinstance(parent, self._PARENT_TYPE):
188 typeNames = " or ".join(f"'{parentType.__name__}'" for parentType in self._PARENT_TYPE)
189 ex = TypeError(f"Parameter 'parent' is not of type {typeNames}.")
190 ex.add_note(f"Got type '{getFullyQualifiedName(parent)}'.")
191 raise ex
192 elif self._parent is not None:
193 raise AlreadyInCoverageReportError(f"{getTypeName(self)} already has a parent.")
195 parent._AddElement(self)
196 self._parent = parent
197 self._SetRoot(parent._root)
199 @readonly
200 def Root(self) -> Nullable[CoverageSummary]:
201 """
202 Read-only property to access the report's root (:attr:`_root`).
204 The root is maintained by :attr:`Parent`: assigning a parent sets it for this element and every element below it.
206 :returns: The root, or ``None`` while the element isn't part of a report.
207 """
208 return self._root
210 def _SetRoot(self, root: Nullable[CoverageSummary]) -> None:
211 """
212 Set the report's root of this element.
214 A class with child elements extends it to set the root of its children too.
216 :param root: The report's root, or ``None`` while the element isn't part of a report.
217 """
218 self._root = root
221@export
222class BaseWithStatus(Base):
223 """
224 Base-class of the elements with a coverage state and a count: lines, branches and units.
225 """
227 _status: LineCoverageStatus #: The coverage state.
228 _coverageCount: Nullable[int] #: How often it ran, was taken or was called, if the report says.
230 def __init__(self, status: LineCoverageStatus, coverageCount: Nullable[int], *, parent: Nullable[Base]) -> None:
231 """
232 Initialize the parent, the coverage state and the count.
234 A count of ``0`` is uncovered, a positive count covered.
236 :param status: The coverage state.
237 :param coverageCount: How often the line ran, the branch was taken or the unit was called; ``None``, if the report
238 doesn't say.
239 :param parent: The element containing this one, or ``None``.
240 :raises ValueError: If parameter ``status`` is ``None``.
241 :raises TypeError: If parameter ``status`` isn't of type :class:`LineCoverageStatus`.
242 :raises TypeError: If parameter ``coverageCount`` isn't of type :class:`int`.
243 :raises ValueError: If parameter ``coverageCount`` is negative.
244 :raises ValueError: If parameter ``coverageCount`` contradicts parameter ``status``.
245 :raises TypeError: If parameter ``parent`` isn't of a type the class declares in :attr:`_PARENT_TYPE`.
246 """
247 super().__init__(parent=parent)
249 if status is None:
250 raise ValueError("Parameter 'status' is None.")
251 elif not isinstance(status, LineCoverageStatus):
252 ex = TypeError("Parameter 'status' is not of type 'LineCoverageStatus'.")
253 ex.add_note(f"Got type '{getFullyQualifiedName(status)}'.")
254 raise ex
256 if coverageCount is not None:
257 if not isinstance(coverageCount, int):
258 ex = TypeError("Parameter 'coverageCount' is not of type 'int'.")
259 ex.add_note(f"Got type '{getFullyQualifiedName(coverageCount)}'.")
260 raise ex
261 elif coverageCount < 0:
262 ex = ValueError("Parameter 'coverageCount' is negative.")
263 ex.add_note(f"Got value '{coverageCount}'.")
264 raise ex
265 elif (coverageCount == 0 and (status is LineCoverageStatus.Covered or \
266 status is LineCoverageStatus.PartiallyCovered)) or \
267 (coverageCount > 0 and status is LineCoverageStatus.Uncovered):
268 ex = ValueError("Parameter 'coverageCount' contradicts parameter 'status'.")
269 ex.add_note(f"Got count '{coverageCount}' for status '{status.name}'.")
270 raise ex
272 self._status = status
273 self._coverageCount = coverageCount
275 @readonly
276 def Status(self) -> LineCoverageStatus:
277 """
278 Read-only property to access the coverage state (:attr:`_status`).
280 :returns: The coverage state; :attr:`LineCoverageStatus.Unknown`, if the report doesn't say.
281 """
282 return self._status
284 @readonly
285 def CoverageCount(self) -> Nullable[int]:
286 """
287 Read-only property to access how often it ran, was taken or was called (:attr:`_coverageCount`).
289 :returns: The count, or ``None`` if the report doesn't say.
290 """
291 return self._coverageCount
294@export
295class CoverageCountersMixin(metaclass=ExtendedType, mixin=True):
296 """
297 A mixin-class adding the counters of lines and branches, computed from the lines of a file or a unit, or summed over
298 a directory's children.
300 The counters are zero until :meth:`BaseWithPath.Aggregate` - of a directory or a file - or :meth:`Unit.Aggregate`
301 computed them.
302 """
304 _totalLines: int #: Number of executable lines, without the excluded ones.
305 _coveredLines: int #: Number of executable lines, which ran.
306 _excludedLines: int #: Number of lines excluded from the measurement.
307 _partialLines: int #: Number of lines, which ran without taking all their branches.
308 _totalBranches: int #: Number of branches.
309 _coveredBranches: int #: Number of branches, which were taken.
311 def __init__(self) -> None:
312 """
313 Initialize the counters to zero.
314 """
315 self._ResetCounters()
317 def _ResetCounters(self) -> None:
318 """
319 Set the counters to zero.
320 """
321 self._totalLines = 0
322 self._coveredLines = 0
323 self._excludedLines = 0
324 self._partialLines = 0
325 self._totalBranches = 0
326 self._coveredBranches = 0
328 def _CountLines(self, lines: Iterable[Line]) -> None:
329 """
330 Set the counters to the counts of lines.
332 A line's covered branches are those its :meth:`Line.Aggregate` computed.
334 :param lines: The lines.
335 """
336 self._ResetCounters()
337 for line in lines:
338 if line._status is LineCoverageStatus.Excluded:
339 self._excludedLines += 1
340 continue
342 self._totalLines += 1
343 self._totalBranches += len(line._branches)
344 self._coveredBranches += line._coveredBranches
345 if line._status is LineCoverageStatus.Covered:
346 self._coveredLines += 1
347 elif line._status is LineCoverageStatus.PartiallyCovered:
348 self._coveredLines += 1
349 self._partialLines += 1
351 @readonly
352 def TotalLines(self) -> int:
353 """
354 Read-only property to access the number of executable lines, without the excluded ones (:attr:`_totalLines`).
356 :returns: The number of executable lines.
357 """
358 return self._totalLines
360 @readonly
361 def CoveredLines(self) -> int:
362 """
363 Read-only property to access the number of executable lines, which ran (:attr:`_coveredLines`).
365 :returns: The number of covered lines, including the partially covered ones.
366 """
367 return self._coveredLines
369 @readonly
370 def MissingLines(self) -> int:
371 """
372 Read-only property to return the number of executable lines, which never ran.
374 :returns: :attr:`TotalLines` minus :attr:`CoveredLines`.
375 """
376 return self._totalLines - self._coveredLines
378 @readonly
379 def ExcludedLines(self) -> int:
380 """
381 Read-only property to access the number of lines excluded from the measurement (:attr:`_excludedLines`).
383 :returns: The number of excluded lines.
384 """
385 return self._excludedLines
387 @readonly
388 def PartialLines(self) -> int:
389 """
390 Read-only property to access the number of lines, which ran without taking all their branches
391 (:attr:`_partialLines`).
393 :returns: The number of partially covered lines.
394 """
395 return self._partialLines
397 @readonly
398 def TotalBranches(self) -> int:
399 """
400 Read-only property to access the number of branches (:attr:`_totalBranches`).
402 :returns: The number of branches.
403 """
404 return self._totalBranches
406 @readonly
407 def CoveredBranches(self) -> int:
408 """
409 Read-only property to access the number of branches, which were taken (:attr:`_coveredBranches`).
411 :returns: The number of covered branches.
412 """
413 return self._coveredBranches
415 @readonly
416 def MissingBranches(self) -> int:
417 """
418 Read-only property to return the number of branches, which were never taken.
420 :returns: :attr:`TotalBranches` minus :attr:`CoveredBranches`.
421 """
422 return self._totalBranches - self._coveredBranches
424 @readonly
425 def LineCoverage(self) -> float:
426 """
427 Read-only property to return the line coverage: the ratio of covered to executable lines.
429 :returns: The line coverage in range 0.0..1.0; ``1.0`` if there is no executable line.
430 """
431 return 1.0 if self._totalLines == 0 else self._coveredLines / self._totalLines
433 @readonly
434 def BranchCoverage(self) -> float:
435 """
436 Read-only property to return the branch coverage: the ratio of taken branches to all branches.
438 :returns: The branch coverage in range 0.0..1.0; ``1.0`` if there is no branch.
439 """
440 return 1.0 if self._totalBranches == 0 else self._coveredBranches / self._totalBranches
442 @readonly
443 def Coverage(self) -> float:
444 """
445 Read-only property to return the combined coverage of lines and branches, as coverage.py computes it.
447 :returns: Covered lines plus taken branches, divided by executable lines plus branches, in range 0.0..1.0;
448 ``1.0`` if there is neither.
449 """
450 total = self._totalLines + self._totalBranches
451 return 1.0 if total == 0 else (self._coveredLines + self._coveredBranches) / total
453 def _AggregateCounters(self, other: CoverageCountersMixin) -> None:
454 """
455 Add the counters of another directory, file or unit to this one's.
457 :param other: The other directory, file or unit, aggregated.
458 """
459 self._totalLines += other._totalLines
460 self._coveredLines += other._coveredLines
461 self._excludedLines += other._excludedLines
462 self._partialLines += other._partialLines
463 self._totalBranches += other._totalBranches
464 self._coveredBranches += other._coveredBranches
467@export
468class BaseWithPath(Base, CoverageCountersMixin):
469 """
470 Base-class of the physical hierarchy - directories and source files -: a name, a path below the report's root, and
471 the counters.
473 Its parent is the :class:`Directory` containing it.
474 """
476 _name: str #: Name of the directory or file.
478 def __init__(self, name: str, *, parent: Nullable[Directory]) -> None:
479 """
480 Initialize the parent, the name and the counters.
482 :param name: Name of the directory or file.
483 :param parent: The directory containing this one, or ``None``.
484 :raises ValueError: If parameter ``name`` is ``None``.
485 :raises TypeError: If parameter ``name`` isn't of type :class:`str`.
486 :raises ValueError: If parameter ``name`` is empty.
487 :raises TypeError: If parameter ``parent`` isn't of type :class:`Directory`.
488 """
489 super().__init__(parent=parent)
490 CoverageCountersMixin.__init__(self)
492 if name is None:
493 raise ValueError("Parameter 'name' is None.")
494 elif not isinstance(name, str):
495 ex = TypeError("Parameter 'name' is not of type 'str'.")
496 ex.add_note(f"Got type '{getFullyQualifiedName(name)}'.")
497 raise ex
498 elif name == "":
499 raise ValueError("Parameter 'name' is empty.")
501 self._name = name
503 @readonly
504 def Name(self) -> str:
505 """
506 Read-only property to access the name of the directory or file (:attr:`_name`).
508 :returns: The name.
509 """
510 return self._name
512 @readonly
513 def Path(self) -> Path:
514 """
515 Read-only property to return the path below the root: the names of the parent directories and the own name.
517 A file ``Counter.vhdl`` in a directory ``src`` has the path ``src/Counter.vhdl``.
519 :returns: The path; the name, if there is no parent.
520 """
521 if self._parent is None:
522 return Path(self._name)
524 return self._parent.Path / self._name
526 @abstractmethod
527 def Aggregate(self) -> None:
528 """
529 Compute the counters.
530 """
533@export
534class Directory(BaseWithPath):
535 """
536 A directory: its directories and source files, and their summed counters.
537 """
539 _PARENT_TYPE: ClassVar[tuple[type, ...]] #: A directory is in a directory; assigned below the class.
541 _directories: dict[str, Directory] #: The directories in this directory, by name.
542 _files: dict[str, File] #: The source files in this directory, by name.
544 def __init__(self, name: str, *, parent: Nullable[Directory] = None) -> None:
545 """
546 Initialize a directory, and add it to its parent directory.
548 :param name: Name of the directory.
549 :param parent: Optional, the directory containing this one. Default: ``None``.
550 :raises ValueError: If parameter ``name`` is ``None``.
551 :raises TypeError: If parameter ``name`` isn't of type :class:`str`.
552 :raises ValueError: If parameter ``name`` is empty.
553 :raises TypeError: If parameter ``parent`` isn't of type :class:`Directory`.
554 :raises DuplicateDirectoryError: If the parent directory already contains a file or directory of this name.
555 """
556 super().__init__(name, parent=parent)
558 self._directories = {}
559 self._files = {}
561 if parent is not None:
562 parent._AddElement(self)
564 def _AddElement(self, element: Directory | File) -> None:
565 """
566 Add a directory or file, which names this directory as its parent.
568 :param element: The directory or file.
569 :raises DuplicateDirectoryError: If this directory already contains a directory of this name.
570 :raises DuplicateFileError: If this directory already contains a file of this name.
571 """
572 if isinstance(element, Directory):
573 elements = self._directories
574 exception = DuplicateDirectoryError
575 else:
576 elements = self._files
577 exception = DuplicateFileError
579 if element._name in self._directories or element._name in self._files:
580 raise exception(f"Directory '{self.Path.as_posix()}' already contains '{element._name}'.")
582 elements[element._name] = element
584 def _SetRoot(self, root: Nullable[CoverageSummary]) -> None:
585 """
586 Set the report's root of this directory, and of the directories and files in it.
588 :param root: The report's root, or ``None`` while the directory isn't part of a report.
589 """
590 super()._SetRoot(root)
591 for directory in self._directories.values():
592 directory._SetRoot(root)
594 for file in self._files.values():
595 file._SetRoot(root)
597 @readonly
598 def Directories(self) -> dict[str, Directory]:
599 """
600 Read-only property to access the directories in this directory (:attr:`_directories`).
602 :returns: The directories, by name.
603 """
604 return self._directories
606 @readonly
607 def Files(self) -> dict[str, File]:
608 """
609 Read-only property to access the source files in this directory (:attr:`_files`).
611 :returns: The files, by name.
612 """
613 return self._files
615 @readonly
616 def FileCount(self) -> int:
617 """
618 Read-only property to return the number of source files in this directory and below.
620 :returns: The number of files.
621 """
622 return len(self._files) + sum(directory.FileCount for directory in self._directories.values())
624 def GetOrAddFile(self, path: Path | str) -> File:
625 """
626 Return the source file at a path below this directory, adding it and the directories on its way, if missing.
628 A backslash in a string path separates directories too, as a report written on Windows has them.
630 :param path: The file's path relative to this directory, e.g. ``src/Counter.vhdl``.
631 :returns: The file.
632 :raises ValueError: If parameter ``path`` is ``None``.
633 :raises TypeError: If parameter ``path`` isn't of type :class:`~pathlib.Path` or :class:`str`.
634 :raises ValueError: If parameter ``path`` names no file.
635 :raises CodeCoverageError: If a part of the path is a file instead of a directory, or the file's name is a
636 directory's.
637 """
638 if path is None: 638 ↛ 639line 638 didn't jump to line 639 because the condition on line 638 was never true
639 raise ValueError("Parameter 'path' is None.")
640 elif isinstance(path, str):
641 path = Path(path.replace("\\", "/"))
642 elif not isinstance(path, Path):
643 ex = TypeError("Parameter 'path' is not of type 'Path' or 'str'.")
644 ex.add_note(f"Got type '{getFullyQualifiedName(path)}'.")
645 raise ex
647 anchor = path.anchor
648 parts = [part for part in path.parts if part != "" and part != "." and part != anchor]
649 if len(parts) == 0:
650 ex = ValueError("Parameter 'path' names no file.")
651 ex.add_note(f"Got path '{path}'.")
652 raise ex
654 directory = self
655 for part in parts[:-1]:
656 if part in directory._files:
657 raise CodeCoverageError(f"'{(directory.Path / part).as_posix()}' is a file, not a directory.")
658 elif (subdirectory := directory._directories.get(part)) is None:
659 subdirectory = Directory(part, parent=directory)
660 directory = subdirectory
662 if (file := directory._files.get(parts[-1])) is None:
663 file = File(parts[-1], parent=directory)
665 return file
667 def IterateFiles(self, predicate: Nullable[Callable[[File], bool]] = None) -> Generator[File, None, None]:
668 """
669 Iterate all or selected source files in this directory and below.
671 A directory's files come before its directories' files, each in the order they were added. If parameter
672 ``predicate`` is not None, the given filter function is used to skip files in the generator.
674 :param predicate: Optional, filter function accepting any file and returning a boolean. Default: ``None``.
675 :returns: A generator of the files.
676 """
677 if predicate is None:
678 yield from self._files.values()
679 for directory in self._directories.values():
680 yield from directory.IterateFiles()
681 else:
682 for file in self._files.values():
683 if predicate(file):
684 yield file
686 for directory in self._directories.values():
687 yield from directory.IterateFiles(predicate)
689 def Aggregate(self) -> None:
690 """
691 Aggregate the directories and files in this directory, then sum their counters.
692 """
693 self._ResetCounters()
694 for child in (*self._directories.values(), *self._files.values()):
695 child.Aggregate()
696 self._AggregateCounters(child)
698 def __repr__(self) -> str:
699 """
700 Return a representation of the directory for debugging.
702 A directory ``src`` of 3 files reads ``<Directory src: 3 files, 75.0%>``.
704 :returns: The directory's path, its number of files and its line coverage.
705 """
706 return f"<Directory {self.Path.as_posix()}: {self.FileCount} files, {self.LineCoverage:.1%}>"
709Directory._PARENT_TYPE = (Directory, )
712@export
713class CoverageSummary(Directory):
714 """
715 The root of a code coverage report: the directory the report's file paths are relative to, and the top-level units
716 of the logical hierarchy.
718 It is its own root.
719 """
721 _sourceDirectories: list[Path] #: The directories the report names as where the sources were, if any.
722 _units: dict[str, Unit] #: The top-level units, by name.
724 def __init__(self, name: str, *, sourceDirectories: Nullable[Iterable[Path]] = None) -> None:
725 """
726 Initialize the root of a code coverage report.
728 :param name: Name of the report, e.g. of the project measured.
729 :param sourceDirectories: Optional, the directories the report names as where the sources were. Default: none.
730 :raises ValueError: If parameter ``name`` is ``None``.
731 :raises TypeError: If parameter ``name`` isn't of type :class:`str`.
732 :raises ValueError: If parameter ``name`` is empty.
733 :raises TypeError: If parameter ``sourceDirectories`` isn't iterable.
734 :raises TypeError: If parameter ``sourceDirectories`` contains an element not of type :class:`~pathlib.Path`.
735 """
736 super().__init__(name)
738 self._root = self
739 self._sourceDirectories = sourceDirectoryList = []
740 self._units = {}
742 if sourceDirectories is not None:
743 if not isinstance(sourceDirectories, Iterable): 743 ↛ 744line 743 didn't jump to line 744 because the condition on line 743 was never true
744 ex = TypeError("Parameter 'sourceDirectories' is not iterable.")
745 ex.add_note(f"Got type '{getFullyQualifiedName(sourceDirectories)}'.")
746 raise ex
748 for sourceDirectory in sourceDirectories:
749 if not isinstance(sourceDirectory, Path):
750 ex = TypeError("Parameter 'sourceDirectories' contains an element not of type 'Path'.")
751 ex.add_note(f"Got type '{getFullyQualifiedName(sourceDirectory)}'.")
752 raise ex
754 sourceDirectoryList.append(sourceDirectory)
756 @Base.Parent.setter
757 def Parent(self, parent: None) -> None:
758 ex = TypeError(f"A '{getFullyQualifiedName(self)}' has no parent.")
759 ex.add_note(f"Got type '{getFullyQualifiedName(parent)}'.")
760 raise ex
762 def _AddElement(self, element: Directory | File | Unit) -> None:
763 """
764 Add a top-level unit, directory or file, which names the report's root as its parent.
766 :param element: The unit, directory or file.
767 :raises DuplicateUnitError: If the root already contains a unit of this name.
768 :raises DuplicateDirectoryError: If the root already contains a directory of this name.
769 :raises DuplicateFileError: If the root already contains a file of this name.
770 """
771 if not isinstance(element, Unit):
772 super()._AddElement(element)
773 elif element._name in self._units:
774 raise DuplicateUnitError(f"Unit '{element._name}' is added twice to '{self._name}'.")
775 else:
776 self._units[element._name] = element
778 @readonly
779 def Path(self) -> Path:
780 """
781 Read-only property to return the path below the root, which is the root's own: ``.``.
783 So the paths of the directories and files below are relative to the root, without its name.
785 :returns: ``.``
786 """
787 return Path(".")
789 @readonly
790 def SourceDirectories(self) -> list[Path]:
791 """
792 Read-only property to access the directories the report names as where the sources were
793 (:attr:`_sourceDirectories`).
795 They are the paths on the machine the coverage was measured on, so they may not exist where the report is read.
797 :returns: The source directories; empty, if the report names none.
798 """
799 return self._sourceDirectories
801 @readonly
802 def Units(self) -> dict[str, Unit]:
803 """
804 Read-only property to access the top-level units of the logical hierarchy (:attr:`_units`).
806 :returns: The units, by name.
807 """
808 return self._units
810 def IterateUnits(self, predicate: Nullable[Callable[[Unit], bool]] = None) -> Generator[Unit, None, None]:
811 """
812 Iterate all or selected units of the logical hierarchy.
814 A unit comes before its units, each level in the order the units were added. If parameter ``predicate`` is not None,
815 the given filter function is used to skip units in the generator. A skipped unit's units are still iterated.
817 :param predicate: Optional, filter function accepting any unit and returning a boolean. Default: ``None``.
818 :returns: A generator of the units.
819 """
820 for unit in self._units.values():
821 yield from unit.IterateUnits(predicate)
823 def Aggregate(self) -> None:
824 """
825 Aggregate the physical hierarchy - directories and files -, then the units of the logical hierarchy.
826 """
827 super().Aggregate()
828 for unit in self._units.values():
829 unit.Aggregate()
832@export
833class File(BaseWithPath):
834 """
835 A source file: the coverage of its executable lines, and the units of the logical hierarchy it holds.
837 The lines are a list indexed by line number: index 0 is unused, and a line the report doesn't list - a comment, a
838 declaration - is ``None``. Lines are iterated in order, and looked up without hashing.
839 """
841 _PARENT_TYPE: ClassVar[tuple[type, ...]] = (Directory, ) #: A file is in a directory.
843 _lines: list[Nullable[Line]] #: The executable lines by line number; ``None`` at index 0 and for gaps.
844 _lastLineNumber: int #: The last line number the report lists; ``0``, if it lists none.
845 _units: list[Unit] #: The units naming this file, in the order they were added.
847 def __init__(self, name: str, *, lines: Nullable[Iterable[Line]] = None, parent: Nullable[Directory] = None) -> None:
848 """
849 Initialize a source file, and add it to its directory.
851 :param name: Name of the file.
852 :param lines: Optional, the executable lines. Default: ``None``.
853 :param parent: Optional, the directory containing the file. Default: ``None``.
854 :raises ValueError: If parameter ``name`` is ``None``.
855 :raises TypeError: If parameter ``name`` isn't of type :class:`str`.
856 :raises ValueError: If parameter ``name`` is empty.
857 :raises TypeError: If parameter ``lines`` isn't iterable.
858 :raises TypeError: If parameter ``lines`` contains an element not of type :class:`Line`.
859 :raises TypeError: If parameter ``parent`` isn't of type :class:`Directory`.
860 :raises DuplicateFileError: If the directory already contains a file or directory of this name.
861 :raises DuplicateLineError: If two lines have the same number.
862 """
863 super().__init__(name, parent=parent)
865 self._units = []
867 if parent is not None:
868 parent._AddElement(self)
870 if lines is None:
871 self._lines = [None]
872 self._lastLineNumber = 0
873 elif not isinstance(lines, Iterable):
874 ex = TypeError("Parameter 'lines' is not iterable.")
875 ex.add_note(f"Got type '{getFullyQualifiedName(lines)}'.")
876 raise ex
877 else:
878 # check the lines and find the last line number, then allocate the list once at its final size
879 lineList = []
880 lastLineNumber = 0
881 for line in lines:
882 if not isinstance(line, Line):
883 ex = TypeError("Parameter 'lines' contains an element not of type 'Line'.")
884 ex.add_note(f"Got type '{getFullyQualifiedName(line)}'.")
885 raise ex
887 lineList.append(line)
888 if line._lineNumber > lastLineNumber:
889 lastLineNumber = line._lineNumber
891 fileLines = [None] * (lastLineNumber + 1)
892 for line in lineList:
893 lineNumber = line._lineNumber
894 if fileLines[lineNumber] is not None:
895 raise DuplicateLineError(f"Line {lineNumber} of file '{self.Path.as_posix()}' is added twice.")
897 fileLines[lineNumber] = line
898 line._parent = self
899 line._SetRoot(self._root)
901 self._lines = fileLines
902 self._lastLineNumber = lastLineNumber
904 def _AddElement(self, line: Line) -> None:
905 """
906 Add a line, which names this file as its parent.
908 :param line: The line.
909 :raises DuplicateLineError: If the file already has a line of this number.
910 """
911 lineNumber = line._lineNumber
912 if (gap := lineNumber - len(self._lines)) >= 0:
913 if gap > 0:
914 self._lines.extend([None] * gap)
916 self._lines.append(line)
917 elif self._lines[lineNumber] is None:
918 self._lines[lineNumber] = line
919 else:
920 raise DuplicateLineError(f"Line {lineNumber} of file '{self.Path.as_posix()}' is added twice.")
922 if lineNumber > self._lastLineNumber:
923 self._lastLineNumber = lineNumber
925 def _SetRoot(self, root: Nullable[CoverageSummary]) -> None:
926 """
927 Set the report's root of this file, and of its lines.
929 :param root: The report's root, or ``None`` while the file isn't part of a report.
930 """
931 super()._SetRoot(root)
932 for line in self.IterateLines():
933 line._SetRoot(root)
935 @readonly
936 def Lines(self) -> list[Nullable[Line]]:
937 """
938 Read-only property to access the executable lines (:attr:`_lines`).
940 The list ends at the last line the report lists. To iterate only the listed lines, use :meth:`IterateLines`.
942 :returns: The lines, indexed by line number; ``None`` for index 0 and for a line the report doesn't list.
943 """
944 return self._lines
946 @readonly
947 def LastLineNumber(self) -> int:
948 """
949 Read-only property to access the number of the last line the report lists (:attr:`_lastLineNumber`).
951 :returns: The line number; ``0``, if the report lists no line.
952 """
953 return self._lastLineNumber
955 def GetLine(self, lineNumber: int) -> Nullable[Line]:
956 """
957 Return the line of a line number.
959 :param lineNumber: The line number, counted from 1.
960 :returns: The line, or ``None`` if the report doesn't list it.
961 :raises ValueError: If parameter ``lineNumber`` is ``None``.
962 :raises TypeError: If parameter ``lineNumber`` isn't of type :class:`int`.
963 :raises ValueError: If parameter ``lineNumber`` is less than 1.
964 :raises ValueError: If parameter ``lineNumber`` is beyond the last line the report lists (:attr:`LastLineNumber`).
965 """
966 if lineNumber is None:
967 raise ValueError("Parameter 'lineNumber' is None.")
968 elif not isinstance(lineNumber, int):
969 ex = TypeError("Parameter 'lineNumber' is not of type 'int'.")
970 ex.add_note(f"Got type '{getFullyQualifiedName(lineNumber)}'.")
971 raise ex
972 elif lineNumber < 1:
973 ex = ValueError("Parameter 'lineNumber' is less than 1.")
974 ex.add_note(f"Got value '{lineNumber}'.")
975 raise ex
976 elif lineNumber > self._lastLineNumber:
977 ex = ValueError(f"Parameter 'lineNumber' is beyond the last line of file '{self.Path.as_posix()}'.")
978 ex.add_note(f"Got value '{lineNumber}' for {self._lastLineNumber} lines.")
979 raise ex from IndexError(f"Index {lineNumber} is out of range 1..{self._lastLineNumber}.")
981 return self._lines[lineNumber]
983 @readonly
984 def Units(self) -> list[Unit]:
985 """
986 Read-only property to access the units naming this file (:attr:`_units`).
988 A Python file is named by its module, its classes and its functions.
990 :returns: The units.
991 """
992 return self._units
994 def IterateLines(
995 self,
996 startLine: Nullable[Line] = None,
997 endLine: Nullable[Line] = None
998 ) -> Generator[Line, None, None]:
999 """
1000 Iterate the executable lines of this file from a first to a last line, both included, by line number.
1002 :param startLine: Optional, the first line. Default: ``None``, the file's first line.
1003 :param endLine: Optional, the last line. Default: ``None``, the file's last line.
1004 :returns: A generator of the lines.
1005 :raises TypeError: If parameter ``startLine`` isn't of type :class:`Line`.
1006 :raises ValueError: If parameter ``startLine`` isn't a line of this file.
1007 :raises TypeError: If parameter ``endLine`` isn't of type :class:`Line`.
1008 :raises ValueError: If parameter ``endLine`` isn't a line of this file.
1009 """
1010 if startLine is None:
1011 first = 1
1012 elif not isinstance(startLine, Line): 1012 ↛ 1013line 1012 didn't jump to line 1013 because the condition on line 1012 was never true
1013 ex = TypeError("Parameter 'startLine' is not of type 'Line'.")
1014 ex.add_note(f"Got type '{getFullyQualifiedName(startLine)}'.")
1015 raise ex
1016 elif startLine._parent is not self:
1017 raise ValueError(f"Parameter 'startLine' is not a line of file '{self.Path.as_posix()}'.")
1018 else:
1019 first = startLine._lineNumber
1021 if endLine is None:
1022 last = self._lastLineNumber
1023 elif not isinstance(endLine, Line): 1023 ↛ 1024line 1023 didn't jump to line 1024 because the condition on line 1023 was never true
1024 ex = TypeError("Parameter 'endLine' is not of type 'Line'.")
1025 ex.add_note(f"Got type '{getFullyQualifiedName(endLine)}'.")
1026 raise ex
1027 elif endLine._parent is not self: 1027 ↛ 1028line 1027 didn't jump to line 1028 because the condition on line 1027 was never true
1028 raise ValueError(f"Parameter 'endLine' is not a line of file '{self.Path.as_posix()}'.")
1029 else:
1030 last = endLine._lineNumber
1032 for lineNumber in range(first, last + 1):
1033 if (line := self._lines[lineNumber]) is not None:
1034 yield line
1036 def Aggregate(self) -> None:
1037 """
1038 Aggregate the file's lines, then compute the counters from them.
1039 """
1040 lines = list(self.IterateLines())
1041 for line in lines:
1042 line.Aggregate()
1044 self._CountLines(lines)
1046 def __repr__(self) -> str:
1047 """
1048 Return a representation of the file for debugging.
1050 A file ``src/Counter.vhdl`` reads ``<File src/Counter.vhdl: 80.0%>``.
1052 :returns: The file's path and line coverage.
1053 """
1054 return f"<File {self.Path.as_posix()}: {self.LineCoverage:.1%}>"
1057@export
1058class Line(BaseWithStatus):
1059 """
1060 The coverage of an executable line: its coverage state, how often it ran - if the report says -, and its branches.
1062 A report lists only executable lines; a line it doesn't list - a comment, a declaration - has no :class:`Line`. Its
1063 parent is the :class:`File` it is in.
1064 """
1066 _PARENT_TYPE: ClassVar[tuple[type, ...]] = (File, ) #: A line is in a file.
1068 _lineNumber: int #: Line number, counted from 1.
1069 _branches: list[Branch] #: The branches starting at this line.
1070 _coveredBranches: int #: Number of branches, which were taken; zero until :meth:`Aggregate` computed it.
1072 def __init__(
1073 self,
1074 lineNumber: int,
1075 status: LineCoverageStatus,
1076 coverageCount: Nullable[int] = None,
1077 branches: Nullable[Iterable[Branch]] = None,
1078 *,
1079 parent: Nullable[File] = None
1080 ) -> None:
1081 """
1082 Initialize a line's coverage, and add it to its file.
1084 :param lineNumber: Line number, counted from 1.
1085 :param status: Coverage state of the line.
1086 :param coverageCount: Optional, how often the line ran, if the report says. Default: ``None``.
1087 :param branches: Optional, the branches starting at this line. Default: ``None``.
1088 :param parent: Optional, the file the line is in. Default: ``None``.
1089 :raises ValueError: If parameter ``lineNumber`` is ``None``.
1090 :raises TypeError: If parameter ``lineNumber`` isn't of type :class:`int`.
1091 :raises ValueError: If parameter ``lineNumber`` is less than 1.
1092 :raises ValueError: If parameter ``status`` is ``None``.
1093 :raises TypeError: If parameter ``status`` isn't of type :class:`LineCoverageStatus`.
1094 :raises TypeError: If parameter ``coverageCount`` isn't of type :class:`int`.
1095 :raises ValueError: If parameter ``coverageCount`` is negative.
1096 :raises ValueError: If parameter ``coverageCount`` contradicts parameter ``status``.
1097 :raises TypeError: If parameter ``branches`` isn't iterable.
1098 :raises TypeError: If parameter ``branches`` contains an element not of type :class:`Branch`.
1099 :raises TypeError: If parameter ``parent`` isn't of type :class:`File`.
1100 :raises DuplicateLineError: If the file already has a line of this number.
1101 """
1102 super().__init__(status, coverageCount, parent=parent)
1104 if lineNumber is None:
1105 raise ValueError("Parameter 'lineNumber' is None.")
1106 elif not isinstance(lineNumber, int):
1107 ex = TypeError("Parameter 'lineNumber' is not of type 'int'.")
1108 ex.add_note(f"Got type '{getFullyQualifiedName(lineNumber)}'.")
1109 raise ex
1110 elif lineNumber < 1:
1111 ex = ValueError("Parameter 'lineNumber' is less than 1.")
1112 ex.add_note(f"Got value '{lineNumber}'.")
1113 raise ex
1115 self._lineNumber = lineNumber
1116 self._branches = branchList = []
1117 self._coveredBranches = 0
1119 if parent is not None:
1120 parent._AddElement(self)
1122 if branches is not None:
1123 if not isinstance(branches, Iterable): 1123 ↛ 1124line 1123 didn't jump to line 1124 because the condition on line 1123 was never true
1124 ex = TypeError("Parameter 'branches' is not iterable.")
1125 ex.add_note(f"Got type '{getFullyQualifiedName(branches)}'.")
1126 raise ex
1128 for branch in branches:
1129 if not isinstance(branch, Branch):
1130 ex = TypeError("Parameter 'branches' contains an element not of type 'Branch'.")
1131 ex.add_note(f"Got type '{getFullyQualifiedName(branch)}'.")
1132 raise ex
1134 branch._parent = self
1135 branch._root = self._root
1136 branchList.append(branch)
1138 def _AddElement(self, branch: Branch) -> None:
1139 """
1140 Add a branch, which names this line as its parent.
1142 :param branch: The branch.
1143 """
1144 self._branches.append(branch)
1146 def _SetRoot(self, root: Nullable[CoverageSummary]) -> None:
1147 """
1148 Set the report's root of this line, and of its branches.
1150 :param root: The report's root, or ``None`` while the line isn't part of a report.
1151 """
1152 super()._SetRoot(root)
1153 for branch in self._branches:
1154 branch._SetRoot(root)
1156 @readonly
1157 def LineNumber(self) -> int:
1158 """
1159 Read-only property to access the line number (:attr:`_lineNumber`).
1161 :returns: The line number, counted from 1.
1162 """
1163 return self._lineNumber
1165 @readonly
1166 def Branches(self) -> list[Branch]:
1167 """
1168 Read-only property to access the branches starting at this line (:attr:`_branches`).
1170 :returns: The branches; empty for a line, which doesn't branch.
1171 """
1172 return self._branches
1174 @readonly
1175 def CoveredBranches(self) -> int:
1176 """
1177 Read-only property to access the number of this line's branches, which were taken (:attr:`_coveredBranches`).
1179 :returns: The number of branches with state :attr:`LineCoverageStatus.Covered`; zero until :meth:`Aggregate`
1180 computed it.
1181 """
1182 return self._coveredBranches
1184 def Aggregate(self) -> None:
1185 """
1186 Compute the number of this line's branches, which were taken.
1187 """
1188 self._coveredBranches = sum(1 for branch in self._branches if branch._status is LineCoverageStatus.Covered)
1190 def __repr__(self) -> str:
1191 """
1192 Return a representation of the line's coverage for debugging.
1194 Line 12 with one of two branches taken reads ``<Line 12: PartiallyCovered (1/2 branches)>``.
1196 :returns: The line number, the state and the branches.
1197 """
1198 branches = f" ({self.CoveredBranches}/{len(self._branches)} branches)" if len(self._branches) > 0 else ""
1199 return f"<Line {self._lineNumber}: {self._status.name}{branches}>"
1202@export
1203class Branch(BaseWithStatus):
1204 """
1205 A branch of a line: whether it was taken, how often - if the report says -, and where it goes - if the report says.
1207 Its parent is the :class:`Line` it starts at.
1208 """
1210 _PARENT_TYPE: ClassVar[tuple[type, ...]] = (Line, ) #: A branch starts at a line.
1212 _target: Nullable[Line] #: The line the branch goes to, if the report says.
1214 def __init__(
1215 self,
1216 status: LineCoverageStatus,
1217 coverageCount: Nullable[int] = None,
1218 target: Nullable[Line] = None,
1219 *,
1220 parent: Nullable[Line] = None
1221 ) -> None:
1222 """
1223 Initialize a branch, and add it to its line.
1225 :param status: Whether the branch was taken.
1226 :param coverageCount: Optional, how often the branch was taken, if the report says. Default: ``None``.
1227 :param target: Optional, the line the branch goes to, if the report says; ``None`` for an exit of a function.
1228 Default: ``None``.
1229 :param parent: Optional, the line the branch starts at. Default: ``None``.
1230 :raises ValueError: If parameter ``status`` is ``None``.
1231 :raises TypeError: If parameter ``status`` isn't of type :class:`LineCoverageStatus`.
1232 :raises TypeError: If parameter ``coverageCount`` isn't of type :class:`int`.
1233 :raises ValueError: If parameter ``coverageCount`` is negative.
1234 :raises ValueError: If parameter ``coverageCount`` contradicts parameter ``status``.
1235 :raises TypeError: If parameter ``target`` isn't of type :class:`Line`.
1236 :raises TypeError: If parameter ``parent`` isn't of type :class:`Line`.
1237 """
1238 super().__init__(status, coverageCount, parent=parent)
1240 if target is not None and not isinstance(target, Line):
1241 ex = TypeError("Parameter 'target' is not of type 'Line'.")
1242 ex.add_note(f"Got type '{getFullyQualifiedName(target)}'.")
1243 raise ex
1245 self._target = target
1247 if parent is not None:
1248 parent._AddElement(self)
1250 @readonly
1251 def Target(self) -> Nullable[Line]:
1252 """
1253 Read-only property to access the line the branch goes to (:attr:`_target`).
1255 :returns: The line, or ``None`` if the report doesn't say or the branch exits the function.
1256 """
1257 return self._target
1260@export
1261class Unit(BaseWithStatus, CoverageCountersMixin):
1262 """
1263 Base-class of the logical hierarchy: a language unit - a package, a module, a class, a function, a method -, the
1264 units it contains, and the lines it spans.
1266 Its parent is the :class:`Unit` containing it, or the report's :class:`CoverageSummary`. A unit spans the lines of
1267 its file from its first to its last line - a language construct wraps the constructs nested in it -, so the
1268 physical and the logical hierarchy count the same lines. A unit without lines, e.g. a package of several files,
1269 counts the lines of the units it contains, each line once.
1270 """
1272 _PARENT_TYPE: ClassVar[tuple[type, ...]] #: A unit is in a unit or the report's root; assigned below the class.
1274 _name: str #: Name of the unit.
1275 _units: dict[str, Unit] #: The units this one contains, by name.
1276 _file: Nullable[File] #: The source file the unit is in, if the report says.
1277 _startLine: Nullable[Line] #: The unit's first line, if the report says.
1278 _endLine: Nullable[Line] #: The unit's last line, if the report says.
1280 def __init__(
1281 self,
1282 name: str,
1283 *,
1284 file: Nullable[File] = None,
1285 startLine: Nullable[Line] = None,
1286 endLine: Nullable[Line] = None,
1287 status: LineCoverageStatus = LineCoverageStatus.Unknown,
1288 coverageCount: Nullable[int] = None,
1289 parent: Nullable[Unit | CoverageSummary] = None
1290 ) -> None:
1291 """
1292 Initialize a unit, and add it to its file and to the unit or report containing it.
1294 :param name: Name of the unit.
1295 :param file: Optional, the source file the unit is in. Default: ``None``.
1296 :param startLine: Optional, the unit's first line. Default: ``None``.
1297 :param endLine: Optional, the unit's last line. Default: ``None``.
1298 :param status: Optional, whether the unit was called. Default: :attr:`LineCoverageStatus.Unknown`.
1299 :param coverageCount: Optional, how often the unit was called. Default: ``None``.
1300 :param parent: Optional, the unit or report containing this unit. Default: ``None``.
1301 :raises ValueError: If parameter ``name`` is ``None``.
1302 :raises TypeError: If parameter ``name`` isn't of type :class:`str`.
1303 :raises ValueError: If parameter ``name`` is empty.
1304 :raises TypeError: If parameter ``file`` isn't of type :class:`File`.
1305 :raises TypeError: If parameter ``startLine`` isn't of type :class:`Line`.
1306 :raises ValueError: If parameter ``startLine`` isn't a line of parameter ``file``.
1307 :raises TypeError: If parameter ``endLine`` isn't of type :class:`Line`.
1308 :raises ValueError: If parameter ``endLine`` isn't a line of parameter ``file``.
1309 :raises ValueError: If parameter ``endLine`` is before parameter ``startLine``.
1310 :raises ValueError: If parameter ``status`` is ``None``.
1311 :raises TypeError: If parameter ``status`` isn't of type :class:`LineCoverageStatus`.
1312 :raises TypeError: If parameter ``coverageCount`` isn't of type :class:`int`.
1313 :raises ValueError: If parameter ``coverageCount`` is negative.
1314 :raises ValueError: If parameter ``coverageCount`` contradicts parameter ``status``.
1315 :raises TypeError: If parameter ``parent`` isn't of type :class:`Unit` or :class:`CoverageSummary`.
1316 :raises DuplicateUnitError: If the parent already contains a unit of this name.
1317 """
1318 super().__init__(status, coverageCount, parent=parent)
1319 CoverageCountersMixin.__init__(self)
1321 if name is None:
1322 raise ValueError("Parameter 'name' is None.")
1323 elif not isinstance(name, str):
1324 ex = TypeError("Parameter 'name' is not of type 'str'.")
1325 ex.add_note(f"Got type '{getFullyQualifiedName(name)}'.")
1326 raise ex
1327 elif name == "":
1328 raise ValueError("Parameter 'name' is empty.")
1330 if file is not None and not isinstance(file, File): 1330 ↛ 1331line 1330 didn't jump to line 1331 because the condition on line 1330 was never true
1331 ex = TypeError("Parameter 'file' is not of type 'File'.")
1332 ex.add_note(f"Got type '{getFullyQualifiedName(file)}'.")
1333 raise ex
1335 if startLine is not None:
1336 if not isinstance(startLine, Line):
1337 ex = TypeError("Parameter 'startLine' is not of type 'Line'.")
1338 ex.add_note(f"Got type '{getFullyQualifiedName(startLine)}'.")
1339 raise ex
1340 elif startLine._parent is not file:
1341 raise ValueError("Parameter 'startLine' is not a line of parameter 'file'.")
1343 if endLine is not None:
1344 if not isinstance(endLine, Line): 1344 ↛ 1345line 1344 didn't jump to line 1345 because the condition on line 1344 was never true
1345 ex = TypeError("Parameter 'endLine' is not of type 'Line'.")
1346 ex.add_note(f"Got type '{getFullyQualifiedName(endLine)}'.")
1347 raise ex
1348 elif endLine._parent is not file: 1348 ↛ 1349line 1348 didn't jump to line 1349 because the condition on line 1348 was never true
1349 raise ValueError("Parameter 'endLine' is not a line of parameter 'file'.")
1350 elif startLine is not None and endLine._lineNumber < startLine._lineNumber:
1351 ex = ValueError("Parameter 'endLine' is before parameter 'startLine'.")
1352 ex.add_note(f"Got lines {startLine._lineNumber} to {endLine._lineNumber}.")
1353 raise ex
1355 self._name = name
1356 self._units = {}
1357 self._file = file
1358 self._startLine = startLine
1359 self._endLine = endLine
1361 if parent is not None:
1362 parent._AddElement(self)
1364 if file is not None:
1365 file._units.append(self)
1367 def _AddElement(self, unit: Unit) -> None:
1368 """
1369 Add a unit, which names this unit as its parent.
1371 :param unit: The unit.
1372 :raises DuplicateUnitError: If this unit already contains a unit of this name.
1373 """
1374 if unit._name in self._units: 1374 ↛ 1375line 1374 didn't jump to line 1375 because the condition on line 1374 was never true
1375 raise DuplicateUnitError(f"Unit '{unit._name}' is added twice to '{self._name}'.")
1377 self._units[unit._name] = unit
1379 def _SetRoot(self, root: Nullable[CoverageSummary]) -> None:
1380 """
1381 Set the report's root of this unit, and of the units it contains.
1383 :param root: The report's root, or ``None`` while the unit isn't part of a report.
1384 """
1385 super()._SetRoot(root)
1386 for unit in self._units.values():
1387 unit._SetRoot(root)
1389 @readonly
1390 def Name(self) -> str:
1391 """
1392 Read-only property to access the unit's name (:attr:`_name`).
1394 :returns: The name.
1395 """
1396 return self._name
1398 @readonly
1399 def QualifiedName(self) -> str:
1400 """
1401 Read-only property to return the names of the units from the top down to this one, joined by ``.``.
1403 A method ``Area`` of a class ``Circle`` in a module ``myPackage.Shapes`` has the qualified name
1404 ``myPackage.Shapes.Circle.Area``.
1406 :returns: The qualified name.
1407 """
1408 if isinstance(self._parent, Unit):
1409 return f"{self._parent.QualifiedName}.{self._name}"
1411 return self._name
1413 @readonly
1414 def Units(self) -> dict[str, Unit]:
1415 """
1416 Read-only property to access the units this one contains (:attr:`_units`).
1418 :returns: The units, by name.
1419 """
1420 return self._units
1422 @readonly
1423 def File(self) -> Nullable[File]:
1424 """
1425 Read-only property to access the source file the unit is in (:attr:`_file`).
1427 :returns: The file, or ``None`` if the report doesn't say.
1428 """
1429 return self._file
1431 @readonly
1432 def StartLine(self) -> Nullable[Line]:
1433 """
1434 Read-only property to access the unit's first line (:attr:`_startLine`).
1436 :returns: The line of the unit's file, or ``None`` if the report doesn't say.
1437 """
1438 return self._startLine
1440 @readonly
1441 def EndLine(self) -> Nullable[Line]:
1442 """
1443 Read-only property to access the unit's last line (:attr:`_endLine`).
1445 :returns: The line of the unit's file, or ``None`` if the report doesn't say.
1446 """
1447 return self._endLine
1449 def IterateLines(self) -> Generator[Line, None, None]:
1450 """
1451 Iterate the executable lines of this unit's file from its first to its last line, both included.
1453 :returns: A generator of the lines; nothing, if the unit has no file, or no first or last line.
1454 """
1455 if self._file is not None and self._startLine is not None and self._endLine is not None:
1456 yield from self._file.IterateLines(self._startLine, self._endLine)
1458 def IterateUnits(self, predicate: Nullable[Callable[[Unit], bool]] = None) -> Generator[Unit, None, None]:
1459 """
1460 Iterate this unit and the units it contains, all or selected ones.
1462 This unit comes first, then the units it contains, each level in the order the units were added. If parameter
1463 ``predicate`` is not None, the given filter function is used to skip units in the generator. A skipped unit's units
1464 are still iterated.
1466 :param predicate: Optional, filter function accepting any unit and returning a boolean. Default: ``None``.
1467 :returns: A generator of the units.
1468 """
1469 if predicate is None:
1470 yield self
1471 for unit in self._units.values():
1472 yield from unit.IterateUnits()
1473 else:
1474 if predicate(self):
1475 yield self
1477 for unit in self._units.values():
1478 yield from unit.IterateUnits(predicate)
1480 def Aggregate(self) -> None:
1481 """
1482 Aggregate the units this one contains, then compute the counters from the lines this unit spans.
1484 A unit without first and last line counts the lines the units below it span, each line once. The lines are
1485 aggregated by their files - :meth:`CoverageSummary.Aggregate` does that first.
1486 """
1487 for unit in self._units.values():
1488 unit.Aggregate()
1490 if self._startLine is not None and self._endLine is not None:
1491 self._CountLines(self.IterateLines())
1492 else:
1493 lines: dict[int, Line] = {}
1494 for unit in self.IterateUnits():
1495 lines.update((id(line), line) for line in unit.IterateLines())
1497 self._CountLines(lines.values())
1499 def __repr__(self) -> str:
1500 """
1501 Return a representation of the unit for debugging.
1503 A method ``Area`` of class ``Circle`` in module ``Shapes`` reads ``<Function Shapes.Circle.Area: 100.0%>``.
1505 :returns: The unit's kind, qualified name and line coverage.
1506 """
1507 return f"<{getTypeName(self)} {self.QualifiedName}: {self.LineCoverage:.1%}>"
1510Unit._PARENT_TYPE = (Unit, CoverageSummary)
1513@export
1514class Package(Unit):
1515 """
1516 A package: a unit grouping modules.
1518 Python and Java have packages, VHDL has libraries.
1519 """
1522@export
1523class Module(Unit):
1524 """
1525 A module: a unit of a package.
1527 A Python module is one, and so are a VHDL package and a VHDL entity.
1528 """
1531@export
1532class SourceFile(Unit):
1533 """
1534 A source file as a unit, where the file is the language's unit.
1536 A C translation unit is one, and so is a Bash or TCL script.
1537 """
1540@export
1541class Class(Unit):
1542 """
1543 A class.
1545 Python, Java and C++ have classes.
1546 """
1549@export
1550class Function(Unit):
1551 """
1552 A function.
1554 Python and C have functions, VHDL has functions and procedures.
1555 """
1558@export
1559class Method(Unit):
1560 """A method of a class."""
1563@export
1564@abstractclass
1565class Document(metaclass=ExtendedType, slots=True):
1566 """
1567 A code coverage report file, which is read in two steps: analyzed, then converted.
1569 A format's document derives from this class and mixes in the root of the format's model.
1570 """
1572 _path: Path #: Path to the report file.
1573 _analysisDuration: Nullable[timedelta] #: Duration of :meth:`Analyze`, or ``None`` before it ran.
1574 _conversionDuration: Nullable[timedelta] #: Duration of :meth:`Convert`, or ``None`` before it ran.
1576 def __init__(self, reportFile: Path) -> None:
1577 """
1578 Initialize the report file.
1580 :param reportFile: Path to the report file.
1581 """
1582 self._path = reportFile
1584 self._analysisDuration = None
1585 self._conversionDuration = None
1587 @readonly
1588 def ReportFile(self) -> Path:
1589 """
1590 Read-only property to access the path to the report file (:attr:`_path`).
1592 :returns: The report file's path.
1593 """
1594 return self._path
1596 @readonly
1597 def AnalysisDuration(self) -> Nullable[timedelta]:
1598 """
1599 Read-only property to access the duration of :meth:`Analyze`: reading, parsing and validating the file
1600 (:attr:`_analysisDuration`).
1602 :returns: The duration, or ``None`` if the file wasn't analyzed yet.
1603 """
1604 return self._analysisDuration
1606 @readonly
1607 def ModelConversionDuration(self) -> Nullable[timedelta]:
1608 """
1609 Read-only property to access the duration of :meth:`Convert`: building the report format's model
1610 (:attr:`_conversionDuration`).
1612 :returns: The duration, or ``None`` if the content wasn't converted yet.
1613 """
1614 return self._conversionDuration
1616 @abstractmethod
1617 def Analyze(self) -> None:
1618 """
1619 Read, parse and validate the report file.
1620 """
1622 @abstractmethod
1623 def Convert(self) -> None:
1624 """
1625 Convert the analyzed content to the report format's model.
1626 """
1628 @abstractmethod
1629 def ToCoverageSummary(self) -> CoverageSummary:
1630 """
1631 Convert the report format's model to the common code coverage model, and aggregate it.
1633 :returns: The report's root of the common model.
1634 """