我找到了罪魁祸首。您说您在导入期间设置了过滤器。但是,自Python
3.2起,unittest模块已更新为将警告过滤器设置为默认值。参见第29.5.5节。基本上,
unittest在完成模块导入后,将覆盖警告过滤器首选项。
例如。
my_tests.py
import socketimport unittestimport warningswarnings.simplefilter("ignore", ResourceWarning)def abusesocket(): s = socket.socket() s.connect(("www.google.com", 80))class Test(unittest.TestCase): def test1(self): print("test1") abusesocket() print("module import warning filter nixed") def test2(self): print("test2") warnings.simplefilter("ignore", ResourceWarning) abusesocket() print("higher warning filter okay")
提供以下输出
解$ python3 -m unittest my_tests.py test1/home/user/my_tests.py:15: ResourceWarning: unclosed <socket.socket fd=3, family=AddressFamily.AF_INET, type=SocketType.SOCK_STREAM, proto=0, laddr=('x.x.x.x', 52332), raddr=('31.55.166.217', 80)> abusesocket()module import warning filter nixed.test2higher warning filter okay.----------------------------------------------------------------------Ran 2 tests in 0.347sOK
unittest似乎在每次测试后重置警告过滤器。因此,您将在每次测试开始时清除过滤器。最好使用装饰器包装测试功能。
def ignore_warnings(test_func): def do_test(self, *args, **kwargs): with warnings.catch_warnings(): warnings.simplefilter("ignore", ResourceWarning) test_func(self, *args, **kwargs) return do_testclass Test(unittest.TestCase): @ignore_warnings def test1(self): abusesocket()
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)