© Sujay Raghavendra 2021
S. RaghavendraPython Testing with Seleniumhttps://doi.org/10.1007/978-1-4842-6249-8_11

11. Page Objects

Sujay Raghavendra1 
(1)
Dharwad, Karnataka, India
 

In all the previous chapters, you learned to write various test conditions for the web elements present in a web page. A test case is built by combining these conditions. Building a successful test case requires a model in which all the essential functions and methods are integrated into a single test case or script. When test cases are bundled into a single script, the complexity of the test script increases, which makes it difficult to read, modify, or maintain. Page objects are used to solve jumbled-up test script issues on a web page.

The chapter begins with the discussion of page objects. The later sections cover the most widely used model for automating tests. The chapter also describes the necessity of the model in today’s environment. Further, you learn the complete process for building a model based on page objects, which is a widely used testing model. This model is defined in a classic example in this chapter. The Selenium support for the model also helps with encapsulating a test case. Now let’s start with page objects overview.

Page Objects Overview

Page objects are classes (an object-oriented concept in Python) that are initialized for a web page. A page object has web elements defined within it, like attributes in the Python language. The page object class serves as a medium to store web elements with their actions and the validations associated with the web page/app. Web elements can be easily accessed using page objects. Multiple page objects can be defined in a Python test script, depending on the requirements.

The basic concept of a page object is to hide the logic to locate the web elements (i.e., user ID, XPath, CSS selectors, etc.) that interact with these elements on a web page when a value is entered, which separates logic and value fields.

Note

Page objects are best suited for web applications with more than one page.

Now let’s look at a model that is built using page objects.

Page Object Model (POM) Overview

In test automation, a design pattern or model has emerged that allows more functionality, maintainability, readability, and flexibility. This design model/pattern based on page objects is known as a Page Object Model (POM) or Page Object Pattern.

(These terms are used interchangeably, but this book uses only POM.)

Page objects are better than unstructured Selenium test scripts and are well-suited for simple test cases/scenarios. As test cases increase in multiple web pages, the complexity of a test script also increases. To bind test cases together and to simplify the test script, a design model or pattern using page objects was developed.

POM in the Selenium WebDriver testing domain was proposed by Simon Steward. The first implementation of the Page Object Model was done in Java, which was later adopted by C#, Ruby, and then Python because they all supported object-oriented concepts.

POM is an organized way to automate Python test scripts. It contains the web elements that have user actions or interactions associated with them and that are tested, which means that POM provides encapsulation for the page objects.

Initially, page objects were defined for each web page, but due to the dynamic nature of web elements, objects can also be defined as classes or functions in a Python test case. In recent years, the use of page objects has increased in Selenium’s automated testing.

Note

A page object is also used for important web elements available in a single web page or application despite the term page object.

The Need for the Page Objects Model

Each web page or specialized web elements, when represented as a class, then a page object serves as an interface medium between page and AUT. The methods described in the class are the test case that interacts with a web page UI when executed.

A major reason to use a POM is that changes in a web page’s UI do not affect test cases. Change is handled by modifying the page objects related to it, which prevents the time and effort of writing a new test.

The procedural way that the model is implemented is explained next.

Creating Page Objects

A page object model is divided into various modules. These test modules contain a main test page that links to other module files. The modules are related to elements, locators, and pages for the specified test case.

A sample POM test case is provided next, where test.py is the main test case file followed by subsidiary files: page.py, elements.py, and locators.py. All files are kept in a single directory.

To execute the POM, you need to run test.py in the command prompt, and each subsidiary file is executed one by one when it is called.

Let’s now create each page necessary to form the POM, starting with the test.py file.

Test.py

test.py is a test case that is developed using the POM architecture. The test.py page contains all the test cases that are necessary to test a specific web page or application. In this example, the POM is designed to test searching a keyword on the Apress web site and then get matching results. test.py needs to import the associated modules, called the page.py file, to complete the test case.

Keep all four files in a single directory. Don’t run them individually because it is the Page Object Model, which is similar to the Page Object Pattern in Java.
import unittest
from selenium import webdriver
import page
class ApressSearch(unittest.TestCase):
#Sample test case using Page Object Model
def setUp(self):
        self.driver = webdriver.Firefox(executable_path=r'')
        self.driver.get("https://www.apress.com")
def test_apress_search(self):
#Visits aprèss.com
        home_page = page.HomePage(self.driver)
#Searches "Python Selenium" keyword
        home_page.search_text ="Python Selenium"
        home_page.click_submit_button()
        search_results_page = page.ResultPage(self.driver)
        #Checks if page is not empty
        assert search_results_page.check_search_results(), "No results found."
def tearDown(self):
        self.driver.close()
if __name__ =="__main__":
    unittest.main()

The test.py file visits the specified web site (Apress.com) and then searches for “Python Selenium” via the search box. The resulting page is also verified, whether it’s empty or not, with an assertion.

Note

The test.py file contains only test cases.

Page.py

The page.py file is created for each web page available in an application. In this file, the actions concerning the test cases are defined. This page separates the test code and its implementation on technical aspects. The page should import elements and locator files along with the standard Selenium library.
from elements import BasePageElement
from locators import HomePageLocators
class SearchText(BasePageElement):
#The locator for search box where search string is entered
    locator ='query'
class BasePage(object):
        def__init__(self, driver):
                self.driver = driver
class HomePage(BasePage):
        #Actions items for Home Page
        #Variable containing retrieved text
        search_text = SearchText()
        def click_submit_button(self):
        #Search is initialized
                element=self.driver.find_element(*HomePageLocators.SUBMIT_BUTTON)
                element.click()
classResultPage(BasePage):
#Actions items for result page
        def check_search_results(self):
        # Checks the result for specified text if found or not
        return "No results found." not in self.driver.page_source

The Submit button click action is defined on this page. It verifies whether the search page result is available or not.

Elements.py

elements.py contains a class that is initialized for each page. This page finds the necessary web elements that are associated with functions performing actions. It can also set conditions to locate web elements.
from selenium.webdriver.support.ui import WebDriverWait
class BasePageElement(object):
#Used in every page
        def__set__(self, obj, value):
        #Contains specified text
                driver = obj.driver
                WebDriverWait(driver, 100).until(lambda driver: driver.find_element_by_name(self.locator))
                driver.find_element_by_name(self.locator).clear()
                        driver.find_element_by_name(self.locator).send_keys(value)
        def__get__(self, obj, owner):
"""Gets the text of the specified object"""
                driver = obj.driver
                WebDriverWait(driver, 100).until(
lambda driver: driver.find_element_by_name(self.locator))
                element = driver.find_element_by_name(self.locator)
                return element.get_attribute("value")

In this page, the web elements are located after waiting for a defined time, and then they are provided to test.py through the page.py file.

Locators.py

The locators.py page contains the names of the web elements that need to be located. This separates pages from elements and locators. Any changes in locator values are done in this page.
from selenium.webdriver.common.by import By
class HomePageLocators(object):
        #Should contain all locators from main page
        SUBMIT_BUTTON = (By.CLASS_NAME, 'search__submit')
class ResultPageLocators(object):
        #It should contain locators from result page
        pass

The locators initialized are passed to elements.py, where it locates web elements for the specified page. The POM is sometimes considered a framework to deploy test cases with Selenium using Python. A test case framework known as unittest is combined with POM. It is described in Chapter 12.

Advantages of Page Objects Model

This section focuses on the advantages of test cases that are created with page objects, as follows.
  • Reduces code duplication: The basic test scripts required by most of the web page undergoing testing needs to be rewritten, which creates duplication of code. This code duplication can be avoided by using page objects because the same test script has page objects specified for various web elements and can be used for other pages.

  • Enhances code maintenance: The creation of a page class helps to separate web elements (data) and test cases. This enables you to avoid unstable test suite conditions in a changing environment. The handling of exceptions in a test case means a more maintainable test script.

  • Shorter test cases: The test script is optimized using POM, and hence the length of test cases is reduced.

  • Increases code reusability: Code that uses page objects can be used in multiple test cases.

  • Readability: The test script written for any web application should be understandable to a new tester or multiple test teams working on the same project. This is done by using page objects that divide the web elements or web pages into several parts, which makes the test script more readable.

Limitations of the Page Object Model

Let’s now look at the limitations of using page objects in a test case.
  • Time and effort: There is a huge risk with using page objects when a web page or application has a large number of pages because the test model needs to be modified for even minor changes in an application. Hence, POM should be used in parallel with the development of the web application/page.

  • High-level skills: To debug or to write test cases aligned to POM, you must have technical knowledge and experience because complexity increases with combined page object architectures.

  • Fixed model: A test developed with POM cannot be utilized on other applications (i.e., POM is not a generic model).

Summary

This chapter provided a complete overview of the page objects that build a model. Page objects are classes that divide a web page into smaller sections, which distinguishes the multiple web elements available in them. It is the basic building block to create the model.

You learned the conceptual and technical implementation aspects of the Page Object Model. The creation of POM includes a file structure that has a main Python file and subsidiary Python files that reside in a single directory, as demonstrated in an example.

You also learned POM’s advantages and limitations.

The final chapter of this book includes various test cases written using different functions.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.145.166.7