0

我想使用此答案pytest 文档中所示的间接参数化。

我希望能够设置范围以能够配置是否为每个功能运行夹具或为其中许多功能运行一次。

但是我看到我可以在fixture装饰器上设置范围:

import pytest

@pytest.fixture(scope="function")
def fixt(request):
    return request.param * 3

@pytest.mark.parametrize("fixt", ["a", "b"], indirect=True)
def test_indirect(fixt):
    assert len(fixt) == 3

或者在parametrize装饰器上:

import pytest

@pytest.fixture
def fixt(request):
    return request.param * 3

@pytest.mark.parametrize("fixt", ["a", "b"], indirect=True, scope="function")
def test_indirect(fixt):
    assert len(fixt) == 3

甚至两者同时:

import pytest

@pytest.fixture(scope="function")
def fixt(request):
    return request.param * 3

@pytest.mark.parametrize("fixt", ["a", "b"], indirect=True, scope="function")
def test_indirect(fixt):
    assert len(fixt) == 3

有什么区别,什么时候应该设置每个?


更新:

我测试了每一个,看看它们有什么不同。

我用于测试的代码:

import pytest

scope_fixture="function"
scope_parametrize="module"

with open('scope_log.txt', 'a') as file:
    file.write(f'--------\n')
    file.write(f'{scope_fixture=}\n')
    file.write(f'{scope_parametrize=}\n')

@pytest.fixture(scope=scope_fixture)
def fixt(request):
    with open('scope_log.txt', 'a') as file:
        file.write(f'fixture ' + str(request.param)+'\n')
    return request.param * 3

@pytest.mark.parametrize("fixt", ["a", "b"], indirect=True, scope=scope_parametrize)
def test_indirect1(fixt):
    with open('scope_log.txt', 'a') as file:
        file.write(f'1 ' + str(fixt)+'\n')
    assert len(fixt) == 3

@pytest.mark.parametrize("fixt", ["a", "b"], indirect=True, scope=scope_parametrize)
def test_indirect2(fixt):
    with open('scope_log.txt', 'a') as file:
        file.write(f'2 ' + str(fixt)+'\n')
    assert len(fixt) == 3

结果:

scope_fixture=None
scope_parametrize=None
fixture a
1 aaa
fixture b
1 bbb
fixture a
2 aaa
fixture b
2 bbb
--------
scope_fixture='function'
scope_parametrize=None
fixture a
1 aaa
fixture b
1 bbb
fixture a
2 aaa
fixture b
2 bbb
--------
scope_fixture='module'
scope_parametrize=None
fixture a
1 aaa
2 aaa
fixture b
1 bbb
2 bbb
--------
scope_fixture=None
scope_parametrize='function'
fixture a
1 aaa
fixture b
1 bbb
fixture a
2 aaa
fixture b
2 bbb
--------
scope_fixture=None
scope_parametrize='module'
fixture a
1 aaa
2 aaa
fixture b
1 bbb
2 bbb
--------
scope_fixture='function'
scope_parametrize='module'
fixture a
1 aaa
2 aaa
fixture b
1 bbb
2 bbb
--------
scope_fixture='module'
scope_parametrize='module'
fixture a
1 aaa
2 aaa
fixture b
1 bbb
2 bbb
--------
scope_fixture='module'
scope_parametrize='function'
fixture a
1 aaa
fixture b
1 bbb
fixture a
2 aaa
fixture b
2 bbb
--------
scope_fixture='function'
scope_parametrize='function'
fixture a
1 aaa
fixture b
1 bbb
fixture a
2 aaa
fixture b
2 bbb

4

1 回答 1

0

正如@Tzane 在评论中指出的那样,设置范围parametrize会覆盖夹具中设置的任何范围。

文档

范围(可选[_ScopeName])——如果指定,它表示参数的范围。范围用于按参数实例对测试进行分组。它还将覆盖任何夹具功能定义的范围,允许使用测试上下文或配置设置动态范围。

于 2022-01-21T14:14:19.120 回答