[英]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 mock out a framework for testing, and I want to have a mock method return a series of values, each time it's called. 我正在使用来自http://www.voidspace.org.uk/python/mock/mock.html的mock-0.6库来模拟测试框架,我希望有一个模拟方法返回一系列值,每次被召唤。
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: 如果您只想返回值列表,如果您使用mock == 0.8.0或更高版本,答案很简单:
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: returnList函数必须创建一个生成器并使用其
next
方法来提供响应:
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.