La plupart des suites de tests Python finissent par etre plus un fardeau qu’une aide. Voici les patterns qui construisent des tests durables.
Fixtures : le pattern le plus important
# conftest.py
import pytest
@pytest.fixture(scope="session")
def db_engine():
engine = create_engine("sqlite:///:memory:")
Base.metadata.create_all(engine)
yield engine
Base.metadata.drop_all(engine)
@pytest.fixture(scope="function")
def db_session(db_engine):
connection = db_engine.connect()
transaction = connection.begin()
session = Session(bind=connection)
yield session
session.close()
transaction.rollback()
connection.close()
Parametriser les tests
@pytest.mark.parametrize("email,expected_valid", [
("alice@example.com", True),
("alice@", False),
("", False),
("alice@example.co.uk", True),
])
def test_email_validation(email, expected_valid):
assert is_valid_email(email) == expected_valid
Un test, quatre cas couverts.
Mocker les dependances externes
from unittest.mock import patch
def test_send_notification_success(test_user):
with patch('myapp.notifications.smtp_client') as mock_smtp:
mock_smtp.send.return_value = True
result = send_notification(test_user.email, "Bienvenue !")
assert result is True
mock_smtp.send.assert_called_once()
def test_send_notification_failure(test_user):
with patch('myapp.notifications.smtp_client') as mock_smtp:
mock_smtp.send.side_effect = SMTPException("Connection refused")
with pytest.raises(NotificationError):
send_notification(test_user.email, "Bienvenue !")
Notre formation Python couvre le testing avec pytest en profondeur.