How to kill tedious operations in seconds with automated testing? Try the PO pattern design framework

Introduction
Have you ever felt exhausted by rewriting a bunch of automated test code every time you update a feature?

Or have to constantly fix test scripts because page elements change frequently?

If you also have these distresses, then the PO pattern design framework may be the solution. It allows you to write automated test code in a simpler and more efficient way, reducing repetitive labor and error rates.

In this article, we will introduce how to use the PO mode design framework to kill the cumbersome automated testing operations in seconds, so that you can easily cope with the ever-changing testing environment.

po mode
In UI-level automated testing, the object design mode means testing an interactive web application, an area in the program user interface, which reduces code duplication, that is, if the user interface changes, only need Just modify the program in one place.

Advantages:
1. Create code that can be shared across multiple test cases

2. Reduce the amount of duplicate code

3. If the user interface changes, it only needs to be maintained in one place.

Create ui, and create corresponding packages and directories in the ui project. utils The name of the last package

Directory explanation:
Detailed explanation of each directory:

(1) base: the basic layer, which mainly writes the class of the underlying positioning elements, which is a package.

(2) common: public class, which writes the methods used by the public.

(3) config: configuration file storage directory.

(4) data: Store the test data used by the test.

(5) page: object layer, write specific business logic, and write a separate method or function for each operation behavior of the page.

(6) report: Test report directory, mainly used to store test reports.

(7) test: the test layer, which mainly contains test modules, which can also be said to be the code of each test scenario.

(8) utils: tools, storage tools, such as file processing, documentation, etc.

(9) run: run layer: the running directory of the entire automated test.

Page object design pattern:
base base layer:
the basic code is mainly written in this layer. In this layer, the class WebUI is mainly defined, and the method of positioning a single element and multiple elements is written in this class.

#! /usr/bin/env python
# -*- coding:utf-8 -*-
# author:张红
 
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.expected_conditions import NoSuchElementException
import time as t
 
class WebUI(object):
    def __init__(self,driver):
        #webdriver实例化后的对象
        self.driver=driver
 
    def findElement(self,*args):
        '''
        单个元素定位的方式
        :param args:
        :return: 它是一个元组,需要带上具体什么方式定位元素属性以及元素属性的值
        '''
        try:
            return self.driver.find_element(*args)
        except NoSuchElementException as e:
            return e.args[0]
 
    def findsElement(self,*args,index):
        '''
        多个元素定位的方式
        :param args:
        :param index: 被定位的目标索引值
        :return: 它是一个元组,需要带上具体什么方式定位元素属性以及元素属性的值
        '''
        try:
            return self.driver.find_elements(*args)[index]
        except NoSuchElementException as e:
            return e.args[0]

page object layer:
the classes at this layer directly inherit the classes of the base layer, specify the value of each operation element attribute with the method of class attribute, and then write the corresponding method according to the operation steps, (such as the operation about login: input user Name, enter password, click login, the information operation of obtaining the text will be the login operation implemented in the instance, and then encapsulate each login operation into a method, so that the login test case can be directly called, and the failure information will be returned --- the formal parameter will be assigned in the test layer)

Note: The method of obtaining file information must have a return value, otherwise the text information cannot be obtained when the test layer asserts, and the data attribute and method name should not be the same

 test: The test layer
first needs to import the classes in the object layer and the unittest unit test framework. In the test class, it inherits unittest.TestCase and the classes in the object layer. TestCase is used in writing automated test cases. The test firmware, test assertion and test execution all need its methods, and the classes in the object layer contain the methods of the test operation steps in the object layer, which can be directly called after inheritance.

Precautions:

1. When writing a use case, it is necessary to add remark information to clearly indicate which point of the test the use case is and which scene is verified.

2. The test modules all start with test_, and the test methods also start with test_

#! /usr/bin/env python

# -*- coding:utf-8 -*-

# author: Zhang Hong

from page.sina import *

import  unittest

from selenium import  webdriver

import time as t

from page.init import *

class SinaTest(Init,Sina):

    def test_username_null(self):

        self.login(username='',password='12345')

        t.sleep(3)

        #Verification email name is empty

        self.assertEqual(self.getUserError(), 'Please enter the mailbox name')

        t.sleep(3)

    def test_username_supportChinese(self):

        self.login(username='中国',password='12345')

        t.sleep(3)

        # Verify that the mailbox name does not support Chinese

        self.assertEqual(self.getUserError(), 'Mailbox name does not support Chinese')

        t.sleep(3)

    def test_username_formatError(self):

        self.login(username='123',password='12345')

        t.sleep(3)

        # Verify that the format of the mailbox name is incorrect

        self.assertEqual(self.getUserError(), 'The format of the mailbox name you entered is incorrect')

    def test_password_null(self):

        self.login(username='[email protected]',password='')

        t.sleep(3)

        # Verify that the password is empty

        self.assertEqual(self.getPassError(), 'Please enter a password')

        t.sleep(3)

    def test_login_error(self):

        self.login(username='[email protected]',password='724225')

        t.sleep(3)

        # Authenticate username error

        self.assertEqual(self.getUserError(), 'login name or password error')

        t.sleep(3)

data data layer:

The test data used in the early spring test (mainly write the data into json file, yaml file)

Create a json file under data

 common layer:
common: common layer, in which the files used by the public are written (processing path --- the focus is on json files or yaml files), which generally define the basic path

1. Create a public.py file in this layer

Import the os library and define the basic path (that is, process the basic path as the path of the folder where the file will be read, so that it is convenient to do path splicing when using)

 untils:
tool layer: basically in the data (reading of json yaml files)

Create a module under untils: operationJson.py, set the method readJson() to read data

In this module, we need to import os for path splicing, Json deserialization for reading files, and import the basic path under the public layer

 

config layer:

Configuration file storage directory

run layer:

The operation layer is mainly the directory for running test cases. We can run according to the test module or all modules. The content of this layer is also applicable to all scenarios (the applicable premise is that the directory structure of the po design mode is as shown above)

testing report:

 1 import time
 2 # 时间
 3 import unittest
 4 # 加载测试模块
 5 import os
 6 # 处理路径
 7 import HTMLTestRunner
 8 # 生成测试报告必须要用的库
 9 def getSuite():
10     # start_dir=加载所有的测试模块来执行,pattern=通过正则的模式加载所有的模块
11     '''获取所有执行的测试模块'''
12     suite = unittest.TestLoader().discover(
13         start_dir=os.path.dirname(__file__),
14         pattern='test_*.py'
15     )
16     return suite
17 
18 # 获取当前时间
19 def getNowtime():
20     return time.strftime("%y-%m-%d %H_%M_%S",time.localtime(time.time()))
21 
22 # 执行获取的测试模块,并获取测试报告
23 def main():
24     filename=os.path.join(os.path.dirname(__file__),'report',getNowtime()+"report.html")
25     # 把测试报告写入文件中,b是以二进制的方式写入
26     fp=open(filename,"wb")
27     # HTMLTestRunner实例化的过程,stream是流式写入,title是测试报告的标题,description是对测试报告的描述
28     runner=HTMLTestRunner.HTMLTestRunner(
29         stream=fp,
30         title="UI自动化测试报告",
31         description="UI自动化测试报告"
32     )
33     runner.run(getSuite())
34 if __name__=="__main__":
35     main()

report:

Mainly used to store test reports

epilogue

This post ends here, and finally, I hope that friends who read this post can gain something.

 How to obtain PO mode tutorial: Click [small card below]

If you think the article is not bad, please  like, share, and leave a message  , because this will be the strongest motivation for me to continue to output more high-quality articles!

Guess you like

Origin blog.csdn.net/2201_76100073/article/details/130487189