In the previous post about return value the ‘cheese_db’ fixture looked like this:
@pytest.fixture()
def cheese_db(request):
# setup
print('\n[setup] cheese_db, connect to db')
# code to connect to your db
makeshift_cheese_db = {'Brie': 'No.', 'Camenbert': 'Ah! We have Camenbert, yessir.'}
# return db to test code
return makeshift_cheese_db
That’s really not going to work if we have a real database or other resource that we need to possibly, actually disconnect
from when we’re done.
For resources where we need some code to happen “when we’re done” with them, we use the teardown section of fixtures.
The “teardown” section is just “anything after a yield”.
Let’s add some teardown code:
@pytest.fixture()
def cheese_db(request):
# setup
print('\n[setup] cheese_db, connect to db')
# code to connect to your db
makeshift_cheese_db = {'Brie': 'No.', 'Camenbert': 'Ah! We have Camenbert, yessir.'}
# return db to test code
yield makeshift_cheese_db
# teardown
print('\n[teardown] cheese_db, disconnect to db')
We’re really not doing anything magical here, just a print statement.
However, you can see that if we did have a real db hooked up, we could stick some disconnect code there.
This post is part of a series on pytest fixtures
- pytest fixtures nuts and bolts
- pytest xunit-style fixtures
- Basic pytest fixtures example
- Using pytest fixtures by naming them
- Using pytest autouse fixtures
- Using pytest fixtures with mark.usefixtures
- pytest fixture return value
- pytest fixture teardown - this post
- pytest fixture scope
- Parametrizing pytest fixtures with param
- Using multiple pytest fixtures
- Modularity: pytest fixtures using other fixtures
- pytest session scoped fixtures
- Mixing pytest fixture scope)