Test Discovery Rules
unittest has built-in test discovery that automatically finds and runs your tests. Understanding the discovery rules ensures all your tests are picked up correctly.
Default Discovery Rules
# unittest discovers tests by looking for:
# 1. Files matching the pattern: test*.py
# 2. Classes that inherit from unittest.TestCase
# 3. Methods starting with 'test_'
# Project structure:
# my_project/
# โโโ test_user.py โ discovered
# โโโ tests.py โ discovered
# โโโ user_test.py โ NOT discovered (doesn't match test*.py)
# โโโ test_auth/
# โโโ __init__.py
# โโโ test_login.py โ discovered
Customizing Discovery
# From command line, specify the start directory and pattern:
# python -m unittest discover -s tests -p "test_*.py"
# In code, use TestLoader:
loader = unittest.TestLoader()
suite = loader.discover(
start_dir='tests',
pattern='test_*.py',
top_level_dir='.'
)
Discovery Behavior
- Discovery starts from the specified directory and walks subdirectories.
- Only files matching the pattern are loaded.
- Within each file, only TestCase subclasses with test methods are included.
- Modules must be importable (need
__init__.pyin package directories). - Test classes without any test methods are silently ignored.
Key Takeaway
unittest discovers tests by scanning for files named test*.py, then finding
TestCase subclasses and their test_* methods. Customize discovery with
discover() or command-line flags.