Make sure the function triggers a nose check warning

I am writing unit tests using nose , and I would like to check if the function raises a warning (the function uses warnings.warn ). Is it easy to do?

+7
python unit-testing warnings nose
source share
2 answers
 def your_code(): # ... warnings.warn("deprecated", DeprecationWarning) # ... def your_test(): with warnings.catch_warnings(record=True) as w: your_code() assert len(w) > 1 

Instead of just checking the length, you can check it in depth, of course:

assert str(w.args[0]) == "deprecated"

In python 2.7 or later, you can do this with a final check like:

assert str(w[0].message[0]) == "deprecated"

+9
source share

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() # per-PEP8 check for empty sequences by their Truthiness self.assertTrue(wrn) 
+1
source share

All Articles