1. 程式人生 > >python+selenium+unitest+HTMLRunner 框架針對從業者專案案例

python+selenium+unitest+HTMLRunner 框架針對從業者專案案例

-------------------------------呼叫模組
# coding=utf-8
import os,time
import unittest
import HTMLTestRunner  # 匯入HTMLTestRunner庫,放在指令碼的開頭也是一樣
-------------------------------編碼轉義
import sys
defaultencoding = 'utf-8'
if sys.getdefaultencoding() != defaultencoding:
    reload(sys)
    sys.setdefaultencoding(defaultencoding)
--------------------------------呼叫驅動
from selenium import webdriver

  

--------------------------------設定類名,初始化類
class TestAuto(unittest.TestCase):
    def setUp(self):
        self.driver = webdriver.Chrome()
        self.driver.maximize_window()
---------------------------------案例初始化指令碼
time.sleep(1)
self.driver.get('http://yingxiao.xuanwo001.com')
# self.driver.find_element_by_class_name('el-checkbox__inner').click()  # 勾選不再提示
# time.sleep(1)
# self.driver.find_element_by_xpath('//*[@id="main-content"]/div/div[7]/div/i').click()  # 關閉活動頁面
# time.sleep(1)
self.driver.find_element_by_class_name('main-btn').click()  # 點選觸發登入按鈕
time.sleep(1)
self.driver.find_element_by_xpath(
    '//*[@id="app"]/div[2]/div[1]/div/div[2]/div/h3/button[2]').click()  # 點選切換到密碼登入
time.sleep(1)
self.driver.find_element_by_xpath(
    '//*[@id="app"]/div[2]/div[1]/div/div[2]/form/div[1]/div/div/input').send_keys('手機號')
time.sleep(1)
self.driver.find_element_by_xpath(
    '//*[@id="app"]/div[2]/div[1]/div/div[2]/form/div[2]/div/div/input').send_keys('密碼')
time.sleep(1)
self.driver.find_element_by_class_name('login-btn').click()  # 點選登入
print u'-------------------------------The test case Running start >>'
---------------------------------------------測試用例名設定,以及設計用例title、設定斷言
def testCase_001(self):
    '''驗證網址開啟是否正確測試用例'''
    print u'test_001>正常開啟網址進入旋渦首頁'
    self.assertEqual('https://yingxiao.xuanwo001.com/#/index', self.driver.current_url)
    print u'>>>PASS'

 ....多個用例

-------------------------------------------結束用例
def tearDown(self):
    self.driver.quit()
    print u'--------------------------------The test case End of Run >>'

---------------------------------------------------------------將測試用例集合

if __name__ == '__main__':
    # unittest.mian()
    suiteTest = unittest.TestSuite()
    suiteTest.addTest(TestAuto("testCase_001"))
    suiteTest.addTest(TestAuto("testCase_002"))
    suiteTest.addTest(TestAuto("testCase_003"))

--------------------------------------------------------------生成測試報告的路徑、名稱。描述

# 按照一定時間格式獲取當前時間(防止測試報告覆蓋)
now = time.strftime(u'%Y-%m-%d-%H-%M-%S')
# 確定生成報告的路徑
report_file = "D:\\python+selenium\\report\\" + now + "_test_report.html"
with open(report_file, 'wb') as report:
    runner = HTMLTestRunner.HTMLTestRunner(stream=report, title=u'title',
                                           description=u'描述',
                                           tester=u'測試人員')
    # runner = unittest.TextTestRunner()
    runner.run(suiteTest)
    report.close()