[Solved]-Assert that two lists of objects are equal in django testing

17👍

To test two lists

use: assertSequenceEqual

Because, in this case, tags = Tag.objects.all() generates a django.db.models.query.QuerySet where as tag_list.append(...) creates a list.

Other options in different situations are:

  • assertListEqual(a, b)
  • assertTupleEqual(a, b)
  • assertSetEqual(a, b)
  • assertDictEqual(a, b)

Why <Tag: a> is not <Tag: a>

The tags are the same model, but they’ve been loaded into different places in memory

for tag_set in zip(tags, tag_list):
    print "\n"
    print tag_set[0].slug + "'s pk is %s" % tag_set[0].pk + ' id is: ' + id(tag_set[0])
    print tag_set[1].slug + "'s pk is %s" % tag_set[1].pk + ' id is: ' + id(tag_set[1])
    print "\n"
    self.assertIs(*tag_set)

returns

.......

a's pk is 1 id is: 4522000208
a's pk is 1 id is: 4522228112

F.

Therefore, is will retrun False

👤Ben

3👍

I think what you want to test is if the tags created have the same slugs as those in your test list.

For that, fetch only the slug as a list with values_list, and then compare that:

assertEqual(Tag.objects.values_list('slug', flat=True), ['a','b','c'])

I have to say, this isn’t quite a useful test because you are checking django orm functionality, which has already been tested quite well.

Your tests should check for specifics of your own application.

Leave a comment