首页 > 解决方案 > 如何动态选择 pytest 夹具?

问题描述

import pytest


@pytest.fixture()
def fixture1(fixture_a):
    print('In fixture 1')
    <do>
    step a
    step b
    <end>
    return <some object1> 



@pytest.fixture()
def fixture2(fixture_b):
    print('In fixture 2')
    <do>
    step x
    step y
    <end>
    return <some object2> 


def decide():
    a = 1
    if a == 1:
        return fixture1: Object1
    else:
        return fixture2: Object2


def test_me():
    res = decide()
    assert res == Object

我有两个夹具 arg1 和 arg2,现在我想将其中一个夹具返回给测试,但这必须是基于条件的动态选择。这个怎么做?

更新:夹具 arg1 和 arg2 有一个依赖链,它们被用于不同的测试。

此外,决定功能需要在多个测试中使用。

标签: pythonpython-3.xpytest

解决方案


您可以将arg1and传递arg2test并测试条件本身。

def decide():
    a = 1
    if a == 1:
        return 1
    else:
        return 2

def test_me(fixture1, fixture2):
    arg = decide()
    if arg == 1:
        assert fixture1 == 1
    else:
        assert fixture2 == 2

推荐阅读