A Django plugin for pytest that provides Django-specific testing fixtures, marks, and assertions.
npx @tessl/cli install tessl/pypi-pytest-django@4.11.00
# pytest-django
1
2
A Django plugin for pytest that enables seamless testing of Django applications using the pytest testing framework. It provides Django-specific fixtures for database testing, settings management, client testing, and Django application lifecycle management while maintaining full compatibility with existing unittest-style TestCase classes.
3
4
## Package Information
5
6
- **Package Name**: pytest-django
7
- **Package Type**: pypi
8
- **Language**: Python
9
- **Installation**: `pip install pytest-django`
10
11
## Core Imports
12
13
```python
14
import pytest
15
from pytest_django import DjangoDbBlocker, DjangoAssertNumQueries, DjangoCaptureOnCommitCallbacks
16
```
17
18
Most functionality is automatically available through pytest plugin system:
19
20
```python
21
# Fixtures are automatically available in tests
22
def test_example(db, client, settings):
23
# db fixture enables database access
24
# client fixture provides Django test client
25
# settings fixture allows settings modification
26
pass
27
```
28
29
## Basic Usage
30
31
```python
32
import pytest
33
34
# Enable database access for test
35
@pytest.mark.django_db
36
def test_database_operations(db):
37
from myapp.models import MyModel
38
39
# Create and test model
40
obj = MyModel.objects.create(name="test")
41
assert obj.name == "test"
42
assert MyModel.objects.count() == 1
43
44
# Use Django test client
45
def test_view_response(client):
46
response = client.get("/my-view/")
47
assert response.status_code == 200
48
49
# Modify Django settings temporarily
50
def test_with_custom_settings(settings):
51
settings.DEBUG = True
52
settings.SECRET_KEY = "test-key"
53
# Settings automatically restored after test
54
55
# Test with admin user
56
def test_admin_functionality(admin_client, admin_user):
57
response = admin_client.get("/admin/")
58
assert response.status_code == 200
59
assert admin_user.is_superuser
60
```
61
62
## Architecture
63
64
pytest-django operates as a pytest plugin that bridges Django's testing ecosystem with pytest's fixture system:
65
66
- **Plugin Registration**: Automatically registers via entry_points.pytest11
67
- **Fixture System**: Provides 40+ fixtures for database, client, settings, and user management
68
- **Mark System**: Custom pytest marks (@pytest.mark.django_db, @pytest.mark.urls, etc.)
69
- **Database Management**: Handles test database creation, transactions, and cleanup
70
- **Django Integration**: Manages Django settings, app configuration, and lifecycle
71
72
The plugin ensures proper Django setup and teardown while leveraging pytest's powerful features like parametrization, fixtures, and parallel execution.
73
74
## Capabilities
75
76
### Database Testing Fixtures
77
78
Database access control, transaction management, and database setup fixtures for Django testing with pytest.
79
80
```python { .api }
81
def db() -> None: ...
82
def transactional_db() -> None: ...
83
def django_db_setup() -> None: ...
84
def django_db_reset_sequences() -> None: ...
85
def django_db_serialized_rollback() -> None: ...
86
```
87
88
[Database Testing](./database-testing.md)
89
90
### Django Test Client Fixtures
91
92
Django test client and request factory fixtures for HTTP testing and view testing.
93
94
```python { .api }
95
def client() -> django.test.Client: ...
96
def async_client() -> django.test.AsyncClient: ...
97
def rf() -> django.test.RequestFactory: ...
98
def async_rf() -> django.test.AsyncRequestFactory: ...
99
```
100
101
[Client Testing](./client-testing.md)
102
103
### User Management Fixtures
104
105
User creation and authentication fixtures for testing Django user functionality.
106
107
```python { .api }
108
def admin_user(db: None, django_user_model, django_username_field): ...
109
def admin_client(admin_user) -> django.test.Client: ...
110
def django_user_model(db: None): ...
111
def django_username_field(django_user_model) -> str: ...
112
```
113
114
[User Management](./user-management.md)
115
116
### Settings Management
117
118
Django settings configuration and temporary modification fixtures.
119
120
```python { .api }
121
class SettingsWrapper:
122
def __setattr__(self, name: str, value: Any) -> None: ...
123
def __getattr__(self, name: str) -> Any: ...
124
def __enter__(self) -> SettingsWrapper: ...
125
def __exit__(self, exc_type, exc_value, traceback) -> None: ...
126
127
def settings() -> SettingsWrapper: ...
128
```
129
130
[Settings Management](./settings-management.md)
131
132
### Email Testing
133
134
Email testing fixtures for capturing and testing Django email functionality.
135
136
```python { .api }
137
def mailoutbox() -> List[django.core.mail.EmailMessage]: ...
138
def django_mail_patch_dns() -> None: ...
139
def django_mail_dnsname() -> str: ...
140
```
141
142
[Email Testing](./email-testing.md)
143
144
### Database Query Testing
145
146
Fixtures for asserting and controlling database query counts during testing.
147
148
```python { .api }
149
class DjangoAssertNumQueries:
150
def __call__(self, num: int) -> ContextManager[None]: ...
151
152
def django_assert_num_queries(pytestconfig: pytest.Config) -> DjangoAssertNumQueries: ...
153
def django_assert_max_num_queries(pytestconfig: pytest.Config) -> DjangoAssertNumQueries: ...
154
```
155
156
[Query Testing](./query-testing.md)
157
158
### Live Server Testing
159
160
Live server fixtures for integration testing with running Django server.
161
162
```python { .api }
163
def live_server(request: pytest.FixtureRequest): ...
164
```
165
166
[Live Server Testing](./live-server-testing.md)
167
168
### Django Assertions
169
170
All Django TestCase assertion methods for comprehensive testing capabilities.
171
172
```python { .api }
173
def assertRedirects(response, expected_url, status_code=302, target_status_code=200, **kwargs): ...
174
def assertContains(response, text, count=None, status_code=200, **kwargs): ...
175
def assertTemplateUsed(response=None, template_name=None, **kwargs): ...
176
def assertFormError(form, field, errors, **kwargs): ...
177
def assertHTMLEqual(html1: str, html2: str, msg=None): ...
178
def assertJSONEqual(raw: str, expected_data, msg=None): ...
179
def assertNumQueries(num: int, func=None, *args, using="default", **kwargs): ...
180
```
181
182
[Django Assertions](./django-assertions.md)
183
184
### Pytest Marks
185
186
Django-specific pytest marks for test configuration and behavior control.
187
188
```python { .api }
189
@pytest.mark.django_db(
190
transaction: bool = False,
191
reset_sequences: bool = False,
192
databases: list[str] | str | None = None,
193
serialized_rollback: bool = False,
194
available_apps: list[str] | None = None
195
): ...
196
197
@pytest.mark.urls(module: str): ...
198
@pytest.mark.ignore_template_errors(): ...
199
```
200
201
[Pytest Marks](./pytest-marks.md)
202
203
### Transaction Callback Testing
204
205
Fixtures for testing Django's on_commit callbacks and transaction behavior.
206
207
```python { .api }
208
class DjangoCaptureOnCommitCallbacks:
209
def __call__(self) -> ContextManager[list]: ...
210
211
def django_capture_on_commit_callbacks() -> DjangoCaptureOnCommitCallbacks: ...
212
```
213
214
[Transaction Callbacks](./transaction-callbacks.md)
215
216
### Django Test Runner
217
218
Django test runner integration for using pytest with Django's manage.py test command.
219
220
```python { .api }
221
class TestRunner:
222
def __init__(
223
self,
224
*,
225
verbosity: int = 1,
226
failfast: bool = False,
227
keepdb: bool = False,
228
**kwargs
229
) -> None: ...
230
231
@classmethod
232
def add_arguments(cls, parser: ArgumentParser) -> None: ...
233
234
def run_tests(self, test_labels: Iterable[str], **kwargs) -> int: ...
235
```
236
237
[Django Utilities](./django-utilities.md)
238
239
## Common Types
240
241
```python { .api }
242
from typing import ContextManager, Any, Optional, Union, List, Literal
243
244
# Database configuration types
245
DatabasesType = Optional[Union[Literal["__all__"], List[str]]]
246
AvailableAppsType = Optional[List[str]]
247
248
# Django test client types
249
from django.test import Client, AsyncClient, RequestFactory, AsyncRequestFactory
250
from django.http import HttpResponse
251
from django.contrib.auth.models import AbstractUser
252
253
# Settings wrapper type
254
class SettingsWrapper:
255
"""Wrapper for Django settings with context manager support."""
256
pass
257
258
# Query assertion types
259
class DjangoAssertNumQueries:
260
"""Context manager for asserting database query counts."""
261
pass
262
263
class DjangoCaptureOnCommitCallbacks:
264
"""Context manager for capturing on_commit callbacks."""
265
pass
266
267
class DjangoDbBlocker:
268
"""Database access control context manager."""
269
def __init__(self, *, _ispytest: bool = False) -> None: ...
270
def block(self) -> ContextManager[None]: ...
271
def unblock(self) -> ContextManager[None]: ...
272
def restore(self) -> None: ...
273
274
@property
275
def is_active(self) -> bool: ...
276
```