[TIP] [python] Re: Mock Testing Patterns

Blake Winton bwinton at latte.ca
Mon Nov 19 09:39:47 PST 2007

Gustavo Niemeyer wrote:
>> I use the same pattern as Michael, and find it works just fine with Dave
>> Kirby's python-mock (located at http://python-mock.sourceforge.net/). 
>> (Okay, I've modified it a little to also take a dictionary of
>> param->return value mappings, but it's a trivial modification.)
> Interesting.  I'm curious about how easy it is to perform certain tasks:
> 1. How does it verify that no *unexpected* methods were called on the mock?

You can get the list of calls, and check that the ones you want were made in a 
certain order.  i.e. call #2 was to spam.write( "eggs", "more eggs")

> 2. How does it tell where these calls were made?

I don't think it does, but I'm sure you could store the traceback, if you cared 
about that sort of thing.

> 3. Is it easy to return values on specific method calls (think about
>    mocking BasicMath.add(first, second))?

Fairly easy, or at least easy enough for me after I added the dict stuff.

> 4. How does it allow nested expressions to be checked
>    (e.g. mock.connection.cursor().execute("SELECT 1"))

I've ended up setting each attribute to a new mock, with the appropriate 
fake-values, but you could have it do that for you, I'm sure.

> These are just a few of the tasks that I imagine would become
> uncomfortable in such an environment.

They're not as easy as they could be, but coming from Java, they're really quite 
simple.  And more importantly, I understand what they're doing.  They fit my 
brain, which the other pattern doesn't seem to...  At least, not yet.

As a return question, if you make the same call, returning the same large set of 
data, several times, how would you mock that up in the replay scenario?  Would 
you need to specify the same big return value many times?


More information about the testing-in-python mailing list