"tests" 包的绝对导入在 PyCharm 调试器中因 ModuleNotFoundError 失败

Absolute imports from "tests" package fails with ModuleNotFoundError in PyCharm debugger

给出以下简单的 Python 项目,

$ tree
.
├── Pipfile
├── Pipfile.lock
├── src
└── tests
    ├── test_foo.py
    └── util.py

$ cat Pipfile
[[source]]
url = "https://pypi.org/simple"
verify_ssl = true
name = "pypi"

[packages]
ipython = "*"
pytest = "*"

[dev-packages]

[requires]
python_version = "3.9"

$ cat tests/util.py 
FOO = 5

$ cat tests/test_foo.py 
from tests.util import FOO


def test_foo():
    assert FOO == 5

运行 test_foo 上的 PyCharm 调试器将 pytest 与适当的 pipenv --venv 一起使用会产生以下错误:

Connected to pydev debugger (build 202.8194.15)
Traceback (most recent call last):
  File "<frozen importlib._bootstrap>", line 1007, in _find_and_load
  File "<frozen importlib._bootstrap>", line 984, in _find_and_load_unlocked
ModuleNotFoundError: No module named 'tests.util'

test_foo.py 中,如果你打印出 sys.path,你会注意到 PyCharm 注入了 <path_to_venv>/lib/python<version>/site-packages/IPython/extensions,它恰好包含一个 tests破坏本地命名空间 tests 的模块。上游已报告此问题:请参阅 https://github.com/ipython/ipython/issues/11592.

目前有两种解决方法:

  1. 将您的 tests 目录重命名为其他名称。
  2. 删除 <path_to_venv>/lib/python<version>/site-packages/IPython/extensions/tests 文件夹。