PageRenderTime 113ms CodeModel.GetById 66ms app.highlight 41ms RepoModel.GetById 1ms app.codeStats 0ms

/tests/regressiontests/model_fields/tests.py

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