Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to test Python readline completion?

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?

like image 357
Tony Avatar asked Apr 01 '14 20:04

Tony


1 Answers

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 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).

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('[email protected]')
child.expect('ftp> ')
like image 167
Jules Reid Avatar answered Oct 01 '22 18:10

Jules Reid