0
# Warning Types and Error Handling
1
2
Comprehensive warning type hierarchy for pytest-specific warnings including deprecation warnings, configuration warnings, collection warnings, and error handling patterns. These warnings help developers identify potential issues and deprecated functionality.
3
4
## Capabilities
5
6
### Base Warning Types
7
8
Foundation warning classes for the pytest warning hierarchy.
9
10
```python { .api }
11
class PytestWarning(UserWarning):
12
"""
13
Base class for all pytest warnings.
14
15
This is the base class that all pytest-specific warnings inherit from.
16
It extends Python's UserWarning to provide pytest-specific warning behavior.
17
"""
18
19
class PytestDeprecationWarning(PytestWarning, DeprecationWarning):
20
"""
21
Warning for features that will be removed in future versions.
22
23
Used to warn about deprecated pytest functionality that will be removed
24
in upcoming major releases. Extends both PytestWarning and DeprecationWarning.
25
"""
26
```
27
28
### Specific Warning Categories
29
30
Detailed warning types for different aspects of pytest functionality.
31
32
```python { .api }
33
class PytestAssertRewriteWarning(PytestWarning):
34
"""
35
Warnings from the assert rewrite module.
36
37
Issued when there are problems with assertion rewriting, such as:
38
- Files that cannot be rewritten
39
- Import-time assertion rewrite issues
40
- Conflicting assertion rewrite configurations
41
"""
42
43
class PytestCacheWarning(PytestWarning):
44
"""
45
Cache plugin warnings.
46
47
Issued when there are problems with pytest's caching functionality:
48
- Cache directory access issues
49
- Cache corruption problems
50
- Cache configuration warnings
51
"""
52
53
class PytestCollectionWarning(PytestWarning):
54
"""
55
Collection failures for files or symbols.
56
57
Issued during test collection when:
58
- Files cannot be imported
59
- Test functions/classes cannot be collected
60
- Collection configuration issues arise
61
"""
62
63
class PytestConfigWarning(PytestWarning):
64
"""
65
Configuration issues and warnings.
66
67
Issued when there are problems with pytest configuration:
68
- Invalid configuration values
69
- Conflicting configuration options
70
- Missing required configuration
71
"""
72
73
class PytestUnknownMarkWarning(PytestWarning):
74
"""
75
Unknown marker usage warnings.
76
77
Issued when tests use marks that haven't been registered:
78
- Unregistered custom marks
79
- Typos in mark names
80
- Missing mark definitions
81
"""
82
```
83
84
### Experimental and Future Warnings
85
86
Warnings for experimental features and future changes.
87
88
```python { .api }
89
class PytestExperimentalApiWarning(PytestWarning, FutureWarning):
90
"""
91
Experimental API usage warnings.
92
93
Issued when using experimental pytest APIs that:
94
- May change without notice
95
- Are not covered by backward compatibility guarantees
96
- Are in development and may be removed
97
"""
98
99
class PytestRemovedIn9Warning(PytestDeprecationWarning):
100
"""
101
Features that will be removed in pytest 9.
102
103
Specific deprecation warning for functionality scheduled for removal
104
in pytest version 9.0. Provides clear migration path and timeline.
105
"""
106
```
107
108
### Runtime and Execution Warnings
109
110
Warnings related to test execution and runtime behavior.
111
112
```python { .api }
113
class PytestReturnNotNoneWarning(PytestWarning):
114
"""
115
Test functions returning non-None values.
116
117
Issued when test functions return values other than None:
118
- Test functions that return values
119
- Generator functions used as tests incorrectly
120
- Functions that should be fixtures but aren't marked
121
"""
122
123
class PytestUnraisableExceptionWarning(PytestWarning):
124
"""
125
Unraisable exceptions (e.g., in __del__ methods).
126
127
Issued when exceptions occur that cannot be properly raised:
128
- Exceptions in __del__ methods
129
- Exceptions in cleanup code
130
- Exceptions in background threads
131
"""
132
133
class PytestUnhandledThreadExceptionWarning(PytestWarning):
134
"""
135
Unhandled exceptions in threads.
136
137
Issued when exceptions occur in threads that are not properly handled:
138
- Background thread exceptions
139
- Thread pool exceptions
140
- Daemon thread exceptions
141
"""
142
143
class PytestFDWarning(PytestWarning):
144
"""
145
File descriptor leak warnings.
146
147
Issued by the lsof plugin when file descriptor leaks are detected:
148
- Open files not properly closed
149
- Network connections left open
150
- Resource leaks between tests
151
"""
152
```
153
154
## Warning Usage Examples
155
156
### Filtering Warnings
157
158
```python
159
import pytest
160
import warnings
161
162
# Filter warnings in test code
163
def test_with_warning_filter():
164
with warnings.catch_warnings():
165
warnings.simplefilter("ignore", PytestDeprecationWarning)
166
# Code that would generate deprecation warnings
167
deprecated_function()
168
169
# Using pytest.mark.filterwarnings
170
@pytest.mark.filterwarnings("ignore::pytest.PytestDeprecationWarning")
171
def test_ignore_deprecation():
172
deprecated_function()
173
174
@pytest.mark.filterwarnings("error::pytest.PytestUnknownMarkWarning")
175
def test_treat_unknown_marks_as_errors():
176
pass
177
```
178
179
### Configuration-based Warning Control
180
181
```python
182
# pytest.ini
183
[tool:pytest]
184
filterwarnings =
185
error
186
ignore::pytest.PytestDeprecationWarning
187
ignore::DeprecationWarning:django.*
188
default::pytest.PytestExperimentalApiWarning
189
190
# pyproject.toml
191
[tool.pytest.ini_options]
192
filterwarnings = [
193
"error",
194
"ignore::pytest.PytestDeprecationWarning",
195
"default::pytest.PytestExperimentalApiWarning",
196
]
197
```
198
199
### Custom Warning Handling
200
201
```python
202
import pytest
203
import warnings
204
205
def test_custom_warning_handling(recwarn):
206
# Trigger some pytest warnings
207
warnings.warn("Test warning", PytestConfigWarning)
208
warnings.warn("Another warning", PytestCollectionWarning)
209
210
# Check that warnings were issued
211
assert len(recwarn) == 2
212
assert recwarn[0].category == PytestConfigWarning
213
assert recwarn[1].category == PytestCollectionWarning
214
215
# Check warning messages
216
assert "Test warning" in str(recwarn[0].message)
217
assert "Another warning" in str(recwarn[1].message)
218
219
def test_specific_warning_check():
220
with pytest.warns(PytestDeprecationWarning, match="deprecated"):
221
warnings.warn("This feature is deprecated", PytestDeprecationWarning)
222
```
223
224
## Common Warning Scenarios
225
226
### Unknown Marks
227
228
```python
229
# This will generate PytestUnknownMarkWarning
230
@pytest.mark.unknownmark # Typo or unregistered mark
231
def test_with_unknown_mark():
232
pass
233
234
# Fix by registering the mark
235
# pytest.ini
236
[tool:pytest]
237
markers =
238
unknownmark: description of the mark
239
```
240
241
### Return Values in Tests
242
243
```python
244
# This will generate PytestReturnNotNoneWarning
245
def test_returning_value():
246
return "Should not return anything" # Warning issued
247
248
# Fix by not returning values
249
def test_fixed():
250
result = calculate_something()
251
assert result == expected # Don't return the result
252
```
253
254
### Deprecated Features
255
256
```python
257
# Using deprecated pytest features
258
def test_with_deprecated_feature():
259
# This might generate PytestDeprecationWarning or PytestRemovedIn9Warning
260
pytest.deprecated_function() # Replace with newer API
261
262
# Check for specific deprecation warnings
263
def test_handle_deprecation():
264
with pytest.warns(PytestRemovedIn9Warning):
265
use_deprecated_feature()
266
```
267
268
### Configuration Issues
269
270
```python
271
# pytest.ini with conflicting options might generate PytestConfigWarning
272
[tool:pytest]
273
addopts = --strict-markers
274
markers =
275
# Missing marker definitions can cause warnings
276
277
# Fix by properly defining all markers
278
markers =
279
slow: marks tests as slow
280
integration: marks tests as integration tests
281
```
282
283
## Warning Hierarchy
284
285
The complete warning hierarchy:
286
287
```
288
UserWarning
289
├── PytestWarning (base for all pytest warnings)
290
├── PytestAssertRewriteWarning
291
├── PytestCacheWarning
292
├── PytestCollectionWarning
293
├── PytestConfigWarning
294
├── PytestUnknownMarkWarning
295
├── PytestReturnNotNoneWarning
296
├── PytestUnraisableExceptionWarning
297
├── PytestUnhandledThreadExceptionWarning
298
├── PytestFDWarning
299
├── PytestDeprecationWarning (also extends DeprecationWarning)
300
│ └── PytestRemovedIn9Warning
301
└── PytestExperimentalApiWarning (also extends FutureWarning)
302
```
303
304
## Best Practices
305
306
### Handling Warnings in Tests
307
308
```python
309
# Don't ignore all warnings - be specific
310
@pytest.mark.filterwarnings("ignore::DeprecationWarning:specific_module.*")
311
312
# Test that warnings are properly issued
313
def test_warning_issued():
314
with pytest.warns(PytestDeprecationWarning):
315
deprecated_api()
316
317
# Handle warnings in fixtures
318
@pytest.fixture
319
def ignore_known_warnings():
320
with warnings.catch_warnings():
321
warnings.simplefilter("ignore", PytestConfigWarning)
322
yield
323
```
324
325
### Warning Documentation
326
327
```python
328
def deprecated_function():
329
"""
330
This function is deprecated.
331
332
.. deprecated:: 8.0
333
Use new_function() instead. Will be removed in pytest 9.0.
334
"""
335
warnings.warn(
336
"deprecated_function is deprecated, use new_function instead",
337
PytestRemovedIn9Warning,
338
stacklevel=2
339
)
340
```