Title: unittest overrides more serious warnings filter added before unittest.main()
Type: behavior Stage:
Components: Library (Lib) Versions: Python 3.10, Python 3.9, Python 3.8
Status: open Resolution:
Dependencies: Superseder:
Assigned To: Nosy List: ncoghlan, terry.reedy, xtreak, yilei
Priority: normal Keywords:

Created on 2020-10-28 20:42 by yilei, last changed 2020-10-31 21:14 by vstinner.

Messages (4)
msg379843 - (view) Author: Yilei Yang (yilei) Date: 2020-10-28 20:42
Because unittest adds a `default` filter before tests run, other warnings filters are overridden if added before.

Ideally, unittest should not make the warnings less serious, e.g. if there is already an 'error' filter that raises exception, it shouldn't "downgrade" to 'default' that simply prints.

The following example, using lib.a_function() raises exception in a regular program, but the unit test passes:

$ cat
import warnings
class MyWarning(UserWarning):
warnings.filterwarnings('error', category=MyWarning)
def a_function():
  warnings.warn('Do not use.', MyWarning)

$ cat
import unittest
import lib
class TestLib(unittest.TestCase):
    def test_function(self):
if __name__ == '__main__':

$ python -m unittest -v lib_test
test_function (lib_test.TestLib) ... MyWarning: Do not use.
  warnings.warn('Do not use.', MyWarning)

Ran 1 test in 0.000s


$ python
>>> import lib
>>> lib.a_function()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "", line 6, in a_function
    warnings.warn('Do not use.', MyWarning)
lib.MyWarning: Do not use.
msg379850 - (view) Author: Karthikeyan Singaravelan (xtreak) * (Python committer) Date: 2020-10-29 00:34
Seems to be a duplicate of See also
msg380016 - (view) Author: Terry J. Reedy (terry.reedy) * (Python committer) Date: 2020-10-30 23:59
Nick and/or Victor: should this be closed in favor of #15626? or should the latter be closed as mostly fixed, with this being left open as a followup?
msg380039 - (view) Author: Nick Coghlan (ncoghlan) * (Python committer) Date: 2020-10-31 05:15
Closing the old one as partially fixed, and linking here as a superseder makes sense to me, so I went ahead and did that.
Date User Action Args
2020-10-31 21:14:17vstinnersetnosy: - vstinner
2020-10-31 05:15:34ncoghlansetmessages: + msg380039
2020-10-31 05:07:43ncoghlanlinkissue15626 superseder
2020-10-30 23:59:51terry.reedysetnosy: + vstinner, terry.reedy

messages: + msg380016
versions: - Python 3.6, Python 3.7
2020-10-29 00:34:46xtreaksetnosy: + ncoghlan
messages: + msg379850
2020-10-29 00:25:05xtreaksetnosy: + xtreak
2020-10-28 20:42:28yileicreate