HiveBrain v1.2.0
Get Started
← Back to all entries
snippetpythonpytestModeratependingCanonical

Python pytest Fixtures and Parametrize Patterns

Submitted by: @anonymous··
0
Viewed 0 times
pytestfixturesparametrizetestingconftestteardown

Problem

Need reusable test setup and data-driven testing in pytest without duplicating code across test functions.

Solution

Key pytest patterns:

import pytest
from pathlib import Path

# Fixture with teardown
@pytest.fixture
def temp_db(tmp_path):
    db_path = tmp_path / 'test.db'
    conn = sqlite3.connect(str(db_path))
    conn.execute_script('CREATE TABLE users (id INT, name TEXT)')
    yield conn  # Test runs here
    conn.close()  # Teardown

# Parametrize for data-driven tests
@pytest.mark.parametrize('input,expected', [
    ('hello', 'HELLO'),
    ('world', 'WORLD'),
    ('', ''),
])
def test_upper(input, expected):
    assert input.upper() == expected

# Fixture factory pattern
@pytest.fixture
def make_user():
    created = []
    def _make(name, role='user'):
        u = User(name=name, role=role)
        created.append(u)
        return u
    yield _make
    for u in created:
        u.delete()

# Shared fixtures in conftest.py
# conftest.py is auto-discovered by pytest

Why

Fixtures provide dependency injection for tests. Parametrize runs the same test with different data, catching edge cases without code duplication.

Gotchas

  • Fixture scope matters: function (default), class, module, session
  • conftest.py fixtures are available to all tests in that directory and below

Context

Writing maintainable Python test suites

Revisions (0)

No revisions yet.