用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!

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章