python runtime_error ai_generated true

AttributeError: 'TestUser' 对象没有属性 'db'

AttributeError: 'TestUser' object has no attribute 'db'

ID: python/unittest-teardown-attribute-error

其他格式: JSON · Markdown 中文 · English
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.

generic

解决方案

  1. 85% 成功率
    class TestUser(unittest.TestCase):
        def setUp(self):
            self.db = connect()
    
        def tearDown(self):
            if hasattr(self, 'db'):
                self.db.close()
  2. 95% 成功率
    def setUp(self):
        self.db = connect()
        self.addCleanup(self.db.close)

无效尝试

常见但无效的做法:

  1. 80% 失败

    Hides the real setup failure; subsequent tests may run against a half-initialized state.

  2. 70% 失败

    If setUp is the failing method, referencing the attribute earlier just moves the error.