Running Tests โ CLI & TestLoader
There are multiple ways to run unittest tests: from the command line, from code, or by using TestLoader for programmatic test execution.
Command Line Execution
# Run all tests in current directory
python -m unittest
# Run a specific module's tests
python -m unittest test_user
# Run a specific test class
python -m unittest test_user.TestUserCreation
# Run a specific test method
python -m unittest test_user.TestUserCreation.test_create_user
# Run with verbose output
python -m unittest -v
# Discover tests in a custom directory
python -m unittest discover -s tests
Running from Code
import unittest
# Using unittest.main() at the bottom of your test file
if __name__ == '__main__':
unittest.main()
# Running with verbosity
if __name__ == '__main__':
unittest.main(verbosity=2)
Using TestLoader
import unittest
loader = unittest.TestLoader()
suite = loader.loadTestsFromName('test_user.TestUserCreation')
runner = unittest.TextTestRunner(verbosity=2)
result = runner.run(suite)
Common CLI Options
-vโ Verbose output showing each test name.-qโ Quiet mode with minimal output.-fโ Fail fast on first error or failure.-sโ Start directory for discovery.-pโ Pattern for test file discovery.
Key Takeaway
Run tests via python -m unittest from the command line, unittest.main() from code,
or TestLoader for programmatic control over which tests execute.