Testing python interactive programs

I would like to know which testing tools for python support testing interactive programs. For example, I have an application running:

$ python dummy_program.py >> Hi whats your name? Joseph 

I would like to use the Joseph tool so that I can emulate this interactive behavior.

+10
python testing
Jan 17 '11 at 18:43
source share
3 answers

If you are testing an interactive program, consider using expect . It is designed specifically for interaction with console programs (although more for task automation, but not for testing).

If you don't like the expected language based on (tcl), you can try pexpect , which also makes it easier to interact with the console program.

+2
Jan 17 2018-11-17T00:
source share

It is best, most likely, to use dependency injection, so what you usually selected from sys.stdin (for example) is actually a passed object. So you can do something like this:

 import sys def myapp(stdin, stdout): print >> stdout, "Hi, what 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) 

Fortunately, Python makes this pretty easy. Here's a more detailed link for an example of a mocking stdin: http://konryd.blogspot.com/2010/05/mockity-mock-mock-some-love-for-mock.html

+1
Jan 17 '11 at 18:55
source share

A good example is the IPython test_embed.py file.

Two different approaches are used there:

subprocess

 import subprocess # ... subprocess.Popen(cmd, env=env, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) out, err = p.communicate(_exit_cmd_string) 

pexpect (as mentioned by Brian Oakley

 import pexpect # ... child = pexpect.spawn(sys.executable, ['-m', 'IPython', '--colors=nocolor'], env=env) # ... child.sendline("some_command") child.expect(ipy_prompt) 
0
Jun 12 '19 at 10:12
source share



All Articles