[Date Prev][Date Next]   [Thread Prev][Thread Next]   [Thread Index] [Date Index] [Author Index]

[Pulp-list] mock side_effect



I needed to simulate a single mock being called more than once. The call_arg_list can be used to track each call to the method, but I wasn't sure how to make it return different values on each invocation. The answer is in the side_effect attribute.

Previously, I've only used this to simulate the call raising an exception:

mock.do.side_effect = Exception()

It turns out side_effect is bit of a catch all for anything you want to do that isn't covered by a simple return value. The type of thing in side_effect dictates how the mock runs. If a function is passed in, it will execute the function and return that as the return value:

In [1]: values = [1, 2, 3]
In [2]: def side_pop():
   ...:     return values.pop(0)
   ...:
In [3]: import mock
In [4]: m = mock.Mock()
In [5]: m.do.side_effect = side_pop
In [6]: m.do()
Out[6]: 1
In [7]: m.do()
Out[7]: 2
In [8]: m.do()
Out[8]: 3
In [9]: m.do()
---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)
[snip]

For my purposes, there's a simpler way. If an iterable is passed into the side effect, each call into the mock method will return an entry from the iterable:

In [10]: values = [1, 2, 3]
In [11]: m.stuff.side_effect = values
In [12]: m.stuff()
Out[12]: 1
In [13]: m.stuff()
Out[13]: 2
In [14]: m.stuff()
Out[14]: 3
In [15]: m.stuff()
---------------------------------------------------------------------------
StopIteration                             Traceback (most recent call last)





--
Jay Dobies
Freenode: jdob @ #pulp
http://pulpproject.org | http://blog.pulpproject.org


[Date Prev][Date Next]   [Thread Prev][Thread Next]   [Thread Index] [Date Index] [Author Index]