我正在使用 pythons mock.patch 并希望更改每个调用的返回值。
这是警告:
正在修补的函数没有输入,因此我无法根据输入更改返回值。
这是我的代码供参考。
def get_boolean_response():
response = io.prompt('y/n').lower()
while response not in ('y', 'n', 'yes', 'no'):
io.echo('Not a valid input. Try again'])
response = io.prompt('y/n').lower()
return response in ('y', 'yes')
我的测试代码:
@mock.patch('io')
def test_get_boolean_response(self, mock_io):
#setup
mock_io.prompt.return_value = ['x','y']
result = operations.get_boolean_response()
#test
self.assertTrue(result)
self.assertEqual(mock_io.prompt.call_count, 2)
io.prompt
只是“输入”的独立于平台(python 2和3)的版本。所以最终我试图模拟用户的输入。我尝试过使用列表作为返回值,但这似乎不起作用。
您可以看到,如果返回值无效,我将在这里得到一个无限循环。所以我需要一种方法来最终改变返回值,以便我的测试真正完成。
(回答这个问题的另一种可能的方法是解释我如何在单元测试中模仿用户输入)
不是重复的这个问题 https://stackoverflow.com/questions/7665682/python-mock-object-with-method-called-multiple-times主要是因为我没有能力改变输入。
答案的评论之一这个问题 https://stackoverflow.com/questions/21927057/mock-patch-os-path-exists-with-multiple-return-values是沿着同样的路线,但没有提供答案/评论。