From a66dc6828dcaab4751aaa97a7ab5590b8e0be343 Mon Sep 17 00:00:00 2001 From: Dan Kenigsberg Date: Sun, 19 Jan 2014 02:03:30 +0000 Subject: MonkeyPatch staticmethod As noticed by Antoni S. Puimedon in http://gerrit.ovirt.org/23378/, in Python 2, setattr(Class, name, func) automatically converts a function into an instancemethod. To keep type(Class.func) as function, staticmethod(func) must be applied explicitly. --- lib/fixtures/_fixtures/monkeypatch.py | 8 ++++++++ lib/fixtures/tests/_fixtures/test_monkeypatch.py | 15 +++++++++++++++ 2 files changed, 23 insertions(+) diff --git a/lib/fixtures/_fixtures/monkeypatch.py b/lib/fixtures/_fixtures/monkeypatch.py index 42de7ec..858c587 100644 --- a/lib/fixtures/_fixtures/monkeypatch.py +++ b/lib/fixtures/_fixtures/monkeypatch.py @@ -17,6 +17,9 @@ __all__ = [ 'MonkeyPatch' ] +import sys +import types + from fixtures import Fixture @@ -62,6 +65,11 @@ class MonkeyPatch(Fixture): 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.major == 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) def _safe_delete(self, obj, attribute): diff --git a/lib/fixtures/tests/_fixtures/test_monkeypatch.py b/lib/fixtures/tests/_fixtures/test_monkeypatch.py index b5977d3..1a84d7f 100644 --- a/lib/fixtures/tests/_fixtures/test_monkeypatch.py +++ b/lib/fixtures/tests/_fixtures/test_monkeypatch.py @@ -19,6 +19,11 @@ from fixtures import MonkeyPatch, TestWithFixtures reference = 23 +class C(object): + @staticmethod + def foo(): pass +def bar(): pass + class TestMonkeyPatch(testtools.TestCase, TestWithFixtures): def test_patch_and_restore(self): @@ -66,3 +71,13 @@ class TestMonkeyPatch(testtools.TestCase, TestWithFixtures): finally: fixture.cleanUp() self.assertFalse('new_attr' in globals()) + + def test_patch_staticmethod(self): + oldfoo = C.foo + fixture = MonkeyPatch( + 'fixtures.tests._fixtures.test_monkeypatch.C.foo', + bar) + with fixture: + pass + self.assertEqual(oldfoo, C.foo) + -- cgit v1.2.1