Unittest automated testing framework vs. Pytest automated testing framework

Introduction
The previous article Introduction to Python unit testing framework has introduced the python unit testing framework. People often use unittest because it is relatively basic and can be used for secondary development. If your development level is very high, integrated development and automated testing Platforms are also available. This article mainly talks about the difference between unittest and pytest. Compared with unittest, pytest has simple code, convenient and flexible use, and rich plug-ins.

Unittest vs Pytest
mainly compares the differences between unittest and pytest in terms of use case writing rules, use case pre- and post-processing, parameterization, assertions, use case execution, failure re-running and reporting:

Use case writing rules

 Use case pre- and post-conditions

  affirmation

 testing report

  Failure rerun mechanism

  to parameterize

 Use case classification execution

  If it doesn’t look good, you can look at the table below:

Generally speaking, the unittest use case format is complex, has no compatibility, has few plug-ins, and is convenient for secondary development. pytest is more convenient and faster. The use case format is simple. It can execute unittest style test cases without modifying any code of the unittest use case. It has better compatibility. There are many pytest plug-ins, such as the flask plug-in, which can be used to rerun use cases when errors occur, and the xdist plug-in, which can be used for parallel execution of devices and is more efficient.

Example Demonstration
After talking about the seven major differences, always demonstrate specific examples and use facts to speak for themselves.

Differences between pre- and post-positioning.
Let’s talk about the difference between pre- and post-positioning in use cases. Let’s first look at the use of pre- and post-positioning in unittest:

import unittest

class TestFixtures01(unittest.TestCase):

    # 所有用例执行前执行

    def setUp(self) -> None:

        print("setUp开始")

    def tearDown(self) -> None:

        print("tearDown结束")

    # 每条用例执行前执行

    @classmethod

    def setUpClass(cls) -> None:

        print("setUpClass开始")

    @classmethod

    def tearDownClass(cls) -> None:

        print("tearDownClass结束")

    # 测试用例

    def test_001(self):

        print("测试用例001")

class TestFixtures02(unittest.TestCase):

    def test_002(self):

        print("测试类2")

# 每个模块执行前执行

def setUpModule():

    """

    在所有测试类在调用之前会被执行一次,函数名是固定写法,会被unittest框架自动识别

    """

    print('集成测试 >>>>>>>>>>>>>>开始')

def tearDownModule():

    print("集成测试 >>>>>>>>>>>>>>结束")

if __name__ == '__main__':

    unittest.main()

operation result:

From the results, we know the logical priority of the three methods: setUp()&tearDown() < setUpClass()&tearDownClass() < setUpModule()&tearDownModule()

Next, look at the pre- and post-processing of pytest:

1. We all know that pre- and post-processing are used in automated testing. Compared with unittest, pytest is much more flexible in terms of pre- and post-processing and plug-ins. It can also be defined by fixtures.

First, let’s understand that the pre- and post-level levels of use case execution are as follows:

1. Module level: global, the entire module is run only once, taking precedence over test cases.

2. Class level: It is defined in a class and only takes effect for this class. cls decorator similar to unittest

3. Function level: Only effective for functions, not functions below the class.

4. Method level: defined in the class, each use case is executed once

def setup_module():

    print('\n整个模块 前 只运行一次')

def teardown_module():

    print('\n整个模块 后 只运行一次')

def setup_function():

    print('\n不在类中的函数,每个用例 前 只运行一次')

def teardown_function():

    print('\n不在类中的函数,每个用例 后 只运行一次')

def test_ab():

    b = 2

    assert b < 3

def test_aba():

    b = 2

    assert b < 3

class Test_api():

    def setup_class(self):

        print('\n此类用例 前 只执行一次')

    def teardown_class(self):

        print('\n此类用例 后 只执行一次')

    def setup_method(self):

        print('\n此类每个用例 前 只执行一次')

    def teardown_method(self):

        print('\n此类每个用例 后 执行一次')

    def test_aa(self):

        a = 1

        print('\n我是用例:a')       # pytest -s 显示打印内容

        assert a > 0

    def test_b(self):

        b = 2

        assert b < 3

operation result:

2. This is the original usage. Let’s look at using Fixture below. Fixture is actually customizing pytest to perform pre- and post-case operations. First, create the conftest.py file (specifying this naming), import the pytest module, and use the pytest.fixture decorator. The default level is: function level:

  It can be called from other use case files. Define a function as follows and inherit the login function in the conftest.py file to call:

# conftest.py配置需要注意以下点:

# conftest.py配置脚本名称是固定的,不能改名称

# conftest.py与运行的用例要在同一个pakage下,并且有__init__.py文件

# 不需要import导入 conftest.py,pytest用例会自动查找

import pytest

def test_one(login):

    print("登陆后,操作111")

# def test_two():

#   print("操作222")

#

# def test_three(login):

#   print("登陆后,操作333")

operation result:

3. Extended usage, multiple custom functions and global level display: (global, such as for logging in to obtain token, other use case modules do not need to log in again)

import pytest

def test_one(login):

    print("登陆后,操作111")

def test_two(login,open_page):

    print("测试用例2")

def test_three(open_page):

    print("测试用例3")

 operation result:

Careful people should know that test case 2 does not call the login function because the preset setting is shared mode, similar to a global function.

Parameterization distinguishes
parameterized application scenarios. The use case of a scenario will use multiple pieces of data for verification. For example, the login function will use the correct user name and password to log in, the wrong user name, the correct password, the correct user name, Wrong passwords, etc. are tested. At this time, parameterization in the framework can be used to complete the test conveniently.

Parameterization is a data-driven idea, that is, multiple sets of data tests can be performed in one test case, and each set of data is separate and independent.

Unittest parameterization is actually: ddt, which is called data-driven.

Pytest data driver is parameterization, use @pytest.mark.parametrize

1. Let’s first look at how unittest is parameterized:

test_data = [1,2,3]

@ddt.ddt

class Testddt(unittest.TestCase):

    @ddt.data(*test_data)

    def test_001(self,get_data):

        print(get_data)

if __name__ == '__main__':

    unittest.main()

operation result:

2.Usage of parameterization in pytest

Add in front of the test case:
@pytest.mark.parametrize("parameter name", list data)
parameter name: used to receive each item of data and serve as a parameter of the test case.
List data: A set of test data.

@pytest.mark.parametrize("parameter1,parameter2",[(data1,data2),(data1,data2)])
Example:
@pytest.mark.parametrize("a,b,c", [(1,3,4),(10,35,45),(22.22,22.22,44.44)])
def test_add(a,b,c):
res = a + b
assert res == c

Example:

@pytest.mark.parametrize('data',[1,2,3])

class Testddt(object):

    def test_001(self,data):

        print(data)

if __name__ == '__main__':

    pytest.main(['-sv'])

operation result:

Summarize

  The above is the difference between the unittest and pytest test frameworks. The seven main differences. Two examples of the differences have been mentioned here. The other five will be added when I have time. Friends who are interested in python automated testing can join the small card below for discussion. Share your thoughts.

The following are supporting learning materials. For those who are doing [software testing], it should be the most comprehensive and complete preparation warehouse. This warehouse has also accompanied me through the most difficult journey. I hope it can also help you!

Software testing interview applet

A software test question bank that has been used by millions of people! ! ! Who is who knows! ! ! The most comprehensive interview test mini program on the Internet, you can use your mobile phone to answer questions, take the subway, bus, and roll it up!

Covers the following interview question sections:

1. Basic theory of software testing, 2. web, app, interface function testing, 3. network, 4. database, 5. linux

6. Web, app, interface automation, 7. Performance testing, 8. Programming basics, 9. HR interview questions, 10. Open test questions, 11. Security testing, 12. Computer basics

How to obtain information:

Guess you like

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