Last active
December 18, 2017 09:28
-
-
Save deepbrook/8eb16eea55913c7020340d8a96e0518e to your computer and use it in GitHub Desktop.
Properly asserting if a warning was emitted in unittests
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # 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() | |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This is better than the above SO question's accepted answer as
catch_warnings()modifies thewarningsmodule 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
Warningwas emitted, usingmock_warn.assert_called_with( MyWarning)should do the trick.