pyhamcrest - Compare two list

942 views Asked by At

I've just started learning python. Currently writing a unit test to assert if the elements in the expected list is present in the actual list

def test_compare_list_of_items():
    actual_list_of_items = ['a','b']
    expected_list_of_items = ['a']

    assert_that(actual_list_of_items, has_item(has_items(expected_list_of_items)))  

but i'm getting errors like

E    Expected: a sequence containing (a sequence containing <['a']>)
E         but: was <['a', 'b']>

How and what sequence matcher should i use in order to assert if item 'a' in the expected list is present in the actual list?

2

There are 2 answers

1
marcos On

I don't know about has_items function, but can you just use something like this?

assertTrue(all(item in expected_list_of_items for item in actual_list_of_items))
3
gold_cy On

You are using has_item when you should only be using has_items. According to the docs this takes multiple matchers which is what you want. Your function then becomes

def test_compare_list_of_items():
    actual_list_of_items = ['a','b']
    expected_list_of_items = ['a']

    assert_that(actual_list_of_items, has_items(*expected_list_of_items))

We use iterable unpacking for the list to feed as the arguments and now when you run it, it shouldn't error out.