From 7f5978c34c3863fb5d7a7ea1fb914bbd056b7965 Mon Sep 17 00:00:00 2001 From: Bruno Oliveira Date: Fri, 1 May 2020 10:58:47 -0300 Subject: [PATCH] Allow File.from_parent to forward custom parameters to the constructor --- changelog/7143.bugfix.rst | 1 + src/_pytest/nodes.py | 4 ++-- testing/test_collection.py | 21 +++++++++++++++++++++ 3 files changed, 24 insertions(+), 2 deletions(-) create mode 100644 changelog/7143.bugfix.rst diff --git a/changelog/7143.bugfix.rst b/changelog/7143.bugfix.rst new file mode 100644 index 00000000000..abf47dd0c2d --- /dev/null +++ b/changelog/7143.bugfix.rst @@ -0,0 +1 @@ +Fix ``File.from_constructor`` so it forwards extra keyword arguments to the constructor. diff --git a/src/_pytest/nodes.py b/src/_pytest/nodes.py index 6761aa79c52..03a4b1af8a2 100644 --- a/src/_pytest/nodes.py +++ b/src/_pytest/nodes.py @@ -483,11 +483,11 @@ def __init__( self._norecursepatterns = self.config.getini("norecursedirs") @classmethod - def from_parent(cls, parent, *, fspath): + def from_parent(cls, parent, *, fspath, **kw): """ The public constructor """ - return super().from_parent(parent=parent, fspath=fspath) + return super().from_parent(parent=parent, fspath=fspath, **kw) def _gethookproxy(self, fspath: py.path.local): # check if we have the common case of running diff --git a/testing/test_collection.py b/testing/test_collection.py index 050b5459812..2fd832dc6b7 100644 --- a/testing/test_collection.py +++ b/testing/test_collection.py @@ -1332,3 +1332,24 @@ def test_does_not_put_src_on_path(testdir): ) result = testdir.runpytest() assert result.ret == ExitCode.OK + + +def test_fscollector_from_parent(tmpdir, request): + """Ensure File.from_parent can forward custom arguments to the constructor. + + Context: https://github.com/pytest-dev/pytest-cpp/pull/47 + """ + + class MyCollector(pytest.File): + def __init__(self, fspath, parent, x): + super().__init__(fspath, parent) + self.x = x + + @classmethod + def from_parent(cls, parent, *, fspath, x): + return super().from_parent(parent=parent, fspath=fspath, x=x) + + collector = MyCollector.from_parent( + parent=request.session, fspath=tmpdir / "foo", x=10 + ) + assert collector.x == 10