warnings.simplefilter('always') does not seem to cause warnings to be repeated in Python 2.7. It seems to have the same effect as 'once'.
I am trying to test some code that issues warnings. Half of the time, the warning I am trying to test has already been issued, so my test uses simplefilter() to ensure that the warning is issued again. This problem only occurs in Python 2.7. The other versions all seem to work as expected.
I have followed the example in the Python 2.7 documentation https://docs.python.org/2/library/warnings.html#testing-warnings
The example works as-is, but if I add a call to fxn() right before the test code, the warning is not raised and len(w) = 0 instead of 1.
Specifically,
import warnings
def fxn():
warnings.warn("deprecated", DeprecationWarning)
fxn()
with warnings.catch_warnings(record=True) as w:
# Cause all warnings to always be triggered.
warnings.simplefilter("always")
# Trigger a warning.
fxn()
# Verify some things
assert len(w) == 1
assert issubclass(w[-1].category, DeprecationWarning)
assert "deprecated" in str(w[-1].message)
Expected result is to run to the end with no output. Actual result in Python 2.7.14 and 2.7.15:
Traceback (most recent call last):
File "warntest.py", line 14, in <module>
assert len(w) == 1
AssertionError
Update:
I also found that calling warnings.resetwarnings() after the first warning is issued does not work.
import warnings
def fxn():
warnings.warn("deprecated", DeprecationWarning)
fxn()
warnings.resetwarnings()
with warnings.catch_warnings(record=True) as w:
# Cause all warnings to always be triggered.
warnings.simplefilter("always")
# Trigger a warning.
fxn()
# Verify some things
assert len(w) == 1
assert issubclass(w[-1].category, DeprecationWarning)
assert "deprecated" in str(w[-1].message)
fxn()
Result:
Traceback (most recent call last):
File "warntest.py", line 15, in <module>
assert len(w) == 1
AssertionError