diff --git a/AUTHORS b/AUTHORS index f04403e2d5c..77d09265e48 100644 --- a/AUTHORS +++ b/AUTHORS @@ -361,6 +361,7 @@ Milan Lesnek minbang930 Minh Dau Miro HronĨok +Mohanad Yehia Mohit Gaur Mulat Mekonen mrbean-bremen diff --git a/changelog/8654.bugfix.rst b/changelog/8654.bugfix.rst new file mode 100644 index 00000000000..ba4efe5feef --- /dev/null +++ b/changelog/8654.bugfix.rst @@ -0,0 +1 @@ +``record_xml_attribute`` now works with :pypi:`pytest-xdist`: attributes recorded in the workers are written to the JUnit XML report. When a test fails and its teardown also errors, the attributes now show up on both ``testcase`` elements, like :fixture:`record_property` already does for properties. diff --git a/src/_pytest/junitxml.py b/src/_pytest/junitxml.py index c8f7a09636e..cd77bdb0d72 100644 --- a/src/_pytest/junitxml.py +++ b/src/_pytest/junitxml.py @@ -11,6 +11,7 @@ from __future__ import annotations from collections.abc import Callable +from collections.abc import Generator import functools import os import platform @@ -29,15 +30,18 @@ from _pytest.fixtures import FixtureRequest from _pytest.nodeid import coerce_node_id from _pytest.nodeid import NodeId +from _pytest.nodes import Item from _pytest.reports import BaseReport from _pytest.reports import CollectReport from _pytest.reports import TestReport +from _pytest.runner import CallInfo from _pytest.stash import StashKey from _pytest.terminal import TerminalReporter import pytest xml_key = StashKey["LogXML"]() +xml_attributes_key = StashKey[dict[str, str]]() _JunitLogging = Literal["no", "log", "system-out", "system-err", "out-err", "all"] _JunitDurationReport = Literal["total", "call"] @@ -304,16 +308,23 @@ def finalize(self) -> None: def _warn_incompatibility_with_xunit2( - request: FixtureRequest, fixture_name: str + request: FixtureRequest, fixture_name: str, *, include_workers: bool = False ) -> None: """Emit a PytestWarning about the given fixture being incompatible with newer xunit revisions.""" from _pytest.warning_types import PytestWarning - xml = request.config.stash.get(xml_key, None) - if xml is not None and xml.family not in ("xunit1", "legacy"): + config = request.config + xml = config.stash.get(xml_key, None) + if xml is not None: + family = xml.family + elif include_workers and config.option.xmlpath: + family = config.getini("junit_family") + else: + return + if family not in ("xunit1", "legacy"): request.node.warn( PytestWarning( - f"{fixture_name} is incompatible with junit_family '{xml.family}' (use 'legacy' or 'xunit1')" + f"{fixture_name} is incompatible with junit_family '{family}' (use 'legacy' or 'xunit1')" ) ) @@ -354,7 +365,9 @@ def record_xml_attribute(request: FixtureRequest) -> Callable[[str, object], Non PytestExperimentalApiWarning("record_xml_attribute is an experimental feature") ) - _warn_incompatibility_with_xunit2(request, "record_xml_attribute") + _warn_incompatibility_with_xunit2( + request, "record_xml_attribute", include_workers=True + ) # Declare noop def add_attr_noop(name: str, value: object) -> None: @@ -362,14 +375,32 @@ def add_attr_noop(name: str, value: object) -> None: attr_func = add_attr_noop - xml = request.config.stash.get(xml_key, None) - if xml is not None: - node_reporter = xml.node_reporter(request.node.id) - attr_func = node_reporter.add_attribute + # Keep the attributes on the item, they get to LogXML through the test + # reports (see pytest_runtest_makereport below). With pytest-xdist the + # worker running the test has no LogXML, the controller writes the file. + if request.config.option.xmlpath: + xml_attributes = request.node.stash.setdefault(xml_attributes_key, {}) + + def add_attr(name: str, value: object) -> None: + xml_attributes[str(name)] = str(value) + + attr_func = add_attr return attr_func +@pytest.hookimpl(wrapper=True) +def pytest_runtest_makereport( + item: Item, call: CallInfo[None] +) -> Generator[None, TestReport, TestReport]: + report = yield + xml_attributes = item.stash.get(xml_attributes_key, None) + if xml_attributes: + # A copy with plain str values, so the report can be serialized. + report._junitxml_attributes = dict(xml_attributes) # type: ignore[attr-defined] + return report + + def _check_record_param_type(param: str, v: str) -> None: """Used by record_testsuite_property to check that the given parameter name is of the proper type.""" @@ -581,6 +612,9 @@ def add_stats(self, key: str) -> None: def _opentestcase(self, report: TestReport | CollectReport) -> _NodeReporter: reporter = self.node_reporter(report) + # Attributes from record_xml_attribute. + for name, value in getattr(report, "_junitxml_attributes", {}).items(): + reporter.add_attribute(name, value) reporter.record_testreport(report) return reporter diff --git a/testing/test_junitxml.py b/testing/test_junitxml.py index 27418049fae..4d19d0c8d69 100644 --- a/testing/test_junitxml.py +++ b/testing/test_junitxml.py @@ -1461,6 +1461,103 @@ def test_record(record_xml_attribute, other): ) +@pytest.mark.filterwarnings("default") +@parametrize_families +def test_record_attribute_on_test_and_teardown_failure( + pytester: Pytester, run_and_parse: RunAndParse, xunit_family: _JunitFamily +) -> None: + pytester.makepyfile( + """ + import pytest + + @pytest.fixture + def other(record_xml_attribute): + record_xml_attribute("bar", 1) + yield + record_xml_attribute("baz", 2) + assert 0 + + def test_record(record_xml_attribute, other): + record_xml_attribute("foo", "<1") + assert 0 + """ + ) + result, dom = run_and_parse(family=xunit_family) + result.assert_outcomes(failed=1, errors=1) + failure, error = dom.find_by_tag("testcase") + if xunit_family == "xunit1": + failure.assert_attr(bar="1", foo="<1") + error.assert_attr(bar="1", foo="<1", baz="2") + # For xunit2, run_and_parse validates the schema, which rejects the + # custom attributes, including the one recorded during teardown. + + +@pytest.mark.filterwarnings("default") +@parametrize_families +def test_record_attribute_xdist( + pytester: Pytester, + monkeypatch: MonkeyPatch, + run_and_parse: RunAndParse, + xunit_family: _JunitFamily, +) -> None: + """Attributes recorded on xdist workers end up in the XML written by the + controller (#8654).""" + pytest.importorskip("xdist") + monkeypatch.delenv("PYTEST_DISABLE_PLUGIN_AUTOLOAD", raising=False) + pytester.makepyfile( + """ + import pytest + + class Value: + def __str__(self): + return "value" + + @pytest.fixture + def other(record_xml_attribute): + record_xml_attribute("bar", 1) + def test_record(record_xml_attribute, other): + record_xml_attribute("foo", "<1") + record_xml_attribute("obj", Value()) + record_xml_attribute("classname", "custom_classname") + """ + ) + result, dom = run_and_parse("-n1", family=xunit_family) + tnode = dom.get_first_by_tag("testcase") + tnode.assert_attr(classname="custom_classname") + if xunit_family == "xunit1": + tnode.assert_attr(bar="1", foo="<1", obj="value") + else: + # run_and_parse validates that the custom attributes are dropped. + result.stdout.fnmatch_lines( + ["*record_xml_attribute is incompatible with junit_family 'xunit2'*"] + ) + result.stdout.fnmatch_lines(["*record_xml_attribute is an experimental feature"]) + + +def test_record_property_xdist( + pytester: Pytester, monkeypatch: MonkeyPatch, run_and_parse: RunAndParse +) -> None: + pytest.importorskip("xdist") + monkeypatch.delenv("PYTEST_DISABLE_PLUGIN_AUTOLOAD", raising=False) + pytester.makepyfile( + """ + import pytest + + @pytest.fixture + def other(record_property): + record_property("bar", 1) + def test_record(record_property, other): + record_property("foo", "<1") + """ + ) + _result, dom = run_and_parse("-n1") + tnode = dom.get_first_by_tag("testcase") + psnode = tnode.get_first_by_tag("properties") + pnodes = psnode.find_by_tag("property") + pnodes[0].assert_attr(name="bar", value="1") + pnodes[1].assert_attr(name="foo", value="<1") + + @pytest.mark.filterwarnings("default") @pytest.mark.parametrize("fixture_name", ["record_xml_attribute", "record_property"]) def test_record_fixtures_xunit2(