是否可以 运行 所有单元测试?

Is it possible to run all unit test?

我有两个模块,有两个不同的 类 及其相应的测试 类。

 foo.py
 ------
 class foo(object):
     def fooMethod(self):
         // smthg

 bar.py
 ------
 class bar(object):
     def barMethod(self):
         // smthg

 fooTest.py
 ------
 class fooTest(unittest.TestCase):
     def fooMethodTest(self):
         // smthg

 barTest.py
 ------
 class barTest(unittest.TestCase):
     def barMethodTest(self):
         // smthg

在任何测试和源模块、文件中,我擦除 if __name__ == "__main__": 因为增加了一致性并遵守面向对象的意识形态。

就像在 Java 单元测试中一样,我正在寻找为 运行 所有单元测试创​​建一个模块。例如,

 runAllTest.py
 -------------
 class runAllTest(unittest.TestCase):
    ?????

 if __name__ == "__main__":
    ?????

我搜索了搜索引擎,但没有找到任何教程或示例。有可能这样做吗?为什么?或如何?

注意:我在 windows 机器上使用 eclipse 和 pydev 发行版。

您可以在 if __name__ == '__main__' 块中创建 TestSuite 和 运行 所有测试:

import unittest   

def create_suite():
    test_suite = unittest.TestSuite()
    test_suite.addTest(fooTest())
    test_suite.addTest(barTest())
    return test_suite

if __name__ == '__main__':
   suite = create_suite()

   runner=unittest.TextTestRunner()
   runner.run(suite)

如果您不想手动创建测试用例,请查看 this quesiton/answer, which basically creates the test cases dynamically, or use some of the features of the unittest module like test discovery feature and command line 选项 ..

我认为您正在寻找的是 TestLoader. With this you can load specific tests or modules or load everything under a given directory. Also, this post 有一些使用 TestSuite 实例的有用示例。

编辑:我通常在 test.py:

中使用的代码
if not popts.tests:
    suite = unittest.TestLoader().discover(os.path.dirname(__file__)+'/tests')
    #print(suite._tests)

    # Print outline
    lg.info(' * Going for Interactive net tests = '+str(not tvars.NOINTERACTIVE))

    # Run
    unittest.TextTestRunner(verbosity=popts.verbosity).run(suite)
else:
    lg.info(' * Running specific tests')

    suite = unittest.TestSuite()

    # Load standard tests
    for t in popts.tests:
        test = unittest.TestLoader().loadTestsFromName("tests."+t)
        suite.addTest(test)

    # Run
    unittest.TextTestRunner(verbosity=popts.verbosity).run(suite)

做两件事:

  1. 如果 -t 标志(测试)不存在,查找并加载目录中的所有测试
  2. 否则,逐个加载请求的测试

您正在寻找 nosetests.

可能需要重命名您的文件;我不确定 nose 用于查找测试文件的模式,但就我个人而言,我使用 *_test.py。可以指定您的项目用于测试文件名的自定义模式,但我记得无法让它工作,所以我最终重命名了我的测试。

您还需要遵循 PEP 328 约定来使用鼻子。我没有将 IDEs 与 Python 一起使用,但您的 IDE 可能已经遵循了它——只需阅读 PEP 并检查即可。

使用 PEP 328 directory/package 结构,您可以 运行 单独测试

nosetests path.to.class_test

请注意,我使用点来代替通常的目录分隔符(/\)。

要运行 所有 测试,只需在项目的根目录调用nosetests

使用 PyDev 右键单击​​ Eclipse 中的文件夹并选择 "Run as-> Python unit-test"。这将 运行 该文件夹中的所有测试(测试文件和方法的名称必须以 "test_" 开头)

我认为您可以 运行 在您的测试文件所在的文件夹下执行以下命令:

python -m unittest

doc中所述,"when executed without arguments Test Discovery is started"

当 运行基于内置 python unittest 模块进行单元测试时,在项目的根级别 运行

python -m unittest discover <module_name>

对于上面的具体例子,运行

python -m unittest discover .

https://docs.python.org/2/library/unittest.html