The most detailed in history, a comprehensive analysis of the Pytest automated testing framework, just read this article...


Preface

1. pytest core basic functions

It is very easy to use, simple to get started, has rich documentation, and many examples for reference
. It has many third-party plug-ins and can customize extended functions.

During the execution of test cases, certain test cases can be marked: skip, specify execution order, mark failure, mark parameterization, etc.

Supports tag parameterization: the use case script only needs to be written once, then data-driven testing can be implemented to complete the test content of the entire module

Supports repeated execution of failed use cases
. Convenient management of use cases to facilitate continuous integration work to complete integration tasks and generate automated test reports.

The core functions of the automated testing framework:
locate test cases;
execute test cases;
assert test cases;
generate test reports;

2. Installation of commonly used plug-ins for pytest

testing framework

pytest

Generate html test report

pytest-html

Multi-threaded operation

pytest-xdist

Control the execution order of use cases

pytest-ordering

Failed use case rerun

pytest-rerunfailures

Generate allure test report

allure-pytest

Manage base paths

pytest-base-url

If you need to install the plug-in content separately, you can use the command:

pip install pytest

For collective plug-in installation, place all plug-ins that need to be installed in requirements.txt

pytest
pytest-html
pytest-xdist
pytest-ordering
pytest-rerunfailures
allure-pytest
pytest-base-url
pip install -r requirements.txt

3. pytest use case execution rules

All use cases in the project will be integrated and managed by
creating a testcases package

Default execution rules:
package name, module name, use case name (function, method) must start with test or end with test.
If the use case is defined in the form of a method, the class must start with Test and cannot have an init constructor.

4. pytest use case execution method

The first execution method: terminal interactively executes
pytest: all use cases that comply with the default rules of
pytest will be executed. Parameter configuration of the execution use case:
-s: will display the output content
-v: will display the details of the use case
-k: specify what to start with Use case execution

The second execution method: Create main function execution

import pytest


if __name__ == '__main__':
	pytest.main()

5. pytest marks skipped use cases

There are two types of marked skip functionality use cases
for unconditional skipping:

@pytest.mark.skip(reason="错误用例直接跳过")
def test_b3():
	print("用例b3开始执行")
	print(1 / 0)

Skip conditionally

# 当跳过的条件不成立,那么用例正常执行,反之不执行
@pytest.mark.skipif(2 > 1, reason="反例不执行")
def test_a2():
	print("用例a2开始执行")

6. pytest controls the order of use cases

By default, the use case execution order is based on the module name and use case name from top to bottom. If you
need to change the default execution method, you can use the pytest-ordering plug-in to change the use case execution order.

import pytest


def func():
	print("这是一个普通的函数func")
	
	
def test_a():
	print("用例a开始执行")
	
	
# 当跳过的条件不成立,那么用例正常执行,反之不执行
@pytest.mark.skipif(2 > 3, reason="反例不执行")
def test_a2():
	print("用例a2开始执行")
	
	
@pytest.mark.run(order=2)
def test_b():
	print("用例b开始执行")
	
	
@pytest.mark.run(order=1)
def test_b2():
	print("用例b2开始执行")


@pytest.mark.skip(reason="错误用例直接跳过")
def test_b3():
	print("用例b3开始执行")
	print(1 / 0)
	
class Test_C:
	@pytest.mark.run(order=0)
	def test_c(self):
		print("用例c开始执行")

If the keyword parameter order value is passed, the smaller the value, the execution will start first. If there is no mark for the execution order of the decorator, the original execution order will be followed.

7. pytest marks failed use cases

Mark use cases where exceptions or failures are expected. Only when exceptions occur are they in line with expectations. If no exceptions occur, it is an error.

An abnormal execution result occurs in the use case
XFAIL

The use case is an abnormal execution result
XPASS

8. pytest markup parameterization

About the usage scenarios of parameterization
For similar use case execution processes but using different data, you can combine parameterization to implement data-driven testing

# 实现参数化:读取不同的账号密码,进行注册测试
import pytest
@pytest.mark.parametrize(["username", "password"],
						[("1d_", "123ad_"),
						("1d_", "123ad_2"),
						("123", "456"),
						("a", "b"),
						("c", "d"),
						("666", "888"), ("1d_", "123ad_"),
						("1d_", "123ad_2"),
						("123", "456"),
						("a", "b"),
						("c", "d"),
						("666", "888"),
						("1d_", "123ad_"),
						("1d_", "123ad_2"),
						("123", "456"),
						("a", "b"),
						("c", "d"),
						("666", "888")
						])
def test_rg(username, password):
	print(f"输入账号:{
      
      username}")
	print(f"输入密码:{
      
      password}")
	print("点击注册")
	print("查看预期结果和实际结果")

The formal parameters and actual parameters used in parameterization can be lists and tuples. In order to distinguish each set of data, nested tuples can be used in the list.

Implement data-driven testing by reading csv file content combined with parameterization

# 数据驱动获取Csv文件内容进行使用
def get_csv_data():
	list1 = []
	
	# csv文件读取
	c1 = csv.reader(open(r"D:\Project234_web\data\后台登录数据内					容.csv", encoding="UTF-8"))
	for i in c1:
		list1.append(i)
	else:
		# print(list1)
		return list1

9. pytest pre- and post-processing

The pre- and post-processing mainly focuses on the pre- and post-
processing operations of the use case before and after the execution of the use case, which is used to fix the test environment and clean up and recycle resources.

The front and rear fixtures in pytest are also called fixtures and are divided into four categories:
module fixtures, class fixtures, method fixtures, and function fixtures.

import pytest


def func():
	print("这是一个普通的函数func")
	
	
@pytest.mark.xfail(reason="a没有被定义")
def test_a():
	# print(a)
	print("用例a开始执行")
	
	
# 当跳过的条件不成立,那么用例正常执行,反之不执行
@pytest.mark.skipif(2 > 3, reason="反例不执行")
def test_a2():
	print("用例a2开始执行")
	
	
@pytest.mark.run(order=2)
def test_b():
	print("用例b开始执行")
	
	
@pytest.mark.run(order=1)
def test_b2():
	print("用例b2开始执行")
	
	
@pytest.mark.skip(reason="错误用例直接跳过")
def test_b3():
	print("用例b3开始执行")
	print(1 / 0)
	
	
class Test_C:
	# 类夹具
	def setup_class(self):
		print("类夹具开始执行")
		
	def teardown_class(self):
		print("类夹具结束执行")
		
	# 方法夹具
	def setup_method(self):
		print("方法夹具开始执行")
		
	def teardown_method(self):
		print("方法夹具结束执行")
		
	@pytest.mark.run(order=0)
	def test_c(self):
		print("用例c开始执行")
		
	def test_c2(self):
		print("用例c2开始执行")

	# 函数的夹具
	def setup_function():
		print("函数夹具开始执行")
		
	def teardown_function():
		print("函数夹具结束执行")
	
	# 模块夹具
	def setup_module():
		print("模块夹具开始执行")

	def teardown_module():
		print("模块夹具结束执行")

10. Fixture firmware in pytest

Flexibly control the fixed environment
and create fixtures to complete pre- and post-processing operations

# 定义一个fixture进行前后置使用
# 用例在执行之前先链接数据库,执行之后关闭数据库
import pytest


# scope作用域:函数级别,类级别,方法级别,模块级别,会话级别
# autouse设置用例是否自动调用
@pytest.fixture(scope="function", autouse=True)
def exe_sql():
	print("开始连接数据库")
	print("连接成功")
	print("提取参数")
	yield
	print("关闭数据库")

Manually call fixture method:

# 手动使用fixture可以在函数的形参中直接写上fixture的名字即可调用前后置
def test_rg2(exe_sql):
	print(f"输入账号")
	print(f"输入密码")
	print("点击注册")
	print("查看预期结果和实际结果")
The following is the most comprehensive software testing engineer learning knowledge architecture system diagram in 2023 that I compiled.

1. Python programming from entry to proficiency

Please add image description

2. Practical implementation of interface automation projects

Please add image description

3. Web automation project actual combat

Please add image description

4. Practical implementation of App automation project

Please add image description

5. Resumes of first-tier manufacturers

Please add image description

6. Test and develop DevOps system

Please add image description

7. Commonly used automated testing tools

Please add image description

8. JMeter performance test

Please add image description

9. Summary (little surprise at the end)

In every difficult moment, there are infinite possibilities. As long as you persevere and move forward courageously, you can surpass yourself, chase your dreams, and create your own brilliant life. Believe in yourself and fight fearlessly!

Life is endless and struggle is endless. No matter the difficulties and setbacks, keep pursuing your dreams. Believe in your own strength, dare to challenge, and move forward courageously. Only by working hard can you create your own brilliant life.

Move forward courageously and not be afraid of difficulties. Overcome obstacles and exceed limits. Believe in yourself and chase your dreams. Every effort will achieve brilliance and create a magnificent life of your own. Only by continuous struggle can you shine.

Guess you like

Origin blog.csdn.net/csdnchengxi/article/details/135152689