0
0
PyTesttesting~5 mins

Handling shared resources in PyTest

Choose your learning style9 modes available
Introduction

Sometimes tests need to use the same resource like a file or database. Handling shared resources helps tests run smoothly without breaking each other.

When multiple tests need to read or write the same file.
When tests share a database connection or table.
When tests use a network service that must be set up once.
When you want to avoid repeating slow setup steps for each test.
When cleaning up resources after tests to keep things tidy.
Syntax
PyTest
import pytest

@pytest.fixture(scope="module")
def shared_resource():
    resource = setup_resource()
    yield resource
    teardown_resource(resource)

Use @pytest.fixture to create shared resources.

The scope controls how often the resource is created and destroyed.

Examples
This fixture runs setup and teardown for each test function.
PyTest
import pytest

@pytest.fixture(scope="function")
def resource():
    print("Setup resource")
    yield "data"
    print("Teardown resource")
This fixture runs setup once for all tests in the module.
PyTest
import pytest

@pytest.fixture(scope="module")
def resource():
    print("Setup once per module")
    yield "data"
    print("Teardown once per module")
This fixture runs setup once for the whole test session.
PyTest
import pytest

@pytest.fixture(scope="session")
def resource():
    print("Setup once per session")
    yield "data"
    print("Teardown once per session")
Sample Program

This example shows a shared list used by two tests. The list is set up once per module and cleared after all tests run.

PyTest
import pytest

@pytest.fixture(scope="module")
def shared_list():
    print("Setup shared list")
    data = []
    yield data
    print("Teardown shared list")
    data.clear()

def test_append(shared_list):
    shared_list.append(1)
    assert shared_list == [1]

def test_append_again(shared_list):
    shared_list.append(2)
    assert shared_list == [1, 2]
OutputSuccess
Important Notes

Always clean up shared resources to avoid side effects between tests.

Choose the right scope to balance speed and isolation.

Use yield in fixtures to separate setup and teardown steps clearly.

Summary

Shared resources help tests reuse setup work and avoid conflicts.

Use pytest fixtures with scopes to control resource lifetime.

Clean up resources after tests to keep tests independent and reliable.