Skip to content

Latest commit

 

History

History
49 lines (36 loc) · 1.07 KB

PT021.md

File metadata and controls

49 lines (36 loc) · 1.07 KB

PT021

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.

Examples

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

Rationale

  • to make fixture code more linear and straightforward