1. 程式人生 > >Python&Selenium 資料驅動【unittest+ddt+json】

Python&Selenium 資料驅動【unittest+ddt+json】

一、摘要

本博文將介紹Python和Selenium做自動化測試的時候,基於unittest框架,藉助ddt模組使用json檔案作為資料檔案作為測試輸入,最後生成html測試報告

二、json檔案

[
  "北京||北京","上海||上海","廣州||廣州","深圳||深圳","香港||香港"
]

三、ReportTemplate.py

# encoding = utf-8
"""
__title__ = 'DataDrivenTestByDDT use this template for generating testing report'
__author__ = 'davieyang'
__mtime__ = '2018/4/21'
""" # encoding = utf-8 def htmlTemplate(trData): htmlStr = u'''<!DOCTYPE HTML> <html> <head> <title>單元測試報告</title> <style> body { width:80%; margin:40px auto; font-weight:bold; font-family: 'trebuchet MS', 'Lucida sans', SimSun; font-size:18px; color: #000; } table { * border-collapse:collapse; border-spacing:0; width:100%; } .tableStyle { /* border:solid #ggg 1px;*/ border-style:outset; border-width:2px; /*border:2px;*/ border-color:blue; } .tableStyle tr:hover { background: rgb(173.216.230); } .tableStyle td,.tableStyle th{ border-left:solid 1px rgb(146,208,80); border-top:1px solid rgb(146,208,80); padding:15px text-align:center } .tableStyle th{ padding:15px; background-color:rgb(146,208,80); /*表格標題欄設定漸變顏色*/ background-image: -webkit -gradient(linear, left top, left bottom, from(#92D050), to(#A2D668)) /*rgb(146,208,80)*/ } </style> </head> <body> <center><h1>測試報告</h1></center><br /> <table class="tableStyle"> <thead> <tr> <th>Search Words</th> <th>Assert Words</th> <th>Start Time</th> <th>Waste Time(s)</th> <th>Status</th> </tr> </thead>
''' endStr = u''' </table> </body> </html>''' html = htmlStr + trData + endStr print(html) with open("D:\\\Programs\\\Python\\\PythonUnittest\\\Reports\\testTemplate.html", "wb") as fp: fp.write(html.encode("gbk"))

 四、測試指令碼

# encoding = utf-8
""" __title__ = '' __author__ = 'davieyang' __mtime__ = '2018/4/21' """ from selenium import webdriver import unittest import time import logging import traceback import ddt from DataDrivenTest.ReportTemplate import htmlTemplate from selenium.common.exceptions import NoSuchElementException # 初始化日誌物件 logging.basicConfig( # 日誌級別 level=logging.INFO, # 時間、程式碼所在檔名、程式碼行號、日誌級別名字、日誌資訊 format='%(asctime)s %(filename)s[line: %(lineno)d] %(levelname)s %(message)s', # 列印日誌的時間 datefmt='%a, %d %b %Y %H:%M:%S', # 日誌檔案存放的目錄及日誌檔名 filename='D:\\Programs\\Python\\PythonUnittest\\Reports\\TestResults.TestResults', # 開啟日誌的方式 filemode='w' ) @ddt.ddt class DataDrivenTestByDDT(unittest.TestCase): @classmethod def setUpClass(cls): # 整個測試過程只調用一次 DataDrivenTestByDDT.trStr = "" def setUp(self): self.driver = webdriver.Chrome(executable_path="D:\\Programs\\Python\\PythonUnittest\\BrowserDrivers\\chromedriver.exe") status = None # 用於存放測試結果狀態,失敗‘fail’,成功‘pass’ flag = 0 # 資料驅動測試結果的標誌,失敗置0,成功置1 @ddt.file_data("D:\\Programs\\Python\\PythonUnittest\\TestData\\test_data_list.json") def test_dataDrivenByFile(self, value): # 決定測試報告中狀態單元格中內容的顏色 flagDict = {0: 'red', 1: '#00AC4E'} url = "http://www.baidu.com" self.driver.get(url) self.driver.maximize_window() print(value) # 從.json檔案中讀取出的資料用“||”分割成測試資料和期望的資料 testdata, execptdata = tuple(value.strip().split("||")) # 設定隱式等待時間 self.driver.implicitly_wait(10) try: # 獲取當前的時間戳,用於後面計算查詢耗時用 start = time.time() # 獲取當前時間的字串,表示測試開始時間 startTime = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) self.driver.find_element_by_id("kw").send_keys(testdata) self.driver.find_element_by_id("su").click() time.sleep(3) # 斷言期望結果是否出現在頁面中 self.assertTrue(execptdata in self.driver.page_source) except NoSuchElementException as e: logging.error(u"查詢的頁面元素不存在,異常堆疊資訊為:"+ str(traceback.format_exc())) status = 'fail' flag = 0 except AssertionError as e: logging.info(u"搜尋 ‘%s’,期望 ‘%s’ ,失敗" %(testdata, execptdata)) status = 'fail' flag = 0 except Exception as e: logging.error(u"未知錯誤,錯誤資訊:" + str(traceback.format_exc())) status = 'fail' flag = 0 else: logging.info(u"搜尋 ‘%s’,期望 ‘%s’ ,通過" %(testdata, execptdata)) status = 'pass' flag = 1 # 計算耗時,從將測試資料輸入到輸入框中到斷言期望結果之間所耗時 wasteTime = time.time() - start - 3 # 減去強制等待3秒 # 每一組資料測試結束後,都將其測試結果資訊插入表格行的HTML程式碼中,並將這些行HTML程式碼拼接到變數trStr變數中, # 等所有測試資料都被測試結束後,傳入htmlTemplate()函式中,生成完整測試報告的HTML程式碼 DataDrivenTestByDDT.trStr += u''' <tr> <td>%s</td> <td>%s</td> <td>%s</td> <td>%.2f</td> <td style = "color: %s">%s</td> </tr><br/>''' % (testdata, execptdata, startTime, wasteTime, flagDict[flag], status) def tearDown(self): self.driver.quit() @classmethod def tearDownClass(cls): # 寫自定義的HTML測試報告,整個過程只被呼叫一次 htmlTemplate(DataDrivenTestByDDT.trStr) if __name__ == '__main__': unittest.main()

 五、生成日誌

Fri, 07 Dec 2018 15:05:36 DataDrivenTestByDDT.py[line: 81] INFO 搜尋 ‘北京’,期望 ‘北京’ ,通過
Fri, 07 Dec 2018 15:05:50 DataDrivenTestByDDT.py[line: 81] INFO 搜尋 ‘上海’,期望 ‘上海’ ,通過
Fri, 07 Dec 2018 15:06:04 DataDrivenTestByDDT.py[line: 81] INFO 搜尋 ‘廣州’,期望 ‘廣州’ ,通過
Fri, 07 Dec 2018 15:06:18 DataDrivenTestByDDT.py[line: 81] INFO 搜尋 ‘深圳’,期望 ‘深圳’ ,通過
Fri, 07 Dec 2018 15:06:32 DataDrivenTestByDDT.py[line: 81] INFO 搜尋 ‘香港’,期望 ‘香港’ ,通過

六、測試報告