tests.py 15 KB

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