如何测试Django QuerySet是否相等? [英] How do I test Django QuerySets are equal?
问题描述
我正在尝试测试Django视图。该视图将QuerySet传递给模板:
def Businessman_home(request,slug):
商人= Merchant.objects .get(slug = slug)
产品列表=商人。产品。全部()
返回render_to_response('merchant_home.html',
{'商人':商人,
'product_list ':product_list},
context_instance = RequestContext(request))
并测试:
def测试(自):
商人主视图应将商人和商人产品发送到模板
商人= Merchant.objects.create(名称=测试商人)
产品=产品.objects.create(名称=测试产品,价格= 100.00)
商人.products.add(产品)
test_client = Client()
响应= test_client.get('/'+商人.slug)
#self.assertListEqual(response.context ['product_list'],商人.products.all())
self.assertQuerysetEqual(response.context ['product_list'],商人.products.all())
EDIT
我正在使用 self.assertQuerysetEqua
l而不是 self.assertListEqual
。不幸的是,这仍然不起作用,并且终端显示以下内容:
['< Product:Product object>']!= [< Product:Product object>]
assertListEqual
加注:'QuerySet'对象没有属性'difference'
并且
assertEqual
也不起作用,尽管 self .assertSetEqual(response.context ['product_list'] [0],merchant.products.all()[0])
会通过。
如何测试两个QuerySet包含相同的数据?我什至在正确测试?这是我学习Django的第四天,因此,如果可能的话,我想了解最佳做法。谢谢。
使用 assertQuerysetEqual ,该功能旨在为您比较两个查询集。您需要将Django的 django.test.TestCase
子类化,以使其在您的测试中可用。
I am trying to test my Django views. This view passes a QuerySet to the template:
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))
and test:
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())
EDIT
I am using self.assertQuerysetEqua
l instead of self.assertListEqual
. Unfortunately this still doesn't work, and the terminal displays this:
['<Product: Product object>'] != [<Product: Product object>]
assertListEqual
raises: 'QuerySet' object has no attribute 'difference'
and
assertEqual
does not work either, although self.assertSetEqual(response.context['product_list'][0], merchant.products.all()[0])
does pass.
I assume this is because the QuerySets are different objects even though they contain the same model instances.
How do I test that two QuerySets contain the same data? I am even testing this correctly? This is my 4th day learning Django so I would like to know best practices, if possible. Thanks.
Use assertQuerysetEqual, which is built to compare the two querysets for you. You will need to subclass Django's django.test.TestCase
for it to be available in your tests.
这篇关于如何测试Django QuerySet是否相等?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!