[TIP] flexmock for Python

Kumar McMillan kumar.mcmillan at gmail.com
Thu Nov 25 10:16:50 PST 2010


On Thu, Nov 25, 2010 at 7:06 AM, Herman Sheremetyev <herman at swebpage.com> wrote:
> Agreed about the large number of testing libraries.

everyone has different ideas so I think it's beneficial

> But I haven't
> found anything in the Python world which performed automatic assertion
> checking and provided terse syntax. Every other library I saw that
> comes close in expressiveness requires you to either put some "verify"
> method in the tearDown method, add decorators to your tests, or both,
> in order to perform assertions.
>
> A flexmock test is as simple as this:
>
> from flexmock import FlexMock
> class TestFoo(unittest.TestCase):
>  def test_some_stuff(self):
>    FlexMock(Foo).should_receive('method1').and_return('value').once
>    # where Foo is some class, or instance of a class, or module
>    # point being I don't want to care, it should just do the right thing
>    run_some_code_that_should_exercise_that_method()
>
> This will raise an exception if Foo.method1 isn't called exactly once.

Dropping the verify() method is a really nice feature.  How does it
work?  Do you register an at_exit() function?  I.E. what happens if
the code never evokes Foo.method1() ever?  Or do you monkey patch the
teardown of the test case?  py.test and unittest2 actually have nice
ways of registering arbitrary teardowns where I can see this use case
applied (but then you're tied to a test framework).


btw, just for reference, the equivalent code in Fudge is:

Foo = Fake().expects('method1').times_called(1).returns('value')

But you have to wrap your test in @fudge.with_fakes so that verify()
is called in case the code never even touches Foo()


> If I leave off the "once" modifier then it just acts as a stub and
> doesn't raise any errors whether the call has been made or not.
>
> This is such a basic pattern that requires so much needless
> boilerplate, or special casing for classes vs instances vs modules, in
> all the other libraries I've found for Python.
>
> But I'm less interested in turning this thread into a discussion of
> other mocking libraries, and would like to hear any feedback from
> people that give flexmock a try to let me know what to improve.
>
> Cheers,
>
> -Herman
>



More information about the testing-in-python mailing list