tests.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470
  1. from __future__ import absolute_import, unicode_literals
  2. import datetime
  3. from decimal import Decimal
  4. import unittest
  5. from django import test
  6. from django import forms
  7. from django.core.exceptions import ValidationError
  8. from django.db import connection, models, IntegrityError
  9. from django.db.models.fields.files import FieldFile
  10. from django.utils import six
  11. from .models import (Foo, Bar, Whiz, BigD, BigS, Image, BigInt, Post,
  12. NullBooleanModel, BooleanModel, DataModel, Document, RenamedField,
  13. VerboseNameField, FksToBooleans)
  14. class BasicFieldTests(test.TestCase):
  15. def test_show_hidden_initial(self):
  16. """
  17. Regression test for #12913. Make sure fields with choices respect
  18. show_hidden_initial as a kwarg to models.Field.formfield()
  19. """
  20. choices = [(0, 0), (1, 1)]
  21. model_field = models.Field(choices=choices)
  22. form_field = model_field.formfield(show_hidden_initial=True)
  23. self.assertTrue(form_field.show_hidden_initial)
  24. form_field = model_field.formfield(show_hidden_initial=False)
  25. self.assertFalse(form_field.show_hidden_initial)
  26. def test_nullbooleanfield_blank(self):
  27. """
  28. Regression test for #13071: NullBooleanField should not throw
  29. a validation error when given a value of None.
  30. """
  31. nullboolean = NullBooleanModel(nbfield=None)
  32. try:
  33. nullboolean.full_clean()
  34. except ValidationError as e:
  35. self.fail("NullBooleanField failed validation with value of None: %s" % e.messages)
  36. def test_field_repr(self):
  37. """
  38. Regression test for #5931: __repr__ of a field also displays its name
  39. """
  40. f = Foo._meta.get_field('a')
  41. self.assertEqual(repr(f), '<django.db.models.fields.CharField: a>')
  42. f = models.fields.CharField()
  43. self.assertEqual(repr(f), '<django.db.models.fields.CharField>')
  44. def test_field_name(self):
  45. """
  46. Regression test for #14695: explicitly defined field name overwritten
  47. by model's attribute name.
  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, 23):
  55. self.assertEqual(m._meta.get_field('field%d' % i).verbose_name,
  56. 'verbose field%d' % i)
  57. self.assertEqual(m._meta.get_field('id').verbose_name, 'verbose pk')
  58. def test_formclass_with_choices(self):
  59. # regression for 18162
  60. class CustomChoiceField(forms.TypedChoiceField):
  61. pass
  62. choices = [('a@b.cc', 'a@b.cc'), ('b@b.cc', 'b@b.cc')]
  63. field = models.CharField(choices=choices)
  64. klass = CustomChoiceField
  65. self.assertIsInstance(field.formfield(form_class=klass), klass)
  66. class DecimalFieldTests(test.TestCase):
  67. def test_to_python(self):
  68. f = models.DecimalField(max_digits=4, decimal_places=2)
  69. self.assertEqual(f.to_python(3), Decimal("3"))
  70. self.assertEqual(f.to_python("3.14"), Decimal("3.14"))
  71. self.assertRaises(ValidationError, f.to_python, "abc")
  72. def test_default(self):
  73. f = models.DecimalField(default=Decimal("0.00"))
  74. self.assertEqual(f.get_default(), Decimal("0.00"))
  75. def test_format(self):
  76. f = models.DecimalField(max_digits=5, decimal_places=1)
  77. self.assertEqual(f._format(f.to_python(2)), '2.0')
  78. self.assertEqual(f._format(f.to_python('2.6')), '2.6')
  79. self.assertEqual(f._format(None), None)
  80. def test_get_db_prep_lookup(self):
  81. from django.db import connection
  82. f = models.DecimalField(max_digits=5, decimal_places=1)
  83. self.assertEqual(f.get_db_prep_lookup('exact', None, connection=connection), [None])
  84. def test_filter_with_strings(self):
  85. """
  86. We should be able to filter decimal fields using strings (#8023)
  87. """
  88. Foo.objects.create(id=1, a='abc', d=Decimal("12.34"))
  89. self.assertEqual(list(Foo.objects.filter(d='1.23')), [])
  90. def test_save_without_float_conversion(self):
  91. """
  92. Ensure decimals don't go through a corrupting float conversion during
  93. save (#5079).
  94. """
  95. bd = BigD(d="12.9")
  96. bd.save()
  97. bd = BigD.objects.get(pk=bd.pk)
  98. self.assertEqual(bd.d, Decimal("12.9"))
  99. def test_lookup_really_big_value(self):
  100. """
  101. Ensure that really big values can be used in a filter statement, even
  102. with older Python versions.
  103. """
  104. # This should not crash. That counts as a win for our purposes.
  105. Foo.objects.filter(d__gte=100000000000)
  106. class ForeignKeyTests(test.TestCase):
  107. def test_callable_default(self):
  108. """Test the use of a lazy callable for ForeignKey.default"""
  109. a = Foo.objects.create(id=1, a='abc', d=Decimal("12.34"))
  110. b = Bar.objects.create(b="bcd")
  111. self.assertEqual(b.a, a)
  112. class DateTimeFieldTests(unittest.TestCase):
  113. def test_datetimefield_to_python_usecs(self):
  114. """DateTimeField.to_python should support usecs"""
  115. f = models.DateTimeField()
  116. self.assertEqual(f.to_python('2001-01-02 03:04:05.000006'),
  117. datetime.datetime(2001, 1, 2, 3, 4, 5, 6))
  118. self.assertEqual(f.to_python('2001-01-02 03:04:05.999999'),
  119. datetime.datetime(2001, 1, 2, 3, 4, 5, 999999))
  120. def test_timefield_to_python_usecs(self):
  121. """TimeField.to_python should support usecs"""
  122. f = models.TimeField()
  123. self.assertEqual(f.to_python('01:02:03.000004'),
  124. datetime.time(1, 2, 3, 4))
  125. self.assertEqual(f.to_python('01:02:03.999999'),
  126. datetime.time(1, 2, 3, 999999))
  127. class BooleanFieldTests(unittest.TestCase):
  128. def _test_get_db_prep_lookup(self, f):
  129. from django.db import connection
  130. self.assertEqual(f.get_db_prep_lookup('exact', True, connection=connection), [True])
  131. self.assertEqual(f.get_db_prep_lookup('exact', '1', connection=connection), [True])
  132. self.assertEqual(f.get_db_prep_lookup('exact', 1, connection=connection), [True])
  133. self.assertEqual(f.get_db_prep_lookup('exact', False, connection=connection), [False])
  134. self.assertEqual(f.get_db_prep_lookup('exact', '0', connection=connection), [False])
  135. self.assertEqual(f.get_db_prep_lookup('exact', 0, connection=connection), [False])
  136. self.assertEqual(f.get_db_prep_lookup('exact', None, connection=connection), [None])
  137. def _test_to_python(self, f):
  138. self.assertTrue(f.to_python(1) is True)
  139. self.assertTrue(f.to_python(0) is False)
  140. def test_booleanfield_get_db_prep_lookup(self):
  141. self._test_get_db_prep_lookup(models.BooleanField())
  142. def test_nullbooleanfield_get_db_prep_lookup(self):
  143. self._test_get_db_prep_lookup(models.NullBooleanField())
  144. def test_booleanfield_to_python(self):
  145. self._test_to_python(models.BooleanField())
  146. def test_nullbooleanfield_to_python(self):
  147. self._test_to_python(models.NullBooleanField())
  148. def test_booleanfield_choices_blank(self):
  149. """
  150. Test that BooleanField with choices and defaults doesn't generate a
  151. formfield with the blank option (#9640, #10549).
  152. """
  153. choices = [(1, 'Si'), (2, 'No')]
  154. f = models.BooleanField(choices=choices, default=1, null=True)
  155. self.assertEqual(f.formfield().choices, [('', '---------')] + choices)
  156. f = models.BooleanField(choices=choices, default=1, null=False)
  157. self.assertEqual(f.formfield().choices, choices)
  158. def test_return_type(self):
  159. b = BooleanModel()
  160. b.bfield = True
  161. b.save()
  162. b2 = BooleanModel.objects.get(pk=b.pk)
  163. self.assertIsInstance(b2.bfield, bool)
  164. self.assertEqual(b2.bfield, True)
  165. b3 = BooleanModel()
  166. b3.bfield = False
  167. b3.save()
  168. b4 = BooleanModel.objects.get(pk=b3.pk)
  169. self.assertIsInstance(b4.bfield, bool)
  170. self.assertEqual(b4.bfield, False)
  171. b = NullBooleanModel()
  172. b.nbfield = True
  173. b.save()
  174. b2 = NullBooleanModel.objects.get(pk=b.pk)
  175. self.assertIsInstance(b2.nbfield, bool)
  176. self.assertEqual(b2.nbfield, True)
  177. b3 = NullBooleanModel()
  178. b3.nbfield = False
  179. b3.save()
  180. b4 = NullBooleanModel.objects.get(pk=b3.pk)
  181. self.assertIsInstance(b4.nbfield, bool)
  182. self.assertEqual(b4.nbfield, False)
  183. # http://code.djangoproject.com/ticket/13293
  184. # Verify that when an extra clause exists, the boolean
  185. # conversions are applied with an offset
  186. b5 = BooleanModel.objects.all().extra(
  187. select={'string_col': 'string'})[0]
  188. self.assertFalse(isinstance(b5.pk, bool))
  189. def test_select_related(self):
  190. """
  191. Test type of boolean fields when retrieved via select_related() (MySQL,
  192. #15040)
  193. """
  194. bmt = BooleanModel.objects.create(bfield=True)
  195. bmf = BooleanModel.objects.create(bfield=False)
  196. nbmt = NullBooleanModel.objects.create(nbfield=True)
  197. nbmf = NullBooleanModel.objects.create(nbfield=False)
  198. m1 = FksToBooleans.objects.create(bf=bmt, nbf=nbmt)
  199. m2 = FksToBooleans.objects.create(bf=bmf, nbf=nbmf)
  200. # Test select_related('fk_field_name')
  201. ma = FksToBooleans.objects.select_related('bf').get(pk=m1.id)
  202. # verify types -- should't be 0/1
  203. self.assertIsInstance(ma.bf.bfield, bool)
  204. self.assertIsInstance(ma.nbf.nbfield, bool)
  205. # verify values
  206. self.assertEqual(ma.bf.bfield, True)
  207. self.assertEqual(ma.nbf.nbfield, True)
  208. # Test select_related()
  209. mb = FksToBooleans.objects.select_related().get(pk=m1.id)
  210. mc = FksToBooleans.objects.select_related().get(pk=m2.id)
  211. # verify types -- shouldn't be 0/1
  212. self.assertIsInstance(mb.bf.bfield, bool)
  213. self.assertIsInstance(mb.nbf.nbfield, bool)
  214. self.assertIsInstance(mc.bf.bfield, bool)
  215. self.assertIsInstance(mc.nbf.nbfield, bool)
  216. # verify values
  217. self.assertEqual(mb.bf.bfield, True)
  218. self.assertEqual(mb.nbf.nbfield, True)
  219. self.assertEqual(mc.bf.bfield, False)
  220. self.assertEqual(mc.nbf.nbfield, False)
  221. def test_null_default(self):
  222. """
  223. Check that a BooleanField defaults to None -- which isn't
  224. a valid value (#15124).
  225. """
  226. b = BooleanModel()
  227. self.assertIsNone(b.bfield)
  228. with self.assertRaises(IntegrityError):
  229. b.save()
  230. nb = NullBooleanModel()
  231. self.assertIsNone(nb.nbfield)
  232. nb.save() # no error
  233. class ChoicesTests(test.TestCase):
  234. def test_choices_and_field_display(self):
  235. """
  236. Check that get_choices and get_flatchoices interact with
  237. get_FIELD_display to return the expected values (#7913).
  238. """
  239. self.assertEqual(Whiz(c=1).get_c_display(), 'First') # A nested value
  240. self.assertEqual(Whiz(c=0).get_c_display(), 'Other') # A top level value
  241. self.assertEqual(Whiz(c=9).get_c_display(), 9) # Invalid value
  242. self.assertEqual(Whiz(c=None).get_c_display(), None) # Blank value
  243. self.assertEqual(Whiz(c='').get_c_display(), '') # Empty value
  244. class SlugFieldTests(test.TestCase):
  245. def test_slugfield_max_length(self):
  246. """
  247. Make sure SlugField honors max_length (#9706)
  248. """
  249. bs = BigS.objects.create(s = 'slug'*50)
  250. bs = BigS.objects.get(pk=bs.pk)
  251. self.assertEqual(bs.s, 'slug'*50)
  252. class ValidationTest(test.TestCase):
  253. def test_charfield_raises_error_on_empty_string(self):
  254. f = models.CharField()
  255. self.assertRaises(ValidationError, f.clean, "", None)
  256. def test_charfield_cleans_empty_string_when_blank_true(self):
  257. f = models.CharField(blank=True)
  258. self.assertEqual('', f.clean('', None))
  259. def test_integerfield_cleans_valid_string(self):
  260. f = models.IntegerField()
  261. self.assertEqual(2, f.clean('2', None))
  262. def test_integerfield_raises_error_on_invalid_intput(self):
  263. f = models.IntegerField()
  264. self.assertRaises(ValidationError, f.clean, "a", None)
  265. def test_charfield_with_choices_cleans_valid_choice(self):
  266. f = models.CharField(max_length=1, choices=[('a','A'), ('b','B')])
  267. self.assertEqual('a', f.clean('a', None))
  268. def test_charfield_with_choices_raises_error_on_invalid_choice(self):
  269. f = models.CharField(choices=[('a','A'), ('b','B')])
  270. self.assertRaises(ValidationError, f.clean, "not a", None)
  271. def test_choices_validation_supports_named_groups(self):
  272. f = models.IntegerField(choices=(('group',((10,'A'),(20,'B'))),(30,'C')))
  273. self.assertEqual(10, f.clean(10, None))
  274. def test_nullable_integerfield_raises_error_with_blank_false(self):
  275. f = models.IntegerField(null=True, blank=False)
  276. self.assertRaises(ValidationError, f.clean, None, None)
  277. def test_nullable_integerfield_cleans_none_on_null_and_blank_true(self):
  278. f = models.IntegerField(null=True, blank=True)
  279. self.assertEqual(None, f.clean(None, None))
  280. def test_integerfield_raises_error_on_empty_input(self):
  281. f = models.IntegerField(null=False)
  282. self.assertRaises(ValidationError, f.clean, None, None)
  283. self.assertRaises(ValidationError, f.clean, '', None)
  284. def test_integerfield_validates_zero_against_choices(self):
  285. f = models.IntegerField(choices=((1, 1),))
  286. self.assertRaises(ValidationError, f.clean, '0', None)
  287. def test_charfield_raises_error_on_empty_input(self):
  288. f = models.CharField(null=False)
  289. self.assertRaises(ValidationError, f.clean, None, None)
  290. def test_datefield_cleans_date(self):
  291. f = models.DateField()
  292. self.assertEqual(datetime.date(2008, 10, 10), f.clean('2008-10-10', None))
  293. def test_boolean_field_doesnt_accept_empty_input(self):
  294. f = models.BooleanField()
  295. self.assertRaises(ValidationError, f.clean, None, None)
  296. class BigIntegerFieldTests(test.TestCase):
  297. def test_limits(self):
  298. # Ensure that values that are right at the limits can be saved
  299. # and then retrieved without corruption.
  300. maxval = 9223372036854775807
  301. minval = -maxval - 1
  302. BigInt.objects.create(value=maxval)
  303. qs = BigInt.objects.filter(value__gte=maxval)
  304. self.assertEqual(qs.count(), 1)
  305. self.assertEqual(qs[0].value, maxval)
  306. BigInt.objects.create(value=minval)
  307. qs = BigInt.objects.filter(value__lte=minval)
  308. self.assertEqual(qs.count(), 1)
  309. self.assertEqual(qs[0].value, minval)
  310. def test_types(self):
  311. b = BigInt(value = 0)
  312. self.assertIsInstance(b.value, six.integer_types)
  313. b.save()
  314. self.assertIsInstance(b.value, six.integer_types)
  315. b = BigInt.objects.all()[0]
  316. self.assertIsInstance(b.value, six.integer_types)
  317. def test_coercing(self):
  318. BigInt.objects.create(value ='10')
  319. b = BigInt.objects.get(value = '10')
  320. self.assertEqual(b.value, 10)
  321. class TypeCoercionTests(test.TestCase):
  322. """
  323. Test that database lookups can accept the wrong types and convert
  324. them with no error: especially on Postgres 8.3+ which does not do
  325. automatic casting at the DB level. See #10015.
  326. """
  327. def test_lookup_integer_in_charfield(self):
  328. self.assertEqual(Post.objects.filter(title=9).count(), 0)
  329. def test_lookup_integer_in_textfield(self):
  330. self.assertEqual(Post.objects.filter(body=24).count(), 0)
  331. class FileFieldTests(unittest.TestCase):
  332. def test_clearable(self):
  333. """
  334. Test that FileField.save_form_data will clear its instance attribute
  335. value if passed False.
  336. """
  337. d = Document(myfile='something.txt')
  338. self.assertEqual(d.myfile, 'something.txt')
  339. field = d._meta.get_field('myfile')
  340. field.save_form_data(d, False)
  341. self.assertEqual(d.myfile, '')
  342. def test_unchanged(self):
  343. """
  344. Test that FileField.save_form_data considers None to mean "no change"
  345. rather than "clear".
  346. """
  347. d = Document(myfile='something.txt')
  348. self.assertEqual(d.myfile, 'something.txt')
  349. field = d._meta.get_field('myfile')
  350. field.save_form_data(d, None)
  351. self.assertEqual(d.myfile, 'something.txt')
  352. def test_changed(self):
  353. """
  354. Test that FileField.save_form_data, if passed a truthy value, updates
  355. its instance attribute.
  356. """
  357. d = Document(myfile='something.txt')
  358. self.assertEqual(d.myfile, 'something.txt')
  359. field = d._meta.get_field('myfile')
  360. field.save_form_data(d, 'else.txt')
  361. self.assertEqual(d.myfile, 'else.txt')
  362. def test_delete_when_file_unset(self):
  363. """
  364. Calling delete on an unset FileField should not call the file deletion
  365. process, but fail silently (#20660).
  366. """
  367. d = Document()
  368. try:
  369. d.myfile.delete()
  370. except OSError:
  371. self.fail("Deleting an unset FileField should not raise OSError.")
  372. class BinaryFieldTests(test.TestCase):
  373. binary_data = b'\x00\x46\xFE'
  374. def test_set_and_retrieve(self):
  375. data_set = (self.binary_data, six.memoryview(self.binary_data))
  376. for bdata in data_set:
  377. dm = DataModel(data=bdata)
  378. dm.save()
  379. dm = DataModel.objects.get(pk=dm.pk)
  380. self.assertEqual(bytes(dm.data), bytes(bdata))
  381. # Resave (=update)
  382. dm.save()
  383. dm = DataModel.objects.get(pk=dm.pk)
  384. self.assertEqual(bytes(dm.data), bytes(bdata))
  385. # Test default value
  386. self.assertEqual(bytes(dm.short_data), b'\x08')
  387. if connection.vendor == 'mysql' and six.PY3:
  388. # Existing MySQL DB-API drivers fail on binary data.
  389. test_set_and_retrieve = unittest.expectedFailure(test_set_and_retrieve)
  390. def test_max_length(self):
  391. dm = DataModel(short_data=self.binary_data*4)
  392. self.assertRaises(ValidationError, dm.full_clean)