代码之家  ›  专栏  ›  技术社区  ›  Shoaib Akhtar

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

  •  8
  • Shoaib Akhtar  · 技术社区  · 9 年前

    假设我有两个测试用例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()
    

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

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

    在测试的情况下。类似xml的特性在python中不可用,那么还有什么其他方法可以创建测试套件并在其中包含我的所有python测试?谢谢

    1 回复  |  直到 8 年前
        1
  •  5
  •   paka    8 年前

    考虑到可能有多种不同的原因

    只是从目录中运行测试

    mytests

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

    从该目录运行所有测试是一个简单的过程

    $> nosetests mytests/
    

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

    $> 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()))
    

    正如你所见, 鼻子.main 获取常规 unittest 测试套件,构造 并由返回 get_suite 这个 get_cases 加载您选择的类(在上面的示例中,刚刚导入了类)。

    如果您真的需要XML, 获取案例 可能是你退回箱子的地方 __import__ importlib.import_module 鼻子.main 打电话给你 argparse