gpt4 book ai didi

python - 将 Python 3 ResourceWarnings 转换为异常

转载 作者:太空狗 更新时间:2023-10-29 21:34:27 24 4
gpt4 key购买 nike

有没有办法强制 Python 3 单元测试失败,而不是简单地向 stderr 打印警告,如果它导致任何 ResourceWarning?

我试过以下方法:

import warnings
warnings.simplefilter(action='error', category=ResourceWarning)

这导致单元测试的输出:

my_test (__main__.MyTest) ... Exception ignored in: <socket.socket fd=9, family=AddressFamily.AF_INET, type=SocketType.SOCK_STREAM, proto=0, laddr=('127.0.0.1', 54065), raddr=('127.0.0.1', 27017)>
ResourceWarning: unclosed <socket.socket fd=9, family=AddressFamily.AF_INET, type=SocketType.SOCK_STREAM, proto=0, laddr=('127.0.0.1', 54065), raddr=('127.0.0.1', 27017)>
ok

----------------------------------------------------------------------
Ran 1 test in 0.110s

注意“忽略异常”消息。我宁愿测试失败,也不要要求我阅读其输出以查找 ResourceWarnings。

最佳答案

这是一个单元测试,如果 ResourceWarning 是由 with catch_warning() 语句生成的:

#!/usr/bin/env python3
import gc
import socket
import unittest
import warnings

class Test(unittest.TestCase):
def test_resource_warning(self):
s = socket.socket()
####s.close() #XXX uncomment to pass the test

# generate resource warning when s is deleted
with warnings.catch_warnings(record=True) as w:
warnings.resetwarnings() # clear all filters
warnings.simplefilter('ignore') # ignore all
warnings.simplefilter('always', ResourceWarning) # add filter
del s # remove reference
gc.collect() # run garbage collection (for pypy3)
self.assertFalse(w and str(w[-1])) # test fails if there
# are warnings

if __name__=="__main__":
unittest.main()

关于python - 将 Python 3 ResourceWarnings 转换为异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24717027/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com