How to write a test for a function with optional arguments

Viewed 3139

I want to test function calls with optional arguments.

Here is my code:

list_get()
list_get(key, "city", 0)
list_get(key, 'contact_no', 2, {}, policy)
list_get(key, "contact_no", 0)
list_get(key, "contact_no", 1, {}, policy, "")
list_get(key, "contact_no", 0, 888)

I am not able to parametrize it due to optional arguments, so I have written separate test functions for each api call in pytest.
I believe there should be better way of testing this one.

4 Answers

For future readers who come to this question trying to set up @parameterized tests to generate a Cartesian set of parameters AND sometimes do not want to pass a given parameter at all (if optional), then using a filter on None values will help

def function_under_test(foo="foo-default", bar="bar-default"):
    print([locals()[arg] for arg in inspect.getargspec(function_under_test).args])


@pytest.mark.parametrize("foo", [None, 1, 2])
@pytest.mark.parametrize("bar", [None, "a", "b"])
def test_optional_params(foo, bar):
    args = locals()
    filtered = {k: v for k, v in args.items() if v is not None}
    function_under_test(**filtered)  # <-- Notice the double star

Sample run:

PASSED   [ 11%]['foo-default', 'bar-default']
PASSED   [ 22%][1, 'bar-default']
PASSED   [ 33%][2, 'bar-default']
PASSED   [ 44%]['foo-default', 'a']
PASSED   [ 55%][1, 'a']
PASSED   [ 66%][2, 'a']
PASSED   [ 77%]['foo-default', 'b']
PASSED   [ 88%][1, 'b']
PASSED   [100%][2, 'b']
Related