python type_error ai_generated true

AttributeError: <class 'mypkg.Client'> 没有属性 'endpoint'

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

ID: python/pytest-monkeypatch-setattr-class

其他格式: JSON · Markdown 中文 · English
80%修复率
90%置信度
0证据数
2024-04-18首次发现

版本兼容性

版本状态引入弃用备注
7.x active
8.x active

根因分析

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

English

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

generic

解决方案

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

无效尝试

常见但无效的做法:

  1. 75% 失败

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

  2. 80% 失败

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