@pytest.mark.parametrize("input,expected", [
("", False), # Empty
("a@b.c", True), # Minimal valid
("test@example.com", True),
("invalid", False), # No @
("@example.com", False), # No local part
("test@", False), # No domain
])
def test_validate_email(input, expected):
assert validate_email(input) == expected
Testing Exceptions
def test_divide_by_zero_raises():
with pytest.raises(ZeroDivisionError):
divide(10, 0)
def test_invalid_input_raises_with_message():
with pytest.raises(ValueError) as exc_info:
process_data(None)
assert "cannot be None" in str(exc_info.value)
Integration Test Patterns
Database Tests
@pytest.fixture
async def db_session():
# Setup
async with engine.begin() as conn:
await conn.run_sync(Base.metadata.create_all)
async with AsyncSession(engine) as session:
yield session
# Teardown
async with engine.begin() as conn:
await conn.run_sync(Base.metadata.drop_all)
async def test_create_and_fetch_user(db_session):
# Create
user = User(email="test@example.com", name="Test")
db_session.add(user)
await db_session.commit()
# Fetch
result = await db_session.get(User, user.id)
assert result.email == "test@example.com"
API Tests
async def test_api_create_user(client):
response = await client.post(
"/users",
json={"email": "test@example.com", "name": "Test"}
)
assert response.status_code == 201
data = response.json()
assert data["email"] == "test@example.com"
assert "id" in data
Mocking Patterns
When to Mock
Mock:
├─ External APIs (payment, email, SMS)
├─ Time/dates (for deterministic tests)
├─ Random values
└─ Slow operations
Don't Mock:
├─ The code you're testing
├─ Simple data structures
└─ Things you can use real instances of