Skip to content

Instantly share code, notes, and snippets.

@deepbrook
Last active December 18, 2017 09:28
Show Gist options
  • Select an option

  • Save deepbrook/8eb16eea55913c7020340d8a96e0518e to your computer and use it in GitHub Desktop.

Select an option

Save deepbrook/8eb16eea55913c7020340d8a96e0518e to your computer and use it in GitHub Desktop.
Properly asserting if a warning was emitted in unittests
# Courtesy of https://stackoverflow.com/a/3892413/5413116
import unittest, warnings
from mock import patch
class MyCustomWarning(warnings.Warning):
pass
def emit_warning():
warnings.warn("My custome warning message", MyCustomWarning)
class Foo(unittest.TestCase):
@patch.object(warnings, 'warn')
def test_is_zero_raises_warning(self, mock_warn):
with mock._patch_object()
emit_warning()
mock_warn.assert_called_with("My custom warning message", MyCustomWarning)
if __name__ == '__main__':
unittest.main()
@deepbrook
Copy link
Author

deepbrook commented Dec 17, 2017

This is better than the above SO question's accepted answer as catch_warnings() modifies the warnings module global state and is NOT thread-safe.
Since unittests executes tests concurrently, this may lead to false negatives or false positives.
If you need to assert that a specific Warning was emitted, using mock_warn.assert_called_with( MyWarning) should do the trick.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment