【发布时间】:2017-11-12 19:44:05
【问题描述】:
这行得通:
我得到了我的程序:
# module/core_functions.py
def new_input(question):
print(question)
value = input(">").strip()
return value
def main_function():
#do things
new_input("question1")
#do other things
new_input("question2")
...
我写了一个单元测试:
import unittest
from unittest.mock import patch, Mock
from module.core_functions import main_function
class MytestClass(unittest.TestCase):
@patch('module.core_functions.new_input')
def test_multiple_answer(self, mock_input):
mock_input.return_value = Mock()
mock_input.side_effect = ['Answer1', 'Answer2']
result = main_function()
self.assertIn('ExpectedResult', result)
这工作得很好(我使用nose2 来运行我的所有测试)。
现在这不起作用:
随着我的代码越来越大,我想让其他人参与到我的项目中,我需要将我的函数模块化以使修改更容易和更清晰。
所以我把new_input 函数放在一个新文件module/io.py 中,我得到了一个新的子函数:
# module/subfunctions.py
from module.io import new_input
def subfunction():
# do things
new_input("question")
# do things
return things
而我的核心程序演变为:
# module/core_functions.py
from module.io import new_input
from module.subfunctions import subfunction
def main_function():
#do things
new_input("question1")
#do other things
subfuntion()
...
所以问题在于要模拟的函数在几个地方:在主函数和一些子函数中。 我找不到让我的单元测试工作的方法(我无法预测主函数或一个子函数中是否需要 AnswerX)。
您知道如何修复我的测试以使其正常工作吗? 谢谢(我希望我已经很清楚了)。
编辑:
我尝试了类似的方法:
@patch('module.core_functions.new_input')
@patch('module.subfunctions.new_input')
def test_multiple_answer(self, mock_input):
mock_input.return_value = Mock()
mock_input.side_effect = ['Answer1', 'Answer2']
result = main_function()
self.assertIn('ExpectedResult', result)
但我得到了错误:TypeError: test_multiple_answer() takes 2 positional arguments but 3 were given。
【问题讨论】:
-
无路可走 - 无论在何处调用该函数,您都必须对其进行模拟。
-
我试过了(见我在第一篇文章中的编辑),但我不知道之后如何处理。
-
对于您要添加的每个补丁,您还需要为您的测试函数添加一个参数。或者,您可以添加一个带有不需要参数的对象的补丁:@mock.patch('target.function', mock.MagickMock(return_value='answer2'))
标签: python unit-testing mocking python-unittest.mock