Django 1.4 - assertQuerysetEqual - how to use method
Asked Answered
M

2

22

I'm wondering how the TestCase.assertQuerysetEqual method works. I tried it in different ways, each of them leading me to another error message.

#create a backup of all records in the tree
tree_record_backup = list(Tree.objects.all())

#do some updates on another table, which should not affect the tree table if everything goes wrong

#check if list of tree records did not changed
tree_record_qs = Tree.objects.all()
#Number1:
self.assertQuerysetEqual(tree_record_qs,[repr(tree_record_backup)])
#Number2:
self.assertQuerysetEqual(tree_record_qs,tree_record_backup)

Error Message for Number1:

First list contains 21 additional elements.
First extra element 1:
node.pk: 2 - node: node2 - pk: 2 - level: 0 - ancestor: 2

Error Message for Number 2:

AssertionError: Lists differ: ['<Tree: node.pk: 1 - node: ro... != [<Tree: node.pk: 1 - node: roo...

First differing element 0:
<Tree: node.pk: 1 - node: root - pk: 1 - level: 0 - ancestor: 1>
node.pk: 1 - node: root - pk: 1 - level: 0 - ancestor: 1

Thanks for hints how to use the assertQuerysetEqual method correctly.

Magyar answered 23/7, 2012 at 10:41 Comment(0)
E
22

try this:

self.assertQuerysetEqual(
    tree_record_qs,
    [repr(r) for r in tree_record_backup]
)

it's a bit weird and undocumented; but, that should work for you.

Enterogastrone answered 25/9, 2012 at 20:35 Comment(0)
C
36

assertQuerysetEqual takes a queryset, a list of values and a transform callable which is called on the queryset to convert it into something comparable to the list of values. By default this callable is repr. This is kind of irritating since it doesn't actually compare two querysets, but the easy fix for most cases is using map(repr, your_second_queryset) for the list of values. This is documented in django since version 1.3.

Controversy answered 7/1, 2013 at 2:20 Comment(1)
Using python 3 + django 1.5 you should to use map(repr, your_second_queryset) because assertQuerysetEqual converts queryset to a list.Frons
E
22

try this:

self.assertQuerysetEqual(
    tree_record_qs,
    [repr(r) for r in tree_record_backup]
)

it's a bit weird and undocumented; but, that should work for you.

Enterogastrone answered 25/9, 2012 at 20:35 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.