我正在使用Python的单元测试,简单的代码如下:
suite = unittest.TestSuite()
suite.addTest(unittest.defaultTestLoader.loadTestsFromTestCase(module1))
suite.addTest(unittest.defaultTestLoader.loadTestsFromTestCase(module2))我想让我的测试套件自动解析所有模块,并搜索我们编写的所有单元测试用例文件?例如
有5个文件,
1)。f1.py
2)。f2.py
3)。f3.py
4)。f4.py
5)。f5.py
我们不知道哪个文件是单元测试用例文件。我想要一种解析每个文件的方法,并且只返回具有单元测试用例的模块的名称
注意:-我使用的是Python2.6.6,所以不能真正使用unittest.TestLoaded.discover()
发布于 2014-02-18 14:12:42
考虑使用nose工具,它完全改变了您的单元测试生活。只需在源文件夹根目录中运行它,如下所示:
> nosetests然后它会自动找到所有的测试用例。
如果您还想运行所有文档测试,请使用:
> nosetests --with-doctest如果您只想以编程方式查找模块列表,nose提供了一些API (不幸的是,没有TestLoader.discover()那么方便)。
PythonUpdatePythonUpdatePythonUpdatePythonUpdatePythonUpdatePythonUpdatePythonUpdatePythonUpdatePythonUpdatePythonUpdatePythonUpdatePythonUpdatePythonUpdatePythonUpdatePythonUpdatePythonUpdatePythonUpdate:我刚刚发现(用双关语),有一个名为unittest2的库,它将所有后来的unittest特性移植到早期版本。我将为考古学家保留下面的代码,但我认为,unittest2是一种更好的方法。
import nose.loader
import nose.suite
import types
def _iter_modules(tests):
'''
Recursively find all the modules containing tests.
(Some may repeat)
'''
for item in tests:
if isinstance(item, nose.suite.ContextSuite):
for t in _iter_modules(item):
yield t
elif isinstance(item.context, types.ModuleType):
yield item.context.__name__
else:
yield item.context.__module__
def find_test_modules(basedir):
'''
Get a list of all the modules that contain tests.
'''
loader = nose.loader.TestLoader()
tests = loader.loadTestsFromDir(basedir)
modules = list(set(_iter_modules(tests))) # remove duplicates
return modules发布于 2020-08-05 17:46:38
使用unittest库的discovery特性:
$ python -m unittest discover --start-directory my_projecthttps://stackoverflow.com/questions/21845596
复制相似问题