侯体宗的博客
  • 首页
  • 人生(杂谈)
  • 技术
  • 关于我
  • 更多分类
    • 文件下载
    • 文字修仙
    • 中国象棋ai
    • 群聊
    • 九宫格抽奖
    • 拼图
    • 消消乐
    • 相册

一个Python最简单的接口自动化框架

Python  /  管理员 发布于 7年前   155

故事背景

读取一个Excel中的一条数据用例,请求接口,然后返回结果并反填到excel中。过程中会生成请求回来的文本,当然还会生成一个xml文件。具体的excel文件如下:

代码方案

# -*- coding: UTF-8 -*- from xml.dom import minidomimport xlrdimport openpyxlimport requestsimport jsonimport sysimport HTMLParserimport osimport reimport codecsimport timeimport datetimereload(sys)sys.setdefaultencoding('utf-8')class OptionExcelData(object):  """对Excel进行操作,包括读取请求参数,和填写操作结果"""  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的行数      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,后续写操作    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:      passclass 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    #记录响应回来的内容    self.requestResult['time'] = round(timeend - timebefore,2)     #计算响应时间    return self.requestResultclass 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)    #转换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   #获取特定字段并返回结果,此处选取Statusif __name__ == '__main__':  requesturl = 'http://www.webservicex.net/globalweather.asmx/GetWeather'  requestHeadrs = {"Content-Type":"application/x-www-form-urlencoded"}  fileName = u'用例内容.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')    #把请求内容写入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实现简单的遗传算法
    下一条:
    利用Hyperic调用Python实现进程守护
  • 昵称:

    邮箱:

    0条评论 (评论内容有缓存机制,请悉知!)
    最新最热
    • 分类目录
    • 人生(杂谈)
    • 技术
    • linux
    • Java
    • php
    • 框架(架构)
    • 前端
    • ThinkPHP
    • 数据库
    • 微信(小程序)
    • Laravel
    • Redis
    • Docker
    • Go
    • swoole
    • Windows
    • Python
    • 苹果(mac/ios)
    • 相关文章
    • 在python语言中Flask框架的学习及简单功能示例(0个评论)
    • 在Python语言中实现GUI全屏倒计时代码示例(0个评论)
    • Python + zipfile库实现zip文件解压自动化脚本示例(0个评论)
    • python爬虫BeautifulSoup快速抓取网站图片(1个评论)
    • vscode 配置 python3开发环境的方法(0个评论)
    • 近期文章
    • 在windows10中升级go版本至1.24后LiteIDE的Ctrl+左击无法跳转问题解决方案(0个评论)
    • 智能合约Solidity学习CryptoZombie第四课:僵尸作战系统(0个评论)
    • 智能合约Solidity学习CryptoZombie第三课:组建僵尸军队(高级Solidity理论)(0个评论)
    • 智能合约Solidity学习CryptoZombie第二课:让你的僵尸猎食(0个评论)
    • 智能合约Solidity学习CryptoZombie第一课:生成一只你的僵尸(0个评论)
    • 在go中实现一个常用的先进先出的缓存淘汰算法示例代码(0个评论)
    • 在go+gin中使用"github.com/skip2/go-qrcode"实现url转二维码功能(0个评论)
    • 在go语言中使用api.geonames.org接口实现根据国际邮政编码获取地址信息功能(1个评论)
    • 在go语言中使用github.com/signintech/gopdf实现生成pdf分页文件功能(95个评论)
    • gmail发邮件报错:534 5.7.9 Application-specific password required...解决方案(0个评论)
    • 近期评论
    • 122 在

      学历:一种延缓就业设计,生活需求下的权衡之选中评论 工作几年后,报名考研了,到现在还没认真学习备考,迷茫中。作为一名北漂互联网打工人..
    • 123 在

      Clash for Windows作者删库跑路了,github已404中评论 按理说只要你在国内,所有的流量进出都在监控范围内,不管你怎么隐藏也没用,想搞你分..
    • 原梓番博客 在

      在Laravel框架中使用模型Model分表最简单的方法中评论 好久好久都没看友情链接申请了,今天刚看,已经添加。..
    • 博主 在

      佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 @1111老铁这个不行了,可以看看近期评论的其他文章..
    • 1111 在

      佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 网站不能打开,博主百忙中能否发个APP下载链接,佛跳墙或极光..
    • 2016-10
    • 2016-11
    • 2018-04
    • 2020-03
    • 2020-04
    • 2020-05
    • 2020-06
    • 2022-01
    • 2023-07
    • 2023-10
    Top

    Copyright·© 2019 侯体宗版权所有· 粤ICP备20027696号 PHP交流群

    侯体宗的博客