【问题标题】:How to achieve TestNG like feature in Python Selenium or add multiple unit test in one test suite?如何在 Python Selenium 中实现类似 TestNG 的功能或在一个测试套件中添加多个单元测试?
【发布时间】:2018-01-01 13:22:53
【问题描述】:

假设我有这两个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 功能的东西,比如下面的 testng.xml,我可以在其中添加所有应该一个一个运行的测试文件

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

如果 python 中没有类似 testng.xml 的功能,那么创建测试套件并在其中包含我所有的 python 测试的其他替代方法是什么?谢谢

【问题讨论】:

  • 您使用的是哪个单元测试框架?到目前为止你搜索了什么?
  • 我正在使用鼻子测试。我已经尝试了很多方法来解决我的上述问题,但还没有得到它,所以在这里问它。

标签: python unit-testing selenium python-unittest nose


【解决方案1】:

鉴于您可能需要多种不同的原因 要构建测试套件,我会给你几个选择。

只是从目录运行测试

假设有mytests dir:

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。 在这里,我为您提供如何手动构建的基本示例 测试套件,然后用鼻子运行它:

#!/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 测试套件,已构建 并由get_suite 返回。 get_cases 函数是测试用例的地方 您选择的“已加载”(在上面的示例中,案例类刚刚导入)。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-28
    • 2010-09-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多