How can I make mock-0.6 return a sequence of values?
I'm using the mock-0.6 library from http://www.voidspace.org.uk/python/mock/mock.html to moc开发者_C百科k out a framework for testing, and I want to have a mock method return a series of values, each time it's called.
Right now, this is what I figured should work:
def returnList(items):
def sideEffect(*args, **kwargs):
for item in items:
yield item
yield mock.DEFAULT
return sideEffect
mock = Mock(side_effect=returnList(aListOfValues))
values = mock()
log.info("Got %s", values)
And the log output is this:
subsys: INFO: Got <generator object func at 0x1021db500>
So, the side effect is returning the generator, not the next value, which seems wrong. Where am I getting this wrong?
If you just want to return a list of values, the answer is easy if you're using mock==0.8.0 or later:
import mock
m = mock.Mock()
m = side_effect = [
['a', 'b', 'c'],
['d', 'e', 'f'],
]
print "First: %s" % m()
print "Second: %s" % m()
The output is:
First: ['a', 'b', 'c']
Second: ['d', 'e', 'f']
If you want the same exact return value every time, then the answer is even simpler:
m = mock.Mock()
m.return_value = ['a', 'b', 'c']
print m('foo')
print m('bar')
print m('baz')
Here's the solution, found by trial and error:
The returnList function must create a generator and use its next
method to provide the responses:
def returnList(items):
log.debug("Creating side effect function for %s", items)
def func():
for item in items:
log.debug("side effect yielding %s", item)
yield item
yield mock.DEFAULT
generator = func()
def effect(*args, **kwargs):
return generator.next()
return effect
精彩评论