Python+Selenium筆記(四):unittest的Test Suite(測試套件),seleniumunittest

來源:互聯網
上載者:User

Python+Selenium筆記(四):unittest的Test Suite(測試套件),seleniumunittest

 

(一) Test Suite測試套件

一個測試套件是多個測試或測試案例的集合,是針對被測程式的對應的功能和模組建立的一組測試,一個測試套件內的測試案例將一起執行。

應用unittest的TestSuites特性,可以將不同的測試組成一個邏輯組,然後設定統一的測試套件,並通過一個命令來執行測試。這都是通過TestSuites、TestLoader和TestRunn類來實現的。

(二) 類層級的setUp()方法和tearDown()方法

使用setUpClass()方法和tearDownClass()方法及@classmethod標識來實現各個測試方法共用初始化資料。具體看下面的代碼。

(三) searchtest.py

import unittest

from selenium import webdriver

from selenium.webdriver.common.action_chains import ActionChainsimport time

class SearchTest(unittest.TestCase):
    '''通過setUpClass()和@classmethod標識,實現
     在類層級初始化資料,所有測試方法共用這些初始化資料.
     不使用這個的話,每個測試方法都會單獨建立一個執行個體'''
   
@classmethod
    def setUpClass(cls):
        cls.driver = webdriver.Firefox()
        cls.driver.implicitly_wait(10)
        cls.driver.maximize_window()
        cls.driver.get("https://www.cnblogs.com/")
    def test_search_by_category(self):
        #讀取category.txt檔案,返回一個字典
       
with open('data/category.txt', encoding='UTF-8') as category_file:
            category_dict = dict()
            category_data = category_file.readline().strip().split(',')
            the_class = category_data.pop(0)
            category_dict[the_class] = category_data
        #定位首頁網站分類中的程式設計語言
       
self.search_class = self.driver.find_element_by_xpath('//li/a[@href="/cate/2/"]')
        #游標懸停在“程式設計語言”上
       
ActionChains(self.driver).move_to_element(self.search_class).perform()
        # 以列表形式返回程式設計語言下的所有小類
       
self.search_small = self.driver.find_elements_by_xpath(
            '//div[@id="cate_content_block_2"]/div[@class="cate_content_block"]/ul/li')
        #休眠3秒
       
time.sleep(3)
        small_cate = []
        for s in self.search_small:
            #去掉小類最後面的(0),並添加到列表small_cate中
           
small = str(s.text).split('(')
            small_cate.append(small[0])
        #檢查運算式是否為true(此處檢查程式設計語言下的小類是否與預期結果一致)
        self.assertTrue(small_cate == category_dict["程式設計語言"])
        # self.assertEqual(small_cate,category_dict["程式設計語言"])
   
def test_search_by_look(self):
        self.seach_class = self.driver.find_element_by_xpath('//li/a[@href="/cate/2/"]')
        #定位程式設計語言下的小類Python
       
self.seach_small =self.driver.find_element_by_xpath('//li/a[@href="/cate/python/"]')
        ActionChains(self.driver).move_to_element(self.seach_class).perform()
        self.seach_small.click()
        #檢查開啟的網頁標題是不是 Python - 網站分類 - 部落格園
        # assert "Python - 網站分類 - 部落格園" in self.driver.title
       
self.assertEqual(self.driver.title,"Python - 網站分類 - 部落格園" )
    '''通過tearDownClass()和@classmethod標識,實現
     在類層級初始化資料,所有測試方法共用這些初始化資料'''
   
@classmethod
    def tearDownClass(cls):
        cls.driver.quit()
#加上下面2句,可以通過命令列運行測試,不加的話不影響通過IDE運行測試
if __name__ == '__main__':
    #加verbosity=2參數,在命令列中顯示具體的測試方法
   
unittest.main(verbosity=2)
(四) homepagetest.py
import  unittest
from selenium import  webdriver
from selenium.common.exceptions import NoSuchElementException
from selenium.webdriver.common.by import By
class HomePageTest(unittest.TestCase):
    '''通過setUpClass()和@classmethod標識,實現
     在類層級初始化資料,所有測試方法共用這些初始化資料.
     不使用這個的話,每個測試方法都會單獨建立一個執行個體'''
   
@classmethod
    def setUpClass(cls):
        cls.driver = webdriver.Firefox()
        cls.driver.implicitly_wait(10)
        cls.driver.maximize_window()
        cls.driver.get("https://www.cnblogs.com/")
    def test_search_field(self):
        #通過by,檢查部落格園首頁有沒有搜尋方塊,is_element_present()是自訂的方法
       
self.assertTrue(self.is_element_present(By.ID,"zzk_q"))
    def test_search_btn(self):
        # 通過by,檢查部落格園首頁有沒有找找看按鈕
       
self.assertTrue(self.is_element_present(By.CLASS_NAME,"search_btn"))
    def test_menu(self):
        #該方法檢查部落格園首頁功能表列資訊是否與預期一致
        #讀取menu.txt檔案資料
       
with open('data/menu.txt',encoding='UTF-8') as menu_file:
            menu_data = menu_file.readline().strip().split(',')
        #以列表形式返回部落格園首頁功能表列資訊
       
self.check_menu = self.driver.find_elements_by_xpath('//div[@id="nav_menu"]/a')
        the_menu = []
        for c in self.check_menu:
            #將部落格園首頁的菜單名稱和URL添加到列表the_menu
           
the_menu.append(c.text + c.get_attribute('href'))
        #檢查2個列表是否一致(檢查部落格園首頁的菜單名稱及URL是否和預期一致)
       
self.assertListEqual(the_menu,menu_data)
    def is_element_present(self,how,what):
        #找到元素,返回True,否則返回False
       
try:
            self.driver.find_element(by=how,value = what)
        except NoSuchElementException as e:
            return False
        return True
   
@classmethod
    def tearDownClass(cls):
        cls.driver.quit()
# 加上下面2句,可以通過命令列運行測試,不加的話不影響通過IDE運行測試
if __name__ == '__main__':
    # 加verbosity=2參數,在命令列中顯示具體的測試方法
   
unittest.main(verbosity=2)
(五) smoketests.py (測試套件)
import unittest
from searchtest import SearchTest
from homepagetest import HomePageTest
#擷取SearchTest類 和 HomePageTest類中的所有測試方法
search_test = unittest.TestLoader().loadTestsFromTestCase(SearchTest)
home_page_test = unittest.TestLoader().loadTestsFromTestCase(HomePageTest)
#建立一個包括SearchTest和HomePageTest的測試套件
smoke_tests = unittest.TestSuite([home_page_test,search_test])
#運行測試套件
unittest.TextTestRunner(verbosity=2).run(smoke_tests)

(六) 其他說明

#另外一個檔案在上一篇中已經說明

要完全使用上面的代碼,需要建立一個檔案menu.txt,輸入以下資料:

園子https://home.cnblogs.com/,新聞https://news.cnblogs.com/,博問https://q.cnblogs.com/,快閃記憶體https://ing.cnblogs.com/,小組https://group.cnblogs.com/,收藏https://wz.cnblogs.com/,招聘https://job.cnblogs.com/,班級https://edu.cnblogs.com/,找找看http://zzk.cnblogs.com/

 

 

(七) 運行smoketests.py

 

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.