py+webdriver学习之旅7:将page object带入到它的世界里
写这篇文章可以说是重中之重,看了乙醇的ruby+webdriver的文章,深有感触,去自己写一个维护性高的简单自动化框架。废话不多说了,下面首先看个百度首页用户登录的简单webdriver脚本:
__author__ = 'Administrator' #coding=gbk from selenium import webdriver url="http://www.baidu.com" driver=webdriver.Firefox() driver.get(url) #进行一次登录百度账号的操作 driver.find_element_by_name("tj_login").click() driver.find_element_by_name("userName").send_keys("xxx") driver.find_element_by_name("password").send_keys("xxx") driver.find_element_by_xpath("//input[@value='登录']").click()
这段脚本的作用是去到百度,然后点击【登录】按钮,待登录的弹出框弹出后输入用户名和密码,点击【登录】按钮进行登陆。
第一步可以将登录的功能封装成函数:
def login(usr,psd): driver.find_element_by_name("userName").send_keys(usr) driver.find_element_by_name("password").send_keys(psd) driver.find_element_by_xpath("//input[@value='登录']").click() click_login()
第二步:我们思考,如果用黑盒自动化测试用例,对功能测试点进行拆分,我举个栗子:1.有效账号密码 2.无效账号密码 3.账号密码为空,或许大家还有其他想法,这方面我不多深入分析,主要给大家看看脚本的思想接下来怎么去用。
第二步就是对会经常复用的登录按钮动作进行方法的封装:
def click_login(): driver.find_element_by_xpath("//input[@value='登录']").click()
而不输入账号和密码的用例可以简化成:
def login_without_user_psd(): click_login()
第三步,对username,password进行参数化:
def login(usr,psd): driver.find_element_by_name("userName").send_keys(usr) driver.find_element_by_name("password").send_keys(psd) #driver.find_element_by_xpath("//input[@value='登录']").click() click_login() #def login_without_user_psd(): #driver.find_element_by_xpath("//input[@value='登录']").click() def click_login(): driver.find_element_by_xpath("//input[@value='登录']").click() def login_without_user_psd(): click_login()
第四步,完整的自动化框架脚本:
__author__ = 'Administrator' #coding=gbk #该demo可能有点bug,在周六写的,初稿,慢慢完善吧, #主要给大家看个想法,如看出bug,请留言,或联系本人,qq79523822 from selenium import webdriver #启动浏览器的基类 class BrowserContainer: def Newdriver(self): self.dr=webdriver.Firefox() #管理各种页面 class Site(BrowserContainer): def main_page(self,url): self.main_page=MainPage.new(BrowserContainer.dr,url) def close(self): BrowserContainer.dr.close() #所有page对象的基类 class BasePage(BrowserContainer): def intpage(self,dr,url): super(dr) self.url=url def open(self): BrowserContainer.dr.get(self.url) class action(): def login_button(self): BasePage.dr.find_element_by_name("tj_login").click() def usr(self): BasePage.dr.find_element_by_name("userName") def psd(self): BasePage.dr.find_element_by_name("password") def click_login(self): BasePage.find_element_by_xpath("//input[@value='登录']").click() #MainPage类,继承了BasePage,action类,封装了我们的一些操作对象,原子操作及基本步骤 class MainPage(BasePage,action): def login(self,usr,psd): action.login_button() action.usr().send_keys("xxx") action.psd().send_keys("xxx") action.login_button() url="http://www.baidu.com" test_page=Site.main_page(url).open test_page.login(u'你的百度账号',u'你的百度密码')