禁用Python 3.2 ResourceWarning

Mik*_*maa 26 python python-3.x

Python 3.2 ResourceWarning为未封闭的系统资源(网络套接字,文件)引入:

尽管代码在生产中运行干净,但由于使用了发生警告的第三方库,因此在运行单元测试时会收到很多关注警告.我可以修复库,但另一方面,在测试运行期间忽略它会简单得多.

 block_io-python/block_io/__init__.py:182: ResourceWarning: unclosed <ssl.SSLSocket fd=11, family=AddressFamily.AF_INET, type=SocketType.SOCK_STREAM, proto=6, laddr=('x', 58395), raddr=('x, 443)>
Run Code Online (Sandbox Code Playgroud)

禁用这些警告的方法是什么?我尝试了以下但没有效果:

 warnings.filterwarnings("ignore", category=ResourceWarning)
Run Code Online (Sandbox Code Playgroud)

(在单元测试导入时间内运行).

Dun*_*nes 29

我找到了罪魁祸首.您说您在导入时设置过滤器.但是,自Python 3.2以来,unittest模块已更新为将警告过滤器设置为默认值.见第29.5.5节.基本上,unittest在完成模块导入后,会覆盖警告过滤器首选项.

例如.

my_tests.py

import socket
import unittest
import warnings

warnings.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")
Run Code Online (Sandbox Code Playgroud)

给出以下输出

$ 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
.test2
higher warning filter okay
.
----------------------------------------------------------------------
Ran 2 tests in 0.347s

OK
Run Code Online (Sandbox Code Playgroud)

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_test

class Test(unittest.TestCase):

    @ignore_warnings
    def test1(self):
        abusesocket()
Run Code Online (Sandbox Code Playgroud)

  • 你也可以把它放在`def setUp(self):`中,让它持续整个测试用例. (7认同)

dee*_*ent 20

unittest.main(警告= '忽略')

  • 该代码在我们的单元测试课中去哪儿了? (2认同)

vlz*_*vlz 8

ResourceWarning我用它来仅在测试前禁用警告并在测试后重新启用它。


import unittest
import warnings

class MyTestCase(unittest.TestCase):

    def setUp(self):
        warnings.simplefilter("ignore", ResourceWarning)

    def tearDown(self):
        warnings.simplefilter("default", ResourceWarning)

Run Code Online (Sandbox Code Playgroud)

另请参阅:“默认”和“忽略”之外的不同选项


小智 5

这种选择对我有用:

    def setUp(self):
        if not sys.warnoptions:
            import warnings
            warnings.simplefilter("ignore")
Run Code Online (Sandbox Code Playgroud)

请参阅:标准库文档-覆盖默认过滤器