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

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.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)