Skip to content

Instantly share code, notes, and snippets.

@mrdrozdov
Last active August 29, 2015 14:27
Show Gist options
  • Save mrdrozdov/be63f936f252b0d19584 to your computer and use it in GitHub Desktop.
Save mrdrozdov/be63f936f252b0d19584 to your computer and use it in GitHub Desktop.
Mock Method Was Called
import itertools
class MethodWasCalled(object):
calls = []
def __init__(self, fn):
self.fn = fn
def __call__(self, *args, **kwargs):
self.calls.append([args, kwargs])
return self.fn(*args, **kwargs)
def was_called(self):
return len(self.calls) > 0
def called_with(self, *args, **kwargs):
for call in self.calls:
success = True
for a, b in itertools.izip_longest(args, call[0]):
if a != b:
success = False
for (a_k, a_v), (b_k, b_v) in itertools.izip_longest(kwargs.iteritems(), call[1].iteritems()):
if a_v != b_v or a_k != b_k:
success = False
if success:
return True
return False
def some_method(a, b, c=None):
return (a, b, c)
if __name__ == '__main__':
mocked = MethodWasCalled(some_method)
a = mocked("a", "b", c="c")
b = mocked("d", "e", c="f")
assert mocked.was_called()
assert mocked.called_with("a", "b", c="c")
assert mocked.called_with("d", "e", c="f")
assert not mocked.called_with("d", "e", c="g")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment