Skip to content

Commit

Permalink
python: add back instance accessor to all python nodes, not just Fu…
Browse files Browse the repository at this point in the history
…nction

Regressed in 062d91a (pytest 7.0.0rc1 only).

Fix pytest-dev#9486.
  • Loading branch information
bluetech committed Jan 9, 2022
1 parent abe2a8f commit f08a77d
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 18 deletions.
19 changes: 10 additions & 9 deletions src/_pytest/python.py
Original file line number Diff line number Diff line change
Expand Up @@ -283,6 +283,16 @@ def cls(self):
node = self.getparent(Class)
return node.obj if node is not None else None

@property
def instance(self):
"""Python instance object the function is bound to.
Returns None if not a test method, e.g. for a standalone test function,
a staticmethod, a class or a module.
"""
node = self.getparent(Function)
return getattr(node.obj, "__self__", None) if node is not None else None

@property
def obj(self):
"""Underlying Python object."""
Expand Down Expand Up @@ -1693,15 +1703,6 @@ def function(self):
"""Underlying python 'function' object."""
return getimfunc(self.obj)

@property
def instance(self):
"""Python instance object the function is bound to.
Returns None if not a test method, e.g. for a standalone test function
or a staticmethod.
"""
return getattr(self.obj, "__self__", None)

def _getobj(self):
assert self.parent is not None
if isinstance(self.parent, Class):
Expand Down
25 changes: 16 additions & 9 deletions testing/test_collection.py
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ def test_fail(): assert 0

assert pytester.collect_by_name(modcol, "doesnotexist") is None

def test_getparent(self, pytester: Pytester) -> None:
def test_getparent_and_accessors(self, pytester: Pytester) -> None:
modcol = pytester.getmodulecol(
"""
class TestClass:
Expand All @@ -77,14 +77,21 @@ def test_foo(self):
fn = pytester.collect_by_name(cls, "test_foo")
assert isinstance(fn, pytest.Function)

module_parent = fn.getparent(pytest.Module)
assert module_parent is modcol

function_parent = fn.getparent(pytest.Function)
assert function_parent is fn

class_parent = fn.getparent(pytest.Class)
assert class_parent is cls
assert fn.getparent(pytest.Module) is modcol
assert modcol.module is not None
assert modcol.cls is None
assert modcol.instance is None

assert fn.getparent(pytest.Class) is cls
assert cls.module is not None
assert cls.cls is not None
assert cls.instance is None

assert fn.getparent(pytest.Function) is fn
assert fn.module is not None
assert fn.cls is not None
assert fn.instance is not None
assert fn.function is not None

def test_getcustomfile_roundtrip(self, pytester: Pytester) -> None:
hello = pytester.makefile(".xxx", hello="world")
Expand Down

0 comments on commit f08a77d

Please sign in to comment.