Python Unittest检查while循环中的输入

2024-06-07 00:08:18 发布

您现在位置:Python中文网/ 问答频道 /正文

我是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)

这是测试套件

^{pr2}$

感谢各位先进人物


Tags: 方法代码numberinputgetlendef单元测试
2条回答

循环是一个无限循环(至少在测试用例的上下文中)。实际上,摆脱循环的唯一方法是让输入成为“exit”,这在您的测试用例中不会发生。在

另外,还不清楚get_input()是如何工作的,因为您定义了popMax和myList,但是在函数中没有实际使用这些函数。。。也许你想这么做myList.append(项)在循环中?在

这应该是你运行测试的方式。这是我的测试代码,手动运行测试。它按预期运行,因为“是”将无法完成“退出”测试,您将在列表中获得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'

相关问题 更多 >