栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

禁用Python 3.2 ResourceWarning

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

禁用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()


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/660725.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号