Lopez
Lopez

Reputation: 472

Pytest - How to pass defaults while testing

Suppose that I have a function as follows

def add_vals(a, b=1, c=2):
    result = a + b + c
    return result

Let the test data be as follows

test_data = [(1, 2, 3), (6),
(2, ,4), (7)
]

For the second test I want the function to use default value for b i.e. b=1 How can I do that?

To test I am using the following function.

@pytest.mark.parametrize("inp,expected", testdata)
def test_add_vals(inp, expected):
    res = historical_returns(*inp)

    assert res == expected

Edit

Based on the suggestion using **kwargs to pass default parameters. Having syntax issue can't figure out the error. Below is the code

def add_vals(a, b=1, c=2):
    result = a + b + c
    return result


testdata = [(1, 'b'=9, 12),
            (2, 'c'=5, 8)
            ]


@pytest.mark.parametrize("args, kwargs, expected", testdata)
def test_add_vals(args, kwargs, expected):
    for key, value in kwargs.items():
        res = add_vals(*args, key=value)

    assert res == expected

Below is the error

E       testdata = [((1), ('b' = 1), (6)),
E                              ^
E   SyntaxError: invalid syntax

Upvotes: 0

Views: 768

Answers (1)

mad
mad

Reputation: 400

As has been suggested, you can use a combination of a list or arguments (args) and a dict of keyword arguments (kwargs) like this:

import pytest


def add_vals(a, b=1, c=2):
    result = a + b + c
    return result


testdata = [([1], {"b": 9}, 12),
            ([2], {"c": 5}, 8),
            ([0, 1, 2], {}, 3),
            ([], {"c": 3, "b": -3, "a": 0}, 0)
            ]


@pytest.mark.parametrize("args, kwargs, expected", testdata)
def test_add_vals(args, kwargs, expected):
    res = add_vals(*args, **kwargs)
    assert res == expected

Further reading: https://book.pythontips.com/en/latest/args_and_kwargs.html

Upvotes: 1

Related Questions