具有长名称的 pytest 夹具变体的较短选项名称

Shorter option names for pytest fixture variants with long names

我正在使用定义为 fixtures 的多个传入数据集测试一个函数,但是夹具名称变得非常麻烦,无法将它们彼此区分开来。

@pytest.fixture()
def dataset_with_foo():
    pass

@pytest.fixture()
def dataset_with_bar():
    pass

@pytest.fixture()
def dataset_with_foo_and_bar():
    pass

def test_something(dataset_with_foo_and_bar):
    pass

有没有办法为更短的选项名称定义某种别名?例如,类似于:

@usesfixture("dataset_with_foo_and_bar", option_name="dataset")
def test_something(dataset):
    pass

好的,我能找到的最好方法是使用 deferred parametrized fixtures:

@pytest.fixture()
def dataset(request):
    mapping = {
        "with-foo": create_dataset_with_foo(),
        "with-bar": create_dataset_with_bar(),
        "with-foo-and-bar": create_dataset_with_foo_and_bar(),
    }

    return mapping[request.param]

def create_dataset_with_foo():
    pass 

def create_dataset_with_bar():
    pass

def create_dataset_with_foo_and_bar():
    pass

@pytest.mark.parametrize("dataset", ["with-foo"], indirect=True)
def test_something(dataset):
    pass

@pytest.mark.parametrize("dataset", ["with-foo-and-bar"], indirect=True)
def test_something(dataset):
    pass

还有其他尝试使用 pytest-lazy-fixture 或专门的装饰器,但我觉得它有点太老套了.. https://gist.github.com/wcooley/7472b8de6edb1e8ceda560843c0519a8

创建一个超级夹具和辅助函数以使用一个夹具获得所需的夹具。

import pytest

@pytest.fixture
def super_fixture(fixture1,fixture2,fixture3):
    local_vars = locals()
    def helper(fixture_name):
        return local_vars.get(fixture_name)
    return helper

def test_a(super_fixture):
    # getting fixture1
    assert super_fixture("fixture1")