python
runtime_error
ai_generated
true
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
80%Fix Rate
88%Confidence
0Evidence
2024-04-27First Seen
Version Compatibility
| Version | Status | Introduced | Deprecated | Notes |
|---|---|---|---|---|
| 3.8 | active | — | — | — |
Root Cause
setUpClass failed earlier (e.g., DB connection refused), so cls.conn was never assigned. unittest still runs tearDownClass, which then dereferences None.
generic中文
setUpClass 之前失败了(例如数据库连接被拒绝),因此 cls.conn 从未被赋值。unittest 仍会运行 tearDownClass,然后解引用 None。
Workarounds
-
95% success
@classmethod def tearDownClass(cls): if getattr(cls, 'conn', None) is not None: cls.conn.close() cls.conn = None -
93% success
@classmethod def setUpClass(cls): cls.conn = connect() cls.addClassCleanup(cls.conn.close)
Dead Ends
Common approaches that don't work:
-
75% fail
Silences the teardown error but leaves real resources (sockets, files) leaked when setUpClass partially succeeded.
-
70% fail
Reconnects per test, dramatically slowing the suite; also does not fix the case where setUpClass itself fails.