Page Object Model (Selenium, Python)

Source: Internet
Author: User
Tags xpath

Time 2015-06-15 00:11:56 Qxf2 Blog

Original http://qxf2.com/blog/page-object-model-selenium-python/ThemeSeleniumPython

We have come a long-since our post on implementing the Page Object Model

-Implementing the Page Object Model (Selenium + Python)

While the above post are useful and we rank high on Google, we routinely hear, and criticisms of it:

A) The post is too

b) The application being tested is not very repeatable

So we thought we would rework the above piece to address the drawbacks. In this post we shall give you a more detailed architecture, provide many more code snippets and write an automated test F or Gmail.

Overview of Page Object Model

A Page object represents an area in the Web application user interface This 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 O Nly. [1]

What vs How

Usually the testers write the test cases describing ' what ' was to being tested, this depends on the product Functiona Lity. But the implementation of this functionality by the developers keeps changing till the final code freeze was done, hence TE Sters should know ' how ' to implement the test cases so, the changes to the test scripts is minimal in case O F 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 SCRI PT more readable and robust.

Sample Test case– (what)

We is going to explain on 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 is to write a test script with all the xpaths and the methods required for the execution of the AB Ove listed steps in one single file. The test would run fine and achieve the purpose but one major drawback are the test script is brittle. For any minor UI change on any page, the test script would has to be updated. To overcome this problem we use the Page object pattern. As its name Suggests,each page of the application to being tested is treated a object which has the variables (xpaths) and methods (actions that can is performed on that particular page). This in turn makes the test script much cleaner.

Implementing the test case using a 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 have 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 XPA THS 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 the user Login. This is the most re-used class.

From Page Import pageclass login_page (page): ' Page object for the Login page ' def start: 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 Lo Gin (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 ("Lo Gin Success ") return True else:self.write (" Fail:login error ") return False def set_login_email (self,u    Sername): "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 fo Rm

  

Once We login, the main page is displayed which consists of the header (which contains the search box, user profile option s), the navigation menu on the left side of the page and the main body. As the header and the navigation menu is common to all pages we created page objects for each of the them. Here are a snippet of each of the classes.

nav_menu.py
From Page Import pageclass 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"

  

header_section.py
From Page Import pageclass 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)    .    .

  

Now, the main_page.py would contain the objects of the above of the classes.

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)

  

This completes the page objects needed-particular test case.**please note–as an alternate, we can also has A ' Template_page ' (which inherits from the Page class and had the common objects) and has all pages (except Login Page) de Rive 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

  

Driverfactory.pywhich returns the appropriate driver for Firefox or Chrome or IE browser.

Login.credentialsfile 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 Filecredentials_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 Testrailresult_flag = false# Setup a Driver#create object of driver Factorydriver_obj = driverfactory () Driver = driver_obj.get_web_driver (Browser, Sauce_flag,browser_version,platform) Driver.maximize_window () #Create a login page objectlogin_obj = pagefactory.get_ Page_object ("Login", driver) if (Login_obj.login (Username,password)): Msg = "Login was successful" Result_flag = True Log In_obj.write (msg) else:msg = "Login failed" Login_obj.write (msg) #Create an object for main page with header and Menumain _obj = Pagefactory.get_page_object ("main", driver) Main_obj.waiT (3) #Search the Inbox for message by subject ' POM ' and open the Messageif main_obj.header_obj.search_by_subject (' Pom '): M Ain_obj.write ("Search successful") Result_flag = Trueelse:main_obj.write ("Search text is not found") Result_flag = Fa Lse#go to Inboxmain_obj.menu_obj.select_menu_item (' Inbox ')

  

As you must has noticed the final test is very easy to read and need not being modified in case of any underlying changes to Individual pages.

Running the test

Let us execute the test,

And here are 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 AU tomated test Case. Maintaining these tests is also very easy.

References:

1. http://selenium-python.readthedocs.org/en/latest/page-objects.html

2. https://code.google.com/p/selenium/wiki/PageObjects

3. Batman and Page Objects

Vrushali Toshniwal

My journey as a tester started at Sun Microsystems (now Oracle). I was part of the testing and sustaining team for the Portal Server and Identity Management products. My first assignment is to test the Rewriter module. I enjoyed understanding the big picture, writing test cases, finding bugs and sometimes suggesting the fix too! I was hooked onto testing. Testing felt natural and intuitive to me. I am technically inclined and can write automation in Java, C + +, Perl and Python. I am well versed with silktest, Selenium, Appium and selendroid. I am a computer science graduate from Bits-pilani. I Love travelling and listening to music.

©2015,qxf2 Services. All rights reserved.

Page Object Model (Selenium, Python)

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.