Skip to main content
 首页 » 编程设计

python之为 py.test fixture 函数提供默认参数值

2025年01月19日10tuyile006

是否有更好的方法为参数 pytest.fixture 函数提供默认值?

我有几个测试用例需要在测试用例之前运行 fixture_func ,如果没有提供它们,我想为 fixture 中的参数使用默认值。我能想出的唯一代码如下。我有更好的方法吗?

@pytest.fixture(scope="function") 
def fixture_func(self, request): 
    argA = request.param['argA'] if request.param.get('argA', None) else 'default value for argA' 
    argB = request.param['argB'] if request.param.get('argB', None) else 'default value for argB' 
    # do something with fixture 
 
@pytest.mark.parametrize('fixture_func', [dict(argA='argA')], indirect=['fixture_func']) 
def test_case_1(self, fixture_func): 
    #do something under testcase 
    pass 
 
@pytest.mark.parametrize('fixture_func', [dict()], indirect=['fixture_func']) 
def test_case_2(self, fixture_func): 
    #do something under testcase 
    pass 

我想用作

def test_case_3(self, fixture_func): 
    #do something under testcase 
    pass 

请您参考如下方法:

None 是默认结果

request.param.get('argA', None)  

所以,你可以:

argA = request.param.get('argA', 'default value for argA')