Python Glossary Русский

all Python 3unittestterm

unittest.TestLoader

running tests

A class that collects tests into a TestSuite: from a TestCase class, a module, a dotted name, or by discovering test*.py files in a directory.

Syntax

loader = unittest.TestLoader()
suite = loader.loadTestsFromTestCase(MyTests)

The loader treats a method as a test only if its name starts with test (the testMethodPrefix attribute); check_sum or Test_sum is silently skipped and the run is green with zero tests. Methods are sorted by name, not by their order in the file. discover() only finds files matching test*.py in importable directories, so tests_math.py or a package directory without __init__.py easily drops out. The ready-made unittest.defaultTestLoader is usually enough.

Examples

import unittest
class Tests(unittest.TestCase):
    def test_b(self): pass
    def test_a(self): pass
    def check_c(self): pass  # не начинается с test — не тест
loader = unittest.TestLoader()
print(loader.getTestCaseNames(Tests))  # → ['test_a', 'test_b']
print(loader.loadTestsFromTestCase(Tests).countTestCases())  # → 2
import unittest
class Tests(unittest.TestCase):
    def check_one(self): pass
loader = unittest.TestLoader()
loader.testMethodPrefix = 'check'
print(loader.getTestCaseNames(Tests))  # → ['check_one']

See also

Open in the full glossarydocs.python.orgReport an inaccuracy