python / intermediate
Snippet
Django Testing mit pytest-django und Factories
Effektives Django-Testing kombiniert pytest-django für Datenbank-Fixtures mit factory_boy für Testdatenerstellung. Der @pytest.mark.django_db-Dekorator bietet Transaktionsebene-Testisolierung. Factories wie BookFactory erstellen gültige Modellinstanzen ohne wiederholende Fixture-Daten. APIClient von DRF simuliert HTTP-Anfragen. Die Verwendung von Fixtures für das Setup gewährleistet, dass Tests isoliert, lesbar und wartbar sind.
snippet.py
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 pytestfrom django.contrib.auth.models import Userfrom rest_framework.test import APIClientfrom books.models import Book, Categoryfrom books.factories import BookFactory, AuthorFactory@pytest.fixturedef api_client():return APIClient()@pytest.fixturedef author(db):return AuthorFactory()@pytest.fixturedef published_book(db, author):return BookFactory(is_published=True, author=author)@pytest.mark.django_dbclass TestBookAPI:def test_book_list_returns_only_published(self, api_client, published_book):response = api_client.get('/api/books/')assert response.status_code == 200assert len(response.data['results']) == 1assert 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 == 200assert unpublished.title not in str(response.data)
django
Erklärung
1
@pytest.mark.django_db
Gewährt dem Test Zugriff auf die Datenbank mit automatischem Transaktions-Rollback nach jedem Test
2
@pytest.fixture
def author(db):
Fixture, das einen Autor mit der Factory erstellt und Datenbankzugriff gewährleistet
3
published_book = BookFactory(is_published=True)
Factory erstellt eine vollständig gültige Book-Instanz mit vernünftigen Standardwerten
4
assert len(response.data['results']) == 1
Überprüft die Paginierungsstruktur und korrekte Filterung nur veröffentlichter Bücher