python
runtime_error
ai_generated
true
ERROR: tearDown (tests.test_db.TestDB.test_insert) Traceback (most recent call last): File "test_db.py", 第 42 行, 在 tearDown 中 self.conn.close() AttributeError: 'NoneType' 对象没有属性 'close'
ERROR: tearDown (tests.test_db.TestDB.test_insert) Traceback (most recent call last): File "test_db.py", line 42, in tearDown self.conn.close() AttributeError: 'NoneType' object has no attribute 'close'
ID: python/unittest-teardown-exception-masks-failure
80%修复率
88%置信度
0证据数
2024-11-30首次发现
版本兼容性
| 版本 | 状态 | 引入 | 弃用 | 备注 |
|---|---|---|---|---|
| 3.9 | active | — | — | — |
| 3.12 | active | — | — | — |
根因分析
setUp 失败或被跳过,导致 self.conn 未设置,但 tearDown 仍执行并抛出异常。teardown 错误掩盖了原始的 setup 失败。
English
setUp failed or was skipped, leaving self.conn unset, but tearDown still runs and raises. The teardown error masks the original setup failure.
解决方案
-
92% 成功率
Guard teardown with hasattr/getattr: def tearDown(self): conn = getattr(self, 'conn', None) if conn is not None: conn.close() -
95% 成功率
Use addCleanup in setUp so cleanup only runs for successfully created resources: def setUp(self): self.conn = create_conn() self.addCleanup(self.conn.close)
无效尝试
常见但无效的做法:
-
85% 失败
Silences real teardown errors and leaks resources, hiding the root cause of future failures.
-
80% 失败
Leaves DB connections and temp files open across tests, causing flaky failures later.