运行 setup.py 测试时子包出现导入错误
我正在尝试为包含单元测试的 Python 项目创建安装包。我的项目布局如下:
setup.py
src/
disttest/
__init__.py
core.py
tests/
disttest/
__init__.py
testcore.py
我的 setup.py 看起来像这样:
from distutils.core import setup
import setuptools
setup(name='disttest',
version='0.1',
package_dir={'': 'src'},
packages=setuptools.find_packages('src'),
test_suite='nose.collector',
tests_require=['Nose'],
)
文件 tests/disttest/testcore.py 包含行 from disttest.core import DistTestCore 。
运行 setup.py test
现在会出现 ImportError: No module named core
。
安装 setup.py 之后,python -c "from disttest.core import DistTestCore" 工作正常。如果我将 import core
放入 src/disttest/__init__.py
中,它也可以工作,但我真的不想维护它,而且它似乎只是测试所必需的。
这是为什么?修复它的正确方法是什么?
I'm trying to create an install package for a Python project with included unit tests. My project layout is as follows:
setup.py
src/
disttest/
__init__.py
core.py
tests/
disttest/
__init__.py
testcore.py
My setup.py
looks like this:
from distutils.core import setup
import setuptools
setup(name='disttest',
version='0.1',
package_dir={'': 'src'},
packages=setuptools.find_packages('src'),
test_suite='nose.collector',
tests_require=['Nose'],
)
The file tests/disttest/testcore.py
contains the line from disttest.core import DistTestCore
.
Running setup.py test
now gives an ImportError: No module named core
.
After a setup.py install
, python -c "from disttest.core import DistTestCore"
works fine. It also works if I put import core
into src/disttest/__init__.py
, but I don't really want to maintain that and it only seems necessary for the tests.
Why is that? And what is the correct way to fix it?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可能需要仔细检查这一点,但看起来您的测试正在导入
tests/
目录中的disttest
包,而不是从src/
目录。为什么需要使用与被测包同名的包?我只需将 testcore 模块移至测试目录,或重命名
tests/disttest
包,并完全避免潜在的命名冲突。无论如何,您想要插入一个 import pdb; pdb.set_trace() 行就在失败的导入之前,并使用不同的导入语句来查看从 where 导入的内容 (
import sys; sys.modules['modulename'].__file__
是你的朋友),这样你就可以更好地了解出了什么问题。You may want to double-check this, but it looks like your tests are importing the
disttest
package in thetests/
directory, instead of the package-under-test from thesrc/
directory.Why do you need to use a package with the same name as the package-under-test? I'd simply move the testcore module up to the tests directory, or rename the
tests/disttest
package and avoid the potential naming conflict altogether.In any case, you want to insert a
import pdb; pdb.set_trace()
line just before the failing import and play around with different import statements to see what is being imported from where (import sys; sys.modules['modulename'].__file__
is your friend) so you get a better insight into what is going wrong.