一个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 相关文章推荐
用python + openpyxl处理excel2007文档思路以及心得
Jul 14 Python
Python网络编程中urllib2模块的用法总结
Jul 12 Python
python实现批量监控网站
Sep 09 Python
Python 高级专用类方法的实例详解
Sep 11 Python
Numpy中的mask的使用
Jul 21 Python
Python实现插入排序和选择排序的方法
May 12 Python
python basemap 画出经纬度并标定的实例
Jul 09 Python
python实现在多维数组中挑选符合条件的全部元素
Nov 26 Python
python序列化与数据持久化实例详解
Dec 20 Python
Python3加密解密库Crypto的RSA加解密和签名/验签实现方法实例
Feb 11 Python
python中的测试框架
Nov 13 Python
python - asyncio异步编程
Apr 06 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
PHP与SQL注入攻击[二]
2007/04/17 PHP
PHP的cURL库简介及使用示例
2015/02/06 PHP
php面向对象编程self和static的区别
2016/05/08 PHP
wordpress网站转移到本地运行测试的方法
2017/03/15 PHP
php + WebUploader实现图片批量上传功能
2019/05/06 PHP
[Web]防止用户复制页面内容和另存页面的方法
2009/02/06 Javascript
javascript将异步校验表单改写为同步表单
2015/01/27 Javascript
由ReactJS的Hello world说开来
2015/07/02 Javascript
使用基于Node.js的构建工具Grunt来发布ASP.NET MVC项目
2016/02/15 Javascript
深入理解jQuery之事件移除
2016/06/02 Javascript
JavaScript必知必会(五) eval 的使用
2016/06/08 Javascript
浅谈JS中的三种字符串连接方式及其性能比较
2016/09/02 Javascript
Ajax跨域实现代码(后台jsp)
2017/01/21 Javascript
JS验证输入的是否是数字及保留几位小数问题
2018/05/09 Javascript
详解jenkins自动化部署vue
2019/05/14 Javascript
js之切换全屏和退出全屏实现代码实例
2019/09/09 Javascript
nuxt.js 在middleware(中间件)中实现路由鉴权操作
2020/11/06 Javascript
Python利用多进程将大量数据放入有限内存的教程
2015/04/01 Python
使用Python脚本来控制Windows Azure的简单教程
2015/04/16 Python
python使用fcntl模块实现程序加锁功能示例
2017/06/23 Python
python django使用haystack:全文检索的框架(实例讲解)
2017/09/27 Python
python自定义线程池控制线程数量的示例
2019/02/22 Python
python图像和办公文档处理总结
2019/05/28 Python
pytz格式化北京时间多出6分钟问题的解决方法
2019/06/21 Python
Python assert关键字原理及实例解析
2019/12/13 Python
new_zeros() pytorch版本的转换方式
2020/02/18 Python
基于python 等频分箱qcut问题的解决
2020/03/03 Python
Python实现猜年龄游戏代码实例
2020/03/25 Python
详解Scrapy Redis入门实战
2020/11/18 Python
css3 线性渐变和径向渐变示例附图
2014/04/08 HTML / CSS
HTML5 对各个标签的定义与规定:body的介绍
2012/06/21 HTML / CSS
为您的家、后院、车库等在线购物:Spreetail
2019/06/17 全球购物
热门专业求职信
2014/05/24 职场文书
党的群众路线教育实践活动心得体会范文
2014/11/05 职场文书
2014年后备干部工作总结
2014/12/08 职场文书
表扬信范文
2015/05/04 职场文书