Reputation: 9037
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
Upvotes: 3
Views: 8559
Reputation: 752
Below is a full example that worked for me. It was quite hard to figure out the required type of the params
arg, as well as which type request
takes in which situation (it changes depending on what you pass to pytest.mark.parametrize()
, and it's also different if you don't use it, ie. use default params).
@pytest.fixture(params=[({'arg1': 1}, {'arg2': 2})])
def my_fixture(request):
if isinstance(request.param, tuple):
arg1 = request.param[0]["arg1"]
arg2 = request.param[1]["arg2"]
else:
arg1 = request.param["arg1"]
arg2 = request.param["arg2"]
return arg1 + arg2
This way (and this way only), I was able to use both the default params, as well as specify overrides when needed. For example:
a) no overrides
def my_test(my_fixture):
print(my_fixture)
# >>> 3
b) with overrides
@pytest.mark.parametrize(
"my_fixture",
[
(
{
"arg1": 3,
"arg2": 4,
}
)
],
indirect=True,
)
def my_test(my_fixture):
print(my_fixture)
# >>> 5
Upvotes: 0
Reputation: 41
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']
Upvotes: 4
Reputation: 493
None
is the default result
request.param.get('argA', None)
So, you can just:
argA = request.param.get('argA', 'default value for argA')
Upvotes: 2