Python鼻子导入错误

Python鼻子导入错误

本文介绍了Python鼻子导入错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我似乎无法获得鼻子测试框架来识别测试中的模块文件结构中的脚本.我设置了最简单的示例来演示该问题.我将在下面解释.

I can't seem to get the nose testing framework to recognize modules beneath my test script in the file structure. I've set up the simplest example that demonstrates the problem. I'll explain it below.

这是打包文件的结构:

./__init__.py
./foo.py
./tests
   ./__init__.py
   ./test_foo.py

foo.py包含:

def dumb_true():
    return True

tests/test_foo.py包含:

tests/test_foo.py contains:

import foo

def test_foo():
    assert foo.dumb_true()

两个 init .py文件均为空

Both init.py files are empty

如果我在主目录(foo.py所在的目录)中运行nosetests -vv,则会得到:

If I run nosetests -vv in the main directory (where foo.py is), I get:

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/目录中运行时,出现相同的错误.根据文档和一个示例,我发现,鼻子应该添加所有父程序包会打包到该路径以及从中调用该路径的目录,但是在我看来,这似乎没有发生.

I get the same error when I run from inside the tests/ directory. According to the documentation and an example I found, nose is supposed to add all parent packages to the path as well as the directory from which it is called, but this doesn't seem to be happening in my case.

我正在使用Python 2.6.2运行Ubuntu 8.04.如果重要的话,我已经手动构建并安装了鼻子(不使用setup_tools).

I'm running Ubuntu 8.04 with Python 2.6.2. I've built and installed nose manually (not with setup_tools) if that matters.

推荐答案

您在顶级目录中有一个__init__.py.这使其成为一个包装.如果将其删除,则nosetests应该可以使用.

You've got an __init__.py in your top level directory. That makes it a package. If you remove it, your nosetests should work.

如果不删除它,则必须将import更改为import dir.foo,其中dir是目录的名称.

If you don't remove it, you'll have to change your import to import dir.foo, where dir is the name of your directory.

这篇关于Python鼻子导入错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-13 22:45