Skip to content

Instantly share code, notes, and snippets.

@alecmunro
Created September 6, 2011 19:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save alecmunro/1198698 to your computer and use it in GitHub Desktop.
Save alecmunro/1198698 to your computer and use it in GitHub Desktop.
Partial mocks
#Need to create this because mocker.patch() and flexmock(object)
#don't work with builtins.
class Something(object):
def do_something(self):
pass
"""Mocker:
Mocker has two methods for partial mocking.
mocker.proxy() will return a mock object that will forward
unmatched calls to the original object.
mocker.patch() is similar, but at replay() time, modifies the
original object with whatever expectations have been set up on
it."""
from mocker import Mocker
def mocker_test_proxy():
mocker = Mocker()
obj = Something()
partial = mocker.proxy(obj, spec=None)
partial.do_something()
mocker.replay()
partial.do_something()
def mocker_test_patch():
mocker = Mocker()
obj = Something()
partial = mocker.patch(obj, spec=None)
partial.do_something()
mocker.replay()
obj.do_something()
"""Flexmock:
Flexmock uses flexmock(original) for partial mocking.
If an expectation is set up that does not match an existing
method on the original object, flexmock.MethodDoesNotExist
is raised.
"""
from flexmock import flexmock
def flexmock_test():
obj = Something()
flexmock(obj)
obj.should_receive("do_something")
obj.do_something()
"""Fudge:
Fudge has a bit of a roundabout approach to partial mocks.
First you need to create a mock object, then create a
PatchHandler with the original class and the method to mock
and use that to patch() the mock you created. Finally you
need to restore() the PatchHandler.
There is also a shortcut using a context manager, which is much
cleaner, but doesn't scale well if you need to mock out multiple
calls."""
import fudge
from fudge.patcher import PatchHandler
def fudge_test():
a_mock = fudge.Fake().is_callable()
patch = PatchHandler(Something, "do_something")
patch.patch(a_mock)
obj = Something()
obj.do_something()
patch.restore()
def fudge_test_cm():
with fudge.patched_context(Something, 'do_something',
fudge.Fake().is_callable()):
obj = Something()
obj.do_something()
"""Mock:
You can create partial mocks with Mock by creating mocks and
assigning them to the attributes you want to mock out. This
seems like a fairly limited approach, because it overrides what
was originally in that attribute."""
import mock
def test_mock():
obj = Something()
something.do_something = mock.Mock()
obj.do_something()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment