The unittest module can be used from the command line to run tests from modules, classes or even individual test methods:
python -m unittest test_module1 test_module2
python -m unittest test_module.TestClass
python -m unittest test_module.TestClass.test_method
You can pass in a list with any combination of module names, and fully qualified class or method names.
You can run tests with more detail (higher verbosity) by passing in the -v flag:
python -m unittest -v test_module
For a list of all the command-line options:
python -m unittest -h
To run tests from modules, classes, or individual test methods using the command-line interface in Python, you can use the unittest test discovery mechanism and specify the test elements you want to run. Here's a checklist for running tests from the command line, along with an example and expected output:
Command-Line Test Execution:
- Ensure your tests are organized in modules and classes that subclass unittest.TestCase.
- Use the unittest test discovery mechanism to discover and run your tests.
- Specify the test elements you want to run using patterns for modules, classes, and methods.
- Run the tests from the command line . Example:
Let's consider an example where you have test modules and test classes, and you want to run specific test methods from the command line.
Suppose you have the following test modules and classes:
# test_math.py
import unittest
class TestMathOperations(unittest.TestCase):
def test_addition(self):
result = 5 + 10
self.assertEqual(result, 15)
def test_subtraction(self):
result = 20 - 7
self.assertEqual(result, 13)
test_strings.py
import unittest
class TestStringOperations(unittest.TestCase):
def test_string_concatenation(self):
str1 = "Hello, "
str2 = "World!"
result = str1 + str2
self.assertEqual(result, "Hello, World")
def test_string_length(self):
string = "Python"
length = len(string)
self.assertEqual(length, 6)
Run Tests from Command Line
:
To run all tests from all modules and classes:
python -m unittest discover
To run all tests from a specific module:
python -m unittest discover -s path_to_tests -p "test_math.py"
To run all tests from a specific test class within a module:
python -m unittest discover -s path_to_tests -p "test_math.py"
To run a specific test method:
python -m unittest path_to_tests.test_math.TestMathOperations.test_addition
Expected Output:
The output will vary based on the specific tests you run. Here's an example of the output for running a specific test method:
.
----------------------------------------------------------------------
Ran 1 test in 0.001s
OK
The output indicates that one test was run, and it passed (indicated by "OK").
You can adapt the checklist and examples to suit your specific test organization and requirements. The unittest test discovery mechanism allows you to selectively run tests from the command line based on modules, classes, or individual test methods.
Top comments (0)