0
0
PytestHow-ToBeginner ยท 3 min read

How to Create Fixture in pytest: Simple Guide with Examples

In pytest, create a fixture by defining a function with the @pytest.fixture decorator. Use this fixture in your test by adding it as a parameter, and pytest will run the fixture function before the test automatically.
๐Ÿ“

Syntax

To create a fixture in pytest, define a function and decorate it with @pytest.fixture. This function can prepare data or resources needed for tests. Tests use the fixture by including its name as a parameter.

  • @pytest.fixture: marks the function as a fixture.
  • Fixture function: sets up and returns data or resources.
  • Test function parameter: pytest injects the fixture result here.
python
import pytest

@pytest.fixture
def sample_data():
    return [1, 2, 3]

def test_sum(sample_data):
    assert sum(sample_data) == 6
๐Ÿ’ป

Example

This example shows a fixture that provides a list of numbers. The test uses this fixture to check if the sum is correct. Pytest runs the fixture before the test and passes its return value to the test function.

python
import pytest

@pytest.fixture
def numbers():
    print("Setting up numbers fixture")
    return [10, 20, 30]

def test_total(numbers):
    assert sum(numbers) == 60

def test_length(numbers):
    assert len(numbers) == 3
Output
Setting up numbers fixture . Setting up numbers fixture .
โš ๏ธ

Common Pitfalls

Common mistakes when creating fixtures include:

  • Forgetting the @pytest.fixture decorator, so pytest does not recognize the function as a fixture.
  • Not using the fixture name as a test function parameter, so the fixture is never called.
  • Modifying fixture data inside tests without copying, which can cause unexpected side effects.
python
import pytest

# Wrong: Missing decorator

def data():
    return 42

def test_value(data):  # This will fail because 'data' is not a fixture
    assert data == 42

# Right:

@pytest.fixture
def data():
    return 42

def test_value(data):
    assert data == 42
๐Ÿ“Š

Quick Reference

Remember these tips when working with pytest fixtures:

  • Use @pytest.fixture to define fixtures.
  • Pass fixture names as test function parameters.
  • Fixtures can return any data or resource.
  • Fixtures run before each test that uses them by default.
  • Use scope parameter in @pytest.fixture to control fixture lifetime.
โœ…

Key Takeaways

Define fixtures with @pytest.fixture decorator to prepare test data or resources.
Use fixture names as parameters in test functions to access fixture data.
Fixtures run automatically before each test that requests them.
Always decorate fixture functions; otherwise, pytest won't recognize them.
Use fixture scope to control how often fixtures are set up and torn down.