1

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?

k10
  • 62
  • 1
  • 7

2 Answers2

3

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.

gold_cy
  • 13,648
  • 3
  • 23
  • 45
  • Thanks! I tried that earlier but it doesn't work: ```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)) E AssertionError: E Expected: (a sequence containing <['a']>) E but: a sequence containing <['a']> was <['a', 'b']>``` – k10 Dec 30 '19 at 23:29
  • you're missing the `*`, please copy my answer directly how it is, the issue is that you aren't _unpacking_ the list, note the `*` directly in front of `expected_list_of_items` – gold_cy Dec 30 '19 at 23:32
  • Oh ok! Thanks a lot @aws_apprentice. I read the document again and now i got what you were trying to say above. This helped a lot – k10 Dec 30 '19 at 23:36
0

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))
marcos
  • 4,473
  • 1
  • 10
  • 24
  • Thanks Marcos! I do have a work around but i want to use pyhamcrest matchers and hence the question. Any help would be appreciated – k10 Dec 30 '19 at 23:16