python runtime_error ai_generated true

属性错误:'MonkeyPatch'对象没有'undo'属性

AttributeError: 'MonkeyPatch' object has no attribute 'undo'

ID: python/pytest-monkeypatch-undo

其他格式: JSON · Markdown 中文 · English
80%修复率
86%置信度
0证据数
2025-10-05首次发现

版本兼容性

版本状态引入弃用备注
7.0.0 active
8.0.0 active

根因分析

monkeypatch fixture的undo方法在pytest 6.0+中被移除,但旧代码可能仍尝试调用它。正确的撤销补丁方法是使用上下文管理器或让fixture自动恢复。

English

The monkeypatch fixture's undo method was removed in pytest 6.0+, but older code may still try to call it. The correct way to undo patches is to use context managers or let the fixture automatically revert.

generic

解决方案

  1. 95% 成功率 Remove calls to monkeypatch.undo() and let the fixture revert changes automatically
    def test_example(monkeypatch):
        monkeypatch.setattr('os.getcwd', lambda: '/tmp')
        # No need to call undo; fixture reverts on teardown
  2. 90% 成功率 Use monkeypatch as a context manager for explicit control
    with monkeypatch.context() as m:
        m.setattr('os.getcwd', lambda: '/tmp')
        # Changes are reverted after the with block

无效尝试

常见但无效的做法:

  1. Downgrading pytest to version 5.x to restore the undo method 60% 失败

    This is a temporary fix and prevents using newer pytest features.

  2. Creating a custom undo function manually 40% 失败

    This duplicates functionality that already exists in the fixture's automatic teardown.