0
# Database Testing
1
2
Database access control, transaction management, and database setup fixtures for Django testing with pytest. These fixtures handle test database creation, transaction rollback, sequence reset, and parallel testing isolation.
3
4
## Capabilities
5
6
### Basic Database Access
7
8
Enable database access for tests with automatic transaction rollback after each test.
9
10
```python { .api }
11
def db() -> None:
12
"""
13
Enable database access for test with transaction rollback.
14
15
Automatically rolls back any database changes after test completion.
16
Use this fixture when you need basic database access without
17
transaction testing requirements.
18
"""
19
```
20
21
Usage example:
22
```python
23
@pytest.mark.django_db
24
def test_model_creation(db):
25
from myapp.models import MyModel
26
obj = MyModel.objects.create(name="test")
27
assert obj.name == "test"
28
# Database changes automatically rolled back
29
```
30
31
### Transactional Database Access
32
33
Enable database access with transaction support for testing transaction-related functionality.
34
35
```python { .api }
36
def transactional_db() -> None:
37
"""
38
Enable database access with transaction support.
39
40
Unlike the db fixture, this allows testing of transaction.atomic(),
41
on_commit callbacks, and other transaction-related Django features.
42
Database changes are still cleaned up after the test.
43
"""
44
```
45
46
Usage example:
47
```python
48
@pytest.mark.django_db(transaction=True)
49
def test_transaction_atomic(transactional_db):
50
from django.db import transaction
51
from myapp.models import MyModel
52
53
with transaction.atomic():
54
MyModel.objects.create(name="test1")
55
# Test transaction behavior
56
```
57
58
### Database Setup
59
60
Session-scoped fixture for database setup and configuration.
61
62
```python { .api }
63
def django_db_setup() -> None:
64
"""
65
Set up Django test databases for the test session.
66
67
Session-scoped fixture that creates test databases and applies
68
migrations. Automatically handles database cleanup at session end.
69
Called automatically when database fixtures are used.
70
"""
71
```
72
73
### Database Settings Modification
74
75
Control database configuration for parallel and distributed testing.
76
77
```python { .api }
78
def django_db_modify_db_settings() -> None:
79
"""
80
Modify database settings for parallel test execution.
81
82
Session-scoped fixture that automatically adds suffixes to database
83
names for tox parallel execution and pytest-xdist worker processes.
84
"""
85
86
def django_db_modify_db_settings_parallel_suffix(
87
django_db_modify_db_settings_tox_suffix: None,
88
django_db_modify_db_settings_xdist_suffix: None
89
) -> None:
90
"""
91
Apply parallel testing database name suffixes.
92
93
Combines tox and xdist suffixes for database isolation in
94
parallel test execution environments.
95
"""
96
97
def django_db_modify_db_settings_tox_suffix() -> None:
98
"""
99
Add tox environment suffix to database names.
100
101
Session-scoped fixture that adds TOX_PARALLEL_ENV suffix
102
to test database names for tox parallel execution isolation.
103
"""
104
105
def django_db_modify_db_settings_xdist_suffix(request: pytest.FixtureRequest) -> None:
106
"""
107
Add pytest-xdist worker suffix to database names.
108
109
Session-scoped fixture that adds worker ID suffix (gw0, gw1, etc.)
110
to test database names for pytest-xdist parallel execution isolation.
111
"""
112
```
113
114
### Sequence Reset
115
116
Reset database sequences after tests that insert data with explicit primary keys.
117
118
```python { .api }
119
def django_db_reset_sequences() -> None:
120
"""
121
Reset database sequences after test completion.
122
123
Use when tests create objects with explicit primary key values,
124
ensuring sequences are properly reset for subsequent tests.
125
Only works with databases that support sequences (PostgreSQL, Oracle).
126
"""
127
```
128
129
Usage example:
130
```python
131
@pytest.mark.django_db(reset_sequences=True)
132
def test_with_explicit_pk(django_db_reset_sequences):
133
from myapp.models import MyModel
134
MyModel.objects.create(id=100, name="test")
135
# Sequences automatically reset after test
136
```
137
138
### Serialized Rollback
139
140
Enable serialized rollback for tests that require specific database state.
141
142
```python { .api }
143
def django_db_serialized_rollback() -> None:
144
"""
145
Enable serialized rollback for database state preservation.
146
147
Serializes database state before test and restores it after,
148
instead of using transaction rollback. Useful for tests that
149
require specific database state or work with multiple databases.
150
"""
151
```
152
153
Usage example:
154
```python
155
@pytest.mark.django_db(serialized_rollback=True)
156
def test_with_serialized_rollback(django_db_serialized_rollback):
157
# Test with preserved database state
158
pass
159
```
160
161
### Migration Control
162
163
Control whether Django migrations are used during test database setup.
164
165
```python { .api }
166
def django_db_use_migrations(request: pytest.FixtureRequest) -> bool:
167
"""
168
Control migration usage during test database setup.
169
170
Session-scoped fixture that determines whether Django migrations
171
are applied during test database creation. Can be controlled via
172
--migrations/--nomigrations command line options.
173
174
Returns:
175
bool: True if migrations should be used, False otherwise
176
"""
177
```
178
179
### Database Persistence Control
180
181
Control test database creation and persistence across test runs.
182
183
```python { .api }
184
def django_db_keepdb(request: pytest.FixtureRequest) -> bool:
185
"""
186
Control database persistence across test runs.
187
188
Session-scoped fixture that determines whether the test database
189
should be preserved after test completion. Controlled via
190
--reuse-db command line option.
191
192
Returns:
193
bool: True if database should be kept, False otherwise
194
"""
195
196
def django_db_createdb(request: pytest.FixtureRequest) -> bool:
197
"""
198
Control test database creation behavior.
199
200
Session-scoped fixture that determines whether the test database
201
should be recreated even if it exists. Controlled via
202
--create-db command line option.
203
204
Returns:
205
bool: True if database should be recreated, False otherwise
206
"""
207
```
208
209
## Database Configuration Types
210
211
```python { .api }
212
from typing import Optional, Union, List, Literal, Tuple, Iterable
213
214
# Database selection types
215
DatabasesType = Optional[Union[Literal["__all__"], Iterable[str]]]
216
AvailableAppsType = Optional[List[str]]
217
218
# Internal database configuration tuple
219
DatabaseConfigTuple = Tuple[
220
bool, # transaction
221
bool, # reset_sequences
222
DatabasesType, # databases
223
bool, # serialized_rollback
224
AvailableAppsType # available_apps
225
]
226
```