Reputation: 9633
I am having difficulty using fixtures with my pytest unit tests.
I am using a test class like this:
class TestMyApp(object):
def setup(self):
self.client = mock_client()
@pytest.fixture
def client_item(self):
return self.client.create_item('test_item')
def test_something1(self, client_item):
# Test here.
pass
When I run the above test I get the following exception:
AttributeError: 'TestMyApp' object has no attribute 'client'
I believe this is because the client_item()
fixture function is being called before the setup()
function.
Am I using fixtures incorrectly? Or is there some way I can force setup()
to be called before the fixture functions?
Thanks in advance.
Upvotes: 1
Views: 2414
Reputation: 181725
Fixtures can use other fixtures, so you can use fixtures all the way down:
class TestMyApp(object):
@pytest.fixture
def client(self):
return mock_client()
@pytest.fixture
def client_item(self, client):
return client.create_item('test_item')
def test_something1(self, client_item):
# Test here.
pass
The documentation subtly recommends fixtures over xUnit style setup/teardown methods:
While these setup/teardown methods are simple and familiar to those coming from a
unittest
ornose
background, you may also consider using pytest’s more powerful fixture mechanism which leverages the concept of dependency injection, allowing for a more modular and more scalable approach for managing test state, especially for larger projects and for functional testing.
It goes on to say that the two styles can be mixed, but isn't clear about the order in which things will happen.
Upvotes: 2