pytest-django

4.12.0 · active · verified Wed Apr 08

pytest-django is an active plugin for the pytest testing framework that enables efficient testing of Django projects and applications. It integrates pytest's powerful fixture system, reduced boilerplate, and advanced test capabilities with Django's ORM and components. The library maintains a regular release cadence, with multiple minor versions and occasional major updates throughout the year, ensuring compatibility with the latest Django and Python versions.

Warnings

Install

Imports

Quickstart

1. Create a `pytest.ini` file in your project root, specifying `DJANGO_SETTINGS_MODULE` to point to your Django settings file. This is crucial for pytest-django to set up the Django environment. 2. Define your Django models as usual. 3. Write test functions, using the `@pytest.mark.django_db` decorator or by requesting the `db` fixture for any test that interacts with the database. This enables transaction management and ensures tests are isolated. 4. Run tests with `pytest` in your project root.

# myproject/pytest.ini
[pytest]
DJANGO_SETTINGS_MODULE = myproject.settings
python_files = tests.py test_*.py *_tests.py
addopts = --reuse-db

# myproject/myproject/settings.py (abbreviated)
# ... standard Django settings ...
INSTALLED_APPS = [
    # ...
    'myapp',
    # ...
]

# myproject/myapp/models.py
from django.db import models

class Book(models.Model):
    title = models.CharField(max_length=200)
    author = models.CharField(max_length=100)

    def __str__(self):
        return self.title

# myproject/myapp/tests.py
import pytest
from myapp.models import Book

@pytest.mark.django_db
def test_book_creation():
    # The 'db' fixture or 'pytest.mark.django_db' is required for database access.
    book = Book.objects.create(title='The Great Adventure', author='Jane Doe')
    assert Book.objects.count() == 1
    assert book.title == 'The Great Adventure'

view raw JSON →