snippetpythonpytestModeratepending
Python pytest fixtures and parameterize patterns
Viewed 0 times
pytestfixturesparametrizetest setupteardown
Problem
Need reusable test setup, teardown, and data-driven tests in pytest.
Solution
Key pytest patterns:
import pytest
# Fixture with setup and teardown
@pytest.fixture
def db_connection():
conn = create_connection()
yield conn # Test runs here
conn.close() # Teardown
# Fixture with scope (shared across module)
@pytest.fixture(scope='module')
def app_client():
app = create_app(testing=True)
return app.test_client()
# Parameterized tests
@pytest.mark.parametrize('input,expected', [
('hello', 'HELLO'),
('world', 'WORLD'),
('', ''),
])
def test_uppercase(input, expected):
assert input.upper() == expected
# Fixture that uses another fixture
@pytest.fixture
def authenticated_client(app_client):
app_client.post('/login', data={'user': 'test'})
return app_client
# tmp_path fixture (built-in)
def test_file_write(tmp_path):
f = tmp_path / 'test.txt'
f.write_text('hello')
assert f.read_text() == 'hello'Why
Fixtures provide dependency injection for tests, making setup reusable and teardown automatic.
Context
Python testing with pytest
Revisions (0)
No revisions yet.