From df1bf082f242cccdcb342000525bede537b95935 Mon Sep 17 00:00:00 2001 From: Kevin Brown-Silva Date: Thu, 27 Apr 2023 05:27:33 -0600 Subject: fix: source paths with trailing slashes causing inconsistent sources in XML report with relative_paths (#1608) * Added failing test for source with trailing slash This test is nearly identical to the one above it, with the only change being the source that is used. This may end up turning into a fixture instead if the tests end up being identical after the fix is made. * Strip trailing slash for relative source paths This fixes an issue introduced in 45cf7936ee605cfe06f7f5967a72a73198960120 where using `relative_files=True` and `src` with a trailing slash, the source inserted as `` in the XML report would also have a trailing slash. This also fixes an issue introduced in the same commit where an empty `` would be inserted as well for cases where the `src` has a trailing slash. --- coverage/xmlreport.py | 2 ++ tests/test_xml.py | 15 ++++++++++++++- 2 files changed, 16 insertions(+), 1 deletion(-) diff --git a/coverage/xmlreport.py b/coverage/xmlreport.py index 2c8fd0cc..b2180266 100644 --- a/coverage/xmlreport.py +++ b/coverage/xmlreport.py @@ -69,6 +69,8 @@ class XmlReporter: if os.path.exists(src): if not self.config.relative_files: src = files.canonical_filename(src) + else: + src = src.rstrip(r"\/") self.source_paths.add(src) self.packages: Dict[str, PackageData] = {} self.xml_out: xml.dom.minidom.Document diff --git a/tests/test_xml.py b/tests/test_xml.py index 94b310e3..0f2cff41 100644 --- a/tests/test_xml.py +++ b/tests/test_xml.py @@ -320,7 +320,7 @@ class XmlReportTest(XmlTestHelpers, CoverageTest): def test_no_duplicate_packages(self) -> None: self.make_file( - "namespace/package/__init__.py", + "namespace/package/__init__.py", "from . import sample; from . import test; from .subpackage import test" ) self.make_file("namespace/package/sample.py", "print('package.sample')") @@ -489,6 +489,19 @@ class XmlPackageStructureTest(XmlTestHelpers, CoverageTest): elts = dom.findall(".//sources/source") assert [elt.text for elt in elts] == ["src"] + def test_relative_source_trailing_slash(self) -> None: + self.make_file("src/mod.py", "print(17)") + cov = coverage.Coverage(source=["src/"]) + cov.set_option("run:relative_files", True) + self.start_import_stop(cov, "mod", modfile="src/mod.py") + cov.xml_report() + + with open("coverage.xml") as x: + print(x.read()) + dom = ElementTree.parse("coverage.xml") + elts = dom.findall(".//sources/source") + assert [elt.text for elt in elts] == ["src"] + def compare_xml(expected: str, actual: str, actual_extra: bool = False) -> None: """Specialized compare function for our XML files.""" -- cgit v1.2.1