python module_error ai_generated true

导入错误:起始目录 'tests' 不可导入:'tests' 不是一个包

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

ID: python/unittest-testloader-discover-error

其他格式: JSON · Markdown 中文 · English
80%修复率
84%置信度
0证据数
2025-07-22首次发现

版本兼容性

版本状态引入弃用备注
3.9 active

根因分析

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

English

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

generic

解决方案

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

无效尝试

常见但无效的做法:

  1. 50% 失败

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

  2. 60% 失败

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