0
0
PytestConceptBeginner · 3 min read

What is Fixture in pytest: Simple Explanation and Example

In pytest, a fixture is a reusable setup function that prepares the environment for tests. It helps provide data, state, or resources needed before running test functions, making tests cleaner and easier to maintain.
⚙️

How It Works

Think of a fixture in pytest like a helper that sets up everything your test needs before it runs. For example, if you want to test a function that works with a database, the fixture can create a temporary database connection and provide it to your test.

When you write a test, you just ask for the fixture by name as a parameter. pytest will run the fixture first, then pass its result to your test. This way, you don’t have to repeat setup code in every test, just like how you prepare ingredients once before cooking many dishes.

💻

Example

This example shows a fixture that provides a simple list to a test function. The test checks if the list contains the expected items.

python
import pytest

@pytest.fixture
def sample_list():
    return [1, 2, 3, 4, 5]

def test_sum(sample_list):
    assert sum(sample_list) == 15

def test_length(sample_list):
    assert len(sample_list) == 5
Output
============================= test session starts ============================== collected 2 items test_sample.py .. [100%] ============================== 2 passed in 0.03s ===============================
🎯

When to Use

Use fixtures when you have setup steps that many tests share, like creating test data, opening files, or connecting to services. They help keep your tests clean and avoid repeating code.

For example, if you test a web app, you might use a fixture to start a test server or prepare user accounts. Fixtures also help manage cleanup after tests, like closing connections or deleting temporary files.

Key Points

  • Fixtures provide reusable setup and teardown for tests.
  • You request fixtures by naming them as test function parameters.
  • They improve test readability and reduce code duplication.
  • Fixtures can return data or resources needed by tests.
  • They support scopes like function, module, or session for flexible use.

Key Takeaways

A fixture in pytest is a setup function that prepares test data or environment.
You use fixtures by adding their name as a parameter to your test functions.
Fixtures help avoid repeating setup code and make tests easier to maintain.
They can manage resources and cleanup automatically after tests run.
Fixtures support different scopes to control how often they run.