python
type_error
ai_generated
true
AttributeError: <class 'mypkg.Client'> has no attribute 'endpoint'
ID: python/pytest-monkeypatch-setattr-class
80%Fix Rate
90%Confidence
0Evidence
2024-04-18First Seen
Version Compatibility
| Version | Status | Introduced | Deprecated | Notes |
|---|---|---|---|---|
| 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
-
95% success
def test_client(monkeypatch): monkeypatch.setattr(Client, 'endpoint', 'http://test', raising=False) -
90% success
client = Client() monkeypatch.setattr(client, 'endpoint', 'http://test')
Dead Ends
Common approaches that don't work:
-
75% fail
Bypasses monkeypatch's automatic undo; the attribute leaks into subsequent tests.
-
80% fail
The code under test instantiates the original Client, not the subclass, so the override has no effect.