Errors
Warnings
Capture warnings in tests when the returned value still matters but the migration notice must be asserted.
Source
import warnings
def old_name():
warnings.warn("old_name is deprecated", DeprecationWarning, stacklevel=2)
return "result"
with warnings.catch_warnings(record=True) as caught:
warnings.simplefilter("always", DeprecationWarning)
print(old_name())
print(caught[0].category.__name__)
print(str(caught[0].message))Output
result
DeprecationWarning
old_name is deprecatedA filter can promote selected warnings to exceptions, which is useful in CI when deprecated calls should fail the build.
Source
with warnings.catch_warnings():
warnings.simplefilter("error", DeprecationWarning)
try:
old_name()
except DeprecationWarning:
print("warning became error")Output
warning became errorNotes
- Use warnings for soft problems callers can act on later.
- Use exceptions when the current operation cannot continue.
stacklevelshould point the warning at the caller rather than inside the helper.
See also
- related: Exceptions
- next depth: Logging
- next depth: Testing
Run the complete example
Expected output
result
DeprecationWarning
old_name is deprecated
warning became error
Execution time appears here after you run the example.