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

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

generic

解决方案

  1. 95% 成功率
    Assign on the class explicitly:
    @classmethod
    def setUpClass(cls):
        cls.client = TestClient(app)
        cls._server = start_server()
  2. 88% 成功率
    Or use a class-scoped pytest fixture instead:
    @pytest.fixture(scope='class')
    def client():
        return TestClient(app)

无效尝试

常见但无效的做法:

  1. 80% 失败

    The attribute exists but is None; calling `.get` raises AttributeError on NoneType.

  2. 50% 失败

    Works but recreates the client for every test, defeating the purpose of setUpClass and slowing the suite.