Understanding pytest Fixtures: A Guide to Better Testing

3D isometric illustration of robotic arms prepping a test robot with tools, representing pytest fixtures setting up a test environment.

In our intro to pytest, we learned how to use simple assert statements. But what if all your tests need the same setup data? You don’t want to copy and paste it every time. That’s where this pytest Fixtures Guide comes in.

A fixture is a function that <a href="https://docs.pytest.org/en/stable/" type="link" id="https://docs.pytest.org/en/stable/">pytest</a> runs before your test to set up the data.

The Problem: Repetitive Setup

def test_can_add_to_list():
    my_list = [1, 2, 3] # Setup
    my_list.append(4)
    assert len(my_list) == 4

def test_can_pop_from_list():
    my_list = [1, 2, 3] # Repetitive Setup!
    my_list.pop()
    assert len(my_list) == 2

The Solution: A Fixture

We use the @pytest.fixture decorator. Then, we pass the fixture’s function name as an argument to our test.

import pytest

@pytest.fixture
def basic_list():
    """A fixture to provide a simple list."""
    return [1, 2, 3]

def test_can_add_to_list(basic_list):
    # 'basic_list' is now [1, 2, 3] from the fixture
    basic_list.append(4)
    assert len(basic_list) == 4

def test_can_pop_from_list(basic_list):
    # This test gets its OWN, FRESH copy of [1, 2, 3]
    basic_list.pop()
    assert len(basic_list) == 2

Fixtures are the core of pytest. You can use them to create fake user data, connect to a temporary database, or set up a complex object, ensuring every test starts from a clean, known state.

Similar Posts

Leave a Reply