[TIP] flexmock

Herman Sheremetyev herman at swebpage.com
Mon Jul 4 02:41:15 PDT 2011

On Mon, Jul 4, 2011 at 10:38 AM, Eric Henry <henryer2 at msu.edu> wrote:
> a_mock_object['key'] = value
> I'm trying to mock the Mechanize browser class, which allows form input to
> be set by item assignment. I was hoping I could just call
> should_receive('__setitem__'), but it looks like is prefixing the method
> name with "Mock".

There's a bug in current flexmock release with mocking private methods
that's fixed in HEAD that causes the should_receive to behave as you
described, but I don't think you really don't need to do anything
fancy like that here. Direct assignment would do the trick:

from flexmock import Mock
Mock.__setitem__ = object.__setattr__
foo = flexmock()
foo['bar'] = 'baz'

The trick is to override the __setitem__ method on the class of the
fake object rather than the particular instance or Python doesn't seem
to respect it. However, I don't advocate actually importing anything
from flexmock other than the flexmock function which should be the
only entry point into the API.

Any reason why you don't just do a partial mock on this Mechanizer
class (or an instance of it) and use that instead of making a vanilla
fake object with flexmock? Something along the lines of:

foo = flexmock(Mechanizer())
foo['bar'] = 'baz'

> Something like what mox.py has. If you look at the mox.py source code line
> 429, you'll see what I'm talking about...
> http://code.google.com/p/pymox/source/browse/trunk/mox.py?r=26

It's a neat idea, I enjoy being able to do this sort of thing in
Javascript as well. I'll think about adding it to flexmock as a

> This issue aside, I really like Flexmock. It's simple, to the point, fits
> exactly where I need it, and it's api makes it super easy to read!
> Thanks!
> Eric

Glad you like it :)



More information about the testing-in-python mailing list