1. 程式人生 > >python+requests+unittest 介面ddt測試

python+requests+unittest 介面ddt測試

以資料驅動的形式,將用例維護在py檔案中

 

原始碼分析:

 

變數定義

publicParameters.py
  
"""
公共引數 , 按照各公司實情,自行編寫
"""
url = "https://XXXX.com"
username = "XXXXXXX"
password = XXXX
tenantId = XXXX
passport_id = XXXX
encryptionKey = XXXX

# 請求引數型別
getType = 'get'
postType = 'post'

 

引數定義

login.py
from
. import publicParameters # 介面資訊 API_ALL = { '登入介面': { 'number': '1', 'url': publicParameters.url + "xxxxxxxx", 'type': publicParameters.postType, 'head': { 'Content-Type': 'application/x-www-form-urlencoded', 'User-Agent'
: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.80 Safari/537.36' }, 'body': { "loginName": "%s" % publicParameters.username, "password": "%s" % publicParameters.password, "pcCodeForFocusMedia
": 0 }, 'assert': { 'status': 202, }, }, '選擇租戶介面': { 'number': '2', 'url': publicParameters.url + "xxxxxxxx", 'type': publicParameters.postType, 'head': { 'Content-Type': 'application/x-www-form-urlencoded', 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.80 Safari/537.36' }, 'body': { "tenantId": "%s" % publicParameters.tenantId, "passport.id": publicParameters.passport_id, "encryptionKey": "%s" % publicParameters.encryptionKey, "loginName": "%s" % publicParameters.username }, 'assert': { 'status': 0, }, } }

 

執行工具類

test.py
import requests
import time

from autoTest.Api_test.common.login import API_ALL
from autoTest.Api_test.page.Log import Log


def Script():
    log = Log()  # 引用日誌方法

    apikeys = API_ALL.keys()  # 獲取所有Api引數
    if apikeys:
        for key in apikeys:
            apiname = key
            url = API_ALL[key]['url']
            number = API_ALL[key]['number']
            type = API_ALL[key]['type']
            body = API_ALL[key]['body']
            assertDate = API_ALL[key]['assert']['status']
            if type == 'post':
                log.info("======="+" api名稱:" + apiname + "=======")
                data = requests.post(url=url, data=body, verify=False)
                log.info(data.json())
                if assertDate == data.json()['status']:
                    testCode = str(data.status_code)
                    Time = str(data.elapsed.microseconds)
                    log.info("執行編號:" + number + "  響應code:" + testCode + "  響應時間:" + Time + "  請求型別:" + type + "  請求引數:" + str(body))
                else:
                    log.error("介面返回異常, status=%s" % data.json()['status'])
                time.sleep(1)

            if type == 'get':
                log.info("======="+" api名稱:" + apiname + "=======")
                data = requests.get(url=url, data=body, verify=False)
                log.info(data.json())
                if assertDate == data.json()['status']:
                    testCode = str(data.status_code)
                    Time = str(data.elapsed.microseconds)
                    log.info("執行編號:" + number + "  響應code:" + testCode + "  響應時間:" + Time + "  請求型別:" + type + "  請求引數:" + str(body))
                else:
                    log.error("介面返回異常, status=%s" % data.json()['status'])
                time.sleep(1)

    else:
        log.error("資料不存在")

 

unittest執行類

testCase.py
import unittest

import requests
from requests.packages.urllib3.exceptions import InsecureRequestWarning

# 禁用安全請求警告
requests.packages.urllib3.disable_warnings(InsecureRequestWarning)

from autoTest.Api_test.ApiTest import test


class testclassone(unittest.TestCase):
    def setUp(self):
        print("setUp")
        pass
    def test_1(self):
        # 執行指令碼
        test.Script()
        pass
    def tearDown(self):
        print("tearDown")
        pass

if __name__ == '__main__':
    unittest.main()

 

最後,我們還可以批量執行case

# coding=utf-8
import unittest
import time
from autoTest.autoTestAPI import HTMLTestRunner_jpg
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
import smtplib
import os

'''
#### 下面三行程式碼python2報告出現亂碼時候可以加上####
import sys
reload(sys)
sys.setdefaultencoding('utf8')
'''

# 這個是優化版執行所有用例併發送報告,分四個步驟
# 第一步載入用例
# 第二步執行用例
# 第三步獲取最新測試報告
# 第四步傳送郵箱 (這一步不想執行的話,可以註釋掉最後面那個函式就行)

# 當前指令碼所在檔案真實路徑
cur_path = os.path.dirname(os.path.realpath(__file__))

def add_case(caseName="case", rule="test*.py"):
    '''第一步:載入所有的測試用例'''
    case_path = os.path.join(cur_path, caseName)  # 用例資料夾
    # 如果不存在這個case資料夾,就自動建立一個
    if not os.path.exists(case_path):os.mkdir(case_path)
    print("test case path:%s"%case_path)
    # 定義discover方法的引數
    discover = unittest.defaultTestLoader.discover(case_path,
                                                  pattern=rule,
                                                  top_level_dir=None)
    print(discover)
    return discover

def run_case(all_case, reportName="report"):
    '''第二步:執行所有的用例, 並把結果寫入HTML測試報告'''
    now = time.strftime("%Y_%m_%d_%H_%M_%S")
    report_path = os.path.join(cur_path, reportName)  # 用例資料夾
    # 如果不存在這個report資料夾,就自動建立一個
    if not os.path.exists(report_path):os.mkdir(report_path)
    report_abspath = os.path.join(report_path, "result.html")
    print("report path:%s"%report_abspath)
    fp = open(report_abspath, "wb")
    runner = HTMLTestRunner_jpg.HTMLTestRunner(stream=fp,
                                           title=u'自動化測試報告,測試結果如下:',
                                           description=u'用例執行情況:',
                                            retry=1  # 失敗重跑
                                           )

    # 呼叫add_case函式返回值
    runner.run(all_case)
    fp.close()

def get_report_file(report_path):
    '''第三步:獲取最新的測試報告'''
    lists = os.listdir(report_path)
    lists.sort(key=lambda fn: os.path.getmtime(os.path.join(report_path, fn)))
    print (u'最新測試生成的報告: '+lists[-1])
    # 找到最新生成的報告檔案
    report_file = os.path.join(report_path, lists[-1])
    return report_file

def send_mail(sender, psw, receiver, smtpserver, report_file, port):
    '''第四步:傳送最新的測試報告內容'''
    with open(report_file, "rb") as f:
        mail_body = f.read()
    # 定義郵件內容
    now_time = time.strftime("%Y-%m-%d %H:%M:%S")
    msg = MIMEMultipart()
    body = MIMEText(mail_body, _subtype='html', _charset='utf-8')
    msg['Subject'] = u"自動化測試報告_%s"%now_time
    msg["from"] = sender
    msg["to"] = "".join(receiver)     # 只能字串
    msg.attach(body)
    # 新增附件
    att = MIMEText(open(report_file, "rb").read(), "base64", "utf-8")
    att["Content-Type"] = "application/octet-stream"
    att["Content-Disposition"] = 'attachment; filename= "report.html"'
    msg.attach(att)
    try:
        smtp = smtplib.SMTP()
        smtp.connect(smtpserver)                      # 連伺服器
        smtp.login(sender, psw)
    except:
        smtp = smtplib.SMTP_SSL(smtpserver, port)
        smtp.login(sender, psw)                       # 登入
    smtp.sendmail(sender, receiver, msg.as_string())
    smtp.quit()
    print('test report email has send out !')

if __name__ == "__main__":
    all_case = add_case()   # 1載入用例
    # # 生成測試報告的路徑
    run_case(all_case)        # 2執行用例
    # # 獲取最新的測試報告檔案
    report_path = os.path.join(cur_path, "report")  # 用例資料夾
    report_file = get_report_file(report_path)  # 3獲取最新的測試報告
    # #郵箱配置
    sender = "xxxxxx"
    psw = "xxxxx"
    smtp_server = "smtp.163.com"
    port = 465
    receiver = ['xxxxxx']
    send_mail(sender, psw, receiver, smtp_server, report_file, port)  # 4最後一步傳送報告

 

當然缺少HTMLTestRunner_jpg檔案的同學,可以百度自行下載(找個好看的)

到這,一個簡單的ddt就完成了, 是不是很簡單?  哈哈, 中午休息時間,寫了程式碼,又完成了一篇部落格,  6666

 

作者:含笑半步顛√

部落格連結:https://www.cnblogs.com/lixy-88428977

宣告:本文為博主學習感悟總結,水平有限,如果不當,歡迎指正。如果您認為還不錯,歡迎轉載。轉載與引用請註明作者及出處。