Communitygithub.com

django-tdd

Django-Teststrategien mit pytest-django, TDD-Methodik, factory_boy, Mocking, Coverage und Testen von Django REST Framework-APIs. Verwenden Sie dies, wenn Sie Django- oder DRF-Tests mit pytest-django schreiben oder eine Django-Funktion testgetrieben entwickeln.

Was ist django-tdd?

Diese Skill-Anleitung beschreibt eine umfassende Test-driven Development (TDD)-Methodik für Django-Anwendungen unter Verwendung von pytest-django, factory_boy und Django REST Framework. Sie ist nützlich für Entwickler, die robuste, getestete Django-Projekte erstellen möchten, und unterstützt Plattformen wie Claude Code, Cursor und Codex. Die Skill-Anleitung führt durch den gesamten TDD-Workflow, einschließlich des Red-Green-Refactor-Zyklus, der Konfiguration von pytest- und Django-Testeinstellungen, der Erstellung von Fixtures in conftest.py sowie der Nutzung von Factory Boy zur effizienten Testdatenerstellung. Darüber hinaus deckt sie das Testen von Django-Modellen, Views und DRF-Serializern sowie API-Endpunkten ab, inklusive Authentifizierung und Autorisierung. Die Anleitung enthält zahlreiche Codebeispiele, die sofort in eigenen Projekten eingesetzt werden können, um eine hohe Codequalität und Zuverlässigkeit sicherzustellen.

Funktioniert mit~Claude Code~Codex CLI~Cursor
npx skills add https://github.com/affaan-m/everything-claude-code/tree/main/skills/django-tdd

In Ihrer bevorzugten KI fragen

Öffnet einen neuen Chat, in dem dieser Agent-Skill bereits geladen ist.

Dokumentation

Django-Testen mit TDD

Testgetriebene Entwicklung für Django-Anwendungen mit pytest, factory_boy und Django REST Framework.

Wann aktivieren

  • Schreiben neuer Django-Anwendungen
  • Implementieren von Django REST Framework APIs
  • Testen von Django-Modellen, Views und Serialsierern
  • Einrichten der Test-Infrastruktur für Django-Projekte

TDD-Workflow für Django

Red-Green-Refactor-Zyklus

# Schritt 1: ROT - Fehlschlagenden Test schreiben
def test_user_creation():
    user = User.objects.create_user(email='[email protected]', password='testpass123')
    assert user.email == '[email protected]'
    assert user.check_password('testpass123')
    assert not user.is_staff

# Schritt 2: GRÜN - Test bestehen lassen
# User-Modell oder Factory erstellen

# Schritt 3: REFAKTORIEREN - Verbessern, während Tests grün bleiben

Einrichtung

pytest-Konfiguration

# pytest.ini
[pytest]
DJANGO_SETTINGS_MODULE = config.settings.test
testpaths = tests
python_files = test_*.py
python_classes = Test*
python_functions = test_*
addopts =
    --reuse-db
    --nomigrations
    --cov=apps
    --cov-report=html
    --cov-report=term-missing
    --strict-markers
markers =
    slow: markiert Tests als langsam
    integration: markiert Tests als Integrationstests

Testeinstellungen

# config/settings/test.py
from .base import *

DEBUG = True
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': ':memory:',
    }
}

# Migrationen für Geschwindigkeit deaktivieren
class DisableMigrations:
    def __contains__(self, item):
        return True

    def __getitem__(self, item):
        return None

MIGRATION_MODULES = DisableMigrations()

# Schnelleres Passwort-Hashing
PASSWORD_HASHERS = [
    'django.contrib.auth.hashers.MD5PasswordHasher',
]

# E-Mail-Backend
EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'

# Celery immer eager
CELERY_TASK_ALWAYS_EAGER = True
CELERY_TASK_EAGER_PROPAGATES = True

conftest.py

# tests/conftest.py
import pytest
from django.utils import timezone
from django.contrib.auth import get_user_model

User = get_user_model()

@pytest.fixture(autouse=True)
def timezone_settings(settings):
    """Sicherstellung konsistenter Zeitzone."""
    settings.TIME_ZONE = 'UTC'

@pytest.fixture
def user(db):
    """Erstellen eines Testbenutzers."""
    return User.objects.create_user(
        email='[email protected]',
        password='testpass123',
        username='testuser'
    )

@pytest.fixture
def admin_user(db):
    """Erstellen eines Admin-Benutzers."""
    return User.objects.create_superuser(
        email='[email protected]',
        password='adminpass123',
        username='admin'
    )

@pytest.fixture
def authenticated_client(client, user):
    """Gibt authentifizierten Client zurück."""
    client.force_login(user)
    return client

@pytest.fixture
def api_client():
    """Gibt DRF API-Client zurück."""
    from rest_framework.test import APIClient
    return APIClient()

@pytest.fixture
def authenticated_api_client(api_client, user):
    """Gibt authentifizierten API-Client zurück."""
    api_client.force_authenticate(user=user)
    return api_client

Factory Boy

Factory-Einrichtung

# tests/factories.py
import factory
from factory import fuzzy
from datetime import datetime, timedelta
from django.contrib.auth import get_user_model
from apps.products.models import Product, Category

User = get_user_model()

class UserFactory(factory.django.DjangoModelFactory):
    """Factory für User-Modell."""

    class Meta:
        model = User

    email = factory.Sequence(lambda n: f"user{n}@example.com")
    username = factory.Sequence(lambda n: f"user{n}")
    password = factory.PostGenerationMethodCall('set_password', 'testpass123')
    first_name = factory.Faker('first_name')
    last_name = factory.Faker('last_name')
    is_active = True

class CategoryFactory(factory.django.DjangoModelFactory):
    """Factory für Category-Modell."""

    class Meta:
        model = Category

    name = factory.Faker('word')
    slug = factory.LazyAttribute(lambda obj: obj.name.lower())
    description = factory.Faker('text')

class ProductFactory(factory.django.DjangoModelFactory):
    """Factory für Product-Modell."""

    class Meta:
        model = Product

    name = factory.Faker('sentence', nb_words=3)
    slug = factory.LazyAttribute(lambda obj: obj.name.lower().replace(' ', '-'))
    description = factory.Faker('text')
    price = fuzzy.FuzzyDecimal(10.00, 1000.00, 2)
    stock = fuzzy.FuzzyInteger(0, 100)
    is_active = True
    category = factory.SubFactory(CategoryFactory)
    created_by = factory.SubFactory(UserFactory)

    @factory.post_generation
    def tags(self, create, extracted, **kwargs):
        """Tags zum Produkt hinzufügen."""
        if not create:
            return
        if extracted:
            for tag in extracted:
                self.tags.add(tag)

Verwendung von Factories

# tests/test_models.py
import pytest
from tests.factories import ProductFactory, UserFactory

def test_product_creation():
    """Test der Produkterstellung mit Factory."""
    product = ProductFactory(price=100.00, stock=50)
    assert product.price == 100.00
    assert product.stock == 50
    assert product.is_active is True

def test_product_with_tags():
    """Test des Produkts mit Tags."""
    tags = [TagFactory(name='electronics'), TagFactory(name='new')]
    product = ProductFactory(tags=tags)
    assert product.tags.count() == 2

def test_multiple_products():
    """Test der Erstellung mehrerer Produkte."""
    products = ProductFactory.create_batch(10)
    assert len(products) == 10

Modell-Tests

Modelltests

# tests/test_models.py
import pytest
from django.core.exceptions import ValidationError
from tests.factories import UserFactory, ProductFactory

class TestUserModel:
    """Test User-Modell."""

    def test_create_user(self, db):
        """Test der Erstellung eines regulären Benutzers."""
        user = UserFactory(email='[email protected]')
        assert user.email == '[email protected]'
        assert user.check_password('testpass123')
        assert not user.is_staff
        assert not user.is_superuser

    def test_create_superuser(self, db):
        """Test der Erstellung eines Superusers."""
        user = UserFactory(
            email='[email protected]',
            is_staff=True,
            is_superuser=True
        )
        assert user.is_staff
        assert user.is_superuser

    def test_user_str(self, db):
        """Test der String-Repräsentation des Benutzers."""
        user = UserFactory(email='[email protected]')
        assert str(user) == '[email protected]'

class TestProductModel:
    """Test Product-Modell."""

    def test_product_creation(self, db):
        """Test der Erstellung eines Produkts."""
        product = ProductFactory()
        assert product.id is not None
        assert product.is_active is True
        assert product.created_at is not None

    def test_product_slug_generation(self, db):
        """Test der automatischen Slug-Generierung."""
        product = ProductFactory(name='Test Product')
        assert product.slug == 'test-product'

    def test_product_price_validation(self, db):
        """Test, dass Preis nicht negativ sein kann."""
        product = ProductFactory(price=-10)
        with pytest.raises(ValidationError):
            product.full_clean()

    def test_product_manager_active(self, db):
        """Test der aktiven Manager-Methode."""
        ProductFactory.create_batch(5, is_active=True)
        ProductFactory.create_batch(3, is_active=False)

        active_count = Product.objects.active().count()
        assert active_count == 5

    def test_product_stock_management(self, db):
        """Test der Bestandsverwaltung."""
        product = ProductFactory(stock=10)
        product.reduce_stock(5)
        product.refresh_from_db()
        assert product.stock == 5

        with pytest.raises(ValueError):
            product.reduce_stock(10)  # Nicht genug Bestand

View-Tests

Django View-Tests

# tests/test_views.py
import pytest
from django.urls import reverse
from tests.factories import ProductFactory, UserFactory

class TestProductViews:
    """Test Produkt-Views."""

    def test_product_list(self, client, db):
        """Test der Produktliste-View."""
        ProductFactory.create_batch(10)

        response = client.get(reverse('products:list'))

        assert response.status_code == 200
        assert len(response.context['products']) == 10

    def test_product_detail(self, client, db):
        """Test der Produktdetail-View."""
        product = ProductFactory()

        response = client.get(reverse('products:detail', kwargs={'slug': product.slug}))

        assert response.status_code == 200
        assert response.context['product'] == product

    def test_product_create_requires_login(self, client, db):
        """Test, dass Produkterstellung Authentifizierung erfordert."""
        response = client.get(reverse('products:create'))

        assert response.status_code == 302
        assert response.url.startswith('/accounts/login/')

    def test_product_create_authenticated(self, authenticated_client, db):
        """Test der Produkterstellung als authentifizierter Benutzer."""
        response = authenticated_client.get(reverse('products:create'))

        assert response.status_code == 200

    def test_product_create_post(self, authenticated_client, db, category):
        """Test der Erstellung eines Produkts per POST."""
        data = {
            'name': 'Test Product',
            'description': 'A test product',
            'price': '99.99',
            'stock': 10,
            'category': category.id,
        }

        response = authenticated_client.post(reverse('products:create'), data)

        assert response.status_code == 302
        assert Product.objects.filter(name='Test Product').exists()

DRF-API-Tests

Serializer-Tests

# tests/test_serializers.py
import pytest
from rest_framework.exceptions import ValidationError
from apps.products.serializers import ProductSerializer
from tests.factories import ProductFactory

class TestProductSerializer:
    """Test ProductSerializer."""

    def test_serialize_product(self, db):
        """Test des Serialisierens eines Produkts."""
        product = ProductFactory()
        serializer = ProductSerializer(product)

        data = serializer.data

        assert data['id'] == product.id
        assert data['name'] == product.name
        assert data['price'] == str(product.price)

    def test_deserialize_product(self, db):
        """Test des Deserialisierens von Produktdaten."""
        data = {
            'name': 'Test Product',
            'description': 'Test description',
            'price': '99.99',
            'stock': 10,
            'category': 1,
        }

        serializer = ProductSerializer(data=data)

        assert serializer.is_valid()
        product = serializer.save()

        assert product.name == 'Test Product'
        assert float(product.price) == 99.99

    def test_price_validation(self, db):
        """Test der Preisvalidierung."""
        data = {
            'name': 'Test Product',
            'price': '-10.00',
            'stock': 10,
        }

        serializer = ProductSerializer(data=data)

        assert not serializer.is_valid()
        assert 'price' in serializer.errors

    def test_stock_validation(self, db):
        """Test, dass Bestand nicht negativ sein kann."""
        data = {
            'name': 'Test Product',
            'price': '99.99',
            'stock': -5,
        }

        serializer = ProductSerializer(data=data)

        assert not serializer.is_valid()
        assert 'stock' in serializer.errors

API-ViewSet-Tests

# tests/test_api.py
import pytest
from rest_framework.test import APIClient
from rest_framework import status
from django.urls import reverse
from tests.factories import ProductFactory, UserFactory

class TestProductAPI:
    """Test Product-API-Endpunkte."""

    @pytest.fixture
    def api_client(self):
        """Gibt API-Client zurück."""
        return APIClient()

    def test_list_products(self, api_client, db):
        """Test der Auflistung von Produkten."""
        ProductFactory.create_batch(10)

        url = reverse('api:product-list')
        response = api_client.get(url)

        assert response.status_code == status.HTTP_200_OK
        assert response.data['count'] == 10

    def test_retrieve_product(self, api_client, db):
        """Test des Abrufens eines Produkts."""
        product = ProductFactory()

        url = reverse('api:product-detail', kwargs={'pk': product.id})
        response = api_client.get(url)

        assert response.status_code == status.HTTP_200_OK
        assert response.data['id'] == product.id

    def test_create_product_unauthorized(self, api_client, db):
        """Test der Produkterstellung ohne Authentifizierung."""
        url = reverse('api:product-list')
        data = {'name': 'Test Product', 'price': '99.99'}

        response = api_client.post(url, data)

        assert response.status_code == status.HTTP_401_UNAUTHORIZED

    def test_create_product_authorized(self, authenticated_api_client, db):
        """Test der Produkterstellung als authentifizierter Benutzer."""
        url = reverse('api:product-list')
        data = {
            'name': 'Test Product',
            'description': 'Test',
            'price': '99.99',
            'stock': 10,
        }

        response = authenticated_api_client.post(url, data)

        assert response.status_code == status.HTTP_201_CREATED
        assert response.data['name'] == 'Test Product'

    def test_update_product(self, authenticated_api_client, db):
        """Test der Aktualisierung eines Produkts."""
        product = ProductFactory(created_by=authenticated_api_client.user)

        url = reverse('api:product-detail', kwargs={'pk': product.id})
        data = {'name': 'Updated Product'}

        response = authenticated_api_client.patch(url, data)

        assert response.status_code == status.HTTP_200_OK
        assert response.data['name'] == 'Updated Product'

    def test_delete_product(self, authenticated_api_client, db):
        """Test der Löschung eines Produkts."""
        product = ProductFactory(created_by=authenticated_api_client.user)

        url = reverse('api:product-detail', kwargs={'pk': product.id})

        response = authenticated_api_client.delete(url)

        assert response.status_code == status.HTTP_204_NO_CONTENT
        assert not Product.objects.filter(id=product.id).exists()

    def test_unauthorized_delete(self, unauthorized_api_client, db):
        """Test der Löschung ohne Authentifizierung."""
        product = ProductFactory()

        url = reverse('api:product-detail', kwargs={'pk': product.id})

        response = unauthorized_api_client.delete(url)

        assert response.status_code == status.HTTP_401_UNAUTHORIZED

Mocking

Patching und Side Effects

# tests/test_services.py
from unittest.mock import patch, Mock
import pytest
from django.core.mail import send_mail

class TestEmailService:
    """Test E-Mail-Dienst."""

    @patch('django.core.mail.send_mail')
    def test_send_welcome_email(self, mock_send_mail, db):
        """Test des Sendens einer Willkommens-E-Mail."""
        user = UserFactory()

        send_welcome_email(user)

        mock_send_mail.assert_called_once()
        args, kwargs = mock_send_mail.call_args
        assert 'Willkommen' in kwargs.get('subject', '')
        assert user.email in kwargs.get('recipient_list', [])

    @patch('django.core.mail.send_mail')
    def test_send_mail_failure(self, mock_send_mail, db):
        """Test der Fehlerbehandlung beim Senden einer E-Mail."""
        mock_send_mail.side_effect = Exception('SMTP-Fehler')
        user = UserFactory()

        with pytest.raises(Exception, match='SMTP-Fehler'):
            send_welcome_email(user)

Mocken von API-Aufrufen

# tests/test_external_api.py
from unittest.mock import patch
import pytest
import requests

class TestExternalAPI:
    """Test externe API-Integration."""

    @patch('requests.post')
    def test_payment_gateway(self, mock_post, db):
        """Test der Zahlungs-Gateway-Integration."""
        mock_response = Mock()
        mock_response.status_code = 200
        mock_response.json.return_value = {
            'status': 'erfolgreich',
            'transaction_id': 'txn_123'
        }
        mock_post.return_value = mock_response

        result = process_payment(100.00, 'tok_visa')

        assert result['status'] == 'erfolgreich'
        mock_post.assert_called_once()

Codeabdeckung

Coverage-Konfiguration

# .coveragerc
[run]
source = apps
omit =
    */migrations/*
    */tests/*
    */admin.py
    */apps.py
    */wsgi.py
    manage.py

[report]
exclude_lines =
    pragma: no cover
    def __repr__
    if self.debug:
    if settings.DEBUG
    raise AssertionError
    raise NotImplementedError
    if 0:
    if __name__ == .__main__.:

Zusammenfassung der Best Practices

  1. Schreiben Sie zuerst den Test – Befolgen Sie den TDD-Rot-Grün-Refaktor-Zyklus
  2. Verwenden Sie Factory Boy für saubere, wartbare Testdaten
  3. Halten Sie Tests isoliert – Jeder Test sollte unabhängig ausführbar sein
  4. Testen Sie Randfälle – Grenzwerte, Fehlerzustände und Berechtigungen
  5. Mocken Sie externe Dienste – für zuverlässige, schnelle Tests
  6. Streben Sie nach hoher Abdeckung – aber fokussieren Sie sich auf sinnvolle Tests
  7. Verwenden Sie sprechende Testnamen – Dokumentieren Sie, was getestet wird
  8. Halten Sie Testdaten minimal – Verwenden Sie nur das, was für den Test benötigt wird

Individual skills in this repo

This repo contains 20 individual skills — each has its own dedicated page.

accessibility

Design, implement, and audit inclusive digital products using WCAG 2.2 Level AA. Use when building or auditing UI that must meet WCAG 2.2 Level AA, or when reviewing a change for keyboard, contrast, or screen-reader support.

affaan-m/claude-api

Anthropic Claude API patterns for Python and TypeScript. Covers Messages API, streaming, tool use, vision, extended thinking, batches, prompt caching, and Claude Agent SDK. Use when building applications with the Claude API or Anthropic SDKs.

affaan-m/everything-claude-code

End-to-end marketing campaign planning and execution. Covers audience research, positioning, campaign angle definition, landing page copy, email sequences, social posts, ad copy, short-form video scripts, and content calendars. Use as the orchestration layer for multi-channel product launches. Use when planning or executing a multi-channel product launch, or producing landing page, email, social, or ad copy.

affaan-m/everything-claude-code

Development conventions and patterns for everything-claude-code. JavaScript project with conventional commits.

affaan-m/everything-claude-code-conventions

Development conventions and patterns for everything-claude-code. JavaScript project with conventional commits.

affaan-m/frontend-design

Create distinctive, production-grade frontend interfaces with high design quality. Use when the user asks to build web components, pages, or applications and the visual direction matters as much as the code quality.

affaan-m/gget

gget CLI and Python workflow for quick genomic database queries, sequence lookup, BLAST-style searches, enrichment checks, and reproducible bioinformatics evidence logs.

affaan-m/literature-review

Systematic literature-review workflow for academic, biomedical, technical, and scientific topics, including search planning, source screening, synthesis, citation checks, and evidence logging.

affaan-m/motion-ui

Production-ready UI motion system for React/Next.js. Use when implementing animations, transitions, or motion patterns.

affaan-m/project-guidelines-example

Example project-specific skill template based on a real production application.

affaan-m/pubmed-database

Direct PubMed and NCBI E-utilities search workflows for biomedical literature, MeSH queries, PMID lookup, citation retrieval, and API-backed literature monitoring.

affaan-m/scholar-evaluation

Structured scholarly-work evaluation for papers, proposals, literature reviews, methods sections, evidence quality, citation support, and research-writing feedback.

affaan-m/uspto-database

USPTO patent and trademark data workflow for official record lookup, PatentSearch queries, TSDR checks, assignment data, and reproducible IP research logs.

agent-architecture-audit

Full-stack diagnostic for agent and LLM applications. Audits the 12-layer agent stack for wrapper regression, memory pollution, tool discipline failures, hidden repair loops, and rendering corruption. Produces severity-ranked findings with code-first fixes. Essential for developers building agent applications, autonomous loops, or any LLM-powered feature. Use when an agent or LLM feature misbehaves and the failing layer is unknown, or before shipping an agent stack.

agent-eval

Head-to-head comparison of coding agents (Claude Code, Aider, Codex, etc.) on custom tasks with pass rate, cost, time, and consistency metrics. Use when choosing between coding agents, or when a change to an agent setup needs measured pass rate, cost, and time rather than an impression.

agent-harness-construction

Design and optimize AI agent action spaces, tool definitions, and observation formatting for higher completion rates. Use when defining or revising an agent

agentic-engineering

Operate as an agentic engineer using eval-first execution, decomposition, and cost-aware model routing. Use when planning or executing engineering work that agents will carry out end to end.

agentic-os

Build persistent multi-agent operating systems on Claude Code. Covers kernel architecture, specialist agents, slash commands, file-based memory, scheduled automation, and state management without external databases. Use when building a persistent multi-agent system on Claude Code with its own memory, commands, and scheduling.

agent-introspection-debugging

Structured self-debugging workflow for AI agent failures using capture, diagnosis, contained recovery, and introspection reports. Use when an agent run fails and you need a reproducible diagnosis instead of a retry.

agent-payment-x402

Add x402 payment execution to AI agents with per-task budgets, spending controls, and non-custodial wallets. Supports Base through agentwallet-sdk and X Layer through OKX Payments / OKX Agent Payments Protocol. Use when an agent must pay for something itself and needs per-task budgets, spending controls, and a non-custodial wallet.

Verwandte Skills