diff --git a/README.md b/README.md index 90c2fe4..aa1691d 100644 --- a/README.md +++ b/README.md @@ -68,8 +68,8 @@ pip install pyTooling.Sphinx[reports] ### Directives of domain `report` (extra `reports`) -* [report:unittest-summary][Directives/UnittestSummary] - A unit test report in Any JUnit XML format, per testsuite and - testcase. +* [report:unittest-summary][Directives/UnittestSummary] - A unit test report in JUnit XML or pyTooling's XML format, per + testsuite and testcase; optionally with a page per testsuite and testcase, referred to by the roles `:ts:` and `:tc:`. * [report:code-coverage][Directives/CodeCoverage] - A Coverage.py report, per package and module, and a legend of its coverage levels. * [report:doc-coverage][Directives/DocCoverage] - A package's documentation coverage, per package and module, and a diff --git a/doc/Directives/UnittestSummary.rst b/doc/Directives/UnittestSummary.rst index d3a80ab..7a555cb 100644 --- a/doc/Directives/UnittestSummary.rst +++ b/doc/Directives/UnittestSummary.rst @@ -13,9 +13,13 @@ report:unittest-summary The hierarchy of testsuites is shown by indentation, a status by a symbol and a CSS class. The report is read by `pyEDAA.Reports `__ in the *Any JUnit* XML - format, so the reports of pytest, OSVVM and other JUnit dialects are accepted. Report files are declared in - :file:`conf.py`, each with an identifier the directive names in its :rst:dir:`report:unittest-summary:reportid` - option - so a documentation shows as many reports as it declares. + format, so the reports of pytest, OSVVM and other JUnit dialects are accepted, or in + :ref:`pyTooling's own XML format `. Report files are declared in :file:`conf.py`, + each with an identifier the directive names in its :rst:dir:`report:unittest-summary:reportid` option - so a + documentation shows as many reports as it declares. + + A report can get a :ref:`page per testsuite and testcase `, which the table links + to and the roles :rst:role:`tc` and :rst:role:`ts` refer to. The directive is part of :mod:`pyTooling.Sphinx`; it needs the :ref:`extra reports `. @@ -27,7 +31,8 @@ report:unittest-summary .. report:unittest-summary:: :reportid: example -This is how the example renders, from a report of four testcases: +This is how the example renders, from a report of five testcases. The report is declared with +:ref:`pages `, so every testsuite and testcase links to its page: .. report:unittest-summary:: :reportid: example @@ -67,10 +72,15 @@ The report files are declared in :file:`conf.py` as a dictionary, keyed by the i :rst:dir:`report:unittest-summary:reportid`. A path is relative to the documentation's source directory. ``pyTooling_Unittest_Testsuites`` - |rarr| The unit test reports, by identifier. An entry has one field: + |rarr| The unit test reports, by identifier. An entry has these fields: ``xml_report`` - |rarr| The report file, in Any JUnit XML format. + |rarr| The report file, in Any JUnit XML format or :ref:`pyTooling's XML format `. + Required. + + ``pages`` + |rarr| The document name the :ref:`pages per testsuite and testcase ` are generated + below, e.g. ``unittests/src``. Optional; without it, the report gets no pages. .. code-block:: Python @@ -78,13 +88,141 @@ The report files are declared in :file:`conf.py` as a dictionary, keyed by the i pyTooling_Unittest_Testsuites = { "src": { "xml_report": "../report/unit/unittest.xml", + "pages": "unittests/src", } } +The first entry is the default report of the roles :rst:role:`tc` and :rst:role:`ts`. + The configuration is checked when the build starts. A report file that doesn't exist is logged as an error, and the entries after it aren't read: an entry whose file is written later - e.g. by a test run in CI - goes last. +.. _DIR/UnittestSummary/Formats: + +Report formats +************** + +The format of a report file is recognized by its root element: + +```` or ```` + |rarr| A JUnit XML file, read by pyEDAA.Reports in the *Any JUnit* dialect - e.g. pytest's ``--junit-xml``. A + testcase's failure, error or skip message, its traceback and its captured output are shown on its + :ref:`page `. + +```` + |rarr| A test report in pyTooling's XML format, written by pyTooling's pytest plugin with ``--pytooling-xml``. + Its testsuites nest, and a testsuite or testcase carries a title, a summary and a description - e.g. from the + markers ``@testsuite`` and ``@testcase`` and the doc-strings. A page shows them below its name, a link shows the + title on hover. + +.. report:unittest-summary:: + :reportid: pytooling + :no-assertions: + + +.. _DIR/UnittestSummary/Pages: + +Pages per testsuite and testcase +******************************** + +A report declared with the key ``pages`` gets a page per testsuite and per testcase. They are generated when the +documentation is built - no source file is written - below the document name the key states: + +* a testsuite's page: ``///...``, the names of the testsuites from the report's top + down, e.g. ``unittests/example/pytest/tests/unit/Arithmetic``; +* a testcase's page: ``//.../``, e.g. + ``unittests/example/pytest/tests/unit/Arithmetic/Division/test_ByZero``. + +Characters of a name other than letters, digits, ``_``, ``-`` and ``.`` - e.g. the brackets of a parametrized pytest +testcase - are replaced by ``_``. A name colliding with a sibling's, also when differing in case only, gets the suffix +``-2``, ``-3``, and so on. + +A **testcase's page** shows its status, duration, number of assertions (if the report has it) and its testsuite, +linked; then the message and details of a failure, error or skip, and the captured standard output and standard error. + +A **testsuite's page** shows its status, the number of testcases per status, the duration, the number of assertions +(if the report has it) and its parent testsuite; then a table of its testsuites and a table of its testcases, each +linked to its page. + +The title, summary and description of a :ref:`pyTooling report ` are shown below the +name, as plain text: they are doc-strings, which aren't necessarily ReST of this documentation. + +The :rst:dir:`report:unittest-summary` table links every testsuite and testcase to its page; that is the entry point. +The directive lists the report's top-level testsuites in a hidden table of contents, and a testsuite's page lists its +testsuites and testcases, so the pages are below the summary's document in the navigation - in the section holding +the directive. A page's own sections - *Summary*, *Testcases*, ... - aren't listed there. A report is best shown on a +page of its own: a title, an introduction and the directive. + +.. hint:: + + A testcase is as many levels below the summary's document as the report nests testsuites - e.g. seven for + ``pytest/tests/unit/Arithmetic/Division/test_ByZero``. A theme limits how deep its navigation goes, e.g. the + option ``navigation_depth`` of the *Read the Docs* theme (default 4; ``-1`` = unlimited). ``pyedaa-reports`` + removes levels like ``pytest/tests/unit`` from a JUnit report with ``--pytest=reduce-depth:pytest.tests.unit``. + +The pages are :ref:`orphans `, so a report with pages, but without a summary directive, causes no +warnings; its pages are reached by the roles only. + +Sphinx regards the report file as the source of its pages, so a changed report regenerates its pages. As the pages +are in the table of contents, LaTeX writes them too - below the summary's section, the deepest levels as +paragraphs. + +.. hint:: + + A report can have thousands of testcases - pages are only generated for a report declaring ``pages``. + + +.. _DIR/UnittestSummary/Roles: + +Roles +***** + +The roles :rst:role:`tc` and :rst:role:`ts` refer to a testcase and a testsuite of a report with pages. They are +registered in domain ``report`` - as ``:report:tc:`` and ``:report:ts:`` - and without the domain's prefix. + +.. rst:role:: tc + + Refers to a testcase's page, showing the testcase's name, or the role's title: ``:tc:```` or + ``:tc:`title <>```. + + The target is ``[:]``. The qualified name is the path from the report's top down, the + names joined by ``.``: e.g. ``pytest.tests.unit.Arithmetic.Division.test_ByZero``. A suffix of it starting at a + name - ``Division.test_ByZero`` or ``test_ByZero`` - is accepted, if it's unique. Without a report ID, the first + report of ``pyTooling_Unittest_Testsuites`` is meant. + + A target matching nothing or several testcases is warned about. + +.. rst:role:: ts + + Refers to a testsuite's page, as :rst:role:`tc` refers to a testcase's. + +.. grid:: 2 + + .. grid-item:: + :columns: 6 + + .. code-block:: ReST + + * :tc:`test_ByZero` + * :tc:`example:Division.test_Fraction` + * :ts:`Arithmetic` + * :ts:`pytooling:Addition` + * :tc:`the skipped one ` + + .. grid-item:: + :columns: 6 + + * :tc:`test_ByZero` + * :tc:`example:Division.test_Fraction` + * :ts:`Arithmetic` + * :ts:`pytooling:Addition` + * :tc:`the skipped one ` + +The testsuites and testcases are objects of domain ``report``, named ``:`` in the +documentation's inventory (:file:`objects.inv`), so another documentation refers to them with ``intersphinx``. + + .. _DIR/UnittestSummary/Options: Options diff --git a/doc/News.rst b/doc/News.rst index 74b12a0..bb3c792 100644 --- a/doc/News.rst +++ b/doc/News.rst @@ -26,6 +26,11 @@ Version 0.x (2026) * Domain ``report`` from :gh:`sphinx-reports ` (v0.11.2), with the directives :ref:`report:unittest-summary `, :ref:`report:code-coverage ` and :ref:`report:doc-coverage `. Reading a report needs the extra ``reports``. + * A unit test report declared with ``pages`` gets a + :ref:`page per testsuite and testcase `, generated without source files, linked + from the summary table and listed in the navigation below the summary's page, and the roles + :ref:`:tc: and :ts: ` refer to them. A report may be in + :ref:`pyTooling's XML format ` too. .. rubric:: Changes compared to sphinx-reports diff --git a/doc/conf.py b/doc/conf.py index e5eb2bc..79975b4 100644 --- a/doc/conf.py +++ b/doc/conf.py @@ -89,7 +89,7 @@ html_theme_options = { "logo_only": True, "vcs_pageview_mode": 'blob', - "navigation_depth": 5, + "navigation_depth": -1, } html_css_files = [ 'css/override.css', @@ -280,6 +280,11 @@ pyTooling_Unittest_Testsuites = { "example": { "xml_report": "../tests/data/Report/unittest.xml", + "pages": "unittests/example", + }, + "pytooling": { + "xml_report": "../tests/data/Report/TestReport.xml", + "pages": "unittests/pytooling", }, "src": { "xml_report": "../report/unit/unittest.xml", diff --git a/doc/index.rst b/doc/index.rst index a9d1767..854dd5e 100644 --- a/doc/index.rst +++ b/doc/index.rst @@ -89,7 +89,9 @@ Roles and Directives .. rubric:: Directives of domain ``report`` (extra ``reports``) :ref:`report:unittest-summary ` - |rarr| A unit test report in Any JUnit XML format, per testsuite and testcase. + |rarr| A unit test report in JUnit XML or pyTooling's XML format, per testsuite and testcase; optionally with a + :ref:`page per testsuite and testcase `, referred to by the roles + :ref:`:ts: and :tc: `. :ref:`report:code-coverage ` |rarr| A Coverage.py report, per package and module, and a legend of its coverage levels. :ref:`report:doc-coverage ` diff --git a/pyTooling/Sphinx/Unittest.py b/pyTooling/Sphinx/Unittest.py index 4208311..66b0b95 100644 --- a/pyTooling/Sphinx/Unittest.py +++ b/pyTooling/Sphinx/Unittest.py @@ -31,9 +31,11 @@ """ A directive rendering a unit test report as a table: per testsuite and testcase, the counts and the runtime. -The reports are read by :mod:`pyEDAA.Reports` in the Any JUnit XML format, so any JUnit dialect is accepted - e.g. -the reports of pytest or OSVVM. The report files are declared in :file:`conf.py` under -``pyTooling_Unittest_Testsuites``, each with an identifier a directive names in its ``:reportid:`` option: +The reports are read by :mod:`pyEDAA.Reports`: a JUnit XML file in any dialect - e.g. the reports of pytest or +OSVVM -, or a test report in pyTooling's own XML format, recognized by its root element ````. The report +files are declared in :file:`conf.py` under ``pyTooling_Unittest_Testsuites``, each with an identifier a directive +names in its ``:reportid:`` option. An entry with the key ``pages`` gets a page per testsuite and testcase, generated +below that document name (see :mod:`pyTooling.Sphinx.UnittestPages`): .. code-block:: Python @@ -41,9 +43,12 @@ pyTooling_Unittest_Testsuites = { "src": { "xml_report": "../report/unit/unittest.xml", + "pages": "unittests/src", } } +The reports are read once, when the builder is initialized, and shared by every directive and page using them. + .. seealso:: :ref:`DIR/UnittestSummary` @@ -56,37 +61,48 @@ from pathlib import Path from typing import TYPE_CHECKING, Any, ClassVar, Generator, Mapping, Optional as Nullable from typing import TypedDict +from xml.etree.ElementTree import iterparse # nosec B405 - reads the root element of the project's report from docutils import nodes from docutils.parsers.rst.directives import flag +from sphinx.addnodes import pending_xref from sphinx.application import Sphinx from sphinx.config import Config from sphinx.util.logging import getLogger +from pyTooling.Common import getFullyQualifiedName from pyTooling.Decorators import export -from pyTooling.Sphinx import INDENTATION, BaseDirective, ReportExtensionError -from pyTooling.Sphinx import ReportsPackageMissingError, SphinxExtensionError, strip +from pyTooling.Sphinx import INDENTATION, BaseDirective, ReportDomain, ReportExtensionError +from pyTooling.Sphinx import ReportsPackageMissingError, SphinxExtensionError, UnittestEntry, strip from pyTooling.Sphinx import stripAndNormalize from pyTooling.Sphinx.Node import Landscape if TYPE_CHECKING: # pragma: no cover # pyEDAA.Reports is an optional dependency (extra 'reports'), imported where a report is read. from pyEDAA.Reports.Unittesting import TestcaseStatus, TestsuiteStatus - from pyEDAA.Reports.Unittesting.JUnit import Testcase, Testsuite, TestsuiteSummary + from pyEDAA.Reports.Unittesting import Testcase, Testsuite, TestsuiteSummary -__all__ = ["CONFIG_PREFIX"] +__all__ = ["CONFIG_PREFIX", "REPORT_FORMATS"] #: Prefix every configuration value of the unit test directive carries in :file:`conf.py`. CONFIG_PREFIX = "pyTooling_Unittest" +#: The report formats, by the root element of a report file. +REPORT_FORMATS = { + "testsuites": "JUnit", + "testsuite": "JUnit", + "TestReport": "pyTooling", +} + @export class TestsuiteConfiguration(TypedDict): """An entry of ``pyTooling_Unittest_Testsuites``, after :meth:`UnittestSummary.CheckConfiguration` read it.""" - xml_report: Path #: The unit test report, in Any JUnit XML format. + xml_report: Path #: The unit test report, in JUnit XML or pyTooling's XML format. + pages: Nullable[str] #: Document name the pages per testsuite and testcase are generated below, if any. @export @@ -97,8 +113,8 @@ class ShowTestcases(Flag): A member compares equal to a :class:`~pyEDAA.Reports.Unittesting.TestcaseStatus` it includes. """ - passed = 1 #: Passed testcases. - failed = 2 #: Failed testcases. + passed = 1 #: Passed testcases, and testcases failing as expected. + failed = 2 #: Failed testcases, and testcases passing unexpectedly. skipped = 4 #: Skipped testcases. excluded = 8 #: Excluded testcases. errors = 16 #: Errored testcases, and testcases whose setup failed. @@ -117,9 +133,9 @@ def __eq__(self, other: Any) -> bool: from pyEDAA.Reports.Unittesting import TestcaseStatus if isinstance(other, TestcaseStatus): - if other is TestcaseStatus.Passed: + if other is TestcaseStatus.Passed or other is TestcaseStatus.ExpectedFailed: return ShowTestcases.passed in self - elif other is TestcaseStatus.Failed: + elif other is TestcaseStatus.Failed or other is TestcaseStatus.UnexpectedPassed: return ShowTestcases.failed in self elif other is TestcaseStatus.Skipped: return ShowTestcases.skipped in self @@ -159,6 +175,8 @@ class UnittestSummary(BaseDirective): } #: Values added to :file:`conf.py`, as ``name: (default, rebuild, types)``, prefixed by :data:`CONFIG_PREFIX`. _testSummaries: ClassVar[dict[str, TestsuiteConfiguration]] = {} #: Report configurations, by report ID. + _reports: ClassVar[dict[str, TestsuiteSummary]] = {} #: Reports read by :meth:`ReadReports`, by ID. + _readErrors: ClassVar[dict[str, Exception]] = {} #: Why a report couldn't be read, by report ID. _cssClasses: list[str] #: Additional CSS classes of the table. _reportID: str #: Identifier of the report in the configuration. @@ -207,14 +225,75 @@ def CheckConfiguration(cls, sphinxApplication: Sphinx, sphinxConfiguration: Conf @classmethod def ReadReports(cls, sphinxApplication: Sphinx) -> None: """ - Read unittest report files. + Read every configured unit test report, once per build. - So far, this only logs that the reports are read; each directive reads its report when it runs. + A report that can't be read keeps the exception, which a directive or a report's pages show when they need it. :param sphinxApplication: Sphinx application instance. """ getLogger(__name__).info("[REPORT] Reading unittest reports ...") + cls._reports = {} + cls._readErrors = {} + for reportID, testSummary in cls._testSummaries.items(): + try: + cls._reports[reportID] = cls._ReadReport(testSummary["xml_report"]) + except Exception as ex: + cls._readErrors[reportID] = ex + + @classmethod + def GetReport(cls, reportID: str) -> TestsuiteSummary: + """ + Return a report read by :meth:`ReadReports`. + + :param reportID: Identifier of the report. + :returns: The report's testsuite summary. + :raises ReportExtensionError: If the report wasn't read, chained to the exception reading it raised. + """ + try: + return cls._reports[reportID] + except KeyError: + cause = cls._readErrors.get(reportID, None) + raise ReportExtensionError(f"Unittest report '{reportID}' wasn't read.") from cause + + @staticmethod + def _ReadReport(xmlReport: Path) -> TestsuiteSummary: + """ + Read a report file, choosing the reader by the file's root element. + + :param xmlReport: The report file. + :returns: The report's testsuite summary, aggregated. + :raises ReportExtensionError: If the file's root element is no known report format. + :raises ReportsPackageMissingError: If pyEDAA.Reports, or its reader for the report's format, isn't installed. + """ + _, rootElement = next(iterparse(xmlReport, events=("start",))) # nosec B314 - the project's own report + try: + reportFormat = REPORT_FORMATS[rootElement.tag] + except KeyError: + ex = ReportExtensionError(f"Unittest report '{xmlReport}' has an unknown format.") + ex.add_note(f"Got root element '<{rootElement.tag}>'; supported: {', '.join(REPORT_FORMATS)}") + raise ex from None + + if reportFormat == "pyTooling": + try: + from pyEDAA.Reports.Unittesting.pyTooling import Document as pyToolingDocument + except ImportError as cause: + raise ReportsPackageMissingError("Reading a pyTooling test report") from cause + + return pyToolingDocument(xmlReport, analyzeAndConvert=True) + + try: + from pyEDAA.Reports.Unittesting.JUnit import Document as JUnitDocument + except ImportError as cause: + raise ReportsPackageMissingError("Reading a unit test report") from cause + + document = JUnitDocument(xmlReport, analyzeAndConvert=True) + document.Aggregate() + testsuiteSummary = document.ToTestsuiteSummary() + testsuiteSummary.Aggregate() + + return testsuiteSummary + @classmethod def _CheckConfiguration(cls, sphinxConfiguration: Config) -> None: """ @@ -224,8 +303,12 @@ def _CheckConfiguration(cls, sphinxConfiguration: Config) -> None: :raises ReportExtensionError: If the configuration value isn't registered. :raises ReportExtensionError: If a report configuration has no ``xml_report``. :raises ReportExtensionError: If the ``xml_report`` file doesn't exist. + :raises ReportExtensionError: If ``pages`` isn't a string. + :raises ReportExtensionError: If ``pages`` isn't a relative document name. |br| + Use a name like 'unittests/src', separated by '/', without '.' or '..'. """ variableName = f"{CONFIG_PREFIX}_Testsuites" + cls._testSummaries = {} try: allTestsuites: dict[str, TestsuiteConfiguration] = sphinxConfiguration[variableName] @@ -245,8 +328,24 @@ def _CheckConfiguration(cls, sphinxConfiguration: Config) -> None: f"{summaryName}.xml_report: Unittest report file '{xmlReport}' doesn't exist." ) from FileNotFoundError(xmlReport) + pages = testSummary.get("pages", None) + if pages is not None: + if not isinstance(pages, str): + ex = ReportExtensionError(f"{summaryName}.pages: Document name is not a string.") + ex.add_note(f"Got type '{getFullyQualifiedName(pages)}'.") + raise ex + + parts = pages.strip("/").split("/") + if "\\" in pages or any(part in ("", ".", "..") for part in parts): + ex = ReportExtensionError(f"{summaryName}.pages: '{pages}' is not a relative document name.") + ex.add_note("Use a name like 'unittests/src', separated by '/', without '.' or '..'.") + raise ex + + pages = "/".join(parts) + cls._testSummaries[reportID] = { - "xml_report": xmlReport + "xml_report": xmlReport, + "pages": pages } def _SortedValues(self, d: Mapping[str, Any]) -> Generator[Any, None, None]: @@ -259,7 +358,8 @@ def _SortedValues(self, d: Mapping[str, Any]) -> Generator[Any, None, None]: for key in sorted(d.keys()): yield d[key] - def _ConvertTestcaseStatusToSymbol(self, status: TestcaseStatus) -> str: + @staticmethod + def _ConvertTestcaseStatusToSymbol(status: TestcaseStatus) -> str: """ Return the symbol shown for a testcase's status. @@ -268,7 +368,7 @@ def _ConvertTestcaseStatusToSymbol(self, status: TestcaseStatus) -> str: """ from pyEDAA.Reports.Unittesting import TestcaseStatus - if status is TestcaseStatus.Passed: + if status is TestcaseStatus.Passed or status is TestcaseStatus.ExpectedFailed: return "✅" elif status is TestcaseStatus.Failed: return "❌" @@ -287,7 +387,8 @@ def _ConvertTestcaseStatusToSymbol(self, status: TestcaseStatus) -> str: else: return "❌" - def _ConvertTestsuiteStatusToSymbol(self, status: TestsuiteStatus) -> str: + @staticmethod + def _ConvertTestsuiteStatusToSymbol(status: TestsuiteStatus) -> str: """ Return the symbol shown for a testsuite's status. @@ -315,7 +416,8 @@ def _ConvertTestsuiteStatusToSymbol(self, status: TestsuiteStatus) -> str: else: return "❌" - def _FormatTimedelta(self, delta: Nullable[timedelta]) -> str: + @staticmethod + def _FormatTimedelta(delta: Nullable[timedelta]) -> str: """ Format a duration as ``HH:MM:SS.sss``, rounded to milliseconds. @@ -426,7 +528,7 @@ def _RenderTestsuite(self, tableBody: nodes.tbody, testsuite: Testsuite, level: tableRow = nodes.row("", classes=["report-testsuite", f"testsuite-{testsuite._status.name.lower()}"]) tableBody += tableRow - tableRow += nodes.entry("", nodes.Text(f"{INDENTATION * 2 * level}{state}{testsuite.Name}")) + tableRow += self._NameEntry(f"{INDENTATION * 2 * level}{state}", testsuite, "ts") tableRow += nodes.entry("", nodes.Text(f"{testsuite.TestcaseCount}")) tableRow += nodes.entry("", nodes.Text(f"{testsuite.Skipped}")) tableRow += nodes.entry("", nodes.Text(f"{testsuite.Errored}")) @@ -456,7 +558,7 @@ def _RenderTestcase(self, tableBody: nodes.tbody, testcase: Testcase, level: int tableRow = nodes.row("", classes=["report-testcase", f"testcase-{testcase._status.name.lower()}"]) tableBody += tableRow - tableRow += nodes.entry("", nodes.Text(f"{INDENTATION * 2 * level}{state}{testcase.Name}")) + tableRow += self._NameEntry(f"{INDENTATION * 2 * level}{state}", testcase, "tc") tableRow += nodes.entry("", nodes.Text("")) tableRow += nodes.entry("", nodes.Text("")) tableRow += nodes.entry("", nodes.Text("")) @@ -466,6 +568,43 @@ def _RenderTestcase(self, tableBody: nodes.tbody, testcase: Testcase, level: int tableRow += nodes.entry("", nodes.Text(f"{testcase.AssertionCount}")) tableRow += nodes.entry("", nodes.Text(f"{self._FormatTimedelta(testcase.TotalDuration)}")) + def _NameEntry(self, prefix: str, entity: Testsuite | Testcase, roleName: str) -> nodes.entry: + """ + Create the cell naming a testsuite or testcase, linked to its page if the report has pages. + + :param prefix: The indentation and the status symbol written before the name. + :param entity: The testsuite or testcase. + :param roleName: The role referring to it: ``ts`` for a testsuite, ``tc`` for a testcase. + :returns: The table cell. + """ + from pyTooling.Sphinx.UnittestPages import UnittestReportPages + + if (pages := UnittestReportPages.GetPages(self._reportID)) is None or (entry := pages.Entry(entity)) is None: + return nodes.entry("", nodes.Text(f"{prefix}{entity.Name}")) + + # a reference has to be inside a text element; an inline keeps the cell free of a paragraph, as the others are + reference = self.CreateReference(roleName, entry, self.env.docname) + return nodes.entry("", nodes.inline("", "", nodes.Text(prefix), reference)) + + @staticmethod + def CreateReference(roleName: str, entry: UnittestEntry, docname: str) -> pending_xref: + """ + Create a reference to the page of a testsuite or testcase, showing its name. + + :param roleName: The role referring to it: ``ts`` for a testsuite, ``tc`` for a testcase. + :param entry: The testsuite or testcase. + :param docname: Name of the document holding the reference. + :returns: The reference, resolved by domain ``report``. + """ + reference = pending_xref( + "", refdomain=ReportDomain.name, reftype=roleName, reftarget=f"{entry.reportID}:{entry.QualifiedName}", + refexplicit=False, refwarn=True, refdoc=docname + ) + classes = ["xref", ReportDomain.name, f"{ReportDomain.name}-{roleName}"] + reference += nodes.inline(entry.Name, entry.Name, classes=classes) + + return reference + def _RenderSummary(self, tableBody: nodes.tbody, testsuiteSummary: TestsuiteSummary) -> None: """ Add the summary row: the overall status and counts. @@ -494,7 +633,11 @@ def run(self) -> list[nodes.Node]: """ Read the configured report and return it as a table, on landscape pages in LaTeX. - :returns: A :class:`~pyTooling.Sphinx.Node.Landscape` container holding the table, or the error message. + A report with pages adds a hidden table of contents of its top-level testsuites, so the pages are below this + document in the navigation. + + :returns: A :class:`~pyTooling.Sphinx.Node.Landscape` container holding the table, or the error message; then + the table of contents, if the report has pages. """ container = Landscape() @@ -504,40 +647,26 @@ def run(self) -> list[nodes.Node]: message = f"Caught {ex.__class__.__name__} when checking options for directive '{self.directiveName}'." return self._internalError(container, __name__, message, ex) - try: - from pyEDAA.Reports.Unittesting.JUnit import Document - except ImportError as cause: - ex = ReportsPackageMissingError("Reading a unit test report") - ex.__cause__ = cause - message = f"Caught {ex.__class__.__name__} when reading '{self._xmlReport}'." - return self._internalError(container, __name__, message, ex) + if (readError := self._readErrors.get(self._reportID, None)) is not None: + if isinstance(readError, ReportsPackageMissingError): + message = f"Caught {readError.__class__.__name__} when reading '{self._xmlReport}'." + else: + message = f"Caught {readError.__class__.__name__} when reading and parsing '{self._xmlReport}'." + return self._internalError(container, __name__, message, readError) try: - doc = Document(self._xmlReport, analyzeAndConvert=True) - except Exception as ex: - message = f"Caught {ex.__class__.__name__} when reading and parsing '{self._xmlReport}'." - return self._internalError(container, __name__, message, ex) - - doc.Aggregate() - - try: - self._testsuite = doc.ToTestsuiteSummary() + self._testsuite = self.GetReport(self._reportID) + container += self._GenerateTestSummaryTable() except Exception as ex: message = ( - f"Caught {ex.__class__.__name__} when converting to a TestsuiteSummary for JUnit document " + f"Caught {ex.__class__.__name__} when generating the document structure for unittest report " f"'{self._xmlReport}'." ) return self._internalError(container, __name__, message, ex) - self._testsuite.Aggregate() + from pyTooling.Sphinx.UnittestPages import UnittestReportPages - try: - container += self._GenerateTestSummaryTable() - except Exception as ex: - message = ( - f"Caught {ex.__class__.__name__} when generating the document structure for JUnit document " - f"'{self._xmlReport}'." - ) - return self._internalError(container, __name__, message, ex) + if (pages := UnittestReportPages.GetPages(self._reportID)) is None: + return [container] - return [container] + return [container, pages.TableOfContents(self.env.docname)] diff --git a/pyTooling/Sphinx/UnittestPages.py b/pyTooling/Sphinx/UnittestPages.py new file mode 100644 index 0000000..149d91f --- /dev/null +++ b/pyTooling/Sphinx/UnittestPages.py @@ -0,0 +1,553 @@ +# ==================================================================================================================== # +# _____ _ _ ____ _ _ # +# _ __ _ |_ _|__ ___ | (_)_ __ __ _ / ___| _ __ | |__ (_)_ __ __ __ # +# | '_ \| | | || |/ _ \ / _ \| | | '_ \ / _` | \___ \| '_ \| '_ \| | '_ \\ \/ / # +# | |_) | |_| || | (_) | (_) | | | | | | (_| |_ ___) | |_) | | | | | | | |> < # +# | .__/ \__, ||_|\___/ \___/|_|_|_| |_|\__, (_)____/| .__/|_| |_|_|_| |_/_/\_\ # +# |_| |___/ |___/ |_| # +# ==================================================================================================================== # +# Authors: # +# Patrick Lehmann # +# # +# License: # +# ==================================================================================================================== # +# Copyright 2026-2026 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 # +# ==================================================================================================================== # +# +""" +A page per testsuite and per testcase of a unit test report, generated without a source file. + +A report declared in ``pyTooling_Unittest_Testsuites`` with the key ``pages`` gets a document per testsuite and per +testcase, named below that key's document name: + +* a testsuite: ``///...``, the names of the testsuites from the report's summary down; +* a testcase: ``//.../``. + +A name's characters other than letters, digits, ``_``, ``-`` and ``.`` - e.g. the brackets of a parametrized pytest +testcase - are replaced by ``_``, and a name colliding with a sibling's (also when differing only in case) gets the +suffix ``-2``, ``-3``, ... + +The pages are built as docutils node trees from the report :class:`UnittestSummary` read, and handed to Sphinx as if +they were read from a file: their names are registered when the builder is initialized and again before the +documents are read - :meth:`sphinx.project.Project.discover` forgets them in between -, and the file Sphinx sees as +their source is the report, so a changed report rebuilds them. A page carries the metadata ``:orphan:``; a testsuite's +page links its testsuites and testcases in a hidden table of contents, as the directive ``report:unittest-summary`` +links the top-level testsuites, so the pages are in the navigation below the summary's document. A page's sections +aren't listed there. Every testsuite and testcase with a page is an object of domain ``report``, referred to by the +roles ``:ts:`` and ``:tc:``. + +.. seealso:: + + :ref:`DIR/UnittestSummary/Pages` + |rarr| The pages and the roles, with examples. +""" +from __future__ import annotations + +from re import compile as re_compile +from textwrap import dedent +from time import time_ns +from typing import TYPE_CHECKING, ClassVar, Iterable, Optional as Nullable + +from docutils import nodes +from docutils.utils import DependencyList +from sphinx import addnodes +from sphinx.application import Sphinx +from sphinx.environment import BuildEnvironment +from sphinx.util.docutils import new_document +from sphinx.util.logging import getLogger + +from pyTooling.Decorators import export, readonly +from pyTooling.MetaClasses import ExtendedType + +from pyTooling.Sphinx import ReportDomain, ReportExtensionError, UnittestEntry +from pyTooling.Sphinx.Unittest import UnittestSummary + +if TYPE_CHECKING: # pragma: no cover + # pyEDAA.Reports is an optional dependency (extra 'reports'), imported where a report is read. + from pathlib import Path + + from pyEDAA.Reports.Unittesting import Testcase, Testsuite, TestsuiteSummary + + +__all__ = ["UNSAFE_CHARACTERS"] + +#: Characters of a testsuite's or testcase's name, which are replaced in its document name. +UNSAFE_CHARACTERS = re_compile(r"[^A-Za-z0-9_.\-]+") + + +@export +class UnittestReportPages(metaclass=ExtendedType, slots=True): + """ + The pages of one unit test report: a document name and an entry of domain ``report`` per testsuite and testcase. + + The document names are computed once, when the report's pages are created, so the summary table, the roles and the + pages agree on them. + """ + + _reportPages: ClassVar[dict[str, UnittestReportPages]] = {} #: The pages of every report with pages, by report ID. + + _reportID: str #: Identifier of the report. + _xmlReport: Path #: The report file, the pages' source for Sphinx. + _summary: TestsuiteSummary #: The report's testsuite summary. + _entries: dict[int, UnittestEntry] #: The entries, by the ``id()`` of their entity. + _documents: dict[str, tuple[str, Testsuite | Testcase]] #: Role name and entity, by document name. + + def __init__(self, reportID: str, prefix: str, xmlReport: Path, summary: TestsuiteSummary) -> None: + """ + Compute the document names and entries of a report's testsuites and testcases. + + A testsuite or testcase whose qualified name is already taken by another of the same kind gets no page; this + is logged as a warning. + + :param reportID: Identifier of the report. + :param prefix: Document name the pages are generated below. + :param xmlReport: The report file. + :param summary: The report's testsuite summary. + """ + self._reportID = reportID + self._xmlReport = xmlReport.resolve() + self._summary = summary + self._entries = {} + self._documents = {} + + qualifiedNames: dict[str, set[str]] = {"ts": set(), "tc": set()} + + def addEntities( + entities: Iterable[Testsuite | Testcase], + roleName: str, + path: tuple[str, ...], + directory: str, + siblings: set[str] + ) -> None: + """ + Nested function adding a document name and entry per testsuite or testcase, recursing into testsuites. + + :param entities: The testsuites or testcases of one parent. + :param roleName: The role referring to them: ``ts`` or ``tc``. + :param path: The parent's path below the summary. + :param directory: The parent's document name, the directory of its children's documents. + :param siblings: The document names used below that directory so far, in lower case. + """ + for entity in sorted(entities, key=lambda item: item._name): + entityPath = (*path, entity._name) + qualifiedName = ".".join(entityPath) + if qualifiedName in qualifiedNames[roleName]: + getLogger(__name__).warning( + f"Unittest report '{reportID}': the qualified name '{qualifiedName}' is not unique, " + f"so the second one gets no page." + ) + continue + + qualifiedNames[roleName].add(qualifiedName) + + baseName = UNSAFE_CHARACTERS.sub("_", entity._name).strip("_.") or "_" + fileName, counter = baseName, 1 + while fileName.lower() in siblings: + counter += 1 + fileName = f"{baseName}-{counter}" + siblings.add(fileName.lower()) + + docName = f"{directory}/{fileName}" + title = None if entity._title == entity._name else entity._title + self._entries[id(entity)] = UnittestEntry(docName, reportID, entityPath, title) + self._documents[docName] = (roleName, entity) + + if roleName == "ts": + children: set[str] = set() + addEntities(entity._testsuites.values(), "ts", entityPath, docName, children) + addEntities(entity._testcases.values(), "tc", entityPath, docName, children) + + addEntities(summary._testsuites.values(), "ts", (), prefix, set()) + + @classmethod + def CreatePages(cls, sphinxApplication: Sphinx) -> None: + """ + Call-back for Sphinx' ``builder-inited`` event, after the reports are read: compute and register the pages. + + Only a report with the key ``pages`` gets pages. A report that couldn't be read gets none; this is logged as an + error. + + :param sphinxApplication: Sphinx application instance. + """ + cls._reportPages = {} + for reportID, testSummary in UnittestSummary._testSummaries.items(): + if (prefix := testSummary["pages"]) is None: + continue + + try: + summary = UnittestSummary.GetReport(reportID) + except ReportExtensionError as ex: + cause = ex if ex.__cause__ is None else ex.__cause__ + getLogger(__name__).error( + f"Caught {ex.__class__.__name__} when generating the pages of unittest report '{reportID}'.\n" + f" {cause.__class__.__name__}: {cause}" + ) + continue + + pages = cls(reportID, prefix, testSummary["xml_report"], summary) + cls._reportPages[reportID] = pages + pages.Register(sphinxApplication.env) + + @classmethod + def GetPages(cls, reportID: str) -> Nullable[UnittestReportPages]: + """ + Return the pages of a report. + + :param reportID: Identifier of the report. + :returns: The report's pages, or ``None`` if the report has none. + """ + return cls._reportPages.get(reportID, None) + + @classmethod + def GenerateAll(cls, sphinxApplication: Sphinx, env: BuildEnvironment, docnames: list[str]) -> None: + """ + Call-back for Sphinx' ``env-before-read-docs`` event: generate the pages of every report. + + :param sphinxApplication: Sphinx application instance. + :param env: The build environment. + :param docnames: The documents to read, from which the generated pages are removed. + """ + for pages in cls._reportPages.values(): + pages.Generate(sphinxApplication) + + docnames[:] = [docname for docname in docnames if docname not in pages._documents] + + @classmethod + def HideSource( + cls, + sphinxApplication: Sphinx, + pagename: str, + templatename: str, + context: dict[str, object], + doctree: Nullable[nodes.document] + ) -> None: + """ + Call-back for Sphinx' ``html-page-context`` event: a generated page has no source to copy or link. + + Without it, the HTML builder would copy the report file - the page's source for Sphinx - per page. + + :param sphinxApplication: Sphinx application instance. + :param pagename: Name of the page. + :param templatename: Name of the page's template. + :param context: The template's context. + :param doctree: The page's doctree. + """ + if any(pagename in pages._documents for pages in cls._reportPages.values()): + context["sourcename"] = "" + + @readonly + def ReportID(self) -> str: + """ + Read-only property to access the report's identifier (:attr:`_reportID`). + + :returns: The identifier of the report. + """ + return self._reportID + + @readonly + def DocNames(self) -> list[str]: + """ + Read-only property to return the names of the generated documents. + + :returns: The document names, a testsuite before its testsuites and testcases. + """ + return list(self._documents) + + def Entry(self, entity: Testsuite | Testcase) -> Nullable[UnittestEntry]: + """ + Return the entry of a testsuite or testcase of this report. + + :param entity: The testsuite or testcase. + :returns: Its entry, or ``None`` if it has no page. + """ + return self._entries.get(id(entity), None) + + def Register(self, env: BuildEnvironment) -> None: + """ + Register the document names, with the report file as their source. + + :param env: The build environment. + """ + for docName in self._documents: + env.project.docnames.add(docName) + env.project._docname_to_path[docName] = self._xmlReport + + def Generate(self, sphinxApplication: Sphinx) -> None: + """ + Build the doctree of every page, have the environment collect it, and store it as if it was read. + + The event ``doctree-read`` is emitted per page, so the environment's collectors record its title, table of + contents and metadata. + + :param sphinxApplication: Sphinx application instance. + """ + env = sphinxApplication.env + domain: ReportDomain = env.domains[ReportDomain.name] # type: ignore[assignment] + + self.Register(env) + for docName, (roleName, entity) in self._documents.items(): + if roleName == "ts": + section = self._TestsuitePage(docName, entity) + else: + section = self._TestcasePage(docName, entity) + + document = new_document(str(self._xmlReport)) + document.settings.env = env + document.settings.record_dependencies = DependencyList() + document += nodes.docinfo("", nodes.field("", nodes.field_name("", "orphan"), nodes.field_body())) + document += section + + env.prepare_settings(docName) + try: + sphinxApplication.events.emit("doctree-read", document) + finally: + env.prepare_settings("") + env.ref_context.clear() + + # the navigation shows a page's testsuites and testcases, not its sections + pageEntry = env.tocs[docName][0] + for entries in pageEntry[1:]: + entries[:] = [entry for entry in entries if isinstance(entry, addnodes.toctree)] + if len(entries) == 0: + pageEntry.remove(entries) + + env.all_docs[docName] = time_ns() // 1_000 + domain.AddUnittestEntry(roleName, self._entries[id(entity)]) + sphinxApplication.builder.write_doctree(docName, document) + + def TableOfContents(self, docName: str) -> nodes.compound: + """ + Create the hidden table of contents of the report's top-level testsuites, for the document showing its summary. + + The pages are then below that document in the navigation. + + :param docName: Name of the document showing the report's summary. + :returns: The table of contents. + """ + children = [ + entry.docName + for testsuite in sorted(self._summary._testsuites.values(), key=lambda item: item._name) + if (entry := self.Entry(testsuite)) is not None + ] + return self._TableOfContents(docName, children) + + @staticmethod + def _TableOfContents(docName: str, children: list[str]) -> nodes.compound: + """ + Create a hidden table of contents listing pages. + + :param docName: Name of the document holding the table of contents. + :param children: Names of the listed pages' documents. + :returns: The table of contents. + """ + toctree = addnodes.toctree( + parent=docName, entries=[(None, child) for child in children], includefiles=children, maxdepth=1, + caption=None, glob=False, hidden=True, includehidden=False, titlesonly=True, numbered=0 + ) + return nodes.compound("", toctree, classes=["toctree-wrapper"]) + + def _Reference(self, roleName: str, entity: Testsuite | Testcase, docName: str) -> nodes.Node: + """ + Create a reference to the page of a testsuite or testcase, or its name if it has no page. + + :param roleName: The role referring to it: ``ts`` or ``tc``. + :param entity: The testsuite or testcase. + :param docName: Name of the document holding the reference. + :returns: The reference, or the name as text. + """ + if (entry := self.Entry(entity)) is None: + return nodes.Text(entity._name) + + return UnittestSummary.CreateReference(roleName, entry, docName) + + def _PageSection(self, entity: Testsuite | Testcase) -> nodes.section: + """ + Create a page's top section: the name as title, then the title, summary and description of the report, if any. + + The title is shown as a lead line, if it differs from the name. The summary is shown, if it differs from the + title. The description is shown without its first paragraph, if that is the summary. The texts are shown as + plain text: a paragraph per block, and a literal block for an indented block. + + :param entity: The testsuite or testcase. + :returns: The section. + """ + section = nodes.section("", nodes.title(entity._name, entity._name), ids=["report-unittest-page"]) + + title, summary, description = entity._title, entity._summary, entity._description + if title is not None and title != entity._name: + section += nodes.paragraph("", "", nodes.strong(title, title), classes=["report-unittest-title"]) + + if summary is not None and summary != title: + section += nodes.paragraph(summary, summary, classes=["report-unittest-summary"]) + + if description is not None: + if summary is not None and description.startswith(summary): + description = description[len(summary):] + + for block in description.strip("\n").split("\n\n"): + lines = [line for line in block.split("\n") if line.strip() != ""] + if len(lines) == 0: + continue + elif all(line[0] in " \t" for line in lines): + text = dedent("\n".join(lines)) + section += nodes.literal_block(text, text, language="text", classes=["report-unittest-description"]) + else: + text = " ".join(line.strip() for line in lines) + section += nodes.paragraph(text, text, classes=["report-unittest-description"]) + + return section + + def _Field(self, fieldList: nodes.field_list, name: str, *content: nodes.Node) -> None: + """ + Add a field to a page's summary. + + :param fieldList: The summary's field list. + :param name: The field's name. + :param content: The field's value. + """ + fieldList += nodes.field("", nodes.field_name(name, name), nodes.field_body("", nodes.paragraph("", "", *content))) + + def _Table(self, columns: list[tuple[str, int]], classes: list[str]) -> tuple[nodes.table, nodes.tbody]: + """ + Create a table with a header row. + + :param columns: One ``(title, width)`` pair per column. + :param classes: CSS classes of the table. + :returns: The table, and its body the rows are added to. + """ + table = nodes.table("", classes=classes) + table += (tableGroup := nodes.tgroup(cols=len(columns))) + for _, width in columns: + tableGroup += nodes.colspec(colwidth=width) + + tableGroup += (tableHeader := nodes.thead()) + tableHeader += (headerRow := nodes.row()) + for columnTitle, _ in columns: + headerRow += nodes.entry("", nodes.paragraph(columnTitle, columnTitle)) + + tableGroup += (tableBody := nodes.tbody()) + return table, tableBody + + def _TestcasePage(self, docName: str, testcase: Testcase) -> nodes.section: + """ + Build a testcase's page: its status, duration, assertions and testsuite, its message and its captured output. + + :param docName: Name of the page's document. + :param testcase: The testcase. + :returns: The page's top section. + """ + page = self._PageSection(testcase) + status = testcase._status + + page += (summarySection := nodes.section("", nodes.title("Summary", "Summary"), ids=["summary"])) + summarySection += (fieldList := nodes.field_list(classes=["report-unittest-fields"])) + symbol = UnittestSummary._ConvertTestcaseStatusToSymbol(status) + self._Field(fieldList, "Status", nodes.Text(f"{symbol} {status.name}")) + self._Field(fieldList, "Duration", nodes.Text(UnittestSummary._FormatTimedelta(testcase._totalDuration))) + if testcase._assertionCount is not None: + self._Field(fieldList, "Assertions", nodes.Text(f"{testcase._assertionCount}")) + self._Field(fieldList, "Testsuite", self._Reference("ts", testcase._parent, docName)) + + for identifier, title, texts in ( + ("message", "Message", (testcase._message, testcase._details)), + ("standard-output", "Standard Output", (testcase._standardOutput, )), + ("standard-error", "Standard Error", (testcase._standardError, )), + ): + if all(text is None for text in texts): + continue + + page += (section := nodes.section("", nodes.title(title, title), ids=[identifier])) + for text in texts: + if text is not None: + section += nodes.literal_block(text, text, language="text", classes=[f"report-unittest-{identifier}"]) + + return page + + def _TestsuitePage(self, docName: str, testsuite: Testsuite) -> nodes.section: + """ + Build a testsuite's page: its status, counts, duration and assertions, then tables of its testsuites and + testcases, each linked to its page. + + :param docName: Name of the page's document. + :param testsuite: The testsuite. + :returns: The page's top section. + """ + page = self._PageSection(testsuite) + status = testsuite._status + testcases = list(testsuite.IterateTestcases()) + withAssertions = any(testcase._assertionCount is not None for testcase in testcases) + + page += (summarySection := nodes.section("", nodes.title("Summary", "Summary"), ids=["summary"])) + summarySection += (fieldList := nodes.field_list(classes=["report-unittest-fields"])) + symbol = UnittestSummary._ConvertTestsuiteStatusToSymbol(status) + self._Field(fieldList, "Status", nodes.Text(f"{symbol} {status.name}")) + self._Field( + fieldList, "Testcases", + nodes.Text( + f"{testsuite.TestcaseCount} - {testsuite.Passed} passed, {testsuite.Failed} failed, " + f"{testsuite.Errored} errored, {testsuite.Skipped} skipped" + ) + ) + self._Field(fieldList, "Duration", nodes.Text(UnittestSummary._FormatTimedelta(testsuite._totalDuration))) + if withAssertions: + self._Field(fieldList, "Assertions", nodes.Text(f"{testsuite.AssertionCount}")) + + if (parent := testsuite._parent) is not None and parent is not self._summary: + self._Field(fieldList, "Testsuite", self._Reference("ts", parent, docName)) + + children: list[str] = [] + if len(testsuite._testsuites) > 0: + page += (section := nodes.section("", nodes.title("Testsuites", "Testsuites"), ids=["testsuites"])) + table, tableBody = self._Table( + [("Testsuite", 6), ("Status", 2), ("Testcases", 1), ("Duration", 2)], ["report-unittest-testsuites"] + ) + section += table + for nested in sorted(testsuite._testsuites.values(), key=lambda item: item._name): + symbol = UnittestSummary._ConvertTestsuiteStatusToSymbol(nested._status) + tableBody += (row := nodes.row("", classes=[f"testsuite-{nested._status.name.lower()}"])) + row += nodes.entry("", nodes.paragraph("", "", self._Reference("ts", nested, docName))) + row += nodes.entry("", nodes.paragraph("", f"{symbol} {nested._status.name}")) + row += nodes.entry("", nodes.paragraph("", f"{nested.TestcaseCount}")) + row += nodes.entry("", nodes.paragraph("", UnittestSummary._FormatTimedelta(nested._totalDuration))) + if (entry := self.Entry(nested)) is not None: + children.append(entry.docName) + + if len(testsuite._testcases) > 0: + page += (section := nodes.section("", nodes.title("Testcases", "Testcases"), ids=["testcases"])) + columns = [("Testcase", 6), ("Status", 2), ("Duration", 2)] + if withAssertions: + columns.append(("Assertions", 1)) + table, tableBody = self._Table(columns, ["report-unittest-testcases"]) + section += table + for testcase in sorted(testsuite._testcases.values(), key=lambda item: item._name): + symbol = UnittestSummary._ConvertTestcaseStatusToSymbol(testcase._status) + tableBody += (row := nodes.row("", classes=[f"testcase-{testcase._status.name.lower()}"])) + row += nodes.entry("", nodes.paragraph("", "", self._Reference("tc", testcase, docName))) + row += nodes.entry("", nodes.paragraph("", f"{symbol} {testcase._status.name}")) + row += nodes.entry("", nodes.paragraph("", UnittestSummary._FormatTimedelta(testcase._totalDuration))) + if withAssertions: + assertions = "" if testcase._assertionCount is None else f"{testcase._assertionCount}" + row += nodes.entry("", nodes.paragraph("", assertions)) + + if (entry := self.Entry(testcase)) is not None: + children.append(entry.docName) + + if len(children) > 0: + # body elements precede a section's subsections, so the hidden table of contents goes before 'Summary' + page.insert(page.index(summarySection), self._TableOfContents(docName, children)) + + return page diff --git a/pyTooling/Sphinx/__init__.py b/pyTooling/Sphinx/__init__.py index 84f34c8..75db6d0 100644 --- a/pyTooling/Sphinx/__init__.py +++ b/pyTooling/Sphinx/__init__.py @@ -79,7 +79,9 @@ ``pyTooling_DocCoverage_Packages`` declaring the reports. Reading a report needs the extra ``reports`` (pyEDAA.Reports), which is imported only then: - * :rst:dir:`report:unittest-summary` - a unit test report, per testsuite and testcase; + * :rst:dir:`report:unittest-summary` - a unit test report, per testsuite and testcase; a report declared with + ``pages`` gets a page per testsuite and testcase (:mod:`~pyTooling.Sphinx.UnittestPages`), which the roles + ``:ts:`` and ``:tc:`` - also ``:report:ts:`` and ``:report:tc:`` - refer to; * :rst:dir:`report:code-coverage` and :rst:dir:`report:code-coverage-legend` - a code coverage report and its coverage levels; * :rst:dir:`report:doc-coverage` and :rst:dir:`report:doc-coverage-legend` - a package's documentation coverage @@ -116,7 +118,7 @@ from hashlib import md5 from pathlib import Path from re import match as re_match -from typing import Any, Iterable, Optional as Nullable, TypeVar +from typing import Any, Iterable, Iterator, NamedTuple, Optional as Nullable, TypeVar from docutils import nodes from sphinx.addnodes import pending_xref @@ -124,13 +126,15 @@ from sphinx.builders import Builder from sphinx.config import Config from sphinx.directives import ObjectDescription -from sphinx.domains import Domain +from sphinx.domains import Domain, ObjType from sphinx.environment import BuildEnvironment -from sphinx.errors import ExtensionError +from sphinx.errors import ExtensionError, NoUri +from sphinx.roles import XRefRole from sphinx.util.logging import getLogger +from sphinx.util.nodes import make_refnode from pyTooling.Common import readResourceFile -from pyTooling.Decorators import export +from pyTooling.Decorators import export, readonly from pyTooling.Documentation import DocumentationError from pyTooling.Sphinx import Resources as SphinxResources @@ -140,7 +144,7 @@ from pyTooling.Sphinx.Node import Abbreviation, Landscape, RegisteredNode, TreeItem, TreeLabel -__all__ = ["STYLESHEET", "SUBSTITUTIONS", "NODES", "INDENTATION"] +__all__ = ["STYLESHEET", "SUBSTITUTIONS", "NODES", "INDENTATION", "UNITTEST_ROLES"] #: Name of the stylesheet, in :mod:`pyTooling.Sphinx.Resources`. STYLESHEET = "pyTooling.css" @@ -173,6 +177,13 @@ #: The character a report table indents an entry by, per level of the hierarchy: an em quad, which HTML keeps. INDENTATION = "\u2001" +#: The roles referring to a testcase or testsuite of a unit test report, mapping a role's name to the object type and +#: the key of the domain data holding these objects. +UNITTEST_ROLES = { + "tc": ("testcase", "testcases"), + "ts": ("testsuite", "testsuites"), +} + _EnumType = TypeVar("_EnumType", bound=Enum) """Type of an enumeration read from a directive's options.""" @@ -566,27 +577,162 @@ def extendProlog(sphinx: Sphinx, config: Any) -> None: config.rst_prolog = (config.rst_prolog or "") + SUBSTITUTIONS +@export +class UnittestEntry(NamedTuple): + """A testsuite or testcase of a unit test report, which has a page of its own: where it is, and its names.""" + + docName: str #: Name of the generated document showing the testsuite or testcase. + reportID: str #: Identifier of the report in ``pyTooling_Unittest_Testsuites``. + path: tuple[str, ...] #: Names of the testsuites below the report's summary, down to this entry's own name. + title: Nullable[str] #: Title of the testsuite or testcase written for a reader, if the report has one. + + @readonly + def Name(self) -> str: + """ + Read-only property to return the testsuite's or testcase's own name, the last element of :attr:`path`. + + :returns: The name. + """ + return self.path[-1] + + @readonly + def QualifiedName(self) -> str: + """ + Read-only property to return the qualified name: the names of :attr:`path` joined by ``.``. + + :returns: The qualified name, e.g. ``pytest.tests.unit.Arithmetic.Addition.test_Positive``. + """ + return ".".join(self.path) + + def Matches(self, name: str) -> bool: + """ + Check whether a name is the qualified name or a suffix of it, which starts at the name of a testsuite. + + :param name: The name as written in a reference, without a report ID. + :returns: ``True`` if the name is the qualified name or one of its suffixes. + """ + return any(".".join(self.path[index:]) == name for index in range(len(self.path))) + + +@export +class UnittestRole(XRefRole): + """ + A role referring to a testcase (``tc``) or testsuite (``ts``) of a unit test report in domain ``report``. + + Sphinx registers a role outside a domain without one, so the reference would be resolved by nobody; this role puts + domain ``report`` on the reference, and uses its name as the reference's type. So it works as ``:report:tc:`` and + as the global ``:tc:``. + """ + + def run(self) -> tuple[list[nodes.Node], list[nodes.system_message]]: + """ + Create the reference, or only the text if the role is written with ``!``. + + :returns: The nodes and messages a role returns. + """ + self.refdomain = ReportDomain.name + self.reftype = self.name.rpartition(":")[2] + self.classes = ["xref", ReportDomain.name, f"{ReportDomain.name}-{self.reftype}"] + + if self.disabled: + return self.create_non_xref_node() + + return self.create_xref_node() + + @export class ReportDomain(Domain): """ The Sphinx domain ``report``, integrating unit test, code coverage and documentation coverage reports. Its directives are registered by :func:`setup`, and read their reports from the files declared in :file:`conf.py`. + + A unit test report with generated pages contributes its testsuites and testcases as objects, which the roles + ``:report:ts:`` and ``:report:tc:`` - also registered as ``:ts:`` and ``:tc:`` - refer to. A reference names an + object by its qualified name, or by a suffix of it, optionally preceded by the report's identifier and a colon; + without one, the first report of ``pyTooling_Unittest_Testsuites`` is meant. """ name = "report" #: Name of the domain, the prefix of its directives. label = "rpt" #: Name of the domain, as displayed. - def merge_domaindata(self, docnames: Iterable[str], otherdata: dict[str, Any]) -> None: + object_types = { + objectType: ObjType(objectType, roleName) for roleName, (objectType, _) in UNITTEST_ROLES.items() + } #: The objects: testsuites and testcases of unit test reports with generated pages. + initial_data: dict[str, Any] = { + dataKey: {} for _, dataKey in UNITTEST_ROLES.values() + } #: The data of an empty documentation: no testsuite and no testcase. + roles = { + roleName: UnittestRole(innernodeclass=nodes.inline, warn_dangling=True) for roleName in UNITTEST_ROLES + } #: The roles, also registered without the domain's prefix. + dangling_warnings = { + roleName: f"{objectType} '%(target)s' not found in the unit test reports" + for roleName, (objectType, _) in UNITTEST_ROLES.items() + } #: The warning for a reference to an unknown testsuite or testcase, per role. + + def AddUnittestEntry(self, roleName: str, entry: UnittestEntry) -> None: + """ + Register a testsuite or testcase which has a generated page. + + :param roleName: The role referring to the object: ``tc`` for a testcase, ``ts`` for a testsuite. + :param entry: The testsuite or testcase. + """ + self.data[UNITTEST_ROLES[roleName][1]].setdefault(entry.reportID, {})[entry.QualifiedName] = entry + + def FindUnittestEntries(self, roleName: str, target: str) -> list[UnittestEntry]: + """ + Find the testsuites or testcases a reference's target names. + + A target is ``[:]``. If the part before the first colon isn't the identifier of a report, the + whole target is the name in the default report - the first one of ``pyTooling_Unittest_Testsuites`` -, as + e.g. a parametrized testcase's name may contain a colon. A name is a qualified name or a suffix of one (see + :meth:`UnittestEntry.Matches`); an exact qualified name wins over suffixes. + + :param roleName: The role referring to the object: ``tc`` for a testcase, ``ts`` for a testsuite. + :param target: The reference's target. + :returns: The matching entries: none, one, or several if the name is ambiguous. + """ + reports: dict[str, dict[str, UnittestEntry]] = self.data[UNITTEST_ROLES[roleName][1]] + configuredReports = list(self.env.config["pyTooling_Unittest_Testsuites"]) + + reportID, separator, name = target.partition(":") + if separator == "" or reportID not in configuredReports: + if len(configuredReports) == 0: + return [] + + reportID, name = configuredReports[0], target + + entries = reports.get(reportID, {}) + if (entry := entries.get(name)) is not None: + return [entry] + + return [entry for entry in entries.values() if entry.Matches(name)] + + def clear_doc(self, docname: str) -> None: + """ + Forget the testsuites and testcases of a document, before it is generated again. + + :param docname: Name of the document. """ - Take over what a parallel reader collected for its documents: nothing, as the domain holds no data. + for _, dataKey in UNITTEST_ROLES.values(): + for entries in self.data[dataKey].values(): + for qualifiedName in [name for name, entry in entries.items() if entry.docName == docname]: + del entries[qualifiedName] - Sphinx calls it for every domain of a parallel build (``-j``); the base-class' implementation raises - :exc:`NotImplementedError`. + def merge_domaindata(self, docnames: Iterable[str], otherdata: dict[str, Any]) -> None: + """ + Take over the testsuites and testcases a parallel reader collected for its documents. :param docnames: Names of the documents the other reader read. :param otherdata: The other reader's domain data. """ + documents = set(docnames) + for _, dataKey in UNITTEST_ROLES.values(): + for reportID, entries in otherdata[dataKey].items(): + ownEntries = self.data[dataKey].setdefault(reportID, {}) + for qualifiedName, entry in entries.items(): + if entry.docName in documents: + ownEntries[qualifiedName] = entry def resolve_xref( self, @@ -599,20 +745,91 @@ def resolve_xref( contnode: nodes.Element ) -> Nullable[nodes.Element]: """ - Resolve a cross-reference of this domain, which has none: the domain has no roles and no objects. + Resolve a reference to a testsuite or testcase into a link to its page. + + The link shows the testsuite's or testcase's name, or the title written in the role; in HTML, its title written + for a reader - if the report has one - is shown on hover. An ambiguous name is warned about and shown as text. + + :param env: The build environment. + :param fromdocname: Name of the document holding the reference. + :param builder: The builder writing the documents. + :param typ: The role's name: ``tc`` or ``ts``. + :param target: The testsuite or testcase referred to. + :param node: The reference. + :param contnode: The reference's text. + :returns: The link, the text if the name is ambiguous or the builder doesn't write the page, or + ``None`` if nothing matches. + """ + if typ not in UNITTEST_ROLES: + return None + + entries = self.FindUnittestEntries(typ, target) + if len(entries) == 0: + return None + elif len(entries) > 1: + candidates = ", ".join(sorted(f"{entry.reportID}:{entry.QualifiedName}" for entry in entries)) + getLogger(__name__).warning( + f"{UNITTEST_ROLES[typ][0]} '{target}' is ambiguous, candidates: {candidates}", + location=node, type="ref", subtype=typ + ) + return contnode + + entry = entries[0] + if node.get("refexplicit", False): + content = contnode + else: + content = nodes.inline(entry.Name, entry.Name, classes=contnode["classes"]) + + try: + return make_refnode(builder, fromdocname, entry.docName, None, content, entry.title) + except NoUri: + # e.g. LaTeX writes only the documents of its toctree, so a link to a page becomes the name + return content - Raises :exc:`NotImplementedError` always. Sphinx doesn't call it, as no role creates a reference of this domain. + def resolve_any_xref( + self, + env: BuildEnvironment, + fromdocname: str, + builder: Builder, + target: str, + node: pending_xref, + contnode: nodes.Element + ) -> list[tuple[str, nodes.reference]]: + """ + Resolve a reference of role ``:any:`` to a testsuite or testcase with an unambiguous name. :param env: The build environment. - :param fromdocname: Name of the document the reference is in. - :param builder: The builder. - :param typ: Type of the reference. - :param target: Target of the reference. - :param node: The pending cross-reference. - :param contnode: The node holding the reference's text. - :returns: Never. + :param fromdocname: Name of the document holding the reference. + :param builder: The builder writing the documents. + :param target: The text referred to. + :param node: The reference. + :param contnode: The reference's text. + :returns: A role and link per kind of object the text names unambiguously. """ - raise NotImplementedError() + results: list[tuple[str, nodes.reference]] = [] + for roleName in UNITTEST_ROLES: + if len(entries := self.FindUnittestEntries(roleName, target)) == 1: + entry = entries[0] + content = nodes.inline(entry.Name, entry.Name, classes=contnode["classes"]) + reference = make_refnode(builder, fromdocname, entry.docName, None, content, entry.title) + results.append((f"{self.name}:{roleName}", reference)) + + return results + + def get_objects(self) -> Iterator[tuple[str, str, str, str, str, int]]: + """ + Name the testsuites and testcases, for the search and for other documentations referring to them. + + An object's name is ``:``. Testcases get a lower search priority than testsuites, as + a report may have thousands of them. + + :returns: A tuple per object: name, display name, type, document, anchor and search priority. + """ + for roleName, (objectType, dataKey) in UNITTEST_ROLES.items(): + priority = 2 if roleName == "tc" else 1 + for reportID, entries in self.data[dataKey].items(): + for qualifiedName, entry in entries.items(): + yield f"{reportID}:{qualifiedName}", entry.QualifiedName, objectType, entry.docName, "", priority @export @@ -645,15 +862,17 @@ def checkReportConfiguration(sphinx: Sphinx, config: Config) -> None: @export def readReports(sphinx: Sphinx) -> None: """ - Call-back for Sphinx' ``builder-inited`` event, reading the report files. + Call-back for Sphinx' ``builder-inited`` event, reading the report files and registering the unit test reports' pages. :param sphinx: The Sphinx application. """ - from pyTooling.Sphinx.CodeCoverage import CodeCoverageBase - from pyTooling.Sphinx.Unittest import UnittestSummary + from pyTooling.Sphinx.CodeCoverage import CodeCoverageBase + from pyTooling.Sphinx.Unittest import UnittestSummary + from pyTooling.Sphinx.UnittestPages import UnittestReportPages CodeCoverageBase.ReadReports(sphinx) UnittestSummary.ReadReports(sphinx) + UnittestReportPages.CreatePages(sphinx) @export @@ -682,6 +901,7 @@ def setup(sphinx: Sphinx) -> dict[str, Any]: from pyTooling.Sphinx.Tree import Tree from pyTooling.Sphinx.Unittest import CONFIG_PREFIX as UNITTEST_PREFIX from pyTooling.Sphinx.Unittest import UnittestSummary + from pyTooling.Sphinx.UnittestPages import UnittestReportPages from pyTooling.Sphinx.Workaround import FixLatexTableWidths from pyTooling.Sphinx.XMLSchemaGraph import XMLSchemaGraph @@ -698,6 +918,10 @@ def setup(sphinx: Sphinx) -> dict[str, Any]: for roleName in ABBREVIATION_ROLES: sphinx.add_role(roleName, AbbreviationRole(innernodeclass=nodes.inline, warn_dangling=True)) + # the unit test roles outside their domain too: ':tc:', not only ':report:tc:' + for roleName in UNITTEST_ROLES: + sphinx.add_role(roleName, UnittestRole(innernodeclass=nodes.inline, warn_dangling=True)) + sphinx.add_directive("condensed-class", CondensedClass) sphinx.add_directive("dependency-table", DependencyTable) sphinx.add_directive("xmlschema-graph", XMLSchemaGraph) @@ -748,6 +972,8 @@ def setup(sphinx: Sphinx) -> dict[str, Any]: sphinx.connect("config-inited", prepareEntrypoints) sphinx.connect("config-inited", checkReportConfiguration) sphinx.connect("builder-inited", readReports) + sphinx.connect("env-before-read-docs", UnittestReportPages.GenerateAll) + sphinx.connect("html-page-context", UnittestReportPages.HideSource) sphinx.connect("build-finished", reportBuildTime) sphinx.connect("builder-inited", installStylesheet) diff --git a/tests/data/Report/TestReport.xml b/tests/data/Report/TestReport.xml new file mode 100644 index 0000000..0a7b098 --- /dev/null +++ b/tests/data/Report/TestReport.xml @@ -0,0 +1,77 @@ + + + + Test code of the example project. + Test code of the example project. + + Unit tests of the example project. + Unit tests of the example project. + + Unit tests for the arithmetic operations. + Unit tests for the arithmetic operations. + + Addition of integers + Add two integers. + Add two integers. + +Every testcase adds two small integers and checks the sum. + + One plus one is two. + One plus one is two. + One plus one is two. + +The simplest addition there is. + + + One plus two is four. + One plus two is four - a deliberately failing testcase. + One plus two is four - a deliberately failing testcase. + self = <tests.unit.Arithmetic.Addition testMethod=OnePlusTwo> + + @testcase("One plus two is four.") + def OnePlusTwo(self) -> None: + """One plus two is four - a deliberately failing testcase.""" + print("adding 1 and 2", file=sys.stderr) +> self.assertEqual(4, 1 + 2) +E AssertionError: 4 != 3 + +tests/unit/Arithmetic.py:30: AssertionError + + + Negative + + + + Division of integers + Divide two integers. + Divide two integers. + + Dividing by zero raises an error. + Dividing by zero is an error, not a failure. + Dividing by zero is an error, not a failure. + self = <tests.unit.Arithmetic.Division testMethod=ByZero> + + @testcase("Dividing by zero raises an error.") + def ByZero(self) -> None: + """Dividing by zero is an error, not a failure.""" +> _ = 1 // 0 + ^^^^^^ +E ZeroDivisionError: division by zero + +tests/unit/Arithmetic.py:44: ZeroDivisionError + + + Dividing by a fraction. + Skipped until fractions exist. + Skipped until fractions exist. + + + Integer division rounds up. + Integer division rounds down, so this is expected to fail. + Integer division rounds down, so this is expected to fail. + + + + + + \ No newline at end of file diff --git a/tests/data/Report/unittest.xml b/tests/data/Report/unittest.xml index a9162d2..60a3368 100644 --- a/tests/data/Report/unittest.xml +++ b/tests/data/Report/unittest.xml @@ -1,15 +1,22 @@ - - - + + 1 + 2 = 3 + Traceback (most recent call last): ... + dividing 1 by 0 + warning: division by zero + + KeyError: 'precision' + diff --git a/tests/unit/Extension.py b/tests/unit/Extension.py index e84c66b..991e777 100644 --- a/tests/unit/Extension.py +++ b/tests/unit/Extension.py @@ -44,7 +44,7 @@ from pyTooling.Testing import Testcase, testsuite, testcase -from pyTooling.Sphinx import __version__, NODES, SUBSTITUTIONS, setup +from pyTooling.Sphinx import __version__, NODES, SUBSTITUTIONS, UNITTEST_ROLES, setup from pyTooling.Sphinx import HTML, LaTeX from pyTooling.Sphinx.Abbreviation import ROLES as ABBREVIATION_ROLES, AbbreviationDomain from pyTooling.Sphinx.Node import Landscape @@ -162,14 +162,17 @@ def RolesAndDirectives(self) -> None: The extension's setup() registers every role and directive it brings. Calls setup() with a mocked application and compares the names passed to 'add_role' and 'add_directive' with the - style, break, code and abbreviation roles and the six directives, and checks the abbreviation domain is added. + style, break, code, abbreviation and unit test roles and the six directives, and checks the abbreviation domain + is added. """ app = MagicMock() metadata = setup(app) roles = {call.args[0] for call in app.add_role.call_args_list} directives = {call.args[0] for call in app.add_directive.call_args_list} - self.assertEqual(set(STYLE_ROLES) | set(BREAK_ROLES) | {PYTHON_CODE_ROLE} | set(ABBREVIATION_ROLES), roles) + self.assertEqual( + set(STYLE_ROLES) | set(BREAK_ROLES) | {PYTHON_CODE_ROLE} | set(ABBREVIATION_ROLES) | set(UNITTEST_ROLES), roles + ) self.assertEqual( {"condensed-class", "dependency-table", "xmlschema-graph", "shields", "tree", "abbreviations"}, directives diff --git a/tests/unit/UnittestPages.py b/tests/unit/UnittestPages.py new file mode 100644 index 0000000..0c1c8d2 --- /dev/null +++ b/tests/unit/UnittestPages.py @@ -0,0 +1,548 @@ +# ==================================================================================================================== # +# _____ _ _ ____ _ _ # +# _ __ _ |_ _|__ ___ | (_)_ __ __ _ / ___| _ __ | |__ (_)_ __ __ __ # +# | '_ \| | | || |/ _ \ / _ \| | | '_ \ / _` | \___ \| '_ \| '_ \| | '_ \\ \/ / # +# | |_) | |_| || | (_) | (_) | | | | | | (_| |_ ___) | |_) | | | | | | | |> < # +# | .__/ \__, ||_|\___/ \___/|_|_|_| |_|\__, (_)____/| .__/|_| |_|_|_| |_/_/\_\ # +# |_| |___/ |___/ |_| # +# ==================================================================================================================== # +# Authors: # +# Patrick Lehmann # +# # +# License: # +# ==================================================================================================================== # +# Copyright 2026-2026 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 # +# ==================================================================================================================== # +# +""" +Unit tests for :mod:`pyTooling.Sphinx.UnittestPages`: the pages per testsuite and testcase, and the roles ``:tc:`` and +``:ts:`` referring to them, each built in a small Sphinx project. +""" +from os import sep +from pathlib import Path +from textwrap import dedent +from typing import Any + +from docutils import nodes +from sphinx import addnodes +from sphinx.testing.util import SphinxTestApp + +from pyTooling.Sphinx import ReportDomain, UnittestEntry +from pyTooling.Sphinx.Unittest import UnittestSummary +from pyTooling.Sphinx.UnittestPages import UnittestReportPages +from pyTooling.Testing import testsuite, testcase + +from tests.unit.Extension import Project + + +if __name__ == "__main__": # pragma: no cover + print("ERROR: you called a testcase declaration file as an executable module.") + print("Use: 'python -m unittest '") + exit(1) + + +DATA = Path(__file__).parent.parent / "data" / "Report" +"""Directory of the report files the testcases read.""" + +JUNIT_PAGES = "unittests/ut/pytest/tests/unit/Arithmetic" +"""Document name of the generated page of testsuite 'Arithmetic' in the JUnit report.""" + +PYTOOLING_PAGES = "unittests/pyt/tests/unit/Arithmetic" +"""Document name of the generated page of testsuite 'Arithmetic' in the pyTooling report.""" + + +class PagesProject(Project): + """Base-class of the testcases: a Sphinx project with a JUnit and a pyTooling report, both with pages.""" + + def _buildPages(self, index: str, builder: str = "html", **config: Any) -> SphinxTestApp: + """ + Write the document and build the project, with the two reports declared with pages. + + :param index: Content of the document ``index``. + :param builder: Optional, name of the builder. Default: ``"html"``. + :param config: Configuration values overriding the defaults. + :returns: The Sphinx application after the build. + """ + testsuites = { + "ut": {"xml_report": str(DATA / "unittest.xml"), "pages": "unittests/ut"}, + "pyt": {"xml_report": str(DATA / "TestReport.xml"), "pages": "/unittests/pyt/"}, + } + return self._build(index, builder, **({"pyTooling_Unittest_Testsuites": testsuites} | config)) + + def _body(self, name: str) -> str: + """ + Read the body of a built page, without the navigation. + + :param name: Name of the document. + :returns: The page's body. + """ + html = self._html(name) + return html[html.index('
None: + """ + A page's document name is the 'pages' prefix followed by the names of its testsuites, and its own name. + + Builds the project and checks the written files of both reports. + """ + self._buildPages("Index\n#####\n") + + self.assertEqual([], self._warningLines()) + html = self._path / "build" / "html" + for docName in ( + "unittests/ut/pytest", f"{JUNIT_PAGES}", f"{JUNIT_PAGES}/Division", f"{JUNIT_PAGES}/Division/test_ByZero", + f"{PYTOOLING_PAGES}/Addition/OnePlusOne" + ): + with self.subTest(docName=docName): + self.assertTrue((html / f"{docName}.html").exists()) + + self.assertFalse((html / "_sources" / f"{JUNIT_PAGES}.html.txt").exists()) + + @testcase("Testcase page") + def TestcasePage(self) -> None: + """ + A testcase's page shows its status, duration and testsuite, its message and its captured output. + + Builds the project and checks the page of a failed testcase with output. + """ + self._buildPages("Index\n#####\n") + + body = self._body(f"{JUNIT_PAGES}/Division/test_ByZero") + self.assertIn("

test_ByZero", body) + self.assertIn("

Summary", body) + self.assertIn("❌ Failed", body) + self.assertIn("00:00:00.070", body) + self.assertIn( + 'Division', + body + ) + self.assertIn("AssertionError: ZeroDivisionError not raised", body) + self.assertIn("Traceback (most recent call last): ...", body) + self.assertIn("

Standard Output", body) + self.assertIn("dividing 1 by 0", body) + self.assertIn("

Standard Error", body) + self.assertIn("warning: division by zero", body) + self.assertNotIn("Assertions", body) + + @testcase("Testcase page without output") + def TestcasePageWithoutOutput(self) -> None: + """ + A passed testcase's page has no message and no output sections. + + Builds the project and checks the page of a passed testcase without output. + """ + self._buildPages("Index\n#####\n") + + body = self._body(f"{JUNIT_PAGES}/Addition/test_Negative") + self.assertIn("✅ Passed", body) + self.assertNotIn("

Message", body) + self.assertNotIn("

Standard Output", body) + self.assertNotIn("

Standard Error", body) + + @testcase("Testsuite page") + def TestsuitePage(self) -> None: + """ + A testsuite's page shows its status and counts, and tables of its testsuites and testcases linked to their pages. + + Builds the project and checks the pages of 'Division' and 'Arithmetic'. + """ + self._buildPages("Index\n#####\n") + + body = self._body(f"{JUNIT_PAGES}/Division") + self.assertIn("❗ Errored", body) + self.assertIn("3 - 0 passed, 1 failed, 1 errored, 1 skipped", body) + self.assertIn("

Testcases", body) + for testcaseName in ("test_ByZero", "test_Fraction", "test_Rounding"): + with self.subTest(testcase=testcaseName): + self.assertIn( + f'href="Division/{testcaseName}.html">{testcaseName}', body + ) + + body = self._body(JUNIT_PAGES) + self.assertIn("

Testsuites", body) + self.assertIn('href="Arithmetic/Addition.html">Addition', body) + self.assertIn('href="Arithmetic/Division.html">Division', body) + + @testcase("Navigation") + def Navigation(self) -> None: + """ + A testsuite's page lists its children in a hidden table of contents, so the navigation works below it. + + Builds the project and checks the environment's table of contents and the pages' metadata. + """ + app = self._buildPages("Index\n#####\n") + + self.assertEqual( + [f"{JUNIT_PAGES}/Division/{name}" for name in ("test_ByZero", "test_Fraction", "test_Rounding")], + app.env.toctree_includes[f"{JUNIT_PAGES}/Division"] + ) + self.assertIn("orphan", app.env.metadata[f"{JUNIT_PAGES}/Division/test_ByZero"]) + self.assertEqual("test_ByZero", app.env.titles[f"{JUNIT_PAGES}/Division/test_ByZero"].astext()) + + @testcase("Navigation below the summary") + def NavigationBelowSummary(self) -> None: + """ + The summary directive lists the report's top-level testsuites in a hidden table of contents, so the pages are + below its document in the navigation; a page's own sections aren't listed there. + + Builds the project with the JUnit report's summary and checks the environment's table of contents. + """ + app = self._buildPages("Index\n#####\n\n.. report:unittest-summary::\n :reportid: ut\n") + + self.assertEqual([], self._warningLines()) + self.assertEqual(["unittests/ut/pytest"], app.env.toctree_includes["index"]) + self.assertNotIn("unittests/pyt/tests", app.env.toctree_includes["index"]) + for docName in (f"{JUNIT_PAGES}/Division", f"{JUNIT_PAGES}/Division/test_ByZero"): + with self.subTest(docName=docName): + toc = app.env.tocs[docName] + self.assertEqual(1, len(list(toc.findall(nodes.reference)))) + self.assertNotIn("Summary", toc.astext()) + + self.assertEqual(1, len(list(app.env.tocs[f"{JUNIT_PAGES}/Division"].findall(addnodes.toctree)))) + + @testcase("pyTooling report") + def pyToolingReport(self) -> None: + """ + A page of a pyTooling report shows the title, summary and description below the name. + + Builds the project and checks the pages of testsuite 'Addition' and testcase 'OnePlusOne'. + """ + self._buildPages("Index\n#####\n") + + body = self._body(f"{PYTOOLING_PAGES}/Addition") + self.assertIn("

Addition", body) + self.assertIn('

Addition of integers

', body) + self.assertIn('

Add two integers.

', body) + self.assertIn( + '

Every testcase adds two small integers and checks the sum.

', body + ) + + body = self._body(f"{PYTOOLING_PAGES}/Addition/OnePlusOne") + self.assertIn('

One plus one is two.

', body) + self.assertNotIn('class="report-unittest-summary"', body) + self.assertIn('

The simplest addition there is.

', body) + + body = self._body(f"{PYTOOLING_PAGES}/Addition/OnePlusTwo") + self.assertIn("E AssertionError: 4 != 3", body) + + @testcase("No pages without the key 'pages'") + def NoPages(self) -> None: + """ + A report without the key 'pages' gets neither pages nor objects, and its summary table doesn't link. + + Builds a unit test summary of a report declared without 'pages'. + """ + app = self._build( + "Index\n#####\n\n.. report:unittest-summary::\n :reportid: ut\n", + pyTooling_Unittest_Testsuites={"ut": {"xml_report": str(DATA / "unittest.xml")}} + ) + + self.assertEqual([], self._warningLines()) + self.assertFalse((self._path / "build" / "html" / "unittests").exists()) + domainData = app.env.domains[ReportDomain.name].data + self.assertEqual({}, domainData["testcases"]) + self.assertEqual({}, domainData["testsuites"]) + self.assertNotIn("report-tc", self._html("index")) + + @testcase("Unreadable report") + def UnreadableReport(self) -> None: + """ + A report with pages that can't be read gets no pages; the error is logged, and the summary shows it. + + Builds a unit test summary of a file whose root element is no report format. + """ + report = self._path / "unknown.xml" + report.write_text("\n", encoding="utf-8") + + self._build( + "Index\n#####\n\n.. report:unittest-summary::\n :reportid: bad\n", + pyTooling_Unittest_Testsuites={"bad": {"xml_report": str(report), "pages": "unittests/bad"}} + ) + + warnings = self._warningLines() + self.assertEqual( + "ERROR: Caught ReportExtensionError when generating the pages of unittest report 'bad'.", warnings[0] + ) + self.assertEqual(" ReportExtensionError: Unittest report 'unknown.xml' has an unknown format.", warnings[1]) + self.assertIn("ERROR: Caught ReportExtensionError when reading and parsing 'unknown.xml'.", warnings) + self.assertIn("ERROR: Got root element ''; supported: testsuites, testsuite, TestReport", warnings) + self.assertFalse((self._path / "build" / "html" / "unittests").exists()) + + @testcase("Summary table links") + def SummaryLinks(self) -> None: + """ + The unit test summary links a testsuite's and a testcase's name to its page, showing the title on hover. + + Builds a unit test summary of both reports. + """ + self._buildPages(dedent("""\ + Index + ##### + + .. report:unittest-summary:: + :reportid: ut + + .. report:unittest-summary:: + :reportid: pyt + """)) + + self.assertEqual([], self._warningLines()) + body = self._body("index") + self.assertIn( + f'❌' + f'test_ByZero', + body + ) + self.assertIn( + f'', body + ) + + @testcase("LaTeX") + def LaTeX(self) -> None: + """ + A LaTeX build writes the pages below the summary, as they are in its table of contents, so a reference to one + is a link. + + Builds the summary and a role as LaTeX. + """ + self._buildPages( + "Index\n#####\n\n.. report:unittest-summary::\n :reportid: ut\n\nSee :tc:`ut:Division.test_ByZero`.\n", "latex" + ) + + self.assertEqual([], self._warningLines()) + latex = next((self._path / "build" / "latex").glob("*.tex")).read_text(encoding="utf-8") + self.assertIn("\\label{\\detokenize{unittests/ut/pytest/tests/unit/Arithmetic/Division/test_ByZero::doc}}", latex) + self.assertIn( + "See {\\hyperref[\\detokenize{unittests/ut/pytest/tests/unit/Arithmetic/Division/test_ByZero::doc}]", latex + ) + + +@testsuite("Roles ':tc:' and ':ts:'") +class Roles(PagesProject): + """The roles referring to a testcase or testsuite, with or without a report ID, and in domain 'report'.""" + + _document = dedent("""\ + Index + ##### + + * :tc:`test_ByZero` + * :tc:`ut:Division.test_Fraction` + * :tc:`ut:pytest.tests.unit.Arithmetic.Division.test_Rounding` + * :ts:`Arithmetic` + * :tc:`pyt:OnePlusTwo` + * :report:ts:`pyt:Addition` + * :report:tc:`Positive case ` + """) + + @testcase("Resolution") + def Resolution(self) -> None: + """ + A reference resolves by qualified name or unique suffix, in the default report or the one named by its ID. + + Builds a document with references to both reports and checks the links. + """ + self._buildPages(self._document) + + self.assertEqual([], self._warningLines()) + body = self._body("index") + for href, text in ( + (f"{JUNIT_PAGES}/Division/test_ByZero.html", 'test_ByZero'), + (f"{JUNIT_PAGES}/Division/test_Fraction.html", 'test_Fraction'), + (f"{JUNIT_PAGES}/Division/test_Rounding.html", 'test_Rounding'), + (f"{JUNIT_PAGES}.html", 'Arithmetic'), + (f"{PYTOOLING_PAGES}/Addition/OnePlusTwo.html", 'OnePlusTwo'), + (f"{PYTOOLING_PAGES}/Addition.html", 'Addition'), + (f"{JUNIT_PAGES}/Addition/test_Positive.html", 'Positive case'), + ): + with self.subTest(href=href): + self.assertRegex(body, rf'{text}') + + @testcase("Unknown target") + def Unknown(self) -> None: + """ + A reference to an unknown testcase or testsuite is warned about; a testcase of another report needs its ID. + + Builds a document with an unknown testcase, a testcase of the second report without ID, and an unknown testsuite. + """ + self._buildPages("Index\n#####\n\n:tc:`test_Unknown` :tc:`OnePlusOne` :ts:`pyt:Unknown`\n") + + self.assertEqual( + [ + "src/index.rst:4: WARNING: testcase 'test_Unknown' not found in the unit test reports [ref.tc]", + "src/index.rst:4: WARNING: testcase 'OnePlusOne' not found in the unit test reports [ref.tc]", + "src/index.rst:4: WARNING: testsuite 'pyt:Unknown' not found in the unit test reports [ref.ts]", + ], + self._warningLines() + ) + + @testcase("Ambiguous target") + def Ambiguous(self) -> None: + """ + A suffix matching several testcases is warned about, naming the candidates, and shown as text. + + Builds a document referring to a testcase name two testsuites have. + """ + report = self._path / "ambiguous.xml" + report.write_text(dedent("""\ + + + + + + + + """), encoding="utf-8") + + self._build( + "Index\n#####\n\n:tc:`test_Same` :tc:`First.test_Same`\n", + pyTooling_Unittest_Testsuites={"amb": {"xml_report": str(report), "pages": "unittests/amb"}} + ) + + self.assertEqual( + [ + "src/index.rst:4: WARNING: testcase 'test_Same' is ambiguous, candidates: " + "amb:pytest.tests.First.test_Same, amb:pytest.tests.Second.test_Same [ref.tc]" + ], + self._warningLines() + ) + self.assertIn('href="unittests/amb/pytest/tests/First/test_Same.html"', self._html("index")) + + @testcase("Objects") + def Objects(self) -> None: + """ + The testsuites and testcases with pages are objects of domain 'report', named ':'. + + Builds the project and checks the domain's objects. + """ + app = self._buildPages("Index\n#####\n") + + domain: ReportDomain = app.env.domains[ReportDomain.name] + objects = {name: (objectType, docName) for name, _, objectType, docName, _, _ in domain.get_objects()} + self.assertEqual( + ("testcase", f"{JUNIT_PAGES}/Division/test_ByZero"), + objects["ut:pytest.tests.unit.Arithmetic.Division.test_ByZero"] + ) + self.assertEqual(("testsuite", PYTOOLING_PAGES), objects["pyt:tests.unit.Arithmetic"]) + self.assertEqual(5 + 6, sum(1 for objectType, _ in objects.values() if objectType == "testcase")) + + +@testsuite("Domain data") +class DomainData(PagesProject): + """The objects in the domain's data, forgotten per document and merged from a parallel reader.""" + + @testcase("Clear a document") + def ClearDoc(self) -> None: + """ + Clearing a generated document forgets its object, and only that one. + + Builds the project and clears the page of one testcase. + """ + app = self._buildPages("Index\n#####\n") + domain: ReportDomain = app.env.domains[ReportDomain.name] + + domain.clear_doc(f"{JUNIT_PAGES}/Division/test_ByZero") + + self.assertEqual([], domain.FindUnittestEntries("tc", "test_ByZero")) + self.assertEqual(1, len(domain.FindUnittestEntries("tc", "test_Fraction"))) + + @testcase("Merge a parallel reader's data") + def MergeDomainData(self) -> None: + """ + Merging takes over the objects of the documents the other reader read, and only those. + + Builds the project, and merges data holding two testcases, of which one document was read. + """ + app = self._buildPages("Index\n#####\n") + domain: ReportDomain = app.env.domains[ReportDomain.name] + + read = UnittestEntry("other/read", "ut", ("other", "test_Read"), None) + unread = UnittestEntry("other/unread", "ut", ("other", "test_Unread"), None) + domain.merge_domaindata( + ["other/read"], + {"testcases": {"ut": {"other.test_Read": read, "other.test_Unread": unread}}, "testsuites": {}} + ) + + self.assertEqual([read], domain.FindUnittestEntries("tc", "test_Read")) + self.assertEqual([], domain.FindUnittestEntries("tc", "test_Unread")) + + +@testsuite("Configuration key 'pages'") +class Configuration(Project): + """The key 'pages' of a report's configuration.""" + + def _check(self, pages: Any) -> list[str]: + """ + Build a project declaring a report with the given 'pages' and return the warnings. + + :param pages: The value of the key 'pages'. + :returns: The warnings. + """ + self._build( + "Index\n#####\n", pyTooling_Unittest_Testsuites={"ut": {"xml_report": str(DATA / "unittest.xml"), "pages": pages}} + ) + return self._warningLines() + + @testcase("Normalized") + def Normalized(self) -> None: + """ + Surrounding slashes are removed from the document name. + + Checks the loaded configuration after a build with '/unittests/ut/'. + """ + self.assertEqual([], self._check("/unittests/ut/")) + self.assertEqual("unittests/ut", UnittestSummary._testSummaries["ut"]["pages"]) + self.assertIsNotNone(UnittestReportPages.GetPages("ut")) + + @testcase("Not a relative document name") + def Invalid(self) -> None: + """ + A document name with '..', an empty part or a backslash is logged as an error. + + Builds projects with 'unittests/../ut', 'unittests//ut' and 'unittests\\ut'. On Windows, the warnings are + compared with '/' for '\\', as ``_warningLines()`` writes them. + """ + for pages in ("unittests/../ut", "unittests//ut", "unittests\\ut"): + with self.subTest(pages=pages): + written = pages.replace("\\", "/") if sep == "\\" else pages + self.assertEqual( + [ + "ERROR: Caught ReportExtensionError when checking configuration variables.", + f" conf.py: pyTooling_Unittest_Testsuites:[ut].pages: '{written}' is not a relative document name." + ], + self._check(pages) + ) + + @testcase("Not a string") + def NotAString(self) -> None: + """ + A document name that isn't a string is logged as an error. + + Builds a project with 'pages' set to a number. + """ + self.assertEqual( + [ + "ERROR: Caught ReportExtensionError when checking configuration variables.", + " conf.py: pyTooling_Unittest_Testsuites:[ut].pages: Document name is not a string." + ], + self._check(1) + )