python - 将 __init__.py 导入到unittest包中

标签 python unit-testing testing

我有一个包和一个测试包。根据Where do the Python unit tests go?的建议,测试应该位于不同的目录中。项目的目录树如下:

project\
    kernel\
        __init__.py
        file1.py
        file2.py
    tests\
        __init__.py
        test1.py
        test2.py
        test3.py

我想将 kernel 包导入到 tests 包中,因为这是 file1.pyfile2.py 所在的位置。 py 正在测试。另外,我想在 __init__.py 中使用一个 import 语句,而不是在每次测试中一次又一次地导入 kernel 。 我尝试将以下内容添加到 tests 中的 __init__.py 文件和 test2.pytest2.py (一起和单独),没有成功(第一个没有害处,第二个给出语法错误):

import kernel
import ../kernel

我使用的是python2.6。从命令行发生上述所有事情。当我使用 Eclipse PyDev 时,一切都神奇地工作了。

最佳答案

您使用的相对导入仅在“project”目录是 python 包(即其中包含 __init__.py 文件)时才有效。首先尝试一下,看看是否适合您。

如果 kernel 目录充当要分发的“包”,那么您可以将 tests 目录放入其中,并以这种方式进行相对导入。所以它看起来像这样:

project/
    kernel/
        __init__.py
        file1.py
        file2.py
        tests/
            __init__.py
            test1.py ...

您可以从测试目录导入内核模块,如下所示:

from kernel import file1  # if it's installed in the python path/environment

或者:

from .. import file1
# 'import ..file1' might work, but I'm not sure that's syntactically correct

关于python - 将 __init__.py 导入到unittest包中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24210651/

相关文章:

python - Adagrad 如何在 Keras 中工作? Keras Optimizer 中的 self.weights 是什么意思?

python - 在 Python 中每 3 列添加小时值

unit-testing - 自动分析/单元测试 NHibernate 行为

c# - NUnit:是否可以从我的应用程序中引用类?

ruby-on-rails - Rspec - Rails - 如何跟随重定向

javascript - 如何在 Python 中生成随机字母数字字符串?

python - 如何从属于 MainWindow 类的 QlineEdit 读取文本,并使用 python 和 pyqt 将其使用到 Qthread 类中?

c# - Rhino 模拟 AAA 快速入门?

c# - 单元测试 - 基于算法还是基于样本?

java - 我应该在远程工作站的哪个位置放置 CSV 配置文件以进行分布式 JMeter 测试?