运行py.test时导入错误

时间:2018-06-29 09:00:36

标签: python unit-testing python-import pytest importerror

当我尝试运行pytest时,出现错误,这是我的项目结构:

slots_tracker/
    README.md
    development.txt
    requirements.txt
    tasks.py
    venv/
    slots_tracker/
        __init__.py
        conf.py
        db.py
        expense.py
        server.py
        swagger.yml
        test_api.py

这是我的测试文件:

from expense import create
from conf import PayMethods


def test_create_new_expense():
    response = create(dict(amount=200, desc='Random stuff',
                           pay_method=PayMethods.Visa.value))
# We got a success code
assert response[1] == 201

当我运行pytest时:

pytest

我收到此错误:

ModuleNotFoundError: No module named 'expense'

如果我使用以下命令运行pytest:

python -m pytest

我没有任何错误,也可以运行我的应用程序,也没有任何导入错误:

python server.py

我还注意到,如果删除__init__.py文件,我只能使用以下命令运行pytest:

pytest

我能解决这个问题吗?删除__init__.py似乎不是“正确”的解决方案,因为我正在构建一个软件包,因此它应该有一个__init__.py文件。

我正在虚拟环境中在装有Python 3.6.5的Mac上运行。

1 个答案:

答案 0 :(得分:2)

在代码和测试中使用绝对导入。

更改此:

from expense import create
from conf import PayMethods

收件人:

from slots_tracker.expense import create
from slots_tracker.conf import PayMethods

我刚刚对其进行了测试,并且可以正常工作。