# 属性错误：'MonkeyPatch'对象没有'undo'属性

- **ID:** `python/pytest-monkeypatch-undo`
- **领域:** python
- **类别:** runtime_error
- **验证级别:** ai_generated
- **修复率:** 80%

## 根因

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

## 版本兼容性

| 版本 | 状态 | 引入 | 弃用 |
|------|------|------|------|
| 7.0.0 | active | — | — |
| 8.0.0 | active | — | — |

## 解决方案

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

## 无效尝试

- **Downgrading pytest to version 5.x to restore the undo method** — This is a temporary fix and prevents using newer pytest features. (60% 失败率)
- **Creating a custom undo function manually** — This duplicates functionality that already exists in the fixture's automatic teardown. (40% 失败率)
