current position:Home>Python + selenium automated test: page object mode
Python + selenium automated test: page object mode
2021-08-23 04:47:58 【Test development technology】
Page Objects yes selenium A test design pattern for , Think of each page as a class.class The main contents of the system include properties and methods , Attributes are not hard to understand , Is the element object in this page , For example, the input box for entering the user name , Input box for entering login password 、 Login button 、 Of this page url etc. . The method , It mainly refers to the specific functions that this page can provide .
01
Why choose POM?
Let's start with a simple code as follows :
from selenium import webdriver
This is a simple little script . Script maintenance looks simple . But over time, the test suite grew . As you add more and more lines to your code , Things get tough . The main problem with script maintenance is , If 10 Different scripts use the same page elements , And any changes in that element , You need to change all 10 Script . This is a Time consuming and error prone .
A better way to maintain scripts is to create a separate class file , It can be found Web Elements , Fill in or verify them . This class can be used in In all scripts reusing . future , If web Elements change , We need to be in 1 Make changes in a class file , instead of 10 A different script .
02
What is? POM?
Page object model Is for Web UI Element creation Object Repository Design mode of .
Under this model , For every web page in the application , There should be corresponding page classes . this Page Class will find the Web Page WebElements, And it's also about these WebElements Page methods to perform operations .
The names of these methods should be given according to the task they are performing , namely If a loader is waiting for the payment gateway to appear ,POM The method name can be waitForPaymentScreenDisplay().
Below is a POM and POM Contrast figure :
In automated testing , Introduced Page Object Model(POM): Page object mode to solve ,POM Can make our test code more readable , High maintainability , High reusability .
POM The advantages of :
- POM Provides a way to UI Layer operation 、 Business process and verification are separated , This makes the test code clearer and more readable .
- Object libraries are separated from use cases , Makes us better reuse objects , It can even be deeply combined with different tools .
- Reusable page method code will become more optimized .
- A more effective naming method makes it easier for us to know what the method operates UI Elements . For example, we want to go back to the home page , The method name is : gotoHomePage(), You can clearly know the specific function implementation through the method name .
03
Case description
Here is a simple and common login test case :
def test_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()
Then how can we carry out a transformation and upgrading ?
Reform case ideas : 1. We're going to separate the test objects ( Element object ) And test scripts ( Use case scripts ), So let's create two script files , Respectively :LoginPage.py Used to define page element objects , Every element is encapsulated as a component ( It can be seen as a warehouse for storing page element objects ) CaseLoginTest.py Test case scripts .
2. The idea of design and implementation , All elements and their operation components are defined in Page page , Use case script page , By calling Page Component objects in , To piece together a login script .
BasePage.py:
#-*- coding: utf-8-*-
LoginPage.py:
#-*- coding: utf-8-*- from selenium.webdriver.common.by importBy import BasePage # Inherit BasePage class class LoginPage(BasePage.Action): # positioner , Locate the element object through the element attribute username_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") #Action def open(self): # call page Medium _open Open the connection self._open(self.base_url,self.pagetitle) # call send_keys object , enter one user name def input_username(self, username): self.find_element(*self.username_loc).send_keys(username) # call send_keys object , Input password def input_password(self, password): self.find_element(*self.password_loc).send_keys(password) # call send_keys object , Click login def click_submit(self): self.find_element(*self.submit_loc).click() # The user name or password is unreasonable Tip Box content display def show_span(self): returnself.find_element(*self.span_loc).text # Switch the login mode to dynamic password login (IE Effective under ) def swich_DynPw(self): self.find_element(*self.dynpw_loc).click() # Users in the login success page ID lookup def show_userid(self): returnself.find_element(*self.userid_loc).text
Caselongintest.py:#-*- coding: utf-8-*- import sys reload(sys) sys.setdef aultencoding('utf-8') import unittest from POimportLoginPage from seleniumimport webdriver classCaselogin126mail(unittest.TestCase): """ Sign in case """ @classmethod def setUpClass(cls): cls.driver = webdriver.Chrome() cls.driver.implicitly_wait(30) cls.url ="http://xxxx.xxx.com" cls.username ="xxxxx" cls.password ="xxxxx" # Use case executor def test_login_mail(self): # Statement LoginPage Class object login_page=LoginPage.LoginPage(self.driver, self.url, u”xxxxx”) # Call the open page component login_page.open() # Call the user name input component login_page.input_username(self.username) # Call the password input component login_page.input_password(self.password) # Call the click login button component login_page.click_submit() @classmethod def tearDownClass(cls): cls.driver.quit() if __name__=="__main__": unittest.main()
Use POM Reconstruct the code structure after , It is found that the readability of code test case code is improved a lot , The way elements are written as components , You don't have to write every time findElement You can use components directly in scripts .
stay CaseLoginTest In the script case executor , Once we type in login_page And type in a point ,LoginPage The elements, objects and components in the page are displayed . also Defined PageObject Components can be reused in other scripts , Reduces the amount of code , It is also convenient for the maintenance and management of the script , When the attributes of an element change , We just need to deal with one PageObaject Change the definition of the object component in the page .
Finally, make a conclusion , Please enter all codes manually , Do not copy directly . Again POM Make a summary :
- POM yes selenium webdriver Automatic test practice object library design pattern
- POM Make test scripts easier to maintain
- POM The elements are further optimized by means of object library 、 Use cases 、 Data maintenance organization
This article is from WeChat official account. - Test development technology (mikezhou_talk) , author : automated testing
The source and reprint of the original text are detailed in the text , If there is any infringement , Please contact the [email protected] Delete .
Original publication time : 2021-08-05
Participation of this paper Tencent cloud media sharing plan , You are welcome to join us , share .
copyright notice
author[Test development technology],Please bring the original link to reprint, thank you.
https://en.pythonmana.com/2021/08/20210823044755662u.html
The sidebar is recommended
- [Python introduction project] use Python to generate QR code
- Compile D + +, and use d to call C from python
- Quickly build Django blog based on function calculation
- Python collects and monitors system data -- psutil
- Finally, this Python import guide has been sorted out. Look!
- Quickly build Django blog based on function calculation
- Python interface test unittest usage details
- Implementation of top-level design pattern in Python
- You can easily get started with Excel. Python data analysis package pandas (VII): breakdown
- Python simulation random coin toss (non optimized version)
guess what you like
-
Python tiktok 5000+ V, and found that everyone love this video.
-
Using linear systems in python with scipy.linalg
-
Using linear systems in python with scipy.linalg
-
Together with Python to do a license plate automatic recognition system, fun and practical!
-
You can easily get started with Excel. Python data analysis package pandas (XI): segment matching
-
Advanced practical case: Javascript confusion of Python anti crawling
-
Using linear systems in python with scipy.linalg
-
Fast power modulus Python implementation of large numbers
-
Quickly build Django blog based on function calculation
-
This paper clarifies the chaotic switching operation and elegant derivation of Python
Random recommended
- You can easily get started with Excel pandas (I): filtering function
- You can easily get started with Excel. Python data analysis package pandas (II): advanced filtering (I)
- You can easily get started with Excel. Python data analysis package pandas (2): advanced filtering (2)
- You can easily get started with Excel. Python data analysis package pandas (3): making score bar
- Test Development: self study Dubbo + Python experience summary and sharing
- You can easily get started with Excel. Python data analysis package pandas (V): duplicate value processing
- How does Python correctly call jar package encryption to get the encrypted value?
- Python 3 interview question: give an array. If there is 0 in the array, add a 0 after 0, and the overall array length remains the same
- Python simple Snake game (single player mode)
- Using linear systems in python with scipy.linalg
- Python executes functions and even code through strings! Come and understand the operation of such a top!
- Decoding the verification code of Taobao slider with Python + selenium, the road of information security
- [Python introduction project] use Python to generate QR code
- Vanessa basks in her photos and gets caught up in the golden python. There are highlights in the accompanying text. She can't forget Kobe after all
- [windows] Python installation pyteseract
- [introduction to Python project] create bar chart animation in Python
- Fundamentals of Python I
- Python series tutorials 116
- Python code reading (chapter 35): fully (deeply) expand nested lists
- Practical series 1 ️⃣ Wechat applet automatic testing practice (with Python source code)
- Python Basics: do you know how to use lists?
- Solution of no Python 3.9 installation was detected when uninstalling Python
- [Python homework] coupling network information dissemination
- [common links of Python & Python]
- Python application software development tool - tkinterdesigner v1.0 5.1 release!
- [Python development tool tkinterdiesigner]: example: develop stock monitoring alarm using Tkinter desinger
- [Python development tool Tkinter designer]: Lecture 2: introduction to Tkinter designer's example project
- [Python development tool Tkinter designer]: Lecture 1: introduction to the basic functions of Tkinter Designer
- [introduction to Python tutorial] use Python 3 to teach you how to extract any HTML main content
- Python socket implements UDP server and client
- Python socket implements TCP server and client
- leetcode 1261. Find Elements in a Contaminated Binary Tree(python)
- [algorithm learning] 1486 Array XOR operation (Java / C / C + + / Python / go / trust)
- leetcode 1974. Minimum Time to Type Word Using Special Typewriter(python)
- The mobile phone uses Python to operate picture files
- [learning notes] Python exception handling try except...
- Two methods of using pandas to read poorly structured excel. You're welcome to take them away
- Python sum (): the summation method of Python
- Practical experience sharing: use pyo3 to build your Python module
- Using Python to realize multitasking process