tests.py 14 KB

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