pythonpytest

Parameterize all key/value pairs in a dictionary mapping of key and list of values using 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.


Solution

  • 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