如何为参数化夹具正确设置作用域

0 投票
2 回答
51 浏览
提问于 2025-04-14 17:33

参数化的固定装置作用范围没有按预期工作。

下面是一个固定装置和测试的例子:

@pytest.fixture(scope='session')
def my_fixture(request):
       # make some API calls
       # print API call response
       return response

测试

@pytest.mark.parametrize('my_fixture',['a','b']):
def test_scenario_1(my_fixture):
      assert response['text'] == 'abc' 

@pytest.mark.parametrize('my_fixture',['a','b']):
def test_scenario_2(my_fixture):
      assert response['image'] == 'def' 

当我运行测试时,我看到API的响应被打印了4次(每个参数打印了两次,分别是参数a和参数b)。我本来希望它只打印两次(每个参数各一次 - a和b),因为这两个测试使用的是同一组参数,而且这个固定装置的作用范围是会话级别的。显然,如果我不对固定装置进行参数化,API的响应只会打印一次。我的Pytest版本是7.4.2。

2 个回答

0

我觉得你对这些测试环境的实现方式有些误解。

函数(每个测试函数只设置和清理一次)。

类(每个测试类只设置和清理一次)。

模块(每个测试模块/文件只设置和清理一次)。

会话(每个测试会话只设置和清理一次,也就是包含一个或多个测试文件)。

这段话是文档中关于每种范围如何处理的说明。正如你所看到的,会话会被调用两次(一次是在开始时设置,一次是在结束时清理,每个测试都会这样)。

0

我猜你是想把参数'a'和'b'传给这个叫my_fixture的工具。下面是我会怎么做的:

import pytest


@pytest.fixture(scope="session", params=["a", "b"])
def my_fixture(request):
    param = request.param  # param='a', then 'b'

    # Call the API and return the response
    return {
        "param": param,
        "text": "abc",
        "image": "def",
    }


def test_scenario_1(my_fixture):
    assert my_fixture["text"] == "abc"


def test_scenario_2(my_fixture):
    assert my_fixture["image"] == "def"

输出结果:

test_foo.py::test_scenario_1[a] PASSED
test_foo.py::test_scenario_2[a] PASSED
test_foo.py::test_scenario_1[b] PASSED
test_foo.py::test_scenario_2[b] PASSED

注意,pytest是根据参数来分组测试的,而不是根据测试的名字。

撰写回答