运行 py.test 时导入错误
Import error while running 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
看起来不像 'right' 解决方案,因为我正在构建一个包,所以它应该有一个 __init__.py
文件。
我运行正在 Mac 上 Python 3.6.5 在虚拟环境中。
在您的代码和测试中使用绝对导入。
改变这个:
from expense import create
from conf import PayMethods
至:
from slots_tracker.expense import create
from slots_tracker.conf import PayMethods
我刚刚测试过它并且有效。
当我尝试 运行 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
看起来不像 'right' 解决方案,因为我正在构建一个包,所以它应该有一个 __init__.py
文件。
我运行正在 Mac 上 Python 3.6.5 在虚拟环境中。
在您的代码和测试中使用绝对导入。
改变这个:
from expense import create
from conf import PayMethods
至:
from slots_tracker.expense import create
from slots_tracker.conf import PayMethods
我刚刚测试过它并且有效。