如何通过字符串访问pytest夹具?

6 投票
2 回答
7082 浏览
提问于 2025-04-18 09:16

pytest 的“夹具”可以通过把其他夹具作为参数传入来互相配合使用:

@pytest.fixture(scope='module')
def wrapper_fixture1(fixture1):
    fixture1.do_something()
    return fixture1

现在我有多个不同的夹具,比如 fixture1fixture2fixture3,它们虽然不同,但有一些相似之处(比如都有一个叫 do_something() 的函数),我想把这个函数应用到每一个夹具上。

但是,我不想像例子那样定义三个新的夹具。我想定义一个通用的夹具/函数,来创建这三个夹具,然后可以把它们传给测试。我在想这样做:

def fixture_factory():
    for index in range(3):
        fixture = pytest.get_fixture('fixture%d'%(index+1))
        fixture.do_something()
        pytest.set_fixture('wrapper_fixture%d'%(index+1), fixture, scope='module')

这样做可以吗?还是说我必须为每个原始夹具写三个包装夹具,重复同样的代码?

2 个回答

1

你可能还想看看 pytest_generate_tests() 这个钩子(hook),它可以帮助你处理你的需求。你可以在这个链接找到更多信息:http://pytest.org/latest/plugins.html?highlight=generate_tests#_pytest.hookspec.pytest_generate_tests

6

如果你想通过一个字符串来获取一个固定的测试数据,可以在测试函数或者其他的固定数据中使用 request.getfuncargvalue()

你可以试试下面这样的写法:

import pytest

@pytest.fixture
def fixture1():
    return "I'm fixture 1"

@pytest.fixture(scope='module')
def fixture2():
    return "I'm fixture 2"

@pytest.fixture(params=[1, 2])
def all_fixtures(request):
    your_fixture = request.getfuncargvalue("fixture{}".format(request.param))
    # here you can call your_fixture.do_something()
    your_fixture += " with something"
    return your_fixture

def test_all(all_fixtures):
    assert 0, all_fixtures

撰写回答