2012-03-15 68 views
1

我有我的所有unittests文件夹。它们都包括:为什么导入*不运行导入的代码?

if __name__ == '__main__': 
    unittest.TextTestRunner(verbosity=2).run(suite()) 

所以对它们进行测试我只需要导入测试脚本。我有一个test_all脚本,通过逐个导入它们来完成所有的单元测试。目前,这看起来像这样:

from pyMS.test import test_baseFunctions 
from pyMS.test import test_compareFeatureXMLmzML 
from pyMS.test import test_config 
from pyMS.test import test_featureFunctions 
from pyMS.test import test_fileHandling 
from pyMS.test import test_mzmlFunctions 
from pyMS.test import test_output 
from pyMS.test import test_parseFeatureXML 
from pyMS.test import test_rFunctions 
from pyMS.test import test_rPlots 
[...] 

这意味着每次添加或删除新测试时,我都需要更改导入。因此,我想使用

from pyMS.test import * 

但是,这不会运行任何代码。我很好奇导入*不运行代码的原因。 此外,如果有人知道一个解决方案(即笔记鼻子)来运行所有的单元测试,而不必一个一个地导入它们会很好。

感谢
NIEK

+5

'if __name__ == __name __:'?我希望你的意思是'if __name__ =='__main __':'? – 2012-03-15 11:24:21

+0

这看起来不是一种运行所有测试的好方法。 – 2012-03-15 11:31:35

+0

woops呀,这就是我的意思 – 2012-03-15 11:32:14

回答

1

如果您使用Python 2.7,你可以使用命令行:

python -m unittest discover 

这会自动查找并在所有子目录执行所有测试。有关更多选项,请参阅:

python -m unittest -h 

该模块已经被移植到Python 2.3及以上版本,可以下载here。如果您使用的反向移植有一个附带的命令行脚本称为UNIT2或unit2.py(你的选择),调用像这样:

unit2.py discover 

至于from XXX import *,这实际上是在文件的命名空间进口一切XXX/__init__.py。将下面的代码__init__.py自动加载任何直接的子模块:

import os 

all_files = os.listdir(os.path.dirname(__file__)) 
modules = [x for x in all_files if x.endswith(".py") and not x.startswith("_")] 
__all__ = [x.rpartition(".")[0] for x in modules] 

如何工作可以在python docs for the __all__ global variable可以找到详细的解释。

+0

我知道,可惜必须使用2.6。不过谢谢。 – 2012-03-15 11:34:11

+0

@Niek看到我更新的答案。 – 2012-03-15 11:36:20

1

运行所有测试的最简单方法(无需使用外部工具)可能使用TestLoader.discover

+1

供参考:这是在python 2.7中添加的。 – 2012-03-15 11:37:43

1

__name__仅设置为"__main__",以供解释器读取的初始python文件。这允许模块在执行if __name__ == "__main__":之后由其他模块导入而无需代码。

任何未受if __name__ == "__main__":保护的代码都将被执行。因此,您可以在每个文件中删除它,然后执行导入unittest.TextTestRunner(verbosity=2).run(suite())

更好的方法是使用unittest.TestLoader()中的方法将测试加载到套件中,然后将该套件加载到unittest.TextTestRunner。然后可以使加载程序自动化,而无需更改测试文件中的导入。将测试文件添加到目录结构中,测试将自动执行。