python -m unittest discover -vOptions:
-v— Verbose output (shows each test name and result)-s tests— Specify the test directory if not automatically discovered-p '*_test.py'— Pattern for test filenames
Example:
python -m unittest discover -s tests -p '*_test.py' -vpython -m unittest tests.ClassTest
python -m unittest tests.ClassTest.test_method(Tip: Use the full import path relative to your repository root.)
import unittest
from tests import ClassTest
suite = unittest.TestLoader().loadTestsFromTestCase(ClassTest)
unittest.TextTestRunner(verbosity=2).run(suite)Install the coverage library (if not already installed):
pip install coverageRun coverage on the entire project:
coverage run -m unittest discover -vGenerate a terminal report:
coverage report -mOr generate an HTML report:
coverage htmlOpen the resulting report (Linux):
xdg-open htmlcov/index.html(On Windows, use start htmlcov/index.html; on macOS, use open htmlcov/index.html.)
To focus coverage analysis on a specific file or package:
coverage run --source=module/file.py -m unittest discover
coverage report -mOr from Python:
import warnings
from coverage import Coverage
from coverage.exceptions import CoverageWarning
# Suppress include/source overlap warnings
warnings.filterwarnings("ignore", category=CoverageWarning)
cov = Coverage(source=['caemate/calcs/modalanalysis/twinwrappers/viadottoparchi.py'])
cov.start()
# Run your tests here
unittest.TextTestRunner(verbosity=2).run(suite)
cov.stop()
cov.save()
cov.report(show_missing=True)When tests are distributed across different environments (e.g., unit and integration layers):
coverage combine
coverage report -mThis merges all .coverage.* data files into a single combined result.