<续>Python接口自动化框架的简单思路

故事背景

2年前,和一个同学(爱奇艺大神)聊起写一个自动化框架。正好,前阵子公司在做python的培训,顺便写了一个python的接口自动化脚本。

自动化框架理解

框架,是一个基本概念上的结构,用于去解决或者处理复杂的问题。那测试框架到底是个啥呢?测试框架,更像是一个容器,这个容器有这样几个特征:

1.存储(数据)
2.调度(任务)
3.执行(请求)

根据特征,可以简单讲下,测试框架具体实现的几个大功能:

1.编写一个http请求的python功能
2.把请求的测试数据独立出来,存储在某个地方
3.通过一个调度器,把http请求功能和测试数据结合起来,并执行
4.把结果在存储到某个地方,存储形式包括日志&结果等

python实践

python实现:excel存储测试用例数据

1、excel用例格式如下:

ID测试要点CityNameCountryName期望值实际值结果响应时间
1检查japan的一个城市Beijingjapan
2检查china的一个城市Shanghaichina

2、python读取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   

3、对于测试结果需要写入到这个Excel,python代码如下:

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                                                                                  

python实现:执行http请求并记录请求结果

1、执行http请求,python代码如下:

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                 

2、把请求后的响应结果写入xml文件,python代码如下:

    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()

python实现:(调度)执行用例

1、分析结果xml文件,并将断言结果,写入excel中。python代码如下:

for caseDict in testCaseList:                                        
    caseId = caseDict['id']                                          
    cityName = caseDict['CityName']                                  
    countryName = caseDict['CountryName']                            
    rspect = caseDict['Rspect']                                      
    #requestBody = 'CityName='+cityName+'&CountryName='+countryName  
    requestBody = 'CountryName='+countryName                         

    getWeather = GetWeather(requesturl,requestBody,requestHeadrs)    
    #获取请求结果                                                    
    tmpString = getWeather.getWeath(getWeather.serviceUrl,\          
        getWeather.requestBody,getWeather.headers)                   

    xd = XmlReader(str(caseId) + '.xml')                             
    print 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最简单的一个接口自动化框架

  • 6
    点赞
  • 29
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值