Python Unittest Assertcountequal Uses 'is' Instead Of '=='?
Solution 1:
you can look for yourself how the comparison is done:
- generate a list from each iterable
- use a collections.Counter to count the objects - works only for hashable elements
- if the elements are not hashable, compare them directly
as your Intersection
s are objects, they are hashable per default, but if you don't provide a suitable hash function (which you should do if you provide comparison methods) they will be considered different.
so, does your Intersection
class fullfill the hash contract?
Solution 2:
When working with unordered lists I typically use this pattern (if you can)
In a class that extends TestCase
self.assertTrue(set(a) == set(b), 'The lists are not equal.')
I use set
in this case because it allows for the comparison of unordered groups BUT if a has two objects that are the same the comparison should fail but won't in that case you need to sort both lists and then compare.
I try to stay away from is
except when comparing it to None
because it relies on an instance like this
Here is an example
In [2]: a = [0,1,2]
In [3]: b = [0,2,1,0]
In [4]: set(a) ==set(b)
Out[4]: TrueIn [5]: c = [2,0,1]
In [6]: a.sort() == c.sort()
Out[6]: True
For a more complex object or class you may want to try something like
self.assertTrue(a==b)
Or you could write your own compare method
defcompare_complex(*args):
for attr in ...
ifgetattr(args[0],attr) != getattr(args[1],attr): returnFalsereturnTrue
I've used something similar in the past when analyzing two Classes that used attributes to store important values, or Numpy instances
Solution 3:
assertCountEqual()
uses collections.Counter
if your elements are hashable. In Python 3 if your class defines its own __eq__
then the default __hash__
is suppressed.
You have your own __eq__
-- define a __hash__
(it must be equal where __eq__
is equal) and you should be okay.
Post a Comment for "Python Unittest Assertcountequal Uses 'is' Instead Of '=='?"