如何在测试运行之外使用 pytest 夹具?

dhi*_*ill 7 python database fixtures pytest

我有一组装置来设置相当大的数据集。设置结果存储在数据库 ( scope=function) 中,用于报告呈现回归测试。固定装置没有参数化,所以只有一种设置,但回归测试有一些相互依赖的固定装置作为参数,无需额外查询即可访问对象。pytest 使用内存数据库并在每次测试后回滚,因此完成测试后,设置不可用。

我想在 pytest 之外使用该数据库设置进行演示和前端自动化测试。

如何在开发数据库中获取pytest夹具的结果?

一个没有细节的例子,展示夹具的结构:

@pytest.fixture
def customer():
    return mommy.make(Customer, name='Customer LTD')

@pytest.fixture(autouse=True)
def inventory_types(customer):
    return seeder.seed_inventory_types('A,B,C', customer=customer)


@pytest.fixture(autouse=True)
def inventory(
    good,
    bad,
    ugly,
    common,
    ...
):
    return

@pytest.fixture
def good(customer, patterns):
    vehicle = mommy.make(
        Inventory, 
        name='Good', 
        type=inventory_types.A, 
        customer=customer
    )

@pytest.fixture
def bad(customer, patterns):
    return make(
        Inventory, 
        name='Bad', 
        type=inventory_types.A,  
        customer=customer
    )

@pytest.fixture
def ugly(customer, patterns):
    return mommy.make(
        Inventory, 
        name='Ugly', 
        type=inventory_types.B, 
        customer=customer
    )

@pytest.fixture
def common(customer, patterns):
    return mommy.make(
        Inventory, 
        name='Common', 
        type=inventory_types.C, 
        customer=customer
    )


def test(good, customer):
    assert good in customer.inventory
Run Code Online (Sandbox Code Playgroud)

ded*_*ed7 4

看来您可以像这样调用由固定装饰器包装的函数customer.__pytest_wrapped__.obj():显然这不是公共 API,因此可能会发生变化。

看起来另一种选择是以不同的方式构建固定装置代码,以便它也公开正常的函数。请参阅name此处提到的参数:https ://docs.pytest.org/en/stable/deprecations.html#calling-fixtures-directly