Labs ICT
โญ Pro Login

Test Discovery Rules

How unittest discovers and runs tests automatically

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__.py in 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.

๐Ÿงช Quick Quiz

By default, unittest discovers test files matching which pattern?