Run unittest from a Python program via a command-line option

RyPeck picture RyPeck · May 31, 2013 · Viewed 41.5k times · Source

Here is my set up -

project/
    __init__.py
    prog.py
    test/
        __init__.py
        test_prog.py

I would like to be able to run my unit tests by calling a command-line option in prog.py. This way, when I deploy my project, I can deploy the ability to run the unit tests at any time.

python prog.py --unittest

What do I need in prog.py, or the rest of my project for this to work?

Answer

Jace Browning picture Jace Browning · May 31, 2013

The Python unittest module contains its own test discovery function, which you can run from the command line:

$ python -m unittest discover

To run this command from within your module, you can use the subprocess module:

#!/usr/bin/env python

import sys
import subprocess

# ...
# the rest of your module's code
# ...

if __name__ == '__main__':
    if '--unittest' in sys.argv:
        subprocess.call([sys.executable, '-m', 'unittest', 'discover'])

If your module has other command-line options you probably want to look into argparse for more advanced options.