22

我想知道 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 方法。

4

2 回答 2

35

assertQuerysetEqual接受一个queryset,一个值列表和一个在查询集transform上调用的可调用对象,以将其转换为与值列表相当的东西。默认情况下,这个可调用对象是repr. 这有点烦人,因为它实际上并没有比较两个查询集,但大多数情况下的简单解决方法是使用map(repr, your_second_queryset)值列表。这在 django 自版本 1.3 开始记录

于 2013-01-07T02:20:03.967 回答
20

试试这个:

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

这有点奇怪和无证;但是,这应该对你有用。

于 2012-09-25T20:35:30.047 回答