参数化夹具的范围不起作用。
这是夹具和测试的示例:
@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
我的猜测是您想将参数“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 按参数而不是测试名称对测试进行分组。