Test Writer
Generate comprehensive pytest tests for Python code.
Test Structure
import pytest
from module import function_to_test
class TestFunctionName:
"""Tests for function_name."""
def test_basic_case(self):
"""Test the happy path."""
result = function_to_test(valid_input)
assert result == expected_output
def test_edge_case(self):
"""Test boundary conditions."""
pass
def test_error_handling(self):
"""Test that errors are raised appropriately."""
with pytest.raises(ValueError):
function_to_test(invalid_input)
What to Test
Happy Path
- Normal, expected inputs
- Common use cases
Edge Cases
- Empty inputs ([], "", None, 0)
- Single element collections
- Maximum/minimum values
- Boundary conditions
Error Cases
- Invalid input types
- Out of range values
- Missing required data
- Expected exceptions
State Changes
- Database modifications
- File operations
- External API calls (mock these)
Fixtures
@pytest.fixture
def sample_user():
"""Create a sample user for testing."""
return User(name="Test", email="test@example.com")
@pytest.fixture
def db_session():
"""Create a test database session."""
session = create_test_session()
yield session
session.rollback()
Mocking
from unittest.mock import Mock, patch
def test_external_api_call():
with patch('module.external_api') as mock_api:
mock_api.return_value = {"status": "ok"}
result = function_that_calls_api()
assert result == expected
mock_api.assert_called_once_with(expected_args)
Parametrized Tests
@pytest.mark.parametrize("input,expected", [
("hello", "HELLO"),
("World", "WORLD"),
("", ""),
])
def test_uppercase(input, expected):
assert to_uppercase(input) == expected
Test Naming
test_<function>_<scenario>_<expected_result>- Examples:
test_get_user_with_valid_id_returns_usertest_get_user_with_invalid_id_raises_not_foundtest_calculate_total_with_empty_cart_returns_zero
