Testing in Django I found two different ways to test functions that include queries. The first one is:
test_instance = FooFactory() self.assertListEqual(list(Foo.objects.all()), [test_instance])
And the second one:
test_instance = FooFactory() self.assertQuerysetEqual(Foo.objects.all(), map(repr, [test_instance]))
Which of these two is better? I read from Django docs that this is what assertQuerysetEqual does:
Claims that the qs query returns a specific list of values.
Comparison of qs contents and values โโis done using function conversion; by default, this means that the repr () value of each value is compared. Any other called can be used if the repr () function does not provide a unique or useful comparison.
By default, the comparison also depends on the order. If qs does not provide implicit order, you can set the ordered parameter to False, which turns the comparison into a collection. Compare links. If the order is undefined (if the given qs are not ordered, and the comparison is against more than one ordered value), the ValueError is increased.
Here I see two important things: one of them is compared with repr() each value, and the other is that assertQuerysetEqual allows assertQuerysetEqual to make an order optional.
In the first case, I believe that it is better to compare the models themselves, and not their repr values, since you know that they are exactly the same (although you can also make an argument that the repr values โโshould be different).
Secondly, I see how disordered comparisons can be useful. Again, if you specifically test something where the ordering is not important / easily mimicked, I don't see the benefits there.
The only argument I can come up with for assertQuerysetEqual (with these assumptions above) is that it is more readable / direct regarding its purpose.
Is there any practical difference between self.assertListEqual(list(<queryset>), [<expected_models_in_correct_order>]) and self.assertQuerysetEqual(<queryset>, map(repr, [<expected_models_in_correct_order>]) , which I could not explain ?