Enhancement to assertQuerysetEqual

83 views
Skip to first unread message

Peter Inglesby

unread,
Feb 4, 2020, 11:35:16 AM2/4/20
to django-d...@googlegroups.com
Hi folks,

I always find the behaviour of assertQuerysetEqual surprising, particularly when I pass it two querysets that I expect to be the same, or when the second argument is a list of model instances.

Under the covers, assertQuerysetEqual(xs, ys) is roughly equivalent to assert [repr(x) for x in xs] == ys, and an optional transform parameter can be passed in to be used instead of repr().

So assertQuerysetEqual(qs1, qs2) is never going to do the right thing and there's always ten seconds of head scratching while I look at something like:

AssertionError: Lists differ: ['<AMP: 10347111000001100>', '<AMP: 4814811000001108>'] != [<AMP: 10347111000001100>, <AMP: 4814811000001108>]

I know that I can use assertCountEqual from the standard library, and I think at the very minimum this should be mentioned in the docs for assertQuerysetEqual.

However, I'd like to go further and propose a change to assertQuerysetEqual so that if no transform argument is passed, and the second argument is not a list of strings, then transform is set to the identity function.

As far as I can tell, this would not introduce a meaningful backwards incompatibility.

I'm willing to do the work to add code and documentation etc.

All the best,

Peter.

Adam Johnson

unread,
Feb 4, 2020, 11:42:15 AM2/4/20
to django-d...@googlegroups.com
Seems reasonable to me. I would certainly read `assertQuerysetEqual(qs1, qs2)` as checking they contain the same items.

--
You received this message because you are subscribed to the Google Groups "Django developers (Contributions to Django itself)" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-develop...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-developers/CAENJrPkCNwH5LEG-OnhmcmkEB0mULgf_LjmFkATZ0ENcSQk_Hw%40mail.gmail.com.


--
Adam

charettes

unread,
Feb 4, 2020, 10:27:56 PM2/4/20
to Django developers (Contributions to Django itself)
Hello Peter,

I've always felt the current behaviour of assertQuerysetEqual was weird and always wondered why it was not implement the way you suggest.

I think you're approach is clever and I can't think of a way it would break backward compatibility except if .values_list('charfield', flat=True) is used.

I'd suggest we go even further and raise a deprecation warning when falling back to repr because of the first item is an instance of str so
we can eventually remove this weird behaviour entirely.

Cheers,
Simon
Reply all
Reply to author
Forward
0 new messages