是否可以从fixture request中检索其他请求的fixture?

2024-03-29 02:16:28 发布

您现在位置:Python中文网/ 问答频道 /正文

例如:

@pytest.fixture()
def connection():
    return make_connection()


@pytest.fixture()
def database(connection):
    connection = request.fixtures['connection']
    return create_database(connection)


@pytest.fixture()
def table(request):
    database = request.fixtures['database']
    return create_table(database)


@pytest.mark.usefixtures('database')
def test_whatever(connection, table):
    insert_some_data(table)
    connection.execute(...)
    ...

我能用Pytest的当前版本做这个吗?用这种非层次化的方式使fixture依赖于其他fixture?你知道吗


Tags: testmakereturnpytestrequestdefcreatetable
1条回答
网友
1楼 · 发布于 2024-03-29 02:16:28

你可以这样做:

@pytest.fixture()
def fixture1():
    return 'fixture1'


@pytest.fixture()
def fixture2(request):
    if 'fixture1' in request._funcargs:
        # fixture1 was requested earlier
        # but most likely you don't need that check because getfuncargvalue always works
        fixture1_instance = request.getfuncargvalue('fixture1')
    return do_stuff(fixture1_instance)


def test_whatever(fixture1, fixture2):
    result = do_some_stuff(fixture1)
    assert result.supermethod(fixture2)

相关问题 更多 >