Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use pytest to assert NO Warning is raised

Tags:

I want to ensure that no warning at all is raised in one assertion.

Could not find any explicit answer in pytest documentation about warnings.

I've tried this, thinking maybe None would mean "nothing":

def test_AttrStr_parse_warnings():     """Check _AttrStr.parse() raises proper warnings in proper cases."""     with pytest.warns(None):         _AttrStr('').parse() 

but this assertion is also always correct, for instance, the test does not fail, even if a warning is actually raised:

def test_AttrStr_parse_warnings():     """Check _AttrStr.parse() raises proper warnings in proper cases."""     with pytest.warns(None):         _AttrStr('').parse()         warnings.warn('any message') 
like image 278
zezollo Avatar asked Aug 14 '17 09:08

zezollo


People also ask

How do I check my pytest warnings?

-r chars show extra test summary info as specified by chars (f)ailed, (E)error, (s)skipped, (x)failed, (X)passed (w)pytest-warnings (a)all. This will allow to show warnings in the report (top portion of the record) will list which pytest plugins use deprecated arguments (in my case bellow):

How do I turn off warnings in Python?

Use the filterwarnings() Function to Suppress Warnings in Python. The warnings module handles warnings in Python. We can show warnings raised by the user with the warn() function. We can use the filterwarnings() function to perform actions on specific warnings.


1 Answers

For pytest >= 7.0

The doc now explicitely mentions this case should be solved this way (without pytest):

with warnings.catch_warnings():     warnings.simplefilter("error")     ... 

though this may not completely solve some cases (dynamic checks: see this post).

The solution suggested for pytest < 7.0, below, now raises a DeprecationWarning. Thanks to @Warren-Weckesser for signaling this in comment!

Possible solution for pytest < 7.0

Yet it was not planned to be used like this, it's possible to "record" any possible warning raised, and use this to add another assertion to ensure the number of raised warnings is 0:

def test_AttrStr_parse_warnings():     """Check parse() raises proper warnings in proper cases."""     with pytest.warns(None) as record:         _AttrStr('').parse()     assert len(record) == 0 

To ensure it works: adding warnings.warn('any message') in the second assertion let the test fail.

like image 111
zezollo Avatar answered Sep 18 '22 22:09

zezollo