一个一个Python最简单的接口自动化框架最简单的接口自动化框架
故事背景故事背景
读取一个Excel中的一条数据用例,请求接口,然后返回结果并反填到excel中。过程中会生成请求回来的文本,当然还会生成一个
xml文件。具体的excel文件如下:
代码方案代码方案
# -*- 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 #填写实际值