pythonpytestoptional-parametersoptional-arguments

How to write a test for a function with optional arguments


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.


Solution

  • You may be able to use the * operator:

    @pytest.mark.parametrize('args,expected', [
        ([], expVal0),
        ([key, "city", 0], expVal1),
        ([key, 'contact_no', 2, {}, policy], expVal2)
        ([key, "contact_no", 0], expVal3)
        ([key, "contact_no", 1, {}, policy, ""], expVal4)
        ([key, "contact_no", 0, 888], expVal5)
    ])
    def test_list_get(args, expected):
        assert list_get(*args) == expected