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


Posted in Python onJanuary 02, 2018

故事背景

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

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

代码方案

# -*- 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进行操作,包括读取请求参数,和填写操作结果"""
  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:
      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                #记录响应回来的内容
    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)                #转换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'用例内容.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 相关文章推荐
pygame学习笔记(6):完成一个简单的游戏
Apr 15 Python
Python字符串、元组、列表、字典互相转换的方法
Jan 23 Python
python连接数据库的方法
Oct 19 Python
Python实现比较扑克牌大小程序代码示例
Dec 06 Python
基于python实现学生管理系统
Oct 17 Python
利用arcgis的python读取要素的X,Y方法
Dec 22 Python
python学习--使用QQ邮箱发送邮件代码实例
Apr 16 Python
对Python3之方法的覆盖与super函数详解
Jun 26 Python
Python3将jpg转为pdf文件的方法示例
Dec 13 Python
tensorflow 环境变量设置方式
Feb 06 Python
python模块如何查看
Jun 16 Python
matplotlib交互式数据光标mpldatacursor的实现
Feb 03 Python
利用Hyperic调用Python实现进程守护
Jan 02 #Python
python实现TF-IDF算法解析
Jan 02 #Python
python实现xlsx文件分析详解
Jan 02 #Python
Python实现KNN邻近算法
Jan 28 #Python
Python+matplotlib+numpy绘制精美的条形统计图
Jan 02 #Python
基于Python实现的ID3决策树功能示例
Jan 02 #Python
python实现基于SVM手写数字识别功能
May 27 #Python
You might like
smarty模板嵌套之include与fetch性能测试
2010/12/05 PHP
php获取当月最后一天函数分享
2015/02/02 PHP
PHP中使用file_get_contents post数据代码例子
2015/02/13 PHP
php实现可逆加密的方法
2015/08/11 PHP
Javascript的IE和Firefox兼容性汇编
2006/07/01 Javascript
做网页的一些技巧
2007/02/01 Javascript
Javascript 获取LI里的内容
2008/12/17 Javascript
JQuery获取样式中的background-color颜色值的问题
2013/08/20 Javascript
JavaScript中读取和保存文件实例
2014/05/08 Javascript
详解AngularJS中的filter过滤器用法
2016/01/04 Javascript
jquery表单提交带错误信息提示效果
2017/03/09 Javascript
详解nodejs express下使用redis管理session
2017/04/24 NodeJs
js获取文件里面的所有文件名(实例)
2017/10/17 Javascript
微信小程序实现点击按钮修改文字大小功能【附demo源码下载】
2017/12/06 Javascript
微信小程序收藏功能的实现代码
2018/06/12 Javascript
写gulp遇到的ES6问题详解
2018/12/03 Javascript
基于javascript实现碰撞检测
2020/03/12 Javascript
Python中join和split用法实例
2015/04/14 Python
Python win32com 操作Exce的l简单方法(必看)
2017/05/25 Python
pycharm激活码快速激活及使用步骤
2020/03/12 Python
基于python实现把json数据转换成Excel表格
2020/05/07 Python
Python 解决相对路径问题:&quot;No such file or directory&quot;
2020/06/05 Python
python如何获得list或numpy数组中最大元素对应的索引
2020/11/16 Python
详解使用CSS3的@media来编写响应式的页面
2017/11/01 HTML / CSS
纯CSS实现右侧底部悬浮效果(悬浮QQ、微信、微博、邮箱等联系方式)
2015/04/24 HTML / CSS
html5的canvas元素使用方法介绍(画矩形、画折线、圆形)
2014/04/14 HTML / CSS
AmazeUI 点击元素显示全屏的实现
2020/08/25 HTML / CSS
ECCO爱步美国官网:来自丹麦的鞋履品牌
2016/11/23 全球购物
Farfetch阿联酋:奢侈品牌时尚购物平台
2019/07/26 全球购物
校园门卫岗位职责
2013/12/09 职场文书
认识深刻的检讨书
2014/02/16 职场文书
入股协议书范本
2014/04/14 职场文书
健康教育评估方案
2014/05/25 职场文书
启动仪式策划方案
2014/06/14 职场文书
优秀中职教师事迹材料
2014/08/26 职场文书
教你用python控制安卓手机
2021/05/13 Python