python runtime_error ai_generated true

ResourceWarning: 未关闭的文件 <_io.TextIOWrapper name='/tmp/test.log' mode='w' encoding='UTF-8'>

ResourceWarning: unclosed file <_io.TextIOWrapper name='/tmp/test.log' mode='w' encoding='UTF-8'>

ID: python/unittest-teardown-not-called-on-skip

其他格式: JSON · Markdown 中文 · English
80%修复率
83%置信度
0证据数
2024-07-30首次发现

版本兼容性

版本状态引入弃用备注
3.8 active — — —
3.12 active — — —

根因分析

测试在 setUp 中打开资源后调用 self.skipTest(),导致 tearDown 从未运行、资源泄漏;或 setUpClass 抛出异常后 tearDownClass 被跳过。

English

A test calls self.skipTest() inside setUp after opening a resource, so tearDown never runs and the resource leaks; or setUpClass raised and tearDownClass is skipped.

generic

解决方案

  1. 95% 成功率
    class TestX(unittest.TestCase):
        def setUp(self):
            self.f = open('/tmp/test.log', 'w')
            self.addCleanup(self.f.close)
            if not condition:
                self.skipTest('condition not met')
  2. 92% 成功率
    def test_x(self):
        with open('/tmp/test.log', 'w') as f:
            ...
        # file closed even if test fails

无效尝试

常见但无效的做法:

  1. 80% 失败

    Hides the leak; file descriptors accumulate across a large test suite and eventually cause EMFILE.

  2. 60% 失败

    Skips before any setup runs, but other tests that do open resources still leak.