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?
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 .
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 ...
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).
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 .
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With