Testing Django requests: self.assertListEqual vs self.assertQuerysetEqual

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 ?

+5
source share
1 answer

The only practical difference is how python compares objects and strings.

self.assertListEqual : compares a list of model instances delegating the __eq__ method, which provides a rule for comparison. See how Django makes comparisons for model instances .

self.assertQuerysetEqual : compares a list of strings using the ord value of each character in each string.

Depending on how __eq__ and __repr__ implemented for the object, you can provide a slight performance increase over the other.

0
source

Source: https://habr.com/ru/post/1261535/


All Articles