use yield instead of request.addfinalizer
pytest
offers two ways to perform cleanup in fixture code. One is sequential
(yield
statement), and the other is callback-based (request.addfinalizer
).
request.addfinalizer
is allowed when implementing Factories as fixtures pattern,
see examples below for more details.
Bad code:
import pytest
@pytest.fixture()
def my_fixture(request):
resource = acquire_resource()
request.addfinalizer(resource.release)
return resource
Good code:
import pytest
@pytest.fixture()
def my_fixture():
resource = acquire_resource()
yield resource
resource.release()
# "Factories as fixtures" pattern
@pytest.fixture()
def my_factory(request):
def create_resource(arg):
resource = acquire_resource(arg)
request.addfinalizer(resource.release)
return resource
return create_resource
- to make fixture code more linear and straightforward