Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions changelog/14161.bugfix.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Fixed :meth:`monkeypatch.setattr() <pytest.MonkeyPatch.setattr>` leaving a stale entry on the undo stack when the underlying ``setattr()`` call fails (e.g. on immutable targets), causing an ``AttributeError`` crash during teardown.
2 changes: 1 addition & 1 deletion src/_pytest/monkeypatch.py
Original file line number Diff line number Diff line change
Expand Up @@ -244,8 +244,8 @@ def setattr(
# avoid class descriptors like staticmethod/classmethod
if inspect.isclass(target):
oldval = target.__dict__.get(name, NOTSET)
self._setattr.append((target, name, oldval))
setattr(target, name, value)
self._setattr.append((target, name, oldval))

def delattr(
self,
Expand Down
16 changes: 16 additions & 0 deletions testing/test_monkeypatch.py
Original file line number Diff line number Diff line change
Expand Up @@ -89,6 +89,22 @@ def test_unknown_attr_non_raising(self, monkeypatch: MonkeyPatch) -> None:
mp.setattr("os.path.qweqwe", 42, raising=False)
assert os.path.qweqwe == 42 # type: ignore

def test_setattr_failure_does_not_corrupt_undo(
self, monkeypatch: MonkeyPatch
) -> None:
"""If setattr() raises (e.g. target doesn't support attribute
setting), the undo stack should not contain a stale entry that
crashes during teardown (#14161)."""

class Immutable:
__slots__ = ()

target = Immutable()
with pytest.raises(AttributeError):
monkeypatch.setattr(target, "x", 42, raising=False)
# undo() must not raise — no entry should be on the undo stack.
monkeypatch.undo()

def test_delattr(self, monkeypatch: MonkeyPatch) -> None:
with monkeypatch.context() as mp:
mp.delattr("os.path.abspath")
Expand Down