python
runtime_error
ai_generated
true
AttributeError: 'MonkeyPatch' object has no attribute 'undo'
ID: python/pytest-monkeypatch-undo
80%Fix Rate
86%Confidence
0Evidence
2025-10-05First Seen
Version Compatibility
| Version | Status | Introduced | Deprecated | Notes |
|---|---|---|---|---|
| 7.0.0 | active | — | — | — |
| 8.0.0 | active | — | — | — |
Root Cause
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中文
monkeypatch fixture的undo方法在pytest 6.0+中被移除,但旧代码可能仍尝试调用它。正确的撤销补丁方法是使用上下文管理器或让fixture自动恢复。
Workarounds
-
95% success 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 -
90% success 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
Dead Ends
Common approaches that don't work:
-
Downgrading pytest to version 5.x to restore the undo method
60% fail
This is a temporary fix and prevents using newer pytest features.
-
Creating a custom undo function manually
40% fail
This duplicates functionality that already exists in the fixture's automatic teardown.