【问题标题】:Import path in pytestpytest中的导入路径
【发布时间】:2021-06-03 06:22:34
【问题描述】:

我的 Python Flask 项目具有以下项目结构(我删除了不必要的东西):

server
    src
        service
            __init__.py
            User.py
    tests
        pytest.ini
        service
            test_user.py

其中pytest.ini 包含:

[pytest]
python_paths = ../src

还有test_user.py:

from service.User import UserService

def test_empty_db():
    service = UserService()
    users = service.get_all()  # Get all users from DB.
    assert len(users) = 0  # There should be users.

现在,我想运行这个测试。当我从项目的根目录运行pytestpytest server 时,一切正常。但是,当我要运行指定文件pytest server/tests/service/test_user.py时出现错误:

从服务.用户导入用户服务
E ModuleNotFoundError: 没有名为“服务”的模块

有什么办法可以解决吗?

【问题讨论】:

    标签: python python-3.x testing pytest python-import


    【解决方案1】:

    您可以尝试在 test_user.py 中使您的导入更加绝对,例如:from server.src.service.User import …

    或者您也可以尝试将__init__.py 添加到您的测试目录。

    【讨论】:

      【解决方案2】:

      您的错误消息显示services.User,而您的代码显示service.User,可能是错字吗?

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-04-20
        • 1970-01-01
        • 1970-01-01
        • 2016-04-28
        • 2013-04-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多