Go to Python Selenium design mode-pom

Source: Internet
Author: User

Objective

This paper shares the POM design pattern needed in the practice of Python Selenium automation test, so that we can understand and master the characteristics, application scenarios and core ideas of pom in practice.

Why use Pom

Starting UI-level automated testing based on Python selenium2 is not a daunting task. just navigate to the element and perform the corresponding action. Let's take a look at this simple script to implement Baidu search.

from selenium import webdriverimport timedriver = webdriver.Firefox()driver.implicitly_wait(30)# 启动浏览器,访问百度driver.get("http://www.baidu.com")# 定位 百度搜索框,并输入seleniumdriver.find_element_by_id("kw").send_keys("selenium")# 定位 百度一下 按钮并单击进行搜索driver.find_element_by_id("su").click()time.sleep(5)driver.quit()

From the above code, all we can do is to locate the element and then do the keyboard input or mouse action. Just for this little program, it looks like it's easy to maintain. But over time, the test suite will continue to grow. The script will also become bloated and bulky. If it turns out that we need to maintain 10 pages, 100 pages, or even 1000 of them? Any change to the page element will make our scripting maintenance cumbersome and time-consuming and error-prone.

How to solve it?
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.

Comparison chart for non pom and pom:


What is Pom.pngpom?
    • The Page object Model (POM) is a design pattern used to manage the object library that maintains a set of web elements
    • Under Pom, each page of the application has a corresponding pages class
    • Each page class maintains the set of elements for the Web page and methods for manipulating those elements
    • The method name in page class is best based on its corresponding business scenario, for example, we will have to wait a few seconds after logging in, so we can name the method: Waitingforloginsuccess ().

Let's look at the Code catalog organization example for POM:


Advantages of Pages_dir.pngpom
    1. POM provides a pattern of separation between UI-level operations, business processes, and validation, which makes test code clearer and more readable
    2. Object Library and use case separation, so that we better reuse objects, and even with different tools to deep integration of 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 is manipulating. 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. Pom Implementation example below we look at the use of pom Baidu search Pom code example:
      Look at the following code organization structure as follows:

      Page_demo_dir.png
# basepage.py code is as follows# _*_ Coding:utf-8 _*___author__ =' Bitter leaves 'Import sysreload (SYS) sys.setdefaultencoding ("Utf-8")# pages Base classClassPage(object):"" Page base class, all page should inherit the class "" "Def__init__(Self, driver, base_url=u "http://www.baidu.com"): Self.driver = Driver Self.base_url = Base_url Self.timeout = 30 def find_ Elementreturn self.driver.find_element (*loc) Span class= "hljs-function" >def input_text < Span class= "Hljs-keyword" >def click (self, loc): Self.find_ Element (*loc). Click () def get_ Titlereturn self.driver.title      
# searchpage.py code is as follows# _*_ Coding:utf-8 _*___author__ =' Bitter leaves 'Import SysFrom selenium.webdriver.common.byImport byFrom Pages.basepageImport pagereload (SYS) sys.setdefaultencoding ("Utf-8")# Baidu Search PageClassSearchpage(Page):# element Set# search Input Box Search_input = (by.id,U ' kw ')# Baidu Button Search_button = (by.id,U ' su ')Def__init__(Self, driver, base_url=U "http://www.baidu.com"): page.__init__ (self, driver, Base_url)def gotobaiduhomepage(self): print u "Open home:", Self.base_url self.driver.get (Self.base_url)  def Input_search_text(self, text=u "Open source"): print u "input search keywords: open source optimization" Self.input_text (self.search _input, text) def click_search_btn(self): print u "click Baidu Button" Self.click (Self.search_button) /c18> 
# testsearchpage.py code is as follows# _*_ Coding:utf-8 _*___author__ =' Bitter leaves 'Import UnitTestImport SysFrom seleniumImport WebdriverFrom Pages.searchpageImport searchpagereload (SYS) sys.setdefaultencoding ("Utf-8")# Baidu Search TestClassTestsearchpage(UnitTest. TestCase):DefSetUp(self): Self.driver = Webdriver. Ie ()DefTestsearch(self): Driver = self.driver # Baidu URL = u "http://www.baidu.com" # search text = u "open source Best Test" # expected to verify the title Assert_title = U "Open Source Excellent test _ Baidu search" print assert_title search_page = searchpage (driver, url ) # Launch Browser, visit Baidu home Search_pa Ge.gotobaiduhomepage () # Enter search term search_page.input_search_text (text) # Click the Baidu button to search Search_page.click_search_ BTN () # Verify Header self.assertequal (Search_page.get_title (), Assert_title) def TearDown(self): Self.driver.quit ()              
# The main entry program code is as follows# _*_ Coding:utf-8 _*___author__ =   ' bitter leaves ' import unittestimport sys< Span class= "Hljs-keyword" >from common import htmltestrunner From Testcase.testsearchpage import testsearchpagereload (SYS) sys.setdefaultencoding ( Span class= "hljs-string" > "Utf-8") if __name__ =  ' __main__ ': Testunit = UnitTest. TestSuite () testunit.addtest (Testsearchpage ( ' Testsearch '))  # define report Output Path Htmlpath = u "page_demo_report.html" fp = File (Htmlpath,  "WB") Runner = Htmltestrunner.htmltestrunner (STREAM=FP, Title= U "Baidu Test", Description=u "test Case Results") Runner.run (Testunit) fp.close ()    

Follow the organization code structure, enter the code as above, run the following command, and generate a test report in the current directory:

python main.py
Summarize

Finally make a summary, all the code please enter manually, do not copy directly. Make a summary of the POM again

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

Transferred from: http://www.cnblogs.com/lym51/p/6646033.html

Go to Python Selenium design mode-pom

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.