[TIP] [python] Re: Mock Testing Patterns
Gustavo Niemeyer
gustavo at niemeyer.net
Mon Nov 19 11:14:45 PST 2007
>> 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")
I see.. then you call something to verify the number of calls done,
or something like that, and print the excessive ones?
I guess that would work. Perhaps a bit harder if some calls weren't
ordered (I like to allow calls to be unordered whenever the ordering
isn't important, so that the implementation can change without
breaking tests).
>> 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.
True.
>> 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.
So that's what the dict stuff is about. Cool.
>> 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.
I understand that this may not feel natural at first. Even more if
the language you use to express expectations is not very readable. This
is one of the reasons why I tried to keep syntax clean and short.. so
that I would be able to remember how the mock behaves more easily when
I come back to the same code base in 6 months.
complexcomplex
> 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?
With Mocker I can simply do the following, for instance:
obj.get_data()
mocker.result(lots_of_data)
mocker.count(N)
With count() you can use min/max values, where max may be None to
make it unbounded.
--
Gustavo Niemeyer
http://niemeyer.net
More information about the testing-in-python
mailing list