将Python3资源警告转换为异常

2024-04-24 23:31:49 发布

您现在位置:Python中文网/ 问答频道 /正文

有没有一种方法可以强制python3unittest失败,而不是简单地向stderr打印一个警告,如果它导致了任何ResourceWarning?在

我试过以下方法:

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

这导致了unittest的输出:

^{pr2}$

请注意“忽略异常”消息。我宁愿测试失败,而不是要求我读取它的输出以查找ResourceWarnings。在


Tags: 方法import消息警告stderractionerrorunittest
2条回答

在 不幸的是,这似乎是不可能的。“Exception ignored in:”消息是由Python/errors.c中的CPython函数PyErr_WriteUnraisable生成的。该函数前面的注释说明:

/* Call when an exception has occurred but there is no way for Python
   to handle it.  Examples: exception in __del__ or during GC. */

垃圾回收过程中确实生成了ResourceWarning,Python会打印一条消息,因为它无法在此时引发异常。这与核心CPython实现有关,unittest无法覆盖它。在

更新:虽然以上是正确的技术分析,但还有另一种方法可以实际解决OP的问题。更多细节请参见J.F.Sebastian的answer。在

如果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()

相关问题 更多 >