Debian Codegraph @

tests/model_fields/tests.py

raw
1 import pickle
2
3 from django import forms
4 from django.core.exceptions import ValidationError
5 from django.db import models
6 from django.test import SimpleTestCase, TestCase
7 from django.utils.choices import CallableChoiceIterator
8 from django.utils.functional import lazy
9
10 from .models import (
11 Bar,
12 Choiceful,
13 Foo,
14 RenamedField,
15 VerboseNameField,
16 Whiz,
17 WhizDelayed,
18 WhizIter,
19 WhizIterEmpty,
20 )
21
22
23 class Nested:
24 class Field(models.Field):
25 pass
26
27
28 class BasicFieldTests(SimpleTestCase):
29 def test_show_hidden_initial(self):
30 """
31 Fields with choices respect show_hidden_initial as a kwarg to
32 formfield().
33 """
34 choices = [(0, 0), (1, 1)]
35 model_field = models.Field(choices=choices)
36 form_field = model_field.formfield(show_hidden_initial=True)
37 self.assertTrue(form_field.show_hidden_initial)
38
39 form_field = model_field.formfield(show_hidden_initial=False)
40 self.assertFalse(form_field.show_hidden_initial)
41
42 def test_field_repr(self):
43 """
44 __repr__() of a field displays its name.
45 """
46 f = Foo._meta.get_field("a")
47 self.assertEqual(repr(f), "<django.db.models.fields.CharField: a>")
48 f = models.fields.CharField()
49 self.assertEqual(repr(f), "<django.db.models.fields.CharField>")
50
51 def test_field_repr_nested(self):
52 """__repr__() uses __qualname__ for nested class support."""
53 self.assertEqual(repr(Nested.Field()), "<model_fields.tests.Nested.Field>")
54
55 def test_field_name(self):
56 """
57 A defined field name (name="fieldname") is used instead of the model
58 model's attribute name (modelname).
59 """
60 instance = RenamedField()
61 self.assertTrue(hasattr(instance, "get_fieldname_display"))
62 self.assertFalse(hasattr(instance, "get_modelname_display"))
63
64 def test_field_verbose_name(self):
65 m = VerboseNameField
66 for i in range(1, 22):
67 self.assertEqual(
68 m._meta.get_field("field%d" % i).verbose_name, "verbose field%d" % i
69 )
70
71 self.assertEqual(m._meta.get_field("id").verbose_name, "verbose pk")
72
73 def test_choices_form_class(self):
74 """Can supply a custom choices form class to Field.formfield()"""
75 choices = [("a", "a")]
76 field = models.CharField(choices=choices)
77 klass = forms.TypedMultipleChoiceField
78 self.assertIsInstance(field.formfield(choices_form_class=klass), klass)
79
80 def test_formfield_disabled(self):
81 """Field.formfield() sets disabled for fields with choices."""
82 field = models.CharField(choices=[("a", "b")])
83 form_field = field.formfield(disabled=True)
84 self.assertIs(form_field.disabled, True)
85
86 def test_field_str(self):
87 f = models.Field()
88 self.assertEqual(str(f), "<django.db.models.fields.Field>")
89 f = Foo._meta.get_field("a")
90 self.assertEqual(str(f), "model_fields.Foo.a")
91
92 def test_field_ordering(self):
93 """Fields are ordered based on their creation."""
94 f1 = models.Field()
95 f2 = models.Field(auto_created=True)
96 f3 = models.Field()
97 self.assertLess(f2, f1)
98 self.assertGreater(f3, f1)
99 self.assertIsNotNone(f1)
100 self.assertNotIn(f2, (None, 1, ""))
101
102 def test_field_instance_is_picklable(self):
103 """Field instances can be pickled."""
104 field = models.Field(max_length=100, default="a string")
105 # Must be picklable with this cached property populated (#28188).
106 field._get_default
107 pickle.dumps(field)
108
109 def test_deconstruct_nested_field(self):
110 """deconstruct() uses __qualname__ for nested class support."""
111 name, path, args, kwargs = Nested.Field().deconstruct()
112 self.assertEqual(path, "model_fields.tests.Nested.Field")
113
114 def test_abstract_inherited_fields(self):
115 """Field instances from abstract models are not equal."""
116
117 class AbstractModel(models.Model):
118 field = models.IntegerField()
119
120 class Meta:
121 abstract = True
122
123 class InheritAbstractModel1(AbstractModel):
124 pass
125
126 class InheritAbstractModel2(AbstractModel):
127 pass
128
129 abstract_model_field = AbstractModel._meta.get_field("field")
130 inherit1_model_field = InheritAbstractModel1._meta.get_field("field")
131 inherit2_model_field = InheritAbstractModel2._meta.get_field("field")
132
133 self.assertNotEqual(abstract_model_field, inherit1_model_field)
134 self.assertNotEqual(abstract_model_field, inherit2_model_field)
135 self.assertNotEqual(inherit1_model_field, inherit2_model_field)
136
137 self.assertLess(abstract_model_field, inherit1_model_field)
138 self.assertLess(abstract_model_field, inherit2_model_field)
139 self.assertLess(inherit1_model_field, inherit2_model_field)
140
141 def test_hash_immutability(self):
142 field = models.IntegerField()
143 field_hash = hash(field)
144
145 class MyModel(models.Model):
146 rank = field
147
148 self.assertEqual(field_hash, hash(field))
149
150
151 class ChoicesTests(SimpleTestCase):
152 @classmethod
153 def setUpClass(cls):
154 super().setUpClass()
155 cls.no_choices = Choiceful._meta.get_field("no_choices")
156 cls.empty_choices = Choiceful._meta.get_field("empty_choices")
157 cls.empty_choices_bool = Choiceful._meta.get_field("empty_choices_bool")
158 cls.empty_choices_text = Choiceful._meta.get_field("empty_choices_text")
159 cls.with_choices = Choiceful._meta.get_field("with_choices")
160 cls.with_choices_dict = Choiceful._meta.get_field("with_choices_dict")
161 cls.with_choices_nested_dict = Choiceful._meta.get_field(
162 "with_choices_nested_dict"
163 )
164 cls.choices_from_enum = Choiceful._meta.get_field("choices_from_enum")
165 cls.choices_from_iterator = Choiceful._meta.get_field("choices_from_iterator")
166 cls.choices_from_callable = Choiceful._meta.get_field("choices_from_callable")
167
168 def test_choices(self):
169 self.assertIsNone(self.no_choices.choices)
170 self.assertEqual(self.empty_choices.choices, [])
171 self.assertEqual(self.empty_choices_bool.choices, [])
172 self.assertEqual(self.empty_choices_text.choices, [])
173 self.assertEqual(self.with_choices.choices, [(1, "A")])
174 self.assertEqual(self.with_choices_dict.choices, [(1, "A")])
175 self.assertEqual(self.with_choices_nested_dict.choices, [("Thing", [(1, "A")])])
176 self.assertEqual(
177 self.choices_from_iterator.choices, [(0, "0"), (1, "1"), (2, "2")]
178 )
179 self.assertIsInstance(
180 self.choices_from_callable.choices, CallableChoiceIterator
181 )
182 self.assertEqual(
183 self.choices_from_callable.choices.func(), [(0, "0"), (1, "1"), (2, "2")]
184 )
185
186 def test_choices_slice(self):
187 for choices, expected_slice in [
188 (self.empty_choices.choices, []),
189 (self.empty_choices_bool.choices, []),
190 (self.empty_choices_text.choices, []),
191 (self.with_choices.choices, [(1, "A")]),
192 (self.with_choices_dict.choices, [(1, "A")]),
193 (self.with_choices_nested_dict.choices, [("Thing", [(1, "A")])]),
194 (self.choices_from_iterator.choices, [(0, "0"), (1, "1")]),
195 (self.choices_from_callable.choices.func(), [(0, "0"), (1, "1")]),
196 (self.choices_from_callable.choices, [(0, "0"), (1, "1")]),
197 ]:
198 with self.subTest(choices=choices):
199 self.assertEqual(choices[:2], expected_slice)
200
201 def test_choices_negative_index(self):
202 for choices, expected_choice in [
203 (self.with_choices.choices, (1, "A")),
204 (self.with_choices_dict.choices, (1, "A")),
205 (self.with_choices_nested_dict.choices, ("Thing", [(1, "A")])),
206 (self.choices_from_iterator.choices, (2, "2")),
207 (self.choices_from_callable.choices.func(), (2, "2")),
208 (self.choices_from_callable.choices, (2, "2")),
209 ]:
210 with self.subTest(choices=choices):
211 self.assertEqual(choices[-1], expected_choice)
212
213 def test_flatchoices(self):
214 self.assertEqual(self.no_choices.flatchoices, [])
215 self.assertEqual(self.empty_choices.flatchoices, [])
216 self.assertEqual(self.empty_choices_bool.flatchoices, [])
217 self.assertEqual(self.empty_choices_text.flatchoices, [])
218 self.assertEqual(self.with_choices.flatchoices, [(1, "A")])
219 self.assertEqual(self.with_choices_dict.flatchoices, [(1, "A")])
220 self.assertEqual(self.with_choices_nested_dict.flatchoices, [(1, "A")])
221 self.assertEqual(
222 self.choices_from_iterator.flatchoices, [(0, "0"), (1, "1"), (2, "2")]
223 )
224 self.assertEqual(
225 self.choices_from_callable.flatchoices, [(0, "0"), (1, "1"), (2, "2")]
226 )
227
228 def test_check(self):
229 self.assertEqual(Choiceful.check(), [])
230
231 def test_invalid_choice(self):
232 model_instance = None # Actual model instance not needed.
233 self.no_choices.validate(0, model_instance)
234 msg = "['Value 99 is not a valid choice.']"
235 with self.assertRaisesMessage(ValidationError, msg):
236 self.empty_choices.validate(99, model_instance)
237 with self.assertRaisesMessage(ValidationError, msg):
238 self.with_choices.validate(99, model_instance)
239
240 def test_formfield(self):
241 no_choices_formfield = self.no_choices.formfield()
242 self.assertIsInstance(no_choices_formfield, forms.IntegerField)
243 fields = (
244 self.empty_choices,
245 self.empty_choices_bool,
246 self.empty_choices_text,
247 self.with_choices,
248 self.with_choices_dict,
249 self.with_choices_nested_dict,
250 self.choices_from_enum,
251 self.choices_from_iterator,
252 self.choices_from_callable,
253 )
254 for field in fields:
255 with self.subTest(field=field):
256 self.assertIsInstance(field.formfield(), forms.ChoiceField)
257
258 def test_choices_from_enum(self):
259 # Choices class was transparently resolved when given as argument.
260 self.assertEqual(self.choices_from_enum.choices, Choiceful.Suit.choices)
261 self.assertEqual(self.choices_from_enum.flatchoices, Choiceful.Suit.choices)
262
263
264 class GetFieldDisplayTests(SimpleTestCase):
265 def test_choices_and_field_display(self):
266 """
267 get_choices() interacts with get_FIELD_display() to return the expected
268 values.
269 """
270 self.assertEqual(Whiz(c=1).get_c_display(), "First") # A nested value
271 self.assertEqual(Whiz(c=0).get_c_display(), "Other") # A top level value
272 self.assertEqual(Whiz(c=9).get_c_display(), 9) # Invalid value
273 self.assertIsNone(Whiz(c=None).get_c_display()) # Blank value
274 self.assertEqual(Whiz(c="").get_c_display(), "") # Empty value
275 self.assertEqual(WhizDelayed(c=0).get_c_display(), "Other") # Delayed choices
276
277 def test_get_FIELD_display_translated(self):
278 """A translated display value is coerced to str."""
279 val = Whiz(c=5).get_c_display()
280 self.assertIsInstance(val, str)
281 self.assertEqual(val, "translated")
282
283 def test_overriding_FIELD_display(self):
284 class FooBar(models.Model):
285 foo_bar = models.IntegerField(choices=[(1, "foo"), (2, "bar")])
286
287 def get_foo_bar_display(self):
288 return "something"
289
290 f = FooBar(foo_bar=1)
291 self.assertEqual(f.get_foo_bar_display(), "something")
292
293 def test_overriding_inherited_FIELD_display(self):
294 class Base(models.Model):
295 foo = models.CharField(max_length=254, choices=[("A", "Base A")])
296
297 class Meta:
298 abstract = True
299
300 class Child(Base):
301 foo = models.CharField(
302 max_length=254, choices=[("A", "Child A"), ("B", "Child B")]
303 )
304
305 self.assertEqual(Child(foo="A").get_foo_display(), "Child A")
306 self.assertEqual(Child(foo="B").get_foo_display(), "Child B")
307
308 def test_iterator_choices(self):
309 """
310 get_choices() works with Iterators.
311 """
312 self.assertEqual(WhizIter(c=1).c, 1) # A nested value
313 self.assertEqual(WhizIter(c=9).c, 9) # Invalid value
314 self.assertIsNone(WhizIter(c=None).c) # Blank value
315 self.assertEqual(WhizIter(c="").c, "") # Empty value
316
317 def test_empty_iterator_choices(self):
318 """
319 get_choices() works with empty iterators.
320 """
321 self.assertEqual(WhizIterEmpty(c="a").c, "a") # A nested value
322 self.assertEqual(WhizIterEmpty(c="b").c, "b") # Invalid value
323 self.assertIsNone(WhizIterEmpty(c=None).c) # Blank value
324 self.assertEqual(WhizIterEmpty(c="").c, "") # Empty value
325
326
327 class GetChoicesTests(SimpleTestCase):
328 def test_empty_choices(self):
329 choices = []
330 f = models.CharField(choices=choices)
331 self.assertEqual(f.get_choices(include_blank=False), choices)
332
333 def test_blank_in_choices(self):
334 choices = [("", "<><>"), ("a", "A")]
335 f = models.CharField(choices=choices)
336 self.assertEqual(f.get_choices(include_blank=True), choices)
337
338 def test_blank_in_grouped_choices(self):
339 choices = [
340 ("f", "Foo"),
341 ("b", "Bar"),
342 (
343 "Group",
344 [
345 ("", "No Preference"),
346 ("fg", "Foo"),
347 ("bg", "Bar"),
348 ],
349 ),
350 ]
351 f = models.CharField(choices=choices)
352 self.assertEqual(f.get_choices(include_blank=True), choices)
353
354 def test_lazy_strings_not_evaluated(self):
355 lazy_func = lazy(lambda x: 0 / 0, int) # raises ZeroDivisionError if evaluated.
356 f = models.CharField(choices=[(lazy_func("group"), [("a", "A"), ("b", "B")])])
357 self.assertEqual(f.get_choices(include_blank=True)[0], ("", "---------"))
358
359
360 class GetChoicesOrderingTests(TestCase):
361 @classmethod
362 def setUpTestData(cls):
363 cls.foo1 = Foo.objects.create(a="a", d="12.35")
364 cls.foo2 = Foo.objects.create(a="b", d="12.34")
365 cls.bar1 = Bar.objects.create(a=cls.foo1, b="b")
366 cls.bar2 = Bar.objects.create(a=cls.foo2, b="a")
367 cls.field = Bar._meta.get_field("a")
368
369 def assertChoicesEqual(self, choices, objs):
370 self.assertEqual(choices, [(obj.pk, str(obj)) for obj in objs])
371
372 def test_get_choices(self):
373 self.assertChoicesEqual(
374 self.field.get_choices(include_blank=False, ordering=("a",)),
375 [self.foo1, self.foo2],
376 )
377 self.assertChoicesEqual(
378 self.field.get_choices(include_blank=False, ordering=("-a",)),
379 [self.foo2, self.foo1],
380 )
381
382 def test_get_choices_default_ordering(self):
383 self.addCleanup(setattr, Foo._meta, "ordering", Foo._meta.ordering)
384 Foo._meta.ordering = ("d",)
385 self.assertChoicesEqual(
386 self.field.get_choices(include_blank=False), [self.foo2, self.foo1]
387 )
388
389 def test_get_choices_reverse_related_field(self):
390 self.assertChoicesEqual(
391 self.field.remote_field.get_choices(include_blank=False, ordering=("a",)),
392 [self.bar1, self.bar2],
393 )
394 self.assertChoicesEqual(
395 self.field.remote_field.get_choices(include_blank=False, ordering=("-a",)),
396 [self.bar2, self.bar1],
397 )
398
399 def test_get_choices_reverse_related_field_default_ordering(self):
400 self.addCleanup(setattr, Bar._meta, "ordering", Bar._meta.ordering)
401 Bar._meta.ordering = ("b",)
402 self.assertChoicesEqual(
403 self.field.remote_field.get_choices(include_blank=False),
404 [self.bar2, self.bar1],
405 )
406
407
408 class GetChoicesLimitChoicesToTests(TestCase):
409 @classmethod
410 def setUpTestData(cls):
411 cls.foo1 = Foo.objects.create(a="a", d="12.34")
412 cls.foo2 = Foo.objects.create(a="b", d="12.34")
413 cls.bar1 = Bar.objects.create(a=cls.foo1, b="b")
414 cls.bar2 = Bar.objects.create(a=cls.foo2, b="a")
415 cls.field = Bar._meta.get_field("a")
416
417 def assertChoicesEqual(self, choices, objs):
418 self.assertCountEqual(choices, [(obj.pk, str(obj)) for obj in objs])
419
420 def test_get_choices(self):
421 self.assertChoicesEqual(
422 self.field.get_choices(include_blank=False, limit_choices_to={"a": "a"}),
423 [self.foo1],
424 )
425 self.assertChoicesEqual(
426 self.field.get_choices(include_blank=False, limit_choices_to={}),
427 [self.foo1, self.foo2],
428 )
429
430 def test_get_choices_reverse_related_field(self):
431 field = self.field.remote_field
432 self.assertChoicesEqual(
433 field.get_choices(include_blank=False, limit_choices_to={"b": "b"}),
434 [self.bar1],
435 )
436 self.assertChoicesEqual(
437 field.get_choices(include_blank=False, limit_choices_to={}),
438 [self.bar1, self.bar2],
439 )