Loading...
Loading...
Implement comprehensive testing strategies with pytest, fixtures, mocking, and test-driven development. Use when writing Python tests, setting up test suites, or implementing testing best practices.
npx skill4agent add rory-data/copilot python-testing-patterns# test_example.py
def add(a, b):
return a + b
def test_add():
"""Basic test example."""
result = add(2, 3)
assert result == 5
def test_add_negative():
"""Test with negative numbers."""
assert add(-1, 1) == 0
# Run with: uv run pytest test_example.py# test_calculator.py
import pytest
class Calculator:
"""Simple calculator for testing."""
def add(self, a: float, b: float) -> float:
return a + b
def divide(self, a: float, b: float) -> float:
if b == 0:
raise ValueError("Cannot divide by zero")
return a / b
def test_addition():
"""Test addition."""
calc = Calculator()
assert calc.add(2, 3) == 5
assert calc.add(-1, 1) == 0
def test_division_by_zero():
"""Test division by zero raises error."""
calc = Calculator()
with pytest.raises(ValueError, match="Cannot divide by zero"):
calc.divide(5, 0)# test_database.py
import pytest
@pytest.fixture
def db():
"""Fixture that provides connected database."""
# Setup
database = {"connected": True}
yield database
# Teardown
database["connected"] = False
def test_database_query(db):
"""Test using fixture."""
assert db["connected"] is True# test_validation.py
import pytest
@pytest.mark.parametrize("email,expected", [
("user@example.com", True),
("invalid.email", False),
])
def test_email_validation(email, expected):
"""Test email validation with various inputs."""
assert is_valid(email) == expected# test_api_client.py
import pytest
from unittest.mock import Mock, patch
def test_api_call():
"""Test API call with mock."""
mock_response = Mock()
mock_response.json.return_value = {"id": 1}
with patch("requests.get", return_value=mock_response):
result = get_user(1)
assert result["id"] == 1# test_exceptions.py
import pytest
def test_exception():
"""Test exception is raised."""
with pytest.raises(ValueError, match="error message"):
divide(10, 0)# tests/
# __init__.py
# conftest.py # Shared fixtures
# test_unit/ # Unit tests
# test_integration/ # Integration tests
# test_e2e/ # End-to-end tests# Good test names describe what is tested and expected outcome
def test_user_creation_with_valid_data():
pass
def test_login_fails_with_invalid_password():
pass
# Bad test names
def test_1(): # Not descriptive
pass
def test_user(): # Too vague
passimport pytest
@pytest.mark.slow
def test_slow_operation():
pass
@pytest.mark.integration
def test_database_integration():
pass
# Run with:
# uv run pytest -m slow # Run only slow tests
# uv run pytest -m "not slow" # Skip slow tests