Labs ICT
โญ Pro Login

Running Tests - CLI & TestLoader

Running tests from the command line and using TestLoader

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.

๐Ÿงช Quick Quiz

How do you run unittest tests from the command line?