Pytest framework + allure explanation of interface automation testing practice

1. Preface
This article will mainly explain the pytest framework in Python, what is pytest, why it needs to be tested, why it is used, reference and extension, etc. Without further ado, let's go directly to the topic.

2. pytest explanation
2.1 What is pytest?
pytest is a unit testing framework. In the programming process, a unit mainly refers to the smallest component of the code, such as a function or a class. In object-oriented, the smallest unit is the method under the class.

When we have written a program, we will test these functions and methods to see if there are program errors. This process of testing the functions and methods of the program is called unit testing.

The test framework of pytest is similar to the unittest framework, but the test framework of pytest is more concise and efficient than unittest.
 

2.2 Why use pytest?
pytest is similar to unittest, but pytest still has many advantages:

"""
pytest优势
1、pytest能够兼容unittest,如果之前用例是unittest编写的,可以使用pytest直接进行使用
2、pytest的断言直接使用assert断言,并非使用self.asert等语法语句以及其他各式各样的断言方式
3、pytest对于失败的测试用例会提供非常详细的错误信息
4、pytest可以自动发现并收集测试用例
5、pytest有非常灵活的fixture管理
6、pytest有mark标记机制,可以标记某些用例为冒烟测试用例
7、pytest提供了非常丰富的插件系统
8、pytest不需要写类,unittest是需要写类并继承的,这里pytest更加简洁
"""

2.3 Using pytest

After installing the pytest library, set the default runner to pytest:

def test_add():
 
assert True

Framework means rules, pytest use case rules are as follows: 

"""
pytest用例规则:
1、模块名称 test开头.py结尾,或者*_test.py
2、测试用例函数的名称 def test_XXX()
3、可以不定义测试类
"""
 
"""
pytest的运行方式:
1、pycharm当中的运行图标,pytest开头开头运行,如不是pytest可以在setting中查找pytest并设置成pytest运行器
2、pytest命令行:要进入项目的根目录运行pytest命令,pytest命令会自动收集运行指令时候,所有子目录下符合要求的测试用例,例如test_login.py,模块且以test开头,函数test开头,类也是如此
3、通过python包或者python模块运行
"""

2.4 How pytest works

There are three ways to run pytest:

"""
方式一:直接通过代码左侧的三角进行运行(pycharm)
"""
 
"""
方式二:通过命令行运行 -- pytest -- html=output.html
"""
 
"""
方式三:通过python运行
"""
from datetime import datetime
 
import pytest
 
date_str = datetime.now().strftime("%Y-%m-%d-%H-%M-%S")
# 测试报告的名称
report_name = date_str + ".html"
 
pytest.main([f"--html={report}"])

2.5 Advanced features of pytest

2.5.1 pytest use case screening

We have all done smoke tests and know smoke test cases. pytest supports case screening. You can mark the desired use case to indicate that it is a smoke test case:

import pytest
 
# 格式为:@pytest.mark.自定义标记名
@pytest.mark.smoke
def test_True()
	assert True
 
@pytest.mark.smoke
def test_False()
	assert False

We can attach a separate tag to a use case or multiple use cases, but this will not work. We need to register the tag first, create a new pytest.ini configuration file and configure it:

[pytest]
markers = 
	smoke

After the registration is complete, we need to run it. Enter pytest - m "smoke" on the command line, so that the test case that has just been marked can be run. It is worth mentioning that if the mark is on the function, it means that the function belongs to the marked screening case. If the mark is on the class, then all functions under the entire class belong to the screening case. As shown in the example, all are smoke test cases

"""
用例筛选流程:
1、需要在pytest.ini中注册标记的名称
2、在测试用例函数或者测试用例类上面加上@pytest.mark.标记名
3、运行指定标签 pytest -m "标记名"
"""

If you run multiple tags, you can continue to make new tags on the function or class, such as the login tag, which means that I only want to execute the smoke test case of the login module, then register and run it again, and run it using pytest -m "smoke and login".

2.5.2 pytest realizes data-driven
pytest realizes data-driven can use unittest to realize, also can use own ddt:

Note: There can only be one parameterization of pytest and unittest, and they cannot be used together

"""
pytest使用unittest进行数据驱动的实现
"""
import unittest
imoort pytest
from unittesetreport import ddt, list_data
 
@pytest.mark.smoke
@unittestreport.ddt
class TestAddwithUnittest(unittest.TestCase):
	
	@unittestreport.list_data(["hello", "world", "mengxiaotian"])
	def test_add_three(self, case_info):
		aseert "" in ""
	
	def test_add_four(self):
		assert "" in ""
 
 
"""
使用自己的pytest实现
"""
@pytest.mark.smoke
@pytest.mark.login
@pytest.mark.parametrize("case_info", ["hello", "world"])
def test_add(case_info):
	assert True

2.5.3 pytest-fixtures

The pytest fixture will be a little different from unittest, see the code for details:

def setup_function():
    """前置条件,每个测试用例之前"""
    print("hello, world!")
 
def teardown_function():
    """后置条件,每个测试用例之后"""
 
def test_hello():
    assert 520 == 1314
 
def test_world():
    assert "" in ""
import pytest
 
# 声明这是一个测试夹具
@pytest.fixture()
def connet_to_db():
    print("前置条件:正在连接数据库...")
    yield # 在yield前的都是前置
# 清理动作
    print("后置清理,断开数据库连接...")
 
@pytest.mark.usefixtures("connect_to_db")
def test_mengxiaotian_love():
    assert 1314 == 1314

2.6 allure download

Universal Baidu search allure to enter GitHub download. Find the word Download and click releases in it

 

 

2.7 pytest plugin: allure-pytest installation and directory generation
Install through pip install allure-pytest

To generate a report, enter on the command line: pytest --alluredir=directory

To view reports use: allure serve directory

allure can be translated into Chinese, here is just a little more about how to view the report data, interested students can learn by themselves

2.8 unittest to pytest form

If it is presented in the form of code, it will be more complicated. The author directly uses remarks to explain. If the previous project is a unittest project, you can convert it to pytest according to this description:

"""
unittest转pytest:
1、数据驱动的ddt换成pytest的标记形式
2、unittest的testcase继承需要移除
3、self.asserEqual 需要重新封装
4、setUpclass 改成 pytest setup_class (参考上面的代码)
"""

 3. Summary

Finally, I would like to thank everyone who has read my article carefully. Reciprocity is always necessary. Although it is not a very valuable thing, you can take it away if you need it:

These materials should be the most comprehensive and complete preparation warehouse for [software testing] friends. This warehouse has also accompanied tens of thousands of test engineers through the most difficult journey, and I hope it can help you! Friends in need can click on the small card below to get it  

Guess you like

Origin blog.csdn.net/2301_76643199/article/details/131738849