从相邻目录导入测试时出现Pytest导入问题


/root
|- __init__.py
|
|- /src 
|  |
|  |- __init__.py
|  |- /x
|     |
|     |- __init__.py
|     |- xy.py
|
|- /tests
|  |- __init__.py
|  |- /test_x
|     |
|     |- __init__.py
|     |- test_xy.py
# tests/test_x/test_xy.py 
from src.x.xy import XY
Class TestXY:
# etc 

当我在根目录中时,我尝试运行pytest tests/*/*,但由于找不到src,我收到了一个由from src.x.xy import XY引起的错误。如果我将导入更改为from …src.x.xy import XY,我会得到"无法导入",因为它来自一级以上的目录。

我也尝试过运行Python -m pytest tests/*/*,但在__pycache__中找不到conftest的错误,我不理解。(ERROR: not found: /root/tests/__pycache__/conftest.cpython-310-pytest-7.1.2.pyc (no name '/root/tests/__pycache__/conftest.cpython-310-pytest-7.1.2.pyc' in any of []))

我错过了什么?为什么以这种方式运行测试如此困难?我可以通过点击测试脚本中的绿色小箭头在pycharm中单独运行它们,没有问题。

在该项目体系结构中,您应该使用配置文件。配置文件应该有src的路径。

pyproject.toml示例:

[tool.pytest.ini_options]
pythonpath = [
"src"
]

pytest.ini示例:

[pytest]
pythonpath = src

如果你有多个src目录,你也可以将其添加到配置中

例如pyproject.toml:

[tool.pytest.ini_options]
pythonpath = [
"src", "src2",
]