我正在尝试使用nosetests在如下的目录结构中运行测试
src
- file1.py
- ...
test
- helper.py
- test_file1.py如您所见,test_file1.py有一些测试file1.py的函数,因此它像这样导入file1.py:
# In file1.py
import file1
import helper
# Tests go here...我还使用了一个内置了一些整洁功能的helper.py文件,这样我就可以更轻松地创建测试。这个功能是通过在我的实际代码中扩展几个类并覆盖一些方法来实现的。
# In helper.py
import file1
# Use stuff in file1.py我很难理解nose是如何通过它的自定义导入器导入这些东西的。我能够通过在src目录中运行nosetest ../tests来让我的测试文件导入file1.py,但我目前收到一个类似以下内容的错误:
File helper.py:
ImportError: cannot import name file1 nose是如何导入的,有没有一种方法可以让它把我所有的测试/src文件放在一起,这样它们就可以互相导入,而我把它们放在不同的文件夹中?
发布于 2014-10-04 02:43:36
看到您使用nosetests ../tests执行测试,我假设它们是从tests文件夹本身执行的。因此,src目录中的文件不会添加到sys.path中,因此会出现错误。
要解决此问题,可以执行以下操作:
nosetests将能够自己识别src和test (或tests)目录,并在运行测试之前将它们添加到sys.path 请注意,您也可以省略nosetest的最后一个参数,因为默认情况下它会从当前目录运行测试。否则,如果测试不在启动nosetests的目录中,您可以使用--where=<path-to-tests>参数(或者简称为-w)来定义它的位置。例如,您可以从src目录执行测试,甚至不需要设置PYTHONPATH (因为当前目录将默认添加到sys.path中),如下所示:nosetests -w ../tests。
最后,尽管这本身是非常有问题的,但是:组织Python源代码的最常见的方法是让python文件和包直接从项目目录开始,并在它们测试的包的" test“子包中进行测试。因此,在您的情况下,它将是:
/file1.py
/test/helper.py
/test/test_file1.py或者更好:
/myproject/__init__.py
/myproject/file1.py
/myproject/test/__init__.py
/myproject/test/helper.py
/myproject/test/test_file1.py(后者,前提是您还在测试源代码中使用了正确的导入,例如from .. import file1)。
在这种情况下,只需使用nosetests而不带任何参数,即可从项目的根目录运行测试。
无论如何,nosetests足够灵活,可以使用任何结构-使用任何看起来更适合您和项目的结构。
有关What is the best project structure for a Python application?中的项目结构的更多信息
发布于 2016-03-31 23:55:39
这似乎是我在鼻子测试中遇到的一个问题:
Importing with Python and Nose Tests
我发现的变通方法是插入一个try..except块,这样python和nosetest命令就可以在同一个目录上运行,如下所示:
(1)在您的主文件中,在最顶部的任何其他内容之前添加:
# In file1.py
try:
# This will allow you to do python file1.py inside the src directory
from file2 import *
from helper import *
except:
# This will allow you to run nosetests in the directory just above
# the src and test directories.
from src.file1 import *
from src.helper import *(2)在您的test.py文件中添加:
from src.file2 import *
from src.helper import * https://stackoverflow.com/questions/26175507
复制相似问题