What if you could write setup code once and have it magically run just the right number of times for all your tests?
Why Fixture scope (function, class, module, session) in PyTest? - Purpose & Use Cases
Imagine you have many tests that need the same setup, like opening a database connection or preparing test data. Doing this setup manually inside each test means repeating code everywhere.
For example, opening and closing a database connection in every test function by hand.
Manually repeating setup and cleanup is slow and boring. It wastes time and can cause mistakes, like forgetting to close a connection or setting up inconsistently.
This leads to flaky tests that sometimes fail for no good reason, making debugging harder.
Fixture scopes in pytest let you define setup code once and control how often it runs: per test function, per test class, per module, or once per test session.
This means you write setup code once, and pytest runs it just the right number of times automatically.
def test1(): db = open_db() # test code db.close() def test2(): db = open_db() # test code db.close()
@pytest.fixture(scope='module') def db(): connection = open_db() yield connection connection.close() def test1(db): # test code def test2(db): # test code
Fixture scopes let tests share setup efficiently, making tests faster, cleaner, and less error-prone.
In a big project, you can open a database connection once per module instead of for every test, saving minutes of setup time and reducing connection errors.
Manual setup repetition wastes time and causes errors.
Fixture scopes control how often setup runs automatically.
This makes tests faster, cleaner, and more reliable.