背景: 自动化框架中使用yaml文件作为数据配置,使用ddt作为数据驱动来运行测试用例,由于测试用例都是基于场景去编写,目前都是一个测试类算是一条测试用例,但基于测试报告里面一个类运行的测试方法有多个,因此统计的测试用例数算的是test方法执行的次数,统计为多条
1.unittestreport的安装
pip install unittestreport
2.unittestreport的使用
编写一个run.py,将测试用例加载到suite中,使用runner运行
-
- import unittest
- import unittestreport
-
- suite = unittest.defaultTestLoader.discover(r'D:\workspace\pytest_project\debug',pattern='huge_test*.py')
-
- # 2、创建一个用例运行程序
- runner = unittestreport.TestRunner(suite,
- tester='虎哥',
- filename="test",
- report_dir=".",
- title='自动化测试报告',
- desc='测试报告',
- templates=2
- )
-
- # 3、运行测试用例
- runner.run()
3.修改unittestreport中的源码,主要是testResult.py文件
在TestResult类下面添加self.fail_case=[],用来添加失败测试类
- class TestResult(unittest.TestResult):
- def __init__(self):
- super().__init__()
-
- self.fields = {
- "success": 0,
- "all": 0,
- "fail": 0,
- "skip": 0,
- "error": 0,
- "begin_time": "",
- "results": [],
- "testClass": set()
- }
- self.sys_stdout = None
- self.sys_stderr = None
- self.outputBuffer = None
- self.fail_case = []
-
修改stopTestRun方法,重新定义success,fail,all的用例总数
- def stopTestRun(self, title=None):
- # self.fields['fail'] = len(self.failures)
- self.fields['error'] = len(self.errors)
- self.fields['skip'] = len(self.skipped)
- # self.fields['all'] = sum(
- # [self.fields['fail'], self.fields['error'], self.fields['skip'],
- #self.fields['success']])
- self.fields['testClass'] = list(self.fields['testClass'])
- #修改用例总数为class的数目
- self.fields['all'] = len(list(self.fields['testClass']))
- new_list = []
- for i in self.fail_case:
- new_list.append(list(i)[0])
- #修改失败用例数为class失败的数目
- self.fields['fail'] = len(set(new_list))
- #修改成功用例数为总数-失败数
- self.fields['success'] = self.fields['all'] - self.fields['fail']
修改addFailure方法,添加self.fail_case.append(self.fields['testClass'])
- def addFailure(self, test, err):
- super().addFailure(test, err)
- self.fail_case.append(self.fields['testClass'])
- logs = []
- test.state = '失败'
- sys.stderr.write("{}执行——>【失败】\n".format(test))
- output = self.complete_output()
- logs.append(output)
- logs.extend(traceback.format_exception(*err))
- test.run_info = logs
4.如下图,执行了2个测试类,运行了4个测试方法,有1个测试方法执行失败,测试条数总数统计为2,失败数为1,成功数为1