python
runtime_error
ai_generated
true
AttributeError: 'TestUser' 对象没有属性 'db'
AttributeError: 'TestUser' object has no attribute 'db'
ID: python/unittest-teardown-attribute-error
80%修复率
87%置信度
0证据数
2024-07-09首次发现
版本兼容性
| 版本 | 状态 | 引入 | 弃用 | 备注 |
|---|---|---|---|---|
| 3.9 | active | — | — | — |
| 3.10 | active | — | — | — |
| 3.11 | active | — | — | — |
| 3.12 | active | — | — | — |
根因分析
setUpClass 或 setUp 静默失败(或拼写错误),导致 setUp 中赋值的属性从未创建,但 tearDown 仍引用它。
English
setUpClass or setUp failed silently (or was misspelled) so the attribute assigned in setUp is never created, but tearDown still references it.
解决方案
-
85% 成功率
class TestUser(unittest.TestCase): def setUp(self): self.db = connect() def tearDown(self): if hasattr(self, 'db'): self.db.close() -
95% 成功率
def setUp(self): self.db = connect() self.addCleanup(self.db.close)
无效尝试
常见但无效的做法:
-
80% 失败
Hides the real setup failure; subsequent tests may run against a half-initialized state.
-
70% 失败
If setUp is the failing method, referencing the attribute earlier just moves the error.