Охватываемые темы: Установка, @pytest.mark.django_db, Фикстуры, Тестирование views.
Установка
pip install pytest pytest-django pytest-cov
# pytest.ini или pyproject.toml
[pytest]
DJANGO_SETTINGS_MODULE = mysite.settings
python_files = tests.py test_*.py *_tests.py
@pytest.mark.django_db
import pytest
from tasks.models import Task
@pytest.mark.django_db
def test_task_creation():
task = Task.objects.create(title='Test Task', status='todo')
assert task.pk is not None
assert task.title == 'Test Task'
Фикстуры
# conftest.py
import pytest
from django.contrib.auth.models import User
from tasks.models import Task, Project
@pytest.fixture
def user(db):
return User.objects.create_user(username='testuser', password='testpass')
@pytest.fixture
def project(db):
return Project.objects.create(name='Test Project')
@pytest.fixture
def task(db, user, project):
return Task.objects.create(
title='Test Task',
owner=user,
project=project,
)
Тестирование views
@pytest.mark.django_db
def test_task_list_requires_login(client):
response = client.get('/tasks/')
assert response.status_code == 302 # редирект на login
@pytest.mark.django_db
def test_task_list_authenticated(client, user, task):
client.login(username='testuser', password='testpass')
response = client.get('/tasks/')
assert response.status_code == 200
assert b'Test Task' in response.content
Тестирование API (DRF)
from rest_framework.test import APIClient
@pytest.fixture
def api_client():
return APIClient()
@pytest.mark.django_db
def test_api_task_list(api_client, user, task):
api_client.force_authenticate(user=user)
response = api_client.get('/api/tasks/')
assert response.status_code == 200
assert len(response.data['results']) == 1
Запуск тестов
pytest # все тесты
pytest tasks/ # конкретное приложение
pytest -v # подробный вывод
pytest -k "test_task" # по имени
pytest --cov=tasks --cov-report=html # с покрытием
pytest -x # стоп на первой ошибке
💬 Комментарии (0)
Комментариев пока нет
Станьте первым, кто поделится мнением об этой статье!