Testy zachytí chyby před produkcí. pytest je de facto standard pro Python testování — jednoduchý, mocný, rozšiřitelný.
Základy pytest¶
test_calculator.py¶
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”)
Spuštění¶
pytest -v # Verbose pytest –cov=src # Coverage pytest -x # Stop on first failure pytest -k “test_login” # Filter by name
Klíčový takeaway¶
pytest pro všechno. Fixtures pro setup/teardown, mock pro external dependencies. Min 80% coverage.