tests.py 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913
  1. from __future__ 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 import validators
  8. from django.core import checks
  9. from django.core.exceptions import ValidationError
  10. from django.db import connection, transaction, models, IntegrityError
  11. from django.db.models.fields import (
  12. AutoField, BigIntegerField, BinaryField, BooleanField, CharField,
  13. CommaSeparatedIntegerField, DateField, DateTimeField, DecimalField,
  14. EmailField, FilePathField, FloatField, IntegerField, IPAddressField,
  15. GenericIPAddressField, NOT_PROVIDED, NullBooleanField, PositiveIntegerField,
  16. PositiveSmallIntegerField, SlugField, SmallIntegerField, TextField,
  17. TimeField, URLField)
  18. from django.db.models.fields.files import FileField, ImageField
  19. from django.utils import six
  20. from django.utils.functional import lazy
  21. from .models import (
  22. Foo, Bar, Whiz, BigD, BigS, BigIntegerModel, Post, NullBooleanModel,
  23. BooleanModel, PrimaryKeyCharModel, DataModel, Document, RenamedField,
  24. DateTimeModel, VerboseNameField, FksToBooleans, FkToChar, FloatModel,
  25. SmallIntegerModel, IntegerModel, PositiveSmallIntegerModel, PositiveIntegerModel,
  26. WhizIter, WhizIterEmpty)
  27. class BasicFieldTests(test.TestCase):
  28. def test_show_hidden_initial(self):
  29. """
  30. Regression test for #12913. Make sure fields with choices respect
  31. show_hidden_initial as a kwarg to models.Field.formfield()
  32. """
  33. choices = [(0, 0), (1, 1)]
  34. model_field = models.Field(choices=choices)
  35. form_field = model_field.formfield(show_hidden_initial=True)
  36. self.assertTrue(form_field.show_hidden_initial)
  37. form_field = model_field.formfield(show_hidden_initial=False)
  38. self.assertFalse(form_field.show_hidden_initial)
  39. def test_nullbooleanfield_blank(self):
  40. """
  41. Regression test for #13071: NullBooleanField should not throw
  42. a validation error when given a value of None.
  43. """
  44. nullboolean = NullBooleanModel(nbfield=None)
  45. try:
  46. nullboolean.full_clean()
  47. except ValidationError as e:
  48. self.fail("NullBooleanField failed validation with value of None: %s" % e.messages)
  49. def test_field_repr(self):
  50. """
  51. Regression test for #5931: __repr__ of a field also displays its name
  52. """
  53. f = Foo._meta.get_field('a')
  54. self.assertEqual(repr(f), '<django.db.models.fields.CharField: a>')
  55. f = models.fields.CharField()
  56. self.assertEqual(repr(f), '<django.db.models.fields.CharField>')
  57. def test_field_name(self):
  58. """
  59. Regression test for #14695: explicitly defined field name overwritten
  60. by model's attribute name.
  61. """
  62. instance = RenamedField()
  63. self.assertTrue(hasattr(instance, 'get_fieldname_display'))
  64. self.assertFalse(hasattr(instance, 'get_modelname_display'))
  65. def test_field_verbose_name(self):
  66. m = VerboseNameField
  67. for i in range(1, 23):
  68. self.assertEqual(m._meta.get_field('field%d' % i).verbose_name,
  69. 'verbose field%d' % i)
  70. self.assertEqual(m._meta.get_field('id').verbose_name, 'verbose pk')
  71. def test_float_validates_object(self):
  72. instance = FloatModel(size=2.5)
  73. # Try setting float field to unsaved object
  74. instance.size = instance
  75. with transaction.atomic():
  76. with self.assertRaises(TypeError):
  77. instance.save()
  78. # Set value to valid and save
  79. instance.size = 2.5
  80. instance.save()
  81. self.assertTrue(instance.id)
  82. # Set field to object on saved instance
  83. instance.size = instance
  84. with transaction.atomic():
  85. with self.assertRaises(TypeError):
  86. instance.save()
  87. # Try setting field to object on retrieved object
  88. obj = FloatModel.objects.get(pk=instance.id)
  89. obj.size = obj
  90. with self.assertRaises(TypeError):
  91. obj.save()
  92. def test_choices_form_class(self):
  93. """Can supply a custom choices form class. Regression for #20999."""
  94. choices = [('a', 'a')]
  95. field = models.CharField(choices=choices)
  96. klass = forms.TypedMultipleChoiceField
  97. self.assertIsInstance(field.formfield(choices_form_class=klass), klass)
  98. def test_field_str(self):
  99. from django.utils.encoding import force_str
  100. f = Foo._meta.get_field('a')
  101. self.assertEqual(force_str(f), "model_fields.Foo.a")
  102. class DecimalFieldTests(test.TestCase):
  103. def test_to_python(self):
  104. f = models.DecimalField(max_digits=4, decimal_places=2)
  105. self.assertEqual(f.to_python(3), Decimal("3"))
  106. self.assertEqual(f.to_python("3.14"), Decimal("3.14"))
  107. self.assertRaises(ValidationError, f.to_python, "abc")
  108. def test_default(self):
  109. f = models.DecimalField(default=Decimal("0.00"))
  110. self.assertEqual(f.get_default(), Decimal("0.00"))
  111. def test_format(self):
  112. f = models.DecimalField(max_digits=5, decimal_places=1)
  113. self.assertEqual(f._format(f.to_python(2)), '2.0')
  114. self.assertEqual(f._format(f.to_python('2.6')), '2.6')
  115. self.assertEqual(f._format(None), None)
  116. def test_get_db_prep_lookup(self):
  117. f = models.DecimalField(max_digits=5, decimal_places=1)
  118. self.assertEqual(f.get_db_prep_lookup('exact', None, connection=connection), [None])
  119. def test_filter_with_strings(self):
  120. """
  121. We should be able to filter decimal fields using strings (#8023)
  122. """
  123. Foo.objects.create(id=1, a='abc', d=Decimal("12.34"))
  124. self.assertEqual(list(Foo.objects.filter(d='1.23')), [])
  125. def test_save_without_float_conversion(self):
  126. """
  127. Ensure decimals don't go through a corrupting float conversion during
  128. save (#5079).
  129. """
  130. bd = BigD(d="12.9")
  131. bd.save()
  132. bd = BigD.objects.get(pk=bd.pk)
  133. self.assertEqual(bd.d, Decimal("12.9"))
  134. def test_lookup_really_big_value(self):
  135. """
  136. Ensure that really big values can be used in a filter statement, even
  137. with older Python versions.
  138. """
  139. # This should not crash. That counts as a win for our purposes.
  140. Foo.objects.filter(d__gte=100000000000)
  141. class ForeignKeyTests(test.TestCase):
  142. def test_callable_default(self):
  143. """Test the use of a lazy callable for ForeignKey.default"""
  144. a = Foo.objects.create(id=1, a='abc', d=Decimal("12.34"))
  145. b = Bar.objects.create(b="bcd")
  146. self.assertEqual(b.a, a)
  147. @test.skipIfDBFeature('interprets_empty_strings_as_nulls')
  148. def test_empty_string_fk(self):
  149. """
  150. Test that foreign key values to empty strings don't get converted
  151. to None (#19299)
  152. """
  153. char_model_empty = PrimaryKeyCharModel.objects.create(string='')
  154. fk_model_empty = FkToChar.objects.create(out=char_model_empty)
  155. fk_model_empty = FkToChar.objects.select_related('out').get(id=fk_model_empty.pk)
  156. self.assertEqual(fk_model_empty.out, char_model_empty)
  157. def test_warning_when_unique_true_on_fk(self):
  158. class FKUniqueTrue(models.Model):
  159. fk_field = models.ForeignKey(Foo, unique=True)
  160. model = FKUniqueTrue()
  161. expected_warnings = [
  162. checks.Warning(
  163. 'Setting unique=True on a ForeignKey has the same effect as using a OneToOneField.',
  164. hint='ForeignKey(unique=True) is usually better served by a OneToOneField.',
  165. obj=FKUniqueTrue.fk_field.field,
  166. id='fields.W342',
  167. )
  168. ]
  169. warnings = model.check()
  170. self.assertEqual(warnings, expected_warnings)
  171. def test_related_name_converted_to_text(self):
  172. rel_name = Bar._meta.get_field('a').rel.related_name
  173. self.assertIsInstance(rel_name, six.text_type)
  174. class DateTimeFieldTests(unittest.TestCase):
  175. def test_datetimefield_to_python_usecs(self):
  176. """DateTimeField.to_python should support usecs"""
  177. f = models.DateTimeField()
  178. self.assertEqual(f.to_python('2001-01-02 03:04:05.000006'),
  179. datetime.datetime(2001, 1, 2, 3, 4, 5, 6))
  180. self.assertEqual(f.to_python('2001-01-02 03:04:05.999999'),
  181. datetime.datetime(2001, 1, 2, 3, 4, 5, 999999))
  182. def test_timefield_to_python_usecs(self):
  183. """TimeField.to_python should support usecs"""
  184. f = models.TimeField()
  185. self.assertEqual(f.to_python('01:02:03.000004'),
  186. datetime.time(1, 2, 3, 4))
  187. self.assertEqual(f.to_python('01:02:03.999999'),
  188. datetime.time(1, 2, 3, 999999))
  189. @test.skipUnlessDBFeature("supports_microsecond_precision")
  190. def test_datetimes_save_completely(self):
  191. dat = datetime.date(2014, 3, 12)
  192. datetim = datetime.datetime(2014, 3, 12, 21, 22, 23, 240000)
  193. tim = datetime.time(21, 22, 23, 240000)
  194. DateTimeModel.objects.create(d=dat, dt=datetim, t=tim)
  195. obj = DateTimeModel.objects.first()
  196. self.assertTrue(obj)
  197. self.assertEqual(obj.d, dat)
  198. self.assertEqual(obj.dt, datetim)
  199. self.assertEqual(obj.t, tim)
  200. class BooleanFieldTests(unittest.TestCase):
  201. def _test_get_db_prep_lookup(self, f):
  202. self.assertEqual(f.get_db_prep_lookup('exact', True, connection=connection), [True])
  203. self.assertEqual(f.get_db_prep_lookup('exact', '1', connection=connection), [True])
  204. self.assertEqual(f.get_db_prep_lookup('exact', 1, connection=connection), [True])
  205. self.assertEqual(f.get_db_prep_lookup('exact', False, connection=connection), [False])
  206. self.assertEqual(f.get_db_prep_lookup('exact', '0', connection=connection), [False])
  207. self.assertEqual(f.get_db_prep_lookup('exact', 0, connection=connection), [False])
  208. self.assertEqual(f.get_db_prep_lookup('exact', None, connection=connection), [None])
  209. def _test_to_python(self, f):
  210. self.assertIs(f.to_python(1), True)
  211. self.assertIs(f.to_python(0), False)
  212. def test_booleanfield_get_db_prep_lookup(self):
  213. self._test_get_db_prep_lookup(models.BooleanField())
  214. def test_nullbooleanfield_get_db_prep_lookup(self):
  215. self._test_get_db_prep_lookup(models.NullBooleanField())
  216. def test_booleanfield_to_python(self):
  217. self._test_to_python(models.BooleanField())
  218. def test_nullbooleanfield_to_python(self):
  219. self._test_to_python(models.NullBooleanField())
  220. def test_charfield_textfield_max_length_passed_to_formfield(self):
  221. """
  222. Test that CharField and TextField pass their max_length attributes to
  223. form fields created using their .formfield() method (#22206).
  224. """
  225. cf1 = models.CharField()
  226. cf2 = models.CharField(max_length=1234)
  227. self.assertIsNone(cf1.formfield().max_length)
  228. self.assertEqual(1234, cf2.formfield().max_length)
  229. tf1 = models.TextField()
  230. tf2 = models.TextField(max_length=2345)
  231. self.assertIsNone(tf1.formfield().max_length)
  232. self.assertEqual(2345, tf2.formfield().max_length)
  233. def test_booleanfield_choices_blank(self):
  234. """
  235. Test that BooleanField with choices and defaults doesn't generate a
  236. formfield with the blank option (#9640, #10549).
  237. """
  238. choices = [(1, 'Si'), (2, 'No')]
  239. f = models.BooleanField(choices=choices, default=1, null=False)
  240. self.assertEqual(f.formfield().choices, choices)
  241. def test_return_type(self):
  242. b = BooleanModel()
  243. b.bfield = True
  244. b.save()
  245. b2 = BooleanModel.objects.get(pk=b.pk)
  246. self.assertIsInstance(b2.bfield, bool)
  247. self.assertEqual(b2.bfield, True)
  248. b3 = BooleanModel()
  249. b3.bfield = False
  250. b3.save()
  251. b4 = BooleanModel.objects.get(pk=b3.pk)
  252. self.assertIsInstance(b4.bfield, bool)
  253. self.assertEqual(b4.bfield, False)
  254. b = NullBooleanModel()
  255. b.nbfield = True
  256. b.save()
  257. b2 = NullBooleanModel.objects.get(pk=b.pk)
  258. self.assertIsInstance(b2.nbfield, bool)
  259. self.assertEqual(b2.nbfield, True)
  260. b3 = NullBooleanModel()
  261. b3.nbfield = False
  262. b3.save()
  263. b4 = NullBooleanModel.objects.get(pk=b3.pk)
  264. self.assertIsInstance(b4.nbfield, bool)
  265. self.assertEqual(b4.nbfield, False)
  266. # http://code.djangoproject.com/ticket/13293
  267. # Verify that when an extra clause exists, the boolean
  268. # conversions are applied with an offset
  269. b5 = BooleanModel.objects.all().extra(
  270. select={'string_col': 'string'})[0]
  271. self.assertNotIsInstance(b5.pk, bool)
  272. def test_select_related(self):
  273. """
  274. Test type of boolean fields when retrieved via select_related() (MySQL,
  275. #15040)
  276. """
  277. bmt = BooleanModel.objects.create(bfield=True)
  278. bmf = BooleanModel.objects.create(bfield=False)
  279. nbmt = NullBooleanModel.objects.create(nbfield=True)
  280. nbmf = NullBooleanModel.objects.create(nbfield=False)
  281. m1 = FksToBooleans.objects.create(bf=bmt, nbf=nbmt)
  282. m2 = FksToBooleans.objects.create(bf=bmf, nbf=nbmf)
  283. # Test select_related('fk_field_name')
  284. ma = FksToBooleans.objects.select_related('bf').get(pk=m1.id)
  285. # verify types -- should't be 0/1
  286. self.assertIsInstance(ma.bf.bfield, bool)
  287. self.assertIsInstance(ma.nbf.nbfield, bool)
  288. # verify values
  289. self.assertEqual(ma.bf.bfield, True)
  290. self.assertEqual(ma.nbf.nbfield, True)
  291. # Test select_related()
  292. mb = FksToBooleans.objects.select_related().get(pk=m1.id)
  293. mc = FksToBooleans.objects.select_related().get(pk=m2.id)
  294. # verify types -- shouldn't be 0/1
  295. self.assertIsInstance(mb.bf.bfield, bool)
  296. self.assertIsInstance(mb.nbf.nbfield, bool)
  297. self.assertIsInstance(mc.bf.bfield, bool)
  298. self.assertIsInstance(mc.nbf.nbfield, bool)
  299. # verify values
  300. self.assertEqual(mb.bf.bfield, True)
  301. self.assertEqual(mb.nbf.nbfield, True)
  302. self.assertEqual(mc.bf.bfield, False)
  303. self.assertEqual(mc.nbf.nbfield, False)
  304. def test_null_default(self):
  305. """
  306. Check that a BooleanField defaults to None -- which isn't
  307. a valid value (#15124).
  308. """
  309. # Patch the boolean field's default value. We give it a default
  310. # value when defining the model to satisfy the check tests
  311. # #20895.
  312. boolean_field = BooleanModel._meta.get_field('bfield')
  313. self.assertTrue(boolean_field.has_default())
  314. old_default = boolean_field.default
  315. try:
  316. boolean_field.default = NOT_PROVIDED
  317. # check patch was successful
  318. self.assertFalse(boolean_field.has_default())
  319. b = BooleanModel()
  320. self.assertIsNone(b.bfield)
  321. with self.assertRaises(IntegrityError):
  322. b.save()
  323. finally:
  324. boolean_field.default = old_default
  325. nb = NullBooleanModel()
  326. self.assertIsNone(nb.nbfield)
  327. nb.save() # no error
  328. class ChoicesTests(test.TestCase):
  329. def test_choices_and_field_display(self):
  330. """
  331. Check that get_choices and get_flatchoices interact with
  332. get_FIELD_display to return the expected values (#7913).
  333. """
  334. self.assertEqual(Whiz(c=1).get_c_display(), 'First') # A nested value
  335. self.assertEqual(Whiz(c=0).get_c_display(), 'Other') # A top level value
  336. self.assertEqual(Whiz(c=9).get_c_display(), 9) # Invalid value
  337. self.assertEqual(Whiz(c=None).get_c_display(), None) # Blank value
  338. self.assertEqual(Whiz(c='').get_c_display(), '') # Empty value
  339. def test_iterator_choices(self):
  340. """
  341. Check that get_choices works with Iterators (#23112).
  342. """
  343. self.assertEqual(WhizIter(c=1).c, 1) # A nested value
  344. self.assertEqual(WhizIter(c=9).c, 9) # Invalid value
  345. self.assertEqual(WhizIter(c=None).c, None) # Blank value
  346. self.assertEqual(WhizIter(c='').c, '') # Empty value
  347. def test_empty_iterator_choices(self):
  348. """
  349. Check that get_choices works with empty iterators (#23112).
  350. """
  351. self.assertEqual(WhizIterEmpty(c="a").c, "a") # A nested value
  352. self.assertEqual(WhizIterEmpty(c="b").c, "b") # Invalid value
  353. self.assertEqual(WhizIterEmpty(c=None).c, None) # Blank value
  354. self.assertEqual(WhizIterEmpty(c='').c, '') # Empty value
  355. def test_charfield_get_choices_with_blank_iterator(self):
  356. """
  357. Check that get_choices works with an empty Iterator
  358. """
  359. f = models.CharField(choices=(x for x in []))
  360. self.assertEqual(f.get_choices(include_blank=True), [('', '---------')])
  361. class SlugFieldTests(test.TestCase):
  362. def test_slugfield_max_length(self):
  363. """
  364. Make sure SlugField honors max_length (#9706)
  365. """
  366. bs = BigS.objects.create(s='slug' * 50)
  367. bs = BigS.objects.get(pk=bs.pk)
  368. self.assertEqual(bs.s, 'slug' * 50)
  369. class ValidationTest(test.TestCase):
  370. def test_charfield_raises_error_on_empty_string(self):
  371. f = models.CharField()
  372. self.assertRaises(ValidationError, f.clean, "", None)
  373. def test_charfield_cleans_empty_string_when_blank_true(self):
  374. f = models.CharField(blank=True)
  375. self.assertEqual('', f.clean('', None))
  376. def test_integerfield_cleans_valid_string(self):
  377. f = models.IntegerField()
  378. self.assertEqual(2, f.clean('2', None))
  379. def test_integerfield_raises_error_on_invalid_intput(self):
  380. f = models.IntegerField()
  381. self.assertRaises(ValidationError, f.clean, "a", None)
  382. def test_charfield_with_choices_cleans_valid_choice(self):
  383. f = models.CharField(max_length=1,
  384. choices=[('a', 'A'), ('b', 'B')])
  385. self.assertEqual('a', f.clean('a', None))
  386. def test_charfield_with_choices_raises_error_on_invalid_choice(self):
  387. f = models.CharField(choices=[('a', 'A'), ('b', 'B')])
  388. self.assertRaises(ValidationError, f.clean, "not a", None)
  389. def test_charfield_get_choices_with_blank_defined(self):
  390. f = models.CharField(choices=[('', '<><>'), ('a', 'A')])
  391. self.assertEqual(f.get_choices(True), [('', '<><>'), ('a', 'A')])
  392. def test_charfield_get_choices_doesnt_evaluate_lazy_strings(self):
  393. # Regression test for #23098
  394. # Will raise ZeroDivisionError if lazy is evaluated
  395. lazy_func = lazy(lambda x: 0 / 0, int)
  396. f = models.CharField(choices=[(lazy_func('group'), (('a', 'A'), ('b', 'B')))])
  397. self.assertEqual(f.get_choices(True)[0], ('', '---------'))
  398. def test_choices_validation_supports_named_groups(self):
  399. f = models.IntegerField(
  400. choices=(('group', ((10, 'A'), (20, 'B'))), (30, 'C')))
  401. self.assertEqual(10, f.clean(10, None))
  402. def test_nullable_integerfield_raises_error_with_blank_false(self):
  403. f = models.IntegerField(null=True, blank=False)
  404. self.assertRaises(ValidationError, f.clean, None, None)
  405. def test_nullable_integerfield_cleans_none_on_null_and_blank_true(self):
  406. f = models.IntegerField(null=True, blank=True)
  407. self.assertEqual(None, f.clean(None, None))
  408. def test_integerfield_raises_error_on_empty_input(self):
  409. f = models.IntegerField(null=False)
  410. self.assertRaises(ValidationError, f.clean, None, None)
  411. self.assertRaises(ValidationError, f.clean, '', None)
  412. def test_integerfield_validates_zero_against_choices(self):
  413. f = models.IntegerField(choices=((1, 1),))
  414. self.assertRaises(ValidationError, f.clean, '0', None)
  415. def test_charfield_raises_error_on_empty_input(self):
  416. f = models.CharField(null=False)
  417. self.assertRaises(ValidationError, f.clean, None, None)
  418. def test_datefield_cleans_date(self):
  419. f = models.DateField()
  420. self.assertEqual(datetime.date(2008, 10, 10), f.clean('2008-10-10', None))
  421. def test_boolean_field_doesnt_accept_empty_input(self):
  422. f = models.BooleanField()
  423. self.assertRaises(ValidationError, f.clean, None, None)
  424. class IntegerFieldTests(test.TestCase):
  425. model = IntegerModel
  426. documented_range = (-2147483648, 2147483647)
  427. def test_documented_range(self):
  428. """
  429. Ensure that values within the documented safe range pass validation,
  430. can be saved and retrieved without corruption.
  431. """
  432. min_value, max_value = self.documented_range
  433. instance = self.model(value=min_value)
  434. instance.full_clean()
  435. instance.save()
  436. qs = self.model.objects.filter(value__lte=min_value)
  437. self.assertEqual(qs.count(), 1)
  438. self.assertEqual(qs[0].value, min_value)
  439. instance = self.model(value=max_value)
  440. instance.full_clean()
  441. instance.save()
  442. qs = self.model.objects.filter(value__gte=max_value)
  443. self.assertEqual(qs.count(), 1)
  444. self.assertEqual(qs[0].value, max_value)
  445. def test_backend_range_validation(self):
  446. """
  447. Ensure that backend specific range are enforced at the model
  448. validation level. ref #12030.
  449. """
  450. field = self.model._meta.get_field('value')
  451. internal_type = field.get_internal_type()
  452. min_value, max_value = connection.ops.integer_field_range(internal_type)
  453. if min_value is not None:
  454. instance = self.model(value=min_value - 1)
  455. expected_message = validators.MinValueValidator.message % {
  456. 'limit_value': min_value
  457. }
  458. with self.assertRaisesMessage(ValidationError, expected_message):
  459. instance.full_clean()
  460. instance.value = min_value
  461. instance.full_clean()
  462. if max_value is not None:
  463. instance = self.model(value=max_value + 1)
  464. expected_message = validators.MaxValueValidator.message % {
  465. 'limit_value': max_value
  466. }
  467. with self.assertRaisesMessage(ValidationError, expected_message):
  468. instance.full_clean()
  469. instance.value = max_value
  470. instance.full_clean()
  471. def test_types(self):
  472. instance = self.model(value=0)
  473. self.assertIsInstance(instance.value, six.integer_types)
  474. instance.save()
  475. self.assertIsInstance(instance.value, six.integer_types)
  476. instance = self.model.objects.get()
  477. self.assertIsInstance(instance.value, six.integer_types)
  478. def test_coercing(self):
  479. self.model.objects.create(value='10')
  480. instance = self.model.objects.get(value='10')
  481. self.assertEqual(instance.value, 10)
  482. class SmallIntegerFieldTests(IntegerFieldTests):
  483. model = SmallIntegerModel
  484. documented_range = (-32768, 32767)
  485. class BigIntegerFieldTests(IntegerFieldTests):
  486. model = BigIntegerModel
  487. documented_range = (-9223372036854775808, 9223372036854775807)
  488. class PositiveSmallIntegerFieldTests(IntegerFieldTests):
  489. model = PositiveSmallIntegerModel
  490. documented_range = (0, 32767)
  491. class PositiveIntegerFieldTests(IntegerFieldTests):
  492. model = PositiveIntegerModel
  493. documented_range = (0, 2147483647)
  494. class TypeCoercionTests(test.TestCase):
  495. """
  496. Test that database lookups can accept the wrong types and convert
  497. them with no error: especially on Postgres 8.3+ which does not do
  498. automatic casting at the DB level. See #10015.
  499. """
  500. def test_lookup_integer_in_charfield(self):
  501. self.assertEqual(Post.objects.filter(title=9).count(), 0)
  502. def test_lookup_integer_in_textfield(self):
  503. self.assertEqual(Post.objects.filter(body=24).count(), 0)
  504. class FileFieldTests(unittest.TestCase):
  505. def test_clearable(self):
  506. """
  507. Test that FileField.save_form_data will clear its instance attribute
  508. value if passed False.
  509. """
  510. d = Document(myfile='something.txt')
  511. self.assertEqual(d.myfile, 'something.txt')
  512. field = d._meta.get_field('myfile')
  513. field.save_form_data(d, False)
  514. self.assertEqual(d.myfile, '')
  515. def test_unchanged(self):
  516. """
  517. Test that FileField.save_form_data considers None to mean "no change"
  518. rather than "clear".
  519. """
  520. d = Document(myfile='something.txt')
  521. self.assertEqual(d.myfile, 'something.txt')
  522. field = d._meta.get_field('myfile')
  523. field.save_form_data(d, None)
  524. self.assertEqual(d.myfile, 'something.txt')
  525. def test_changed(self):
  526. """
  527. Test that FileField.save_form_data, if passed a truthy value, updates
  528. its instance attribute.
  529. """
  530. d = Document(myfile='something.txt')
  531. self.assertEqual(d.myfile, 'something.txt')
  532. field = d._meta.get_field('myfile')
  533. field.save_form_data(d, 'else.txt')
  534. self.assertEqual(d.myfile, 'else.txt')
  535. def test_delete_when_file_unset(self):
  536. """
  537. Calling delete on an unset FileField should not call the file deletion
  538. process, but fail silently (#20660).
  539. """
  540. d = Document()
  541. try:
  542. d.myfile.delete()
  543. except OSError:
  544. self.fail("Deleting an unset FileField should not raise OSError.")
  545. class BinaryFieldTests(test.TestCase):
  546. binary_data = b'\x00\x46\xFE'
  547. @test.skipUnlessDBFeature('supports_binary_field')
  548. def test_set_and_retrieve(self):
  549. data_set = (self.binary_data, six.memoryview(self.binary_data))
  550. for bdata in data_set:
  551. dm = DataModel(data=bdata)
  552. dm.save()
  553. dm = DataModel.objects.get(pk=dm.pk)
  554. self.assertEqual(bytes(dm.data), bytes(bdata))
  555. # Resave (=update)
  556. dm.save()
  557. dm = DataModel.objects.get(pk=dm.pk)
  558. self.assertEqual(bytes(dm.data), bytes(bdata))
  559. # Test default value
  560. self.assertEqual(bytes(dm.short_data), b'\x08')
  561. def test_max_length(self):
  562. dm = DataModel(short_data=self.binary_data * 4)
  563. self.assertRaises(ValidationError, dm.full_clean)
  564. class GenericIPAddressFieldTests(test.TestCase):
  565. def test_genericipaddressfield_formfield_protocol(self):
  566. """
  567. Test that GenericIPAddressField with a specified protocol does not
  568. generate a formfield with no specified protocol. See #20740.
  569. """
  570. model_field = models.GenericIPAddressField(protocol='IPv4')
  571. form_field = model_field.formfield()
  572. self.assertRaises(ValidationError, form_field.clean, '::1')
  573. model_field = models.GenericIPAddressField(protocol='IPv6')
  574. form_field = model_field.formfield()
  575. self.assertRaises(ValidationError, form_field.clean, '127.0.0.1')
  576. class PromiseTest(test.TestCase):
  577. def test_AutoField(self):
  578. lazy_func = lazy(lambda: 1, int)
  579. self.assertIsInstance(
  580. AutoField(primary_key=True).get_prep_value(lazy_func()),
  581. int)
  582. @unittest.skipIf(six.PY3, "Python 3 has no `long` type.")
  583. def test_BigIntegerField(self):
  584. lazy_func = lazy(lambda: long(9999999999999999999), long)
  585. self.assertIsInstance(
  586. BigIntegerField().get_prep_value(lazy_func()),
  587. long)
  588. def test_BinaryField(self):
  589. lazy_func = lazy(lambda: b'', bytes)
  590. self.assertIsInstance(
  591. BinaryField().get_prep_value(lazy_func()),
  592. bytes)
  593. def test_BooleanField(self):
  594. lazy_func = lazy(lambda: True, bool)
  595. self.assertIsInstance(
  596. BooleanField().get_prep_value(lazy_func()),
  597. bool)
  598. def test_CharField(self):
  599. lazy_func = lazy(lambda: '', six.text_type)
  600. self.assertIsInstance(
  601. CharField().get_prep_value(lazy_func()),
  602. six.text_type)
  603. lazy_func = lazy(lambda: 0, int)
  604. self.assertIsInstance(
  605. CharField().get_prep_value(lazy_func()),
  606. six.text_type)
  607. def test_CommaSeparatedIntegerField(self):
  608. lazy_func = lazy(lambda: '1,2', six.text_type)
  609. self.assertIsInstance(
  610. CommaSeparatedIntegerField().get_prep_value(lazy_func()),
  611. six.text_type)
  612. lazy_func = lazy(lambda: 0, int)
  613. self.assertIsInstance(
  614. CommaSeparatedIntegerField().get_prep_value(lazy_func()),
  615. six.text_type)
  616. def test_DateField(self):
  617. lazy_func = lazy(lambda: datetime.date.today(), datetime.date)
  618. self.assertIsInstance(
  619. DateField().get_prep_value(lazy_func()),
  620. datetime.date)
  621. def test_DateTimeField(self):
  622. lazy_func = lazy(lambda: datetime.datetime.now(), datetime.datetime)
  623. self.assertIsInstance(
  624. DateTimeField().get_prep_value(lazy_func()),
  625. datetime.datetime)
  626. def test_DecimalField(self):
  627. lazy_func = lazy(lambda: Decimal('1.2'), Decimal)
  628. self.assertIsInstance(
  629. DecimalField().get_prep_value(lazy_func()),
  630. Decimal)
  631. def test_EmailField(self):
  632. lazy_func = lazy(lambda: 'mailbox@domain.com', six.text_type)
  633. self.assertIsInstance(
  634. EmailField().get_prep_value(lazy_func()),
  635. six.text_type)
  636. def test_FileField(self):
  637. lazy_func = lazy(lambda: 'filename.ext', six.text_type)
  638. self.assertIsInstance(
  639. FileField().get_prep_value(lazy_func()),
  640. six.text_type)
  641. lazy_func = lazy(lambda: 0, int)
  642. self.assertIsInstance(
  643. FileField().get_prep_value(lazy_func()),
  644. six.text_type)
  645. def test_FilePathField(self):
  646. lazy_func = lazy(lambda: 'tests.py', six.text_type)
  647. self.assertIsInstance(
  648. FilePathField().get_prep_value(lazy_func()),
  649. six.text_type)
  650. lazy_func = lazy(lambda: 0, int)
  651. self.assertIsInstance(
  652. FilePathField().get_prep_value(lazy_func()),
  653. six.text_type)
  654. def test_FloatField(self):
  655. lazy_func = lazy(lambda: 1.2, float)
  656. self.assertIsInstance(
  657. FloatField().get_prep_value(lazy_func()),
  658. float)
  659. def test_ImageField(self):
  660. lazy_func = lazy(lambda: 'filename.ext', six.text_type)
  661. self.assertIsInstance(
  662. ImageField().get_prep_value(lazy_func()),
  663. six.text_type)
  664. def test_IntegerField(self):
  665. lazy_func = lazy(lambda: 1, int)
  666. self.assertIsInstance(
  667. IntegerField().get_prep_value(lazy_func()),
  668. int)
  669. def test_IPAddressField(self):
  670. lazy_func = lazy(lambda: '127.0.0.1', six.text_type)
  671. self.assertIsInstance(
  672. IPAddressField().get_prep_value(lazy_func()),
  673. six.text_type)
  674. lazy_func = lazy(lambda: 0, int)
  675. self.assertIsInstance(
  676. IPAddressField().get_prep_value(lazy_func()),
  677. six.text_type)
  678. def test_IPAddressField_deprecated(self):
  679. class IPAddressModel(models.Model):
  680. ip = IPAddressField()
  681. model = IPAddressModel()
  682. self.assertEqual(
  683. model.check(),
  684. [checks.Warning(
  685. 'IPAddressField has been deprecated. Support for it '
  686. '(except in historical migrations) will be removed in Django 1.9.',
  687. hint='Use GenericIPAddressField instead.',
  688. obj=IPAddressModel._meta.get_field('ip'),
  689. id='fields.W900',
  690. )],
  691. )
  692. def test_GenericIPAddressField(self):
  693. lazy_func = lazy(lambda: '127.0.0.1', six.text_type)
  694. self.assertIsInstance(
  695. GenericIPAddressField().get_prep_value(lazy_func()),
  696. six.text_type)
  697. lazy_func = lazy(lambda: 0, int)
  698. self.assertIsInstance(
  699. GenericIPAddressField().get_prep_value(lazy_func()),
  700. six.text_type)
  701. def test_NullBooleanField(self):
  702. lazy_func = lazy(lambda: True, bool)
  703. self.assertIsInstance(
  704. NullBooleanField().get_prep_value(lazy_func()),
  705. bool)
  706. def test_PositiveIntegerField(self):
  707. lazy_func = lazy(lambda: 1, int)
  708. self.assertIsInstance(
  709. PositiveIntegerField().get_prep_value(lazy_func()),
  710. int)
  711. def test_PositiveSmallIntegerField(self):
  712. lazy_func = lazy(lambda: 1, int)
  713. self.assertIsInstance(
  714. PositiveSmallIntegerField().get_prep_value(lazy_func()),
  715. int)
  716. def test_SlugField(self):
  717. lazy_func = lazy(lambda: 'slug', six.text_type)
  718. self.assertIsInstance(
  719. SlugField().get_prep_value(lazy_func()),
  720. six.text_type)
  721. lazy_func = lazy(lambda: 0, int)
  722. self.assertIsInstance(
  723. SlugField().get_prep_value(lazy_func()),
  724. six.text_type)
  725. def test_SmallIntegerField(self):
  726. lazy_func = lazy(lambda: 1, int)
  727. self.assertIsInstance(
  728. SmallIntegerField().get_prep_value(lazy_func()),
  729. int)
  730. def test_TextField(self):
  731. lazy_func = lazy(lambda: 'Abc', six.text_type)
  732. self.assertIsInstance(
  733. TextField().get_prep_value(lazy_func()),
  734. six.text_type)
  735. lazy_func = lazy(lambda: 0, int)
  736. self.assertIsInstance(
  737. TextField().get_prep_value(lazy_func()),
  738. six.text_type)
  739. def test_TimeField(self):
  740. lazy_func = lazy(lambda: datetime.datetime.now().time(), datetime.time)
  741. self.assertIsInstance(
  742. TimeField().get_prep_value(lazy_func()),
  743. datetime.time)
  744. def test_URLField(self):
  745. lazy_func = lazy(lambda: 'http://domain.com', six.text_type)
  746. self.assertIsInstance(
  747. URLField().get_prep_value(lazy_func()),
  748. six.text_type)
  749. class CustomFieldTests(unittest.TestCase):
  750. def test_14786(self):
  751. """
  752. Regression test for #14786 -- Test that field values are not prepared
  753. twice in get_db_prep_lookup().
  754. """
  755. class NoopField(models.TextField):
  756. def __init__(self, *args, **kwargs):
  757. self.prep_value_count = 0
  758. super(NoopField, self).__init__(*args, **kwargs)
  759. def get_prep_value(self, value):
  760. self.prep_value_count += 1
  761. return super(NoopField, self).get_prep_value(value)
  762. field = NoopField()
  763. field.get_db_prep_lookup(
  764. 'exact', 'TEST', connection=connection, prepared=False
  765. )
  766. self.assertEqual(field.prep_value_count, 1)