我们先下载对应的模块到我们的目录下
(venv是python的虚拟环境,这个可有可无)
使用HTMLTestRunner
我们在项目里新建一个用来放测试用例的文件夹testCase,把我们之前的登录测试移动到该文件夹里并重命名为test_login.py。
在项目目录里新建runner.py文件:
#coding=utf-8
from HTMLTestReportCN import HTMLTestReportCN
import unittest
import time
casefile = "./testCase/"
#遍历testCase里的所有test_*.py文件,添加所有测试用例。
def createsuite():
testunit = unittest.TestSuite()
discover = unittest.defaultTestLoader.discover(casefile,pattern='test_*.py',top_level_dir=None)
for test_suite in discover:
for test_case in test_suite:
testunit.addTests(test_case)
return testunit
now = time.strftime("%Y-%m-%d_%H%M",time.localtime())
#测试报告存放的位置
filepath = './result/report/' + now +'.html'
fp = open(filepath,'wb')
runner = HTMLTestReportCN.HTMLTestRunner(
stream=fp,
title='自动化报告',
tester='lin'
)
runner.run(createsuite())
fp.close()
并手动新建./result/report/文件夹
项目目录
在终端cd到项目目录,输入python runner.py
(venv) yauloladeMacBook-Air:appium yaulola$ python runner.py
.
Time Elapsed: 0:00:43.602967
(venv) yauloladeMacBook-Air:appium yaulola$
运行成功,在./result/report/里生成测试报告
修改HTMLTestRunner模板
现在我想修改测试报告的模板
1.字体太小
2.在上面加测试机型
3.增加截图,方便查看测试结果
修改字体大小
我们先打开HTMLTestReportCN.py文件,搜索px字段,找到如下控制字体大小的字段
body { font-family: Microsoft YaHei,Tahoma,arial,helvetica,sans-serif;padding: 20px; font-size: 80%; }
table { font-size: 100%; }
修改font-size: 80%为想要的字段,这里我修改为150%
添加测试机型
打开HTMLTestReportCN.py文件,添加获取机型的方法
def deviceModel():
cmd = "adb shell getprop ro.product.model"
result = ""
p = subprocess.Popen(cmd, stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
stdin=subprocess.PIPE, shell=True)
(output, err) = p.communicate()
if output != "":
result = ''.join(output.decode().split())
return result
记得要import subprocess
然后我们搜索(测试人员、开始时间、合计消耗、测试结果)其中一个字段,找到以下代码段
def getReportAttributes(self, result):
"""
Return report attributes as a list of (name, value).
Override this to add custom attributes.
"""
startTime = str(self.startTime)[:19]
duration = str(self.stopTime - self.startTime)
status = []
status.append('共 %s' % (result.success_count + result.failure_count + result.error_count))
if result.success_count: status.append('通过 %s' % result.success_count)
if result.failure_count: status.append('失败 %s' % result.failure_count)
if result.error_count: status.append('错误 %s' % result.error_count )
if status:
status = ','.join(status)
self.passrate = str("%.2f%%" % (float(result.success_count) / float(result.success_count + result.failure_count + result.error_count) * 100))
else:
status = 'none'
return [
('测试人员', self.tester),
('开始时间',startTime),
('合计耗时',duration),
('测试结果',status + ",通过率= "+self.passrate),
]
在测试人员下面添加测试机型
return [
('测试人员', self.tester),
('测试机型',deviceModel()),
('开始时间',startTime),
('合计耗时',duration),
('测试结果',status + ",通过率= "+self.passrate),
]
添加截图
打开HTMLTestReportCN.py文件,搜索(用例集/测试用例、总计、通过、失败、错误、详细)其中一个字段,找到以下代码段
用例集/测试用例总计通过失败错误详细在后面添加截图一项
用例集/测试用例总计通过失败错误详细截图搜索REPORT_CLASS_TMPL,找到以下代码
REPORT_CLASS_TMPL = r"""
%(desc)s%(count)s%(Pass)s%(fail)s%(error)s 详细在后面添加占位符
:REPORT_CLASS_TMPL = r"""
%(desc)s%(count)s%(Pass)s%(fail)s%(error)s 详细搜索%(test_list)s,找到以下代码添加占位符:
%(test_list)s
总计%(count)s%(Pass)s%(fail)s%(error)s通过率:%(passrate)s搜索REPORT_TEST_WITH_OUTPUT_TMPL找到以下代码
REPORT_TEST_WITH_OUTPUT_TMPL = r"""
%(status)s
%(script)s
""" # variables: (tid, Class, style, desc, status)
修改为
%(status)s
%(script)s
""" # variables: (tid, Class, style, desc, status)
搜索REPORT_TEST_NO_OUTPUT_TMPL找到以下代码
REPORT_TEST_NO_OUTPUT_TMPL = r"""
""" # variables: (tid, Class, style, desc, status)
修改为
REPORT_TEST_NO_OUTPUT_TMPL = r"""
""" # variables: (tid, Class, style, desc, status)
搜索row,找到以下代码
row = tmpl % dict(
tid = tid,
Class = (n == 0 and 'hiddenRow' or 'none'),
style = n == 2 and 'errorCase' or (n == 1 and 'failCase' or 'passCase'),
desc = desc,
script = script,
status = self.STATUS[n],
)
rows.append(row)
if not has_output:
return
添加截图的地址,如下:
row = tmpl % dict(
tid = tid,
Class = (n == 0 and 'hiddenRow' or 'none'),
style = n == 2 and 'errorCase' or (n == 1 and 'failCase' or 'passCase'),
desc = desc,
script = script,
status = self.STATUS[n],
screenshot = "../screen/" + deviceModel() + '_' + name + '.png',
)
rows.append(row)
if not has_output:
return
然后回到我们测试用例的脚本,添加截图功能
#coding=utf-8
import unittest
from time import sleep
from appium import webdriver
import sys
import os
PATH = lambda p: os.path.abspath(
os.path.join(os.path.dirname(__file__), p)
)
import common
class Login(unittest.TestCase):
def setUp(self):
desired_caps = common.get_desiredCaps()
url = common.url()
global driver
driver = webdriver.Remote(url,desired_caps)
sleep(3)
def test_login(self):
EditText = driver.find_elements_by_class_name("android.widget.EditText")
EditText[0].send_keys("13410066133")
EditText[1].send_keys("1234567a")
driver.find_element_by_id("com.happy.food:id/login").click()
sleep(3)
#截图函数,保存在./result/screen/文件夹里,以机型+用例名命名
driver.get_screenshot_as_file("./result/screen/" + common.deviceModel() + '_' + sys._getframe().f_code.co_name + '.png')
sleep(1)
def tearDown(self):
driver.quit()
if __name__ == '__main__':
unittest.main()
在result文件夹里新建screen目录
现在我们可以开始运行我们的测试了python runner.py
打开测试报告
修改成功!