Search code examples
pythonpython-unittest

Test function with default argument


Lets say I wish to test this function:

def get_user(user_id, adults_only=False):
    pass

where the implementation is not shown.

I would like to test this using parameterised expand, something like this:

@paramaterized.expand([(True, "none"),(False, "child")])
def test_get_child(self, adults_only, expected):
    child = self.child
    actual = get_user(child.id, adults_only)
    assert expected == actual

However, I am not testing the default argument. And have to add a second test to test this:

def test_get_child_default(self):
    child = self.child
    actual = get_user(child.id)
    assert "child" == actual

It would be nice to be able to combine the two tests into one. Is it possible to do this using python and the unittest framework?


Solution

  • I guess the reason for this additional test is to make sure that the default value does not change... There is no direct support for this, as far as I know, but you can handle this yourself. You can do something like this (admittedly not very nice):

    @paramaterized.expand([(True, "none"), (False, "child"), (None, "child")])
    def test_get_child(self, adults_only, expected):
        child = self.child
        kwargs = {"adults_only": adults_only} if adults_only is not None else {}
        actual = get_user(child.id, **kwargs)
        assert expected == actual
    

    Basically you use a sentinel value (None) for the default parameter and construct the kwargs yourself accordingly.