36👍
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.
47👍
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)
- [Django]-Django – how to detect test environment (check / determine if tests are being run)
- [Django]-Django: ImproperlyConfigured: The SECRET_KEY setting must not be empty
- [Django]-Django: Implementing a Form within a generic DetailView
11👍
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)
- [Django]-How to save a model without sending a signal?
- [Django]-Simple approach to launching background task in Django
- [Django]-Django character set with MySQL weirdness
4👍
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.
- [Django]-How to PATCH a single field using Django Rest Framework?
- [Django]-Should I avoid multi-table (concrete) inheritance in Django by any means?
- [Django]-Django Error u"'polls" is not a registered namespace
4👍
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))
- [Django]-HTTPError 403 (Forbidden) with Django and python-social-auth connecting to Google with OAuth2
- [Django]-Django-rest-framework 3.0 create or update in nested serializer
- [Django]-Detect django testing mode
-1👍
I found that using self.assertCountEqual(queryset1, queryset2)
also solves the issue.
- [Django]-Django model "doesn't declare an explicit app_label"
- [Django]-Django 1.4 timezone.now() vs datetime.datetime.now()
- [Django]-Django: Catching Integrity Error and showing a customized message using template