1 | from django.db import models
|
---|
2 | from django.test import TestCase
|
---|
3 |
|
---|
4 |
|
---|
5 | class MyModel(models.Model):
|
---|
6 | pass
|
---|
7 |
|
---|
8 |
|
---|
9 | class CaseStatemenetEmptyListTestCase(TestCase):
|
---|
10 | """Test that annotation doesn't change the count of items in a queryset when
|
---|
11 | calling `__in=[]` in a When expression inside a Case exporession in the
|
---|
12 | annotation.
|
---|
13 | """
|
---|
14 |
|
---|
15 | def setUp(self):
|
---|
16 | for i in range(3):
|
---|
17 | MyModel().save()
|
---|
18 |
|
---|
19 | def test_full_list(self):
|
---|
20 | ids = [1, 2, 3]
|
---|
21 | qs = MyModel.objects.all()
|
---|
22 | count_before = qs.count()
|
---|
23 | qs = qs.annotate(
|
---|
24 | field=models.Case(
|
---|
25 | models.When(id__in=ids, then=models.Value(True)),
|
---|
26 | default=models.Value(False),
|
---|
27 | output_field=models.BooleanField()
|
---|
28 | )
|
---|
29 | )
|
---|
30 | count_after = qs.count()
|
---|
31 |
|
---|
32 | self.assertEqual(count_before, count_after)
|
---|
33 |
|
---|
34 | def test_empty_lsit(self):
|
---|
35 | ids = []
|
---|
36 | qs = MyModel.objects.all()
|
---|
37 | count_before = qs.count()
|
---|
38 | qs = qs.annotate(
|
---|
39 | field=models.Case(
|
---|
40 | models.When(id__in=ids, then=models.Value(True)),
|
---|
41 | default=models.Value(False),
|
---|
42 | output_field=models.BooleanField()
|
---|
43 | )
|
---|
44 | )
|
---|
45 | count_after = qs.count()
|
---|
46 |
|
---|
47 | self.assertEqual(count_before, count_after)
|
---|
48 |
|
---|
49 | def test_empty_qs(self):
|
---|
50 | empty_qs = MyModel.objects.none()
|
---|
51 | qs = MyModel.objects.all()
|
---|
52 | count_before = qs.count()
|
---|
53 | qs = qs.annotate(
|
---|
54 | field=models.Case(
|
---|
55 | models.When(id__in=empty_qs, then=models.Value(True)),
|
---|
56 | default=models.Value(False),
|
---|
57 | output_field=models.BooleanField()
|
---|
58 | )
|
---|
59 | )
|
---|
60 | count_after = qs.count()
|
---|
61 |
|
---|
62 | self.assertEqual(count_before, count_after)
|
---|
63 |
|
---|
64 | def test_empty_lsit_query_raises_exception(self):
|
---|
65 | ids = []
|
---|
66 | qs = MyModel.objects.all()
|
---|
67 | qs = qs.annotate(
|
---|
68 | field=models.Case(
|
---|
69 | models.When(id__in=ids, then=models.Value(True)),
|
---|
70 | default=models.Value(False),
|
---|
71 | output_field=models.BooleanField()
|
---|
72 | )
|
---|
73 | )
|
---|
74 |
|
---|
75 | with self.assertRaises(models.sql.datastructures.EmptyResultSet):
|
---|
76 | str(qs.query)
|
---|