Охватываемые темы: Installation, @pytest.mark.django_db, Fixtures, Testing views.
Installation
pip install pytest pytest-django pytest-cov
# pytest.ini or 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'
Fixtures
# 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,
)
Testing views
@pytest.mark.django_db
def test_task_list_requires_login(client):
response = client.get('/tasks/')
assert response.status_code == 302 # redirect to 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
Testing the 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
Running tests
pytest # all tests
pytest tasks/ # a specific app
pytest -v # verbose output
pytest -k "test_task" # by name
pytest --cov=tasks --cov-report=html # with coverage
pytest -x # stop on first failure
💬 Comments (0)
No comments yet
Be the first to share your opinion about this article!