tests.py 38 KB

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