[英]Return different mock results for the same call within a function in pytest
I have a test function where I successfully patched a function call to return a mock result.我有一个测试函数,我成功地修补了一个函数调用以返回模拟结果。 It works for the one time the patched function is called:它只在一次调用修补函数时起作用:
@patch(‘db.get_session’)
def test_some_function(mock_session):
mock_session.return_value.query.return_value = MockResult(1)
assert some_function()
However, I'm trying to test a function that uses get_session().query() multiple times and should return a different result each time.但是,我正在尝试测试一个多次使用 get_session().query() 并且每次都应该返回不同结果的函数。 I'm not sure how to mock this.我不知道如何嘲笑这个。
@patch(‘db.get_session’)
def test_some_other_function(mock_session):
# First call should return one
mock_session.return_value.query.return_value = MockResult(1)
# Second call should return no results:
mock_session.return_value.query.return_value = MockResult(0)
assert some_other_function()
def some_other_function():
session = get_session()
one = session.query('some_query')
zero = session.query('some_other_query')
if one == 1 and zero == 0:
return True
I've taken a look at side_effect
but I'm not sure how to set it up since I'm not changing the straight return_value but rather the return_value of the return_value (if that makes sense).我看过side_effect
但我不确定如何设置它,因为我没有改变直接的 return_value 而是 return_value 的 return_value (如果有道理的话)。
the side_effect
attribute of a mock can contain an iterable -- each item in the iterable will be returned in order:模拟的side_effect
属性可以包含一个可迭代对象——可迭代对象中的每个项目都将按顺序返回:
>>> m = mock.Mock(side_effect=(1, 2))
>>> m()
1
>>> m()
2
combining this with your example:将此与您的示例相结合:
mock_session.return_value.query.side_effect = (MockResult(1), MockResult(0))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.