tests.py 32 KB

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