【问题标题】:Importing in __init__.py to a unittest package将 __init__.py 导入到 unittest 包
【发布时间】:2014-08-04 07:52:08
【问题描述】:

我有一个包和一个测试包。根据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 的地方。另外,我想在__init__.py 中使用一个import 语句,而不是在每个测试中一次又一次地导入kernel。 我尝试将以下内容添加到 teststest2.pytest2.py 中的 __init__.py 文件中(一起和分别),但没有成功(第一个没有害处,第二个给出语法错误):

import kernel
import ../kernel

我正在使用 python2.6。从命令行发生上述所有事情。当我使用 Eclipse PyDev 时,一切都很神奇。

【问题讨论】:

    标签: python unit-testing testing


    【解决方案1】:

    您使用的相对导入仅在“项目”目录是 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
    

    【讨论】:

      猜你喜欢
      • 2017-07-25
      • 2013-04-21
      • 1970-01-01
      • 2013-07-29
      • 1970-01-01
      • 2016-06-14
      • 2017-03-12
      • 2023-03-04
      • 1970-01-01
      相关资源
      最近更新 更多