Pytest在一个函数中使用相同的fixture两次

2024-05-17 11:58:40 发布

您现在位置:Python中文网/ 问答频道 /正文

对于我的web服务器,我有一个loginfixture,它创建一个用户并返回发送请求所需的头。对于某个测试,我需要两个用户。如何在一个函数中使用同一个夹具两次?在

from test.fixtures import login


class TestGroups(object):

    def test_get_own_only(self, login, login):
         pass

Tags: 函数用户fromtestimport服务器webobject
3条回答

另一种方法是复制fixture函数。这既简单又正确地处理了参数化fixture,并使用两个fixture的所有参数组合调用test函数。下面的示例代码引发了9个断言:

import pytest

@pytest.fixture(params=[0, 1, 2])
def first(request):
    return request.param

second = first

def test_double_fixture(first, second):
    assert False, '{} {}'.format(first, second)

诀窍是利用标记参数化使用“间接”开关,因此:

@pytest.fixture
def data_repeated(request):
    return [deepcopy({'a': 1, 'b': 2}) for _ in range(request.param)]


@pytest.mark.parametrize('data_repeated', [3], indirect=['data_repeated'])
def test(data_repeated):
    assert data_repeated == [
        {'a': 1, 'b': 2},
        {'a': 1, 'b': 2},
        {'a': 1, 'b': 2}]

我用Dummy类来实现fixture功能。那就从你的测试中打出来。提供明确的方法名称,以便更好地理解您的测试在做什么。 在

import pytest

@pytest.fixture
def login():
    class Dummy:
        def make_user(self):
            return 'New user name'
    return Dummy()

def test_something(login):
    a = login.make_user()
    b = login.make_user()
    assert a == b

相关问题 更多 >