Debian Codegraph @

tests/model_fields/test_decimalfield.py

raw
1 import math
2 from decimal import Decimal
3 from unittest import mock
4
5 from django.core import validators
6 from django.core.exceptions import ValidationError
7 from django.db import connection, models
8 from django.test import TestCase
9
10 from .models import BigD, Foo
11
12
13 class DecimalFieldTests(TestCase):
14 def test_to_python(self):
15 f = models.DecimalField(max_digits=4, decimal_places=2)
16 self.assertEqual(f.to_python(3), Decimal("3"))
17 self.assertEqual(f.to_python("3.14"), Decimal("3.14"))
18 # to_python() converts floats and honors max_digits.
19 self.assertEqual(f.to_python(3.1415926535897), Decimal("3.142"))
20 self.assertEqual(f.to_python(2.4), Decimal("2.400"))
21 # Uses default rounding of ROUND_HALF_EVEN.
22 self.assertEqual(f.to_python(2.0625), Decimal("2.062"))
23 self.assertEqual(f.to_python(2.1875), Decimal("2.188"))
24
25 def test_invalid_value(self):
26 field = models.DecimalField(max_digits=4, decimal_places=2)
27 msg = "“%s” value must be a decimal number."
28 tests = [
29 (),
30 [],
31 {},
32 set(),
33 object(),
34 complex(),
35 "non-numeric string",
36 b"non-numeric byte-string",
37 ]
38 for value in tests:
39 with self.subTest(value):
40 with self.assertRaisesMessage(ValidationError, msg % (value,)):
41 field.clean(value, None)
42
43 def test_default(self):
44 f = models.DecimalField(default=Decimal("0.00"))
45 self.assertEqual(f.get_default(), Decimal("0.00"))
46
47 def test_get_prep_value(self):
48 f = models.DecimalField(max_digits=5, decimal_places=1)
49 self.assertIsNone(f.get_prep_value(None))
50 self.assertEqual(f.get_prep_value("2.4"), Decimal("2.4"))
51
52 def test_get_db_prep_value(self):
53 """
54 DecimalField.get_db_prep_value() must call
55 DatabaseOperations.adapt_decimalfield_value().
56 """
57 f = models.DecimalField(max_digits=5, decimal_places=1)
58 # None of the built-in database backends implement
59 # adapt_decimalfield_value(), so this must be confirmed with mocking.
60 with mock.patch.object(
61 connection.ops.__class__, "adapt_decimalfield_value"
62 ) as adapt_decimalfield_value:
63 f.get_db_prep_value("2.4", connection)
64 adapt_decimalfield_value.assert_called_with(Decimal("2.4"), 5, 1)
65
66 def test_filter_with_strings(self):
67 """
68 Should be able to filter decimal fields using strings (#8023).
69 """
70 foo = Foo.objects.create(a="abc", d=Decimal("12.34"))
71 self.assertEqual(list(Foo.objects.filter(d="12.34")), [foo])
72
73 def test_save_without_float_conversion(self):
74 """
75 Ensure decimals don't go through a corrupting float conversion during
76 save (#5079).
77 """
78 bd = BigD(d="12.9")
79 bd.save()
80 bd = BigD.objects.get(pk=bd.pk)
81 self.assertEqual(bd.d, Decimal("12.9"))
82
83 def test_save_nan_invalid(self):
84 msg = "“nan” value must be a decimal number."
85 for value in [float("nan"), math.nan, "nan"]:
86 with self.subTest(value), self.assertRaisesMessage(ValidationError, msg):
87 BigD.objects.create(d=value)
88
89 def test_save_inf_invalid(self):
90 msg = "“inf” value must be a decimal number."
91 for value in [float("inf"), math.inf, "inf"]:
92 with self.subTest(value), self.assertRaisesMessage(ValidationError, msg):
93 BigD.objects.create(d=value)
94 msg = "“-inf” value must be a decimal number."
95 for value in [float("-inf"), -math.inf, "-inf"]:
96 with self.subTest(value), self.assertRaisesMessage(ValidationError, msg):
97 BigD.objects.create(d=value)
98
99 def test_fetch_from_db_without_float_rounding(self):
100 big_decimal = BigD.objects.create(d=Decimal(".100000000000000000000000000005"))
101 big_decimal.refresh_from_db()
102 self.assertEqual(big_decimal.d, Decimal(".100000000000000000000000000005"))
103
104 def test_lookup_really_big_value(self):
105 """
106 Really big values can be used in a filter statement.
107 """
108 # This should not crash.
109 self.assertSequenceEqual(Foo.objects.filter(d__gte=100000000000), [])
110
111 def test_lookup_decimal_larger_than_max_digits(self):
112 self.assertSequenceEqual(Foo.objects.filter(d__lte=Decimal("123456")), [])
113
114 def test_max_digits_validation(self):
115 field = models.DecimalField(max_digits=2)
116 expected_message = validators.DecimalValidator.messages["max_digits"] % {
117 "max": 2
118 }
119 with self.assertRaisesMessage(ValidationError, expected_message):
120 field.clean(100, None)
121
122 def test_max_decimal_places_validation(self):
123 field = models.DecimalField(decimal_places=1)
124 expected_message = validators.DecimalValidator.messages[
125 "max_decimal_places"
126 ] % {"max": 1}
127 with self.assertRaisesMessage(ValidationError, expected_message):
128 field.clean(Decimal("0.99"), None)
129
130 def test_max_whole_digits_validation(self):
131 field = models.DecimalField(max_digits=3, decimal_places=1)
132 expected_message = validators.DecimalValidator.messages["max_whole_digits"] % {
133 "max": 2
134 }
135 with self.assertRaisesMessage(ValidationError, expected_message):
136 field.clean(Decimal("999"), None)
137
138 def test_roundtrip_with_trailing_zeros(self):
139 """Trailing zeros in the fractional part aren't truncated."""
140 obj = Foo.objects.create(a="bar", d=Decimal("8.320"))
141 obj.refresh_from_db()
142 self.assertEqual(obj.d.compare_total(Decimal("8.320")), Decimal("0"))