Make42 Make42 - 2 months ago 15
Python Question

How to assert that exactly the expected elements are in a list?

I want to unit-test a function that takes a list and returns (a very different) list. I know what elements I expect, but I do not know in what order they will me in the returned list. How can I assert that exactly those elements are in the list an no other? I would like to do this using py.test. Also: I expect to have multiple duplicates.

scf scf

If I understand you correctly, you want to test if list A and list B have the exact same elements, including duplicates but disregarding order.
This calls for use of Counters:

from collections import Counter
wanted_elements = [1, 1, 2, 3, 4, 4, 4, 4]
input_list = [1, 2, 1, 4, 4, 4, 4, 3]
c1 = Counter(wanted_elements)
c2 = Counter(input_list)
assert c1 == c2