Skip to content

Commit 54a154c

Browse files
committed
Allow Class.from_parent to forward custom parameters to the constructor
Similarly to #7143, at work we have a project with a custom pytest.Class subclass, adding an additional argument to the constructor. All from_parent implementations in pytest accept and forward *kw, except Class (before this change) and DoctestItem - since I'm not familiar with doctest support, I've left the latter as-is.
1 parent d6522b5 commit 54a154c

File tree

3 files changed

+21
-2
lines changed

3 files changed

+21
-2
lines changed

changelog/8367.bugfix.rst

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Fix ``Class.from_parent`` so it forwards extra keyword arguments to the constructor.

src/_pytest/python.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -763,9 +763,9 @@ class Class(PyCollector):
763763
"""Collector for test methods."""
764764

765765
@classmethod
766-
def from_parent(cls, parent, *, name, obj=None):
766+
def from_parent(cls, parent, *, name, obj=None, **kw):
767767
"""The public constructor."""
768-
return super().from_parent(name=name, parent=parent)
768+
return super().from_parent(name=name, parent=parent, **kw)
769769

770770
def collect(self) -> Iterable[Union[nodes.Item, nodes.Collector]]:
771771
if not safe_getattr(self.obj, "__test__", True):

testing/test_collection.py

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1360,6 +1360,24 @@ def from_parent(cls, parent, *, fspath, x):
13601360
assert collector.x == 10
13611361

13621362

1363+
def test_class_from_parent(pytester: Pytester, request: FixtureRequest) -> None:
1364+
"""Ensure Class.from_parent can forward custom arguments to the constructor."""
1365+
1366+
class MyCollector(pytest.Class):
1367+
def __init__(self, name, parent, x):
1368+
super().__init__(name, parent)
1369+
self.x = x
1370+
1371+
@classmethod
1372+
def from_parent(cls, parent, *, name, x):
1373+
return super().from_parent(parent=parent, name=name, x=x)
1374+
1375+
collector = MyCollector.from_parent(
1376+
parent=request.session, name="foo", x=10
1377+
)
1378+
assert collector.x == 10
1379+
1380+
13631381
class TestImportModeImportlib:
13641382
def test_collect_duplicate_names(self, pytester: Pytester) -> None:
13651383
"""--import-mode=importlib can import modules with same names that are not in packages."""

0 commit comments

Comments
 (0)