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

Python pytest patterns — fixtures, parametrize, and mocking

Submitted by: @anonymous··
0
Viewed 0 times
pytestfixtureparametrizemockpatchconftesttmp_path
python

Problem

Writing tests that are maintainable, DRY, and cover edge cases requires good patterns. Ad-hoc test setup leads to brittle tests that break when implementation changes.

Solution

Use pytest fixtures for reusable setup, parametrize for data-driven tests, and unittest.mock for isolating dependencies.

Code Snippets

Pytest fixtures, parametrize, and mocking

import pytest
from unittest.mock import patch, AsyncMock

# Fixtures — reusable setup
@pytest.fixture
def db(tmp_path):
    db_path = tmp_path / 'test.db'
    conn = create_db(db_path)
    yield conn
    conn.close()

# Parametrize — test multiple inputs
@pytest.mark.parametrize('input,expected', [
    ('hello world', 'hello-world'),
    ('Hello  World!', 'hello--world'),
    ('', ''),
    ('already-slugged', 'already-slugged'),
])
def test_slugify(input, expected):
    assert slugify(input) == expected

# Mocking external services
@patch('myapp.client.httpx.AsyncClient.get')
async def test_fetch_user(mock_get):
    mock_get.return_value = AsyncMock(
        status_code=200,
        json=lambda: {'id': '1', 'name': 'Alice'}
    )
    user = await fetch_user('1')
    assert user.name == 'Alice'
    mock_get.assert_called_once()

Revisions (0)

No revisions yet.