Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python, unittest, test a script with command line args

I've written a python script that takes command line arguments and plays one round of Tic Tac Toe.
running it looks like this...

run ttt o#xo##x## x 0 1

If the move is legal it then prints the new board layout and whether anyone won the game

I have to write tests for it using unittest. I dont know how to test the whole script with various command line parameters, all the examples I've seen seem to just test individual functions within the script. Also the script uses argparse to parse the parameters

Thanks!

like image 894
Guye Incognito Avatar asked Oct 09 '12 23:10

Guye Incognito


1 Answers

Refactor your program so that its main action (minus the argparsing) happens in a "main" function:

def main(args):
    ...

if __name__ == '__main__':
    args = parse_args()
    main(args)

Then you can write tests for the behavior of main and parse_args.

PS. It is possible to use the subprocess module to call your program as an external process and then parse the output, but I think that would be uglier and unnecessary.

PPS. As an added benefit of writing your program this way, you will be able to import your program as a module, and call its main function in other scripts. That might be useful if, for example, you would one day like to build a GUI for it.

like image 105
unutbu Avatar answered Oct 16 '22 06:10

unutbu