Manuals / Python / Ch 8

C · TestingIntermediate40 min read

8. Fixtures & parametrization

Python · 52 pages source format

@pytest.fixture for shared setup. @pytest.mark.parametrize for data-driven tests. conftest.py for shared fixtures.

What you'll learn

  • @pytest.fixture
  • parametrize
  • conftest.py
  • Fixture scope

Fixtures

Fixture functions provide test data or clients. pytest injects by parameter name.

import pytest

@pytest.fixture
def sample_users():
    return [{"username": "a"}, {"username": "b"}]

def test_user_count(sample_users):
    assert len(sample_users) == 2

Do this now

Create sample_users fixture returning list of dicts. Use in 2 tests.

Clear?

Parametrize

Run same test logic with multiple inputs. Great for validation functions.

@pytest.mark.parametrize("pwd,expected", [
    ("secret123", True),
    ("", False),
    ("ab", False),
])
def test_password(pwd, expected):
    assert is_valid_password(pwd) == expected

Do this now

Parametrize is_valid_password with 4 cases: valid, empty, short, long.

Clear?

conftest.py

Shared fixtures live in tests/conftest.py — auto-discovered, no imports needed.

Do this now

Move sample_users fixture to conftest.py.

Clear?

Checklist