pythonintermediate

Pytest Fixtures and Parametrize

Reusable pytest fixtures with scope control, parametrize for data-driven tests, and temporary resources.

python
import pytest
from typing import Generator


# Session-scoped fixture (created once per test session)
@pytest.fixture(scope="session")
def db_connection():
    conn = create_db_connection()  # your connection logic
    yield conn
    conn.close()


# Function-scoped fixture with cleanup
@pytest.fixture
def sample_user(db_connection) -> Generator[dict, None, None]:
    user = {"id": 1, "name": "Ada", "email": "ada@example.com"}
    db_connection.insert("users", user)
    yield user
    db_connection.delete("users", user["id"])


# Fixture factory pattern
@pytest.fixture
def make_user():
    created = []

    def _make(name: str, email: str) -> dict:
        user = {"id": len(created) + 1, "name": name, "email": email}
        created.append(user)
        return user

    yield _make
    # Cleanup all created users
    for u in created:
        pass  # db.delete(u)


# Parametrized test
@pytest.mark.parametrize(
    "email,valid",
    [
        ("user@example.com", True),
        ("user@sub.domain.com", True),
        ("invalid", False),
        ("", False),
        ("@missing.com", False),
    ],
)
def test_email_validation(email: str, valid: bool):
    result = validate_email(email)  # your validation function
    assert result == valid


# Temporary directory fixture (built-in)
def test_file_processing(tmp_path):
    test_file = tmp_path / "data.csv"
    test_file.write_text("name,age\nAda,30\n")
    result = process_csv(str(test_file))  # your processing function
    assert len(result) == 1


def create_db_connection():
    return type("DB", (), {"insert": lambda *a: None, "delete": lambda *a: None, "close": lambda s: None})()

def validate_email(email: str) -> bool:
    return "@" in email and "." in email.split("@")[-1] and email[0] != "@" and len(email) > 0

def process_csv(path: str) -> list:
    import csv
    with open(path) as f:
        return list(csv.DictReader(f))

Use Cases

  • Unit test setup
  • Integration test fixtures
  • Data-driven test suites

Tags

Related Snippets

Similar patterns you can reuse in the same workflow.