Selenium-python use PageObject to implement automated testing __python

Source: Internet
Author: User

Automated tests that have been done with the UI know that testing is an action on an element, so it is particularly dependent on the positioning of the element. But this poses a big problem-"maintenance cost", if you are positioned multiple times with an element in a different test case script, and when the position or attribute of the element changes, you must find the corresponding location in the script to modify it.

Page Object
Page objects mode is a test design pattern that can refer to an entire page or to an area on a page.
Page object separates the location of the pages from the business operations, separates the test objects (element objects) and test scripts (use case scripts), and improves the maintainability of the use cases.

the advantages of Page object
-Reduce the duplication of the code
-Make the test more readable and powerful
-Improved maintainability of testing

instance
The following "Baidu search" as an example of detailed, Page object principle:
1, the project directory:

.
├──pages
│   ├──baidupage.py
│   ├──basepage.py
│   └──__init__.py
├──report
├── run.py
├──testcases
│   └──test_baidu.py
└──utils
    ├──publicmethod.py ├──__init__
    . PY
    └──configfile.py

The base class for the test page object and the corresponding test page under the Pages folder
Report: Storage location of test reports generated by Htmltestrunner
Testcases: A specific test script is stored to test the. py File Open
Utils: Public Methods (Publicmethod) and configuration files (configfile)
run.py: Get the test case set from Testcases and execute the script file

2.1, pages-definition page base class basepage.py

#-*-Coding:utf-8-*-

class BasePage (object): "" "is
    a base Page class for Page object.
    " "" def __init__ (self, driver):
        self.driver = Driver

2.2, pages-definition of Baidu search page Object (baidupage.py)
All page element positioning is defined at this level, and once the UI has changed, just modify this layer of Page object properties.

#-*-Coding:utf-8-*-
import BasePage

class Baidu_page (basepage.basepage):
    search_box = "id>>> KW "  # Locating the search box by id
    search_button =" Id>>>su "  # positioning" Baidu click "button by ID

    enter search content to search box
    def Input_search_text (self, text):
        Input_box = self.driver.get_element (self.search_box)
        Input_box.send_keys (text)

    # Click search button
    def click_search_button (self):
        self.driver.get_element (Self.search_button). Click ()

3, testcases-specific test Cases

#-*-Coding:utf-8-*-import unittest, time, sys sys.path.append ("...") from Utils. Publicmethod Import Publicmethod from utils.configfile import env_info from pages Import Baidupage class Baidutest (Unitte St. TestCase): def setUp (self): # Instantiate Utils under Publicmethod class, which contains several webdriver two-time encapsulation methods Self.driver = Publicmetho D (env_info[' browser ']) self.driver.wd.implicitly_wait Self.driver.max_window () def Test_01_search _selenium (self): self._search_content (U ' Baidu search selenium ', ' Selenium ', U ' selenium_ Baidu search ') def test_02_search_pytho N (self): self._search_content (U ' Baidu search python, ' Pyhon ', U ' python_ Baidu search ') def teardown (self): Self.driver Quit () # abstract Baidu Search Private method, description for case description, text to search for content, expected expected results def _search_content (self, description, text, ex pected): Driver = Self.driver driver.open_link (env_info[' url ']) print ' Case description: ', DESCRI
     Ption baidupage = baidupage.baidu_page (Driver)   Baidupage.input_search_text (text) Baidupage.click_search_button () time.sleep (1) self._verify_te
        XT (Expected) # Verify search results page title def _verify_text (Self, expacted): Actual_text = Self.driver.get_title () Expact_text = expacted if Actual_text = = Expact_text:print ' Pass-----', ' actual result: ', actual _text else:print ' FAIL-----', ' Expect result: ', expact_text, ' ***actual result: ', actual_text if __n ame__ = = "__main__": Suite = unittest. TestSuite () suite.addtest (baidutest (' Test_01_search_selenium ')) suite.addtest (baidutest (' Test_02_search_python ') ) UnitTest. Texttestrunner (). Run (Suite)

The UnitTest unit test framework is used, encapsulating two private method _search_content (the abstract method of test case) and _verify_text (validating the results and printing, or using the assertion method provided by UnitTest)

4, run.py-to run test case set method

#-*-Coding:utf-8-*-
import unittest
import Htmltestrunner

def get_test_cases (dirpath):
    test_cases = UnitTest. TestSuite ()
    suites = Unittest.defaultTestLoader.discover (Dirpath, ' test*.py ', Top_level_dir=dirpath)
    for Suite in Suites:
        test_cases.addtests (Suite) return
    test_cases

if __name__ = = ' __main__ ':
    cases = get_ Test_cases (' testcases ')
    filename = ' report/testreport.html '  # Set report filename
    f = file (filename, ' WB ')
    Runner = Htmltestrunner.htmltestrunner (stream=f, Title=u ' Page Object Demo test ', Description=u ' detailed test results are as follows: ')
    Runner.run (cases)

Navigate to the project directory, run Python run.py waiting for cases suites to run, and generate testreport.html test reports under result.

Some of the code is not fully posted (Publicmethod and ConfigFile code), all code see: Https://git.oschina.net/ljzhangi/pageobjectdemo.git

the other:
1. A basic rule of thumb for page object is that the Page object can be done by the software client, whatever the human could do. It should also provide an easily programmable interface and hide the lower parts of the window. So accessing a text box should be done using an access method (accessor methods) to get and return the string, the checkbox should use a Boolean value, and the button should be represented as a behavior-oriented method name.
2. The Page object should encapsulate the behavior of all query and manipulation data on a GUI control as a method. A good rule of thumb is that even if you change the control, the Page object's interface should not change.
3. Although the term is a "page" object, it does not mean creating an object for each page, such as a Page object that has significant elements that can be independent. The rule of thumb is to make it meaningful to the users of the application by modeling the page.

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.