如何解决如何在Python的stdin / stdout中使用Black Box Test
我喜欢TDD,所以我首先尝试写我的Black Box Test
。
这是一个处理stdin
并像这样输出到stdout
的python程序(我尝试编写自己的只处理stdin和stdout的语言):
$ python3 ./minor.py
>>> print,"hello\nthis is a good morning"
... hello
. this is a good morning
>>> $quit
但是我不能嘲笑标准输入和标准输出。我尝试在Python中使用subprocess
,但是Popen.stdout.read()
挂在EOF
上,这需要杀死程序。或communicate()
,但它将杀死我的程序,并且无法处理两个或多个输入。
这让我感到沮丧2天以上,我找不到使用stdin / stdout进行模拟或黑盒测试的任何有用的东西(我可以用浏览器进行测试但不能轻易地使用stdin / stdout看起来很奇怪)。
谢谢。
*** First Editing ***
我创建了一个新的unittest类来处理我的课程。它具有创建新的Popen对象的功能。
我尝试写stdin
并声明stdout
...但是它挂起只是因为找不到EOF
。
我应该如何处理它?感谢您的帮助!
class TestFunc(unittest.TestCase):
def run_minor(self):
return Popen(['python3','./minor.py'],stdin = PIPE,stdout = PIPE,stderr = PIPE,text = True,)
def test_print(self):
prop = self.run_minor()
self.assertEqual(prop.stdout.read(),'>>> ')
prop.stdin.write("print,'this'")
self.assertEqual(prop.stdout.read(),'... this\n>>> ')
prop.stdin.write("$quit")
self.assertEqual(prop.stdout.read(),'')
prop.kill()
解决方法
我创建了一个帮助器类来提供帮助...我不知道这是否是最好的主意,但效果很好:
class MinorMock(object):
"""
The Mock of Minor Programme.
Use method `input` and `assertOutput` to set the input and the output want. Use
`assertInputMeetOutput` to check if the input is meet its output by unittest's object.
"""
def __init__(self,test_obj):
self.popen = Popen(['python3','minor.py'],stdin=PIPE,stdout=PIPE,stderr=PIPE,text=True)
self.input_text = ''
self.output_text = ''
self.err_text = ''
self.test_obj = test_obj
def input(self,text):
self.input_text += text
return self
def assertOutput(self,text):
self.output_text += text
return self
def assertError(self,text):
self.err_text += text
return self
def assertInputMeetOutput(self):
(out,err) = self.popen.communicate(self.input_text)
self.test_obj.assertEqual(out,self.output_text)
self.test_obj.assertEqual(err,self.err_text)
self.popen.kill()
欢迎其他答案...
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。