【问题标题】:Pytest: No module named 'src' when run tests from command linePytest:从命令行运行测试时没有名为 \'src\' 的模块
【发布时间】:2023-01-25 03:31:55
【问题描述】:

所以我有python项目和pytest的几个测试。

这是我的项目层次结构:

project_name
  src
    managers
      config_manager.py (with ConfigManager class inside)
    tests
      api_tests.py
  config.ini

api_tests.py

from src.managers.config_manager import ConfigManager

def test_foo():
   print('tests tarted')

因此,当从我的 pycharm ide 运行测试时,我点击运行按钮一切正常,但是当我使用终端开始测试时,出现此错误:

from src.managers.config_manager import ConfigManager
E   ModuleNotFoundError: No module named 'src'

当然如果把这一行注释掉测试就可以执行了。 任何建议可能导致此问题以及如何解决?

【问题讨论】:

  • 你在 src 和子文件夹中有 __init__.py 吗?
  • 不,我没有这个文件
  • 我添加了这些文件,但仍然出现此错误
  • 您是否将一个添加到测试文件夹?另外,我会将 tests 文件夹放在与 src 目录相同的级别而不是在其中,但这是个人喜好。

标签: python pytest


【解决方案1】:

原因:

解释器不知道去哪里寻找你的模块/包

为什么这个工作使用PyCharm?因为PyCharm 自动解析路径。您可以在设置中找到选项 add content roots to PYTHONPATHadd content source roots to PYTHONPATH

如何使用终端运行测试?文件内容:

# 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())

打开终端:

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 ====================================================================

您也可以尝试使用pytest-srcpathstox

【讨论】:

    猜你喜欢
    • 2018-06-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-15
    相关资源
    最近更新 更多