Pytest-drf unit tests and dict_items assert

There is a code in a legacy project using pytest-drf and I'm new in Python and tests, I would like to know what an assert checking two dict_items is comparing, but could not find out neither other examples nor explanations about it. Here's the code:

class TestPhones(Base)
    list_url = lambda_fixture(lambda: url_for('phones-list'))
    detail_url = lambda_fixture(
        lambda old_phone: url_for('phones-detail',

    class TestCreate(VerbTests.Create):
    data = phone_json
    def test_returned_json(self, data, json, model):
        expected = data.items()
        actual = json.items()
        assert expected <= actual

What is this assert code doing?

I couldn't understand why it's being used the lower symbol '<' for this assert, I see that it's comparing dict_items content in 'expected' and 'actual' received from the API in json format, but couldn't find what's going on.

1 answer

  • answered 2022-01-14 18:39 Fran&#231;ois B.

    assert <condition> is used to check that an expected condition is fulfilled. For more information on the testing and especially on assert, you can have a look on Pytest documentation

    While comparing the dictionaries, dict1<=dict2 returns True if dict1 is contained in dict2.

    Here a code which show the different cases:

    my_dict = {"test1":"test_val1", "test2":"test_val2", "test3":"test_val3", "test4":"test_val4", "test5":"test_val5"}
    for my_tuple in [
        (["test1", "test2"], ["test1", "test5"]),
        (["test1", "test2"], ["test1", "test2"]),
        (["test1", "test2"], ["test1"]),
        (["test1"], ["test1", "test5"]),
        my_dict1 = {}
        my_dict2 = {}
        for key in my_tuple[0]:
            my_dict1[key] = my_dict[key]
        for key in my_tuple[1]:
            my_dict2[key] = my_dict[key]
        print(my_dict1.items() <= my_dict2.items(), "---", my_dict1, "<=", my_dict2)

    The returned output

    False --- {'test1': 'test_val1', 'test2': 'test_val2'} <= {'test1': 'test_val1', 'test5': 'test_val5'} # not contained
    True --- {'test1': 'test_val1', 'test2': 'test_val2'} <= {'test1': 'test_val1', 'test2': 'test_val2'} # equal
    False --- {'test1': 'test_val1', 'test2': 'test_val2'} <= {'test1': 'test_val1'} # not contained
    True --- {'test1': 'test_val1'} <= {'test1': 'test_val1', 'test5': 'test_val5'} # contained

How many English words
do you know?
Test your English vocabulary size, and measure
how many words do you know
Online Test
Powered by Examplum