How do I test Django QuerySets are equal?

前端 未结 6 748
挽巷
挽巷 2020-12-17 07:40

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=sl         


        
相关标签:
6条回答
  • 2020-12-17 08:15

    I just had the same problem. The second argument of assertQuerysetEqual needs to be a list of the expected repr()s as strings. Here is an example from the Django test suite:

    self.assertQuerysetEqual(c1.tags.all(), ["<Tag: t1>", "<Tag: t2>"], ordered=False)
    
    0 讨论(0)
  • 2020-12-17 08:26

    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.

    0 讨论(0)
  • 2020-12-17 08:26

    I found that using self.assertCountEqual(queryset1, queryset2) also solves the issue.

    0 讨论(0)
  • 2020-12-17 08:31

    By default assertQuerysetEqual uses repr() on the first argument. This is why you were having issues with the strings in the queryset comparison.

    To work around this you can override the transform argument with a lambda function that doesn't use repr():

    self.assertQuerysetEqual(queryset_1, queryset_2, transform=lambda x: x)
    
    0 讨论(0)
  • 2020-12-17 08:32

    I ended up solving this issue using map to repr() each entry in the queryset inside the self.assertQuerysetEqual call, e.g.

    self.assertQuerysetEqual(queryset_1, map(repr, queryset_2))
    
    0 讨论(0)
  • 2020-12-17 08:32

    An alternative, but not necessarily better, method might look like this (testing context in a view, for example) when using pytest:

    all_the_things = Things.objects.all()
    assert set(response.context_data['all_the_things']) == set(all_the_things)
    

    This converts it to a set, which is directly comparable with another set. Be careful with the behaviour of set though, it might not be exactly what you want since it will remove duplicates and ignore the order of objects.

    0 讨论(0)
提交回复
热议问题