我具有显示菜单的功能,供用户输入选择。然后,根据用户选择,程序将调用单独的功能。我试图为我的程序编写一个测试套件,并且无法通过任何涉及用户交互的测试,因此我研究并发现了Mock()模块。
到目前为止,我还无法找到足够接近的示例来帮助我理解该示例如何在函数或模块中的用户输入中发挥作用。我找到了有用的资源here和here,但是都没有使我能够解决问题。我还检查了这里的论坛,以在提出问题之前先查看一下,尽管有些主题还是相似(例如Python Mocking Raw Input in Unittests),但我的知识和任务的复杂性仍然有限,但我很难接受我不了解的事物,并以不同于我所看到的方式应用它。
我希望测试的代码是:
import sys
def menu():
"""Display menu of options to toggle between to perform separate actions"""
selection_dict = {'A': func_A, 'B': func_B, 'C': func_C,
'D': func_D, 'E': quit_program, 'Q': quit_program}
while True:
selection = input('''
-- Menu Options --
A. Call Function A
B. Call Function B
C. Call Function C
D. Call Function D
E. Quit
Menu Selection: ''').upper()
print()
try:
selection_dict[selection]()
except ValueError:
print('Incorrect entry. Please enter A, B, C, D, or E.')
def func_A():
print('Function a')
menu()
def func_B():
print('Function b')
menu()
def func_C():
print('Function c')
menu()
def func_D():
print('Function d')
menu()
def func_E():
print('Function e')
menu()
sys.exit()
if __name__ == '__main__':
menu() # Program starts here
到目前为止,我尝试过的测试(失败了)是:
from unittest import mock
from io import StringIO
import my_file as m
class Test_file(unittest.TestCase):
@mock.patch('sys.stdout', new_callable=StringIO)
def test_mock(self, tst_str, mock_stdout):
with mock.patch('builtins.input', side_effect=tst_str):
m.menu()
return mock_stdout.getvalue()
def test_entry(self):
self.assertEqual(self.test_mock(), 'Menu Options?')
if __name__ == '__main__':
unittest.main()