Python&Selenium 資料驅動【unittest+ddt】
阿新 • • 發佈:2018-12-07
一、摘要
本博文將介紹Python和Selenium做自動化測試的時候,基於unittest框架,藉助ddt實現資料驅動
二、測試程式碼
# 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 selenium.common.exceptions importNoSuchElementException # 初始化日誌物件 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='F:\\DataDriven\\TestResults\TestResults.TestResults', # 開啟日誌的方式 filemode='w' ) @ddt.ddt class DataDrivenDDT(unittest.TestCase): def setUp(self): self.driver = webdriver.Chrome(executable_path="F:\\automation\\webdriver\\chromedriver.exe") @ddt.data([u"阿里巴巴", u"騰訊"], [u"美團外賣", u"百度"], [u"餓了麼", u"螞蟻金服"]) @ddt.unpackdef test_dataDrivenByDDT(self, testdata, expectdata): url = "http://www.baidu.com" self.driver.get(url) self.driver.implicitly_wait(30) try: self.driver.find_element_by_id("kw").send_keys(testdata) self.driver.find_element_by_id("su").click() time.sleep(3) self.assertTrue(expectdata in self.driver.page_source) except NoSuchElementException as e: logging.error(u"查詢的頁面元素不存在,異常堆疊資訊:" + str(traceback.format_exc())) except AssertionError as e: logging.info(u"搜尋 '%s',期望 '%s' ,失敗" % (testdata, expectdata)) except Exception as e: logging.error(u"未知錯誤,錯誤資訊:" + str(traceback.format_exc())) else: logging.info(u"搜尋 '%s',期望 '%s' ,通過" % (testdata, expectdata)) def tearDown(self): self.driver.quit() if __name__ == '__main__': unittest.main()