diff options
Diffstat (limited to 'fixtures/_fixtures/monkeypatch.py')
-rw-r--r-- | fixtures/_fixtures/monkeypatch.py | 26 |
1 files changed, 19 insertions, 7 deletions
diff --git a/fixtures/_fixtures/monkeypatch.py b/fixtures/_fixtures/monkeypatch.py index 7db3671..4198b4f 100644 --- a/fixtures/_fixtures/monkeypatch.py +++ b/fixtures/_fixtures/monkeypatch.py @@ -23,6 +23,23 @@ import types from fixtures import Fixture +def _setattr(obj, name, value): + """Handle some corner cases when calling setattr. + + setattr transforms a function into instancemethod, so where appropriate + value needs to be wrapped with staticmethod(). + """ + if sys.version_info[0] == 2: + class_types = (type, types.ClassType) + else: + # All classes are <class 'type'> in Python 3 + class_types = type + if (isinstance(obj, class_types) and + isinstance(value, types.FunctionType)): + value = staticmethod(value) + setattr(obj, name, value) + + class MonkeyPatch(Fixture): """Replace or delete an attribute.""" @@ -60,16 +77,11 @@ class MonkeyPatch(Fixture): if old_value is not sentinel: delattr(current, attribute) else: - setattr(current, attribute, self.new_value) + _setattr(current, attribute, self.new_value) if old_value is sentinel: self.addCleanup(self._safe_delete, current, attribute) else: - # Python 2's setattr transforms function into instancemethod - if (sys.version_info[0] == 2 and - isinstance(current, (type, types.ClassType)) and - isinstance(old_value, types.FunctionType)): - old_value = staticmethod(old_value) - self.addCleanup(setattr, current, attribute, old_value) + self.addCleanup(_setattr, current, attribute, old_value) def _safe_delete(self, obj, attribute): """Delete obj.attribute handling the case where its missing.""" |