以數據驅動的形式,將用例維護在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
聲明:本文為博主學習感悟總結,水平有限,如果不當,歡迎指正。如果您認為還不錯,歡迎轉載。轉載與引用請注明作者及出處。