我正在尝试测试我的Django视图.此视图将QuerySet传递给模板:
def merchant_home(request, slug):
merchant = Merchant.objects.get(slug=slug)
product_list = merchant.products.all()
return render_to_response('merchant_home.html',
{'merchant': merchant,
'product_list': product_list},
context_instance=RequestContext(request))
Run Code Online (Sandbox Code Playgroud)
并测试:
def test(self):
"Merchant home view should send merchant and merchant products to the template"
merchant = Merchant.objects.create(name='test merchant')
product = Product.objects.create(name='test product', price=100.00)
merchant.products.add(product)
test_client = Client()
response = test_client.get('/' + merchant.slug)
# self.assertListEqual(response.context['product_list'], merchant.products.all())
self.assertQuerysetEqual(response.context['product_list'], merchant.products.all())
Run Code Online (Sandbox Code Playgroud)
编辑
我用的是self.assertQuerysetEqual而不是self.assertListEqual.不幸的是,这仍然无效,终端显示:
['<Product: Product object>'] != [<Product: Product object>]
assertListEqual提出:'QuerySet' object has no attribute 'difference'并且
assertEqual也不起作用,虽然self.assertSetEqual(response.context['product_list'][0], …
我想知道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)
Run Code Online (Sandbox Code Playgroud)
Number1的错误消息:
First list contains 21 additional elements.
First extra element 1:
node.pk: 2 - node: node2 - pk: 2 - level: 0 - ancestor: 2
Run Code Online (Sandbox Code Playgroud)
第2个错误消息:
AssertionError: Lists differ: ['<Tree: node.pk: 1 - node: …Run Code Online (Sandbox Code Playgroud)