[TIP] Struggling with pymock
varmaa at gmail.com
Fri Sep 7 15:23:04 PDT 2007
pymock definitely took me a bit of getting used to. Here's example code to
test your Example class; I've tried commenting it to make evident some of
the things I had a hard time understanding when I first started using
Note that while I believe this works, it may not be the best way to go about
doing things--suggestions from more experienced pymock users are welcome.
c = pymock.Controller()
# Override the built-in open() function.
c.override( __builtins__, "open" )
# Create a mock file object, which our mock open() will return.
mockFile = c.mock()
# The first parameter here looks a little weird; we've already
# overridden open() with a mock object, so when we call open() here,
# we're "recording" the call, not actually calling open().
c.expectAndReturn( open("myfile.conf"), mockFile )
# This looks a little weird: we're actually "recording" the calling of
# mockFile.close() here, we're not actually calling it!
# We're done "recording" the calls that our mocked objects/functions
# will receive; now prepare for them to be "replayed" by our
# production code.
# Call our real code, which will ultimately call into our mock
Example( "myfile.conf" )
# Verify that all the calls we told our mock objects/functions to
# expect were actually "played back" properly.
Note also that in particular regard to the topic of mocking or stubbing out
built-ins, you may also find this Google Testing in the Toilet article
I hope this helps.
On 9/7/07, Tobias Roth <misc.lists at fsck.ch> wrote:
> I am struggling with the basics of pymock. Here is a simplified example
> class I'd like to test:
> class Example(object):
> def __init__(self, cf):
> self.conffile = cf
> f = open(self.conffile)
> # read and assign
> What I'd like to test is whether the constructor correctly opens a file
> and reads and assigns its contents to some member variables.
> What I'd do with conventional unit testing would be to create a fake
> conffile with some data, have it read by __init__ and then compare what
> has been read with what I set up.
> Now what I imagined to do with pymock was to stub out
> __builtins__.open(). But I could't get pymock to handle the
> self.conffile argument to open() correctly.
> I feel like I am looking at the whole pymock testing from the wrong way,
> since I can't get such a simple example to work. Can someone enlighten me?
> testing-in-python mailing list
> testing-in-python at lists.idyll.org
-------------- next part --------------
An HTML attachment was scrubbed...
More information about the testing-in-python