Raise an exception if RuntimeWarning found during pytest execution - python

I want to raise an error if RuntimeWarning's occurred during pytest call. The problem is, the solutions below are doing nothing - each time I call pytest, RuntimeWarnings are still warnings:
import warnings
warnings.filterwarnings("error", category=RuntimeWarning)
# setup.cfg
filterwarnings =
error::RuntimeWarning
default
pytest -W error::RuntimeWarning
Meanwhile, ignore::RuntimeWarning (and error::DeprecationWorning)works as expected. What's wrong with my code?
Warning example below:
/app/src/pbp_data_platfrom/tests/test_service.py:20: RuntimeWarning: coroutine 'AsyncMock.__call__' was never awaited
assert send_events_mock.called_count == 1
Enable tracemalloc to get traceback where the object was allocated.
See https://docs.pytest.org/en/stable/how-to/capture-warnings.html#resource-warnings for more info.
-- Docs: https://docs.pytest.org/en/stable/how-to/capture-warnings.html
P.S. I know I can add the error option into filterwarning so it will raise an error each time any warning found (and it will work, I've tested it a couple of times). But this solution looks a bit clunky.

Related

Breakpoint when encountering RunTimeWarning

I am having trouble getting the following code to work in Python:
for t in range(-5,5):
try:
a = np.log(t)
except RunTimeWarning:
breakpoint()
What I want is to execute the breakpoint statement, when the log function is evaluated from -5 to 0.
When using np.log(0), numpy won't throw an exception but a warning. These are significantly different from exceptions as an exception will stop the current code from running, whereas a warning just notifies you but keeps the code running.
Take this example:
>>> x = np.log(0)
Warning (from warnings module):
File "<pyshell#1>", line 1
RuntimeWarning: divide by zero encountered in log
>>> x
-inf
As you can see the variable x does get a value assigned -> the warning never kept log(...) from running and returning a value.
So to solve your problem, you'd have to check if the value passed to your code is 0 before calling np.log. Or if you don't want -inf to be a valid return value but still need to call np.log for some reason, you can check if the value is -inf after the call. However it's best practise not to write code that causes warnings so you should probably just check if it's 0 before calling log.
You can read more about warnings in the python docs.

Python: why is warning printed twice following temporary suppression?

It seems that temporarily suppressing warnings makes repeat warnings outside of the context manager display repeatedly.
Example:
import warnings
def f():
with warnings.catch_warnings():
warnings.simplefilter("ignore", category=Warning)
print("A")
print("B")
warnings.warn("My warning")
f()
f()
Output:
A
B
tmp2.py:10: UserWarning: My warning
warnings.warn("My warning")
A
B
tmp2.py:10: UserWarning: My warning
warnings.warn("My warning")
Also, it does not seem to matter what action and category I give to simplefilter.
On the other hand, if I comment out the context catch_warnings block,
then the warning only displays once (as intended).
Why? Is it a bug? What am I missing?
This is a known bug
also asked about here
with a PR that seems pretty stale

Python still throwing exception I've explicitly excepted

I've got some code that I know will fail in the edge case where the list is empty so I added exception handling for IndexError.
But, despite handling the exception, it's still getting raised.
~/Code/foo.py in decode_tokens(tokens)
196 new_toks.append(new_tok)
197 else:
--> 198 try: new_toks[-1] += new_tok
199 except IndexError: pass
200 new_elem = True
IndexError: list index out of range
I don't understand how if I'm explicitly excepting IndexError why it's still getting raised and aborting script execution.
Edit: adding that this is Python 3.6 running in a Jupyter notebook. As it looked like a python error I didn't think that was relevant (but it sounds like it might be.)
Editors that support IPython, which include Jupyter, do not always reload modules even after they have been edited. I think this might be an unfortunate coincidence; the line that the error is thrown happens to coincide with the line of your exception handler after an edit. Likely the code that threw the error isn't what's at that line now. You may wish to force a reload of imported modules each time you run a script, or at least restart the underlying IPython kernel for now.

Why does the default pylintrc have so many disabled messages?

If you run pylint --generate-rcfile > pylintrc and look at the default rc file you'll see the following list of disabled warnings.
Why are they disabled by default?
disable=print-statement,
parameter-unpacking,
unpacking-in-except,
old-raise-syntax,
backtick,
long-suffix,
old-ne-operator,
old-octal-literal,
import-star-module-level,
non-ascii-bytes-literal,
raw-checker-failed,
bad-inline-option,
locally-disabled,
locally-enabled,
file-ignored,
suppressed-message,
useless-suppression,
deprecated-pragma,
apply-builtin,
basestring-builtin,
buffer-builtin,
cmp-builtin,
coerce-builtin,
execfile-builtin,
file-builtin,
long-builtin,
raw_input-builtin,
reduce-builtin,
standarderror-builtin,
unicode-builtin,
xrange-builtin,
coerce-method,
delslice-method,
getslice-method,
setslice-method,
no-absolute-import,
old-division,
dict-iter-method,
dict-view-method,
next-method-called,
metaclass-assignment,
indexing-exception,
raising-string,
reload-builtin,
oct-method,
hex-method,
nonzero-method,
cmp-method,
input-builtin,
round-builtin,
intern-builtin,
unichr-builtin,
map-builtin-not-iterating,
zip-builtin-not-iterating,
range-builtin-not-iterating,
filter-builtin-not-iterating,
using-cmp-argument,
eq-without-hash,
div-method,
idiv-method,
rdiv-method,
exception-message-attribute,
invalid-str-codec,
sys-max-int,
bad-python3-import,
deprecated-string-function,
deprecated-str-translate-call,
deprecated-itertools-function,
deprecated-types-field,
next-method-defined,
dict-items-not-iterating,
dict-keys-not-iterating,
dict-values-not-iterating
From the documentation's Frequently Asked Questions...
Why are there a bunch of messages disabled by default?
pylint does have some messages disabled by default, either because
they are prone to false positives or that they are opinionated enough
for not being included as default messages. But most of the disabled
messages are from the Python 3 porting checker, which is disabled by
default. It needs special activation with the --py3k flag.
I think that such default rc file is designed to apply pylint to python2 code without tons of errors and warnings. Note: most of the disabled statements belongs to python2 syntax and standard library api:
print-statement - print was a statement in Python2, in Python3 it is a function
old-raise-syntax - there was except Exception, e syntax that is invalid for Python3, in Python3 except Exception as e is only valid
xrange-builtin - xrange was replaced with range
etc.
So, with this default rc you can use pylint for python2 code to find out such things as redefined-outer-name, line-too-long and other bad things without getting annoying errors and warnings for valid Python2 syntax and standard library calls.

Stop cssutils from generating warning messages

I am using the parseFile convenience method to read a css file but it is generating a huge amount of warning messages.
I have set validate=False but it is still printing the messages. I have tried to create a CSSParser object and initialising the log object and logging level to none but it is still printing warnings and errors. I looked in the source code and couldn't see where these message are being created so it might be in something that parseFile calls.
Is there any way of stopping the CSSParser.parseFile() from generating message like the ones below?
WARNING CSSStylesheet: Unknown #rule found. [3:43150:#-webkit-keyframes]
WARNING CSSStylesheet: Unknown #rule found. [3:43329: #-moz-keyframes]
WARNING CSSStylesheet: Unknown #rule found. [3:43496: #keyframes]
WARNING CSSStylesheet: Unknown #rule found. [3:43643: #-webkit-keyframes]
WARNING Property: Unknown Property name. [3:79871: min-device-width]
WARNING Property: Unknown Property name. [3:79900: max-device-width]
ERROR MediaQuery: Unexpected syntax, expected "and" but found "(". [3:86572: (]
ERROR MediaQuery: Unexpected syntax, expected "and" but found ":". [3:86582: :]
ERROR MediaQuery: Unexpected syntax. [3:86583: 35em]
ERROR MediaQuery: Unexpected syntax, expected "and" but found ")". [3:86587: )]
Any help would be greatly appreciated!
The logger is a singleton, so, put this line above your instruction
import logging
cssutils.log.setLevel(logging.CRITICAL)
This disables the warning and error logging.

Categories