在unittest包的__init__.py中导入

2 投票
1 回答
4015 浏览
提问于 2025-04-18 09:42

我有一个包和一个测试包。根据关于Python单元测试应该放在哪里的建议,测试应该放在不同的目录里。这个项目的目录结构如下:

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

我想在tests包中导入kernel包,因为file1.pyfile2.py就是在这里进行测试的。而且,我希望在__init__.py文件中只用一个import语句,而不是在每个测试中都重复导入kernel

我尝试在tests中的__init__.py文件和test2.py中添加以下内容,但都没有成功(第一个没有影响,第二个给了语法错误):

import kernel
import ../kernel

我使用的是python2.6。在命令行中,以上所有操作都能正常进行。当我使用Eclipse PyDev时,一切又神奇地正常工作。

1 个回答

3

你现在使用的相对导入方式,只有在“项目”目录是一个Python包的情况下才能正常工作,也就是说这个目录里需要有一个叫__init__.py的文件。你可以先试试这个,看能不能解决你的问题。

如果kernel目录是你要分发的“包”,那么你可以把tests目录放在里面,这样就可以用相对导入的方式了。结构大概是这样的:

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

然后你可以从tests目录导入kernel模块,可以用以下两种方式:

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

撰写回答