Python Programming, news on the Voidspace Python Projects and all things techie.

mock 0.8 beta 2:bug fix and side_effect iterables

emoticon:scanner I've released mock 0.8 beta 2. You can download it it or install it with:

pip install -U mock==dev

mock is a library for testing in Python. It allows you to replace parts of your system under test with mock objects. The latest stable release is 0.7.2, which you can download from pypi.

There are only a few changes from the beta 1 release, the most important of these is a bugfix. 0.8 beta 1 turned call_args, and entries in call_args_list, into tuples with three members instead of two members as previously. This has now been fixed. In addition yhere is one api change and a couple of features added since the beta 1 release:

  • Setting side_effect to an iterable will cause calls to the mock to return the next value from the iterable
  • Added assert_any_call method
  • Moved assert_has_calls from call lists onto mocks
  • BUGFIX: call_args and all members of call_args_list are two tuples of (args, kwargs) again instead of three tuples of (name, args, kwargs)

For the full list of new features in the 0.8 release, read these blog entries:

The first of the new features in beta 2 simplifies creating mocks that return a sequence of values for a series of calls.

>>> from mock import Mock
>>> m = Mock(side_effect=[1, 2, 3])
>>> m(), m(), m()
(1, 2, 3)

There are also two new assert methods on mocks. The first of these, assert_any_call, checks that the mock has been called with particular arguments. Unlike assert_called_with it doesn't just check the most recent call, but will pass if any of the calls (in call_args_list) match the call you are checking:

>>> m = MagicMock(return_value=None)
>>> m(5, 6, 7, 8)
>>> m(1, 2, 3, 4)
>>> m.assert_any_call(5, 6, 7, 8)
>>> m.assert_any_call(a=3)
Traceback (most recent call last):
 ...
AssertionError: mock(a=3) call not found

The second new method is assert_has_calls. This method allows you to check multiple calls, and as it uses mock_calls you can make asserts for calls on child mocks. You provide a list of calls and assert_has_calls checks that those calls appear sequentially in the mock_calls_list but it doesn't fail if there are extra calls before or after the list of calls. If you switch on any_order then assert_has_calls just checks that all of the calls you provide in the list are present, but without worrying about order at all:

>>> m = MagicMock()
>>> m.foo()
>>> m.bar.baz(1, 2, 3)
>>> m.bing.bong()
>>> m.assert_has_calls([call.foo(), call.bar.baz(1, 2, 3)])
>>> kalls = [call.bing.bong(), call.foo()]
>>> m.assert_has_calls(kalls, any_order=True)

There are now only two new features being considered for 0.8 final (both minor and to do with the repr of callargs objects). They are issues 108 & 113.

Like this post? Digg it or Del.icio.us it.

Posted by Fuzzyman on 2011-08-04 10:48:24 | |

Categories: , Tags: , , ,


Hosted by Webfaction

Counter...