tests.py 15 KB

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