Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parameterize all key/value pairs in a dictionary mapping of key and list of values using pytest?

Tags:

python

pytest

I have a dictionary containing a mapping of possible valid values. How can I test that my validation function works by using this map? I can't figure out how to properly use the @parameterize option in pytest for this map.

My first attempt was this:

TEST_MAP = {
    'key1': ['val1', 'val2', 'val3'],
    'key2': ['val1', 'val2', 'val4', 'val5'],
    'key3': ['val2', 'val4'],
    'key4': ['val3', 'val4', 'val6'],
}

@pytest.mark.parametrize("map", TEST_MAP)
def test_map(self, map):
    ...
    validate()
    assert ...

The problem with this is that it's only iterating over the keys. I also want to iterate over the values for each key. I need the key/value combinations to be tested.

How can I adjust my paramertization of this test case to test call key/value pairs in my map?

I do not want to iterate over the values within the test for each key. I want each key/value to be it's own unique test.

like image 734
NewGuy Avatar asked Oct 19 '25 09:10

NewGuy


2 Answers

Updated based on comment to use a generator to get the required combinations:

def get_items():
TEST_MAP = {
    'key1': ['val1', 'val2', 'val3'],
    'key2': ['val1', 'val2', 'val4', 'val5'],
    'key3': ['val2', 'val4'],
    'key4': ['val3', 'val4', 'val6'],
}
for key, value in TEST_MAP.items():
    for val in value:
        yield key, val


@pytest.mark.parametrize("items", get_items())
def test_map(items):
    key, value = items
    print(key, value)
    assert len(value) > 1
like image 55
Amit Verma Avatar answered Oct 22 '25 00:10

Amit Verma


Piggybacking on what Amit wrote, you don't need a separate function to get the items from the dictionary. @pytest.mark.parametrize("map", TEST_MAP.items()) would be fine. Or you could use print(TEST_MAP.items()) within your test_map function.

The output I received was formated like this when I ran it:

'key1', ['val1', 'val2', 'val3']
'key2', ['val1', 'val2', 'val4', 'val5']
'key3', ['val2', 'val4']
'key4', ['val3', 'val4', 'val6']
like image 42
Corbin Avatar answered Oct 21 '25 22:10

Corbin