I am using Pytest. I have a function with several arguments and I am using a parametrized test to check different combinations of those arguments. But I would like to be able to not have all arguments in all test cases. Is there a way that I can indicate in the tuples where I define the test cases that some arguments are empty?
Here is a minimal example. In the case below I would like to have another test wher I pass only the first argument, e.g. 1 and the expected result 5 (1+4).
I have tried (1,,5) and (1,None,5) but none seems to work.
The example below is a very simplified case, I could probably have a separate test function. But in a general case with lots of arguments it would be quite helpful to be able to parametrize the function to test not passing a each argument.
import pytest
def foo(arg1, arg2=4):
return arg1+arg2
@pytest.mark.parametrize("first,second,expected_result",[(1,2,3),(2,3,5)])
def test(first,second,expected_result):
assert foo(first,second) == expected_result
A simple approach is:
@pytest.mark.parametrize(
"first,second,expected_result", [(1, 2, 3), (2, 3, 5), (1, None, 5)]
)
def test(first, second, expected_result):
if second is None:
actual = foo(first)
else:
actual = foo(first, second)
assert actual == expected_result
A more generic approach, which can be used to test any function with any number of parameters:
@pytest.mark.parametrize(
"args,kwargs,expected_result",
[
((1, 2), {}, 3),
((2, 3), {}, 5),
((1,), {}, 5),
],
)
def test(args, kwargs, expected_result):
actual = foo(*args, **kwargs)
assert actual == expected_result