Reputation: 13108
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.
Upvotes: 1
Views: 3510
Reputation: 406
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
Upvotes: 1
Reputation: 49330
Assuming the elements are hashable and unique, just use sets:
set(l) == set(f(l))
If those conditions don't apply, sort them:
sorted(l) == sorted(f(l))
And there's collections.Counter
, if the elements are hashable and non-unique:
import collections
collections.Counter(l) == collections.Counter(f(l))
Upvotes: 4
Reputation: 406
You might want to use the set operation difference:
list_to_test = [1,2,3,4,5,5,4,3,2,1,2]
wanted_elements = [1,2,3]
d = set(list_to_test).difference(set(wanted_elements))
print d
set([4, 5])
and so eventually you would assert that len(d) == 0.
Upvotes: 0
Reputation: 61042
If order doesn't matter, sort both lists and check their equality
assert sorted(exampleOutput) == sorted(func(inputList))
Upvotes: 1