简体   繁体   中英

Python: assert call to a list that contains a variable

This question follows python 2.7.3 syntax. In unittest framework, suppose I have the following set up:

import mock;
my_mock = mock.Mock();
my_patch = mock.patch("my_method", my_mock);

Now suppose my_method takes on a list argument as input.

How Can I use my_mock.assert_any_call to make sure that a call is made to my_method such that the input list contains a particular value?

You can do that by use both mock_calls and call unpacking as documented here . Now a for cycle can be enough to do the work:

>>> import mock
>>> m = mock.Mock()
>>> m([1,2])
<Mock name='mock()' id='140596484020816'>
>>> m([5,6])
<Mock name='mock()' id='140596484020816'>
>>> m([8,9])
<Mock name='mock()' id='140596484020816'>
>>> for name,args,kwrgs in m.mock_calls:
...     if 5 in args[0]:
...         print("found")
... 
found

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM