Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Allow Class.from_parent to forward custom parameters to the constructor #8367

Merged
merged 2 commits into from Feb 23, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
1 change: 1 addition & 0 deletions changelog/8367.bugfix.rst
@@ -0,0 +1 @@
Fix ``Class.from_parent`` so it forwards extra keyword arguments to the constructor.
4 changes: 2 additions & 2 deletions src/_pytest/python.py
Expand Up @@ -763,9 +763,9 @@ class Class(PyCollector):
"""Collector for test methods."""

@classmethod
def from_parent(cls, parent, *, name, obj=None):
def from_parent(cls, parent, *, name, obj=None, **kw):
"""The public constructor."""
return super().from_parent(name=name, parent=parent)
return super().from_parent(name=name, parent=parent, **kw)

def collect(self) -> Iterable[Union[nodes.Item, nodes.Collector]]:
if not safe_getattr(self.obj, "__test__", True):
Expand Down
16 changes: 16 additions & 0 deletions testing/test_collection.py
Expand Up @@ -1360,6 +1360,22 @@ def from_parent(cls, parent, *, fspath, x):
assert collector.x == 10


def test_class_from_parent(pytester: Pytester, request: FixtureRequest) -> None:
"""Ensure Class.from_parent can forward custom arguments to the constructor."""

class MyCollector(pytest.Class):
def __init__(self, name, parent, x):
super().__init__(name, parent)
self.x = x

@classmethod
def from_parent(cls, parent, *, name, x):
return super().from_parent(parent=parent, name=name, x=x)

collector = MyCollector.from_parent(parent=request.session, name="foo", x=10)
assert collector.x == 10


class TestImportModeImportlib:
def test_collect_duplicate_names(self, pytester: Pytester) -> None:
"""--import-mode=importlib can import modules with same names that are not in packages."""
Expand Down