Appium+Python之PO模型(Page object Model)
阿新 • • 發佈:2019-01-07
思考:我們進行自動化測試時,如果把程式碼都寫在一個指令碼中,程式碼的可讀性會變差,且後期程式碼維護也麻煩,最好的想法就是測試物件和測試用例可以分離,可以很快定位問題,程式碼可讀性高,也比較容易理解。這裡推薦大家在自動化框架中加入PO模型思想,那什麼是PO模型呢?
所謂的PO就是page object,通俗解釋一下就是每個頁面當成一個物件,給這些頁面寫一個類,主要就是完成元素定位和業務操作;至於測試指令碼要和ta區別開來,需要什麼去這些頁面類去呼叫即可。
上面流程圖意思就是測試用例類呼叫不同的頁面類,頁面類呼叫公共基類,基類裡面封裝定義定位頁面元素和基本業務操作方法。
BasePage.py(頁面基類指令碼)
# -*- coding: utf-8 -*- ''' Created on 2018-11-4 @author: 丹姐 Project:UI頁面公共類 ''' from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC import selenium.common.exceptions from selenium.webdriver.common.by import By #定義頁面基類 classBasePage(object): #初始化 def __init__(self,driver): self.driver=driver # 重寫元素定位方法 def find_element(self,timeout,poll_frequency,type,*loc): element=WebDriverWait(self.driver, timeout, poll_frequency).until( EC.presence_of_element_located((type,*loc)))return element # 重寫定義send_keys方法 def send_keys(self,timeout,poll_frequency,type,loc,value): try: self.find_element(timeout,poll_frequency,type,loc).clear() return self.find_element(timeout,poll_frequency,type,loc).send_keys(value) except AttributeError: print("%s 頁面中未能找到 %s 元素" % (self,loc)) # 重寫定義click方法 def click(self,timeout,poll_frequency,type,*loc): return self.find_element(timeout,poll_frequency,type,*loc).click() # 重寫多元素定位方法 def find_elements(self,timeout,poll_frequency,index,type,*loc ): elements = WebDriverWait(self.driver, timeout, poll_frequency).until( EC.presence_of_all_elements_located((type, *loc))) return elements[index]
LoginPage.py(登入頁面指令碼)
# coding=utf-8 ''' Created on 2018-11-4 @author: 丹姐 Project:登入頁面 ''' from src.common.BasePage import BasePage from selenium.webdriver.common.by import By # 定義登入頁面類,父類是BasePage class Login(BasePage): etUser_loc = "com.baidu.baidu:id/et_name" etPws_loc = "com.baidu.baidu:id/et_pass" btnLogin_loc = "com.baidu.baidu:id/rt_login" def login_in(self, username, password): print(u'輸入使用者名稱', username) self.send_keys(10, 0.1, By.ID, self.etUser_loc, username) print(u'輸入密碼', password) self.send_keys(10, 0.1, By.ID, self.etPws_loc, password) print(u'點選登入按鈕') self.click(20, 0.1, By.ID, self.btnLogin_loc)
TestCase.py(測試用例指令碼)
# coding=utf-8 ''' Created on 2018-12-24 @author: 丹姐 Project:登入測試用例 ''' import unittest from config import DriverConfigure from src.pages.Login import Login class Login(unittest.TestCase): @classmethod def setUpClass(cls): driver = DriverConfigure.get_driver() cls.driver = driver def setUp(self): self.login_page = Login(self.driver) def test_login(self): # 登入 self.login_page.login_in("zhanghao", "123456") def tearDown(self): pass @classmethod def tearDownClass(cls): cls.driver.quit()
if __name__ =="__main__": unittest.main()