[英]Pytest: No module named 'src' when run tests from command line
So I have python
project and several tests with pytest
.所以我有
python
项目和pytest
的几个测试。
This is my project hierarchy:这是我的项目层次结构:
project_name
src
managers
config_manager.py (with ConfigManager class inside)
tests
api_tests.py
config.ini
api_tests.py api_tests.py
from src.managers.config_manager import ConfigManager
def test_foo():
print('tests tarted')
So when the test run from my pycharm
ide my click on run button all works fine but when I start the test using terminal I got this error:因此,当从我的
pycharm
ide 运行测试时,我点击运行按钮一切正常,但是当我使用终端开始测试时,出现此错误:
from src.managers.config_manager import ConfigManager E ModuleNotFoundError: No module named 'src'
Of course if this line comment out the test can execute.当然如果把这一行注释掉测试就可以执行了。 Any suggestion what could cause this and how to fix it?
任何建议可能导致此问题以及如何解决?
The reason:原因:
The interpreter doesn't know where to look for your module / package
解释器不知道去哪里找你的模块 / package
Why does this work using PyCharm
?为什么使用
PyCharm
可以工作? Because PyCharm
automatically resolves paths.因为
PyCharm
自动解析路径。 You can find options add content roots to PYTHONPATH
and add content source roots to PYTHONPATH
in settings.您可以在设置中找到
add content roots to PYTHONPATH
和add content source roots to PYTHONPATH
的选项。
How to run tests using terminal?如何使用终端运行测试? Files content:
文件内容:
# src/managers/config_manager.py
class ConfigManager:
@staticmethod
def get_config() -> dict:
return dict(parsed='config')
# src/tests/api_tests.py
from src.managers.config_manager import ConfigManager
def test_get_config():
print(ConfigManager.get_config())
Open terminal:打开终端:
cd project_name
tree
# Example structure. Result:
# ── src
# ├── managers
# │ ├── config_manager.py
# │ └── __init__.py
# └── tests
# └── api_tests.py
export PYTHONPATH="${PYTHONPATH}:${pwd}/src/"
pytest src/tests/*
# =================================================================== test session starts ===================================================================
# platform linux -- Python 3.10.6, pytest-7.2.1, pluggy-1.0.0
# rootdir: /home/d_ganchar/PycharmProjects/project_name
# collected 1 item
# src/tests/api_tests.py . [100%]
# ==================================================================== 1 passed in 0.00s ====================================================================
Also you can try to use pytest-srcpaths or tox您也可以尝试使用pytest-srcpaths或tox
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.