1
from __future__ import absolute_import, unicode_literals
1
from __future__ import unicode_literals
4
4
from decimal import Decimal
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
21
from .models import (Foo, Bar, Whiz, BigD, BigS, Image, BigInt, Post,
22
NullBooleanModel, BooleanModel, DataModel, Document, RenamedField,
23
DateTimeModel, VerboseNameField, FksToBooleans)
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)
26
32
class BasicFieldTests(test.TestCase):
315
376
self.assertEqual(Whiz(c=None).get_c_display(), None) # Blank value
316
377
self.assertEqual(Whiz(c='').get_c_display(), '') # Empty value
379
def test_iterator_choices(self):
381
Check that get_choices works with Iterators (#23112).
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
388
def test_empty_iterator_choices(self):
390
Check that get_choices works with empty iterators (#23112).
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
397
def test_charfield_get_choices_with_blank_iterator(self):
399
Check that get_choices works with an empty Iterator
401
f = models.CharField(choices=(x for x in []))
402
self.assertEqual(f.get_choices(include_blank=True), [('', '---------')])
318
405
class SlugFieldTests(test.TestCase):
319
406
def test_slugfield_max_length(self):
321
408
Make sure SlugField honors max_length (#9706)
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)
328
415
class ValidationTest(test.TestCase):
343
430
self.assertRaises(ValidationError, f.clean, "a", None)
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))
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)
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')])
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], ('', '---------'))
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))
357
457
def test_nullable_integerfield_raises_error_with_blank_false(self):
384
484
self.assertRaises(ValidationError, f.clean, None, None)
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
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):
489
documented_range = (-2147483648, 2147483647)
491
def test_documented_range(self):
493
Ensure that values within the documented safe range pass validation,
494
can be saved and retrieved without corruption.
496
min_value, max_value = self.documented_range
498
instance = self.model(value=min_value)
499
instance.full_clean()
501
qs = self.model.objects.filter(value__lte=min_value)
502
self.assertEqual(qs.count(), 1)
503
self.assertEqual(qs[0].value, min_value)
505
instance = self.model(value=max_value)
506
instance.full_clean()
508
qs = self.model.objects.filter(value__gte=max_value)
509
self.assertEqual(qs.count(), 1)
510
self.assertEqual(qs[0].value, max_value)
512
def test_backend_range_validation(self):
514
Ensure that backend specific range are enforced at the model
515
validation level. ref #12030.
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)
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
526
with self.assertRaisesMessage(ValidationError, expected_message):
527
instance.full_clean()
528
instance.value = min_value
529
instance.full_clean()
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
536
with self.assertRaisesMessage(ValidationError, expected_message):
537
instance.full_clean()
538
instance.value = max_value
539
instance.full_clean()
402
541
def test_types(self):
403
b = BigInt(value = 0)
404
self.assertIsInstance(b.value, six.integer_types)
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)
545
self.assertIsInstance(instance.value, six.integer_types)
546
instance = self.model.objects.get()
547
self.assertIsInstance(instance.value, six.integer_types)
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)
555
class SmallIntegerFieldTests(IntegerFieldTests):
556
model = SmallIntegerModel
557
documented_range = (-32768, 32767)
560
class BigIntegerFieldTests(IntegerFieldTests):
561
model = BigIntegerModel
562
documented_range = (-9223372036854775808, 9223372036854775807)
565
class PositiveSmallIntegerFieldTests(IntegerFieldTests):
566
model = PositiveSmallIntegerModel
567
documented_range = (0, 32767)
570
class PositiveIntegerFieldTests(IntegerFieldTests):
571
model = PositiveIntegerModel
572
documented_range = (0, 2147483647)
415
575
class TypeCoercionTests(test.TestCase):
513
672
self.assertRaises(ValidationError, form_field.clean, '127.0.0.1')
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()),
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()),
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()),
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()),
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()),
706
lazy_func = lazy(lambda: 0, int)
707
self.assertIsInstance(
708
CharField().get_prep_value(lazy_func()),
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()),
716
lazy_func = lazy(lambda: 0, int)
717
self.assertIsInstance(
718
CommaSeparatedIntegerField().get_prep_value(lazy_func()),
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()),
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()),
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()),
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()),
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()),
750
lazy_func = lazy(lambda: 0, int)
751
self.assertIsInstance(
752
FileField().get_prep_value(lazy_func()),
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()),
760
lazy_func = lazy(lambda: 0, int)
761
self.assertIsInstance(
762
FilePathField().get_prep_value(lazy_func()),
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()),
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()),
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()),
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()),
790
lazy_func = lazy(lambda: 0, int)
791
self.assertIsInstance(
792
IPAddressField().get_prep_value(lazy_func()),
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()),
800
lazy_func = lazy(lambda: 0, int)
801
self.assertIsInstance(
802
GenericIPAddressField().get_prep_value(lazy_func()),
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()),
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()),
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()),
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()),
828
lazy_func = lazy(lambda: 0, int)
829
self.assertIsInstance(
830
SlugField().get_prep_value(lazy_func()),
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()),
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()),
844
lazy_func = lazy(lambda: 0, int)
845
self.assertIsInstance(
846
TextField().get_prep_value(lazy_func()),
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()),
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()),
604
862
class CustomFieldTests(unittest.TestCase):