The best in the whole network, Web automated testing framework + PO mode layered actual combat (ultra-fine finishing)


foreword

PO mode

In UI-level automated testing, the object design pattern 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 one Just modify the program locally.

Advantages:
Create code that can be shared across multiple test cases;
reduce the amount of duplicate code;
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

B1

Explanation:
base: base layer, which mainly writes classes for positioning elements at the bottom layer, which is a package.
common: public class, which writes the methods used by the public.
config: Configuration file storage directory.
data: store the test data used by the test.
page: object layer, write specific business logic, and write a method or function for each operation behavior of the page separately.
report: Test report directory, mainly used to store test reports.
test: The test layer, which mainly contains test modules, which can also be said to be the code of each test scenario.
utils: tool class, storing tools, such as file processing, documentation, etc.
run: running layer: the running directory of the entire automated test.

Page Object Design Pattern

1. Base base layer
In this layer, the basic code is mainly written. 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.

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]

2. 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.

For example, about the login operation: enter the user name, enter the password, click login, and the information operation of obtaining the text will implement the login operation in the instance, and then encapsulate each login operation into a method, so that the login test case can be directly called and returned Failure message—where formal parameters will be assigned values ​​at 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

from base.base import *
from selenium.webdriver.common.by import By

class Sina(WebUI):
    username_loc=(By.ID,'freename')
    password_loc=(By.ID,'freepassword')
    login_loc=(By.CLASS_NAME,'loginBtn')
    userError_loc=(By.XPATH,'/html/body/div[3]/div/div[2]/div/div/div[4]/div[1]/div[1]/div[1]/span[1]')
    passError_loc=(By.XPATH,'/html/body/div[3]/div/div[2]/div/div/div[4]/div[1]/div[1]/div[1]/span[2]')



    def inputUserName(self,username):
        self.findElement(*self.username_loc).send_keys(username)

    def inputPassWord(self,password):
        self.findElement(*self.password_loc).send_keys(password)


    def clickLogin(self):
        self.findElement(*self.login_loc).click()

    def login(self,username,password):
        self.inputUserName(username=username)
        self.inputPassWord(password=password)
        self.clickLogin()

    def getUserError(self):
        return self.findElement(*self.userError_loc).text

    def getPassError(self):
        return self.findElement(*self.passError_loc).text

B2

3. The test test layer
here 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.

Note:
When writing a use case, you need to add remark information to clearly indicate which point of the use case is tested and which scenario is verified;
test modules start with test_, and test methods also start with test_;

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)
        # 验证邮箱名为空
        self.assertEqual(self.getUserError(),'请输入邮箱名')
        t.sleep(3)
 
 
    def test_username_supportChinese(self):
        self.login(username='中国',password='12345')
        t.sleep(3)
        # 验证邮箱名不支持中文
        self.assertEqual(self.getUserError(),'邮箱名不支持中文')
        t.sleep(3)
 
 
    def test_username_formatError(self):
        self.login(username='123',password='12345')
        t.sleep(3)
        # 验证邮箱名格式不正确
        self.assertEqual(self.getUserError(),'您输入的邮箱名格式不正确')
 
    def test_password_null(self):
        self.login(username='[email protected]',password='')
        t.sleep(3)
        # 验证密码为空
        self.assertEqual(self.getPassError(),'请输入密码')
        t.sleep(3)
 
    def test_login_error(self):
        self.login(username='[email protected]',password='724225')
        t.sleep(3)
        # 验证用户名错误
        self.assertEqual(self.getUserError(),'登录名或密码错误')
        t.sleep(3)

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

Create a json file under data

B3

5. 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

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)

import os

def base_dir():
	return os.path.dirname(os.path.dirname(__file__))
 	# print(base_dir())

B4

6. Untils layer
Tool layer: basically for 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

import os
from common.public import base_dir
import json

def readJson():
    return json.load(open(file=os.path.join(base_dir(),'data','sina.json'),encoding='utf-8'))

B6

7. config layer
configuration file storage directory

8. 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 the directory structure of the po design mode As shown above)

testing report:

import time
# 时间
import unittest
# 加载测试模块
import os
# 处理路径
import HTMLTestRunner
# 生成测试报告必须要用的库
def getSuite():
    # start_dir=加载所有的测试模块来执行,pattern=通过正则的模式加载所有的模块
    '''获取所有执行的测试模块'''
    suite = unittest.TestLoader().discover(
        start_dir=os.path.dirname(__file__),
        pattern='test_*.py'
    )
    return suite

# 获取当前时间
def getNowtime():
    return time.strftime("%y-%m-%d %H_%M_%S",time.localtime(time.time()))

# 执行获取的测试模块,并获取测试报告
def main():
    filename=os.path.join(os.path.dirname(__file__),'report',getNowtime()+"report.html")
    # 把测试报告写入文件中,b是以二进制的方式写入
    fp=open(filename,"wb")
    # HTMLTestRunner实例化的过程,stream是流式写入,title是测试报告的标题,description是对测试报告的描述
    runner=HTMLTestRunner.HTMLTestRunner(
        stream=fp,
        title="UI自动化测试报告",
        description="UI自动化测试报告"
    )
    runner.run(getSuite())
if __name__=="__main__":
    main()

9. The report layer
is mainly used to store test reports

The following is the most complete software test engineer learning knowledge architecture system diagram in 2023 that I compiled

1. From entry to mastery of Python programming

Please add a picture description

2. Interface automation project actual combat

Please add a picture description

3. Actual Combat of Web Automation Project

Please add a picture description

4. Actual Combat of App Automation Project

Please add a picture description

5. Resume of first-tier manufacturers

Please add a picture description

6. Test and develop DevOps system

Please add a picture description

7. Commonly used automated testing tools

Please add a picture description

Eight, JMeter performance test

Please add a picture description

9. Summary (little surprise at the end)

On the stage of life, only struggle can compose a brilliant movement! No matter how difficult it is, as long as you have a dream and work hard, success will eventually belong to you! Believe in your own strength, go forward bravely, and meet the glory and glory of the future!

Only with unremitting efforts can we reap brilliant achievements; every challenge is an opportunity for success, go forward bravely, with faith in your heart, you will be able to create your own brilliant chapter!

Only with unremitting struggle can we write a brilliant movement of life; only with the sweat of hard work can we water the flowers of success. Believe in yourself, go forward bravely, you will create your own brilliance!

Guess you like

Origin blog.csdn.net/m0_70102063/article/details/131788276