Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

testing interactive python programs

Tags:

python

testing

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

$ python dummy_program.py 

>> Hi whats your name? Joseph

I would like to instrument Joseph so I can emulate that interactive behaviour.

like image 800
L.o.c Avatar asked Jan 17 '11 18:01

L.o.c


People also ask

How do I test a Python script online?

To run Python code online, write your Python code in the editor and press the Run button to execute it. You will see the result in your browser.

Can testing be used with Python?

Automated testing is the execution of your test plan (the parts of your application you want to test, the order in which you want to test them, and the expected responses) by a script instead of a human. Python already comes with a set of tools and libraries to help you create automated tests for your application.

Where can I test my Python skills?

You can test your Python skills with W3Schools' Quiz.


2 Answers

If you are testing an interactive program, consider using expect. It's designed specifically for interacting with console programs (though, more for automating tasks rather than testing).

If you don't like the language expect is based on (tcl) you can try pexpect which also makes it easy to interact with a console program.

like image 198
Bryan Oakley Avatar answered Oct 21 '22 06:10

Bryan Oakley


Your best bet is probably dependency injection, so that what you'd ordinarily pick up from sys.stdin (for example) is actually an object passed in. So you might do something like this:

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)

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

like image 41
Raph Levien Avatar answered Oct 21 '22 04:10

Raph Levien