python runtime_error ai_generated true

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

Also available as: JSON · Markdown · 中文
80%Fix Rate
88%Confidence
0Evidence
2024-04-25First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
3.10 active — — —
3.12 active — — —

Root Cause

`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

中文

`setUpClass` 是类方法;在其中赋值 `self.client` 设置的是类对象上的实例属性,而非测试实例上的属性,因此测试实例上的 `self.client` 不存在。

Workarounds

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

Dead Ends

Common approaches that don't work:

  1. 80% fail

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

  2. 50% fail

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