我想知道Python中哪些测试工具支持交互式程序的测试。例如,我有一个通过以下方式启动的应用程序:
$ python dummy_program.py
>> Hi whats your name? Joseph
我想要对 Joseph
进行工具化,以便我可以模拟那种交互式的行为。
import sys
def myapp(stdin, stdout):
print >> stdout, "Hi, what's your name?"
name = stdin.readline()
print >> stdout "Hi,", name
# This might be in a separate test module
def test_myapp():
mock_stdin = [create mock object that has .readline() method]
mock_stdout = [create mock object that has .write() method]
myapp(mock_stdin, mock_stdout)
if __name__ == '__main__':
myapp(sys.stdin, sys.stdout)
幸运的是,Python 让这个过程变得非常简单。以下是一个更详细的链接,用于模拟 stdin 的示例:http://konryd.blogspot.com/2010/05/mockity-mock-mock-some-love-for-mock.html
import subprocess
# ...
subprocess.Popen(cmd, env=env, stdin=subprocess.PIPE,
stdout=subprocess.PIPE, stderr=subprocess.PIPE)
out, err = p.communicate(_exit_cmd_string)
pexpect(正如Brian Oakley所提到的)
import pexpect
# ...
child = pexpect.spawn(sys.executable, ['-m', 'IPython', '--colors=nocolor'],
env=env)
# ...
child.sendline("some_command")
child.expect(ipy_prompt)
sys.stdin = mock_stdin
和sys.stdout = mock_stdout
更改标准输入和输出。如果在测试期间需要原始值,他可以使用sys.__stdin__
和sys.__stdout__
来保留原始值。 - PaoloVictor