Python单元测试检查while循环中的输入
我刚开始学习Python的单元测试,虽然有一些成功的经验,但在这个单元测试上我遇到了困难。我想检查一个叫做item
的输入方法,并模拟输入。但是我没有收到任何测试结果。很可能我做错了,所以任何帮助都会很棒。以下是正在测试的代码
def get_input():
myList = []
popMax = 6
while len(myList) < popMax:
item = input("Enter a number: ")
if item == "exit":
break
else:
myList.append(item)
print(myList)
print("This is your list!")
print(myList)
这是测试套件
import unittest
from unittest.mock import patch
from get_input import *
class GetInputTest(unittest.TestCase):
@patch('builtins.input', return_value='yes')
def test_answer_yes(self, input):
self.assertEqual(get_input(), 'yes')
if __name__ == "__main__":
unittest.main()
谢谢大家的提前帮助
2 个回答
0
这应该是你运行测试的方式。这里是我的测试代码,你可以手动运行这个测试。它会按预期工作,因为“yes”不会满足“exit”的条件,所以你会在列表中得到6个项目。
def get_input():
myList = []
popMax = 6
while len(myList) < popMax:
item = input("Enter a number: ")
if item == "exit":
break
else:
myList.append(item)
print(myList)
print("This is your list!")
print(myList)
class GetInputTest(unittest.TestCase):
@patch('builtins.input', return_value='1\n2\n3\n4\n5\n6\n')
def test_answer_yes(self, input):
self.assertEqual(get_input(), 'yes')
>>> a = GetInputTest()
>>> a.test_answer_yes()
['yes']
['yes', 'yes']
['yes', 'yes', 'yes']
['yes', 'yes', 'yes', 'yes']
['yes', 'yes', 'yes', 'yes', 'yes']
['yes', 'yes', 'yes', 'yes', 'yes', 'yes']
This is your list!
['yes', 'yes', 'yes', 'yes', 'yes', 'yes']
Traceback (most recent call last):
File "<pyshell#12>", line 1, in <module>
a.test_answer_yes()
File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/unittest/mock.py", line 1136, in patched
return func(*args, **keywargs)
File "<pyshell#9>", line 4, in test_answer_yes
self.assertEqual(get_input(), 'yes')
File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/unittest/case.py", line 797, in assertEqual
assertion_func(first, second, msg=msg)
File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/unittest/case.py", line 790, in _baseAssertEqual
raise self.failureException(msg)
AssertionError: None != 'yes'
0
你的循环是一个无限循环(至少在你的测试案例中是这样的)。实际上,唯一能让你跳出这个循环的方法就是输入“exit”,但在你的测试案例中并没有发生这种情况。
另外,get_input()这个函数是怎么工作的也不太清楚,因为你定义了popMax和myList,但在这个函数里并没有实际使用它们……也许你想在循环里加上myList.append(item)?