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
80%Fix Rate
88%Confidence
0Evidence
2024-04-25First Seen
Version Compatibility
| Version | Status | Introduced | Deprecated | Notes |
|---|---|---|---|---|
| 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
-
94% success
def tearDown(self): conn = getattr(self, 'conn', None) if conn is not None: conn.close() super().tearDown() -
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:
-
70% fail
Silences the error but leaks resources (open sockets, temp files) and hides genuine teardown bugs, causing cascading failures in later tests.
-
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.