Tests catch bugs before production. pytest is the de facto standard for Python testing — simple, powerful, extensible.
pytest Basics¶
Python Testing — pytest Guide¶
def test_add(): assert add(2, 3) == 5 def test_divide(): assert divide(10, 2) == 5.0 def test_divide_by_zero(): with pytest.raises(ZeroDivisionError): divide(10, 0)
Fixtures¶
import pytest @pytest.fixture def db_session(): session = create_test_session() yield session session.rollback() session.close() def test_create_user(db_session): user = User(name=”Jan”) db_session.add(user) db_session.flush() assert user.id is not None
Mocking¶
from unittest.mock import patch, AsyncMock @patch(‘myapp.services.send_email’) def test_registration(mock_email): register_user(“[email protected]”) mock_email.assert_called_once_with(“[email protected]”, subject=”Welcome”)
Running Tests¶
pytest -v # Verbose pytest –cov=src # Coverage pytest -x # Stop on first failure pytest -k “test_login” # Filter by name
Key Takeaway¶
pytest for everything. Fixtures for setup/teardown, mock for external dependencies. Minimum 80% coverage.