Python&Selenium 數據驅動【unittest+ddt+json】

1、摘要

本博文將介紹Python和Selenium作自動化測試的時候,基於unittest框架,藉助ddt模塊使用json文件做爲數據文件做爲測試輸入,最後生成html測試報告html

2、json文件

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

3、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"))

 4、測試腳本

# 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()

 5、生成日誌

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 搜索 ‘香港’,指望 ‘香港’ ,經過

6、測試報告

相關文章
相關標籤/搜索