8
votes

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!

1
@Pedro, yeah I have been reading that stuff, but it all seems to be about testing functions. I dont know if its even possible to test a whole script with command line parameters, can someone at least say if it is possible? - Guye Incognito
This one may be more in the vein of what you are looking for: Testing Python Scripts. - Pedro Romano

1 Answers

13
votes

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.