gpt4 book ai didi

运行测试时不导入 Python 嵌套子包

转载 作者:太空宇宙 更新时间:2023-11-04 04:57:04 25 4
gpt4 key购买 nike

我有这样的文件夹结构:

api
-- test
-- test_api.py
-- __init__.py
-- api
-- api.py
-- __init__.py
-- sub
-- sub.py
-- __init__.py

子.py:

Base = 'base'

api.py:

from sub.sub import Base

def stuff_to_test(): 通过

test_api.py:

from api.api import stuff_to_test

def test_stuff_to_test():
stuff_to_test()

我在目录 api 中。我运行 pytest:

==================================== ERRORS ====================================
______________________ ERROR collecting tests/test_api.py ______________________
ImportError while importing test module '/<somepath>/api/tests/test_api.py'.
Hint: make sure your test modules/packages have valid Python names.
Traceback:
tests/test_api.py:1: in <module>
from ..api.api import stuff_to_test
api/__init__.py:1: in <module>
from . import api
api/api.py:1: in <module>
from sub.sub import Base
E ImportError: No module named 'sub'
!!!!!!!!!!!!!!!!!!! Interrupted: 1 errors during collection !!!!!!!!!!!!!!!!!!!!
=========================== 1 error in 0.08 seconds ============================

如果我运行 python 解释器并从 test_api.py 导入内容,也会发生同样的情况:

>>> from tests.test_api import *
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/<somepath>/api/tests/test_api.py", line 1, in <module>
from api.api import stuff_to_test
File "/<somepath>/api/api/__init__.py", line 1, in <module>
from . import api
File "/<somepath>/api/api/api.py", line 1, in <module>
from sub.sub import Base
ImportError: No module named 'sub'

我的第一个想法是在 api.py 中进行相对导入:

from .sub.sub import Base

这种方式测试运行良好。但是如果我运行 python api/api.py 我会得到这个错误:

Traceback (most recent call last):
File "api/api.py", line 1, in <module>
from .sub.sub import Base
SystemError: Parent module '' not loaded, cannot perform relative import

我怎样才能让它运行测试和应用程序?

最佳答案

我通过将以下内容添加到 test.__init__.py

解决了这个问题
project_path = os.path.dirname(os.path.dirname(os.path.realpath(__file__)))
api_path= os.path.join(project_path, 'api')
sys.path.append(api_path)

关于运行测试时不导入 Python 嵌套子包,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46810554/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com