禁用Python 3.2 ResourceWarning

禁用Python 3.2 ResourceWarning,第1张

禁用Python 3.2 ResourceWarning

我找到了罪魁祸首。您说您在导入期间设置了过滤器。但是,自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()


欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/zaji/5666841.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-17
下一篇 2022-12-16

发表评论

登录后才能评论

评论列表(0条)

保存