pytest fixture 中参数的传递并举例子
时间: 2023-07-08 09:37:03 浏览: 55
pytest fixture 中的参数是通过函数参数传递的,具体传递方式有两种:一种是使用 `@pytest.fixture` 的 `params` 参数,另一种是在测试函数中直接传递参数。下面分别给出示例:
1. 使用 `@pytest.fixture` 的 `params` 参数传递参数
```python
import pytest
@pytest.fixture(params=[1, 2, 3])
def my_fixture(request):
return request.param
def test_my_fixture(my_fixture):
assert my_fixture > 0
```
在这个例子中,`@pytest.fixture` 声明了一个 fixture 函数 `my_fixture`,并使用 `params` 参数指定了三个参数值:1、2、3。在测试函数 `test_my_fixture` 中,`my_fixture` 作为参数传递进去,它的值会依次取到 1、2、3,每次都会执行一遍测试函数。因为 `assert` 语句的条件 `my_fixture > 0` 满足,所以测试函数通过。
2. 在测试函数中直接传递参数
```python
import pytest
@pytest.fixture
def my_fixture():
return 42
def test_my_fixture(my_fixture):
assert my_fixture == 42
def test_my_fixture_with_param():
param = 24
assert my_fixture(param) == 66
```
在这个例子中,`@pytest.fixture` 声明了一个 fixture 函数 `my_fixture`,它返回了一个值 42。在测试函数 `test_my_fixture` 中,`my_fixture` 作为参数传递进去,这个测试函数断言 `my_fixture` 返回的值等于 42。在测试函数 `test_my_fixture_with_param` 中,我们创建了一个参数 `param`,并通过 `my_fixture(param)` 的方式直接调用了 fixture 函数,并传递了参数 `param`。这里我们规定,`my_fixture` 函数接收一个整数参数,然后把它加上 42 再返回。因此,测试函数 `test_my_fixture_with_param` 的断言条件是 `my_fixture(param) == 66`。这个测试函数通过。