作者:郝泓帥_169 | 来源:互联网 | 2023-01-28 12:07
假设我有这两个鼻子测试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,在这里我可以添加所有应该逐个运行的测试文件
如果python中没有testng.xml之类的功能,那么还有什么其他方法可以创建测试套件并在其中包含我所有的python测试呢?谢谢
1> 小智..:
鉴于您可能要构建测试套件的原因可能有多种,我将提供几种选择。
仅从目录运行测试
假设有mytests
目录:
mytests/
??? test_something_else.py
??? test_thing.py
从该目录运行所有测试很容易
$> nosetests mytests/
例如,您可以将烟雾测试,单元测试和集成测试放入不同的目录中,但仍然可以运行“所有测试”:
$> nosetests functional/ unit/ other/
通过标签运行测试
鼻子有
属性选择器插件。用这样的测试:
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
参数:如果传递了,
则不会完成发现。在这里,我为您提供了有关如何手动构造测试套件然后使用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
由构造和返回的常规测试套件get_suite
。该get_cases
功能是您选择的测试用例被“加载”的地方(例如,上面的案例类仅被导入)。
如果您确实需要XML,get_cases
则可以在这里返回从通过解析的XML文件获得的模块(通过__import__
或
导入importlib.import_module
)获得的案例类。在nose.main
通话附近,您可以argparse
用来获取XML文件的路径。