当我尝试运行 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
文件。
我在 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
我刚刚测试过它并且它有效。
关于python - 运行 py.test 时导入错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51098026/