一个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中的循环语句的用法
Apr 09 Python
Python3实现并发检验代理池地址的方法
Sep 18 Python
python的Tqdm模块的使用
Jan 10 Python
使用python爬取B站千万级数据
Jun 08 Python
Python设计模式之职责链模式原理与用法实例分析
Jan 11 Python
python占位符输入方式实例
May 27 Python
python 命令行传入参数实现解析
Aug 30 Python
使用python绘制cdf的多种实现方法
Feb 25 Python
python dict乱码如何解决
Jun 07 Python
Pycharm2020最新激活码|永久激活(附最新激活码和插件的详细教程)
Sep 29 Python
python代码实现猜拳小游戏
Nov 30 Python
如何利用python正则表达式匹配版本信息
Dec 09 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开发时容易忘记的一些技术细节
2016/02/03 PHP
php无限级分类实现方法分析
2016/10/19 PHP
SUN的《AJAX与J2EE》全文译了
2007/02/23 Javascript
JavaScript XML操作 封装类
2009/07/01 Javascript
Javascript学习笔记之 函数篇(二) : this 的工作机制
2014/06/24 Javascript
JavaScript简介
2015/02/15 Javascript
javascript生成大小写字母
2015/07/03 Javascript
jQuery实现简单的列表式导航菜单效果代码
2015/08/31 Javascript
jQuery ajax中使用confirm,确认是否删除的简单实例
2016/06/17 Javascript
JavaScript之Date_动力节点Java学院整理
2017/06/28 Javascript
JS实现下拉菜单列表与登录注册弹窗效果
2017/08/10 Javascript
Vue脚手架的简单使用实例
2018/07/10 Javascript
详解从vue-loader源码分析CSS Scoped的实现
2019/09/23 Javascript
JS实现密码框效果
2020/09/10 Javascript
用webAPI实现图片放大镜效果
2020/11/23 Javascript
基于vuex实现购物车功能
2021/01/10 Vue.js
[03:40]2014DOTA2国际邀请赛 B神专访:躲箭真的很难
2014/07/13 DOTA
[03:22]DSPL第一期精彩集锦:酷炫到底!
2014/11/07 DOTA
[16:56]heroes英雄教学 司夜刺客
2014/09/18 DOTA
Python中实现对Timestamp和Datetime及UTC时间之间的转换
2015/04/08 Python
python 根据正则表达式提取指定的内容实例详解
2016/12/04 Python
在python中实现对list求和及求积
2018/11/14 Python
pyinstaller打包找不到文件的问题解决
2020/04/15 Python
python的launcher用法知识点总结
2020/08/07 Python
CSS3 选择器 伪类选择器介绍
2012/01/21 HTML / CSS
照片礼物和装饰:MyPhoto
2019/11/02 全球购物
办公室主任竞聘演讲稿
2014/05/15 职场文书
我的中国梦演讲稿600字
2014/08/19 职场文书
护士2014年终工作总结
2014/11/11 职场文书
骨干教师个人总结
2015/02/11 职场文书
介绍信格式样本
2015/05/05 职场文书
党员发展大会主持词
2015/07/03 职场文书
初中化学教学反思
2016/02/22 职场文书
Java实现房屋出租系统详解
2021/10/05 Java/Android
python入门学习关于for else的特殊特性讲解
2021/11/20 Python
Python的三个重要函数详解
2022/01/18 Python