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