如何在 Python Selenium 中实现类似 TestNG 的功能或在一个测试套件中添加多个单元测试?

How to achieve TestNG like feature in Python Selenium or add multiple unit test in one test suite?

假设我有这两个 nosetest ExampleTest1.py 和 ExampleTest2.py

 ExampleTest1.py
 class ExampleTest1(TestBase):
            """
            """

        def testExampleTest1(self):
            -----
            -----

    if __name__ == "__main__":
        import nose
        nose.run()

---------------
ExampleTest2.py
class ExampleTest2(TestBase):
        """
        """

        def testExampleTest2(self):
            -----
            -----

    if __name__ == "__main__":
        import nose
        nose.run()

现在我想 运行 一个套件中的数百个测试文件。

我正在寻找类似于下面 testng.xml 之类的 TestNG 功能,我可以在其中添加我所有的测试文件,这些文件应该 运行 一个一个

 <suite name="Suite1">
      <test name="ExampleTest1">
        <classes>
           <class name="ExampleTest1" />          
        </classes>
      </test>  
      <test name="ExampleTest2">
        <classes>
           <class name="ExampleTest2" />          
        </classes>
      </test>  
    </suite> 

如果 testng.xml 之类的功能在 python 中不可用,那么还有什么其他方法可以创建测试套件并将我所有的 python 测试包含在其中?谢谢

考虑到您可能想要的原因可能有多种 构建测试套件,我会给你几个选择。

只需从目录运行测试

假设有 mytests 目录:

mytests/
├── test_something_else.py
└── test_thing.py

运行 来自该目录的所有测试都很简单

$> nosetests mytests/

例如,您可以将冒烟、单元和集成测试放入 不同的目录,仍然能够 运行 “所有测试”:

$> nosetests functional/ unit/ other/

运行 标签测试

鼻子有 attribute selector plugin。 通过这样的测试:

import unittest

from nose.plugins.attrib import attr


class Thing1Test(unittest.TestCase):

    @attr(platform=("windows", "linux"))
    def test_me(self):
        self.assertNotEqual(1, 0 - 1)

    @attr(platform=("linux", ))
    def test_me_also(self):
        self.assertFalse(2 == 1)

您将能够 运行 具有特定标签的测试:

$> nosetests -a platform=linux tests/

$> nosetests -a platform=windows tests/

运行 手动构建的测试套件

最后,nose.main支持suite参数:如果通过, discovery is not done。 在这里,我为您提供了如何手动构建的基本示例 测试套件,然后 运行 它与 Nose:

#!/usr/bin/env python

import unittest

import nose


def get_cases():
    from test_thing import Thing1Test
    return [Thing1Test]


def get_suite(cases):
    suite = unittest.TestSuite()
    for case in cases:
        tests = unittest.defaultTestLoader.loadTestsFromTestCase(case)
        suite.addTests(tests)
    return suite


if __name__ == "__main__":
    nose.main(suite=get_suite(get_cases()))

如您所见,nose.main 获得常规 unittest 测试套件,构建 return 由 get_suite 编辑。 get_cases 函数是测试用例所在的地方 您选择的是“已加载”(在上面的示例中,class 只是导入)。

如果你真的需要XML,get_cases可能就是你return的地方 class 是你从模块中得到的(通过 __import__ 或者 importlib.import_module) 你从你解析的 XML 文件中得到。 在 nose.main 调用附近,您可以使用 argparse 获取 XML 文件的路径。