Selenium PageObject设计模式
简介
PageObject是Selenium自动化测试项目开发实践的最佳设计模式之一,通过对界面元素的封装减少冗余代码,同时在后期维护中,若元素定位发生变化,只需要调整页面元素封装的代码,提高测试用例的可维护性。
实践案例
1.封装BasePage
from selenium import webdriver
from time import sleep
class Page():
'''页面基础类'''
#初始化
def __init__(self, dirver):
self.base_url = 'https://passport.csdn.net'
self.driver = dirver
self.timeout = 30
#打开不同的子页面
def _open(self, url):
url_ = self.base_url + url
print("Test page is: %s" %url_)
self.driver.maximize_window()
self.driver.get(url_)
sleep(2)
assert self.driver.current_url == url_, 'Did ont land on %s' % url_
def open(self):
self._open(self.base_url)
def quit(self):
self.driver.quit()
#元素定位方法封装
def find_element(self,*loc):
return self.driver.find_element(*loc)
if __name__ == '__main__':
driver = webdriver.Chrome()
BsPg = Page(driver)
BsPg._open('/login')
BsPg.quit()
2.封装Loginpage
from BasePage import *
from selenium.webdriver.common.by import By
from selenium import webdriver
class LoginPage(Page):
'''首页登录页面'''
url='/login'
#定位器
username_loc=(By.NAME,'all')
password_loc=(By.NAME,'pwd')
submit_loc=(By.CLASS_NAME,'btn-primary')
click_loc=(By.LINK_TEXT,'账号密码登录')
#用户名输入框元素
def type_username(self,username):
self.find_element(*self.username_loc).clear()
self.find_element(*self.username_loc).send_keys(username)
#密码输入框元素
def type_password(self,password):
self.find_element(*self.password_loc).clear()
self.find_element(*self.password_loc).send_keys(password)
#登录按钮元素
def type_submit(self):
self.find_element(*self.submit_loc).click()
#点击切换登录方式
def type_click(self):
self.find_element(*self.click_loc).click()
#登录功能模块封装
def test_user_login(driver,username,password):
'''测试用户名密码是否可以登录'''
login_page=LoginPage(driver)
login_page.open()
login_page.type_click()
sleep(2)
login_page.type_username(username)
login_page.type_password(password)
sleep(2)
login_page.type_submit()
if __name__ == '__main__':
driver = webdriver.Chrome()
test_user_login(driver,'testname','testpwd')
3.封装登录测试模块
from LoginPage import *
from selenium import webdriver
driver=webdriver.Chrome()
username = '51zxw'
password = '123456'
test_user_login(driver, username, password)
sleep(3)
driver.quit()