[TIP] flexmock for Python
Herman Sheremetyev
herman at swebpage.com
Fri Nov 26 19:30:07 PST 2010
On Fri, Nov 26, 2010 at 3:16 AM, Kumar McMillan
<kumar.mcmillan at gmail.com> wrote:
> 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
atexit would only get run when the interpreter exited so I don't think
that would be useful in this case.
> 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
yup, and the current implementation is rather tightly entwined with
unittest as a result. Which isn't really an issue for me at the moment
as all the tests I have to work with personally use unittest or nose
(which allows for unittest classes).
> ways of registering arbitrary teardowns where I can see this use case
> applied (but then you're tied to a test framework).
FlexMock in Ruby has a different module you import flexmock from
depending on which test runner you want to integrate with, which
extends that test runner class in the process. I don't think there's
quite such a clean way to do it for Python, maybe by messing around
with __init__(?), but that's not something I really want to do.
My plan for (probably) the next release is to include something
similar in spirit, where you would do:
from flexmock.unittest import flexmock
or
from flexmock.<insert your test runner> import flexmock
And make it very easy to write the flexmock.runner classes that do the
right things for whatever test runner you're interested in.
-Herman
More information about the testing-in-python
mailing list