For those who use like to add warnings to your Python code, and want to test those warnings actually happen in your unit tests, here are two techniques to do so, both are based around fixtures/funcargs.
Firstly is the mechanism built into py.test using recwarn
.
The second is to create a fixture that specifically enables warnings as exceptions and combined that with pytest.raises
, for instance:
import warnings @pytest.fixture def warnings_as_errors(request): warnings.simplefilter('error') request.addfinalizer(lambda *args: warnings.resetwarnings()) def test_timers_warn(log, warnings_as_errors): log.start_timer('method') with pytest.raises(RuntimeWarning): log.start_timer('method')
The advantage of this second method is you can guarantee exactly what method call raises the warning without repeatedly having to check recwarn
.