Охватываемые темы: Installation, conftest.py — Fixtures, Model Test, View Test with Client.
Installation
pip install pytest pytest-django
# pytest.ini or pyproject.toml
[pytest]
DJANGO_SETTINGS_MODULE = mysite.settings
conftest.py — 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,
status='todo',
)
Model Test
# tasks/tests/test_models.py
import pytest
from tasks.models import Task
@pytest.mark.django_db
def test_task_creation(user, project):
task = Task.objects.create(title='Test', owner=user, project=project)
assert task.title == 'Test'
assert task.status == 'todo'
assert str(task) == 'Test'
@pytest.mark.django_db
def test_task_complete(task):
task.status = 'done'
task.save()
assert Task.objects.get(pk=task.pk).status == 'done'
View Test with Client
# tasks/tests/test_views.py
import pytest
from django.test import Client
from django.urls import reverse
@pytest.mark.django_db
def test_task_list_requires_login(client):
response = client.get(reverse('task-list'))
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(reverse('task-list'))
assert response.status_code == 200
assert task.title.encode() in response.content
Access Control Test
@pytest.mark.django_db
def test_cannot_edit_others_task(client, task):
other = User.objects.create_user(username='other', password='pass')
client.login(username='other', password='pass')
response = client.post(
reverse('task-edit', kwargs={'pk': task.pk}),
{'title': 'Hacked!'}
)
assert response.status_code in [403, 404]
task.refresh_from_db()
assert task.title != 'Hacked!'
Running Tests
pytest # run all tests
pytest tasks/ # tests for a specific application
pytest -v # verbose output
pytest -k "test_task" # filter by name
pytest --cov=tasks # with coverage report
💬 Comments (0)
No comments yet
Be the first to share your opinion about this article!