Fixtures and Parametrize
Fixtures and Parametrize
pytest becomes even more powerful with fixtures and parameterized tests.
These tools help you reduce repeated code and test many inputs easily.
What Is a Fixture?
A fixture is reusable setup code for tests.
Use fixtures when many tests need the same data or objects.
Examples:
- sample user data
- database connection
- test file
- shared list
Why Fixtures Matter
Fixtures help you:
- remove repeated setup code
- keep tests cleaner
- reuse test data
- improve readability
Basic Fixture Example
import pytest
@pytest.fixture
def numbers():
return [1, 2, 3]
Use the fixture:
def test_length(numbers):
assert len(numbers) == 3
def test_first(numbers):
assert numbers[0] == 1
Example Output
2 passed
How It Works
pytest sees the fixture name as a function parameter and provides the value automatically.
Another Fixture Example
import pytest
@pytest.fixture
def user():
return {"name": "Maya", "active": True}
def test_name(user):
assert user["name"] == "Maya"
What Is Parametrize?
Sometimes one test should run with many inputs.
Use:
@pytest.mark.parametrize
Basic Example
import pytest
def add(a, b):
return a + b
@pytest.mark.parametrize(
"a,b,expected",
[
(2, 3, 5),
(1, 1, 2),
(0, 5, 5),
]
)
def test_add(a, b, expected):
assert add(a, b) == expected
Example Output
3 passed
Each row becomes a separate test case.
Why Parametrize Matters
It helps you:
- test many values quickly
- avoid repeated test functions
- keep tests short and clear
Combine Fixture + Parametrize
import pytest
@pytest.fixture
def base():
return 10
@pytest.mark.parametrize("value", [1, 2, 3])
def test_total(base, value):
assert base + value > 10
Code Along
Create a fixture named items that returns:
["Pen", "Book"]
Write two tests using it.
Mini Challenge
Create function:
def square(n):
return n * n
Use parametrize to test:
2 → 43 → 95 → 25
Expected output:
3 passed
Real World Use Case
Teams use fixtures for test users, database setup, API clients, files, and reusable environments.
Quiz
- What is a fixture?
- Why use fixtures?
- What does
parametrizedo? - Why is parametrize useful?
Assignment
Create a fixture with user data and two tests that use it.
Summary
You learned how fixtures reuse setup code and how parametrize runs one test with many inputs.