Python+requests+unittest+excel搭建接口自动化测试框架

news/2024/11/22 22:04:31/

一、框架结构:

工程目录

代码:基于python2编写

二、Case文件设计

三、基础包 base

3.1 封装get/post请求(runmethon.py)

import requests
import json
class RunMethod:def post_main(self,url,data,header=None):res = Noneif header !=None:res = requests.post(url=url,data=data,headers=header)else:res = requests.post(url=url,data=data)return res.json()def get_main(self,url,data=None,header=None):res = Noneif header !=None:res = requests.get(url=url,data=data,headers=header,verify=False)else:res = requests.get(url=url,data=data,verify=False)return res.json()def run_main(self,method,url,data=None,header=None):res = Noneif method == 'Post':res = self.post_main(url,data,header)else:res = self.get_main(url,data,header)return json.dumps(res,ensure_ascii=False,sort_keys=True,indent=2)

3.2 封装mock(mock.py)

from mock import mock
#模拟mock 封装
def mock_test(mock_method,request_data,url,method,response_data):mock_method = mock.Mock(return_value=response_data)res = mock_method(url,method,request_data)return res

四、数据操作包 operation_data

4.1 获取excel单元格中的内容(get_data.py)

#coding:utf-8
from tool.operation_excel import OperationExcel
import data_config
from tool.operation_json import OperetionJson
from tool.connect_db import OperationMysql
class GetData:def __init__(self):self.opera_excel = OperationExcel()#去获取excel行数,就是case的个数def get_case_lines(self):return self.opera_excel.get_lines()#获取是否执行def get_is_run(self,row):flag = Nonecol = int(data_config.get_run())run_model = self.opera_excel.get_cell_value(row,col)if run_model == 'yes':flag = Trueelse:flag = Falsereturn flag#是否携带headerdef is_header(self,row):col = int(data_config.get_header())header = self.opera_excel.get_cell_value(row,col)if header != '':return headerelse:return None#获取请求方式def get_request_method(self,row):col = int(data_config.get_run_way())request_method = self.opera_excel.get_cell_value(row,col)return request_method#获取urldef get_request_url(self,row):col = int(data_config.get_url())url = self.opera_excel.get_cell_value(row,col)return url#获取请求数据def get_request_data(self,row):col = int(data_config.get_data())data = self.opera_excel.get_cell_value(row,col)if data == '':return Nonereturn data#通过获取关键字拿到data数据def get_data_for_json(self,row):opera_json = OperetionJson()request_data = opera_json.get_data(self.get_request_data(row))return request_data#获取预期结果def get_expcet_data(self,row):col = int(data_config.get_expect())expect = self.opera_excel.get_cell_value(row,col)if expect == '':return Nonereturn expect#通过sql获取预期结果def get_expcet_data_for_mysql(self,row):op_mysql = OperationMysql()sql = self.get_expcet_data(row)res = op_mysql.search_one(sql)return res.decode('unicode-escape')def write_result(self,row,value):col = int(data_config.get_result())self.opera_excel.write_value(row,col,value)#获取依赖数据的keydef get_depend_key(self,row):col = int(data_config.get_data_depend())depent_key = self.opera_excel.get_cell_value(row,col)if depent_key == "":return Noneelse:return depent_key#判断是否有case依赖def is_depend(self,row):col = int(data_config.get_case_depend())depend_case_id = self.opera_excel.get_cell_value(row,col)if depend_case_id == "":return Noneelse:return depend_case_id#获取数据依赖字段def get_depend_field(self,row):col = int(data_config.get_field_depend())data = self.opera_excel.get_cell_value(row,col)if data == "":return Noneelse:return data

4.2 获取excel中每个列(data_config.py)

#coding:utf-8
class global_var:#case_idId = '0'request_name = '1'url = '2'run = '3'request_way = '4'header = '5'case_depend = '6'data_depend = '7'field_depend = '8'data = '9'expect = '10'result = '11'
#获取caseid
def get_id():return global_var.Id#获取url
def get_url():return global_var.urldef get_run():return global_var.rundef get_run_way():return global_var.request_waydef get_header():return global_var.headerdef get_case_depend():return global_var.case_dependdef get_data_depend():return global_var.data_dependdef get_field_depend():return global_var.field_dependdef get_data():return global_var.datadef get_expect():return global_var.expectdef get_result():return global_var.resultdef get_header_value():return global_var.header

4.3 解决数据依赖(dependent.py )

#coding:utf-8
import sys
import json
sys.path.append('C:/Users/lxz/Desktop/InterFace_JIA')
from tool.operation_excel import OperationExcel
from base.runmethod import RunMethod
from operation_data.get_data import GetData
from jsonpath_rw import jsonpath,parse
class DependdentData:def __init__(self,case_id):self.case_id = case_idself.opera_excel = OperationExcel()self.data = GetData()#通过case_id去获取该case_id的整行数据def get_case_line_data(self):rows_data = self.opera_excel.get_rows_data(self.case_id)return rows_data#执行依赖测试,获取结果def run_dependent(self):run_method = RunMethod()row_num  = self.opera_excel.get_row_num(self.case_id)request_data = self.data.get_data_for_json(row_num)#header = self.data.is_header(row_num)method = self.data.get_request_method(row_num)url = self.data.get_request_url(row_num)res = run_method.run_main(method,url,request_data)return json.loads(res)#根据依赖的key去获取执行依赖测试case的响应,然后返回def get_data_for_key(self,row):depend_data = self.data.get_depend_key(row)response_data = self.run_dependent()json_exe = parse(depend_data)madle = json_exe.find(response_data)return [math.value for math in madle][0]if __name__ == '__main__':order = {"data": {"_input_charset": "utf-8","body": "京东订单-1710141907182334","it_b_pay": "1d","notify_url": "http://order.imooc.com/pay/notifyalipay","out_trade_no": "1710141907182334","partner": "2088002966755334","payment_type": "1","seller_id": "yangyan01@tcl.com","service": "mobile.securitypay.pay","sign": "kZBV53KuiUf5HIrVLBCcBpWDg%2FnzO%2BtyEnBqgVYwwBtDU66Xk8VQUTbVOqDjrNymCupkVhlI%2BkFZq1jOr8C554KsZ7Gk7orC9dDbQlpr%2BaMmdjO30JBgjqjj4mmM%2Flphy9Xwr0Xrv46uSkDKdlQqLDdGAOP7YwOM2dSLyUQX%2Bo4%3D", "sign_type": "RSA","string": "_input_charset=utf-8&body=京东订单-1710141907182334&it_b_pay=1d&notify_url=http://order.imooc.com/pay/notifyalipay&out_trade_no=1710141907182334&partner=2088002966755334&payment_type=1&seller_id=yangyan01@tcl.com&service=mobile.securitypay.pay&subject=京东订单-1710141907182334&total_fee=299&sign=kZBV53KuiUf5HIrVLBCcBpWDg%2FnzO%2BtyEnBqgVYwwBtDU66Xk8VQUTbVOqDjrNymCupkVhlI%2BkFZq1jOr8C554KsZ7Gk7orC9dDbQlpr%2BaMmdjO30JBgjqjj4mmM%2Flphy9Xwr0Xrv46uSkDKdlQqLDdGAOP7YwOM2dSLyUQX%2Bo4%3D&sign_type=RSA", "subject": "京东订单-1710141907182334","total_fee": 299},"errorCode": 1000,"errorDesc": "成功","status": 1,"timestamp": 1507979239100}res = "data.out_trade_no"json_exe = parse(res)madle = json_exe.find(order)print [math.value for math in madle][0]

五、工具类包 tool

5.1 操作excel (operation_excel.py)

#coding:utf-8
import xlrd
from xlutils.copy import copy
class OperationExcel:def __init__(self,file_name=None,sheet_id=None):if file_name:self.file_name = file_nameself.sheet_id = sheet_id    else:self.file_name = '../dataconfig/case1.xls'self.sheet_id = 0self.data = self.get_data()#获取sheets的内容def get_data(self):data = xlrd.open_workbook(self.file_name)tables = data.sheets()[self.sheet_id]return tables#获取单元格的行数def get_lines(self):tables = self.datareturn tables.nrows#获取某一个单元格的内容def get_cell_value(self,row,col):return self.data.cell_value(row,col)#写入数据def write_value(self,row,col,value):'''写入excel数据row,col,value'''read_data = xlrd.open_workbook(self.file_name)write_data = copy(read_data)sheet_data = write_data.get_sheet(0)sheet_data.write(row,col,value)write_data.save(self.file_name)#根据对应的caseid 找到对应行的内容def get_rows_data(self,case_id):row_num = self.get_row_num(case_id)rows_data = self.get_row_values(row_num)return rows_data#根据对应的caseid找到对应的行号def get_row_num(self,case_id):num = 0clols_data = self.get_cols_data()for col_data in clols_data:if case_id in col_data:return numnum = num+1#根据行号,找到该行的内容def get_row_values(self,row):tables = self.datarow_data = tables.row_values(row)return row_data#获取某一列的内容def get_cols_data(self,col_id=None):if col_id != None:cols = self.data.col_values(col_id)else:cols = self.data.col_values(0)return colsif __name__ == '__main__':opers = OperationExcel()print opers.get_cell_value(1,2)

5.2判断字符串包含,判断字典是否相等(common_util.py)

#coding:utf-8
import json
class CommonUtil:def is_contain(self,str_one,str_two):'''判断一个字符串是否再另外一个字符串中str_one:查找的字符串str_two:被查找的字符串'''flag = Noneif isinstance(str_one,unicode):str_one = str_one.encode('unicode-escape').decode('string_escape')return cmp(str_one,str_two)if str_one in str_two:flag = Trueelse:flag = Falsereturn flagdef is_equal_dict(self,dict_one,dict_two):'''判断两个字典是否相等'''if isinstance(dict_one,str):dict_one = json.loads(dict_one)if isinstance(dict_two,str):dict_two = json.loads(dict_two)return cmp(dict_one,dict_two)

5.3 操作header(operation_herder.py)

# coding:utf-8
import requests
import json
from operation_json import OperetionJsonclass OperationHeader:def __init__(self ,response):self.response = json.loads(response)def get_response_url(self):'''获取登录返回的token的url'''url = self.response['data']['url'][0]return urldef get_cookie(self):'''获取cookie的jar文件'''url = self.get_response_url( ) +"&callback=jQuery21008240514814031887_1508666806688&_=1508666806689"cookie = requests.get(url).cookiesreturn cookiedef write_cookie(self):cookie = requests.utils.dict_from_cookiejar(self.get_cookie())op_json = OperetionJson()op_json.write_data(cookie)if __name__ == '__main__':url = "http://www.jd.com/passport/user/login"data = {"username" :"18513199586","password" :"111111","verify" :"","referer" :"https://www.jd.com"}res = json.dumps(requests.post(url ,data).json())op_header = OperationHeader(res)op_header.write_cookie()

5.4 操作json文件(operation_json.py)

#coding:utf-8
import json
class OperetionJson:def __init__(self,file_path=None):if file_path  == None:self.file_path = '../dataconfig/user.json'else:self.file_path = file_pathself.data = self.read_data()#读取json文件def read_data(self):with open(self.file_path) as fp:data = json.load(fp)return data#根据关键字获取数据def get_data(self,id):print type(self.data)return self.data[id]#写jsondef write_data(self,data):with open('../dataconfig/cookie.json','w') as fp:fp.write(json.dumps(data))if __name__ == '__main__':opjson = OperetionJson()print opjson.get_data('shop')

5.5 操作数据库(connect_db.py)

 #coding:utf-8
import MySQLdb.cursors
import json
class OperationMysql:def __init__(self):self.conn = MySQLdb.connect(host='localhost',port=3306,user='root',passwd='123456',db='le_study',charset='utf8',cursorclass=MySQLdb.cursors.DictCursor)self.cur = self.conn.cursor()#查询一条数据def search_one(self,sql):self.cur.execute(sql)result = self.cur.fetchone()result = json.dumps(result)return resultif __name__ == '__main__':op_mysql = OperationMysql()res = op_mysql.search_one("select * from web_user where Name='ailiailan'")print res

5.6 发送报告邮件(send_email.py)

#coding:utf-8
import smtplib
from email.mime.text import MIMEText
class SendEmail:global send_userglobal email_hostglobal passwordemail_host = "smtp.163.com"send_user = "jiaxiaonan666@163.com"password = "jia_668"def send_mail(self,user_list,sub,content):user = "jiaxiaonan"+"<"+send_user+">"message = MIMEText(content,_subtype='plain',_charset='utf-8')message['Subject'] = submessage['From'] = usermessage['To'] = ";".join(user_list)server = smtplib.SMTP()server.connect(email_host)server.login(send_user,password)server.sendmail(user,user_list,message.as_string())server.close()def send_main(self,pass_list,fail_list):pass_num = float(len(pass_list))fail_num = float(len(fail_list))count_num = pass_num+fail_num#90%pass_result = "%.2f%%" %(pass_num/count_num*100)fail_result = "%.2f%%" %(fail_num/count_num*100)user_list = ['609037724@qq.com']sub = "接口自动化测试报告"content = "此次一共运行接口个数为%s个,通过个数为%s个,失败个数为%s,通过率为%s,失败率为%s" %(count_num,pass_num,fail_num,pass_result,fail_result )self.send_mail(user_list,sub,content)if __name__ == '__main__':sen = SendEmail()sen.send_main([1,2,3,4],[2,3,4,5,6,7])

六、主函数

run_test.py

#coding:utf-8
import sys
sys.path.append("C:/Users/lxz/Desktop/InterFace_JIA")
from base.runmethod import RunMethod
from operation_data.get_data import GetData
from tool.common_util import CommonUtil
from operation_data.dependent_data import DependdentData
from tool.send_email import SendEmail
from tool.operation_header import OperationHeader
from tool.operation_json import OperetionJson
class RunTest:def __init__(self):self.run_method = RunMethod()self.data = GetData()self.com_util = CommonUtil()self.send_mai = SendEmail()#程序执行的def go_on_run(self):res = Nonepass_count = []fail_count = []#10  0,1,2,3rows_count = self.data.get_case_lines()for i in range(1,rows_count):is_run = self.data.get_is_run(i)if is_run:url = self.data.get_request_url(i)method = self.data.get_request_method(i)request_data = self.data.get_data_for_json(i)expect = self.data.get_expcet_data_for_mysql(i)header = self.data.is_header(i)depend_case = self.data.is_depend(i)if depend_case != None:self.depend_data = DependdentData(depend_case)#获取的依赖响应数据depend_response_data = self.depend_data.get_data_for_key(i)#获取依赖的keydepend_key = self.data.get_depend_field(i)request_data[depend_key] = depend_response_dataif header == 'write':res = self.run_method.run_main(method,url,request_data)op_header = OperationHeader(res)op_header.write_cookie()elif header == 'yes':op_json = OperetionJson('../dataconfig/cookie.json')cookie = op_json.get_data('apsid')cookies = {'apsid':cookie}res = self.run_method.run_main(method,url,request_data,cookies)else:res = self.run_method.run_main(method,url,request_data)if self.com_util.is_equal_dict(expect,res) == 0:self.data.write_result(i,'pass')pass_count.append(i)else:self.data.write_result(i,res)fail_count.append(i)self.send_mai.send_main(pass_count,fail_count)#将执行判断封装#def get_cookie_run(self,header):
if __name__ == '__main__':run = RunTest()run.go_on_run()

总结

Python+requests+unittest+excel搭建接口自动化测试框架是一种流行的方法,可以帮助测试人员以有效和可靠的方式管理API测试用例。以下是该框架的一些主要优点和总结:

  1. 灵活和易于扩展:Python作为一种灵活的编程语言,可以轻松地扩展和定制测试框架,以满足特定项目或团队的需求。

  2. 高效和可维护:使用Python+requests+unittest+excel框架进行API测试可以大大提高测试效率,并减少手动测试所需的时间和成本。测试脚本易于维护和更新。

  3. 完整的测试覆盖:通过使用Excel表格来管理测试数据,可以确保所有测试用例都具有完整的测试覆盖,从而检测更多潜在的错误和缺陷。

  4. 生成详细的测试报告:该框架可以生成详细的HTML测试报告,包括测试结果、错误信息和性能统计数据等,以便于分析和评估接口质量。

  5. 适用于不同的测试场景:无论您是在测试Web应用程序、客户端应用程序还是其他类型的应用程序,都可以使用此框架进行API测试。它适用于各种测试场景,包括功能测试、性能测试和负载测试等。

总之,Python+requests+unittest+excel搭建接口自动化测试框架是一种功能强大且易于使用的API测试方法。通过这个框架,可以轻松管理和运行大量测试用例,并生成有用的测试报告,以便于分析和评估接口质量。

正在做测试的朋友可以进来交流,群里给大家整理了大量学习资料和面试题项目简历等等....


http://www.ppmy.cn/news/570994.html

相关文章

基于企业微电网平台的食用菌工厂的能源管理

摘要&#xff1a;从食用菌生产经营者角度指出食用菌工厂化生产的产品生鲜属性、微生物培养的技术特点和竞争战略难以突破决定了成本控制是经营的核心。分析食用菌生产的成本构成&#xff0c;指出加强能源管理是节本增效的重要途径&#xff0c;从电费的分类和改善方式、灭菌的燃…

深度学习(26)——YOLO系列(5)

深度学习&#xff08;26&#xff09;——YOLO-v7&#xff08;5&#xff09; 文章目录 深度学习&#xff08;26&#xff09;——YOLO-v7&#xff08;5&#xff09;絮絮叨叨1. conv和BN的融合2. 3*3卷积的替换&#xff08;1&#xff09;1*1卷积有什么作用&#xff1f;&#xff08…

LeetCode 每日一题 2023/6/19-2023/6/25

记录了初步解题思路 以及本地实现代码&#xff1b;并不一定为最优 也希望大家能一起探讨 一起进步 目录 6/19 1262. 可被三整除的最大和6/20 1595. 连通两组点的最小成本6/21 LCP 41. 黑白翻转棋6/22 面试题 16.19. 水域大小6/23 2496. 数组中字符串的最大值6/24 1659. 最大化网…

深入Python网络编程:从基础到实践

Python&#xff0c;作为一种被广泛使用的高级编程语言&#xff0c;拥有许多优势&#xff0c;其中之一就是它的网络编程能力。Python的强大网络库如socket, requests, urllib, asyncio,等等&#xff0c;让它在网络编程中表现优秀。本文将深入探讨Python在网络编程中的应用&#…

汽车行业项目管理面临的5个挑战及解决方案

汽车行业正跨越式地迈向新的未来。其目前的发展主要由四大趋势驱动&#xff1a;连接性、自动驾驶汽车、共享出行和电气化。这给汽车企业带来了诸多挑战&#xff1a;竞争加剧&#xff0c;快速发展带来的频繁变化&#xff0c;与软件公司建立伙伴关系&#xff0c;以及其他相关问题…

Chrome浏览器对应chromedriver版本 最新2019

直接参考下表&#xff0c;根据自己的浏览器版本去下载对应的Chromedriver&#xff1a; ChromeDriver版本 Support Chrome版本 2.46 V71-73 2.45 V70-72 2.44 V69-71 2.43 V69-71 2.42 V68-70 2.41 V67-69 2.40 V66-68 2.39 V66-68 2.38 V65-67 2.37 V64-…

如何让antv x6兼容IE浏览器

如何让antv x6兼容IE浏览器&#xff1a; 可以学习anvt G6的方法去处理&#xff0c;亲测有效。 链接地址&#xff1a;https://antv-g6.gitee.io/zh/docs/manual/FAQ/supportIE解决方法&#xff1a; 1、在main.js中&#xff0c;引入babel-polyfill import babel-polyfill;2、在…

Windows 11如何使用IE浏览器

Windows 11已经彻底移除了我们一直使用的IE浏览器。但是众所周知有一些网站还是一定要通过IE访问&#xff0c;怎么办&#xff1f;很简单&#xff0c;使用Microsoft Edge内置的IE模式就可以了。 在开启任意网页时只要选择右上角的三个点 开启后&#xff0c;网页旁边会有一个IE地…