自动在 python 中处理单元测试用例



我正在使用Python的unittest和简单的代码,如下所示:

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

我们不知道这个文件中的哪个是单元测试用例文件。我想要一种解析每个文件的方法,并且只应返回具有单元测试用例的模块的名称

注意:- 我使用的是python 2.6.6,所以无法真正使用unittest.TestLoaded.discover()

考虑使用 nose 工具,它完全改变了你的单元测试生活。您只需在源文件夹根目录中运行它,如下所示:

> nosetests

然后它会自动查找所有测试用例。

如果您还想运行所有文档测试,请使用:

> nosetests --with-doctest

如果您只想以编程方式查找模块列表,nose提供了一些 API(不幸的是,不如 TestLoader.discover() 方便)。

更新:我刚刚发现(双关语)有一个名为unittest2的库,它将所有后来的unittest功能向后移植到早期版本的Python。我会为考古学家保留下面的代码,但我认为,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

使用unittest库的发现功能:

$ python -m unittest discover --start-directory my_project

最新更新