There are (at least) two ways to do this. You can catch the warning in the list of warnings.WarningMessage in the test, or use the mock - patch imported warnings in your module.
I think the patch version is more general.
raise_warning.py:
import warnings def should_warn(): warnings.warn('message', RuntimeWarning) print('didn\'t I warn you?')
raise_warning_tests.py:
import unittest from mock import patch import raise_warning class TestWarnings(unittest.TestCase): @patch('raise_warning.warnings.warn') def test_patched(self, mock_warnings): """test with patched warnings""" raise_warning.should_warn() self.assertTrue(mock_warnings.called) def test_that_catches_warning(self): """test by catching warning""" with raise_warning.warnings.catch_warnings(True) as wrn: raise_warning.should_warn()
Laurence billingham
source share