http接口測試框架-python


簡單分解一下

接口測試框架設計:

主入口 -> 遍歷接口/用例 -> 發送請求+接收響應 ->結果的對比 -> 生成報告 ->發送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('收衣服了')
'''

 

簡單的運行結果:

 

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM