码迷,mamicode.com
首页 > 编程语言 > 详细

http接口测试框架-python

时间:2017-07-17 10:09:07      阅读:464      评论:0      收藏:0      [点我收藏+]

标签:dex   save   没有   sys   except   eval   app   插件   标记   

简单分解一下

接口测试框架设计:

主入口 -> 遍历接口/用例 -> 发送请求+接收响应 ->结果的对比 -> 生成报告 ->发送email

分成几大类:
主入口的py文件

src-核心代码文件
    遍历case,发送请求和接收响应

存放case的
    2、数据库里维护
    3、excel里维护
        包括的字段:编号,接口名称,地址前缀,请求地址,请求方法,请求数据类型,请        求数据,检查点,是否运行,测试结果,响应参数

公共函数:被多次重复调用,且没有依赖性
commans-存放公共函数库文件
    2、数据库里维护
    3、excel里维护
        包括的字段:

reports存放报告
    excel

放插件的目录

log日志目录

技术分享

 

1\先编写请求类,requests库里各类请求的封装

#! /usr/bin/env python
#coding=utf-8

import requests
import json

#定义请求类
class Interface_Request:
    def req_get(self,url,params,headers):
        try:
            r = requests.get(url,params=params,headers=headers)
            #转换为python类型的字典格式,json包的响应结果,调用json(),转换成python类型
            json_r = r.json()
            return json_r
        except BaseException as e:
            print("请求不能完成:",str(e))
    
    def post_kv(self,url,data,headers):
        try:
            r = requests.post(url,data=data,headers=headers)
            #转换为python类型的字典格式,json包的响应结果,调用json(),转换成python类型
            json_r = r.json()
            #print(json_r)
            return json_r
        except BaseException as e:
            print("请求不能完成:",str(e))
    
    def post_json(self,url,data,headers):
        try:
            #python类型转化为json类型
            data = json.dumps(data)
            r = requests.post(url,data=data,headers=headers)
            json_r = r.json()
            return json_r
        except Exception as e:
            print("请求不能完成:",str(e))

‘‘‘  
下面为测试代码      
url = "http://v.juhe.cn/laohuangli/d"
params = {"key":"e711bc6362b3179f5a28de7fd3ee4ace","date":"2016-5-14"}
headers = {}


req = Interface_Request()
req.req_get(url,params,headers)
req.post_kv(url,params,headers)
req.post_json(url,params,headers)
‘‘‘

 

2\接口类编写,完成调用请求并接受响应然后对结果进行对比,对结果和响应的写入

import requests
import re
import sys
sys.path.append("C:/Users/Administrator/Desktop/接口自动化测试/common")
from laohuangli_requests import Interface_Request

‘‘‘
class InterfaceTest(object):
    def 方法名称(self):
        请求类的调用,发送请求,获取响应
        re.search(检查点,响应内容)
        re.search(rro_code:‘0‘,r)#匹配到就返回Ture,没有就返回False
        if re.search(rro_code:‘0‘,r):
            print("xxxxxx")
        else:
            print(xxxxxx)
‘‘‘

‘‘‘
class InterfaceTest:
    def testGet(self):
        url = "http://v.juhe.cn/laohuangli/d"
        params = {"key":"e711bc6362b3179f5a28de7fd3ee4ace","date":"2016-5-14"}
        headers = {}
               
        req = Interface_Request()
        req_get = req.req_get(url,params = params,headers = headers)
        print(str(req_get))
        if(re.search("‘error_code‘: 0",str(req_get))):
            print("pass")
        else:
            print("fail")
            

it = InterfaceTest()
it.testGet()
‘‘‘

class InterfaceTest:
    def testrequest(self,url,uri,params,reqform,dataform,checkpoint,headers,i,sheet,num,name,log):
        #可选
        ‘‘‘
        headers = {‘Content-Type‘:‘application/x-www-form-urlencoded;charset=UTF-8‘}
        headers = {‘Content-Type‘:‘application/json;charset=utf-8‘}
        ‘‘‘
        #生成请求类的对象
        req = Interface_Request()
        #req_get = req.req_get(url,params = params,headers = headers)
        #请求前缀和接口地址的拼接
        full_url = url + uri
        
        #判断请求类型
        if(reqform == GET):
            #调用请求类的函数,得到返回结果
            self.req_test = req.req_get(full_url,params,headers)
        elif(reqform == POST and dataform == Form):
            self.req_test = req.post_kv(full_url,params,headers)
        elif(reqform == POST and dataform == Json):
            headers = {Content-Type:application/json;charset=utf-8}
            self.req_test = req.post_json(full_url,params,headers)
        else:
            print("请求不通过,请检查case用例配置")
        print(self.req_test)
        
        #检查点与响应数据做对比
        if(re.search(checkpoint,str(self.req_test))):
            sheet.cell(row = i,column = 11).value = "成功" #row是通过遍历case类传递的
            sheet.cell(row = i,column = 12).value = str(self.req_test)
            log.info("用例编号"+ str(num) + " " + name + "接口执行成功")
        else:
            sheet.cell(row = i,column = 11).value = "失败"
            sheet.cell(row = i,column = 12).value = str(self.req_test)
            log.error("用例编号"+ str(num) + " " + name + "接口执行失败")

‘‘‘
#请求前缀
url = "http://v.juhe.cn/"
#接口地址
uri = "laohuangli/d"
params = {"key":"e711bc6362b3179f5a28de7fd3ee4ace","date":"2016-5-14"}
headers = {}
#请求类型
reqform = ‘post‘
#数据类型
dataform = ‘json‘
#检查点
checkpoint = "‘error_code‘: 0"

it = InterfaceTest()
it.testrequest(url,uri,params,reqform,dataform,checkpoint,headers)
‘‘‘

 

3\遍历case,读取数据,传入数据给接口类,得到请求类的数据,实际结果与预期结果做对比,填写case,得到报告

#! /usr/bin/env python
#coding=utf-8


import openpyxl

import sys
sys.path.append("C:/Users/Administrator/Desktop/接口自动化测试/src")
from laohuangli_InterfaceTest import InterfaceTest

sys.path.append("C:/Users/Administrator/Desktop/接口自动化测试/common")
from log import Log
#避免转义,将\写成/
#path = "C:/Users/Administrator/Desktop/laohuangli-testcase.xlsx"

class ReadCase:
    def get_case(self,path1,path2):
        log = Log(C:/Users/Administrator/Desktop/接口自动化测试/logs/test.log)
        try:
            #打开excel文件,返回标记位给wb
            wb = openpyxl.load_workbook(path1)
            log.info("打开测试用例成功!")
        except BaseException as e:
            log.info("打开测试测试用例失败:",str(e))
        #获取sheet(第二个sheet)
        sheet = wb.get_sheet_by_name("TestCase")
        print("获取指定的工作表:",sheet.title)

#for循环遍历case
        for i in range(2,sheet.max_row + 1):
            if sheet.cell(row = i,column = 10).value.replace(\n,‘‘).replace(r,‘‘) != Yes:
                continue
        
            request_data1 = sheet.cell(row = i,column = 1).value
            print(type(request_data1),request_data1)
    
            request_data2 = sheet.cell(row = i,column = 2).value
            print(type(request_data2),request_data2)

            request_data3 = sheet.cell(row = i,column = 3).value
            print(type(request_data3),request_data3)
    
            request_data4 = sheet.cell(row = i,column = 4).value
            print(type(request_data4),request_data4)
    
            request_data5 = sheet.cell(row = i,column = 5).value
            print(type(request_data5),request_data5)
    
            request_data6 = sheet.cell(row = i,column = 6).value
            print(type(request_data6),request_data6)
    
            request_data7 = sheet.cell(row = i,column = 7).value
            #excel里取出来的是字符串,需要用eval函数转换
            #取的是字符串,转换成字典
            request_data7 = eval(request_data7)
            print(type(request_data7),request_data7)
    
    
            request_data8 = sheet.cell(row = i,column = 8).value
            print(type(request_data8),request_data8)
    
            request_data9 = sheet.cell(row = i,column = 9).value
            print(type(request_data9),request_data9)

       
            #调用接口类
            headers = {}
            it = InterfaceTest()
            it.testrequest(request_data3,request_data4,request_data7,request_data5,request_data6,request_data8,headers,i,sheet,request_data1,request_data2,log)
            
#保存数据,excel另存为
        wb.save(path2)

‘‘‘
#测试用例地址
path1 = "C:/Users/Administrator/Desktop/laohuangli-testcase.xlsx"
path2 = "C:/Users/Administrator/Desktop/laohuangli-testreport.xlsx"
readcase1 = ReadCase()
readcase1.get_case(path1,path2)

    if sheet.cell(row = i,column = 10).value.replace(‘\n‘,‘‘).replace(‘r‘,‘‘) != ‘Yes‘:
        continue
    request_data1 = sheet.cell(row = i,column = 2).value.replace(‘\n‘,‘‘).replace(‘r‘,‘‘)
    #excel里取出来的是字符串,需要用eval函数转换
    print(type(request_data1))

    request_data1 = eval(request_data1)
    print(request_data1)
‘‘‘

4\发送邮件的代码封装成类

#! /usr/bin/env python
#coding=utf-8


import smtplib
import email.mime.multipart
import email.mime.text

from email.mime.application import MIMEApplication

‘‘‘
先来想下发送邮件需要填写什么,还需要有什么条件
1.与邮件服务器建立连接,用户名和密码
2.发邮件:发件人\收件人\主题\内容\附件
3.发送
‘‘‘




class SendMail:
    
    def send_mail(self,sender,receiver,title,attach_xlsx,attach_jpg):
        msg=email.mime.multipart.MIMEMultipart()#生成包含多个邮件体的对象
        msg[from]=sender
        msg[to]=receiver
        msg[subject]= title
        content=‘‘‘
        Hi all,
        这是一封huipaodexiong自动化测试发送的邮件
        QQ:361702852
        博客:xxxxxxxxxxxxxx            
        微信号:361702852            
        带附件
        ‘‘‘
        print(成功1)
        #邮件正文,将文件正文当成附件发送,当正文内容很多时,提高效率
        txt=email.mime.text.MIMEText(content)
        msg.attach(txt)
        print(成功2)
        
        #excel附件--固定格式
        xlsxpart = MIMEApplication(open(attach_xlsx, rb).read())
        xlsxpart.add_header(Content-Disposition, attachment, filename=laohuangli-testcase1.xlsx)
        msg.attach(xlsxpart)

        #jpg图片附件
        jpgpart = MIMEApplication(open(attach_jpg, rb).read())
        jpgpart.add_header(Content-Disposition, attachment, filename=接口测试框架.jpg)
        msg.attach(jpgpart)
        
        
        #发送邮件
        smtp=smtplib
        smtp=smtplib.SMTP()
        smtp.set_debuglevel(1)#设置为调试模式,console中显示
        print(成功3)
        smtp.connect(smtp.126.com,25) #链接服务器,smtp地址+端口
        print(成功4)
        smtp.login(huipaodexiong@126.com,xxxxxx) #登录,用户名+密码
        print(成功5)
        smtp.sendmail(sender,receiver,str(msg)) #发送,from+to+内容
        smtp.quit()
        print(发送邮件成功)

"""
sender = ‘huipaodexiong@126.com‘
receiver = ‘huipaodexiong@126.com‘
title = ‘测试文件‘
attach_xlsx = ‘C:/Users/Administrator/Desktop/laohuangli-testcase1.xlsx‘
attach_jpg = ‘C:/Users/Administrator/Desktop/接口测试框架.jpg‘

mail = SendMail()
mail.send_mail(sender,receiver,title,attach_xlsx,attach_jpg)
"""

5\主文件入口

调用遍历case类,并传递相关参数(case文件,report文件)

调用发送邮件的类,并传递相关参数(发件人,收件人,主题,附件)

#! /usr/bin/env python
#coding=utf-8
import sys
sys.path.append("C:/Users/Administrator/Desktop/接口自动化测试/src")
from readCase import ReadCase

sys.path.append("C:/Users/Administrator/Desktop/接口自动化测试/common")
from sendMail import SendMail

path1 = "C:/Users/Administrator/Desktop/接口自动化测试/case/laohuangli-testcase.xlsx"
path2 = "C:/Users/Administrator/Desktop/接口自动化测试/report/laohuangli-testreport.xlsx"

rc = ReadCase()
rc.get_case(path1,path2)


sender = huipaodexiong@126.com
receiver = huipaodexiong@126.com
title = 测试文件

attach_jpg = C:/Users/Administrator/Desktop/接口自动化测试/report/接口测试流程图.jpg

mail = SendMail()
mail.send_mail(sender,receiver,title,path2,attach_jpg)
print("成功")

6\日志类,关键地方打印日志

接口判断,调用请求,请求结果\....等等一些重要地方打印日志

#! /usr/bin/env python
#coding=utf-8
import logging
import os


#实现,让日志信息既在控制台,也在指定路径的文件中输出
#日志级别等级 CRITICAL > ERROR > WARNING > INFO > DEBUG
class Log():
    def __init__(self,log_file):
        #创建一个logger,顶级的根目录getlogger,有两个分支,一个是FileHander,一个是StreamHandler
        self.logger = logging.getLogger(mylogger)
        self.logger.setLevel(logging.INFO)

        #创建一个handler,将log写入文件
        fh = logging.FileHandler(log_file,mode = w)
        fh.setLevel(logging.INFO)

        #再创建一个handler,将log输出到控制台
        ch = logging.StreamHandler()
        ch.setLevel(logging.INFO)

        #设置输出格式
        log_format = "%(asctime)s %(filename)s [line:%(lineno)d] %(levelname)s: %(message)s"
        #把格式添加进来
        formatter = logging.Formatter(log_format)
        fh.setFormatter(formatter)
        ch.setFormatter(formatter)


        #把handler添加到logger里,其实你理解为汇报给大领导即可
        self.logger.addHandler(fh)
        self.logger.addHandler(ch)
        
    def info(self,content):
        self.logger.info(content)
        
    def error(self,content):
        self.logger.error(content)
        
        
        
‘‘‘
log1 = Log(‘D:/接口自动化测试/logs/test.log‘)
log1.info("测试") 
‘‘‘   
‘‘‘
logger.error(‘下雨了‘)
logger.info(‘打雷了‘)
logger.debug(‘收衣服了‘)
‘‘‘

 

简单的运行结果:

技术分享

 

技术分享

 

技术分享

 

http接口测试框架-python

标签:dex   save   没有   sys   except   eval   app   插件   标记   

原文地址:http://www.cnblogs.com/R-bear/p/7192571.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!