Python3从Excel中读接口测试数据和需要检查的响应内容

2023-11-01

需求
接口测试,包含有多种测试场景,检查response。只是一次性测试,就不弄啥测试框架了哈,简单看看。

设计表格内容
包含request 和response需要检查的code、result_code、message等在这里插入图片描述代码主要设计如下部分

  1. 从表格中读数据
  2. 打请求
  3. 检查响应数据
  4. Log

下面直接上代码
读excel数据

class Readdata():
    def __init__(self):
        nowpath = os.path.dirname(os.path.realpath(__file__))
        # datapath = os.path.join(nowpath,'..' )
        self.xlspath=nowpath +'/testdata.xlsx'
        # print(self.xlspath)
        if not os.path.exists(self.xlspath):
            raise FileNotFoundError('The test data file does not exist')

    def get_data(self,sheetname='testdata'):
        file = xlrd.open_workbook(self.xlspath, 3)
        cls = []
        clsdict_list=[]
        # Get the sheet that opens Excel
        sheet = file.sheet_by_name(sheetname)  
        nrows = sheet.nrows
        # Loop according to the number of lines
        for i in range(nrows):  
            # print(sheet.row_values(i))
            # If the first column of row i of the Excel sheet is not equal to casename then we add that row to cls[]
            if sheet.row_values(i)[0] != u'casename': 
                data_dict=dict(zip(sheet.row_values(0),sheet.row_values(i)))
                clsdict_list.append(data_dict)
                cls.append(sheet.row_values(i))
        return clsdict_list

封装request

'''
Created by Mia

'''
import json
import requests
import random
import traceback
from requests_toolbelt import MultipartEncoder
from log import log



class Request:
    def  get_request(self,url,data,headers=None,timeout=None):
        '''
        Get
        :param url:
        :param data:
        :param headers:
        :return:
        '''
        try:
            response = requests.get(url=url,params=data,headers=headers,timeout=timeout)
            time_rspconsume= response.elapsed.total_seconds()
            response_dicts={}
            response_dicts['code'] = response.status_code
            response_dicts['body'] = response.json()
            response_dicts['time_rspconsume'] = time_rspconsume
            log.info(url + '   request_data: ' +  str(json.loads(data))  + '   response_content: ' + str(response_dicts['body']))
            return response_dicts
        except TimeoutError:
            log.error("TIme out!")
            return None
        except Exception as e:
            log.error(traceback.format_exc())
            return None

    def post_requst(self, url,data ,headers,timeout):
        '''
        Post
        :param url:
        :param data:
        :param headers:
        :return:
        '''

        try:
            response = requests.post(url=url,data=data,headers=headers,timeout=timeout)
            print(response.text)
            if response.status_code != 200:
                return response.text
            else:

                time_rspconsume= response.elapsed.total_seconds()
                response_dicts={}
                response_dicts['code'] = response.status_code
                response_dicts['body'] = response.json()
                response_dicts['time_rspconsume'] = time_rspconsume
                log.info(url + '   request_data: ' +  data + '   response_content: ' + str(response_dicts['body']))
                return response_dicts
        except TimeoutError:
            log.error("TIme out!")
            return None
        except Exception as e:
            log.error(traceback.format_exc())
            return response.text

    def post_request_multipart(self,url,data,headers=None,timeout=None):
        """
        Submit a Post request in Multipart/form-data format
        :param url:
        :param data:
        :param headers:
        :param file_parm:
        :param file:
        :param type:
        :return:
        """
        try:
            m= MultipartEncoder(fields=data,boundary='-------------'+ str(random.randint(1e28,1e29)))
            response= requests(url=url,data=m,headers=headers,timeout=timeout)
            time_rspconsume= response.elapsed.total_seconds()
            response_dicts={}
            response_dicts['code'] = response.status_code
            response_dicts['body'] = response.json()
            response_dicts['time_rspconsume'] = time_rspconsume
            log.info(url + '   request_data: ' +  str(json.loads(data))  + '   response_content: ' + str(response_dicts['body']))
            return response_dicts
        except TimeoutError:
            log.error("TIme out!")
            return None
        except Exception as e:
            log.error(traceback.format_exc())
            return None

    def put_request(self,url,data,headers,timeout):
        """
        Put
        :param url:
        :param data:
        :param headers:
        :return:
        """
        try:
            response=requests.put(url=url,data=data,headers=headers,timeout=timeout)
            time_rspconsume= response.elapsed.total_seconds()
            response_dicts={}
            response_dicts['code'] = response.status_code
            response_dicts['body'] = response.json()
            response_dicts['time_rspconsume'] = time_rspconsume
            log.info(url + '   request_data: ' +   str(json.loads(data))  + '   response_content: ' + str(response_dicts['body']))
            return response_dicts
        except TimeoutError:
            log.error("TIme out!")
            return None
        except Exception as e:
            log.error(traceback.format_exc())
            return None

    def requests_main(self, url, data, method ,headers=None,timeout=None):

        if method=='post':
            result = self.post_requst(url,data,headers,timeout)
            return result
        elif method== 'get':
            result = self.get_request(url,data,headers,timeout)
            return result
        elif method=='put':
            result =self.put_request(url,data,headers,timeout)
            return result
        else:
            log.error('Currently the form form is not compatible or has errors',)
            return False

req=Request()

封装assertion

'''
Created by Mia

'''

from log import log
import json
import requests


class Assertions():
    def assert_code(self,code, except_code):
        log.info('*****begin assert code*******')
        try:
            assert int(code) == int(except_code)
            log.info('code assertion pass,code=%d, except_code=%d',code,except_code)
            return True
        except:
            log.error("Code error , code is %s ,except_code is %s"  %(str(code),str(except_code)))
            raise
    
    def assert_body(self,body,result_code,except_result_code):
        log.info('*****begin assert body*******')
        if isinstance(body,dict):
            try:
                assert int(except_result_code)==int(body[result_code])
                log.info('result_code assertion pass, result_code= %d, except_result_code= %d' %(int(body[result_code]),int(except_result_code)))
                return True
            except:
                log.error(result_code + ' is diff , result_code is %d , except_result_code is %d '  %(int(body[result_code]),int(except_result_code)))
                raise
        else:
            raise


    def assert_contain_text(self,body,expected_msg):
        log.info('*****begin assert contain text*******')
        try:
            text = json.dumps(body,ensure_ascii=False)
            assert expected_msg in  text
            log.info('excepted_msg assertion pass, text=%s, excepted_msg=%s',text,expected_msg)
            return True
        except:
            log.error('Response body Does not contain expected_msg, expected_msg is %s' %expected_msg)
            raise

    def assert_body_key(self, body, expected_msg):
        try:
            if isinstance(body, str):
                body_dict=json.loads(body)
            for  key in body_dict:
                body_dict[key]=''
            if isinstance(expected_msg):
                expected_msg_dict = json.loads(body)
                for key in expected_msg_dict:
                    expected_msg[key]=''
            assert  body_dict== expected_msg_dict
            return True
        except:
            log.error('body_dict is diff , body_dict is %s , expected_msg_dict is ' %(body_dict, expected_msg_dict))
            raise

ass= Assertions()

封装Log

'''
Created by Mia

'''
import logging ,os
class Logger(object):

    def __init__(self):
        self.cur_path = os.path.dirname(os.path.realpath(__file__))
        self.log_dir = os.path.abspath(os.path.join(self.cur_path,'Log'))
        if os.path.exists(self.log_dir):
            self.logfile_path=os.path.join(self.log_dir,"log.log")
        else:
            os.mkdir(self.log_dir)
            self.logfile_path=os.path.abspath(os.path.join(self.log_dir,"log.log"))

    def get_log(self):
        logger=logging.getLogger('V1API')
        self.fmt = '%(asctime)s - %(levelname)s - %(filename)s:%(lineno)d - %(name)s - %(message)s'
        self.formatter=logging.Formatter(self.fmt)
        self.handler= logging.FileHandler(self.logfile_path,encoding='utf-8')
        self.handler.setFormatter(self.formatter)
        logger.addHandler(self.handler)
        logger.setLevel(logging.DEBUG)
        return logger

log=Logger().get_log()

最后再调用request 和 assertion,完工

def all_api(self):
    data = self.get_data()
    for i in data:
        self.casename=i.get('casename')
        self.host=i.get('host')
        self.path = i.get('path')
        # Convert a string to a dict using ast.literal_eval
        self.headers = ast.literal_eval(i.get('headers'))
        self.url = self.host+self.path
        self.data=i.get('data')
        self.method=i.get('method')
        self.code=i.get('code')
        self.except_code=int(i.get('except_code'))
        self.result_code=i.get('result_code')
        self.except_result_code=int(i.get('except_result_code'))
        self.except_msg=i.get('except_msg')
        self.is_run=i.get('is_run')
        if self.is_run < 1:
            pass
        else:
            resp=req.requests_main(self.url,self.data,self.method,headers=self.headers) 
            ass.assert_code(resp['code'],self.except_code)
            ass.assert_body(resp['body'],self.result_code,self.except_result_code)
            ass.assert_contain_text(resp['body'],self.except_msg)

运行一下,看下log成了,不用一遍遍改postman啦,就直接把测试数据放到Excel中,也有log方便回顾测试结果
在这里插入图片描述

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Python3从Excel中读接口测试数据和需要检查的响应内容 的相关文章

随机推荐

  • Android面试心得

    过年回来到现在也一个月了 这段时间一直没写文章 这是因为我准备换工作了 一直在面试 也面试了四五家 但是效果都不是很好 虽然如此 但也算收获了一些经验 我就将我面试遇到的问题记录下来 与大家一起分享吧 本人是做游戏sdk的 所以一些问题会偏
  • JavaScript编程语言-交互:alert、prompt 和 confirm类型转换,字符串转换,数字型转换,布尔型转换,

    交互 alert prompt 和 confirm 由于我们将使用浏览器作为我们的演示环境 让我们看几个与用户交互的函数 alert prompt 和confirm alert 这个我们前面已经看到过了 它会显示一条信息 并等待用户按下 O
  • 【著名博客搬运翻译】无限过程式生成城市使用波函数坍缩算法

    Infinite procedurally generated city with the Wave Function Collapse algorithm 英文原址 https marian42 de article wfc 这是一个游戏
  • 虚拟机ubuntu18.04安装AoiAWD

    AoiAWD 轻量级EDR系统 AoiAWD 是一个由Aodzip 安恒信息 海特实验室研究员 HAC战队成员 维护的一个针对于CTF AWD模式的开源项目 专为比赛设计 便携性好 低权限运行的EDR系统 任何人都可以在 GNU AGPL
  • unity解决射线穿透UGUI的问题

    if Input GetMouseButtonDown 0 EventSystem current IsPointerOverGameObject Ray ray Camera main ScreenPointToRay Input mou
  • STL中的list容器

    以下转自http www cnblogs com BeyondAnyTime archive 2012 08 10 2631191 html STL中的list容器的一点总结 1 关于list容器 list是一种序列式容器 list容器完成
  • Excutors 线程池

    实例一 作为服务端 使用线程池接收多个客户端的TCP请求 String port 9015 ServerSocket serverSocket new ServerSocket port Executor exe Executors new
  • Base64加密解密算法【js】

    废话不多说 上代码 var Base64 private property keyStr ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789 public metho
  • 最小二乘法(Least square method)

    最小二乘法是在线性回归模型最小化均方误差时使用 其实就是对误差函数求导数 然后让其等于0 然后解出使得误差最小 本篇文章讲解最小二乘法 首先声明 此篇的内容是来自 马同学高等数学 微信公众号的内容 目录 1 日用而不知 2 最小二乘法 3
  • 模板--类型萃取

    当我们在实现数据结构vector时 我们发现使用mencpy时只能实现基本类型的拷贝 而不能实现自定义类型的拷贝 比如说字符串类型 这问题如何解决呢 在学习了模板和基于模板的类型萃取之后 我们就有方法是在实现基本类型的拷贝时使用memcpy
  • iOS 网络

    1 http介绍 请求报文 响应报文 2 http的请求方式有哪些 get post head put delete options 3 get和post方式的区别 rfc官方文档 get请求参数以 分割拼接到url后面 post请求参数在
  • WPF 下的 VlcControl 控件,播放视频过程中,闪黑屏问题的排查与解决方法

    在Wpf 下 使用 VlcControl 控件 可以实现很多强大的播放功能和解码功能 但是在使用过程中发现当视频播放时 会有预加载时间 导致出现闪黑屏的情况 如下面gif所展示 这种情况其实是VlcControl视频控件在预加载视频 从而导
  • Linux shell上传/下载命令

    sz 和 rz sz命令发送文件到本地 sz filename rz命令本地上传文件到服务器 rz 执行该命令后 在弹出框中选择要上传的文件即可
  • ADB error: device unauthorized 问题解决

    error device unauthorized This adb server s ADB VENDOR KEYS is not set Try adb kill server if that seems wrong Otherwise
  • 学习笔记(材料力学组合梁实验报告图表绘制)

    一些反思 虽然大学里做了一些物理和力学实验 会进行基本的数据处理 但是其实还是很皮毛 深以为不可得过且过 本着钻研问题 深入研究excel制图的角度开启此篇章 一 需求 1 实验时本人所测量的 叠梁和楔块梁的实验应力值 表格化 对应力 高度
  • Truncate和Delete的区别

    1 表和索引所bai占空间 当表被truncate 后 这个表和索引所占du用的空间会恢复到初始zhi大小 delete操作不dao会减少表或索引所占用的空间 2 应用范围 truncate 只能对table delete可以是table和
  • 国内好的破解软件下载站

    MSDN https msdn itellyou cn 吾爱破解 https www 52pojie cn 奥学网 https 6so so 果核剥壳 http www ghboke com zd423 http www zdfans co
  • 使用STM32测量脉宽可变的PWM波的脉冲宽度

    最近受疫情影响导致我莫得办法出去玩 打游戏一不小心又给打通关了就只能找点东西玩玩了 所以就有了下面这篇文章 搞这个东西的时候遇见一些好玩的问题 我写在第6部分 希望能帮到看到这篇小文章的同志们 1 硬件平台 stm32f103zet6 正点
  • Windows远程桌面(mstsc)笔记:Windows 7远程桌面连接Windows Server 2019报错:“您的凭证不工作“

    使用Windows 7的远程桌面连接Windows Server 2019报错 您的凭证不工作 关联 内部错误 解决方法一 在Windows Server 2019的本地组策略编辑器 gpedit msc 上修改远程连接配置 本地组策略编辑
  • Python3从Excel中读接口测试数据和需要检查的响应内容

    需求 接口测试 包含有多种测试场景 检查response 只是一次性测试 就不弄啥测试框架了哈 简单看看 设计表格内容 包含request 和response需要检查的code result code message等代码主要设计如下部分