Search code examples
pythonpytest

How to compare and test specific key in list of dictionaries using Python and Pytest


I have a list of dictionary items and i want to compare specific keys in the list of dictionaries.I am trying the following code and it is working fine, but i see duplication of code . Is there anyway i can optimize the code .

My data structure is as follows

[{
        "title": "x86_64",
        "type": "info",
        "list_type": ["2016-9131", "2016-9147", "2016-9444"]

    }, {
        "title": "x_64",
        "type": "info",
        "list_type": ["2036-9131", "2026-9147", "2046-9444"],
    }
]

python code below

import json,pytest

with open('expected_resuts.json') as expected_result:
    expected_results=json.load(expected_result)

with open('actual_results.json') as actual_result:
    actual_results=json.load(actual_result)

expected_title_list=[]
expected_title_list=[]
expected_name=[]
actual_name=[]

for item in expected_results:
    expected_title_list.append(item['title'])

for item in actual_results:
    expected_title_list.append(item['title'])

for item in expected_results:
    expected_name.append(item['type'])

for item in actual_results:
    actual_name.append(item['type'])


def test_title_list():
    assert expected_title_list==expected_title_list

def test_name():
    assert actual_name==expected_name

Solution

  • You could improve it quite a lot just by using list comprehensions. You could also move variables like expected_vpk_list inside the test that needs it (to avoid creating too many global variables). Example below:

    import json, pytest
    
    with open('expected_results.json') as expected_result:
        expected_results = json.load(expected_result)
    
    with open('actual_results.json') as actual_result:
        actual_results = json.load(actual_result)
    
    def test_vpk_list():
        expected_vpk_list = [result['vpk'] for result in expected_results]
        actual_vpk_list = [result['vpk'] for result in actual_results]
        assert actual_vpk_list == expected_vpk_list
    
    def test_patch_title():
        expected_patch_title = [result['patchTitle'] for result in expected_results]
        actual_patch_title = [result['patchTitle'] for result in actual_results]
        assert actual_patch_title == expected_patch_title
    

    UPDATE: These tests can be merged by using parametrize as shown below:

    @pytest.mark.parametrize('key', [
        'vpk',
        'patchTitle',
    ])
    def test_key_from_results(key):
        expected_values = [result[key] for result in expected_results]
        actual_values = [result[key] for result in actual_results]
        assert expected_values == actual_values