unit testing - How can I effectively test my readline-based Python program using subprocesses? -
i have python program, which, under conditions, should prompt user filename. however, there default filename want provide, user can edit if wish. this means typically need hit backspace key delete current filename , replace 1 prefer.
to this, i've adapted this answer python 3, into:
def rlinput(prompt, prefill=''): readline.set_startup_hook(lambda: readline.insert_text(prefill)) try: return input(prompt) finally: readline.set_startup_hook() new_filename = rlinput("what filename want?", "foo.txt")
this works expected when program run interactively intended - after backspacing , entering new filename, new_filename
contains bar.txt
or whatever filename user enters.
however, want test program using unit tests. generally, this, run program subprocess, can feed input stdin (and hence test user use it). have unit testing code (simplified) looks this:
p = popen(['mypythonutility', 'some', 'arguments'], stdin=pipe) p.communicate('\b\b\bbar.txt')
my intention should simulate user 'backspacing' on provided foo.txt
, , entering bar.txt
instead.
however, doesn't seem have desired effect. instead, appear, after debugging, new_filename
in program ends equivalent of \b\b\bbar.txt
in it. expecting bar.txt
.
what doing wrong?
the appropriate way control interactive child process python use pexpect
module. module makes child process believe running in interactive terminal session, , lets parent process determine keystrokes sent child process.
pexpect pure python module spawning child applications; controlling them; , responding expected patterns in output. pexpect works don libes’ expect. pexpect allows script spawn child application , control if human typing commands.
Comments
Post a Comment