Debian Codegraph @

tests/model_enums/tests.py

raw
1 import datetime
2 import decimal
3 import ipaddress
4 import uuid
5
6 from django.db import models
7 from django.template import Context, Template
8 from django.test import SimpleTestCase
9 from django.utils.deprecation import RemovedInDjango60Warning
10 from django.utils.functional import Promise
11 from django.utils.translation import gettext_lazy as _
12 from django.utils.version import PY311
13
14
15 class Suit(models.IntegerChoices):
16 DIAMOND = 1, _("Diamond")
17 SPADE = 2, _("Spade")
18 HEART = 3, _("Heart")
19 CLUB = 4, _("Club")
20
21
22 class YearInSchool(models.TextChoices):
23 FRESHMAN = "FR", _("Freshman")
24 SOPHOMORE = "SO", _("Sophomore")
25 JUNIOR = "JR", _("Junior")
26 SENIOR = "SR", _("Senior")
27 GRADUATE = "GR", _("Graduate")
28
29
30 class Vehicle(models.IntegerChoices):
31 CAR = 1, "Carriage"
32 TRUCK = 2
33 JET_SKI = 3
34
35 __empty__ = _("(Unknown)")
36
37
38 class Gender(models.TextChoices):
39 MALE = "M"
40 FEMALE = "F"
41 NOT_SPECIFIED = "X"
42
43 __empty__ = "(Undeclared)"
44
45
46 class ChoicesTests(SimpleTestCase):
47 def test_integerchoices(self):
48 self.assertEqual(
49 Suit.choices, [(1, "Diamond"), (2, "Spade"), (3, "Heart"), (4, "Club")]
50 )
51 self.assertEqual(Suit.labels, ["Diamond", "Spade", "Heart", "Club"])
52 self.assertEqual(Suit.values, [1, 2, 3, 4])
53 self.assertEqual(Suit.names, ["DIAMOND", "SPADE", "HEART", "CLUB"])
54
55 self.assertEqual(repr(Suit.DIAMOND), "Suit.DIAMOND")
56 self.assertEqual(Suit.DIAMOND.label, "Diamond")
57 self.assertEqual(Suit.DIAMOND.value, 1)
58 self.assertEqual(Suit["DIAMOND"], Suit.DIAMOND)
59 self.assertEqual(Suit(1), Suit.DIAMOND)
60
61 self.assertIsInstance(Suit, type(models.Choices))
62 self.assertIsInstance(Suit.DIAMOND, Suit)
63 self.assertIsInstance(Suit.DIAMOND.label, Promise)
64 self.assertIsInstance(Suit.DIAMOND.value, int)
65
66 def test_integerchoices_auto_label(self):
67 self.assertEqual(Vehicle.CAR.label, "Carriage")
68 self.assertEqual(Vehicle.TRUCK.label, "Truck")
69 self.assertEqual(Vehicle.JET_SKI.label, "Jet Ski")
70
71 def test_integerchoices_empty_label(self):
72 self.assertEqual(Vehicle.choices[0], (None, "(Unknown)"))
73 self.assertEqual(Vehicle.labels[0], "(Unknown)")
74 self.assertIsNone(Vehicle.values[0])
75 self.assertEqual(Vehicle.names[0], "__empty__")
76
77 def test_integerchoices_functional_api(self):
78 Place = models.IntegerChoices("Place", "FIRST SECOND THIRD")
79 self.assertEqual(Place.labels, ["First", "Second", "Third"])
80 self.assertEqual(Place.values, [1, 2, 3])
81 self.assertEqual(Place.names, ["FIRST", "SECOND", "THIRD"])
82
83 def test_integerchoices_containment(self):
84 self.assertIn(Suit.DIAMOND, Suit)
85 self.assertIn(1, Suit)
86 self.assertNotIn(0, Suit)
87
88 def test_textchoices(self):
89 self.assertEqual(
90 YearInSchool.choices,
91 [
92 ("FR", "Freshman"),
93 ("SO", "Sophomore"),
94 ("JR", "Junior"),
95 ("SR", "Senior"),
96 ("GR", "Graduate"),
97 ],
98 )
99 self.assertEqual(
100 YearInSchool.labels,
101 ["Freshman", "Sophomore", "Junior", "Senior", "Graduate"],
102 )
103 self.assertEqual(YearInSchool.values, ["FR", "SO", "JR", "SR", "GR"])
104 self.assertEqual(
105 YearInSchool.names,
106 ["FRESHMAN", "SOPHOMORE", "JUNIOR", "SENIOR", "GRADUATE"],
107 )
108
109 self.assertEqual(repr(YearInSchool.FRESHMAN), "YearInSchool.FRESHMAN")
110 self.assertEqual(YearInSchool.FRESHMAN.label, "Freshman")
111 self.assertEqual(YearInSchool.FRESHMAN.value, "FR")
112 self.assertEqual(YearInSchool["FRESHMAN"], YearInSchool.FRESHMAN)
113 self.assertEqual(YearInSchool("FR"), YearInSchool.FRESHMAN)
114
115 self.assertIsInstance(YearInSchool, type(models.Choices))
116 self.assertIsInstance(YearInSchool.FRESHMAN, YearInSchool)
117 self.assertIsInstance(YearInSchool.FRESHMAN.label, Promise)
118 self.assertIsInstance(YearInSchool.FRESHMAN.value, str)
119
120 def test_textchoices_auto_label(self):
121 self.assertEqual(Gender.MALE.label, "Male")
122 self.assertEqual(Gender.FEMALE.label, "Female")
123 self.assertEqual(Gender.NOT_SPECIFIED.label, "Not Specified")
124
125 def test_textchoices_empty_label(self):
126 self.assertEqual(Gender.choices[0], (None, "(Undeclared)"))
127 self.assertEqual(Gender.labels[0], "(Undeclared)")
128 self.assertIsNone(Gender.values[0])
129 self.assertEqual(Gender.names[0], "__empty__")
130
131 def test_textchoices_functional_api(self):
132 Medal = models.TextChoices("Medal", "GOLD SILVER BRONZE")
133 self.assertEqual(Medal.labels, ["Gold", "Silver", "Bronze"])
134 self.assertEqual(Medal.values, ["GOLD", "SILVER", "BRONZE"])
135 self.assertEqual(Medal.names, ["GOLD", "SILVER", "BRONZE"])
136
137 def test_textchoices_containment(self):
138 self.assertIn(YearInSchool.FRESHMAN, YearInSchool)
139 self.assertIn("FR", YearInSchool)
140 self.assertNotIn("XX", YearInSchool)
141
142 def test_textchoices_blank_value(self):
143 class BlankStr(models.TextChoices):
144 EMPTY = "", "(Empty)"
145 ONE = "ONE", "One"
146
147 self.assertEqual(BlankStr.labels, ["(Empty)", "One"])
148 self.assertEqual(BlankStr.values, ["", "ONE"])
149 self.assertEqual(BlankStr.names, ["EMPTY", "ONE"])
150
151 def test_invalid_definition(self):
152 msg = "'str' object cannot be interpreted as an integer"
153 with self.assertRaisesMessage(TypeError, msg):
154
155 class InvalidArgumentEnum(models.IntegerChoices):
156 # A string is not permitted as the second argument to int().
157 ONE = 1, "X", "Invalid"
158
159 msg = "duplicate values found in <enum 'Fruit'>: PINEAPPLE -> APPLE"
160 with self.assertRaisesMessage(ValueError, msg):
161
162 class Fruit(models.IntegerChoices):
163 APPLE = 1, "Apple"
164 PINEAPPLE = 1, "Pineapple"
165
166 def test_str(self):
167 for test in [Gender, Suit, YearInSchool, Vehicle]:
168 for member in test:
169 with self.subTest(member=member):
170 self.assertEqual(str(test[member.name]), str(member.value))
171
172 def test_templates(self):
173 template = Template("{{ Suit.DIAMOND.label }}|{{ Suit.DIAMOND.value }}")
174 output = template.render(Context({"Suit": Suit}))
175 self.assertEqual(output, "Diamond|1")
176
177 def test_property_names_conflict_with_member_names(self):
178 with self.assertRaises(AttributeError):
179 models.TextChoices("Properties", "choices labels names values")
180
181 def test_label_member(self):
182 # label can be used as a member.
183 Stationery = models.TextChoices("Stationery", "label stamp sticker")
184 self.assertEqual(Stationery.label.label, "Label")
185 self.assertEqual(Stationery.label.value, "label")
186 self.assertEqual(Stationery.label.name, "label")
187
188 def test_do_not_call_in_templates_member(self):
189 # do_not_call_in_templates is not implicitly treated as a member.
190 Special = models.IntegerChoices("Special", "do_not_call_in_templates")
191 self.assertIn("do_not_call_in_templates", Special.__members__)
192 self.assertEqual(
193 Special.do_not_call_in_templates.label,
194 "Do Not Call In Templates",
195 )
196 self.assertEqual(Special.do_not_call_in_templates.value, 1)
197 self.assertEqual(
198 Special.do_not_call_in_templates.name,
199 "do_not_call_in_templates",
200 )
201
202 def test_do_not_call_in_templates_nonmember(self):
203 self.assertNotIn("do_not_call_in_templates", Suit.__members__)
204 if PY311:
205 self.assertIs(Suit.do_not_call_in_templates, True)
206 else:
207 # Using @property on an enum does not behave as expected.
208 self.assertTrue(Suit.do_not_call_in_templates)
209 self.assertIsNot(Suit.do_not_call_in_templates, True)
210 self.assertIsInstance(Suit.do_not_call_in_templates, property)
211
212
213 class Separator(bytes, models.Choices):
214 FS = b"\x1c", "File Separator"
215 GS = b"\x1d", "Group Separator"
216 RS = b"\x1e", "Record Separator"
217 US = b"\x1f", "Unit Separator"
218
219
220 class Constants(float, models.Choices):
221 PI = 3.141592653589793, "π"
222 TAU = 6.283185307179586, "τ"
223
224
225 class Set(frozenset, models.Choices):
226 A = {1, 2}
227 B = {2, 3}
228 UNION = A | B
229 DIFFERENCE = A - B
230 INTERSECTION = A & B
231
232
233 class MoonLandings(datetime.date, models.Choices):
234 APOLLO_11 = 1969, 7, 20, "Apollo 11 (Eagle)"
235 APOLLO_12 = 1969, 11, 19, "Apollo 12 (Intrepid)"
236 APOLLO_14 = 1971, 2, 5, "Apollo 14 (Antares)"
237 APOLLO_15 = 1971, 7, 30, "Apollo 15 (Falcon)"
238 APOLLO_16 = 1972, 4, 21, "Apollo 16 (Orion)"
239 APOLLO_17 = 1972, 12, 11, "Apollo 17 (Challenger)"
240
241
242 class DateAndTime(datetime.datetime, models.Choices):
243 A = 2010, 10, 10, 10, 10, 10
244 B = 2011, 11, 11, 11, 11, 11
245 C = 2012, 12, 12, 12, 12, 12
246
247
248 class MealTimes(datetime.time, models.Choices):
249 BREAKFAST = 7, 0
250 LUNCH = 13, 0
251 DINNER = 18, 30
252
253
254 class Frequency(datetime.timedelta, models.Choices):
255 WEEK = 0, 0, 0, 0, 0, 0, 1, "Week"
256 DAY = 1, "Day"
257 HOUR = 0, 0, 0, 0, 0, 1, "Hour"
258 MINUTE = 0, 0, 0, 0, 1, "Hour"
259 SECOND = 0, 1, "Second"
260
261
262 class Number(decimal.Decimal, models.Choices):
263 E = 2.718281828459045, "e"
264 PI = "3.141592653589793", "π"
265 TAU = decimal.Decimal("6.283185307179586"), "τ"
266
267
268 class IPv4Address(ipaddress.IPv4Address, models.Choices):
269 LOCALHOST = "127.0.0.1", "Localhost"
270 GATEWAY = "192.168.0.1", "Gateway"
271 BROADCAST = "192.168.0.255", "Broadcast"
272
273
274 class IPv6Address(ipaddress.IPv6Address, models.Choices):
275 LOCALHOST = "::1", "Localhost"
276 UNSPECIFIED = "::", "Unspecified"
277
278
279 class IPv4Network(ipaddress.IPv4Network, models.Choices):
280 LOOPBACK = "127.0.0.0/8", "Loopback"
281 LINK_LOCAL = "169.254.0.0/16", "Link-Local"
282 PRIVATE_USE_A = "10.0.0.0/8", "Private-Use (Class A)"
283
284
285 class IPv6Network(ipaddress.IPv6Network, models.Choices):
286 LOOPBACK = "::1/128", "Loopback"
287 UNSPECIFIED = "::/128", "Unspecified"
288 UNIQUE_LOCAL = "fc00::/7", "Unique-Local"
289 LINK_LOCAL_UNICAST = "fe80::/10", "Link-Local Unicast"
290
291
292 class CustomChoicesTests(SimpleTestCase):
293 def test_labels_valid(self):
294 enums = (
295 Separator,
296 Constants,
297 Set,
298 MoonLandings,
299 DateAndTime,
300 MealTimes,
301 Frequency,
302 Number,
303 IPv4Address,
304 IPv6Address,
305 IPv4Network,
306 IPv6Network,
307 )
308 for choice_enum in enums:
309 with self.subTest(choice_enum.__name__):
310 self.assertNotIn(None, choice_enum.labels)
311
312 def test_bool_unsupported(self):
313 msg = "type 'bool' is not an acceptable base type"
314 with self.assertRaisesMessage(TypeError, msg):
315
316 class Boolean(bool, models.Choices):
317 pass
318
319 def test_uuid_unsupported(self):
320 with self.assertRaises(TypeError):
321
322 class Identifier(uuid.UUID, models.Choices):
323 A = "972ce4eb-a95f-4a56-9339-68c208a76f18"
324
325
326 class ChoicesMetaDeprecationTests(SimpleTestCase):
327 def test_deprecation_warning(self):
328 from django.db.models import enums
329
330 msg = "ChoicesMeta is deprecated in favor of ChoicesType."
331 with self.assertWarnsMessage(RemovedInDjango60Warning, msg) as ctx:
332 enums.ChoicesMeta
333 self.assertEqual(ctx.filename, __file__)