Question
Choosing Between yield and addfinalizer in pytest Fixtures for Teardown
I've recently started using pytest for testing in Python and created a fixture to manage a collection of items using gRPC. Below is the code snippet for my fixture:
import pytest
@pytest.fixture(scope="session")
def collection():
grpc_page = GrpcPages().collections
def create_collection(collection_id=None, **kwargs):
default_params = {
"id": collection_id,
"is_active": True,
# some other params
}
try:
return grpc_page.create_collection(**{**default_params, **kwargs})
except Exception as err:
print(err)
raise err
yield create_collection
def delete_created_collection():
# Some code to hard and soft delete created data
This is my first attempt at creating a fixture, and I realized that I need a mechanism to delete data created during the fixture's lifecycle.
While exploring options for implementing teardown procedures, I came across yield and addfinalizer. From what I understand, both can be used to define teardown actions in pytest fixtures. However, I'm having trouble finding clear documentation and examples that explain the key differences between these two approaches and when to choose one over the other.
Here are the questions (for fast-forwarding :) ):
- What are the primary differences between using yield and addfinalizer in pytest fixtures for handling teardown?
- Are there specific scenarios where one is preferred over the other?