Skip to content

Fix self reference in function scoped fixtures #5768

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

Merged
merged 3 commits into from
Aug 30, 2019
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.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions AUTHORS
Original file line number Diff line number Diff line change
Expand Up @@ -210,6 +210,7 @@ Raphael Castaneda
Raphael Pierzina
Raquel Alegre
Ravi Chandra
Robert Holt
Roberto Polli
Roland Puntaier
Romain Dorgueil
Expand Down
2 changes: 2 additions & 0 deletions changelog/2270.bugfix.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
Fixed ``self`` reference in function-scoped fixtures defined plugin classes: previously ``self``
would be a reference to a *test* class, not the *plugin* class.
6 changes: 6 additions & 0 deletions src/_pytest/fixtures.py
Original file line number Diff line number Diff line change
Expand Up @@ -897,6 +897,12 @@ def resolve_fixture_function(fixturedef, request):
# request.instance so that code working with "fixturedef" behaves
# as expected.
if request.instance is not None:
# handle the case where fixture is defined not in a test class, but some other class
# (for example a plugin class with a fixture), see #2270
if hasattr(fixturefunc, "__self__") and not isinstance(
request.instance, fixturefunc.__self__.__class__
):
return fixturefunc
fixturefunc = getimfunc(fixturedef.func)
if fixturefunc != fixturedef.func:
fixturefunc = fixturefunc.__get__(request.instance)
Expand Down
32 changes: 32 additions & 0 deletions testing/python/fixtures.py
Original file line number Diff line number Diff line change
Expand Up @@ -3945,6 +3945,38 @@ def test_2(fix):
reprec = testdir.inline_run()
reprec.assertoutcome(passed=2)

def test_class_fixture_self_instance(self, testdir):
"""Check that plugin classes which implement fixtures receive the plugin instance
as self (see #2270).
"""
testdir.makeconftest(
"""
import pytest

def pytest_configure(config):
config.pluginmanager.register(MyPlugin())

class MyPlugin():
def __init__(self):
self.arg = 1

@pytest.fixture(scope='function')
def myfix(self):
assert isinstance(self, MyPlugin)
return self.arg
"""
)

testdir.makepyfile(
"""
class TestClass(object):
def test_1(self, myfix):
assert myfix == 1
"""
)
reprec = testdir.inline_run()
reprec.assertoutcome(passed=1)


def test_call_fixture_function_error():
"""Check if an error is raised if a fixture function is called directly (#4545)"""
Expand Down