08、pytest-fixture装饰器

定义fixture跟定义普通函数差不多,唯一区别就是在函数上加个装饰器@pytest.fixture(),fixture命名不要以test开头,跟用例区分开。fixture是有返回值的,没有返回值默认为None。用例调用fixture的返回值,直接就是把fixture的函数名称当做变量名称。

import pytest

@pytest.fixture()
def test1():
    a = 'leo'
    return a

def test2(test1):
    assert test1 == 'leo'

if __name__ == '__main__':
    pytest.main(['-q','test_fixture.py'])
    
# test1函数的返回值为a,在test2函数中将test1作为参数传入

如果用例需要用到多个fixture的返回数据,fixture也可以返回一个元祖,list或字典,然后从里面取出对应数据。

import pytest

@pytest.fixture()
def test1():
    a = 1
    b = 2
    return (a, b)


def test2(test1):
    c = test1[0]
    d = test1[1]
    assert c == 1
    assert d == 2
    print('元祖形式正确')


if __name__ == '__main__':
    pytest.main('-q test_fixture.py')

当然也可以分成多个fixture,然后在用例中传多个fixture参数

import pytest

@pytest.fixture()
def test1():
    a = 1
    return a


@pytest.fixture()
def test2():
    b = 2
    return b


def test3(test1, test2):
    c = test1
    d = test2
    assert c == 1
    assert d == 2
    print('传入多个fixture参数正确')


if __name__ == '__main__':
    pytest.main(['-q' ,'test_fixture.py'])


# test3函数中传入test1和test2作为参数

先简单介绍一下,后续pytest实现前置后置的时候会说明这个pytest的具体应用场景

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值