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

dan*_*jar 16 python dependency-injection fixtures pytest

对于我的Web服务器,我有一个login创建用户的fixture,并返回发送请求所需的头.对于某个测试,我需要两个用户.如何在一个功能中两次使用相同的夹具?

from test.fixtures import login


class TestGroups(object):

    def test_get_own_only(self, login, login):
         pass
Run Code Online (Sandbox Code Playgroud)

dan*_*jar 10

另一种方法是复制夹具功能.这既简单又正确处理参数化夹具,使用两个夹具的所有参数组合调用测试功能.下面的示例代码引发了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)
Run Code Online (Sandbox Code Playgroud)

  • 不幸的是,如果 `first` 是通过它所依赖的夹具参数化的,这将无济于事。 (3认同)

Ser*_*kiy 5

我用Dummy实现夹具功能的类来做。然后从测试中调用它。提供澄清的方法名称,以更好地了解您的测试正在做什么。

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
Run Code Online (Sandbox Code Playgroud)


Dun*_*unk 5

技巧是将 mark.parametrize 与“间接”开关一起使用,因此:

@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}]
Run Code Online (Sandbox Code Playgroud)