#!/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()
在 不幸的是,这似乎是不可能的。“Exception ignored in:”消息是由
Python/errors.c
中的CPython函数PyErr_WriteUnraisable
生成的。该函数前面的注释说明:垃圾回收过程中确实生成了
ResourceWarning
,Python会打印一条消息,因为它无法在此时引发异常。这与核心CPython实现有关,unittest无法覆盖它。在更新:虽然以上是正确的技术分析,但还有另一种方法可以实际解决OP的问题。更多细节请参见J.F.Sebastian的answer。在
如果
ResourceWarning
是由with catch_warning()
语句中的代码生成的,则该单元测试将失败:相关问题 更多 >
编程相关推荐