Home > OS >  assertEqual vs assertSetEqulal in unittest
assertEqual vs assertSetEqulal in unittest

Time:01-27

Is there a difference between assertEquals and assertSetEqual in the python unittest.TestCase for assertion of sets or frozensets?

And if there is not, why are there assertSetEqual?

also for this situation we can use assertCountEqual and assertSequenceEqual!

.
.
.

self.assertEqual({1, 2, 3}, {1, 2, 3})
self.assertSetEqual({1, 2, 3}, {1, 2, 3})

.
.
.

CodePudding user response:

The type-specific calls give type-specific error messages when they fail. For instance, for a set it will list the elements found in each set but not found in the other.

The docs note that assertEqual will call the type-specific test if both args are of the exact same type and if there is a type-specific test - thus, for two sets assertEqual will call assertSetEqual and therefore show the more helpful error message. However, it doesn't do this if both one arg is a set and the other is a frozenset. This may not come up often, but it's one case in which you might call assertSetEqual directly.

>>> TestCase().assertEqual({1, 2, 3}, frozenset((2, 1)))
Traceback (most recent call last):
...
AssertionError: {1, 2, 3} != frozenset({1, 2})
>>> TestCase().assertSetEqual({1, 2, 3}, frozenset((2, 1)))
Traceback (most recent call last):
 ...
AssertionError: Items in the first set but not the second:
3
  • Related