用excel格式书写的接口用例执行脚本

创建测试用例和测试结果集文件夹:

 

 

excel编写的接口测试用例如下:

1 encoding 响应的编码格式。所测项目大部分是utf-8,有一个特殊项目是utf-8-sig

2 params  对应requests的params

 

3 data,对应requests的data

 

 

 

有些参数是动态的:写参数名,程序中用eval()函数转化

 

 

baseapi.py

#-*-coding:utf-8-*-
"""
接口基类
dinghanhua
baseapi.py
"""

import requests
from requests.cookies import RequestsCookieJar


class apitest:
    def __init__(self):
        self.cookies = RequestsCookieJar()

    def response_text(self,method,url,encoding='utf-8',**kwargs):
        """请求函数"""
        response = requests.request(method,url,cookies=self.cookies,**kwargs)

        self.cookies.update(response.cookies) #更新cookies

        if encoding: # 如果有响应编码则配置编码
            response.encoding = encoding
        result = response.text

        return result

 

runtest.py

#-*-coding:utf-8-*-
"""
读取excel用例并执行
dinghanhua
"""

import xlrd
from xlutils.copy import copy
from baseapi import apitest
import datetime
import os
import re
import logging;logging.basicConfig(level=logging.INFO)


def run_testcase(excelpath,sheetindex=0):

    # region 读取excel和sheet
    book = xlrd.open_workbook(excelpath)  # 打开excel
    try:
        sheet = book.sheet_by_index(sheetindex)  # 读取sheet
        wb = copy(book)  # 转变成xlwt book对象
        wsheet = wb.get_sheet(sheetindex)
    except IndexError:
        logging.info("读取的sheet不存在")
        raise IndexError("读取的sheet不存在")
    #endregion

    # region 读取和运行用例
    testapi = apitest()
    fail = 0 # 用例执行失败个数
    success = 0 # 用例执行成功个数
    for row in range(1, sheet.nrows):
        isrun = str(int(sheet.cell_value(row,8))).strip() # 是否运行
        if isrun == '1': # 判断用例是否运行;运行则读取其他字段
            label = str(sheet.cell_value(row, 1)).strip()
            method = str(sheet.cell_value(row,2)).strip()
            url = str(sheet.cell_value(row, 3)).strip()
            encoding = str(sheet.cell_value(row, 4)).strip()
            headers = str(sheet.cell_value(row, 5)).strip()
            params = str(sheet.cell_value(row, 6)).strip()
            data = str(sheet.cell_value(row, 7)).strip()
            checkpoint = str(sheet.cell_value(row, 9)).strip()

            try:
                params = eval(params)  # 参数转变 从字符串转变成字典或带入参数;转变不了则不处理
            except:
                pass

            try:
                data = eval(data)
            except:
                pass

            try:
                headers = eval(headers)
            except:
                pass

            actual_result = testapi.response_text(method=method,url=url,params=params,data=data,encoding=encoding,headers=headers) # 获取响应

            if re.search(checkpoint,actual_result):  #测试通过写excel ; 测试通过计数加1
                wsheet.write(row,10,'pass')
                success += 1
                logging.info(label+'test pass')
            else:  #测试不通过写excel ; 测试不通过计数加1
                wsheet.write(row,10,'fail')
                wsheet.write(row,11, actual_result)  # 写入响应
                fail += 1
                logging.info("%s test fail.检查点:%s,响应结果:%s"%(label,checkpoint,actual_result))
    # endregion

    # region 保存测试结果
    filepath = os.path.join(os.path.dirname(__file__),'testresult') # 测试结果目录
    if not os.path.exists(filepath): # 目录不存在则创建
        os.mkdir(filepath)
    filename = os.path.join(filepath,datetime.datetime.now().strftime('%Y%m%d%H%M%S%f')+'.xls') # 测试结果文件
    wb.save(filename) # 保存文件
    logging.info('测试结果:测试通过%s,测试不通过%s。测试结果文件路径:%s'%(success,fail,filename))
    # endregion



#执行测试用例
# 测试要用的动态参数 nowtime = datetime.time().strftime('%Y%m%d%H%M%S%f') # 时间戳 today = str(datetime.date.today()) # 当前日期 newdate = (datetime.datetime.now()-datetime.timedelta(minutes=30)).strftime('%Y-%m-%d %H:%M:%S') # 当前时间点前半小时 sso = "test" # sso串 id = 1 # id token = 'token' # token,通过抓包获取 excelpath = r'C:\Users\dinghanhua\PycharmProjects\ApiTest\testcase\testcase1.xlsx' # excel用例文件 run_testcase(excelpath=excelpath,sheetindex=1) # 逐条读取并运行用例

 

运行之后testresult文件夹下查看已生成的测试结果文件,文件名=测试运行时间戳

该项目用jmeter、postman也可以做接口测试。用python脚本可以用excel写好用例直接执行。脚本中的检查点等可根据实际项目再调整。

 

the end!

posted @ 2020-10-23 10:48  dinghanhua  阅读(558)  评论(0编辑  收藏  举报