PageRenderTime 49ms CodeModel.GetById 15ms RepoModel.GetById 0ms app.codeStats 0ms

/tests/regressiontests/model_fields/tests.py

https://github.com/Tippr/django
Python | 364 lines | 337 code | 9 blank | 18 comment | 3 complexity | a228514a9c69a3a9265a267ded94031f MD5 | raw file
  1. import datetime
  2. from decimal import Decimal
  3. from django import test
  4. from django import forms
  5. from django.core.exceptions import ValidationError
  6. from django.db import models
  7. from django.db.models.fields.files import FieldFile
  8. from django.utils import unittest
  9. from models import Foo, Bar, Whiz, BigD, BigS, Image, BigInt, Post, NullBooleanModel, BooleanModel, Document, RenamedField
  10. # If PIL available, do these tests.
  11. if Image:
  12. from imagefield import (
  13. ImageFieldTests, ImageFieldTwoDimensionsTests, TwoImageFieldTests,
  14. ImageFieldNoDimensionsTests, ImageFieldOneDimensionTests,
  15. ImageFieldDimensionsFirstTests, ImageFieldUsingFileTests)
  16. class BasicFieldTests(test.TestCase):
  17. def test_show_hidden_initial(self):
  18. """
  19. Regression test for #12913. Make sure fields with choices respect
  20. show_hidden_initial as a kwarg to models.Field.formfield()
  21. """
  22. choices = [(0, 0), (1, 1)]
  23. model_field = models.Field(choices=choices)
  24. form_field = model_field.formfield(show_hidden_initial=True)
  25. self.assertTrue(form_field.show_hidden_initial)
  26. form_field = model_field.formfield(show_hidden_initial=False)
  27. self.assertFalse(form_field.show_hidden_initial)
  28. def test_nullbooleanfield_blank(self):
  29. """
  30. Regression test for #13071: NullBooleanField should not throw
  31. a validation error when given a value of None.
  32. """
  33. nullboolean = NullBooleanModel(nbfield=None)
  34. try:
  35. nullboolean.full_clean()
  36. except ValidationError, e:
  37. self.fail("NullBooleanField failed validation with value of None: %s" % e.messages)
  38. def test_field_repr(self):
  39. """
  40. Regression test for #5931: __repr__ of a field also displays its name
  41. """
  42. f = Foo._meta.get_field('a')
  43. self.assertEqual(repr(f), '<django.db.models.fields.CharField: a>')
  44. f = models.fields.CharField()
  45. self.assertEqual(repr(f), '<django.db.models.fields.CharField>')
  46. def test_field_name(self):
  47. """
  48. Regression test for #14695: explicitly defined field name overwritten
  49. by model's attribute name.
  50. """
  51. instance = RenamedField()
  52. self.assertTrue(hasattr(instance, 'get_fieldname_display'))
  53. self.assertFalse(hasattr(instance, 'get_modelname_display'))
  54. class DecimalFieldTests(test.TestCase):
  55. def test_to_python(self):
  56. f = models.DecimalField(max_digits=4, decimal_places=2)
  57. self.assertEqual(f.to_python(3), Decimal("3"))
  58. self.assertEqual(f.to_python("3.14"), Decimal("3.14"))
  59. self.assertRaises(ValidationError, f.to_python, "abc")
  60. def test_default(self):
  61. f = models.DecimalField(default=Decimal("0.00"))
  62. self.assertEqual(f.get_default(), Decimal("0.00"))
  63. def test_format(self):
  64. f = models.DecimalField(max_digits=5, decimal_places=1)
  65. self.assertEqual(f._format(f.to_python(2)), u'2.0')
  66. self.assertEqual(f._format(f.to_python('2.6')), u'2.6')
  67. self.assertEqual(f._format(None), None)
  68. def test_get_db_prep_lookup(self):
  69. from django.db import connection
  70. f = models.DecimalField(max_digits=5, decimal_places=1)
  71. self.assertEqual(f.get_db_prep_lookup('exact', None, connection=connection), [None])
  72. def test_filter_with_strings(self):
  73. """
  74. We should be able to filter decimal fields using strings (#8023)
  75. """
  76. Foo.objects.create(id=1, a='abc', d=Decimal("12.34"))
  77. self.assertEqual(list(Foo.objects.filter(d=u'1.23')), [])
  78. def test_save_without_float_conversion(self):
  79. """
  80. Ensure decimals don't go through a corrupting float conversion during
  81. save (#5079).
  82. """
  83. bd = BigD(d="12.9")
  84. bd.save()
  85. bd = BigD.objects.get(pk=bd.pk)
  86. self.assertEqual(bd.d, Decimal("12.9"))
  87. def test_lookup_really_big_value(self):
  88. """
  89. Ensure that really big values can be used in a filter statement, even
  90. with older Python versions.
  91. """
  92. # This should not crash. That counts as a win for our purposes.
  93. Foo.objects.filter(d__gte=100000000000)
  94. class ForeignKeyTests(test.TestCase):
  95. def test_callable_default(self):
  96. """Test the use of a lazy callable for ForeignKey.default"""
  97. a = Foo.objects.create(id=1, a='abc', d=Decimal("12.34"))
  98. b = Bar.objects.create(b="bcd")
  99. self.assertEqual(b.a, a)
  100. class DateTimeFieldTests(unittest.TestCase):
  101. def test_datetimefield_to_python_usecs(self):
  102. """DateTimeField.to_python should support usecs"""
  103. f = models.DateTimeField()
  104. self.assertEqual(f.to_python('2001-01-02 03:04:05.000006'),
  105. datetime.datetime(2001, 1, 2, 3, 4, 5, 6))
  106. self.assertEqual(f.to_python('2001-01-02 03:04:05.999999'),
  107. datetime.datetime(2001, 1, 2, 3, 4, 5, 999999))
  108. def test_timefield_to_python_usecs(self):
  109. """TimeField.to_python should support usecs"""
  110. f = models.TimeField()
  111. self.assertEqual(f.to_python('01:02:03.000004'),
  112. datetime.time(1, 2, 3, 4))
  113. self.assertEqual(f.to_python('01:02:03.999999'),
  114. datetime.time(1, 2, 3, 999999))
  115. class BooleanFieldTests(unittest.TestCase):
  116. def _test_get_db_prep_lookup(self, f):
  117. from django.db import connection
  118. self.assertEqual(f.get_db_prep_lookup('exact', True, connection=connection), [True])
  119. self.assertEqual(f.get_db_prep_lookup('exact', '1', connection=connection), [True])
  120. self.assertEqual(f.get_db_prep_lookup('exact', 1, connection=connection), [True])
  121. self.assertEqual(f.get_db_prep_lookup('exact', False, connection=connection), [False])
  122. self.assertEqual(f.get_db_prep_lookup('exact', '0', connection=connection), [False])
  123. self.assertEqual(f.get_db_prep_lookup('exact', 0, connection=connection), [False])
  124. self.assertEqual(f.get_db_prep_lookup('exact', None, connection=connection), [None])
  125. def _test_to_python(self, f):
  126. self.assertTrue(f.to_python(1) is True)
  127. self.assertTrue(f.to_python(0) is False)
  128. def test_booleanfield_get_db_prep_lookup(self):
  129. self._test_get_db_prep_lookup(models.BooleanField())
  130. def test_nullbooleanfield_get_db_prep_lookup(self):
  131. self._test_get_db_prep_lookup(models.NullBooleanField())
  132. def test_booleanfield_to_python(self):
  133. self._test_to_python(models.BooleanField())
  134. def test_nullbooleanfield_to_python(self):
  135. self._test_to_python(models.NullBooleanField())
  136. def test_booleanfield_choices_blank(self):
  137. """
  138. Test that BooleanField with choices and defaults doesn't generate a
  139. formfield with the blank option (#9640, #10549).
  140. """
  141. choices = [(1, u'Si'), (2, 'No')]
  142. f = models.BooleanField(choices=choices, default=1, null=True)
  143. self.assertEqual(f.formfield().choices, [('', '---------')] + choices)
  144. f = models.BooleanField(choices=choices, default=1, null=False)
  145. self.assertEqual(f.formfield().choices, choices)
  146. def test_return_type(self):
  147. b = BooleanModel()
  148. b.bfield = True
  149. b.save()
  150. b2 = BooleanModel.objects.get(pk=b.pk)
  151. self.assertTrue(isinstance(b2.bfield, bool))
  152. self.assertEqual(b2.bfield, True)
  153. b3 = BooleanModel()
  154. b3.bfield = False
  155. b3.save()
  156. b4 = BooleanModel.objects.get(pk=b3.pk)
  157. self.assertTrue(isinstance(b4.bfield, bool))
  158. self.assertEqual(b4.bfield, False)
  159. b = NullBooleanModel()
  160. b.nbfield = True
  161. b.save()
  162. b2 = NullBooleanModel.objects.get(pk=b.pk)
  163. self.assertTrue(isinstance(b2.nbfield, bool))
  164. self.assertEqual(b2.nbfield, True)
  165. b3 = NullBooleanModel()
  166. b3.nbfield = False
  167. b3.save()
  168. b4 = NullBooleanModel.objects.get(pk=b3.pk)
  169. self.assertTrue(isinstance(b4.nbfield, bool))
  170. self.assertEqual(b4.nbfield, False)
  171. # http://code.djangoproject.com/ticket/13293
  172. # Verify that when an extra clause exists, the boolean
  173. # conversions are applied with an offset
  174. b5 = BooleanModel.objects.all().extra(
  175. select={'string_length': 'LENGTH(string)'})[0]
  176. self.assertFalse(isinstance(b5.pk, bool))
  177. class ChoicesTests(test.TestCase):
  178. def test_choices_and_field_display(self):
  179. """
  180. Check that get_choices and get_flatchoices interact with
  181. get_FIELD_display to return the expected values (#7913).
  182. """
  183. self.assertEqual(Whiz(c=1).get_c_display(), 'First') # A nested value
  184. self.assertEqual(Whiz(c=0).get_c_display(), 'Other') # A top level value
  185. self.assertEqual(Whiz(c=9).get_c_display(), 9) # Invalid value
  186. self.assertEqual(Whiz(c=None).get_c_display(), None) # Blank value
  187. self.assertEqual(Whiz(c='').get_c_display(), '') # Empty value
  188. class SlugFieldTests(test.TestCase):
  189. def test_slugfield_max_length(self):
  190. """
  191. Make sure SlugField honors max_length (#9706)
  192. """
  193. bs = BigS.objects.create(s = 'slug'*50)
  194. bs = BigS.objects.get(pk=bs.pk)
  195. self.assertEqual(bs.s, 'slug'*50)
  196. class ValidationTest(test.TestCase):
  197. def test_charfield_raises_error_on_empty_string(self):
  198. f = models.CharField()
  199. self.assertRaises(ValidationError, f.clean, "", None)
  200. def test_charfield_cleans_empty_string_when_blank_true(self):
  201. f = models.CharField(blank=True)
  202. self.assertEqual('', f.clean('', None))
  203. def test_integerfield_cleans_valid_string(self):
  204. f = models.IntegerField()
  205. self.assertEqual(2, f.clean('2', None))
  206. def test_integerfield_raises_error_on_invalid_intput(self):
  207. f = models.IntegerField()
  208. self.assertRaises(ValidationError, f.clean, "a", None)
  209. def test_charfield_with_choices_cleans_valid_choice(self):
  210. f = models.CharField(max_length=1, choices=[('a','A'), ('b','B')])
  211. self.assertEqual('a', f.clean('a', None))
  212. def test_charfield_with_choices_raises_error_on_invalid_choice(self):
  213. f = models.CharField(choices=[('a','A'), ('b','B')])
  214. self.assertRaises(ValidationError, f.clean, "not a", None)
  215. def test_choices_validation_supports_named_groups(self):
  216. f = models.IntegerField(choices=(('group',((10,'A'),(20,'B'))),(30,'C')))
  217. self.assertEqual(10, f.clean(10, None))
  218. def test_nullable_integerfield_raises_error_with_blank_false(self):
  219. f = models.IntegerField(null=True, blank=False)
  220. self.assertRaises(ValidationError, f.clean, None, None)
  221. def test_nullable_integerfield_cleans_none_on_null_and_blank_true(self):
  222. f = models.IntegerField(null=True, blank=True)
  223. self.assertEqual(None, f.clean(None, None))
  224. def test_integerfield_raises_error_on_empty_input(self):
  225. f = models.IntegerField(null=False)
  226. self.assertRaises(ValidationError, f.clean, None, None)
  227. self.assertRaises(ValidationError, f.clean, '', None)
  228. def test_charfield_raises_error_on_empty_input(self):
  229. f = models.CharField(null=False)
  230. self.assertRaises(ValidationError, f.clean, None, None)
  231. def test_datefield_cleans_date(self):
  232. f = models.DateField()
  233. self.assertEqual(datetime.date(2008, 10, 10), f.clean('2008-10-10', None))
  234. def test_boolean_field_doesnt_accept_empty_input(self):
  235. f = models.BooleanField()
  236. self.assertRaises(ValidationError, f.clean, None, None)
  237. class BigIntegerFieldTests(test.TestCase):
  238. def test_limits(self):
  239. # Ensure that values that are right at the limits can be saved
  240. # and then retrieved without corruption.
  241. maxval = 9223372036854775807
  242. minval = -maxval - 1
  243. BigInt.objects.create(value=maxval)
  244. qs = BigInt.objects.filter(value__gte=maxval)
  245. self.assertEqual(qs.count(), 1)
  246. self.assertEqual(qs[0].value, maxval)
  247. BigInt.objects.create(value=minval)
  248. qs = BigInt.objects.filter(value__lte=minval)
  249. self.assertEqual(qs.count(), 1)
  250. self.assertEqual(qs[0].value, minval)
  251. def test_types(self):
  252. b = BigInt(value = 0)
  253. self.assertTrue(isinstance(b.value, (int, long)))
  254. b.save()
  255. self.assertTrue(isinstance(b.value, (int, long)))
  256. b = BigInt.objects.all()[0]
  257. self.assertTrue(isinstance(b.value, (int, long)))
  258. def test_coercing(self):
  259. BigInt.objects.create(value ='10')
  260. b = BigInt.objects.get(value = '10')
  261. self.assertEqual(b.value, 10)
  262. class TypeCoercionTests(test.TestCase):
  263. """
  264. Test that database lookups can accept the wrong types and convert
  265. them with no error: especially on Postgres 8.3+ which does not do
  266. automatic casting at the DB level. See #10015.
  267. """
  268. def test_lookup_integer_in_charfield(self):
  269. self.assertEqual(Post.objects.filter(title=9).count(), 0)
  270. def test_lookup_integer_in_textfield(self):
  271. self.assertEqual(Post.objects.filter(body=24).count(), 0)
  272. class FileFieldTests(unittest.TestCase):
  273. def test_clearable(self):
  274. """
  275. Test that FileField.save_form_data will clear its instance attribute
  276. value if passed False.
  277. """
  278. d = Document(myfile='something.txt')
  279. self.assertEqual(d.myfile, 'something.txt')
  280. field = d._meta.get_field('myfile')
  281. field.save_form_data(d, False)
  282. self.assertEqual(d.myfile, '')
  283. def test_unchanged(self):
  284. """
  285. Test that FileField.save_form_data considers None to mean "no change"
  286. rather than "clear".
  287. """
  288. d = Document(myfile='something.txt')
  289. self.assertEqual(d.myfile, 'something.txt')
  290. field = d._meta.get_field('myfile')
  291. field.save_form_data(d, None)
  292. self.assertEqual(d.myfile, 'something.txt')
  293. def test_changed(self):
  294. """
  295. Test that FileField.save_form_data, if passed a truthy value, updates
  296. its instance attribute.
  297. """
  298. d = Document(myfile='something.txt')
  299. self.assertEqual(d.myfile, 'something.txt')
  300. field = d._meta.get_field('myfile')
  301. field.save_form_data(d, 'else.txt')
  302. self.assertEqual(d.myfile, 'else.txt')