Super Simple Mocking For Python
pythonwise.blogspot.com
pythonwise.blogspot.com
self.orig = self.obj.__dict__
Should be more like:
self.orig = self.obj.__dict__.copy()
def __enter__(self):
self.original = dict(self.obj.__dict__)
self.obj.__dict__.update(self.mocks)
return self
def __exit__(self, typ, val, traceback):
self.obj.__dict__ = self.original
This doesn't perform a deep copy, but prevents modifications on self.obj.__dict__ from modifying self.original also. self.mocks = dict(zip(args[::2], args[1::2]))
Makes for a very unpythonic feeling API. I’d be interested to hear why the author settled on this design, and see example uses that he likes the look of. Are there any other libraries which use this pattern?Seriously though, cool lib, thanks for it =)
mock(obj, x=1, y=2)
Which you get by: def __init__(self, obj, **mocks):
self.obj = obj
self.mocks = mocks
This can then also be called (using the built-in double-star-unpacking feature) as: mock(obj, **{'x': 1, 'y': 2})
or even mock(obj, **dict([('x', 1), ('y', 2)]))
Then there’s no explicit need to support multiple alternative function signatures, and in particular you don’t get people using the (quite atypical and therefore semantically ambiguous): mock(obj, 'x', 1, 'y', 2).