Python+selenium Automated Software Testing (7th): Page Object mode

Source: Internet
Author: User
Tags readable

What is page ObjectModel mode
Page objects is a test design pattern for selenium, which mainly considers each page as a class. Class content mainly includes properties and methods, the property is not difficult to understand, is the element object in this page, such as input user name input box, enter the login password input box, login button, this page URL, and method, mainly refers to this page can provide specific functions.
Why Choose POM?
Let's look at a simple code like this:

 fromSeleniumImportWebdriverImportTime driver=Webdriver. Firefox () driver.implicitly_wait (30) #Launch Browser, visit BaiduDriver.get ("http://www.baidu.com") #Locate the Baidu search box and enter SeleniumDRIVER.FIND_ELEMENT_BY_ID ("kw"). Send_keys ("Selenium") #Locate Baidu button and click to searchDRIVER.FIND_ELEMENT_BY_ID ("su"). Click () time.sleep (5) Driver.quit ()

This is a simple little script. Script maintenance looks simple. But with the growth of the time test suite. As you add more and more lines to your code, things get tough.
The main problem with scripting maintenance is that if 10 different scripts use the same page element and any changes in that element, you need to change all 10 scripts. This is time-consuming and error-prone.
A better way to maintain a script is to create a separate class file that can find web elements, populate them, or validate them. The class can be reused in all scripts that use the element. In the future, if web elements change, we need to make changes in 1 class files instead of 10 different scripts.
What is POM?
The Page object model is the design pattern for creating an object repository for a Web UI element.
Under this model, there should be a corresponding page class for each page in the application.
This page class will find the webelements of the Web page and also contain page methods for performing actions on those webelements.
The names of these methods should be given according to the task they are performing, that is, if a loader is waiting for the payment gateway to appear, the Pom method name can be Waitforpaymentscreendisplay ().

Comparison chart for non pom and pom:

In automated testing, the introduction of the Page object Model (POM): The model of the Web objects to solve, POM can make our test code more readable, high maintainability, high reusability.
Advantages of POM
1. POM provides a pattern that separates the UI layer operations, business processes, and validations, which makes the test code clearer and more readable.

2. Object Library and use case separation, so that we better reuse objects, and even with different tools for deep integration application.

3. Reusable page method code becomes more optimized.

4. A more efficient naming approach allows us to know more clearly what UI elements the method operates on. For example, we want to go back to the homepage, the method name is: Gotohomepage (), through the method name can clearly know the specific function implementation.

Case Description:
The following are simple, common logon test cases:

defTest_login_mail (self): driver=self.driver Driver.get ("http://www.xxx.xxx.com") driver.find_element_by_id ("Idinput"). Clear () driver.find_element_by_id ("xxxxxxx"). Send_keys ("xxxxx") driver.find_element_by_id ("xxxxxxx"). Clear () driver.find_element_by_id ("xxxxxxx"). Send_keys ("xxxxxx") driver.find_element_by_id ("loginbtn"). Click ()

So how do we make a retrofit upgrade?
Transformation Case Ideas:
First, we want to isolate the test object (the element object) and the test script (use case script), then we create two script files, respectively: loginpage.py is used to define the page element object, each element is encapsulated as a component (can be regarded as the repository of the page element object) caselogintest.py the test case script.
Second, the design realizes the idea, all elements and elements of the operation of the component are defined in page pages, use Case script page, by calling the Component object in the page, make a login script.

basepage.py:

#-*-coding:utf-8-*- fromselenium.webdriver.support.wait importwebdriverwait fromseleniumimport webdriverclassaction (object):"""BasePage encapsulates methods that are common to all pages, such as driver, URLs, findelement, etc."""#Initialize driver, URLs, etc.def __init__(Self,selenium_driver, Base_url, pagetitle): Self.base_url=Base_url Self.pagetitle=pagetitle Self.driver=Selenium_driver#Open the page to verify that the page link is loaded correctlydef_open (Self,url, pagetitle):#use get to open access link addressself.driver.get (URL) self.driver.maximize_window ()#use Assert to verify that the link address opened is the same as the configured address. Call the On_page () methodAssertself.on_page (PageTitle), u"Open page failed%s"%URL#overriding element positioning methodsdefFind_element (self,*Loc):#returnself.driver.find_element (*loc)Try: Webdriverwait (Self.driver,). Until (Lambdadriver:driver.find_element (*Loc). is_displayed ())returnSelf.driver.find_element (*Loc)except:PrintU"%s element could not be found in%s page"%(self, loc)#overriding the Switch_frame methoddefSwitch_frame (Self, loc):returnself.driver.switch_to_frame (Loc)#define the Open method, call _open () for opening the linkdefOpen (self): Self._open (Self.base_url, Self.pagetitle)#use Current_url to get the current window URL address, compare with the configuration address, return the comparison result (True False)defon_page (self,pagetitle):returnPagetitlein Self.driver.title#defines the script method for executing the JS script, the scope execution resultdefscript (SELF,SRC): Self.driver.execute_script (SRC)#overriding the definition Send_keys methoddef send_keys (self, loc, vaule, Clear_first=true, click_first=True):Try: Loc= GetAttr (self,"_%s"%Loc)ifClick_first:self.find_element (*Loc). Click ()ifClear_first:self.find_element (*Loc). Clear () self.find_element (*Loc). Send_keys (Vaule) Exceptattributeerror:PrintU"%s element could not be found in%s page"% (self, loc)

loginpage.py:

#-*-coding:utf-8-*- fromselenium.webdriver.common.by ImportbyImportBasePage#inheriting the BasePage classclassLoginPage (basepage.action):#locators, locating element objects through element propertiesUsername_loc= (By.id,"Idinput") Password_loc= (By.id,"Pwdinput") Submit_loc= (By.id,"loginbtn") Span_loc= (By.css_selector,"div.error-tt>p") Dynpw_loc= (By.id,"LBDYNPW") Userid_loc= (By.id,"Spnuid")#ActiondefOpen (self):#call _open in page to open a connectionSelf._open (self.base_url,self.pagetitle)#Call the Send_keys object, enter the user namedefinput_username (self, username): Self.find_element (*self.username_loc). Send_keys (username)#call the Send_keys object and enter the passworddefInput_password (self, password): Self.find_element (*self.password_loc). Send_keys (password)#call the Send_keys object and click LogindefClick_submit (self): self.find_element (*self.submit_loc). Click ()#user name or password is not reasonable is the Tip box content displaydefShow_span (self): returnself.find_element (*self.span_loc). Text#Toggle Login mode for dynamic password login (ie valid)defSWICH_DYNPW (self): self.find_element (*self.dynpw_loc). Click ()#User ID lookup in the Login Success pagedefShow_userid (self): returnself.find_element (*self.userid_loc). Text
caselongintest.py

#-*-coding:utf-8-*-Importsysreload (SYS) sys.setdef aultencoding ('Utf-8')ImportUnitTest fromPoimportloginpage fromseleniumimport Webdriverclasscaselogin126mail (unittest. TestCase):"""Login Case"""@classmethoddefSetupClass (CLS): Cls.driver=Webdriver. Chrome () cls.driver.implicitly_wait (30) Cls.url="http://xxxx.xxx.com"Cls.username="xxxxx"Cls.password="xxxxx" #use case Execution BodydefTest_login_mail (self):#declaring a LoginPage class objectLogin_page=loginpage.loginpage (Self.driver, Self.url, U "xxxxx")#Call Open Page componentLogin_page.open ()#calling the user name Input componentlogin_page.input_username (self.username)#calling the password input componentLogin_page.input_password (Self.password)#Call Click the Login button componentlogin_page.click_submit () @classmethoddefTeardownclass (CLS): Cls.driver.quit ()if __name__=="__main__": Unittest.main ()

After using POM to reconstruct the structure of the code, it is found that the code test case code is much more readable, and the elements are written in a way that does not have to be written every findelement directly in the script to invoke the component.
In the Caselogintest script use case execution body, the element object components in the LoginPage page are displayed as soon as we enter login_page and type a point. and the defined PageObject components can be reused in other scripts, reduce the workload of the Code, and facilitate later maintenance management of the script, when the element attributes change, we only need to a Pageobaject page of the object component definition to make changes.
Finally make a summary, all the code please enter manually, do not copy directly.
Make a summary of the POM again:

1. Pom is selenium webdriver Automation test Practice Object Library design mode
2. Pom makes test scripts easier to maintain
3. Pom Further optimizes the maintenance organization of elements, use cases, and data through the object library approach


Python+selenium Automated Software Testing (7th): Page Object mode

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.