Merge lp:~danken/python-fixtures/staticmethod into lp:~python-fixtures/python-fixtures/trunk

Proposed by Dan Kenigsberg
Status: Merged
Merged at revision: 76
Proposed branch: lp:~danken/python-fixtures/staticmethod
Merge into: lp:~python-fixtures/python-fixtures/trunk
Diff against target: 55 lines (+23/-0)
2 files modified
lib/fixtures/_fixtures/monkeypatch.py (+8/-0)
lib/fixtures/tests/_fixtures/test_monkeypatch.py (+15/-0)
To merge this branch: bzr merge lp:~danken/python-fixtures/staticmethod
Reviewer Review Type Date Requested Status
python-fixtures committers Pending
Review via email: mp+202207@code.launchpad.net

Description of the change

When MonkeyPatch() is applied to a staticmethod of a class object, it does not restore it into its former state, due to an arcane Python 2 behaviour. Please review the suggested fix to the problem.

To post a comment you must log in.
Revision history for this message
Robert Collins (lifeless) wrote :

thank you for the fix, sorry I didn't notice the pending merge till now!

Revision history for this message
Robert Collins (lifeless) wrote :

And merged - thanks again!

Preview Diff

[H/L] Next/Prev Comment, [J/K] Next/Prev File, [N/P] Next/Prev Hunk
1=== modified file 'lib/fixtures/_fixtures/monkeypatch.py'
2--- lib/fixtures/_fixtures/monkeypatch.py 2012-07-04 17:51:59 +0000
3+++ lib/fixtures/_fixtures/monkeypatch.py 2014-01-19 02:22:26 +0000
4@@ -17,6 +17,9 @@
5 'MonkeyPatch'
6 ]
7
8+import sys
9+import types
10+
11 from fixtures import Fixture
12
13
14@@ -62,6 +65,11 @@
15 if old_value is sentinel:
16 self.addCleanup(self._safe_delete, current, attribute)
17 else:
18+ # Python 2's setattr transforms function into instancemethod
19+ if (sys.version_info.major == 2 and
20+ isinstance(current, (type, types.ClassType)) and
21+ isinstance(old_value, types.FunctionType)):
22+ old_value = staticmethod(old_value)
23 self.addCleanup(setattr, current, attribute, old_value)
24
25 def _safe_delete(self, obj, attribute):
26
27=== modified file 'lib/fixtures/tests/_fixtures/test_monkeypatch.py'
28--- lib/fixtures/tests/_fixtures/test_monkeypatch.py 2012-07-04 17:51:59 +0000
29+++ lib/fixtures/tests/_fixtures/test_monkeypatch.py 2014-01-19 02:22:26 +0000
30@@ -19,6 +19,11 @@
31
32 reference = 23
33
34+class C(object):
35+ @staticmethod
36+ def foo(): pass
37+def bar(): pass
38+
39 class TestMonkeyPatch(testtools.TestCase, TestWithFixtures):
40
41 def test_patch_and_restore(self):
42@@ -66,3 +71,13 @@
43 finally:
44 fixture.cleanUp()
45 self.assertFalse('new_attr' in globals())
46+
47+ def test_patch_staticmethod(self):
48+ oldfoo = C.foo
49+ fixture = MonkeyPatch(
50+ 'fixtures.tests._fixtures.test_monkeypatch.C.foo',
51+ bar)
52+ with fixture:
53+ pass
54+ self.assertEqual(oldfoo, C.foo)
55+

Subscribers

People subscribed via source and target branches