snippetpythonpytestModeratependingCanonical
Python pytest patterns -- fixtures, parametrize, and mocking
Viewed 0 times
pytestfixtureparametrizemockpatchconftesttmp_path
python
Problem
Writing tests that are maintainable, DRY, and cover edge cases requires good patterns.
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
@pytest.fixture
def db(tmp_path):
db_path = tmp_path / 'test.db'
conn = create_db(db_path)
yield conn
conn.close()
@pytest.mark.parametrize('input_val,expected', [
('hello world', 'hello-world'),
('Hello World!', 'hello--world'),
('', ''),
])
def test_slugify(input_val, expected):
assert slugify(input_val) == expected
@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'Revisions (0)
No revisions yet.