0
0
PyTesttesting~3 mins

Why Fixture scope (function, class, module, session) in PyTest? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

What if you could write setup code once and have it magically run just the right number of times for all your tests?

The Scenario

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.

The Problem

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.

The Solution

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.

Before vs After
Before
def test1():
    db = open_db()
    # test code
    db.close()

def test2():
    db = open_db()
    # test code
    db.close()
After
@pytest.fixture(scope='module')
def db():
    connection = open_db()
    yield connection
    connection.close()

def test1(db):
    # test code

def test2(db):
    # test code
What It Enables

Fixture scopes let tests share setup efficiently, making tests faster, cleaner, and less error-prone.

Real Life Example

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.

Key Takeaways

Manual setup repetition wastes time and causes errors.

Fixture scopes control how often setup runs automatically.

This makes tests faster, cleaner, and more reliable.