fudge.patcher

Patching utilities for working with fake objects.

See Using Fudge for common scenarios.

fudge.patcher.with_patched_object(obj, attr_name, patched_value)

Decorator that patches an object before the decorated method is called and restores it afterwards.

This is a wrapper around fudge.patcher.patch_object()

Example:

>>> from fudge import with_patched_object
>>> class Session:
...     state = 'clean'
... 
>>> @with_patched_object(Session, "state", "dirty")
... def test():
...     print Session.state
... 
>>> test()
dirty
>>> print Session.state
clean
fudge.patcher.patched_context(obj, attr_name, patched_value)

A context manager to patch an object temporarily during a with statement block.

This is a wrapper around fudge.patcher.patch_object()

>>> from fudge import patched_context
>>> class Session:
...     state = 'clean'
... 
>>> with patched_context(Session, "state", "dirty"): 
...     print Session.state
... 
dirty
>>> print Session.state
clean
fudge.patcher.patch_object(obj, attr_name, patched_value)

Patches an object and returns an instance of fudge.patcher.PatchHandler for later restoration.

Note that if obj is not an object but a path to a module then it will be imported.

You may want to use a more convenient wrapper with_patched_object() or patched_context()

Example:

>>> from fudge import patch_object
>>> class Session:
...     state = 'clean'
... 
>>> patched_session = patch_object(Session, "state", "dirty")
>>> Session.state
'dirty'
>>> patched_session.restore()
>>> Session.state
'clean'

Here is another example showing how to patch multiple objects at once:

>>> class Session:
...     state = 'clean'
... 
>>> class config:
...     session_strategy = 'database'
... 
>>> patches = [
...     patch_object(config, "session_strategy", "filesystem"),
...     patch_object(Session, "state", "dirty")
... ]
>>> try:
...     # your app under test would run here ...
...     print "(while patched)"
...     print "config.session_strategy=%r" % config.session_strategy
...     print "Session.state=%r" % Session.state
... finally:
...     for p in patches:
...         p.restore()
...     print "(patches restored)"
(while patched)
config.session_strategy='filesystem'
Session.state='dirty'
(patches restored)
>>> config.session_strategy
'database'
>>> Session.state
'clean'
class fudge.patcher.PatchHandler(orig_object, attr_name)

Low level patch handler that memorizes a patch so you can restore it later.

You can use more convenient wrappers with_patched_object() and patched_context()

patch(patched_value)

Set a new value for the attribute of the object.

restore()

Restore the saved value for the attribute of the object.

Previous topic

fudge.inspector

This Page