测开之路五十七:实现runner和测试报告

时间:2021-09-20 20:16:56

 

准备测试用例

测开之路五十七:实现runner和测试报告

from fox.case import Case
from src import Calculator


class TestCalculator(Case):

def setUp(self):
self.calc = Calculator()
print("setUp")

def tearDown(self):
print("tearDown")

def test_add(self):
result = self.calc.add(2, 3)
self.assertEqual(result, 6, "测试加法。")
print("test_add")

def test_sub(self):
result = self.calc.sub(2, 3)
self.assertEqual(result, -1, "测试减法。")
print("test_sub")

def test_mul(self):
result = self.calc.mul(2, 3)
self.assertEqual(result, 6, "测试乘法。")
print("test_mul")

def test_div(self):
result = self.calc.div(4, 2)
self.assertEqual(result, 2, "测试除法。")
print("test_div")


if __name__ == '__main__':
pass
# main()

生成报告,这里只完成了json格式的

测开之路五十七:实现runner和测试报告

import json


class Reporter(object):

def __init__(self):
pass

def generate_report(self, results, format='console'):
if format == 'json':
self.json(results)
elif format == 'html':
self.html(results)
elif format == 'xml':
self.xml(results)
else:
self.console(results)

def console(self, results):
for result in results:
print(result)

def json(self, results):
file = open("result.json", "w", encoding="utf-8")
file.write(json.dumps(results))
file.close()

def html(self, results):
pass

def xml(self, results):
pass

runner

测开之路五十七:实现runner和测试报告

测开之路五十七:实现runner和测试报告

from fox.discovery import Discovery  # 获取测试用例
from fox.reporter import Reporter # 生成报告


class Runner(object):

def __init__(self):
pass

def run(self, path):
results = []
discovery = Discovery()
cases = discovery.find_case_by_path(path)
for case in cases:
if 'method' not in case:
continue
for method in case['method']:
if 'setUp' in case:
case['setUp']() # 执行setUp
method()
if 'tearDown' in case:
case['tearDown']() # 执行tearDown
results.append(case['result']) # 保存结果
reporter = Reporter()
reporter.generate_report(results, 'json') # 生成json格式的报告


if __name__ == '__main__':
import os

case_path = os.path.join(os.path.dirname(os.getcwd()), 'unit') # unit 文件夹
print(case_path)
runner = Runner()
runner.run(case_path)

json报告

 测开之路五十七:实现runner和测试报告