python runtime_error ai_generated true

ERROR: test_foo (tests.test_x.TestCase.test_foo) ---------------------------------------------------------------------- Traceback (most recent call last): File "...", line N, in tearDown self.conn.close() AttributeError: 'NoneType' object has no attribute 'close'

ID: python/unittest-teardown-exception-masked

Also available as: JSON · Markdown · 中文
80%Fix Rate
88%Confidence
0Evidence
2024-11-14First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
3.10 active
3.11 active
3.12 active

Root Cause

tearDown runs even when setUp failed, so resources are None; the teardown exception replaces the original test error, obscuring the real failure.

generic

中文

即使 setUp 失败,tearDown 也会运行,因此资源为 None;teardown 异常替换了原始测试错误,掩盖了真正的失败。

Workarounds

  1. 95% success
    def setUp(self):
        self.conn = create_conn()
        self.addCleanup(self.conn.close)
    
    # If create_conn raises, addCleanup is never registered, so tearDown does nothing
  2. 85% success
    def tearDown(self):
        conn = getattr(self, 'conn', None)
        if conn is not None:
            conn.close()

Dead Ends

Common approaches that don't work:

  1. 90% fail

    Silences real teardown errors and leaks resources, causing cascading failures in later tests.

  2. 85% fail

    Resources (DB connections, temp files) leak between tests, causing flakiness and cross-test pollution.

  3. 60% fail

    Symptom-level fix; the underlying setUp failure still hides behind the teardown error path.