📝 Python

pytest-django: Testing Django

P
Author
Pyland
📅
Published
30.06.2026
⏱️
Reading time
1 min
👁️
Views
132
🌳
Level
Advanced

Охватываемые темы: 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

Your reaction to the article

💬 Comments (0)

🔐 Sign in to leave a comment
🚪 Login
💭

No comments yet

Be the first to share your opinion about this article!

🔗 Similar

Similar articles

Continue learning with these materials

📝

Event Loop in Python: How asyncio Achieves "Paral…

Event loop is the heart of asyncio. It doesn't run code in parallel across multiple...

📅 30.06.2026 👁️ 122
📝

pip: Python Package Manager

Охватываемые темы: Installing packages, Upgrading and removing, requirements.txt, Virtual environment.

📅 30.06.2026 👁️ 117
📝

run_in_executor and anyio: Sync Libraries in Asyn…

Sometimes you need to call a synchronous library from async code without blocking the event...

📅 30.06.2026 👁️ 100

Did you like the article?

Subscribe to our updates and receive new articles first. Grow with PyLand!