If it won't be simple, it simply won't be. [Hire me, source code] by Miki Tebeka, CEO, 353Solutions

Thursday, February 23, 2012

Super Simple Mocking

There are many mocking libraries for Python out there. Due to the dynamic nature of Python I find them an overkill. Below is a super simple mocking library that works for me.


Note that for some types (such as C extensions, objects with __slots__ ...) this will not work since they do not have a __dict__.

EDIT: Following HackerNews comments , I've changed the interface to mock(obj, **kw).

4 comments:

Anonymous said...

I tried this out, but the object wouldn't be fully restored on context exit.

This is what worked for me :

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

Miki Tebeka said...

Good catch, I forgot to .copy the object original __dict__ (line 28). Fixed now - thanks.

jonathan hartley said...

It's interesting to write your own, but there are a few gotchas.

The attribute you are restoring mat not have been defined on the owning object. It may have been defined on that object's class, or one of the classes' bases. So your __exit__ doesn't always put things back precisely as they were.

Highly recommend using Michael Foord's Mock library instead of rolling your own. It fixes many unexpected complications like this.

Miki Tebeka said...

And objects __dict__ holds only attributes defined withing the object, not in class or base class. See http://codepad.org/PhGMzpVn for example.

As said, this is a super simple example. If you need something more complicated I agree you should look elsewhere :)
However I find this one is enough for me.

Blog Archive