~ubuntu-branches/debian/sid/python-django/sid

« back to all changes in this revision

Viewing changes to tests/model_fields/tests.py

  • Committer: Package Import Robot
  • Author(s): Raphaël Hertzog
  • Date: 2014-09-17 14:15:11 UTC
  • mfrom: (1.3.17) (6.2.18 experimental)
  • Revision ID: package-import@ubuntu.com-20140917141511-icneokthe9ww5sk4
Tags: 1.7-2
* Release to unstable.
* Add a migrate-south sample script to help users apply their South
  migrations. Thanks to Brian May.

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
from __future__ import absolute_import, unicode_literals
 
1
from __future__ import unicode_literals
2
2
 
3
3
import datetime
4
4
from decimal import Decimal
 
5
import unittest
 
6
import warnings
5
7
 
6
8
from django import test
7
9
from django import forms
 
10
from django.core import validators
8
11
from django.core.exceptions import ValidationError
9
 
from django.db import connection, models, IntegrityError
 
12
from django.db import connection, transaction, models, IntegrityError
10
13
from django.db.models.fields import (
11
14
    AutoField, BigIntegerField, BinaryField, BooleanField, CharField,
12
15
    CommaSeparatedIntegerField, DateField, DateTimeField, DecimalField,
13
16
    EmailField, FilePathField, FloatField, IntegerField, IPAddressField,
14
 
    GenericIPAddressField, NullBooleanField, PositiveIntegerField,
 
17
    GenericIPAddressField, NOT_PROVIDED, NullBooleanField, PositiveIntegerField,
15
18
    PositiveSmallIntegerField, SlugField, SmallIntegerField, TextField,
16
19
    TimeField, URLField)
17
20
from django.db.models.fields.files import FileField, ImageField
18
21
from django.utils import six
19
 
from django.utils import unittest
 
22
from django.utils.functional import lazy
20
23
 
21
 
from .models import (Foo, Bar, Whiz, BigD, BigS, Image, BigInt, Post,
22
 
    NullBooleanModel, BooleanModel, DataModel, Document, RenamedField,
23
 
    DateTimeModel, VerboseNameField, FksToBooleans)
 
24
from .models import (
 
25
    Foo, Bar, Whiz, BigD, BigS, BigIntegerModel, Post, NullBooleanModel,
 
26
    BooleanModel, PrimaryKeyCharModel, DataModel, Document, RenamedField,
 
27
    DateTimeModel, VerboseNameField, FksToBooleans, FkToChar, FloatModel,
 
28
    SmallIntegerModel, IntegerModel, PositiveSmallIntegerModel, PositiveIntegerModel,
 
29
    WhizIter, WhizIterEmpty)
24
30
 
25
31
 
26
32
class BasicFieldTests(test.TestCase):
71
77
        m = VerboseNameField
72
78
        for i in range(1, 23):
73
79
            self.assertEqual(m._meta.get_field('field%d' % i).verbose_name,
74
 
                    'verbose field%d' % i)
 
80
                             'verbose field%d' % i)
75
81
 
76
82
        self.assertEqual(m._meta.get_field('id').verbose_name, 'verbose pk')
77
83
 
 
84
    def test_float_validates_object(self):
 
85
        instance = FloatModel(size=2.5)
 
86
        # Try setting float field to unsaved object
 
87
        instance.size = instance
 
88
        with transaction.atomic():
 
89
            with self.assertRaises(TypeError):
 
90
                instance.save()
 
91
        # Set value to valid and save
 
92
        instance.size = 2.5
 
93
        instance.save()
 
94
        self.assertTrue(instance.id)
 
95
        # Set field to object on saved instance
 
96
        instance.size = instance
 
97
        with transaction.atomic():
 
98
            with self.assertRaises(TypeError):
 
99
                instance.save()
 
100
        # Try setting field to object on retrieved object
 
101
        obj = FloatModel.objects.get(pk=instance.id)
 
102
        obj.size = obj
 
103
        with self.assertRaises(TypeError):
 
104
            obj.save()
 
105
 
78
106
    def test_choices_form_class(self):
79
107
        """Can supply a custom choices form class. Regression for #20999."""
80
108
        choices = [('a', 'a')]
82
110
        klass = forms.TypedMultipleChoiceField
83
111
        self.assertIsInstance(field.formfield(choices_form_class=klass), klass)
84
112
 
 
113
    def test_field_str(self):
 
114
        from django.utils.encoding import force_str
 
115
        f = Foo._meta.get_field('a')
 
116
        self.assertEqual(force_str(f), "model_fields.Foo.a")
 
117
 
85
118
 
86
119
class DecimalFieldTests(test.TestCase):
87
120
    def test_to_python(self):
101
134
        self.assertEqual(f._format(None), None)
102
135
 
103
136
    def test_get_db_prep_lookup(self):
104
 
        from django.db import connection
105
137
        f = models.DecimalField(max_digits=5, decimal_places=1)
106
138
        self.assertEqual(f.get_db_prep_lookup('exact', None, connection=connection), [None])
107
139
 
130
162
        # This should not crash. That counts as a win for our purposes.
131
163
        Foo.objects.filter(d__gte=100000000000)
132
164
 
 
165
 
133
166
class ForeignKeyTests(test.TestCase):
134
167
    def test_callable_default(self):
135
168
        """Test the use of a lazy callable for ForeignKey.default"""
137
170
        b = Bar.objects.create(b="bcd")
138
171
        self.assertEqual(b.a, a)
139
172
 
 
173
    @test.skipIfDBFeature('interprets_empty_strings_as_nulls')
 
174
    def test_empty_string_fk(self):
 
175
        """
 
176
        Test that foreign key values to empty strings don't get converted
 
177
        to None (#19299)
 
178
        """
 
179
        char_model_empty = PrimaryKeyCharModel.objects.create(string='')
 
180
        fk_model_empty = FkToChar.objects.create(out=char_model_empty)
 
181
        fk_model_empty = FkToChar.objects.select_related('out').get(id=fk_model_empty.pk)
 
182
        self.assertEqual(fk_model_empty.out, char_model_empty)
 
183
 
 
184
 
140
185
class DateTimeFieldTests(unittest.TestCase):
141
186
    def test_datetimefield_to_python_usecs(self):
142
187
        """DateTimeField.to_python should support usecs"""
166
211
        self.assertEqual(obj.dt, datetim)
167
212
        self.assertEqual(obj.t, tim)
168
213
 
 
214
 
169
215
class BooleanFieldTests(unittest.TestCase):
170
216
    def _test_get_db_prep_lookup(self, f):
171
 
        from django.db import connection
172
217
        self.assertEqual(f.get_db_prep_lookup('exact', True, connection=connection), [True])
173
218
        self.assertEqual(f.get_db_prep_lookup('exact', '1', connection=connection), [True])
174
219
        self.assertEqual(f.get_db_prep_lookup('exact', 1, connection=connection), [True])
193
238
    def test_nullbooleanfield_to_python(self):
194
239
        self._test_to_python(models.NullBooleanField())
195
240
 
 
241
    def test_charfield_textfield_max_length_passed_to_formfield(self):
 
242
        """
 
243
        Test that CharField and TextField pass their max_length attributes to
 
244
        form fields created using their .formfield() method (#22206).
 
245
        """
 
246
        cf1 = models.CharField()
 
247
        cf2 = models.CharField(max_length=1234)
 
248
        self.assertIsNone(cf1.formfield().max_length)
 
249
        self.assertEqual(1234, cf2.formfield().max_length)
 
250
 
 
251
        tf1 = models.TextField()
 
252
        tf2 = models.TextField(max_length=2345)
 
253
        self.assertIsNone(tf1.formfield().max_length)
 
254
        self.assertEqual(2345, tf2.formfield().max_length)
 
255
 
196
256
    def test_booleanfield_choices_blank(self):
197
257
        """
198
258
        Test that BooleanField with choices and defaults doesn't generate a
289
349
        self.assertTrue(boolean_field.has_default())
290
350
        old_default = boolean_field.default
291
351
        try:
292
 
            boolean_field.default = models.NOT_PROVIDED
293
 
            # check patch was succcessful
 
352
            boolean_field.default = NOT_PROVIDED
 
353
            # check patch was successful
294
354
            self.assertFalse(boolean_field.has_default())
295
355
            b = BooleanModel()
296
356
            self.assertIsNone(b.bfield)
303
363
        self.assertIsNone(nb.nbfield)
304
364
        nb.save()           # no error
305
365
 
 
366
 
306
367
class ChoicesTests(test.TestCase):
307
368
    def test_choices_and_field_display(self):
308
369
        """
315
376
        self.assertEqual(Whiz(c=None).get_c_display(), None)    # Blank value
316
377
        self.assertEqual(Whiz(c='').get_c_display(), '')        # Empty value
317
378
 
 
379
    def test_iterator_choices(self):
 
380
        """
 
381
        Check that get_choices works with Iterators (#23112).
 
382
        """
 
383
        self.assertEqual(WhizIter(c=1).c, 1)          # A nested value
 
384
        self.assertEqual(WhizIter(c=9).c, 9)          # Invalid value
 
385
        self.assertEqual(WhizIter(c=None).c, None)    # Blank value
 
386
        self.assertEqual(WhizIter(c='').c, '')        # Empty value
 
387
 
 
388
    def test_empty_iterator_choices(self):
 
389
        """
 
390
        Check that get_choices works with empty iterators (#23112).
 
391
        """
 
392
        self.assertEqual(WhizIterEmpty(c="a").c, "a")      # A nested value
 
393
        self.assertEqual(WhizIterEmpty(c="b").c, "b")      # Invalid value
 
394
        self.assertEqual(WhizIterEmpty(c=None).c, None)    # Blank value
 
395
        self.assertEqual(WhizIterEmpty(c='').c, '')        # Empty value
 
396
 
 
397
    def test_charfield_get_choices_with_blank_iterator(self):
 
398
        """
 
399
        Check that get_choices works with an empty Iterator
 
400
        """
 
401
        f = models.CharField(choices=(x for x in []))
 
402
        self.assertEqual(f.get_choices(include_blank=True), [('', '---------')])
 
403
 
 
404
 
318
405
class SlugFieldTests(test.TestCase):
319
406
    def test_slugfield_max_length(self):
320
407
        """
321
408
        Make sure SlugField honors max_length (#9706)
322
409
        """
323
 
        bs = BigS.objects.create(s = 'slug'*50)
 
410
        bs = BigS.objects.create(s='slug' * 50)
324
411
        bs = BigS.objects.get(pk=bs.pk)
325
 
        self.assertEqual(bs.s, 'slug'*50)
 
412
        self.assertEqual(bs.s, 'slug' * 50)
326
413
 
327
414
 
328
415
class ValidationTest(test.TestCase):
343
430
        self.assertRaises(ValidationError, f.clean, "a", None)
344
431
 
345
432
    def test_charfield_with_choices_cleans_valid_choice(self):
346
 
        f = models.CharField(max_length=1, choices=[('a','A'), ('b','B')])
 
433
        f = models.CharField(max_length=1,
 
434
                             choices=[('a', 'A'), ('b', 'B')])
347
435
        self.assertEqual('a', f.clean('a', None))
348
436
 
349
437
    def test_charfield_with_choices_raises_error_on_invalid_choice(self):
350
 
        f = models.CharField(choices=[('a','A'), ('b','B')])
 
438
        f = models.CharField(choices=[('a', 'A'), ('b', 'B')])
351
439
        self.assertRaises(ValidationError, f.clean, "not a", None)
352
440
 
 
441
    def test_charfield_get_choices_with_blank_defined(self):
 
442
        f = models.CharField(choices=[('', '<><>'), ('a', 'A')])
 
443
        self.assertEqual(f.get_choices(True), [('', '<><>'), ('a', 'A')])
 
444
 
 
445
    def test_charfield_get_choices_doesnt_evaluate_lazy_strings(self):
 
446
        # Regression test for #23098
 
447
        # Will raise ZeroDivisionError if lazy is evaluated
 
448
        lazy_func = lazy(lambda x: 0 / 0, int)
 
449
        f = models.CharField(choices=[(lazy_func('group'), (('a', 'A'), ('b', 'B')))])
 
450
        self.assertEqual(f.get_choices(True)[0], ('', '---------'))
 
451
 
353
452
    def test_choices_validation_supports_named_groups(self):
354
 
        f = models.IntegerField(choices=(('group',((10,'A'),(20,'B'))),(30,'C')))
 
453
        f = models.IntegerField(
 
454
            choices=(('group', ((10, 'A'), (20, 'B'))), (30, 'C')))
355
455
        self.assertEqual(10, f.clean(10, None))
356
456
 
357
457
    def test_nullable_integerfield_raises_error_with_blank_false(self):
384
484
        self.assertRaises(ValidationError, f.clean, None, None)
385
485
 
386
486
 
387
 
class BigIntegerFieldTests(test.TestCase):
388
 
    def test_limits(self):
389
 
        # Ensure that values that are right at the limits can be saved
390
 
        # and then retrieved without corruption.
391
 
        maxval = 9223372036854775807
392
 
        minval = -maxval - 1
393
 
        BigInt.objects.create(value=maxval)
394
 
        qs = BigInt.objects.filter(value__gte=maxval)
395
 
        self.assertEqual(qs.count(), 1)
396
 
        self.assertEqual(qs[0].value, maxval)
397
 
        BigInt.objects.create(value=minval)
398
 
        qs = BigInt.objects.filter(value__lte=minval)
399
 
        self.assertEqual(qs.count(), 1)
400
 
        self.assertEqual(qs[0].value, minval)
 
487
class IntegerFieldTests(test.TestCase):
 
488
    model = IntegerModel
 
489
    documented_range = (-2147483648, 2147483647)
 
490
 
 
491
    def test_documented_range(self):
 
492
        """
 
493
        Ensure that values within the documented safe range pass validation,
 
494
        can be saved and retrieved without corruption.
 
495
        """
 
496
        min_value, max_value = self.documented_range
 
497
 
 
498
        instance = self.model(value=min_value)
 
499
        instance.full_clean()
 
500
        instance.save()
 
501
        qs = self.model.objects.filter(value__lte=min_value)
 
502
        self.assertEqual(qs.count(), 1)
 
503
        self.assertEqual(qs[0].value, min_value)
 
504
 
 
505
        instance = self.model(value=max_value)
 
506
        instance.full_clean()
 
507
        instance.save()
 
508
        qs = self.model.objects.filter(value__gte=max_value)
 
509
        self.assertEqual(qs.count(), 1)
 
510
        self.assertEqual(qs[0].value, max_value)
 
511
 
 
512
    def test_backend_range_validation(self):
 
513
        """
 
514
        Ensure that backend specific range are enforced at the model
 
515
        validation level. ref #12030.
 
516
        """
 
517
        field = self.model._meta.get_field('value')
 
518
        internal_type = field.get_internal_type()
 
519
        min_value, max_value = connection.ops.integer_field_range(internal_type)
 
520
 
 
521
        if min_value is not None:
 
522
            instance = self.model(value=min_value - 1)
 
523
            expected_message = validators.MinValueValidator.message % {
 
524
                'limit_value': min_value
 
525
            }
 
526
            with self.assertRaisesMessage(ValidationError, expected_message):
 
527
                instance.full_clean()
 
528
            instance.value = min_value
 
529
            instance.full_clean()
 
530
 
 
531
        if max_value is not None:
 
532
            instance = self.model(value=max_value + 1)
 
533
            expected_message = validators.MaxValueValidator.message % {
 
534
                'limit_value': max_value
 
535
            }
 
536
            with self.assertRaisesMessage(ValidationError, expected_message):
 
537
                instance.full_clean()
 
538
            instance.value = max_value
 
539
            instance.full_clean()
401
540
 
402
541
    def test_types(self):
403
 
        b = BigInt(value = 0)
404
 
        self.assertIsInstance(b.value, six.integer_types)
405
 
        b.save()
406
 
        self.assertIsInstance(b.value, six.integer_types)
407
 
        b = BigInt.objects.all()[0]
408
 
        self.assertIsInstance(b.value, six.integer_types)
 
542
        instance = self.model(value=0)
 
543
        self.assertIsInstance(instance.value, six.integer_types)
 
544
        instance.save()
 
545
        self.assertIsInstance(instance.value, six.integer_types)
 
546
        instance = self.model.objects.get()
 
547
        self.assertIsInstance(instance.value, six.integer_types)
409
548
 
410
549
    def test_coercing(self):
411
 
        BigInt.objects.create(value ='10')
412
 
        b = BigInt.objects.get(value = '10')
413
 
        self.assertEqual(b.value, 10)
 
550
        self.model.objects.create(value='10')
 
551
        instance = self.model.objects.get(value='10')
 
552
        self.assertEqual(instance.value, 10)
 
553
 
 
554
 
 
555
class SmallIntegerFieldTests(IntegerFieldTests):
 
556
    model = SmallIntegerModel
 
557
    documented_range = (-32768, 32767)
 
558
 
 
559
 
 
560
class BigIntegerFieldTests(IntegerFieldTests):
 
561
    model = BigIntegerModel
 
562
    documented_range = (-9223372036854775808, 9223372036854775807)
 
563
 
 
564
 
 
565
class PositiveSmallIntegerFieldTests(IntegerFieldTests):
 
566
    model = PositiveSmallIntegerModel
 
567
    documented_range = (0, 32767)
 
568
 
 
569
 
 
570
class PositiveIntegerFieldTests(IntegerFieldTests):
 
571
    model = PositiveIntegerModel
 
572
    documented_range = (0, 2147483647)
 
573
 
414
574
 
415
575
class TypeCoercionTests(test.TestCase):
416
576
    """
425
585
    def test_lookup_integer_in_textfield(self):
426
586
        self.assertEqual(Post.objects.filter(body=24).count(), 0)
427
587
 
 
588
 
428
589
class FileFieldTests(unittest.TestCase):
429
590
    def test_clearable(self):
430
591
        """
477
638
class BinaryFieldTests(test.TestCase):
478
639
    binary_data = b'\x00\x46\xFE'
479
640
 
 
641
    @test.skipUnlessDBFeature('supports_binary_field')
480
642
    def test_set_and_retrieve(self):
481
643
        data_set = (self.binary_data, six.memoryview(self.binary_data))
482
644
        for bdata in data_set:
491
653
            # Test default value
492
654
            self.assertEqual(bytes(dm.short_data), b'\x08')
493
655
 
494
 
    if connection.vendor == 'mysql' and six.PY3:
495
 
        # Existing MySQL DB-API drivers fail on binary data.
496
 
        test_set_and_retrieve = unittest.expectedFailure(test_set_and_retrieve)
497
 
 
498
656
    def test_max_length(self):
499
 
        dm = DataModel(short_data=self.binary_data*4)
 
657
        dm = DataModel(short_data=self.binary_data * 4)
500
658
        self.assertRaises(ValidationError, dm.full_clean)
501
659
 
 
660
 
502
661
class GenericIPAddressFieldTests(test.TestCase):
503
662
    def test_genericipaddressfield_formfield_protocol(self):
504
663
        """
513
672
        self.assertRaises(ValidationError, form_field.clean, '127.0.0.1')
514
673
 
515
674
 
516
 
class PrepValueTest(test.TestCase):
 
675
class PromiseTest(test.TestCase):
517
676
    def test_AutoField(self):
518
 
        self.assertIsInstance(AutoField(primary_key=True).get_prep_value(1), int)
 
677
        lazy_func = lazy(lambda: 1, int)
 
678
        self.assertIsInstance(
 
679
            AutoField(primary_key=True).get_prep_value(lazy_func()),
 
680
            int)
519
681
 
520
682
    @unittest.skipIf(six.PY3, "Python 3 has no `long` type.")
521
683
    def test_BigIntegerField(self):
522
 
        self.assertIsInstance(BigIntegerField().get_prep_value(long(9999999999999999999)), long)
 
684
        lazy_func = lazy(lambda: long(9999999999999999999), long)
 
685
        self.assertIsInstance(
 
686
            BigIntegerField().get_prep_value(lazy_func()),
 
687
            long)
523
688
 
524
689
    def test_BinaryField(self):
525
 
        self.assertIsInstance(BinaryField().get_prep_value(b''), bytes)
 
690
        lazy_func = lazy(lambda: b'', bytes)
 
691
        self.assertIsInstance(
 
692
            BinaryField().get_prep_value(lazy_func()),
 
693
            bytes)
526
694
 
527
695
    def test_BooleanField(self):
528
 
        self.assertIsInstance(BooleanField().get_prep_value(True), bool)
 
696
        lazy_func = lazy(lambda: True, bool)
 
697
        self.assertIsInstance(
 
698
            BooleanField().get_prep_value(lazy_func()),
 
699
            bool)
529
700
 
530
701
    def test_CharField(self):
531
 
        self.assertIsInstance(CharField().get_prep_value(''), six.text_type)
532
 
        self.assertIsInstance(CharField().get_prep_value(0), six.text_type)
 
702
        lazy_func = lazy(lambda: '', six.text_type)
 
703
        self.assertIsInstance(
 
704
            CharField().get_prep_value(lazy_func()),
 
705
            six.text_type)
 
706
        lazy_func = lazy(lambda: 0, int)
 
707
        self.assertIsInstance(
 
708
            CharField().get_prep_value(lazy_func()),
 
709
            six.text_type)
533
710
 
534
711
    def test_CommaSeparatedIntegerField(self):
535
 
        self.assertIsInstance(CommaSeparatedIntegerField().get_prep_value('1,2'), six.text_type)
536
 
        self.assertIsInstance(CommaSeparatedIntegerField().get_prep_value(0), six.text_type)
 
712
        lazy_func = lazy(lambda: '1,2', six.text_type)
 
713
        self.assertIsInstance(
 
714
            CommaSeparatedIntegerField().get_prep_value(lazy_func()),
 
715
            six.text_type)
 
716
        lazy_func = lazy(lambda: 0, int)
 
717
        self.assertIsInstance(
 
718
            CommaSeparatedIntegerField().get_prep_value(lazy_func()),
 
719
            six.text_type)
537
720
 
538
721
    def test_DateField(self):
539
 
        self.assertIsInstance(DateField().get_prep_value(datetime.date.today()), datetime.date)
 
722
        lazy_func = lazy(lambda: datetime.date.today(), datetime.date)
 
723
        self.assertIsInstance(
 
724
            DateField().get_prep_value(lazy_func()),
 
725
            datetime.date)
540
726
 
541
727
    def test_DateTimeField(self):
542
 
        self.assertIsInstance(DateTimeField().get_prep_value(datetime.datetime.now()), datetime.datetime)
 
728
        lazy_func = lazy(lambda: datetime.datetime.now(), datetime.datetime)
 
729
        self.assertIsInstance(
 
730
            DateTimeField().get_prep_value(lazy_func()),
 
731
            datetime.datetime)
543
732
 
544
733
    def test_DecimalField(self):
545
 
        self.assertIsInstance(DecimalField().get_prep_value(Decimal('1.2')), Decimal)
 
734
        lazy_func = lazy(lambda: Decimal('1.2'), Decimal)
 
735
        self.assertIsInstance(
 
736
            DecimalField().get_prep_value(lazy_func()),
 
737
            Decimal)
546
738
 
547
739
    def test_EmailField(self):
548
 
        self.assertIsInstance(EmailField().get_prep_value('mailbox@domain.com'), six.text_type)
 
740
        lazy_func = lazy(lambda: 'mailbox@domain.com', six.text_type)
 
741
        self.assertIsInstance(
 
742
            EmailField().get_prep_value(lazy_func()),
 
743
            six.text_type)
549
744
 
550
745
    def test_FileField(self):
551
 
        self.assertIsInstance(FileField().get_prep_value('filename.ext'), six.text_type)
552
 
        self.assertIsInstance(FileField().get_prep_value(0), six.text_type)
 
746
        lazy_func = lazy(lambda: 'filename.ext', six.text_type)
 
747
        self.assertIsInstance(
 
748
            FileField().get_prep_value(lazy_func()),
 
749
            six.text_type)
 
750
        lazy_func = lazy(lambda: 0, int)
 
751
        self.assertIsInstance(
 
752
            FileField().get_prep_value(lazy_func()),
 
753
            six.text_type)
553
754
 
554
755
    def test_FilePathField(self):
555
 
        self.assertIsInstance(FilePathField().get_prep_value('tests.py'), six.text_type)
556
 
        self.assertIsInstance(FilePathField().get_prep_value(0), six.text_type)
 
756
        lazy_func = lazy(lambda: 'tests.py', six.text_type)
 
757
        self.assertIsInstance(
 
758
            FilePathField().get_prep_value(lazy_func()),
 
759
            six.text_type)
 
760
        lazy_func = lazy(lambda: 0, int)
 
761
        self.assertIsInstance(
 
762
            FilePathField().get_prep_value(lazy_func()),
 
763
            six.text_type)
557
764
 
558
765
    def test_FloatField(self):
559
 
        self.assertIsInstance(FloatField().get_prep_value(1.2), float)
 
766
        lazy_func = lazy(lambda: 1.2, float)
 
767
        self.assertIsInstance(
 
768
            FloatField().get_prep_value(lazy_func()),
 
769
            float)
560
770
 
561
771
    def test_ImageField(self):
562
 
        self.assertIsInstance(ImageField().get_prep_value('filename.ext'), six.text_type)
 
772
        lazy_func = lazy(lambda: 'filename.ext', six.text_type)
 
773
        self.assertIsInstance(
 
774
            ImageField().get_prep_value(lazy_func()),
 
775
            six.text_type)
563
776
 
564
777
    def test_IntegerField(self):
565
 
        self.assertIsInstance(IntegerField().get_prep_value(1), int)
 
778
        lazy_func = lazy(lambda: 1, int)
 
779
        self.assertIsInstance(
 
780
            IntegerField().get_prep_value(lazy_func()),
 
781
            int)
566
782
 
567
783
    def test_IPAddressField(self):
568
 
        self.assertIsInstance(IPAddressField().get_prep_value('127.0.0.1'), six.text_type)
569
 
        self.assertIsInstance(IPAddressField().get_prep_value(0), six.text_type)
 
784
        with warnings.catch_warnings(record=True):
 
785
            warnings.simplefilter("always")
 
786
            lazy_func = lazy(lambda: '127.0.0.1', six.text_type)
 
787
            self.assertIsInstance(
 
788
                IPAddressField().get_prep_value(lazy_func()),
 
789
                six.text_type)
 
790
            lazy_func = lazy(lambda: 0, int)
 
791
            self.assertIsInstance(
 
792
                IPAddressField().get_prep_value(lazy_func()),
 
793
                six.text_type)
570
794
 
571
795
    def test_GenericIPAddressField(self):
572
 
        self.assertIsInstance(GenericIPAddressField().get_prep_value('127.0.0.1'), six.text_type)
573
 
        self.assertIsInstance(GenericIPAddressField().get_prep_value(0), six.text_type)
 
796
        lazy_func = lazy(lambda: '127.0.0.1', six.text_type)
 
797
        self.assertIsInstance(
 
798
            GenericIPAddressField().get_prep_value(lazy_func()),
 
799
            six.text_type)
 
800
        lazy_func = lazy(lambda: 0, int)
 
801
        self.assertIsInstance(
 
802
            GenericIPAddressField().get_prep_value(lazy_func()),
 
803
            six.text_type)
574
804
 
575
805
    def test_NullBooleanField(self):
576
 
        self.assertIsInstance(NullBooleanField().get_prep_value(True), bool)
 
806
        lazy_func = lazy(lambda: True, bool)
 
807
        self.assertIsInstance(
 
808
            NullBooleanField().get_prep_value(lazy_func()),
 
809
            bool)
577
810
 
578
811
    def test_PositiveIntegerField(self):
579
 
        self.assertIsInstance(PositiveIntegerField().get_prep_value(1), int)
 
812
        lazy_func = lazy(lambda: 1, int)
 
813
        self.assertIsInstance(
 
814
            PositiveIntegerField().get_prep_value(lazy_func()),
 
815
            int)
580
816
 
581
817
    def test_PositiveSmallIntegerField(self):
582
 
        self.assertIsInstance(PositiveSmallIntegerField().get_prep_value(1), int)
 
818
        lazy_func = lazy(lambda: 1, int)
 
819
        self.assertIsInstance(
 
820
            PositiveSmallIntegerField().get_prep_value(lazy_func()),
 
821
            int)
583
822
 
584
823
    def test_SlugField(self):
585
 
        self.assertIsInstance(SlugField().get_prep_value('slug'), six.text_type)
586
 
        self.assertIsInstance(SlugField().get_prep_value(0), six.text_type)
 
824
        lazy_func = lazy(lambda: 'slug', six.text_type)
 
825
        self.assertIsInstance(
 
826
            SlugField().get_prep_value(lazy_func()),
 
827
            six.text_type)
 
828
        lazy_func = lazy(lambda: 0, int)
 
829
        self.assertIsInstance(
 
830
            SlugField().get_prep_value(lazy_func()),
 
831
            six.text_type)
587
832
 
588
833
    def test_SmallIntegerField(self):
589
 
        self.assertIsInstance(SmallIntegerField().get_prep_value(1), int)
 
834
        lazy_func = lazy(lambda: 1, int)
 
835
        self.assertIsInstance(
 
836
            SmallIntegerField().get_prep_value(lazy_func()),
 
837
            int)
590
838
 
591
839
    def test_TextField(self):
592
 
        self.assertIsInstance(TextField().get_prep_value('Abc'), six.text_type)
593
 
        self.assertIsInstance(TextField().get_prep_value(0), six.text_type)
 
840
        lazy_func = lazy(lambda: 'Abc', six.text_type)
 
841
        self.assertIsInstance(
 
842
            TextField().get_prep_value(lazy_func()),
 
843
            six.text_type)
 
844
        lazy_func = lazy(lambda: 0, int)
 
845
        self.assertIsInstance(
 
846
            TextField().get_prep_value(lazy_func()),
 
847
            six.text_type)
594
848
 
595
849
    def test_TimeField(self):
 
850
        lazy_func = lazy(lambda: datetime.datetime.now().time(), datetime.time)
596
851
        self.assertIsInstance(
597
 
            TimeField().get_prep_value(datetime.datetime.now().time()),
 
852
            TimeField().get_prep_value(lazy_func()),
598
853
            datetime.time)
599
854
 
600
855
    def test_URLField(self):
601
 
        self.assertIsInstance(URLField().get_prep_value('http://domain.com'), six.text_type)
 
856
        lazy_func = lazy(lambda: 'http://domain.com', six.text_type)
 
857
        self.assertIsInstance(
 
858
            URLField().get_prep_value(lazy_func()),
 
859
            six.text_type)
602
860
 
603
861
 
604
862
class CustomFieldTests(unittest.TestCase):
608
866
        Regression test for #14786 -- Test that field values are not prepared
609
867
        twice in get_db_prep_lookup().
610
868
        """
611
 
        prepare_count = [0]
612
869
        class NoopField(models.TextField):
 
870
            def __init__(self, *args, **kwargs):
 
871
                self.prep_value_count = 0
 
872
                super(NoopField, self).__init__(*args, **kwargs)
 
873
 
613
874
            def get_prep_value(self, value):
614
 
                prepare_count[0] += 1
 
875
                self.prep_value_count += 1
615
876
                return super(NoopField, self).get_prep_value(value)
616
877
 
617
878
        field = NoopField()
618
 
        field.get_db_prep_lookup('exact', 'TEST', connection=connection, prepared=False)
619
 
        self.assertEqual(prepare_count[0], 1)
 
879
        field.get_db_prep_lookup(
 
880
            'exact', 'TEST', connection=connection, prepared=False
 
881
        )
 
882
        self.assertEqual(field.prep_value_count, 1)