如何使用可选参数为函数编写测试

Pav*_*pta 5 python optional-parameters optional-arguments pytest

我想用可选参数测试函数调用.

这是我的代码:

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)
Run Code Online (Sandbox Code Playgroud)

由于可选参数,我无法对其进行参数化,因此我为每个api调用编写了单独的测试函数pytest.
我相信应该有更好的方法来测试这个.

Eze*_*uns 7

您可以使用*运营商:

@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
Run Code Online (Sandbox Code Playgroud)