python runtime_error ai_generated true

ERROR: tearDownClass (tests.test_db.TestDB) ---------------------------------------------------------------------- Traceback (最近调用最后): 文件 "tests/test_db.py",第 30 行,在 tearDownClass 中 cls.conn.close() AttributeError: 'NoneType' 对象没有属性 'close'

ERROR: tearDownClass (tests.test_db.TestDB) ---------------------------------------------------------------------- Traceback (most recent call last): File "tests/test_db.py", line 30, in tearDownClass cls.conn.close() AttributeError: 'NoneType' object has no attribute 'close'

ID: python/unittest-teardown-order-failure

其他格式: JSON · Markdown 中文 · English
80%修复率
88%置信度
0证据数
2024-04-27首次发现

版本兼容性

版本状态引入弃用备注
3.8 active

根因分析

setUpClass 之前失败了(例如数据库连接被拒绝),因此 cls.conn 从未被赋值。unittest 仍会运行 tearDownClass,然后解引用 None。

English

setUpClass failed earlier (e.g., DB connection refused), so cls.conn was never assigned. unittest still runs tearDownClass, which then dereferences None.

generic

解决方案

  1. 95% 成功率
    @classmethod
    def tearDownClass(cls):
        if getattr(cls, 'conn', None) is not None:
            cls.conn.close()
            cls.conn = None
  2. 93% 成功率
    @classmethod
    def setUpClass(cls):
        cls.conn = connect()
        cls.addClassCleanup(cls.conn.close)

无效尝试

常见但无效的做法:

  1. 75% 失败

    Silences the teardown error but leaves real resources (sockets, files) leaked when setUpClass partially succeeded.

  2. 70% 失败

    Reconnects per test, dramatically slowing the suite; also does not fix the case where setUpClass itself fails.