1
# -*- test-case-name: twisted.test.test_monkey -*-
3
# Copyright (c) 2007 Twisted Matrix Laboratories.
4
# See LICENSE for details.
7
class MonkeyPatcher(object):
9
Cover up attributes with new objects. Neat for monkey-patching things for
10
unit-testing purposes.
13
def __init__(self, *patches):
14
# List of patches to apply in (obj, name, value).
15
self._patchesToApply = []
16
# List of the original values for things that have been patched.
17
# (obj, name, value) format.
23
def addPatch(self, obj, name, value):
25
Add a patch so that the attribute C{name} on C{obj} will be assigned to
26
C{value} when C{patch} is called or during C{runWithPatches}.
28
You can restore the original values with a call to restore().
30
self._patchesToApply.append((obj, name, value))
33
def _alreadyPatched(self, obj, name):
35
Has the C{name} attribute of C{obj} already been patched by this
38
for o, n, v in self._originals:
39
if (o, n) == (obj, name):
46
Apply all of the patches that have been specified with L{addPatch}.
47
Reverse this operation using L{restore}.
49
for obj, name, value in self._patchesToApply:
50
if not self._alreadyPatched(obj, name):
51
self._originals.append((obj, name, getattr(obj, name)))
52
setattr(obj, name, value)
57
Restore all original values to any patched objects.
59
while self._originals:
60
obj, name, value = self._originals.pop()
61
setattr(obj, name, value)
64
def runWithPatches(self, f, *args, **kw):
66
Apply each patch already specified. Then run the function f with the
67
given args and kwargs. Restore everything when done.