In the basic example, the fixture returns None
.
It actually doesn’t have a return statement. So like any other function in Python, if you don’t supply a return
(or yield
) statement, it returns None
.
However, you can return anything you want from the fixture function.
If your fixture is setting up some data, or reading a file, or opening a connection to a database, then access to that data or resources is what you ought to return from the fixture.
Returning some data from a fixture.
@pytest.fixture()
def some_data():
data = {'foo':1, 'bar':2, 'baz':3}
return data
def test_foo(some_data):
assert some_data['foo'] == 1
Returning a database object:
@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
def test_brie(cheese_db):
print('in test_brie()')
assert cheese_db['Brie'] == 'No.'
def test_camenbert(cheese_db):
print('in test_camenbert()')
assert cheese_db['Camenbert'] != 'No.'
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 - this post
- pytest fixture teardown
- 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)