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/1938.bugfix.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
``monkeypatch.undo()`` now restores ``__bases__`` and similar type-level attributes patched via ``monkeypatch.setattr()``, instead of raising ``TypeError``.
13 changes: 11 additions & 2 deletions src/_pytest/monkeypatch.py
Original file line number Diff line number Diff line change
Expand Up @@ -256,8 +256,10 @@ def setattr(
raise AttributeError(f"{target!r} has no attribute {name!r}")

# avoid class descriptors like staticmethod/classmethod
if inspect.isclass(target):
oldval = target.__dict__.get(name, NOTSET)
is_class = inspect.isclass(target)
if is_class:
in_class_dict = name in target.__dict__
oldval = target.__dict__.get(name, oldval)
elif not _is_data_descriptor(type(target), name):
# With no data descriptor in the way, the `setattr()` below writes
# into the instance `__dict__`, so `undo()` has to restore that
Expand All @@ -269,6 +271,13 @@ def setattr(
if isinstance(target_dict, Mapping):
oldval = target_dict.get(name, NOTSET)
setattr(target, name, value)
if is_class and not in_class_dict:
if name in target.__dict__:
# setattr() created a new entry shadowing an inherited
# attribute: undo() must remove it with delattr() (#156).
oldval = NOTSET
# setattr() did not add a __dict__ entry: undo() restores the old
# value via setattr() (#1938).
self._setattr.append((target, name, oldval))

def delattr(
Expand Down
20 changes: 20 additions & 0 deletions testing/test_monkeypatch.py
Original file line number Diff line number Diff line change
Expand Up @@ -443,6 +443,26 @@ def test_issue156_undo_staticmethod(Sample: type[Sample]) -> None:
assert Sample.hello()


def test_issue1938_patch_class_bases() -> None:
class Loud:
def thing(self):
return "!!!!"

class Quiet:
def thing(self):
return "sssh..."

class ThingToTest(Loud):
pass

monkeypatch = MonkeyPatch()
monkeypatch.setattr(ThingToTest, "__bases__", (Quiet,))
assert ThingToTest().thing() == "sssh..."
monkeypatch.undo()
assert ThingToTest.__bases__ == (Loud,)
assert ThingToTest().thing() == "!!!!"


def test_undo_class_descriptors_delattr() -> None:
class SampleParent:
@classmethod
Expand Down
Loading