You must make sure that you consistently follow some naming conventions (which you seem to be doing):
All tests are named with the same prefix (test_
is the norm), followed by the name of the module you wish to test.
prog.py
=> test_prog.py
Tests reside in test/
directory.
Then you can do something like this:
prog.py
import sys
...
... do module stuff here...
...
if __name__ == "__main__":
# Check if we want to run the tests for this file
if "--unittest" in sys.argv:
import unittest
test_filename = 'test_' + __file__
test_directory = 'test'
suite = unittest.TestLoader().discover(test_directory, pattern=test_filename)
unittest.TextTestRunner(verbosity=2).run(suite)
What we are doing, is:
Checking the command arguments to see if --unittest
is present (since that's the only time you want to run the tests).
If it is, then we create the test_prog.py
- following the naming conventions we have set.
Then we pass that to the TestLoader().discover
function.
discover(...) starts at the specified directory and finds all test modules (recursing into subdirectories ) that match the pattern provided.
In our case, it will look inside the test/
directory for any module named test_prog.py
. When it does, it loads it and creates a TestSuite with the TestCases that we want to run.
Lastly, we manually test unittest
to run the suite
obtained in the previous step.
Normally, unittest
will do all of this for us in the background, but since we are trying to run a specific test module, we have to tell exactly how and where to get it from.
Also, note that you will have to do this for every file where you want to do this at.