编程技术分享平台

网站首页 > 技术教程 正文

Pytest提供的fixture修饰器怎么玩?看这里

xnh888 2024-11-17 17:25:00 技术教程 22 ℃ 0 评论

pytest 提供的 fixture 实现 unittest 中 setup/teardown 功能,可以在每次执行case之前初始化数据。不同点是,fixture 可以只在执行某几个特定 case 前运行,只需要在运行 case 前调用即可。比 setup/teardown 使用起来更灵活。
1.fixture scope 作用范围,先看下 fixture 函数的定义:

def fixture(scope="function", params=None, autouse=False, ids=None, name=None):
    """
    :arg scope:    可选四组参数:function(默认)、calss、module、package/session


    :arg params:   一个可选的参数列表,它将导致多个参数调用fixture函数和所有测试使用它。


    :arg autouse:  如果为True,则fixture func将为所有测试激活可以看到它。如果为False(默认值),则需要显式激活fixture。


    :arg ids:      每个参数对应的字符串id列表,因此它们是测试id的一部分。如果没有提供id,它们将从参数中自动生成。


    :arg name:     fixture的名称。这默认为装饰函数的名称。如果fixture在定义它的同一模块中使用,夹具的功能名称将被请求夹具的功能arg遮蔽; 解决这个问题的一种方法是将装饰函数命名 “fixture_ <fixturename>”然后使用”@ pytest.fixture(name ='<fixturename>')”。
  """


重点说下 scope 四组参数的意义:

    function:每个方法(函数)都会执行一次。


    class:每个类都会执行一次。类中有多个方法调用,只在第一个方法调用时执行。


    module:一个 .py 文件执行一次。一个.py 文件可能包含多个类和方法。


    package/session:多个文件调用一次,可以跨 .py 文件。

在所需要调用的函数前面加个装饰器@pytest.fixture()。举一个简单的例子:

import pytest


@pytest.fixture(scope='function')
def login():
    print("登录")




def test_1():
    print('测试用例1')


def test_2(login):
    print('测试用例2')


def test_3():
    print('测试用例3')


if __name__ == "__main__":
    pytest.main(['test_bcbx.py', '-s'])

执行结果:

============================= test session starts =============================
platform win32 -- Python 3.7.1, pytest-6.2.2, py-1.9.0, pluggy-0.13.1
rootdir: F:\pytest_test, configfile: pytest.ini
plugins: Faker-4.1.3, html-3.1.1, metadata-1.11.0collected 3 items


test_bcbx.py .测试用例1
登录
.测试用例2
.测试用例3
                                                         [100%]


============================== 3 passed in 0.42s ==============================
Process finished with exit code 0

只在test_2运行前运行login()

想要了解软件测试 ,或者有什么问题不懂 需要解答 记得主动咨询老师哦!

#软件测试# #程序员##Python#

Tags:

本文暂时没有评论,来添加一个吧(●'◡'●)

欢迎 发表评论:

最近发表
标签列表