【问题标题】:Provide default argument value for py.test fixture function为 py.test 夹具函数提供默认参数值
【发布时间】:2017-12-11 17:41:00
【问题描述】:

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

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

@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

【问题讨论】:

    标签: python pytest


    【解决方案1】:

    None 是默认结果

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

    所以,你可以:

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

    【讨论】:

    • 这样,如果我使用test_case_3(self, fixture_func):,错误将被打印为 no param on request
    • 是的,但是如果我使用 test_case_3(self, fixture_func) 而不是提供空的 dict() 作为参数,attributeError 会抛出,因为 SubRequest 对象没有属性参数
    【解决方案2】:

    为您的夹具添加参数:

    @pytest.fixture(scope='function', params=[{'arg1': 'default'}, {'arg2': 'default'}])
    def my_fixture(request):
        return request.param['arg1'] + request.param['arg1']
    

    【讨论】:

      猜你喜欢
      • 2019-02-02
      • 2018-07-08
      • 2014-02-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-02-23
      相关资源
      最近更新 更多