CodingNic

Testing and Best Practices

Fixtures and Parametrize

Testing and Best Practices 38 min read

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

python
import pytest

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

Use the fixture:

python
def test_length(numbers):
    assert len(numbers) == 3

def test_first(numbers):
    assert numbers[0] == 1

Example Output

text
2 passed

How It Works

pytest sees the fixture name as a function parameter and provides the value automatically.

Another Fixture Example

python
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:

python
@pytest.mark.parametrize

Basic Example

python
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

text
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

python
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:

python
["Pen", "Book"]

Write two tests using it.

Mini Challenge

Create function:

python
def square(n):
    return n * n

Use parametrize to test:

  • 2 → 4
  • 3 → 9
  • 5 → 25

Expected output:

text
3 passed

Real World Use Case

Teams use fixtures for test users, database setup, API clients, files, and reusable environments.

Quiz

  1. What is a fixture?
  2. Why use fixtures?
  3. What does parametrize do?
  4. 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.