python
runtime_error
ai_generated
true
ResourceWarning: unclosed file <_io.TextIOWrapper name='/tmp/test.log' mode='w' encoding='UTF-8'>
ID: python/unittest-teardown-not-called-on-skip
80%Fix Rate
83%Confidence
0Evidence
2024-07-30First Seen
Version Compatibility
| Version | Status | Introduced | Deprecated | Notes |
|---|---|---|---|---|
| 3.8 | active | — | — | — |
| 3.12 | active | — | — | — |
Root Cause
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中文
测试在 setUp 中打开资源后调用 self.skipTest(),导致 tearDown 从未运行、资源泄漏;或 setUpClass 抛出异常后 tearDownClass 被跳过。
Workarounds
-
95% success
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') -
92% success
def test_x(self): with open('/tmp/test.log', 'w') as f: ... # file closed even if test fails
Dead Ends
Common approaches that don't work:
-
80% fail
Hides the leak; file descriptors accumulate across a large test suite and eventually cause EMFILE.
-
60% fail
Skips before any setup runs, but other tests that do open resources still leak.