Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 357
RyPeck Avatar asked May 31 '13 18:05

RyPeck


People also ask

How do I run a Python unittest command line?

The command to run the tests is python -m unittest filename.py . In our case, the command to run the tests is python -m unittest test_utils.py .

How do you pass a command line argument in unittest Python?

So the way I use to handle the command line arguments can be summarized as: Refactor your program to have the arguments parsing as a function. Refactor your program to handle the arguments parsing differently when doing unit testing. In the unit tests, set the arguments and pass them directly to the functions under ...

How do I run unittest?

To run all the tests in a default group, choose the Run icon and then choose the group on the menu. Select the individual tests that you want to run, open the right-click menu for a selected test and then choose Run Selected Tests (or press Ctrl + R, T).

How do I test Python in terminal?

To start a Python interactive session, just open a command-line or terminal and then type in python , or python3 depending on your Python installation, and then hit Enter .


1 Answers

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.

like image 55
Jace Browning Avatar answered Oct 05 '22 02:10

Jace Browning