Sobes.tech
Senior

How to add list clearing after test completion? What is the difference between yield and AdFinalizer?

sobes.tech AI

Answer from AI

In Python testing with pytest, a common pattern for resource cleanup after tests is to use yield in fixtures. Code before yield runs before the test, and code after yield runs after the test, which is convenient for cleanup, such as clearing a list.

Example of a fixture with list cleanup:

import pytest

@pytest.fixture
def my_list():
    lst = [1, 2, 3]
    yield lst
    lst.clear()  # Cleanup after test

AdFinalizer is a method in pytest that allows adding a cleanup function to be called after the test. It can be used inside a fixture via request.addfinalizer(cleanup_func).

Difference between yield and addfinalizer:

  • yield is a more readable and modern way to organize setup/teardown in fixtures.
  • addfinalizer allows adding multiple cleanup functions dynamically.

Example with addfinalizer:

import pytest

def cleanup():
    print("Cleanup after test")

@pytest.fixture
def my_resource(request):
    # setup
    request.addfinalizer(cleanup)
    return some_resource

Overall, yield is preferred for simple cases, while addfinalizer is suitable for more complex scenarios with multiple finalizers.