python type_error ai_generated true

AttributeError: <class 'mypkg.Client'> has no attribute 'endpoint'

ID: python/pytest-monkeypatch-setattr-class

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

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
7.x active
8.x active

Root Cause

monkeypatch.setattr(Client, 'endpoint', ...) requires the attribute to already exist unless raising=False is passed; monkeypatch deliberately refuses to create new attributes.

generic

中文

monkeypatch.setattr(Client, 'endpoint', ...) 要求属性已存在,除非传入 raising=False;monkeypatch 有意拒绝创建新属性。

Workarounds

  1. 95% success
    def test_client(monkeypatch):
        monkeypatch.setattr(Client, 'endpoint', 'http://test', raising=False)
  2. 90% success
    client = Client()
    monkeypatch.setattr(client, 'endpoint', 'http://test')

Dead Ends

Common approaches that don't work:

  1. 75% fail

    Bypasses monkeypatch's automatic undo; the attribute leaks into subsequent tests.

  2. 80% fail

    The code under test instantiates the original Client, not the subclass, so the override has no effect.