Debian Codegraph @

tests/db_functions/comparison/test_cast.py

raw
1 import datetime
2 import decimal
3 import unittest
4
5 from django.db import connection, models
6 from django.db.models.functions import Cast
7 from django.test import TestCase, ignore_warnings, skipUnlessDBFeature
8 from django.test.utils import CaptureQueriesContext
9
10 from ..models import Author, DTModel, Fan, FloatModel
11
12
13 class CastTests(TestCase):
14 @classmethod
15 def setUpTestData(self):
16 Author.objects.create(name="Bob", age=1, alias="1")
17
18 def test_cast_from_value(self):
19 numbers = Author.objects.annotate(
20 cast_integer=Cast(models.Value("0"), models.IntegerField())
21 )
22 self.assertEqual(numbers.get().cast_integer, 0)
23
24 def test_cast_from_field(self):
25 numbers = Author.objects.annotate(
26 cast_string=Cast("age", models.CharField(max_length=255)),
27 )
28 self.assertEqual(numbers.get().cast_string, "1")
29
30 def test_cast_to_char_field_without_max_length(self):
31 numbers = Author.objects.annotate(cast_string=Cast("age", models.CharField()))
32 self.assertEqual(numbers.get().cast_string, "1")
33
34 # Silence "Truncated incorrect CHAR(1) value: 'Bob'".
35 @ignore_warnings(module="django.db.backends.mysql.base")
36 @skipUnlessDBFeature("supports_cast_with_precision")
37 def test_cast_to_char_field_with_max_length(self):
38 names = Author.objects.annotate(
39 cast_string=Cast("name", models.CharField(max_length=1))
40 )
41 self.assertEqual(names.get().cast_string, "B")
42
43 @skipUnlessDBFeature("supports_cast_with_precision")
44 def test_cast_to_decimal_field(self):
45 FloatModel.objects.create(f1=-1.934, f2=3.467)
46 float_obj = FloatModel.objects.annotate(
47 cast_f1_decimal=Cast(
48 "f1", models.DecimalField(max_digits=8, decimal_places=2)
49 ),
50 cast_f2_decimal=Cast(
51 "f2", models.DecimalField(max_digits=8, decimal_places=1)
52 ),
53 ).get()
54 self.assertEqual(float_obj.cast_f1_decimal, decimal.Decimal("-1.93"))
55 expected = "3.4" if connection.features.rounds_to_even else "3.5"
56 self.assertEqual(float_obj.cast_f2_decimal, decimal.Decimal(expected))
57 author_obj = Author.objects.annotate(
58 cast_alias_decimal=Cast(
59 "alias", models.DecimalField(max_digits=8, decimal_places=2)
60 ),
61 ).get()
62 self.assertEqual(author_obj.cast_alias_decimal, decimal.Decimal("1"))
63
64 def test_cast_to_integer(self):
65 for field_class in (
66 models.AutoField,
67 models.BigAutoField,
68 models.SmallAutoField,
69 models.IntegerField,
70 models.BigIntegerField,
71 models.SmallIntegerField,
72 models.PositiveBigIntegerField,
73 models.PositiveIntegerField,
74 models.PositiveSmallIntegerField,
75 ):
76 with self.subTest(field_class=field_class):
77 numbers = Author.objects.annotate(cast_int=Cast("alias", field_class()))
78 self.assertEqual(numbers.get().cast_int, 1)
79
80 def test_cast_to_integer_foreign_key(self):
81 numbers = Author.objects.annotate(
82 cast_fk=Cast(
83 models.Value("0"),
84 models.ForeignKey(Author, on_delete=models.SET_NULL),
85 )
86 )
87 self.assertEqual(numbers.get().cast_fk, 0)
88
89 def test_cast_to_duration(self):
90 duration = datetime.timedelta(days=1, seconds=2, microseconds=3)
91 DTModel.objects.create(duration=duration)
92 dtm = DTModel.objects.annotate(
93 cast_duration=Cast("duration", models.DurationField()),
94 cast_neg_duration=Cast(-duration, models.DurationField()),
95 ).get()
96 self.assertEqual(dtm.cast_duration, duration)
97 self.assertEqual(dtm.cast_neg_duration, -duration)
98
99 def test_cast_from_db_datetime_to_date(self):
100 dt_value = datetime.datetime(2018, 9, 28, 12, 42, 10, 234567)
101 DTModel.objects.create(start_datetime=dt_value)
102 dtm = DTModel.objects.annotate(
103 start_datetime_as_date=Cast("start_datetime", models.DateField())
104 ).first()
105 self.assertEqual(dtm.start_datetime_as_date, datetime.date(2018, 9, 28))
106
107 def test_cast_from_db_datetime_to_time(self):
108 dt_value = datetime.datetime(2018, 9, 28, 12, 42, 10, 234567)
109 DTModel.objects.create(start_datetime=dt_value)
110 dtm = DTModel.objects.annotate(
111 start_datetime_as_time=Cast("start_datetime", models.TimeField())
112 ).first()
113 rounded_ms = int(
114 round(0.234567, connection.features.time_cast_precision) * 10**6
115 )
116 self.assertEqual(
117 dtm.start_datetime_as_time, datetime.time(12, 42, 10, rounded_ms)
118 )
119
120 def test_cast_from_db_date_to_datetime(self):
121 dt_value = datetime.date(2018, 9, 28)
122 DTModel.objects.create(start_date=dt_value)
123 dtm = DTModel.objects.annotate(
124 start_as_datetime=Cast("start_date", models.DateTimeField())
125 ).first()
126 self.assertEqual(
127 dtm.start_as_datetime, datetime.datetime(2018, 9, 28, 0, 0, 0, 0)
128 )
129
130 def test_cast_from_db_datetime_to_date_group_by(self):
131 author = Author.objects.create(name="John Smith", age=45)
132 dt_value = datetime.datetime(2018, 9, 28, 12, 42, 10, 234567)
133 Fan.objects.create(name="Margaret", age=50, author=author, fan_since=dt_value)
134 fans = (
135 Fan.objects.values("author")
136 .annotate(
137 fan_for_day=Cast("fan_since", models.DateField()),
138 fans=models.Count("*"),
139 )
140 .values()
141 )
142 self.assertEqual(fans[0]["fan_for_day"], datetime.date(2018, 9, 28))
143 self.assertEqual(fans[0]["fans"], 1)
144
145 def test_cast_from_python_to_date(self):
146 today = datetime.date.today()
147 dates = Author.objects.annotate(cast_date=Cast(today, models.DateField()))
148 self.assertEqual(dates.get().cast_date, today)
149
150 def test_cast_from_python_to_datetime(self):
151 now = datetime.datetime.now()
152 dates = Author.objects.annotate(cast_datetime=Cast(now, models.DateTimeField()))
153 time_precision = datetime.timedelta(
154 microseconds=10 ** (6 - connection.features.time_cast_precision)
155 )
156 self.assertAlmostEqual(dates.get().cast_datetime, now, delta=time_precision)
157
158 def test_cast_from_python(self):
159 numbers = Author.objects.annotate(
160 cast_float=Cast(decimal.Decimal(0.125), models.FloatField())
161 )
162 cast_float = numbers.get().cast_float
163 self.assertIsInstance(cast_float, float)
164 self.assertEqual(cast_float, 0.125)
165
166 @unittest.skipUnless(connection.vendor == "postgresql", "PostgreSQL test")
167 def test_expression_wrapped_with_parentheses_on_postgresql(self):
168 """
169 The SQL for the Cast expression is wrapped with parentheses in case
170 it's a complex expression.
171 """
172 with CaptureQueriesContext(connection) as captured_queries:
173 list(
174 Author.objects.annotate(
175 cast_float=Cast(models.Avg("age"), models.FloatField()),
176 )
177 )
178 self.assertIn(
179 '(AVG("db_functions_author"."age"))::double precision',
180 captured_queries[0]["sql"],
181 )
182
183 def test_cast_to_text_field(self):
184 self.assertEqual(
185 Author.objects.values_list(
186 Cast("age", models.TextField()), flat=True
187 ).get(),
188 "1",
189 )