pytest的fixture

发布时间 2023-05-04 17:01:19作者: 工作手记

1 什么是fixture

@pytest.fixture
def my_fruit():
    return Fruit("apple")

如上,用@pytest.fixture装饰的函数就是fixture

2 fixture的作用

我的理解是为test函数的运行提供数据、必要的环境支持等

3 fixture的定义与使用

fixture直接用于test函数

image

image

@pytest.fixture
def mysql_conn(url):
    return xxx
#提供一个mysql连接给到test,方便test查询mysql数据
def test_get_data(mysql_conn):
    conn = mysql_conn
    xxx

如上,pytest在执行test函数之前会检查test函数的参数,然后去fixture里面找有没有与参数同名的函数,有的话就会先执行fixture,然后在执行test函数,在test函数里面,用该参数就能获得它所表示的fixture的返回值

fixture 用于其他fixture之中

image
执行结果
image

pytest内置的fixture

pytest有自带许多fixture,不需要我们定义直接拿来用就行
https://docs.pytest.org/en/stable/reference/fixtures.html#built-in-fixtures
下面是tmpdir这个fixture
image