我想使用间接参数化,如这个答案和pytest文档中所示。
我希望能够设置范围,以便能够配置fixture是为每个函数运行,还是为其中许多函数运行一次。
然而,我看到我可以在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
正如@Tzane在评论中指出的那样,设置parametrize
的作用域将覆盖fixture中设置的任何作用域。
来自文件:
scope(可选[_ScopeName](–如果指定,则表示参数。作用域用于按参数对测试进行分组实例它还将覆盖任何夹具功能定义的范围,允许使用测试上下文或配置来设置动态范围。