Skip to content

Instantly share code, notes, and snippets.

@vpetro
Created August 26, 2011 18:10
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save vpetro/1174019 to your computer and use it in GitHub Desktop.
Save vpetro/1174019 to your computer and use it in GitHub Desktop.
Return multiple items from a mocked function with Python's mock.
import mock
def returnList(items):
def func():
for item in items:
yield item
yield mock.DEFAULT
generator = func()
def effect(*args, **kwargs):
return generator.next()
return effect
m = mock.Mock()
m.side_effect = returnList([1,2,3])
for i in ['a', 'b', 'c']:
print i, m()
@jtpereyda
Copy link

Turns out you can also just set a side effect to any iterable, including a list:

m = mock.Mock()
m.side_effect = [1, 2, 3]
for i in ['a', 'b', 'c']:
    print(i, m())

http://stackoverflow.com/questions/24897145/python-mock-multiple-return-values

@Arnie97
Copy link

Arnie97 commented Apr 23, 2018

Thanks for your great ideas, vpetro.
By the way, you can always use return_values.pop instead of lambda: return_values.pop().

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment