The most detailed on the whole network, Pytest automated test framework association/parameterization actual combat, and ready-to-use...


foreword

Pytest automated testing framework: https://www.bilibili.com/video/BV18K411m7FH/

Association
Use the fixture provided by Python to achieve association

Implementation steps:
In the case directory, create a new conftest.py file. For example, if we need a token, define a public method under this file, call the login interface and return the required token value (note: public methods generally do not pass in parameters , the return value is actually optional depending on the situation)

Please add a picture description

@pytest.fixture(scope='function')   #使用pytest的fixture把下面的方法变成公共方法

In the test case that needs to be used, pass in the method name, and use it directly when you need to use the associated parameters

Please add a picture description

Interview question: How to deal with the association between interfaces?

Answer: The framework uses Python fixtures, defines a public method, and automatically calls this public method by referencing the name of the method, and obtains the required return value, such as token, to solve the associated problem. question

Separation of data and scripts in pytest (i.e. realizing parameterization process)

When is parameterization required?
In actual projects, interface addresses, request headers, request parameters, etc. are all called data. Generally speaking, data needs to be stored separately, such as in data files

Parameterization is generally used for the use of different parameters of the same interface, such as login interface, there are login success and login failure

pytest parameterization

There are two main ways to parameterize pytest, the first is to use pytest's parametrize to achieve parameterization; the second is to use data files

Use parametrize to achieve parameterized
pytest parameterization----parametrize understands: the first parameter is a string, indicating which parameter to give to the test_data() method, that is, they are the same, and the second parameter is given to a sequence. Data type (that is, tuple and array), and finally the test_data() method takes the value of the sequence and executes

Please add a picture description

The result of the operation is as follows:

Please add a picture description

From this, it can be found that the current test case has become four, which can serialize the length of the tuple (1, 2, 3, 4), and the datas at this time are each data in the tuple

Write the first interface using parametrize:

Please add a picture description

By analogy, multiple interfaces can be written

Write 6 interfaces using parametrize

Please add a picture description

For optimization
, you can also add the interface name before each test case, as follows:

Please add a picture description

Parameterization using data files

Data file preparation
You can use txt, excel, yaml and other files to store data. Beginners recommend excel, which is more intuitive

The following takes the excel file as an example: generally there will be id, title, url, headers, method, data, http_code, msg columns, pay attention to the sheet page

Please add a picture description

Store data files in the data folder
Select the data folder, right-click to display it in the file explorer, and paste the excle file just now into the data directory

Please add a picture description

Please add a picture description

Under the data folder, there is a test data file

Please add a picture description

fetch data

This will involve the knowledge of reading excel in Python, which requires the use of the third-party package xlrd in Python

①Install the xlrd package: pip3 install xlrd==1.2.0 (specified version)

Please add a picture description

②Import the py file containing the file reading and writing method in utils

Please add a picture description

Python reads the excel code:

import xlrd
def read_excel(excel_path, sheet_name, skip_first=True):    
results = []
datas = xlrd.open_workbook(excel_path)  # 打开excel获取excel的操作对象
table = datas.sheet_by_name(sheet_name) # 根据sheetname打开具体的页面
# start_row = 1 if skip_first is True else 0
if skip_first is True:      # skip_first为true:从第二行取
	start_row = 1
else:
	start_row = 0

# 循环读取excel
for row in range(start_row, table.nrows):   # [1,2,3,4,5,6]
	results.append(table.row_values(row))        
return results

# [
#     [行1],
#     [行2],
#     [行3]...
# ]
# 防止其他文件导入exceltools时执行这些代码,测试代码
if __name__ == "__main__":
a = read_excel(r'D:\小可爱\code\RCtest\data\人才管理系统.xlsx', "首页")
print(len(a), type(a))
for i in a :
	print(i)

Import exceltools in the py file for writing test cases

Please add a picture description

code show as below:

import os,sys
sys.path.append(os.getcwd())
from utils.exceltools import read_excel

Write test cases

First of all, pay special attention to the results returned by reading excel as follows, which are string type data and need to be eval, especially pay attention to the value of token: '{"token":"user_login"}', you can find that if in the excel data file , if it is directly written as {"token":user_login}, then after Python reads it, it will become '{"token":user_login}', and it can become the required dictionary format directly after eval

Please add a picture description

Modify the data file:

Please add a picture description

Print the excel file read by Python again, and the return is as follows:

Please add a picture description

Write a test case:

Please add a picture description

So far, parameterized test case writing has been realized.

optimization

Observation shows that all the test cases we have written so far are post methods. Once other types of methods are filled in the excel form, the test case will report an error. Therefore, it is necessary to encapsulate the request method twice (put in utils).

Please add a picture description

①The packaging code is as follows:

import requests


def http_request(url="", method="post", headers={
    
    }, json={
    
    }):
if method == "post":
	return requests.post(url=url, headers=headers, json=json)
elif method == "get":
	return requests.get(url=url, headers=headers, json=json)
else:
	return False

②The method of importing the package in the test case:

import os,sys
sys.path.append(os.getcwd())
from utils.httprequest import http_request

③ Modify the original test case (the method parameter was passed before ----- foresight):

Please add a picture description

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)

In your life journey, don't give up your dreams easily. No matter how difficult the road ahead is, as long as you persevere and take every step, success is waiting for you not far away.

The greatest achievement in life does not lie in the amount of harvest, but in the hard work and sweat we put in during the process of fighting and fighting for the love in our hearts and the cause we firmly believe in.

No matter what it is, only after experiencing setbacks and failures can you be more aware of what you really want and better achieve your goals. Therefore, don’t be afraid of failure, let alone difficulties, believe in yourself, and move forward firmly!

Guess you like

Origin blog.csdn.net/shuang_waiwai/article/details/130324040