简体   繁体   中英

pyhamcrest - Compare two list

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?

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.

我不知道has_items函数,但你可以使用这样的东西吗?

assertTrue(all(item in expected_list_of_items for item in actual_list_of_items))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM