3

Is there a better way for me to provide default value for argument pytest.fixture function?

I have a couple of testcases that requires to run fixture_func before testcase and I would like to use default value for argument in fixture if none of them is provided. The only code I can come up with is as follows. Any better way for me to do it?

@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

i wna to use as

def test_case_3(self, fixture_func):
    #do something under testcase
    pass
gmauch
  • 1,316
  • 4
  • 25
  • 39
jacobcan118
  • 7,797
  • 12
  • 50
  • 95

2 Answers2

4

None is the default result

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

So, you can just:

argA = request.param.get('argA', 'default value for argA')
Latrova
  • 468
  • 6
  • 15
  • in that way if i use ```test_case_3(self, fixture_func):```, error will be printed out as no param on request – jacobcan118 Dec 11 '17 at 17:55
  • yes, but if i use like ```test_case_3(self, fixture_func)``` instead of provide empty dict() as param attributeError throw out as SubRequest object has no attribute param – jacobcan118 Dec 11 '17 at 18:00
3

Add params to your fixture:

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