首页 > 解决方案 > 运行 py.test 时导入错误

问题描述

当我尝试运行 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 上运行。

标签: pythonunit-testingpython-importpytestimporterror

解决方案


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

改变这个:

from expense import create
from conf import PayMethods

至:

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

我刚刚测试过它并且它有效。


推荐阅读