python-----实现接口自动化测试(实例4)

实现接口自动化测试
1、读取case---从测试用例Excel表格中读取接口请求数据
2、调用接口---发送请求获取实际结果
3、校验结果---实际结果与预期结果对比
4、结果写入表格---将实际结果与测试状态填入Excel表格
5、生成报告---发送邮件
目录划分
1、bin--start 
2 cases--测试用例
3 config---setting(邮件连接、路径)
4 lib--request(get post请求) tools(从Ecxel获取接口信息,发送请求,写入Ecxel,实际结果与预期结果对比)
5 log-atp.log(日志)
 
#####################my_request.py文件#####################
import requests
from config.setting import my_log

def post(url,data,header=None,cookie=None,is_json=False):
try:
if is_json:
res = requests.post(url=url, json=data, headers=header, cookies=cookie).text
else:
res = requests.post(url=url, data=data, headers=header, cookies=cookie).text
except Exception as e:
my_log.error('接口请求出错%s '% e)
res = str(e)
return res

def get(url,data,header=None,cookie=None):
try:
res = requests.get(url=url, params=data, headers=header, cookies=cookie).text
except Exception as e:
my_log.error('接口请求出错%s '% e)
res = str(e)
return res

#####################tools.py文件#####################

import xlrd
from xlutils import copy
from config.setting import my_log,MAIL_INFO,TO,CC
from lib import my_request
import yagmail
import time

def readExcel(filepath):
try:
book = xlrd.open_workbook(filepath)
except Exception as e:
my_log.error('打开用例出错,文件名是%s' % filepath)
return []
finally:
allcase = []
sheet = book.sheet_by_index(0)
rownum = sheet.nrows
for i in range(1, rownum):
allcase.append(sheet.row_values(i)[4:8])
return allcase

def write_res(file_name,res_list):
book = xlrd.open_workbook(file_name)
new_book = copy(book)
sheet = new_book.get_sheet(0)
# res_list ['str','']
for row,data in enumerate(res_list,1):
res,status=data
sheet.write(row,8,res) # 写入返回结果
sheet.write(row,9,status) # 写入运行状态
new_book.save(file_name)

#对测试用例中请求数据参数处理后返回dict形式
def str_to_dict(s:str,seq='&'):
d={}
if s.strip():
for i in s.split(seq):
k,v=i.split("=")
d[k] = v
return d

#核对请求返回值与列表预期值
def check_res(res:str,check:str):
new_res = res.replace('": "', '=').replace('": ', '=')
for c in check.strip(','):
if c not in new_res:
return '失败'
return '通过'

#发送请求后结果校验,将请求结果与校验结果存在list中返回
def run_case(all_case):
all_res = []
for case in all_case:
url,method,data,check = case
data=str_to_dict(data) #把请求参数转成字典
if str(method).upper()=='POST':
res=my_request.post(url,data)
else:
res=my_request.get(url,data)
status=check_res(res,check)
all_res.append([res,check])
return all_res

def send_mail(content,files):
mail=yagmail.SMTP(**MAIL_INFO)
subject="%s 接口测试报告" %time.strptime('%Y-%m-%d %H:%M:%S')
mail.send(to=TO,cc=CC,subject=subject,content=content,attachments=files)

#####################setting.py文件#####################
import nnlog
import os
BASE_PATH=os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
LOG_FILE_NAME='atp.log'
ABS_FILE_PATH=os.path.join(BASE_PATH,'log')
print(ABS_FILE_PATH)
my_log=nnlog.Logger(ABS_FILE_PATH)

CASE_PATH = os.path.join(BASE_PATH,'cases') #存放用例的目录
MAIL_INFO={
'user':'uitestp4p@163.com', #邮箱账号
'password':'houyafan123', #邮箱密码
'host':'smtp.163.com' #邮箱的服务器地址
} #邮箱信息
TO = ['***@qq.com',] #发送给谁
CC = ['***@163.com'] #抄送给谁

#####################start.py文件#####################
import os,sys
BASE_PATH=os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.index(0,BASE_PATH)
from lib import tools
import glob
from config.setting import CASE_PATH
def main():
all_count = 0 # 存的所有文件里面用例的个数
all_pass_count = 0 # 存的所有文件里面用例通过的个数
files = [] # 存放的是运行过所有的用例文件
for file in glob.glob(CASE_PATH,'**xls'): #获取用例文件夹下的所有xls文件
all_case=tools.readExcel(file)
all_res=tools.run_case(all_case)
tools.write_res(file,all_res)
case_count = len(all_res) # 所有用例的个数
pass_count = str(all_res).count('通过') # 通过的个数
all_count += case_count # 累加每个文件里面的用例
all_pass_count += pass_count # 累加通过的用例数
files.append(file)
msg='''
本次运行的测试用例数量%s,通过%s,失败%s
'''%(all_count,all_pass_count,all_count-all_pass_count)
tools.send_mail(msg,files)
main()



原文地址:https://www.cnblogs.com/wenchengqingfeng/p/9455513.html