单元测试中的相对导入

问题描述 投票:0回答:1

我已经审阅了几篇关于相对与绝对导入的帖子,但所提出的解决方案似乎都不能解决我的问题。

我的目录结构如下:

--src
    --dir1
        --signal
            __init__.py
            parent_class.py
            --hf
                __init__.py
                child_class.py
                child_class_tests.py
          

父类

child_class.py
内的导入如下
from ..parent_class import Parent

如果我使用 pycharm 运行配置执行

child_class_tests.py
,脚本路径为:
C:\test\src\dir1\signal\hf\child_class_tests.py
,工作目录为
C:\test\src\dir1\signal\hf\
,我会得到异常:
ImportError: attempted relative import with no known parent package

child_class_tests.py
内我有以下代码:

import unittest
import pandas as pd
import sys
import os
print(os.getcwd())
from child_class import Child


class TestSignals(unittest.TestCase):

    DATA = pd.read_pickle(r'data.pkl')

    def test_child_class(self):
        """
        Test 
        """
        test_set = self.DATA.copy()

        print(test_set.head())


if __name__ == '__main__':
    unittest.main()

在 Child 类定义中尝试

from child_class import Child
上的
from ..parent import Parent
时发生错误。

我尝试过添加绝对引用以及从更高的目录运行,但都没有成功。我正在使用 Python 3.9 和 PyCharm 2021.1.1。

在关注其他帖子时,我尝试重新创建他们引用的环境,但无法纠正问题。

python path reference
1个回答
0
投票

child_class
被视为不包含在任何包中的顶级模块,即它位于目录
src/dir1/signal/hf
中(在
sys.path
中隐式显示为
''
),而不是包
dir1.signal.hf

您的测试不应该像这样导入它,而应该从它所属的包中导入它(因此您的测试运行程序应该配置为知道在哪里找到

dir1
):

import unittest
import pandas as pd

from dir1.signal.hf.child_class import Child


class TestSignals(unittest.TestCase):

    DATA = pd.read_pickle(r'data.pkl')

    def test_child_class(self):
        """
        Test 
        """
        test_set = self.DATA.copy()

        print(test_set.head())


if __name__ == '__main__':
    unittest.main()
© www.soinside.com 2019 - 2024. All rights reserved.