diff options
author | Dan Kenigsberg <danken@redhat.com> | 2014-01-19 02:03:30 +0000 |
---|---|---|
committer | Dan Kenigsberg <danken@redhat.com> | 2014-01-19 02:03:30 +0000 |
commit | a66dc6828dcaab4751aaa97a7ab5590b8e0be343 (patch) | |
tree | 414c205c70fc8ed6de42202e6f85345e0adab3a9 | |
parent | 8727fe0376204056557267b13dc073fc571f67f6 (diff) | |
download | fixtures-a66dc6828dcaab4751aaa97a7ab5590b8e0be343.tar.gz |
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.
-rw-r--r-- | lib/fixtures/_fixtures/monkeypatch.py | 8 | ||||
-rw-r--r-- | lib/fixtures/tests/_fixtures/test_monkeypatch.py | 15 |
2 files changed, 23 insertions, 0 deletions
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) + |