python - 如何通过字符串访问 pytest fixture?

标签 python pytest

pytest fixtures 可以通过将它们作为参数传递给其他 fixtures 来工作:

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

现在我有多个不同的 fixture 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')

这可以通过某种方式完成吗?或者我是否必须为每个原始装置编写三个包装器装置,一遍又一遍地重复相同的代码?

最佳答案

要通过字符串获取 fixture ,您可以在测试函数或另一个 fixture 中使用 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

关于python - 如何通过字符串访问 pytest fixture?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24140639/

相关文章:

python - python 中的 str(len(x))

python - 从 nd 数组中的 bin 索引查找封闭网格点的索引

python - 是否可以为每个模型自动创建 View 集和序列化器?

python - 如何使用 pytest fixtures 和 django 在 unittest 中创建类似于 "setUp"的方法

python - 为什么 pytest.mark.parametrize 不适用于 pytest 中的类?

python - 在测试文件中使用一个 @allure.epic 装饰器

python - 如何从 tf.data.Dataset.zip((images, labels)) 获取两个 tf.dataset

python - Windows 上多个 Python 安装的奇怪问题

xml - 无论如何要指定 .coveragerc 上的报告类型?

python - 在 pytest 中模拟模块导入