tests.py 26 KB

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