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

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

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

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截图:
在这里插入图片描述
测试报告:

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

相关实践学习
【涂鸦即艺术】基于云应用开发平台CAP部署AI实时生图绘板
【涂鸦即艺术】基于云应用开发平台CAP部署AI实时生图绘板
目录
相关文章
|
数据采集 Web App开发 数据可视化
Python零基础爬取东方财富网股票行情数据指南
东方财富网数据稳定、反爬宽松,适合爬虫入门。本文详解使用Python抓取股票行情数据,涵盖请求发送、HTML解析、动态加载处理、代理IP切换及数据可视化,助你快速掌握金融数据爬取技能。
8892 1
|
机器学习/深度学习 新能源 调度
电力系统短期负荷预测(Python代码+数据+详细文章讲解)
电力系统短期负荷预测(Python代码+数据+详细文章讲解)
928 1
|
缓存 API 网络架构
淘宝item_search_similar - 搜索相似的商品API接口,用python返回数据
淘宝联盟开放平台中,可通过“物料优选接口”(taobao.tbk.dg.optimus.material)实现“搜索相似商品”功能。该接口支持根据商品 ID 获取相似推荐商品,并返回商品信息、价格、优惠等数据,适用于商品推荐、比价等场景。本文提供基于 Python 的实现示例,包含接口调用、数据解析及结果展示。使用时需配置淘宝联盟的 appkey、appsecret 和 adzone_id,并注意接口调用频率限制和使用规范。
|
Java 数据挖掘 数据处理
(Pandas)Python做数据处理必选框架之一!(一):介绍Pandas中的两个数据结构;刨析Series:如何访问数据;数据去重、取众数、总和、标准差、方差、平均值等;判断缺失值、获取索引...
Pandas 是一个开源的数据分析和数据处理库,它是基于 Python 编程语言的。 Pandas 提供了易于使用的数据结构和数据分析工具,特别适用于处理结构化数据,如表格型数据(类似于Excel表格)。 Pandas 是数据科学和分析领域中常用的工具之一,它使得用户能够轻松地从各种数据源中导入数据,并对数据进行高效的操作和分析。 Pandas 主要引入了两种新的数据结构:Series 和 DataFrame。
932 0
|
JSON 算法 API
Python采集淘宝商品评论API接口及JSON数据返回全程指南
Python采集淘宝商品评论API接口及JSON数据返回全程指南
|
JSON API 数据安全/隐私保护
Python采集淘宝拍立淘按图搜索API接口及JSON数据返回全流程指南
通过以上流程,可实现淘宝拍立淘按图搜索的完整调用链路,并获取结构化的JSON商品数据,支撑电商比价、智能推荐等业务场景。
|
存储 监控 API
Python实战:跨平台电商数据聚合系统的技术实现
本文介绍如何通过标准化API调用协议,实现淘宝、京东、拼多多等电商平台的商品数据自动化采集、清洗与存储。内容涵盖技术架构设计、Python代码示例及高阶应用(如价格监控系统),提供可直接落地的技术方案,帮助开发者解决多平台数据同步难题。
|
存储 JSON 算法
Python集合:高效处理无序唯一数据的利器
Python集合是一种高效的数据结构,具备自动去重、快速成员检测和无序性等特点,适用于数据去重、集合运算和性能优化等场景。本文通过实例详解其用法与技巧。
442 0
|
存储 数据采集 监控
Python定时爬取新闻网站头条:从零到一的自动化实践
在信息爆炸时代,本文教你用Python定时爬取腾讯新闻头条,实现自动化监控。涵盖请求、解析、存储、去重、代理及异常通知,助你构建高效新闻采集系统,适用于金融、电商、媒体等场景。(238字)
1901 2
|
数据采集 关系型数据库 MySQL
python爬取数据存入数据库
Python爬虫结合Scrapy与SQLAlchemy,实现高效数据采集并存入MySQL/PostgreSQL/SQLite。通过ORM映射、连接池优化与批量提交,支持百万级数据高速写入,具备良好的可扩展性与稳定性。

推荐镜像

更多