[Tutor] unit testing raw_input()

Alan Gauld alan.gauld at freenet.co.uk
Wed Apr 19 08:01:45 CEST 2006


> Suppose I had a function like the following:
#############
def y_n(prompt="Answer yes or no"):
    while True:
        answer = raw_input(prompt)
        if answer in ['y', 'Y', 'yes']:
            print "You said yes!"
            break
        elif answer in ['n', 'N', 'no']:
            print "You said no!"
            break
        else:
            print "%s is an invalid answer."%answer
################
> How could I go about to write an automated test for it?

Create a data file with all of the inputs you need and use input 
redirection to run it. Assuming its called y_n.py:

$ python y_n.py <y_n.in > y_n.out

This is the easiest way of testing interactive programs.
This has limitations for unit testing if you have more 
than one function per module however, in that case 
you need to write a driver module that imports yours 
and takes as a first input the function you want to test...
In Python the driver can sit inside the 
if __name__ == __main__ stanza

Alan G



More information about the Tutor mailing list