python+requests+excel+unittest+ddt接口自动化数据驱动并生成html报告(优化版)

本文涉及的产品
日志服务 SLS,月写入数据量 50GB 1个月
简介: python+requests+excel+unittest+ddt接口自动化数据驱动并生成html报告(优化版)

本文章内容是基于上海-悠悠的版本,进行了优化,增加了部分内容,详细请查阅下文。
@TOC

1、原文链接

python+requests+excel+unittest+ddt接口自动化数据驱动并生成html报告

2、修改前后框架区别

修改前:
在这里插入图片描述
修改后:
在这里插入图片描述

3、主要修改内容

  • 增加:token关联(token获取和保存)
  • 增加:cookie关联(cookie获取和保存)
  • 增加:发送邮件(使用SMTP)
  • 修改:HTML报告模板中的样式和ddt用例的标题
  • 增加:logo日志

### 4、详细修改内容说明
#### 4.1、增加token关联
##### 4.1.1、token获取get_token.py

import json
import requests
from common.operation_json import OperetionJson

class OperationHeader:

    def __init__(self, response):
        # self.response = json.loads(response)
        self.response = response

    def get_response_token(self):
        '''
        获取登录返回的token
        '''
        token = {"data":{"token":self.response['data']['token']}}
        #token = {"token": self.response['data']['token']}
        return token

    def write_token(self):
        op_json = OperetionJson()
        op_json.write_data(self.get_response_token())

    def get_response_msg(self):
        reponse_msg = {"msg":self.response['msg']}
        #print("reponse_msg:", reponse_msg)
        return reponse_msg
4.1.2、token保存operation_json.py
#coding:utf-8
import json
class OperetionJson:

    def __init__(self,file_path=None):
        if file_path  == None:
            self.file_path = '../case/cookie.json'
        else:
            self.file_path = file_path
        self.data = self.read_data()

    #读取json文件
    def read_data(self):
        with open(self.file_path, 'r', encoding='utf-8') as fp:
            data1 = fp.read()
            if len(data1) > 0:
                data = json.loads(data1)
            else:
                data = {}
            return data

    #根据关键字获取数据
    def get_data(self,id):
        print(type(self.data))
        return self.data[id]

    #写json
    def write_data(self,data):
        with open('../case/token.json','w') as fp:
            fp.truncate()  # 先清空之前的数据,再写入,这样每次登录的token都是不一样的
            fp.write(json.dumps(data))
4.1.3、token的读取base_api.py

在原代码中加入token的读取,即把token加入到heasers中

 # 请求头部headers
    try:
        headers = eval(testdata["headers"])
        if testdata["token"] == "yes":
            op_json = OperetionJson("../case/token.json")
            token = op_json.get_data('data')
            headers = dict(headers, **token)
        print("请求头部:", headers)
        log.info("请求头部:", headers)
    except:
        headers = None

4.2、增加cookie关联

实现逻辑和获取token一模一样

4.2.1、cookie获取get_token.py

直接在获取token的get_token.py中加入,而这里的token格式需要根据自己的业务修改

    def get_response_cookie(self):
        cookie1 = requests.utils.dict_from_cookiejar(self.response.cookies)
        cookie = {"data":{"gfsessionid":cookie1["gfsessionid"]}}
        # {"data": {"token": self.response['data']['token']}}
        print("cookie:", cookie)
        return cookie
    def write_cookie(self):
        op = OperetionJson()
        op.write_mydata(self.get_response_cookie())
4.2.2、cookie保存operation_json.py

直接在operation_json.py中加入

    def write_mydata(self,data):
        with open('../case/cookie.json','w') as fp:
            fp.truncate()  # 先清空之前的数据,再写入,这样每次登录的token都是不一样的
            fp.write(json.dumps(data))
4.2.3、cookie的读取base_api.py

直接在base_api.py中加入

    try:
        headers = eval(testdata["headers"])
        if testdata["cookie"] == "yes":
            op_json = OperetionJson("../case/cookie.json")
            token1 = op_json.get_data('data')
            headers = dict(headers, **token1)
        print("请求头部:", headers)
        log.info("请求头部:", headers)
    except:
        headers = None

4.3、增加邮件服务

4.3.1、邮件服务封装send_mail.py
#coding=utf-8
from email.mime.text import MIMEText
import time
import smtplib
import getpass
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.base import MIMEBase
from email import encoders
import email
import os

def sendmain(file_path,mail_to = 'xxxxx@126.com'):
    mail_from = 'yyyyy@126.com'
    f = open(file_path,'rb')
    mail_body=f.read()
    f.close()
    
    #msg = email.MIMEMultipart.MIMEMultipart()
    msg = MIMEMultipart()

    # 构造MIMEBase对象做为文件附件内容并附加到根容器  
    contype = 'application/octet-stream'  
    maintype, subtype = contype.split('/', 1)  
    ## 读入文件内容并格式化  
    data = open(file_path, 'rb')
    #file_msg = email.MIMEBase.MIMEBase(maintype, subtype)
    file_msg = MIMEBase(maintype, subtype)
    file_msg.set_payload(data.read( ))  
    data.close( )  
    #email.Encoders.encode_base64(file_msg)
    encoders.encode_base64(file_msg)
    ## 设置附件头  
    basename = os.path.basename(file_path)  
    file_msg.add_header('Content-Disposition',  
                        'attachment', filename = basename)  
    msg.attach(file_msg)  
    print(u'msg 附件添加成功')
    
    msg1 = MIMEText(mail_body,_subtype='html',_charset='utf-8')
    msg.attach(msg1)
    
    if isinstance(mail_to,str):
        msg['To'] = mail_to
    else: 
        msg['To'] = ','.join(mail_to)
    msg['From'] = mail_from
    msg['Subject'] = u'xxxxxxxxx接口自动化测试' # 邮件标题
    msg['date']=time.strftime('%Y-%m-%d-%H_%M_%S')
    print(msg['date'])

    smtp = smtplib.SMTP()
    smtp.connect('smtp.126.com')
    smtp.login('yyyyyy@126.com','aaaaaaaaaa') # 这里的密码是邮件第三方客户端认证密码
    smtp.sendmail(mail_from, mail_to, msg.as_string())
    smtp.quit()
    print('email has send out !')
'''
if __name__=='__main__':
    sendmain('../report/2017-08-18-10_18_57_result.html')
'''
4.3.2、邮件调用run_this.py

直接在主函数入口中调用

sendmain(htmlreport, mail_to=['hhhhhhhh@126.com', 'jjjjjj@126.com', 'uuuuuu@126.com']) #多个收件人的话,直接在列表中,用,号隔开即可

4.4、修改html报告模板

4.4.1、修改报告中用例的标题,修改ddt源码

①原报告用例的标题:
因为使用ddt,所以ddt格式中用例标题是test_api_数字开头的用例名称,如果要自定义需要修改ddt源码

在这里插入图片描述
②修改后的报告标题:
在这里插入图片描述
③ 如何修改?
可以参考之前的博文:
unittest中使用ddt后生成的测试报告名称如何修改?(如test_api_0修改成test_api_0_titile)

def mk_test_name(name, value, index=0):
    """
    Generate a new name for a test case.

    It will take the original test name and append an ordinal index and a
    string representation of the value, and convert the result into a valid
    python identifier by replacing extraneous characters with ``_``.

    We avoid doing str(value) if dealing with non-trivial values.
    The problem is possible different names with different runs, e.g.
    different order of dictionary keys (see PYTHONHASHSEED) or dealing
    with mock objects.
    Trivial scalar values are passed as is.

    A "trivial" value is a plain scalar, or a tuple or list consisting
    only of trivial values.
    """

    # Add zeros before index to keep order

    index = "{0:0{1}}".format(index + 1, index_len, )
    if not is_trivial(value) and type(value) is not dict: # 增加的地方,增加value的字典判断

        return "{0}_{1}_{2}".format(name, index, value.name) # 修改的地方,增加返回的值
    if type(value) is dict: # 增加的地方
        try: # 增加的地方
            value = value["name"] + "_" + value["function"] # 增加的地方,name和function必须是execl用例中整正存在的表头,这里我是把两个表头合并了(name是我表格中接口的名称,function是表格中接口的功能描述)
        except: # 增加的地方
            return "{0}_{1}".format(name.index) # 增加的地方
    try:
        value = str(value)
    except UnicodeEncodeError:
        # fallback for python2
        value = value.encode('ascii', 'backslashreplace')
    test_name = "{0}_{1}_{2}".format(name, index, value)  # 修改的地方
    return re.sub(r'\W|^(?=\d)', '_', test_name)
4.4.2、增加用例执行人

在HTMLTestRunner.py中加入如下,即获取当前用例执行的负载机的用户名

 DEFAULT_TESTER = getpass.getuser()

4.5、增加log日志

4.5.1、在框架入口中直接加入run_this.py
# LOG日志记录
    logging.basicConfig(level=logging.DEBUG,
                        format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s',
                        datefmt='%a, %d %b %Y %H:%M:%S',
                        filename=log_path + '/' + now + r"result.log",
                        filemode='w')
    logger = logging.getLogger()
    logger.info(all_case)

详细可以参考之前的博文:
Unittest接口测试生成报告和日志方法

4.5.2、在其它模块中直接使用即可
log = logging.getLogger()
log.info("请求头部:", headers)

5、其它截图

log截图:
在这里插入图片描述
测试报告:

在这里插入图片描述
邮件:
在这里插入图片描述

相关实践学习
日志服务之使用Nginx模式采集日志
本文介绍如何通过日志服务控制台创建Nginx模式的Logtail配置快速采集Nginx日志并进行多维度分析。
目录
相关文章
|
4天前
|
开发框架 JSON API
震撼发布!Python Web开发框架下的RESTful API设计全攻略,让数据交互更自由!
【7月更文挑战第22天】在Python Web开发中,设计高效的RESTful API涉及选择框架(如Flask或Django)、明确资源及使用HTTP方法(GET, POST, PUT, DELETE)来操作数据。响应格式通常是JSON,错误处理也很重要。示例展示了使用Flask创建图书管理API,包括版本控制、文档化、安全性和性能优化是最佳实践。这样的API使数据交互更顺畅。
26 2
|
5天前
|
SQL 存储 数据库
数据聚合大揭秘!Python如何一键整合海量信息,洞察数据背后的秘密?
【7月更文挑战第21天】在数据驱动时代,Python以强大库支持,如Pandas与SQLAlchemy,轻松聚合分析海量信息。Pandas简化数据整合,从CSV文件加载数据,利用`pd.concat()`合并,`groupby()`进行聚合分析,揭示销售趋势。SQLAlchemy则无缝链接数据库,执行SQL查询,汇总复杂数据。Python一键操作,开启数据洞察之旅,无论源数据格式,均能深入挖掘价值。
15 0
|
5天前
|
机器学习/深度学习 数据采集 数据挖掘
数据界的整容大师!Python如何让你的数据‘洗心革面’,焕然一新?
【7月更文挑战第21天】在数据科学领域,Python扮演着数据“整容大师”的角色,通过清洗、重塑与特征工程,将原始数据美化成分析佳品。首先,利用Pandas清洗数据,删除或填充缺失值,清除异常值,如同洁面般净化数据。其次,通过数据重塑与格式化,如按年龄分组统计薪资并优雅展示,赋予数据直观可读性,好比化妆塑形。最后,特征工程创造新维度,如年龄分组,提升数据分析价值,这全过程是对数据价值的深度挖掘和精细打磨。
|
4天前
|
机器学习/深度学习 搜索推荐 TensorFlow
使用Python实现深度学习模型:个性化推荐与广告优化
【7月更文挑战第22天】 使用Python实现深度学习模型:个性化推荐与广告优化
133 70
|
1天前
|
机器学习/深度学习 数据可视化 vr&ar
|
3天前
|
算法 搜索推荐 开发者
别再让复杂度拖你后腿!Python 算法设计与分析实战,教你如何精准评估与优化!
【7月更文挑战第23天】在Python编程中,掌握算法复杂度—时间与空间消耗,是提升程序效能的关键。算法如冒泡排序($O(n^2)$时间/$O(1)$空间),或使用Python内置函数找最大值($O(n)$时间),需精确诊断与优化。数据结构如哈希表可将查找从$O(n)$降至$O(1)$。运用`timeit`模块评估性能,深入理解数据结构和算法,使Python代码更高效。持续实践与学习,精通复杂度管理。
22 9
|
2天前
|
数据可视化 数据挖掘 Python
数据界的颜值担当!Python数据分析遇上Matplotlib、Seaborn,可视化美出新高度!
【7月更文挑战第24天】在数据科学领域,Python的Matplotlib与Seaborn将数据可视化升华为艺术,提升报告魅力。Matplotlib作为基石,灵活性强,新手友好;代码示例展示正弦波图的绘制与美化技巧。Seaborn针对统计图表,提供直观且美观的图形,如小提琴图,增强数据表达力。两者结合,创造视觉盛宴,如分析电商平台销售数据时,Matplotlib描绘趋势,Seaborn揭示类别差异,共塑洞察力强的作品,使数据可视化成为触动人心的艺术。
22 7
|
3天前
|
数据采集 Web App开发 存储
Python-数据爬取(爬虫)
【7月更文挑战第24天】
30 7
|
1天前
|
机器学习/深度学习 数据采集 算法
数据海洋中的导航者:Scikit-learn库引领Python数据分析与机器学习新航向!
【7月更文挑战第26天】在数据的海洋里,Python以强大的生态成为探索者的首选,尤其Scikit-learn库(简称sklearn),作为一颗璀璨明珠,以高效、灵活、易用的特性引领数据科学家们破浪前行。无论新手还是专家,sklearn提供的广泛算法与工具支持从数据预处理到模型评估的全流程。秉承“简单有效”的设计哲学,它简化了复杂模型的操作,如线性回归等,使用户能轻松比较并选择最优方案。示例代码展示了如何简洁地实现线性回归分析,彰显了sklearn的强大能力。总之,sklearn不仅是数据科学家的利器,也是推动行业进步的关键力量。
|
4天前
|
数据可视化 数据挖掘 开发者
数据可视化新纪元!Python + Matplotlib + Seaborn,让你的数据故事生动起来!
【7月更文挑战第23天】在数据驱动时代,Python通过Matplotlib与Seaborn引领数据可视化新纪元。Matplotlib基础强大,提供广泛绘图选项;Seaborn则简化流程,图表更美观,适合快速可视化。两者结合,轻松应对复杂定制需求,将数据转化为生动故事,支持决策与交流。
18 6