接口自动化之测试报告

写好脚本后,需要生成一个测试报告

目录

1、安装HTMLTestRunner

1、安装HTMLTestRunner

第一步:下载后,放入lib中,下载链接:https://pan.baidu.com/s/1_e6mIgPFzu24k1Q3wbOJ9w 密码:e6nw

第二步:导入试试,没报错就没问题

扫描二维码关注公众号,回复: 2655089 查看本文章

2、应用

在run_all.py文件中,

第一步:我们可以调用discover方法,来找到所有的用例

如图:discover方法,需要传入3个参数,第一个参数start_dir,查找测试用例路径;第二个参数pattern,匹配规则;第三个参数top_level_dir,测试模块的顶层目录,如果没有顶层目录,默认为None

#找到所有用例
#用例路径 case_path="D:\\test001\\labledemo" def all_case(): discover=unittest.defaultTestLoader.discover(case_path, "test*.py") return discover

  

第二步:调用HTMLTestRunner中的方法,来生成报告

调用HTMLTestRunner方法,给定参数的值,第一个参数stream,查找测试报告路径;第二个参数title,html文件的title;第三个参数description,用例的执行情况标题 

    #将生成的报告写入文件
    fp=open(report_path,"wb")  #写测试报告
  
    runner= HTMLTestRunner.HTMLTestRunner(stream=fp,
                                          title=u'这是我的报告',
                                          description=u'用例执行情况')


    runner.run(all_case()) #调用run方法,执行
    fp.close()  #关闭,以免影响内存

  

完整代码如下:

import HTMLTestRunner
import unittest

#用例路径
case_path="D:\\test001\\labledemo"
#报告存放路径
report_path="D:\\test001\\report\\result.html"

def all_case():
    discover=unittest.defaultTestLoader.discover(case_path,
                                                 "test*.py")
    return discover
        
if __name__=="__main__":
    fp=open(report_path,"wb")  #写测试报告
  
    runner= HTMLTestRunner.HTMLTestRunner(stream=fp,
                                          title=u'这是我的报告',
                                          description=u'用例执行情况')
    runner.run(all_case()) #调用run方法,执行
    fp.close()  #关闭,以免影响内存

 第四步:优化

调用os和sys的一些方法,让代码自己找用例,和生成报告的位置

import os
import sys
reload(sys)
sys.setdefaultencoding('utf-8')

# 用例路径
case_path = os.path.join(os.getcwd(), "case")
# 报告存放路径
report_path = os.path.join(os.getcwd(), "report")

 完整代码:

import HTMLTestRunner
import unittest
import os
import sys
reload(sys)
sys.setdefaultencoding('utf-8')

#用例路径
# case_path="D:\\test001\\labledemo"
case_path=os.path.join(os.getcwd(),"case")
#报告存放路径
# report_path="D:\\test001\\report\\result.html"
report_path=os.path.join(os.getcwd(),"report")
def all_case():
    discover=unittest.defaultTestLoader.discover(start_dir=case_path,
                                                 pattern="test*.py",
                                                 top_level_dir=None)

    return discover

if __name__=="__main__":
    fp=open(report_path,"wb")
    runner= HTMLTestRunner.HTMLTestRunner(stream=fp,
                                          title=u'这是我的报告',
                                          description=u'用例执行情况')
    runner.run(all_case())
    fp.close()

  

 

猜你喜欢

转载自www.cnblogs.com/weizhideweilai/p/9452348.html