Sobes.tech
Junior — Middle

What methods are used in pytest to release resources after a test is completed?

sobes.tech AI

Answer from AI

In pytest, resource cleanup after a test is usually implemented using fixtures with the yield keyword or the request.addfinalizer function.

  1. Fixtures with yield: Code before yield runs before the test, and code after runs after the test to clean up resources.
import pytest

@pytest.fixture
def resource():
    # prepare resource
    res = open('file.txt', 'w')
    yield res
    # cleanup resource
    res.close()
  1. addfinalizer: You can register a cleanup function that will be executed after the test.
@pytest.fixture
def resource(request):
    res = open('file.txt', 'w')
    def cleanup():
        res.close()
    request.addfinalizer(cleanup)
    return res

Thus, pytest provides convenient mechanisms to ensure resources are released after tests are executed.