Django 1.4 - assertQuerysetEqual - 如何使用方法

时间:2012-07-23 10:41:56

标签: django testing django-queryset

我想知道TestCase.assertQuerysetEqual方法是如何工作的。我以不同的方式尝试了它,每个都引导我发出另一条错误信息。

#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)

Number1的错误消息:

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

数字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

感谢您提示如何正确使用assertQuerysetEqual方法。

2 个答案:

答案 0 :(得分:31)

assertQuerysetEqual获取queryset值列表transform可调用对象,在查询集上调用它以将其转换为与列表相当的值价值观默认情况下,此可调用项为repr。这有点令人恼火,因为它实际上并不比较两个查询集,但大多数情况下的简单修复是使用map(repr, your_second_queryset)作为值列表。这是documented in django since version 1.3

答案 1 :(得分:14)

试试这个:

self.assertQuerysetEqual(
    tree_record_qs,
    [repr(r) for r in tree_record_backup]
)
它有点奇怪而且没有记录;但是,这应该适合你。