python runtime_error ai_generated true

ERROR: tearDown (tests.test_foo.TestFoo) ... 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-masks-test

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

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
3.11 active — — —
3.12 active — — —

Root Cause

tearDown references an attribute that setUp failed to assign (e.g., because setUp raised or was skipped), so the cleanup runs against an uninitialized value.

generic

中文

tearDown 引用了 setUp 未能赋值的属性(例如 setUp 抛出异常或被跳过),导致清理逻辑作用于未初始化的值。

Workarounds

  1. 94% success
    def tearDown(self):
        conn = getattr(self, 'conn', None)
        if conn is not None:
            conn.close()
        super().tearDown()
  2. 96% success
    def setUp(self):
        self.conn = connect()
        self.addCleanup(self.conn.close)
    
    # addCleanup runs only if the resource was created

Dead Ends

Common approaches that don't work:

  1. 70% fail

    Silences the error but leaks resources (open sockets, temp files) and hides genuine teardown bugs, causing cascading failures in later tests.

  2. 80% fail

    addCleanup still calls the same code path; if the attribute is None the same AttributeError is raised, now reported as a cleanup error.