0
# Django Utilities
1
2
Utility functions and test runner integration for Django and pytest. This includes helper functions for Django configuration checks, test case identification, and the Django test runner class for manage.py integration.
3
4
## Capabilities
5
6
### Django Configuration Helpers
7
8
Utility functions for checking Django configuration state and skipping tests.
9
10
```python { .api }
11
def skip_if_no_django() -> None:
12
"""
13
Skip test if Django settings are not configured.
14
15
Raises pytest.skip if Django settings module is not available
16
or Django is not properly configured. Used internally by fixtures
17
to gracefully handle tests in non-Django environments.
18
"""
19
20
def django_settings_is_configured() -> bool:
21
"""
22
Check if Django settings are configured.
23
24
Checks both DJANGO_SETTINGS_MODULE environment variable and
25
django.conf.settings.configured flag to determine if Django
26
is properly set up.
27
28
Returns:
29
bool: True if Django settings are configured, False otherwise
30
"""
31
32
def get_django_version() -> tuple[int, int, int, str, int]:
33
"""
34
Get Django version tuple.
35
36
Returns Django version information in the same format as
37
django.VERSION tuple.
38
39
Returns:
40
tuple: Django version as (major, minor, micro, releaselevel, serial)
41
"""
42
```
43
44
Usage examples:
45
```python
46
from pytest_django import skip_if_no_django, django_settings_is_configured
47
48
# Skip test if Django not available
49
def test_django_feature():
50
skip_if_no_django()
51
from django.contrib.auth.models import User
52
# Test Django functionality
53
54
# Conditional test execution
55
def test_conditional_django():
56
if not django_settings_is_configured():
57
pytest.skip("Django not configured")
58
# Test requires Django configuration
59
```
60
61
### Django Test Case Detection
62
63
Helper function for identifying Django test cases.
64
65
```python { .api }
66
def is_django_unittest(request_or_item: Union[pytest.FixtureRequest, pytest.Item]) -> bool:
67
"""
68
Check if request or item is a Django test case.
69
70
Determines whether a pytest request or item represents a Django
71
unittest-style test case (subclass of django.test.SimpleTestCase).
72
Used internally for applying Django-specific test setup.
73
74
Args:
75
request_or_item: pytest FixtureRequest or Item to check
76
77
Returns:
78
bool: True if item is Django test case, False otherwise
79
"""
80
```
81
82
Usage example:
83
```python
84
import pytest
85
from pytest_django import is_django_unittest
86
87
def pytest_runtest_setup(item):
88
if is_django_unittest(item):
89
# Apply Django-specific setup
90
setup_django_test(item)
91
```
92
93
### Django Test Runner
94
95
Test runner class for using pytest with Django's manage.py test command.
96
97
```python { .api }
98
class TestRunner:
99
"""Django test runner that uses pytest for test discovery and execution."""
100
101
def __init__(
102
self,
103
*,
104
verbosity: int = 1,
105
failfast: bool = False,
106
keepdb: bool = False,
107
**kwargs: Any
108
) -> None:
109
"""
110
Initialize test runner with Django test command options.
111
112
Args:
113
verbosity: Test output verbosity level (0-3)
114
failfast: Stop on first test failure
115
keepdb: Preserve test database between runs
116
kwargs: Additional keyword arguments
117
"""
118
119
@classmethod
120
def add_arguments(cls, parser: ArgumentParser) -> None:
121
"""
122
Add command line arguments to Django test command parser.
123
124
Adds pytest-django specific arguments to Django's test command,
125
allowing integration with manage.py test.
126
127
Args:
128
parser: Django command argument parser
129
"""
130
131
def run_tests(self, test_labels: Iterable[str], **kwargs: Any) -> int:
132
"""
133
Run tests using pytest and return exit code.
134
135
Translates Django test command options to pytest arguments
136
and executes pytest with the specified test labels.
137
138
Args:
139
test_labels: Test labels to run (paths, modules, classes)
140
kwargs: Additional keyword arguments
141
142
Returns:
143
int: pytest exit code (0 for success, non-zero for failures)
144
"""
145
```
146
147
Usage in Django settings:
148
```python
149
# settings.py
150
TEST_RUNNER = 'pytest_django.TestRunner'
151
152
# Now can use: python manage.py test
153
# Which will run pytest instead of Django's default test runner
154
```
155
156
Django management command usage:
157
```bash
158
# Run all tests with pytest
159
python manage.py test
160
161
# Run specific test with pytest
162
python manage.py test myapp.tests.test_models
163
164
# Run with pytest options via Django
165
python manage.py test --keepdb --failfast
166
```
167
168
## Utility Types
169
170
```python { .api }
171
from typing import Union, Iterable, Any, Tuple
172
from argparse import ArgumentParser
173
import pytest
174
175
# Django version type
176
DjangoVersion = Tuple[int, int, int, str, int]
177
178
# Test runner types
179
TestLabels = Iterable[str]
180
TestRunnerKwargs = dict[str, Any]
181
ExitCode = int
182
183
# Request/Item types
184
RequestOrItem = Union[pytest.FixtureRequest, pytest.Item]
185
186
# Test runner configuration
187
class TestRunnerConfig:
188
verbosity: int
189
failfast: bool
190
keepdb: bool
191
192
# Argument parser type
193
CommandParser = ArgumentParser
194
```