python 接口自动化测试(四)

说完了SOAP协议的接口自动化

该说下http协议的接口测试了

HttpService.py

import requests
import sys
reload(sys)
sys.setdefaultencoding( "utf-8" )



class HttpService():
    def __init__(self,host,url):
        self.host=host
        self.url=url

    def httpReq(self,params,method="POST"):
        requesturl=self.host+self.url
        if(method == "POST"):
            resp_data=requests.post(requesturl,params)
        else:
            resp_data=requests.get(requesturl)
        resp=resp_data.text
        return resp

这是http请求的实现类,运用了requests模块

之后就是在具体的执行文件中调用上面的HttpService.py

在RunMain.py中添加方法:

def runHttpTest(ip,list,serviceClass):
    length=len(list)
    #实现控制台输出执行进度
    widgets = [ip+' Progress: ', Percentage(), ' ', Bar(marker=RotatingMarker('>')),
      ' ', ETA()]
    pbar = ProgressBar(widgets=widgets, maxval=length).start()
    for i in range(length):
        pbar.update(i+1)
        try:
            #实例化类的对象
            runhttptest = serviceClass(ip,str(list[i][0]))
            if(str(list[i][2]) == "GET"): #判断http请求的方法
                test_rep=runhttptest.httpReq(None,"GET")
                DataEngine.httpGetResultCheck(test_rep,xlw,list,i) #返回结果判断
            else:
                dict=eval(str(list[i][2]))
                test_rep=runhttptest.httpReq(dict)
                DataEngine.httpResultCheck(test_rep,xlw,list,i)

        except Exception,e:
            print(str(list[i][1])+"\t"+str(e))
            Logging.writeException(e)
    pbar.finish()

由于接口返回结果和SOAP接口的返回结果类型不一致,所以DataEngine.py中的结果处理方法就要做一些扩展,由于时间关系,我这边就直接另写了两个方法进行结果断言处理

def httpResultCheck(test_rep,xlw,list,xls_row):
    global COUNT_ROWs
    result=test_rep.find(',"status":1',22)
    if(result != -1):
        xlw.write_HttpResult(COUNT_ROWs,list,xls_row,True)
        COUNT_ROWs=COUNT_ROWs+1
    else:
        Logging.writeHttpLog(str(list[xls_row][1]),str(test_rep))
        xlw.write_HttpResult(COUNT_ROWs,list,xls_row,False)
        COUNT_ROWs=COUNT_ROWs+1

def httpGetResultCheck(test_rep,xlw,list,xls_row):
    global COUNT_ROWs
    test_rep=json.loads(test_rep)
    result=test_rep['status']
    if(result == 1):
        xlw.write_HttpResult(COUNT_ROWs,list,xls_row,True)
        COUNT_ROWs=COUNT_ROWs+1
    else:
        Logging.writeHttpLog(str(list[xls_row][1]),str(test_rep))
        xlw.write_HttpResult(COUNT_ROWs,list,xls_row,False)
        COUNT_ROWs=COUNT_ROWs+1

以上就是所有的代码添加:

执行后结果输出见下图:

python 接口自动化测试(四)_第1张图片

其中执行失败的用例,会以红色醒目标识出来,并在其后输出具体的中文用例描述



你可能感兴趣的:(自动化测试,测试工具,Python)