airtest聚合报告2.0优化版本
问题:前一个博客中写了https://blog.csdn.net/zhichuan0307/article/details/116461607,博客中是将报告聚合到了一起,但是在用例执行中,发现有问题,聚合报告中有record_ui,查询一直都没查到原因,看报告中也没有record_ui字段显示这个会有时间损耗,导致效率下降,UI自动化本身存在时间问题,如果加上这个损耗时间,全量跑的话,时间会更长
·
问题:
前一个博客中写了https://blog.csdn.net/zhichuan0307/article/details/116461607,博客中是将报告聚合到了一起,但是在用例执行中,发现有问题,聚合报告中有record_ui,查询一直都没查到原因,看报告中也没有record_ui字段显示这个会有时间损耗,导致效率下降,UI自动化本身存在时间问题,如果加上这个损耗时间,全量跑的话,时间会更长,所以进行了优化

解决思路:
之前使用的方式是jingja2,将模板聚合到一起,生成报告时,将跑出的结果添加到result中,这种思路不变,前一个是通过继承了AirtestCase,然后使用run_script方法
这里直接使用unittest框架
上代码
# coding:utf-8
import logging
logger = logging.getLogger("airtest")
logger.setLevel(logging.ERROR)
import airtest.report.report as report
import jinja2
import io
from airtest.core.api import *
import unittest
from datetime import datetime
import traceback, time, os, subprocess
from airtest.core.android.adb import *
from airtest.core.android.android import *
auto_setup(__file__)
# 解析给定文件夹,列出所有的用例.air
def collect_testCases(filePath):
fileList = os.listdir(filePath)
# 跑单独一个用例
# fileList = ['login.air']
# 跑多个用例
# fileList = ['boutique_buy.air', 'boutique_buy_shoppingCart.air', 'view_event.air', 'view_news.air', 'car_owner_service.air', 'explore_enjoy.air', 'performanceCar_club.air', 'my_territory.air', 'my_medal.air', 'my_appointment.air', 'my_fans.air']
# 跑所有生产用例
fileList = [file for file in fileList if file.endswith('.air')]
return fileList
# 获取当前设备的序列号
def get_devices():
str1 = '\r\n'
deviceInfo = subprocess.check_output("adb devices").split(bytes(str1, 'UTF-8'))
num = str(deviceInfo[1])
devices_num = num.split('\\')[0].strip(" b' ")
return devices_num
# 在log下创建已时间命名的文件夹
def create_path(path_name):
if not os.path.exists('log'):
os.mkdir('log')
time.sleep(0.1)
if not os.path.exists('log/{}'.format(path_name)):
os.mkdir('log/{}'.format(path_name))
time.sleep(0.1)
class RunCases(unittest.TestCase):
def setUp(self):
print('这里首先执行,嘿嘿。。。')
pass
def test_run_case(self):
results = []
path = os.getcwd()
fileList = collect_testCases(path)
for fileDir in fileList:
script = os.path.join(path, fileDir)
filename = fileDir.split('.')[0]
# 构造log目录
datestr = datetime.now().strftime("%Y%m%d%H%M%S")
log_dir = 'log' + '_' + datestr
# 这里创建路径
create_path(log_dir)
# 运行airtest run命令
try:
os.system(
'airtest run {} --device ios:///http://127.0.0.1:8100 --log log/{}/{}'.format(
fileDir, log_dir, filename))
except Exception:
log("{}运行出错啦".format(filename), traceback.format_exc())
finally:
os.system(
'airtest report {0} --log_root log/{1}/{2} --outfile log/{1}/{2}/log.html --lang zh --plugin airtest_selenium.report poco.utils.airtest.report'.format(
fileDir, log_dir, filename, log_dir))
log_file = os.path.join(log_dir, filename)
log_path = os.path.join(path, 'log', log_file)
output_file = log_path + 'log.txt'
rpt = report.LogToHtml(script, log_path)
rpt.report("log_template.html", output_file=output_file)
result = {}
result["name"] = fileDir.replace('.air', '')
result["result"] = rpt.test_result
result['run_start'] = rpt.run_start
result['run_end'] = rpt.run_end
run_time = int(result['run_end'] - result['run_start'])
result['run_time'] = run_time
result['log_path'] = log_path
print(result)
results.append(result)
# 生成聚合报告
env = jinja2.Environment(
loader=jinja2.FileSystemLoader(path),
extensions=(),
autoescape=True
)
template = env.get_template("summary_template.html", path)
html = template.render({"results": results})
# 将报告聚合一起
output_file = os.path.join(log_path, "summary.html")
with io.open(output_file, 'w', encoding="utf-8") as f:
f.write(html)
print(output_file)
def tearDown(self):
print('这是最后执行的步骤。。。')
pass
if __name__ == "__main__":
print(collect_testCases('../iOS_Pro'))
suite = unittest.TestSuite()
suite.addTest(RunCases("test_run_case"))
runner = unittest.TextTestRunner()
runner.run(suite)
代码中是运行iOS的,运行安卓需要修改为
os.system(
'airtest run {} --device Android://127.0.0.1:5037/{}?cap_method=JAVACAP^&^&ori_method=ADBOR --log log/{}/{}'.format(
fileDir, get_devices(), log_dir, log_name))
这里可以写一个获取设备信息的方法,我们还在完善,另外聚合报告中增加了每个用例运行时间
<!DOCTYPE html>
<html>
<head>
<title>测试结果汇总</title>
<style>
.fail {
color: #ff0000;
width: 7emem;
text-align: center;
}
.success {
color: green;
width: 7emem;
text-align: center;
}
.details-col-elapsed {
width: 7em;
text-align: center;
}
.details-col-msg {
width: 7em;
text-align: center;
background-color:#ccc;
}
</style>
</head>
<body>
<div>
<div><h2>Test Statistics</h2></div>
<table width="800" border="thin" cellspacing="0" cellpadding="0">
<tr width="600">
<th width="300" class='details-col-msg'>案例名称</th>
<th class='details-col-msg'>执行结果</th>
<th width="300" class='details-col-msg'>运行时间</th>
</tr>
{% for r in results %}
<tr width="600">
<td class='details-col-elapsed'><a href="{{r.log_path}}/log.html" target="view_window">{{r.name}}</a></td>
<td class="{{'success' if r.result else 'fail'}}">{{"成功" if r.result else "失败"}}</td>
<td class="details-col-elapsed">{{r.run_time}}s</td>
</tr>
{% endfor %}
</table>
</div>
</body>
</html>
如此操作过后,就可以去掉报告中record_ui步骤,用例数多的话,可以节省很多时间
更多推荐


所有评论(0)