这个问题在这里已有答案:
我有这个Python的简单程序(hello.py
):
name=input()
print("Hello " + name)
就这么简单,没有类,没有函数,没有什么,只是一个输入和相应的输出。
我的目标是创建test_hello.py
,hello.py
的测试文件。我花了几个小时在互联网上搜索,但我只找到功能或方法的单元测试,但不是简单的输入和输出程序。任何线索?非常感谢你提前!
注意:堆栈溢出表明有一个答案:How to assert output with nosetest/unittest in python?但是这两个问题非常不同,我的代码中没有函数,并且有一个input()
。在“回答”中建议代码在函数内部,并且没有input()
。
最后,我提出了解决方案:
import unittest
import os
import subprocess
class TestHello(unittest.TestCase):
def test_case1(self):
input = "Alan"
expected_output = "Hello Alan"
with os.popen("echo '" + input + "' | python hello.py") as o:
output = o.read()
output = output.strip() # Remove leading spaces and LFs
self.assertEqual(output, expected_output)
def test_case2(self):
input = "John"
expected_output = "Hello John"
with os.popen("echo '" + input + "' | python hello.py") as o:
output = o.read()
output = output.strip() # Remove leading spaces and LFs
self.assertEqual(output, expected_output)
if __name__ == '__main__':
unittest.main()
我有两个测试用例:“Alan”必须打印“Hello Alan”,John必须打印“Hello John”。
谢谢你们的线索!
我真的建议使用类或函数,但如果你坚持,那么你可以尝试在子进程中使用它并捕获输出