Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using parametrize for keyword arguments in pytest

Tags:

python

pytest

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
like image 920
d_j Avatar asked May 02 '14 00:05

d_j


People also ask

Can I use fixture in parametrize pytest?

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.

Which annotation is used for parameterization in pytest?

you can put @pytest. mark. parametrize style parametrization on the test functions to parametrize input/output values as well.

What is Conftest PY in pytest?

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.


1 Answers

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
like image 157
Matthew Trevor Avatar answered Sep 23 '22 02:09

Matthew Trevor