溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

使用Python怎么實現(xiàn)一個接口自動化框架

發(fā)布時間:2021-04-13 17:35:07 來源:億速云 閱讀:137 作者:Leah 欄目:開發(fā)技術

本篇文章給大家分享的是有關使用Python怎么實現(xiàn)一個接口自動化框架,小編覺得挺實用的,因此分享給大家學習,希望大家閱讀完這篇文章后可以有所收獲,話不多說,跟著小編一起來看看吧。

# -*- coding: UTF-8 -*- 
from xml.dom import minidom
import xlrd
import openpyxl
import requests
import json
import sys
import HTMLParser
import os
import re
import codecs
import time
import datetime

reload(sys)
sys.setdefaultencoding('utf-8')

class OptionExcelData(object):
  """對Excel進行操作,包括讀取請求參數(shù),和填寫操作結果"""
  def __init__(self, excelFile,excelPath=''):
    self.excelFile = excelFile
    self.excelPath = excelPath
    self.caseList = []

  """
  傳入:傳入用例Excel名稱
  返回:[],其中元素為{},每個{}包含行號、城市、國家和期望結果的鍵值對
  """
  def getCaseList(self,excelFile,excelPath=''):
    readExcel = xlrd.open_workbook(fileName)              #讀取指定的Excel
    try:
      table = readExcel.sheet_by_index(0)               #獲取Excel的第一個sheet
      trows = table.nrows                       #獲取Excel的行數(shù)
      for n in range(1,trows):
        tmpdict = {}                        #把一行記錄寫進一個{}
        tmpdict['id'] = n                      #n是Excel中的第n行
        tmpdict['CityName'] = table.cell(n,2).value
        tmpdict['CountryName'] = table.cell(n,3).value
        tmpdict['Rspect'] = table.cell(n,4).value
        self.caseList.append(tmpdict)
    except Exception, e:
      raise
    finally:
      pass
    return self.caseList

  """
  傳入:請求指定字段結果,是否通過,響應時間
  返回:
  """
  def writeCaseResult(self,resultBody,isSuccess,respTime,\
    excelFile,theRow,theCol=5):
    writeExcel = openpyxl.load_workbook(excelFile)           #加載Excel,后續(xù)寫操作
    try:
      wtable = writeExcel.get_sheet_by_name('Sheet1')         #獲取名為Sheet1的sheet
      wtable.cell(row=theRow+1,column=theCol+1).value = resultBody  #填寫實際值
      wtable.cell(row=theRow+1,column=theCol+2).value = isSuccess   #填寫是否通過
      wtable.cell(row=theRow+1,column=theCol+3).value = respTime   #填寫響應時間
      writeExcel.save(excelFile)
    except Exception, e:
      raise
    finally:
      pass


class GetWeather(object):
  """獲取天氣的http請求"""
  def __init__(self, serviceUrl,requestBody,headers):
    self.serviceUrl = serviceUrl
    self.requestBody = requestBody
    self.headers = headers
    self.requestResult = {}

  """
  傳入:請求地址,請求體,請求頭
  返回:返回{},包含響應時間和請求結果的鍵值對
  """
  def getWeath(self,serviceUrl,requestBody,headers):
    timebefore = time.time()                      #獲取請求開始的時間,不太嚴禁
    tmp = requests.post(serviceUrl,data=requestBody,\
      headers=headers)
    timeend = time.time()                        #獲取請求結束的時間
    tmptext = tmp.text
    self.requestResult['text'] = tmptext                #記錄響應回來的內(nèi)容
    self.requestResult['time'] = round(timeend - timebefore,2)     #計算響應時間
    return self.requestResult

class XmlReader:
  """操作XML文件"""
  def __init__(self,testFile,testFilePath=''):
    self.fromXml = testFile
    self.xmlFilePath = testFilePath
    self.resultList = []

  def writeXmlData(self,resultBody,testFile,testFilePath=''):
    tmpXmlFile = codecs.open(testFile,'w','utf-16')           #新建xml文件
    tmpLogFile = codecs.open(testFile+'.log','w','utf-16')       #新建log文件

    tmp1 = re.compile(r'\<.*?\>')                   #生成正則表達式:<*?>
    tmp2 = tmp1.sub('',resultBody['text'])               #替換相應結果中的<*?>
    html_parser = HTMLParser.HTMLParser()
    xmlText = html_parser.unescape(tmp2)                #轉(zhuǎn)換html編碼

    try:
      tmpXmlFile.writelines(xmlText.strip())             #去除空行并寫入xml
      tmpLogFile.writelines('time: '+\
        str(resultBody['time'])+'\r\n')               #把響應時間寫入log
      tmpLogFile.writelines('text: '+resultBody['text'].strip())   #把請求回來的文本寫入log
    except Exception, e:
      raise
    finally:
      tmpXmlFile.close()
      tmpLogFile.close()

  """返回一個list"""
  def readXmlData(self,testFile,testFilePath=''):
    tmpXmlFile = minidom.parse(testFile)
    root = tmpXmlFile.documentElement
    tmpValue = root.getElementsByTagName('Status')[0].\
    childNodes[0].data
    return tmpValue                           #獲取特定字段并返回結果,此處選取Status


if __name__ == '__main__':

  requesturl = 'http://www.webservicex.net/globalweather.asmx/GetWeather'
  requestHeadrs = {"Content-Type":"application/x-www-form-urlencoded"}
  fileName = u'用例內(nèi)容.xlsx'

  ed = OptionExcelData(fileName) 
  testCaseList = ed.getCaseList(ed.excelFile)

  for caseDict in testCaseList:
    caseId = caseDict['id']
    cityName = caseDict['CityName']
    countryName = caseDict['CountryName']
    rspect = caseDict['Rspect']
    requestBody = 'CityName='+cityName+'&CountryName='+countryName

    getWeather = GetWeather(requesturl,requestBody,requestHeadrs)
    #獲取請求結果
    tmpString = getWeather.getWeath(getWeather.serviceUrl,\
      getWeather.requestBody,getWeather.headers)

    xd = XmlReader(str(caseId) + '.xml')
    #把請求內(nèi)容寫入xml和log
    xd.writeXmlData(tmpString,xd.fromXml)
    response = xd.readXmlData(str(caseId) + '.xml')
    respTime = tmpString['time']
    if response == rspect:
      theResult = 'Pass'
    else:
      theResult = 'False'
   ed.writeCaseResult(response,theResult,respTime,fileName,caseId)

以上就是使用Python怎么實現(xiàn)一個接口自動化框架,小編相信有部分知識點可能是我們?nèi)粘9ぷ鲿姷交蛴玫降摹OM隳芡ㄟ^這篇文章學到更多知識。更多詳情敬請關注億速云行業(yè)資訊頻道。

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權內(nèi)容。

AI