我一直在阅读this,this和this,但我仍然不知道如何正确导入,以便可以进行报道。
这是我的应用程序的结构
package/
app/
services/
__init__.py
news_services.py
test/
news_test.py
这是导入
from ..app.services.news_services import NewsServices
这是我运行文件的命令。
coverage run .\test\news_test.py
这是我得到的错误
ValueError: attempted relative import beyond top-level package
答案 0 :(得分:2)
为了在同一应用程序/服务中进行测试,我经常使用以下模式:
import inspect
import os
import sys
test_dir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))
src_dir = os.path.join(test_dir, '..', 'app')
sys.path.append(src_dir)
from services.news_services import NewsServices
您最好的选择(我每天都会使用我维护的软件包)是安装您自己的软件包,而完全不使用相对导入。
您的测试将完全按照您的用户查找和导入程序包。
这是我的install.sh
,您只需要做一次;诀窍是以“可编辑”的方式安装它,在这种情况下,将导致从环境中导入它的任何内容都能在您的工作结构中通过本地更改完全找到它:
#!/bin/bash
python3 -m venv env/
source env/bin/activate
pip install --editable "."
然后,在您的测试中:
from app.services.news_services import NewsServices
此答案中也对此进行了描述: