pytest的fixture使用方法

'''
pytest的夹具(fixture)相比较unittest更强大,与unittest类似也是提供前后置
1、setup_function、teardown_function、setup_method、teardown_method 函数级别前后置和类级别前后置
2、pytest的fixture的包是放在conftest中,使用@pytest.fixture() 装饰器定义前置和后置,而且可以把前后置条件封装起来,将里面的一些参数给我们的测试用例使用,如果我们要用的时候直接调用就行了
3、@pytest.fixture装饰器有几个参数scope是作为作用范围,这个是很重要的概念,类似setup、teardown中的function和method,function:默认作用域,函数级别,class是测试类,module,每个模块,package 每个python包,session会话级别
4、使用yield区分前后置,前面是前置后面是后置
5、顺序:
session -> 包 -》 模块 -》 类 -》函数
同一级别,哪个在前,先执行
'''

#下面是conftest的测试夹具

import pytest

# 夹具(前置后置)
@pytest.fixture()
def init():
    print("用例级别前置")
    # yield 之前的就是前置
    yield #执行用例
    # yield 之后的就是后置
    print("用例级别后置")

@pytest.fixture(scope='module')
def read_excel():
    print("模块级别前置")
    yield
    print("模块级别后置")

@pytest.fixture(scope='class')
def db():
    print("类级别前置")
    yield
    print("类级别后置")

# package

@pytest.fixture(scope='session')
def session():
    print("我是session级别前置")
    yield
    print("我是session级别后置")

#下面是测试用例类里面的使用方法,直接当入参调用即可

class testClass1:
    def test1(self, init, read_excel, db,session):
        pass
    def test2(self, init, read_excel, db,session):
        pass
class TestClass2:
    def test3(self, init, read_excel, db,session):
        pass
    def test4(self, init, read_excel, db,session):
        pass
#看运行结果,可以看到运行顺序以及在类、方法中前后置使用的次数是怎么样的

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值