I'm learning pytest and I'm trying to use pytest.mark.parametrize for keyword arguments.
This is the simple example without pytest.mark.parametrize:
G = 10
H = 2
def f(g=G, h=H):
return 5 * g + h
def test_f1():
assert f(h=4) == 54
assert f(g=20) == 102
And this is one of my unsuccessful trails using pytest.mark.parametrize. It doesn't work but it helps to understand what I would like to achieve:
import pytest
G = 10
H = 2
def f(g=G, h=H):
return 5 * g + h
@pytest.mark.parametrize("arg, expected", [
("h=4", 54),
("g=20", 102),
])
def test_f2(arg, expected):
assert f(eval(arg)) == expected
You can use such a simple parametrized fixture for more complex fixtures by combining the param value with some kind of factory. You can also alias the call to parametrize: numbers = pytest.
you can put @pytest. mark. parametrize style parametrization on the test functions to parametrize input/output values as well.
conftest.py is where you setup test configurations and store the testcases that are used by test functions. The configurations and the testcases are called fixture in pytest.
The function f
accepts keyword arguments, so you need to assign your test parameters to keywords. Luckily, Python provides a very handy way of passing keyword arguments to a function...the dictionary:
d = {'h': 4}
f(**d)
The **
prefix before d
will "unpack" the dictionary, passing each key/value pair as a keyword argument to the function.
For your pytest
example, this means you just need to replace the string parameter with a dictionary, and the eval
in test_f2
with the keyword unpacker:
@pytest.mark.parametrize("arg,expected", [
({'h':4}, 54),
({'g':20}, 102),
])
def test_f2(arg, expected):
assert f(**arg) == expected
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With