[TIP] Return different values based on an argument passed to a method

Michael Foord michael at voidspace.org.uk
Mon Mar 5 08:08:02 PST 2012


On 05/03/2012 12:41, Michael Foord wrote:
> On 05/03/2012 12:33, Marcin Zajączkowski wrote:
>> Hi,
>>
>> Is it possible to simple stub a method's return value when called 
>> with an argument (any argument or specific one)?
>>
>> I tried with:
>> mock = Mock()
>> mock.foo(ANY).return_value(False)
>>
>> but in a debugger I see that in my code mock.foo(<<some_object>>) 
>> returns a mock instead of False value. If not the returning value I 
>> could use assert_called_with with custom mather, but how to return 
>> different value based on an argument?
>
> To change the return value of mock.foo you set mock.foo.return_value.
>
> mock.foo(ANY).return_value(False)  is fetching the return_value mock 
> got by calling mock.foo - and then calling that mock with False! 
> (You're not setting any return_value at all, you're just making calls.)
>
> To have mock.foo return False, do this:
>
>     mock.foo.return_value = False
>
> It's not entirely clear to me from your post, but if you want to you 
> can dynamically change the value returned from a call using side_effect.
>
> >>> from mock import MagicMock
> >>> def side_effect(arg):
> ...      if arg == 1:
> ...          return False
> ...      return True
> ...
> >>> m = MagicMock()
> >>> m.foo.side_effect = side_effect

And for those who like one-liners (needs mock 0.8):

 >>> m = MagicMock(**{'foo.side_effect': lambda arg: True if arg == 1 
else False})
 >>> m.foo(1)
True
 >>> m.foo(37)
False

All the best,

Michael


> >>> m.foo(1)
> False
> >>> m.foo(37)
> True
>
> All the best,
>
> Michael Foord
>
>
>> Regards
>> Marcin
>>
>>
>>
>>
>> _______________________________________________
>> testing-in-python mailing list
>> testing-in-python at lists.idyll.org
>> http://lists.idyll.org/listinfo/testing-in-python
>>
>
>


-- 
http://www.voidspace.org.uk/

May you do good and not evil
May you find forgiveness for yourself and forgive others
May you share freely, never taking more than you give.
-- the sqlite blessing http://www.sqlite.org/different.html




More information about the testing-in-python mailing list