PageRenderTime 95ms CodeModel.GetById 28ms RepoModel.GetById 2ms app.codeStats 0ms

/lib/django-1.3/tests/regressiontests/model_fields/tests.py

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