python module_error ai_generated true

ImportError: Start directory 'tests' is not importable: 'tests' is not a package

ID: python/unittest-testloader-discover-error

Also available as: JSON · Markdown · 中文
80%Fix Rate
84%Confidence
0Evidence
2025-07-22First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
3.9 active

Root Cause

When using unittest.TestLoader().discover('tests'), the directory must be a Python package (containing __init__.py) and importable from the current Python path.

generic

中文

使用 unittest.TestLoader().discover('tests') 时,该目录必须是 Python 包(包含 __init__.py),并且可以从当前 Python 路径导入。

Workarounds

  1. 90% success
    Add an empty __init__.py file to the 'tests' directory to make it a package, then run discovery from the parent directory.
  2. 80% success
    Use a relative path or run the test script from the parent directory of 'tests' to ensure proper import resolution.

Dead Ends

Common approaches that don't work:

  1. 50% fail

    Adding sys.path.append('.') may fix the import but is a fragile workaround that can cause other import issues.

  2. 60% fail

    Changing the discovery pattern (e.g., 'test*.py') without fixing the package structure still fails if the directory is not a package.