Page Object Model (Selenium, Python)(一)
2017-04-19 11:22
381 查看
Overview of Page Object Model
A page object represents an area in the web application user interface that your test is interacting with. Page objects reduces the amount of duplicated code and if the user interface changes, the fix needs changes in one place only.[1]WHAT vs HOW
Usually the testers write the test cases describing ‘what’ is to be tested, this depends on the product functionality. But the implementation of this functionality by the developers keeps changing till the final code freeze is done, hence
testers should know ‘how’ to implement the test cases so that the changes to the test scripts are minimal in case of code changes by the the developers. Page Objects encapsulates the finer details(locators and methods) of the pages from
the test script and make the test script more readable and robust.
Sample Test Case – (WHAT)
We are going to explain about page objects with a very simple test case for Gmail.-Goto http://gmail.com
-Enter the username, click Next
-Enter the password, click Sign in
-Perform search on the inbox ‘subject:POM’
-Click on the search result
-Click on inbox
A simple approach would be to write a test script with all the xpaths and the methods required for the execution of the above listed steps in one single file. The test would run fine and achieve the purpose but one major drawback is the test script is brittle.
For any minor UI change on any page, the test script would have to be updated.To overcome this problem we use the page object pattern. As its name suggests,each page of the application to be tested is treated like an object which has the variables (xpaths)
and methods (actions that can be performed on that particular page). This in turn makes the test script much cleaner.
Implementing the test case using POM templates (HOW)
Given below is the pictorial description of the various page objects used for the implementation of the test case.Lets start with the main hero – Page.py
All page models can inherit from the Page class. This has useful wrappers for common Selenium operations
class Page(unittest.TestCase): "Page class that all page models can inherit from" def __init__(self,selenium_driver,base_url='https://mail.google.com/'): "Constructor" #We assume relative URLs start without a / in the beginning if base_url[-1] != '/': base_url += '/' self.base_url = base_url self.driver = selenium_driver #Visit and initialize xpaths for the appropriate page self.start() #Initialize the logger object self.log_obj = Base_Logging(level=logging.DEBUG) def open(self,url): "Visit the page base_url + url" url = self.base_url + url self.driver.get(url) def get_xpath(self,xpath): "Return the DOM element of the xpath OR the 'None' object if the element is not found" def click_element(self,xpath): "Click the button supplied" . . def write(self,msg,level='info'): self.log_obj.write(msg,level) def wait(self,wait_seconds=5): " Performs wait for time provided" time.sleep(wait_seconds)
Next is the Login_Page.py which handles the common functionality of user login. This will be the most re-used class.
from Page import Page class Login_Page(Page): "Page object for the Login page" def start(self): self.url = "" self.open(self.url) # Assert Title of the Login Page and Login self.assertIn("Gmail", self.driver.title) "Xpath of all the field" #Login self.login_email = "//input[@name='Email']" self.login_next_button = "//input[@id='next']" self.login_password = "//input[@placeholder='Password']" self.login_signin_button = "//input[@id='signIn']" def login(self,username,password): "Login using credentials provided" self.set_login_email(username) self.submit_next() self.set_login_password(password) self.submit_login() if 'Qxf2 Mail' in self.driver.title : self.write("Login Success") return True else: self.write("FAIL: Login error") return False def set_login_email(self,username): "Set the username on the login screen" def submit_next(self): self.click_element(self.login_next_button) self.wait(3) def set_login_password(self,password): "Set the password on the login screen" def submit_login(self): "Submit the login form" |
created page objects for each of them. Here is a snippet of each of the classes.
Nav_Menu.py
from Page import Page class Nav_Menu(Page): "Page object for the side menu" def start(self): "Xpath of all the field" #Navigation Menu self.inbox = "//a[contains(@href, '#inbox')]" self.sent_mail = "//a[contains(@href, '#sent')]" self.drafts= "//a[contains(@href, '#drafts')]" def select_menu_item(self,menu_item): "select menu item" |
from Page import Page class Header_Section(Page): "Page object for the page header" def start(self): "Xpath of all the fields" #Search and profile self.search_textbox = "//input[@id='gbqfq']" self.search_button = "//button[@id='gbqfb']" self.signout_button = "//a[text()='Sign out']" self.search_result = "//span[contains(text(),'%s')]" def search_by_subject(self,searchtext): self.set_text(self.search_textbox,'subject:'+searchtext) |
class Main_Page(Page): "Page object for the Main page" def start(self): self.url = "" self.open(self.url) #Create a Header Section object self.header_obj = Header_Section(self.driver) #Create a Menu object self.menu_obj = Nav_Menu(self.driver) |
**Please note – as an alternate way, we can also have a ‘Template_Page'(which inherits from the Page class and has the common objects) and have all pages(except Login page) derive from it.
In addition to these we have the following files
PageFactory.py
PageFactory uses the factory design pattern. get_page_object() returns the appropriate page object.
def get_page_object(page_name,driver,base_url='https://gmail.com/'): "Return the appropriate page object based on page_name" test_obj = None page_name = page_name.lower() if page_name == "login": test_obj = Login_Page(driver,base_url=base_url) elif page_name == "main": test_obj = Main_Page(driver,base_url=base_url) return test_obj |
login.credentials file contains the username , password required for authentication.
Finally , we have our test script which puts it all together and executes the test case.
Search_Inbox_Test.py
def run_search_inbox_test(browser,conf,base_url,sauce_flag,browser_version,platform,testrail_run_id): "Login to Gmail using the page object model" # get the test account credentials from the .credentials file credentials_file = os.path.join(os.path.dirname(__file__),'login.credentials') username = Conf_Reader.get_value(credentials_file,'LOGIN_USER') password = Conf_Reader.get_value(credentials_file,'LOGIN_PASSWORD') #Result flag used by TestRail result_flag = False #Setup a driver #create object of driver factory driver_obj = DriverFactory() driver = driver_obj.get_web_driver(browser,sauce_flag,browser_version,platform) driver.maximize_window() #Create a login page object login_obj = PageFactory.get_page_object("login",driver) if (login_obj.login(username,password)): msg = "Login was successful" result_flag = True login_obj.write(msg) else: msg = "Login failed" login_obj.write(msg) #Create an object for main page with header and menu main_obj = PageFactory.get_page_object("main",driver) main_obj.wait(3) #Search the inbox for message by subject 'POM' and open the message if main_obj.header_obj.search_by_subject('POM'): main_obj.write("Search successful") result_flag = True else: main_obj.write("Search text was not found") result_flag = False #Go to inbox main_obj.menu_obj.select_menu_item('inbox') |
Running the test
Let us execute the test,and here is the log file for the test run.
So now, we all agree that the page objects make it really easy for the tester to convert the documented test case to an automated test case. Not only that, maintaining these tests is also very easy.
原文:https://qxf2.com/blog/page-object-model-selenium-python/?utm_source=tuicool&utm_medium=referral
相关文章推荐
- Selenium的PO模式(Page Object Model)[python版]
- Page Object Model (Selenium + Python)(三)
- Selenium的PO模式(Page Object Model)|(Selenium Webdriver For Python)
- Python+Selenium框架设计--- Page Object Model
- Selenium的PO模式(Page Object Model)|(Selenium Webdriver For Python)
- Page Object Model (Selenium, Python)
- Selenium的PO模式(Page Object Model)[python版]
- Selenium(Python)PageObject页面对象
- Page Object Model (POM) & Page Factory in Selenium: Ultimate Guide
- Selenium Page Object Model-FindAll annotation
- Selenium+Python :WebDriver设计模式( Page Object )
- selenium page object model
- Python3-Selenium3使用PO设计模式(Page Object)实现简单的页面登录操作
- Python+Selenium中级篇之9-把截图类方法封装到前面的BasePage.py
- Page Object Model (Selenium + Python)(二)
- Selenium Page object Pattern usage
- selenium+java+testNG+pageObject深入理解自动化测试框架
- Selenium自动化Page模式(Python)
- selenium+java+testNG+pageObject深入理解自动化测试框架
- Selenium PageObject实例