如何正确导入单元测试的相对路径

幸广

我一直在阅读thisthisthis,但我仍然不知道如何正确导入,这样我才能进行报道。

这是我的应用程序的结构

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

马特博恩

编辑:这是一个应用程序/服务的答案

为了在同一应用程序/服务中进行测试,我经常使用以下模式:

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

此答案中也对此进行了描述:

https://stackoverflow.com/a/6466139/351084

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章