Implementing the Page Object Model (Selenium + Python)

UPDATE:

We are retiring this post in favor of a newer post: Page Object Model (Selenium, Python)
Please refer to the newer post. It has a more detailed architectural breakdown, provides many more code snippets and write an automated test for a very relatable application – Gmail.


Problem: Testers think changing existing test scripts to use the page object model is complicated.


Why this post?

Tutorials on the page object model usually show you how to implement the page object model using a cliched login page as an example. Most online tutorials rarely show you how to modify your existing tests to use the page object model. This post is a follow up to our descriptive introduction to the page object model. In this tutorial, we provide a hands on example of how to revamp your existing test scripts to use the page object model.


A refresher

Within your web app’s UI there are areas that your tests interact with. A Page Object simply models these as objects within the test code. This reduces the amount of duplicated code and means that if the UI changes, the fix need only be applied in one place.[1]

The page object model allows us to do two things mainly:[2] 1) Encapsulate the low-level “internals” of the page – the ids of the buttons, classes of element, etc.
2) Make the client (of the Page Object) test methods more elegant by taking them to a higher level.


Test scenario

I am going to test the chess viewer widget on Chessgames.com. I am choosing to check if Black’s 21st move in the Casino Royale Chess Game is executed correctly. Black’s queen moves from the b6 square to the f2 square. We will verify that the b6 square is empty and that the f2 square has a black queen on it.
PS: Black’s 21st move in this game is the reason behind our company name Qxf2.

qxf2_move


Implementing the page object model

For this tutorial, we will show the following:
1. Write a working test
2. Prepare to move to the page object model
3. Implement the page objects
4. Run the test
5. Compare with the first implementation

1. Write a working test
I am going to implement a working test. We will use this as a starting point. Let’s pretend that this is your existing test. I have written the following qxf2move.py

qxf2move.py

import unittest
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
 
class qxf2move(unittest.TestCase):
 
    def setUp(self):
        self.driver=webdriver.Firefox()
 
    def testUserMove21Black(self):
        driver=self.driver
        driver.get("http://www.chessgames.com/perl/chessgame?gid=1477101")
        self.assertIn("Mikhail Krasenkow vs Hikaru Nakamura (2007) \"Casino Royale\"",driver.title)
 
        #Click on Black's 21st move
        driver.find_element_by_id("Var0Mv42").click()
 
        #Verify the squares b6 and f2 ([2,1], [6,5]) have the right pieces
        chess_square = driver.find_element_by_id("img_tcol5trow6")
        #Verify that the square f2 has a black queen (bq.png)
        self.assertEqual("http://www.chessgames.com/pgn4web-2.82/images/bq.png",chess_square.get_attribute('src'))
 
        chess_square = driver.find_element_by_id("img_tcol1trow2")
        #Verify that the square b6 is empty (clear.png)
        self.assertEqual("http://www.chessgames.com/pgn4web-2.82/images/clear.png",chess_square.get_attribute('src'))
 
    def tearDown(self):
        self.driver.close()
 
if __name__=="__main__":
    unittest.main()

Here as you can see the test scripts contains the actual details of the attributes and ids as they appear in the page source. It is not easy to maintain these scripts in case of underlying changes. Hence we try to make the test script more readable and extendable by making a few changes.

2. Prepare to move to the page object model
– Identify the various objects and elements on the web page. Define them as objects and variables in the test script. E.g.: Title, Game_Id, Move_Str, Chess Board, Chess Piece, locators for the various objects

chess_pageobjectmodel

– Identify the various actions possible on these objects using the available elements. These actions can be defined as the methods in the test script. E.g.: get_Title, getCurrentBoard, create_mov_str, gotoMove, gotoStart, gotoEnd

3. Implement the different pages as page objects
-Separate the test case and the page objects, methods in different files. Here my test case is present in TestChessGamePage.py and the page objects, methods are present in ChessGamePage.py

TestChessGamePage.py

from selenium import webdriver
from selenium.webdriver.common.by import By
import unittest
import ChessGamePage
 
class TestChessGamePage(unittest.TestCase):
 
    def setUp(self):
        self.driver = webdriver.Firefox()
 
    def testUserMove21Black(self):
        "Test Black's 21st move (qxf2)"
        gameid = "1477101"
        player = "black"
        movenum = 21
        """List of the board position in the format (Piece,row,col)
        where top left corner of the board is row =0, col= 0,
        white player = 'w',black player = 'b'
        pawn(p), rook(r), knight(n), bishop(b), queen(q), and king(k)"""
        lst = [('br',0,4), ('bk',0,6),
               ('bn',1,3), ('bb',1,4), ('bp',1,5), ('bp',1,6), ('bp',1,7),
               ('bb',2,0), ('br',2,2), ('wb',2,5),
               ('bp',3,0),
               ('bp',4,2),
               ('wp',5,6),
               ('wp',6,0), ('wn',6,3), ('bq',6,5), ('wb',6,6), ('wp',6,7),
               ('wr',7,1), ('wq',7,3), ('wr',7,4), ('wk',7,6)]
 
        chessgame_page = ChessGamePage.ChessGamePage(self.driver,gameid)
        chessgame_page.open()
        page_title = chessgame_page.get_Title()
        self.assertIn("Mikhail Krasenkow vs Hikaru Nakamura (2007) \"Casino Royale\"", page_title)
        #Goto Black's 21st move 
        chessgame_page.goto_Move(player,movenum)
        actualBoardb21 = chessgame_page.getCurrentBoard()
        expectedBoardb21 = ChessGamePage.ChessBoard()
        expectedBoardb21.populate(lst)
        #Compare with the expected chess board
        self.assertEqual(actualBoardb21,expectedBoardb21)
 
    def tearDown(self):
        self.driver.close()
 
#---START OF SCRIPT
if __name__=="__main__":
    suite = unittest.TestLoader().loadTestsFromTestCase (TestChessGamePage)
    unittest.TextTestRunner(verbosity=2).run(suite)

The above file does not contain the driver calls to get the elements in the page. For the sake of simplicity, we have not shown you how to implement a driver factory.

All the finer details are added to the files Base_Page_Object.py and ChessGamePage.py as shown below

Base_Page_Object.py

from selenium import webdriver
from selenium.webdriver.common.by import By
 
class Page(object):
    """
    Base class that all page models can inherit from
    """
    def __init__(self, selenium_driver, base_url='http://www.chessgames.com/'):
        self.base_url = base_url
        self.driver = selenium_driver
        self.timeout = 30
 
    def find_element(self, *loc):
        return self.driver.find_element(*loc)
 
    def open(self,url):
        url = self.base_url + url
        self.driver.get(url)

ChessGamePage.py

from selenium import webdriver
from selenium.webdriver.common.by import By
from Base_Page_Object import Page
 
class ChessGamePage(Page):
    #Elements
    move_str = ""
    url = ""
    """ Var0Mv(N*2-1) is the id for Nth white move
        Var0Mv(N*2)   is the id for Nth black move """
    id_str = "Var0Mv"
    #Locators
    startButton_loc = (By.ID, 'startButton')
    backbButton_loc = (By.ID, 'backButton')
    autoplayButton_loc = (By.ID, 'autoplayButton')
    forwardButton_loc = (By.ID, 'forwardButton')
    endButton_loc = (By.ID, 'endButton')
 
 
    def __init__(self, selenium_driver,gameid,base_url='http://www.chessgames.com/'):
        Page.__init__(self, selenium_driver, base_url='http://www.chessgames.com/') 
        self.url = 'perl/chessgame?gid=' + gameid
 
    # Actions
    def openpage(self):
        self.open(self.url)
 
    def get_Title(self):
        """Returns the page title"""        
        return self.driver.title
 
    def getCurrentBoard(self):
        """Returns the current chessboard positions"""
        board = ChessBoard(self.driver)
        board.loadFromPage()
        return board
 
    def create_move_str(self,player,move):
        """Creates the value string using the player and move information"""
        if player.lower() == "white":
            self.move_str = self.id_str + str((move*2)-1)
        else:
            self.move_str = self.id_str + str(move*2)
 
    def goto_Move(self,player,move):
        """Clicks on the particular move"""
        self.create_move_str(player,move)
        move_loc = (By.ID,self.move_str)
        self.find_element(*move_loc).click()
 
    def goto_Start(self):
        """Clicks the start of the game button"""
        self.find_element(*self.startButton_loc).click()
 
    def goto_Back(self):
        """Clicks the ack one step bbutton"""
        self.find_element(*self.backButton_loc).click()
 
    def goto_AutoPlay(self):
        """Clicks the autoplay button"""
        self.find_element(*self.autoplayButton_loc).click()
 
    def goto_Forward(self):
        """Clicks the one step forward button"""
        self.find_element(*self.forwardButton_loc).click()
 
    def goto_End(self):
        """Clicks the end of game button"""
        self.find_element(*self.endButton_loc).click()
 
"""This class represents the actual chess board present on the page"""
class ChessBoard(object):
    """This string is the id for the image(piece) present in each square(col,row) of the chess board"""
    id_str = "img_tcol%strow%s"
 
    def __init__(self,driver=None):
        self.driver = driver
        self.grid = []
 
    def loadFromPage(self):
        """Creates the chess matrix from the page data"""
        for row in xrange(8):
            for col in xrange(8):
                name = self.getSquare(row,col)
                if name:
                    piece = ChessPiece(name,row,col)
                    self.grid.append(piece)
 
    def getSquare(self, row, col):
        """Returns the piece present at the particular row,col. None if the square is vacant"""
        elem = self.driver.find_element_by_id(self.id_str%(str(col),str(row)))
        src = elem.get_attribute('src')
        name = src.split("/")[-1].split(".")[0]
        return name if (name.lower() != 'clear') else None
 
    def populate(self,lst):
        """Creates the chess matrix as per the user data"""
        for entry in lst:
            name,row,col = entry
            piece = ChessPiece(name,row,col)
            self.grid.append(piece)
    def __str__(self):
        return str(self.grid)
    def __eq__(self,obj):
        return self.grid == obj.grid
 
"""This class represents the chessmen deployed on a chessboard for playing the game of chess"""
class ChessPiece(object):
    def __init__(self,name,row,col):
        self.name = name
        self.row = row
        self.col = col
    def __eq__(self,obj):
        return (self.name == obj.name and self.row == obj.row and self.col == obj.col)
    def __hash__(self):
        tmp = 'row' + `self.row` + 'col' + `self.col` + self.name
        return hash(tmp)
    def __str__(self):
        return "(%s,%d,%d)" % (self.name, self.row, self.col)
    def __repr__(self):
        return "(%s,%d,%d)" % (self.name, self.row, self.col)

4. Run the test
Here is the snapshot of the test run
run the page object model test

5. Compare with the first implementation
Let us compare the files qxf2move.py and TestChessGamePage.py
file_compare

You’ll notice that using the page object model, it becomes easy to add new testcases without bothering about the details of the page elements. Also any changes to the page elements do not change the testcases – only the logic in ChessGamePage.py needs to be modified.


References:

1. https://code.google.com/p/selenium/wiki/PageObjects
2. http://www.ralphlavelle.net/2012/08/the-page-object-pattern-for-ui-tests.html


A weekly newsletter for testers


View a sample



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 was 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.

© 2013-2017, Vrushali Toshniwal. All rights reserved.

5 Comments

  1. Jame said:

    Hi Vrushali Mahalley,

    Thank for your effort,

    I confuse at function __init__ on ChessGamePage.py and Base_Page_Object.py, we will create constructor ‘selenium_driver’, but I see it’s not used on file test case because the test case file is using ‘setUP’ function calling Firefox instance. So, I think __init__ on files as above is useless – we can remove it

    If wrong, please correct for me

    December 9, 2014
    Reply
    • Vrushali Toshniwal Vrushali Mahalley said:

      Jame,
      Good question! To limit the tutorial to a reasonable length we chose to share the webdriver object with the Page Object and the Base Page Object through the test case .
      Here is the flow of execution
      1.TestChessGamePage.py
      def setUp(self):
      self.driver = webdriver.Firefox()
      Here the the instance of Firefox WebDriver is created which is then passed to the ChessGamePage object.
      chessgame_page = ChessGamePage.ChessGamePage(self.driver,gameid)

      2.ChessGamePage.py
      class ChessGamePage(Page)
      ChessGamePage is derived from Page, hence __init__ in ChessGamePage in turn calls __init__ in Page class
      def __init__(self, selenium_driver,gameid,base_url=’http://www.chessgames.com/’):
      Page.__init__(self, selenium_driver, base_url=’http://www.chessgames.com/’)

      3.Base_Page_Object.py
      class Page(object):
      def __init__(self, selenium_driver, base_url=’http://www.chessgames.com/’):
      self.base_url = base_url
      self.driver = selenium_driver
      For a more advanced and detailed architecture you can refer here:
      http://www.slisenko.net/2014/06/22/best-practices-in-test-automation-using-selenium-webdriver/
      Hope this helps.

      December 11, 2014
      Reply
  2. L Mubarak said:

    Really very helpful. It would be really more helpful if you could provide any meterial to learn complete selenium with python(Using pytest framework). Hoping from you. Thank you!

    February 14, 2017
    Reply

Leave a Reply

Your email address will not be published.