Python Nose 导入错误
我似乎无法让 nose 测试框架 识别我测试脚本下的模块。为了说明这个问题,我设置了一个最简单的例子。下面我会详细解释。
这是我的文件结构:
./__init__.py
./foo.py
./tests
./__init__.py
./test_foo.py
foo.py 文件内容如下:
def dumb_true():
return True
tests/test_foo.py 文件内容如下:
import foo
def test_foo():
assert foo.dumb_true()
这两个 init.py 文件都是空的。
如果我在主目录(也就是 foo.py 所在的地方)运行 nosetests -vv
,我会得到:
Failure: ImportError (No module named foo) ... ERROR
======================================================================
ERROR: Failure: ImportError (No module named foo)
----------------------------------------------------------------------
Traceback (most recent call last):
File "/usr/lib/python/site-packages/nose-0.11.1-py2.6.egg/nose/loader.py", line 379, in loadTestsFromName
addr.filename, addr.module)
File "/usr/lib/python/site-packages/nose-0.11.1-py2.6.egg/nose/importer.py", line 39, in importFromPath
return self.importFromDir(dir_path, fqname)
File "/usr/lib/python/site-packages/nose-0.11.1-py2.6.egg/nose/importer.py", line 86, in importFromDir
mod = load_module(part_fqname, fh, filename, desc)
File "/home/user/nose_testing/tests/test_foo.py", line 1, in <module>
import foo
ImportError: No module named foo
----------------------------------------------------------------------
Ran 1 test in 0.002s
FAILED (errors=1)
当我在 tests/ 目录内部运行时,也会出现同样的错误。根据文档和我找到的 一个例子,nose 应该会把所有父级包添加到路径中,还包括它被调用的目录,但在我的情况下似乎并没有发生。
我正在使用 Ubuntu 8.04 和 Python 2.6.2。我是手动构建和安装的 nose(不是用 setup_tools),如果这有影响的话。
9 个回答
15
对于那些以后看到这个问题的人:如果我的测试目录里没有一个 __init__.py
文件,我就会遇到导入错误。
我的目录结构是这样的:
./tests/
./test_some_random_stuff.py
如果我运行 nosetests:
nosetests -w tests
它会出现大家都遇到的 ImportError
错误。如果我添加一个空的 __init__.py
文件,它就能正常工作了:
./tests/
./__init__.py
./test_some_random_stuff.py
35
你在使用虚拟环境吗?在我的情况下,nosetests
是在 /usr/bin/nosetests
这个位置,它使用的是 /usr/bin/python
。虚拟环境里的包肯定不会在系统的路径中。下面的内容解决了这个问题:
source myvirtualenv/activate
pip install nose
which nosetests
/home/me/myvirtualenv/bin/nosetests
235
你在最上层的文件夹里有一个叫 __init__.py
的文件,这样就把这个文件夹变成了一个包。如果你把这个文件删掉,你的 nosetests
就应该能正常运行了。
如果你不删这个文件,你就得把你的 import
改成 import dir.foo
,这里的 dir
是你文件夹的名字。