python - 运行 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 上运行。
解决方案
在您的代码和测试中使用绝对导入。
改变这个:
from expense import create
from conf import PayMethods
至:
from slots_tracker.expense import create
from slots_tracker.conf import PayMethods
我刚刚测试过它并且它有效。
推荐阅读
- angular - 如何进行水平拖动和替换
- javascript - 在 DomPurify 中允许 HTML 注释
- css - 如何将输入值内容左对齐而不是居中对齐?
- angular - 如何从服务器响应中提取 json 对象的第二层属性
- ios - Apple Map 和 MKLocalSearch 的搜索结果不同
- python - Python - 删除行和previos行(匹配模式模式)
- sql - 将我的 SQL 数据库备份还原到 Azure 后,我的所有索引都被禁用
- ios - 是否允许在我们的应用程序中使用苹果自己的应用程序图标?
- smtp - 需要 smtp 中继解决方案
- android - 在 EditText 上调用 setText() 时会发生什么?