0 day streak
python / intermediate
Snippet

Django Testing with pytest-django and Factories

Effective Django testing combines pytest-django for database fixtures with factory_boy for test data creation. The @pytest.mark.django_db decorator provides transaction-level test isolation. Factories like BookFactory create valid model instances without repetitive fixture data. APIClient from DRF simulates HTTP requests. Using fixtures for setup ensures tests are isolated, readable, and maintainable.

snippet.py
python
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
import pytest
from django.contrib.auth.models import User
from rest_framework.test import APIClient
from books.models import Book, Category
from books.factories import BookFactory, AuthorFactory
@pytest.fixture
def api_client():
return APIClient()
@pytest.fixture
def author(db):
return AuthorFactory()
@pytest.fixture
def published_book(db, author):
return BookFactory(is_published=True, author=author)
@pytest.mark.django_db
class TestBookAPI:
def test_book_list_returns_only_published(self, api_client, published_book):
response = api_client.get('/api/books/')
assert response.status_code == 200
assert len(response.data['results']) == 1
assert published_book.title in str(response.data)
def test_unpublished_book_not_in_list(self, api_client, db):
unpublished = BookFactory(is_published=False)
response = api_client.get('/api/books/')
assert response.status_code == 200
assert unpublished.title not in str(response.data)
django
Breakdown
1
@pytest.mark.django_db
Grants test access to the database with automatic transaction rollback after each test
2
@pytest.fixture def author(db):
Fixture that creates an Author using the factory and ensures database access
3
published_book = BookFactory(is_published=True)
Factory creates a fully valid Book instance with sensible defaults
4
assert len(response.data['results']) == 1
Verifies pagination structure and correct filtering of published books only