比较 django TestCase 中的查询集 [英] comparing querysets in django TestCase

查看:19
本文介绍了比较 django TestCase 中的查询集的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有个很简单的看法如下

I have a very simple view as follows

def simple_view(request):
    documents = request.user.document_set.all()
    return render(request, 'simple.html', {'documents': documents})

为了在我的测试用例中测试上述视图,我有以下方法会出错.

To test the above view in my test case i have the following method which errors out.

Class SomeTestCase(TestCase):
    # ...
    def test_simple_view(self):
        # ... some other checks
        docset = self.resonse.context['documents']
        self.assertTrue(self.user.document_set.all() == docset) # This line raises an error
    # ...

我得到的错误是 AssertionError: False is not true.我已经尝试打印两个查询集,并且两者都完全相同.当两个对象相同时,为什么会返回 False ?有什么想法吗?

The error i get is AssertionError: False is not true. I have tried printing both the querysets and both are absolutely identical. Why would it return False when both the objects are identical ? Any Ideas ?

目前为了克服这个问题,我正在使用一种令人讨厌的检查长度的方法,如下所示:

Currently to overcome this, I am using a nasty hack of checking lengths as follows:

ds1, ds2 = self.response.context['documents'], self.user.document_set.all()
self.assertTrue(len([x for x in ds1 if x in ds2]) == len(ds1) == len(ds2)) # Makes sure each entry in ds1 exists in ds2

推荐答案

如果查询集对象是不同查询的结果,即使它们的结果中具有相同的值(比较 ds1.queryds2.query).

The queryset objects will not be identical if they are the result of different queries even if they have the same values in their result (compare ds1.query and ds2.query).

如果你先将查询集转换为列表,你应该可以进行正常的比较(当然假设它们具有相同的排序顺序):

If you convert the query set to a list first, you should be able to do a normal comparison (assuming they have the same sort order of course):

self.assertEqual(list(ds1), list(ds2))

这篇关于比较 django TestCase 中的查询集的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆