UI物件庫-定位元素與程式分離
1.前言
這幾天有人問我,UI自動化測試中使用到的頁面定位元素應該存放在哪裡比較合適?我想說的是如果你使用的是PO設計模式設計測試用例的話,可以把定位元素存在每一個page頁面,一個page存放對應的TestCase的頁面元素,當頁面變動的時候方便修改。還有一種就是存放在配置檔案下,這樣對於不懂得自動化測試的人員也可以配置。那麼下面我看就來看一下如何存放到配置檔案中?如何來讀取並定位?
2.目錄結構
測試地址:http://www.sogou.com
測試步驟:1.開啟網址2.搜尋框輸入python3.點選搜尋按鈕4.判斷python是否包含在頁面原始碼中
檔案說明:WebElement.ini 存放定位元素。GetElement.py用來讀取配置檔案並查詢頁面元素。SouGouTc.py用來編寫測試用例
3.例項程式碼
WebElement.ini
[sogou] queryBox=id:query queryBtn=id:stb
GetElement.py
1 from selenium.webdriver.support.ui import WebDriverWait 2 import configparser 3 import os 4 from selenium import webdriver 5 class getElement(): 6''' 7從配置檔案中來獲取定位資訊 8''' 9def __init__(self): 10self.elementIni = os.path.dirname(os.path.abspath(__file__))\ 11+r'\WebElement.ini' # 配置檔案所在目錄 12def getElement(self, driver, sogouSection, sogouOption): 13try: 14f = configparser.ConfigParser() 15f.read(self.elementIni) # 讀配置檔案內容到記憶體中 16locators = f.get(sogouSection, sogouOption).split(':') 17# 獲取定位方式 18locaMethod = locators[0] 19# 獲取定位表示式 20locaExpression = locators[1] 21# 通過顯示等待的方式獲取頁面的元素 22element = WebDriverWait(driver,5).until(lambda x : x.find_element(locaMethod, locaExpression)) 23except Exception as e: 24raise e 25else: 26return element 27 28 if __name__ == '__main__': 29ele = getElement() 30print(ele.elementIni) 31driver = webdriver.Firefox() 32driver.get('http://www.sogou.com') 33element = ele.getElement(driver, 'sougou', 'queryBox') 34element.send_keys('python')
SouGouTc.py
1 from selenium import webdriver 2 import unittest 3 import time 4 from programDataSeparate.GetElement import getElement 5 class sogouTc(unittest.TestCase): 6 7def setUp(self): 8self.obj = getElement() 9self.driver = webdriver.Firefox() 10self.driver.get('http://www.sogou.com') 11def testSoGou(self): 12elementQuery = self.obj.getElement(self.driver, 'sogou', 'queryBox') # 搜尋框 13elementQuery.send_keys('python') 14elementBtn = self.obj.getElement(self.driver, 'sogou', 'queryBtn') # 搜尋按鈕 15elementBtn.click() 16time.sleep(2) 17self.assertTrue('python' in self.driver.page_source) # 斷言 18def tearDown(self): 19self.driver.quit() 20 21 if __name__ == '__main__': 22unittest.main()
總結
本例項實現了程式與資料的分離,首先從UI物件庫檔案WebElement.ini中取得sogou首頁中需要操作的頁面元素的定位方式和定位表示式,然後在GetElement.py中取得該頁面元素的例項物件,最後返回給測試用例方法中進行後續處理,這樣做的好處是即使不懂得測試的人員也可以配置用例。