当前位置:网站首页>How to apply Po mode in selenium automated testing
How to apply Po mode in selenium automated testing
2022-07-24 20:23:00 【Zeze said test】
PO The pattern is UI A design pattern that is frequently used in automated testing , After using this mode , It can effectively improve the reusability of code , And make the maintenance of automatic test code more convenient .
PO The full name of the pattern is page object model(POM), Sometimes it's called page object pattern. First proposed by Martin Fowler , This model is affected selenium Automated testing framework is vigorously promoted , Therefore, it has become a very mainstream automatic test design pattern .
stay PO In the mode , every last UI Pages are represented by classes in the programming language . In this class , Define the behavior and operation of the page in the form of function . This allows the caller not to pay attention to whether the specific operation is to click or drag , But focus on specific business , For example, login. 、 Shopping and so on , Even if the programmer shows the code directly to the product manager , He can also understand .

Not used PO Mode time
Write browser operations directly in test cases API, It's not very difficult for coders , Because he himself has been to these API very familiar , But these browser operations do not reflect the business , At least not as familiar as the product manager , So it's hard for him to communicate with the product manager , It's also difficult to communicate with developers , Even half a month later , He had forgotten what he had written .
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()
Use PO Pattern
Use PO The mode is conducive to combing the business , It's also good for communicating with others . When you show the following code to the product manager , He may also know what business you are measuring , Can help you correct your test process , Or make some more constructive suggestions , This is very useful when large projects need to communicate and sort out business frequently .
def test_login_mail(self):
LoginPage(driver).login()
The operation of the browser itself , Will be separated into a lower level module , This code you can not expose to the caller , The product manager doesn't care what elements of your page are positioned , He doesn't understand .
class LoginPage:
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")
def __init__(self, driver):
self.driver = driver
def login(self):
self.driver.find_element(*self.username_loc).clear()
self.driver.find_element(*self.username_loc).send_keys("xxxxx")
self.driver.find_element(*self.password_loc).clear()
self.driver.find_element(*self.password_loc).send_keys("xxxxxx")
self.driver.find_element(*self.submit_loc).click()
This method separates the element positioning method . However, the readability of this element positioning expression is not very strong , It can be replaced by property Way to represent elements , All the elements are put together , It's also convenient to modify .
class LoginPage:
def __init__(self, driver)
self.driver = driver
@property
def username_element(self):
return self.driver.find_element('id', 'idInput')
@property
def password_element(self):
return self.driver.find_element('id', 'pwdInput')
@property
def submit_element(self):
return self.driver.find_element('id', 'loginBtn')
def login(self, name, password):
self.username_element.send_keys(name)
self.password_element.send_keys(password)
self.submit_element.click()
The third way can make full use of Python Descriptor properties , You will find many serialization libraries or ORM Frameworks have similar uses .
class LoginPage:
def __init__(self, driver)
self.driver = driver
username = Element(css='#idInput', desc=' User name input box ')
password = Element(css='#pwdInput', desc=' Password input box ')
confirm = Element(css='#loginBtn', desc=' Login confirmation button ')
def login(self, name, password):
self.username.send_keys(name)
self.password.send_keys(password)
self.confirm.click()
and Element Class can pass through Python Descriptor implementation , This is just for convenience , It only defines xpath The element positioning method of :
class Element:
def __init__(self,xpath=None,desc=''):
self.xpath = xpath
self.desc = desc
def __get__(self, instance, owner):
driver = instance.browser
el = driver.find_element('xpath', self.xpath)
return el
PO Patterns and DDD
PO The pattern is DDD( Domain-driven design ) A simple implementation of , But it's not thorough enough . If you want to implement in automated testing DDD, I think there is still some room for optimization .
First of all, a business is not necessarily just the operation of a single page , For example, login does not necessarily involve only LoginPage This page , So directly in LoginPage Written in login Function is not very reasonable . For the caller , It should be clear who is logging in , Not a page . like this :
user.login()
# or
login(user)
The code we write is like natural language , Anyone who knows English knows what the code is doing , stay DDD in , It's called domain specific language (DSL), To implement this logic , stay Page There should also be a hierarchy between classes and calls to encapsulate user.
secondly ,Page Pages rely on lower level resources , Like components , Element type . So in Page Class should use InputElement, ButtonElement 、SelectElement Such element classes and HeaderComponent、FooterComponent Such component classes .
class LoginPage:
username_filed = InputElement('xxx')
password_filed = PasswordElement('xxx')
Domain driven design is very important for large-scale projects 、 Synchronization service 、 Communicating business is very helpful , It is a business centered design paradigm .PO Pattern for DDD Small scale application of , And specific enough benefits :
- Easy to maintain . The operation of each page is stored separately in a class file , After the current page is modified , You just need to find the corresponding class file to modify , Other code does not need to be modified , This is in line with the principle of single responsibility .
- Easy to reuse . During automated testing , A test consists of multiple test steps , These test steps may involve the operation of multiple pages . The operations between use cases may coincide .PO Patterns can reuse these test steps , Simplify the writing of code .
- Improved readability . The operations of the page are encapsulated in the form of functions . The function name has the function of annotation , When others read the code, they can understand the business through functions .
The end of this paper , If it's not fun , I also sorted out the complete notes from the introduction to advanced software testing , You can click to view
What does software testing need to learn ?
The contents that have been updated include Selenium Web side web automated testing :
One 、 Why Selenium Do automated tests
Two 、Selenium chromedriver Installation tutorial and quick use
Four 、Selenium How elements are positioned
5、 ... and 、Selenium The way to wait
6、 ... and 、Selenium Scrolling pages
7、 ... and 、Selenium How to use POM Hierarchical mode
8、 ... and 、Selenium Keyword driven automated test framework
Appium Mobile App automated testing
One 、Appium Environment construction nanny level tutorial
Two 、Appium Get started quickly in five minutes
3、 ... and 、Appium How to locate elements
Four 、Appium The core API operation
5、 ... and 、Appium Get and click coordinates
6、 ... and 、Appium Zoom in and out of the picture
7、 ... and 、Appium H5 How to test the page
8、 ... and 、Appium 2.0 Release , How to upgrade
Nine 、Appium How to do concurrent testing
Come in and have a look :
Software testing and automated testing learning roadmap
边栏推荐
- Redis common configuration description
- English grammar_ Demonstrative pronoun this / these / that / those
- API data interface of A-share transaction data
- Lunch break train & problem thinking: thinking about the problem of converting the string formed by hour: minute: second to second
- Install MySQL 5.7.37 on windows10
- [mathematical modeling / mathematical programming model]
- How to view the execution plan of a stored procedure in Youxuan database
- Synthesis route of ALA PNA alanine modified PNA peptide nucleic acid | AC ala PNA
- Easy to use office network optimization tool onedns
- Expression evaluation (stack)
猜你喜欢

Xiaomi 12s ultra products are so powerful, but foreigners can't buy Lei Jun: first concentrate on the Chinese market

API data interface of A-share transaction data

Each blogger needs to ask himself seven basic questions

Redis basic knowledge, application scenarios, cluster installation

Leetcode 560 and the subarray of K (with negative numbers, one-time traversal prefix and), leetcode 438 find all alphabetic ectopic words in the string (optimized sliding window), leetcode 141 circula

Connect the smart WiFi remote control in the home assistant
![[training Day9] rotate [violence] [thinking]](/img/b9/598dd0dffb9c82230f43484f9c8a1e.png)
[training Day9] rotate [violence] [thinking]

Browser local storage webstroage

C form application treeview control use

Methods of using tyrosine modified peptide nucleic acid PNA | Tyr PNA | BZ Tyr PNA | 99Tcm survivinmrna antisense peptide nucleic acid
随机推荐
Software testing interview tips | if you don't receive the offer, I'll wash my hair upside down
Todolist case
871. Sum of divisors
Substr and substring function usage in SQL
SSL Error: Unable to verify the first certificate
【LeetCode】1184. 公交站间的距离
Bypass using the upper limit of the maximum number of regular backtracking
Xiaomi 12s ultra products are so powerful, but foreigners can't buy Lei Jun: first concentrate on the Chinese market
[German flavor] safety: how to provide more protection for pedestrians
Student achievement management system based on PHP
1. Mx6u-alpha development board (key input experiment)
Leetcode 1911. maximum subsequence alternating sum
Synthesis route of ALA PNA alanine modified PNA peptide nucleic acid | AC ala PNA
Machine learning job interview summary: five key points that resume should pay attention to
Alibaba cloud technology expert Yang Zeqiang: building observable capabilities on elastic computing cloud
[sciter]: window communication
Monotone stack and monotone queue (linear complexity optimization)
Choose the appropriate container runtime for kubernetes
API data interface of A-share transaction data
vlan技术