如何测试Python readline的完成? [英] How to test Python readline completion?

查看:72
本文介绍了如何测试Python readline的完成?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在用Python编写命令行界面.它使用readline模块提供命令历史记录和完成情况.

I'm writing a command-line interface in Python. It uses the readline module to provide command history and completion.

虽然在交互模式下一切正常,但我想在完成功能上运行自动化测试.我幼稚的第一次尝试是使用文件进行标准输入:

While everything works fine in interactive mode, I'd like to run automated tests on the completion feature. My naive first try involved using a file for standard input:

my_app < command.file

命令文件包含一个选项卡,希望它可以调用完成功能.没运气.做测试的正确方法是什么?

The command file contained a tab, in the hopes that it would invoke the completion feature. No luck. What's the right way to do the testing?

推荐答案

为此,我将使用期望 (Expect的Python版本). readline库需要与终端进行对话才能完成交互式制表符填充,这样-如果它仅从重定向文件中获得单向输入,则无法做到这一点.

For this I would use Pexpect (Python version of Expect). The readline library needs to be speaking to a terminal to do interactive tab-completion and such—it can't do this if it is only getting one-way input from a redirected file.

Pexpect可以做到这一点,因为它创建了一个伪终端,该终端由两部分组成:从站(在其中运行要测试的程序)和主站(在其中运行Python pexpect代码). pexpect代码模拟了运行测试程序的人员.它负责向从站发送字符,包括换行符和制表符之类的字符,并对预期的输出做出反应(这是短语期望"的来源).

Pexpect works for this because it creates a pseudo terminal, which consists of two parts: the slave, where the program you are testing runs, and the master, where the Python pexpect code runs. The pexpect code emulates the human running the test program. It is responsible for sending characters to the slave, including characters such as newline and tab, and reacting to the expected output (this is where the phrase "expect" comes from).

从示例目录中查看程序 ftp.py 很好的例子说明了如何在期望范围内控制测试程序.这是代码示例:

See the program ftp.py from the examples directory for a good example of how you would control your test program from within expect. Here is a sample of the code:

child = pexpect.spawn('ftp ftp.openbsd.org')
child.expect('(?i)name .*: ')
child.sendline('anonymous')
child.expect('(?i)password')
child.sendline('pexpect@sourceforge.net')
child.expect('ftp> ')

这篇关于如何测试Python readline的完成?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆