python
runtime_error
ai_generated
true
AttributeError: 类型对象 'TestDb' 没有属性 'client' File "tests/test_db.py", line 22, in test_query resp = self.client.get('/health')
AttributeError: type object 'TestDb' has no attribute 'client' File "tests/test_db.py", line 22, in test_query resp = self.client.get('/health')
ID: python/unittest-setupclass-attribute-error
80%修复率
88%置信度
0证据数
2024-04-25首次发现
版本兼容性
| 版本 | 状态 | 引入 | 弃用 | 备注 |
|---|---|---|---|---|
| 3.10 | active | — | — | — |
| 3.12 | active | — | — | — |
根因分析
`setUpClass` 是类方法;在其中赋值 `self.client` 设置的是类对象上的实例属性,而非测试实例上的属性,因此测试实例上的 `self.client` 不存在。
English
`setUpClass` is a classmethod; assigning `self.client` inside it sets an instance attribute on the class object, not on instances, so `self.client` on a test instance is missing.
解决方案
-
95% 成功率
Assign on the class explicitly: @classmethod def setUpClass(cls): cls.client = TestClient(app) cls._server = start_server() -
88% 成功率
Or use a class-scoped pytest fixture instead: @pytest.fixture(scope='class') def client(): return TestClient(app)
无效尝试
常见但无效的做法:
-
80% 失败
The attribute exists but is None; calling `.get` raises AttributeError on NoneType.
-
50% 失败
Works but recreates the client for every test, defeating the purpose of setUpClass and slowing the suite.