summaryrefslogtreecommitdiff
path: root/tests/validation
diff options
context:
space:
mode:
authordjango-bot <ops@djangoproject.com>2022-02-03 20:24:19 +0100
committerMariusz Felisiak <felisiak.mariusz@gmail.com>2022-02-07 20:37:05 +0100
commit9c19aff7c7561e3a82978a272ecdaad40dda5c00 (patch)
treef0506b668a013d0063e5fba3dbf4863b466713ba /tests/validation
parentf68fa8b45dfac545cfc4111d4e52804c86db68d3 (diff)
Refs #33476 -- Reformatted code with Black.
Diffstat (limited to 'tests/validation')
-rw-r--r--tests/validation/models.py83
-rw-r--r--tests/validation/test_custom_messages.py4
-rw-r--r--tests/validation/test_error_messages.py88
-rw-r--r--tests/validation/test_picklable.py37
-rw-r--r--tests/validation/test_unique.py159
-rw-r--r--tests/validation/test_validators.py36
-rw-r--r--tests/validation/tests.py105
7 files changed, 324 insertions, 188 deletions
diff --git a/tests/validation/models.py b/tests/validation/models.py
index b2d705aed2..6934fa017c 100644
--- a/tests/validation/models.py
+++ b/tests/validation/models.py
@@ -7,36 +7,43 @@ from django.db.models.functions import Lower
def validate_answer_to_universe(value):
if value != 42:
- raise ValidationError('This is not the answer to life, universe and everything!', code='not42')
+ raise ValidationError(
+ "This is not the answer to life, universe and everything!", code="not42"
+ )
class ModelToValidate(models.Model):
name = models.CharField(max_length=100)
created = models.DateTimeField(default=datetime.now)
- number = models.IntegerField(db_column='number_val')
+ number = models.IntegerField(db_column="number_val")
parent = models.ForeignKey(
- 'self',
+ "self",
models.SET_NULL,
- blank=True, null=True,
- limit_choices_to={'number': 10},
+ blank=True,
+ null=True,
+ limit_choices_to={"number": 10},
)
email = models.EmailField(blank=True)
ufm = models.ForeignKey(
- 'UniqueFieldsModel',
+ "UniqueFieldsModel",
models.SET_NULL,
- to_field='unique_charfield',
- blank=True, null=True,
+ to_field="unique_charfield",
+ blank=True,
+ null=True,
)
url = models.URLField(blank=True)
- f_with_custom_validator = models.IntegerField(blank=True, null=True, validators=[validate_answer_to_universe])
- f_with_iterable_of_validators = models.IntegerField(blank=True, null=True,
- validators=(validate_answer_to_universe,))
+ f_with_custom_validator = models.IntegerField(
+ blank=True, null=True, validators=[validate_answer_to_universe]
+ )
+ f_with_iterable_of_validators = models.IntegerField(
+ blank=True, null=True, validators=(validate_answer_to_universe,)
+ )
slug = models.SlugField(blank=True)
def clean(self):
super().clean()
if self.number == 11:
- raise ValidationError('Invalid number supplied!')
+ raise ValidationError("Invalid number supplied!")
class UniqueFieldsModel(models.Model):
@@ -55,13 +62,21 @@ class UniqueTogetherModel(models.Model):
efield = models.EmailField()
class Meta:
- unique_together = (('ifield', 'cfield',), ['ifield', 'efield'])
+ unique_together = (
+ (
+ "ifield",
+ "cfield",
+ ),
+ ["ifield", "efield"],
+ )
class UniqueForDateModel(models.Model):
start_date = models.DateField()
end_date = models.DateTimeField()
- count = models.IntegerField(unique_for_date="start_date", unique_for_year="end_date")
+ count = models.IntegerField(
+ unique_for_date="start_date", unique_for_year="end_date"
+ )
order = models.IntegerField(unique_for_month="end_date")
name = models.CharField(max_length=100)
@@ -69,9 +84,9 @@ class UniqueForDateModel(models.Model):
class CustomMessagesModel(models.Model):
other = models.IntegerField(blank=True, null=True)
number = models.IntegerField(
- db_column='number_val',
- error_messages={'null': 'NULL', 'not42': 'AAARGH', 'not_equal': '%s != me'},
- validators=[validate_answer_to_universe]
+ db_column="number_val",
+ error_messages={"null": "NULL", "not42": "AAARGH", "not_equal": "%s != me"},
+ validators=[validate_answer_to_universe],
)
@@ -99,40 +114,50 @@ class Article(models.Model):
class Post(models.Model):
- title = models.CharField(max_length=50, unique_for_date='posted', blank=True)
- slug = models.CharField(max_length=50, unique_for_year='posted', blank=True)
- subtitle = models.CharField(max_length=50, unique_for_month='posted', blank=True)
+ title = models.CharField(max_length=50, unique_for_date="posted", blank=True)
+ slug = models.CharField(max_length=50, unique_for_year="posted", blank=True)
+ subtitle = models.CharField(max_length=50, unique_for_month="posted", blank=True)
posted = models.DateField()
class FlexibleDatePost(models.Model):
- title = models.CharField(max_length=50, unique_for_date='posted', blank=True)
- slug = models.CharField(max_length=50, unique_for_year='posted', blank=True)
- subtitle = models.CharField(max_length=50, unique_for_month='posted', blank=True)
+ title = models.CharField(max_length=50, unique_for_date="posted", blank=True)
+ slug = models.CharField(max_length=50, unique_for_year="posted", blank=True)
+ subtitle = models.CharField(max_length=50, unique_for_month="posted", blank=True)
posted = models.DateField(blank=True, null=True)
class UniqueErrorsModel(models.Model):
- name = models.CharField(max_length=100, unique=True, error_messages={'unique': 'Custom unique name message.'})
- no = models.IntegerField(unique=True, error_messages={'unique': 'Custom unique number message.'})
+ name = models.CharField(
+ max_length=100,
+ unique=True,
+ error_messages={"unique": "Custom unique name message."},
+ )
+ no = models.IntegerField(
+ unique=True, error_messages={"unique": "Custom unique number message."}
+ )
class GenericIPAddressTestModel(models.Model):
generic_ip = models.GenericIPAddressField(blank=True, null=True, unique=True)
v4_ip = models.GenericIPAddressField(blank=True, null=True, protocol="ipv4")
v6_ip = models.GenericIPAddressField(blank=True, null=True, protocol="ipv6")
- ip_verbose_name = models.GenericIPAddressField("IP Address Verbose", blank=True, null=True)
+ ip_verbose_name = models.GenericIPAddressField(
+ "IP Address Verbose", blank=True, null=True
+ )
class GenericIPAddrUnpackUniqueTest(models.Model):
- generic_v4unpack_ip = models.GenericIPAddressField(null=True, blank=True, unique=True, unpack_ipv4=True)
+ generic_v4unpack_ip = models.GenericIPAddressField(
+ null=True, blank=True, unique=True, unpack_ipv4=True
+ )
class UniqueFuncConstraintModel(models.Model):
field = models.CharField(max_length=255)
class Meta:
- required_db_features = {'supports_expression_indexes'}
+ required_db_features = {"supports_expression_indexes"}
constraints = [
- models.UniqueConstraint(Lower('field'), name='func_lower_field_uq'),
+ models.UniqueConstraint(Lower("field"), name="func_lower_field_uq"),
]
diff --git a/tests/validation/test_custom_messages.py b/tests/validation/test_custom_messages.py
index 4e4897e5b4..3b130caa1e 100644
--- a/tests/validation/test_custom_messages.py
+++ b/tests/validation/test_custom_messages.py
@@ -7,8 +7,8 @@ from .models import CustomMessagesModel
class CustomMessagesTests(ValidationAssertions, SimpleTestCase):
def test_custom_simple_validator_message(self):
cmm = CustomMessagesModel(number=12)
- self.assertFieldFailsValidationWithMessage(cmm.full_clean, 'number', ['AAARGH'])
+ self.assertFieldFailsValidationWithMessage(cmm.full_clean, "number", ["AAARGH"])
def test_custom_null_message(self):
cmm = CustomMessagesModel()
- self.assertFieldFailsValidationWithMessage(cmm.full_clean, 'number', ['NULL'])
+ self.assertFieldFailsValidationWithMessage(cmm.full_clean, "number", ["NULL"])
diff --git a/tests/validation/test_error_messages.py b/tests/validation/test_error_messages.py
index 5f1e0a75d0..470c055eef 100644
--- a/tests/validation/test_error_messages.py
+++ b/tests/validation/test_error_messages.py
@@ -5,7 +5,6 @@ from django.db import models
class ValidationMessagesTest(TestCase):
-
def _test_validation_messages(self, field, value, expected):
with self.assertRaises(ValidationError) as cm:
field.clean(value, None)
@@ -13,79 +12,114 @@ class ValidationMessagesTest(TestCase):
def test_autofield_field_raises_error_message(self):
f = models.AutoField(primary_key=True)
- self._test_validation_messages(f, 'fõo', ['“fõo” value must be an integer.'])
+ self._test_validation_messages(f, "fõo", ["“fõo” value must be an integer."])
def test_integer_field_raises_error_message(self):
f = models.IntegerField()
- self._test_validation_messages(f, 'fõo', ['“fõo” value must be an integer.'])
+ self._test_validation_messages(f, "fõo", ["“fõo” value must be an integer."])
def test_boolean_field_raises_error_message(self):
f = models.BooleanField()
- self._test_validation_messages(f, 'fõo', ['“fõo” value must be either True or False.'])
+ self._test_validation_messages(
+ f, "fõo", ["“fõo” value must be either True or False."]
+ )
def test_nullable_boolean_field_raises_error_message(self):
f = models.BooleanField(null=True)
- self._test_validation_messages(f, 'fõo', ['“fõo” value must be either True, False, or None.'])
+ self._test_validation_messages(
+ f, "fõo", ["“fõo” value must be either True, False, or None."]
+ )
def test_float_field_raises_error_message(self):
f = models.FloatField()
- self._test_validation_messages(f, 'fõo', ['“fõo” value must be a float.'])
+ self._test_validation_messages(f, "fõo", ["“fõo” value must be a float."])
def test_decimal_field_raises_error_message(self):
f = models.DecimalField()
- self._test_validation_messages(f, 'fõo', ['“fõo” value must be a decimal number.'])
+ self._test_validation_messages(
+ f, "fõo", ["“fõo” value must be a decimal number."]
+ )
def test_null_boolean_field_raises_error_message(self):
f = models.BooleanField(null=True)
- self._test_validation_messages(f, 'fõo', ['“fõo” value must be either True, False, or None.'])
+ self._test_validation_messages(
+ f, "fõo", ["“fõo” value must be either True, False, or None."]
+ )
def test_date_field_raises_error_message(self):
f = models.DateField()
self._test_validation_messages(
- f, 'fõo',
- ['“fõo” value has an invalid date format. It must be in YYYY-MM-DD format.']
+ f,
+ "fõo",
+ [
+ "“fõo” value has an invalid date format. It must be in YYYY-MM-DD format."
+ ],
)
self._test_validation_messages(
- f, 'aaaa-10-10',
- ['“aaaa-10-10” value has an invalid date format. It must be in YYYY-MM-DD format.']
+ f,
+ "aaaa-10-10",
+ [
+ "“aaaa-10-10” value has an invalid date format. It must be in YYYY-MM-DD format."
+ ],
)
self._test_validation_messages(
- f, '2011-13-10',
- ['“2011-13-10” value has the correct format (YYYY-MM-DD) but it is an invalid date.']
+ f,
+ "2011-13-10",
+ [
+ "“2011-13-10” value has the correct format (YYYY-MM-DD) but it is an invalid date."
+ ],
)
self._test_validation_messages(
- f, '2011-10-32',
- ['“2011-10-32” value has the correct format (YYYY-MM-DD) but it is an invalid date.']
+ f,
+ "2011-10-32",
+ [
+ "“2011-10-32” value has the correct format (YYYY-MM-DD) but it is an invalid date."
+ ],
)
def test_datetime_field_raises_error_message(self):
f = models.DateTimeField()
# Wrong format
self._test_validation_messages(
- f, 'fõo',
- ['“fõo” value has an invalid format. It must be in YYYY-MM-DD HH:MM[:ss[.uuuuuu]][TZ] format.']
+ f,
+ "fõo",
+ [
+ "“fõo” value has an invalid format. It must be in YYYY-MM-DD HH:MM[:ss[.uuuuuu]][TZ] format."
+ ],
)
# Correct format but invalid date
self._test_validation_messages(
- f, '2011-10-32',
- ['“2011-10-32” value has the correct format (YYYY-MM-DD) but it is an invalid date.']
+ f,
+ "2011-10-32",
+ [
+ "“2011-10-32” value has the correct format (YYYY-MM-DD) but it is an invalid date."
+ ],
)
# Correct format but invalid date/time
self._test_validation_messages(
- f, '2011-10-32 10:10',
- ['“2011-10-32 10:10” value has the correct format (YYYY-MM-DD HH:MM[:ss[.uuuuuu]][TZ]) '
- 'but it is an invalid date/time.']
+ f,
+ "2011-10-32 10:10",
+ [
+ "“2011-10-32 10:10” value has the correct format (YYYY-MM-DD HH:MM[:ss[.uuuuuu]][TZ]) "
+ "but it is an invalid date/time."
+ ],
)
def test_time_field_raises_error_message(self):
f = models.TimeField()
# Wrong format
self._test_validation_messages(
- f, 'fõo',
- ['“fõo” value has an invalid format. It must be in HH:MM[:ss[.uuuuuu]] format.']
+ f,
+ "fõo",
+ [
+ "“fõo” value has an invalid format. It must be in HH:MM[:ss[.uuuuuu]] format."
+ ],
)
# Correct format but invalid time
self._test_validation_messages(
- f, '25:50',
- ['“25:50” value has the correct format (HH:MM[:ss[.uuuuuu]]) but it is an invalid time.']
+ f,
+ "25:50",
+ [
+ "“25:50” value has the correct format (HH:MM[:ss[.uuuuuu]]) but it is an invalid time."
+ ],
)
diff --git a/tests/validation/test_picklable.py b/tests/validation/test_picklable.py
index a8d84dba20..1fce55d9a3 100644
--- a/tests/validation/test_picklable.py
+++ b/tests/validation/test_picklable.py
@@ -5,37 +5,48 @@ from django.core.exceptions import ValidationError
class PickableValidationErrorTestCase(TestCase):
-
def test_validationerror_is_picklable(self):
- original = ValidationError('a', code='something')
+ original = ValidationError("a", code="something")
unpickled = pickle.loads(pickle.dumps(original))
self.assertIs(unpickled, unpickled.error_list[0])
self.assertEqual(original.message, unpickled.message)
self.assertEqual(original.code, unpickled.code)
- original = ValidationError('a', code='something')
+ original = ValidationError("a", code="something")
unpickled = pickle.loads(pickle.dumps(ValidationError(original)))
self.assertIs(unpickled, unpickled.error_list[0])
self.assertEqual(original.message, unpickled.message)
self.assertEqual(original.code, unpickled.code)
- original = ValidationError(['a', 'b'])
+ original = ValidationError(["a", "b"])
unpickled = pickle.loads(pickle.dumps(original))
- self.assertEqual(original.error_list[0].message, unpickled.error_list[0].message)
- self.assertEqual(original.error_list[1].message, unpickled.error_list[1].message)
+ self.assertEqual(
+ original.error_list[0].message, unpickled.error_list[0].message
+ )
+ self.assertEqual(
+ original.error_list[1].message, unpickled.error_list[1].message
+ )
- original = ValidationError(['a', 'b'])
+ original = ValidationError(["a", "b"])
unpickled = pickle.loads(pickle.dumps(ValidationError(original)))
- self.assertEqual(original.error_list[0].message, unpickled.error_list[0].message)
- self.assertEqual(original.error_list[1].message, unpickled.error_list[1].message)
+ self.assertEqual(
+ original.error_list[0].message, unpickled.error_list[0].message
+ )
+ self.assertEqual(
+ original.error_list[1].message, unpickled.error_list[1].message
+ )
- original = ValidationError([ValidationError('a'), ValidationError('b')])
+ original = ValidationError([ValidationError("a"), ValidationError("b")])
unpickled = pickle.loads(pickle.dumps(original))
self.assertIs(unpickled.args[0][0], unpickled.error_list[0])
- self.assertEqual(original.error_list[0].message, unpickled.error_list[0].message)
- self.assertEqual(original.error_list[1].message, unpickled.error_list[1].message)
+ self.assertEqual(
+ original.error_list[0].message, unpickled.error_list[0].message
+ )
+ self.assertEqual(
+ original.error_list[1].message, unpickled.error_list[1].message
+ )
- message_dict = {'field1': ['a', 'b'], 'field2': ['c', 'd']}
+ message_dict = {"field1": ["a", "b"], "field2": ["c", "d"]}
original = ValidationError(message_dict)
unpickled = pickle.loads(pickle.dumps(original))
self.assertEqual(unpickled.message_dict, message_dict)
diff --git a/tests/validation/test_unique.py b/tests/validation/test_unique.py
index 8bf4ca2122..b8fd95abcb 100644
--- a/tests/validation/test_unique.py
+++ b/tests/validation/test_unique.py
@@ -7,8 +7,14 @@ from django.db import models
from django.test import TestCase
from .models import (
- CustomPKModel, FlexibleDatePost, ModelToValidate, Post, UniqueErrorsModel,
- UniqueFieldsModel, UniqueForDateModel, UniqueFuncConstraintModel,
+ CustomPKModel,
+ FlexibleDatePost,
+ ModelToValidate,
+ Post,
+ UniqueErrorsModel,
+ UniqueFieldsModel,
+ UniqueForDateModel,
+ UniqueFuncConstraintModel,
UniqueTogetherModel,
)
@@ -17,21 +23,29 @@ class GetUniqueCheckTests(unittest.TestCase):
def test_unique_fields_get_collected(self):
m = UniqueFieldsModel()
self.assertEqual(
- ([(UniqueFieldsModel, ('id',)),
- (UniqueFieldsModel, ('unique_charfield',)),
- (UniqueFieldsModel, ('unique_integerfield',))],
- []),
- m._get_unique_checks()
+ (
+ [
+ (UniqueFieldsModel, ("id",)),
+ (UniqueFieldsModel, ("unique_charfield",)),
+ (UniqueFieldsModel, ("unique_integerfield",)),
+ ],
+ [],
+ ),
+ m._get_unique_checks(),
)
def test_unique_together_gets_picked_up_and_converted_to_tuple(self):
m = UniqueTogetherModel()
self.assertEqual(
- ([(UniqueTogetherModel, ('ifield', 'cfield')),
- (UniqueTogetherModel, ('ifield', 'efield')),
- (UniqueTogetherModel, ('id',))],
- []),
- m._get_unique_checks()
+ (
+ [
+ (UniqueTogetherModel, ("ifield", "cfield")),
+ (UniqueTogetherModel, ("ifield", "efield")),
+ (UniqueTogetherModel, ("id",)),
+ ],
+ [],
+ ),
+ m._get_unique_checks(),
)
def test_unique_together_normalization(self):
@@ -40,24 +54,28 @@ class GetUniqueCheckTests(unittest.TestCase):
objects.
"""
data = {
- '2-tuple': (('foo', 'bar'), (('foo', 'bar'),)),
- 'list': (['foo', 'bar'], (('foo', 'bar'),)),
- 'already normalized': ((('foo', 'bar'), ('bar', 'baz')),
- (('foo', 'bar'), ('bar', 'baz'))),
- 'set': ({('foo', 'bar'), ('bar', 'baz')}, # Ref #21469
- (('foo', 'bar'), ('bar', 'baz'))),
+ "2-tuple": (("foo", "bar"), (("foo", "bar"),)),
+ "list": (["foo", "bar"], (("foo", "bar"),)),
+ "already normalized": (
+ (("foo", "bar"), ("bar", "baz")),
+ (("foo", "bar"), ("bar", "baz")),
+ ),
+ "set": (
+ {("foo", "bar"), ("bar", "baz")}, # Ref #21469
+ (("foo", "bar"), ("bar", "baz")),
+ ),
}
for unique_together, normalized in data.values():
+
class M(models.Model):
foo = models.IntegerField()
bar = models.IntegerField()
baz = models.IntegerField()
- Meta = type('Meta', (), {
- 'unique_together': unique_together,
- 'apps': Apps()
- })
+ Meta = type(
+ "Meta", (), {"unique_together": unique_together, "apps": Apps()}
+ )
checks, _ = M()._get_unique_checks()
for t in normalized:
@@ -66,69 +84,86 @@ class GetUniqueCheckTests(unittest.TestCase):
def test_primary_key_is_considered_unique(self):
m = CustomPKModel()
- self.assertEqual(([(CustomPKModel, ('my_pk_field',))], []), m._get_unique_checks())
+ self.assertEqual(
+ ([(CustomPKModel, ("my_pk_field",))], []), m._get_unique_checks()
+ )
def test_unique_for_date_gets_picked_up(self):
m = UniqueForDateModel()
- self.assertEqual((
- [(UniqueForDateModel, ('id',))],
- [(UniqueForDateModel, 'date', 'count', 'start_date'),
- (UniqueForDateModel, 'year', 'count', 'end_date'),
- (UniqueForDateModel, 'month', 'order', 'end_date')]
- ), m._get_unique_checks()
+ self.assertEqual(
+ (
+ [(UniqueForDateModel, ("id",))],
+ [
+ (UniqueForDateModel, "date", "count", "start_date"),
+ (UniqueForDateModel, "year", "count", "end_date"),
+ (UniqueForDateModel, "month", "order", "end_date"),
+ ],
+ ),
+ m._get_unique_checks(),
)
def test_unique_for_date_exclusion(self):
m = UniqueForDateModel()
- self.assertEqual((
- [(UniqueForDateModel, ('id',))],
- [(UniqueForDateModel, 'year', 'count', 'end_date'),
- (UniqueForDateModel, 'month', 'order', 'end_date')]
- ), m._get_unique_checks(exclude='start_date')
+ self.assertEqual(
+ (
+ [(UniqueForDateModel, ("id",))],
+ [
+ (UniqueForDateModel, "year", "count", "end_date"),
+ (UniqueForDateModel, "month", "order", "end_date"),
+ ],
+ ),
+ m._get_unique_checks(exclude="start_date"),
)
def test_func_unique_constraint_ignored(self):
m = UniqueFuncConstraintModel()
self.assertEqual(
m._get_unique_checks(),
- ([(UniqueFuncConstraintModel, ('id',))], []),
+ ([(UniqueFuncConstraintModel, ("id",))], []),
)
class PerformUniqueChecksTest(TestCase):
- def test_primary_key_unique_check_not_performed_when_adding_and_pk_not_specified(self):
+ def test_primary_key_unique_check_not_performed_when_adding_and_pk_not_specified(
+ self,
+ ):
# Regression test for #12560
with self.assertNumQueries(0):
- mtv = ModelToValidate(number=10, name='Some Name')
- setattr(mtv, '_adding', True)
+ mtv = ModelToValidate(number=10, name="Some Name")
+ setattr(mtv, "_adding", True)
mtv.full_clean()
def test_primary_key_unique_check_performed_when_adding_and_pk_specified(self):
# Regression test for #12560
with self.assertNumQueries(1):
- mtv = ModelToValidate(number=10, name='Some Name', id=123)
- setattr(mtv, '_adding', True)
+ mtv = ModelToValidate(number=10, name="Some Name", id=123)
+ setattr(mtv, "_adding", True)
mtv.full_clean()
def test_primary_key_unique_check_not_performed_when_not_adding(self):
# Regression test for #12132
with self.assertNumQueries(0):
- mtv = ModelToValidate(number=10, name='Some Name')
+ mtv = ModelToValidate(number=10, name="Some Name")
mtv.full_clean()
def test_func_unique_check_not_performed(self):
with self.assertNumQueries(0):
- UniqueFuncConstraintModel(field='some name').full_clean()
+ UniqueFuncConstraintModel(field="some name").full_clean()
def test_unique_for_date(self):
Post.objects.create(
- title="Django 1.0 is released", slug="Django 1.0",
- subtitle="Finally", posted=datetime.date(2008, 9, 3),
+ title="Django 1.0 is released",
+ slug="Django 1.0",
+ subtitle="Finally",
+ posted=datetime.date(2008, 9, 3),
)
p = Post(title="Django 1.0 is released", posted=datetime.date(2008, 9, 3))
with self.assertRaises(ValidationError) as cm:
p.full_clean()
- self.assertEqual(cm.exception.message_dict, {'title': ['Title must be unique for Posted date.']})
+ self.assertEqual(
+ cm.exception.message_dict,
+ {"title": ["Title must be unique for Posted date."]},
+ )
# Should work without errors
p = Post(title="Work on Django 1.1 begins", posted=datetime.date(2008, 9, 3))
@@ -141,17 +176,25 @@ class PerformUniqueChecksTest(TestCase):
p = Post(slug="Django 1.0", posted=datetime.datetime(2008, 1, 1))
with self.assertRaises(ValidationError) as cm:
p.full_clean()
- self.assertEqual(cm.exception.message_dict, {'slug': ['Slug must be unique for Posted year.']})
+ self.assertEqual(
+ cm.exception.message_dict,
+ {"slug": ["Slug must be unique for Posted year."]},
+ )
p = Post(subtitle="Finally", posted=datetime.datetime(2008, 9, 30))
with self.assertRaises(ValidationError) as cm:
p.full_clean()
- self.assertEqual(cm.exception.message_dict, {'subtitle': ['Subtitle must be unique for Posted month.']})
+ self.assertEqual(
+ cm.exception.message_dict,
+ {"subtitle": ["Subtitle must be unique for Posted month."]},
+ )
p = Post(title="Django 1.0 is released")
with self.assertRaises(ValidationError) as cm:
p.full_clean()
- self.assertEqual(cm.exception.message_dict, {'posted': ['This field cannot be null.']})
+ self.assertEqual(
+ cm.exception.message_dict, {"posted": ["This field cannot be null."]}
+ )
def test_unique_for_date_with_nullable_date(self):
"""
@@ -159,8 +202,10 @@ class PerformUniqueChecksTest(TestCase):
associated DateField is None.
"""
FlexibleDatePost.objects.create(
- title="Django 1.0 is released", slug="Django 1.0",
- subtitle="Finally", posted=datetime.date(2008, 9, 3),
+ title="Django 1.0 is released",
+ slug="Django 1.0",
+ subtitle="Finally",
+ posted=datetime.date(2008, 9, 3),
)
p = FlexibleDatePost(title="Django 1.0 is released")
p.full_clean()
@@ -172,13 +217,17 @@ class PerformUniqueChecksTest(TestCase):
p.full_clean()
def test_unique_errors(self):
- UniqueErrorsModel.objects.create(name='Some Name', no=10)
- m = UniqueErrorsModel(name='Some Name', no=11)
+ UniqueErrorsModel.objects.create(name="Some Name", no=10)
+ m = UniqueErrorsModel(name="Some Name", no=11)
with self.assertRaises(ValidationError) as cm:
m.full_clean()
- self.assertEqual(cm.exception.message_dict, {'name': ['Custom unique name message.']})
+ self.assertEqual(
+ cm.exception.message_dict, {"name": ["Custom unique name message."]}
+ )
- m = UniqueErrorsModel(name='Some Other Name', no=10)
+ m = UniqueErrorsModel(name="Some Other Name", no=10)
with self.assertRaises(ValidationError) as cm:
m.full_clean()
- self.assertEqual(cm.exception.message_dict, {'no': ['Custom unique number message.']})
+ self.assertEqual(
+ cm.exception.message_dict, {"no": ["Custom unique number message."]}
+ )
diff --git a/tests/validation/test_validators.py b/tests/validation/test_validators.py
index 9817b6594b..0c7250f8b1 100644
--- a/tests/validation/test_validators.py
+++ b/tests/validation/test_validators.py
@@ -6,26 +6,38 @@ from .models import ModelToValidate
class TestModelsWithValidators(ValidationAssertions, SimpleTestCase):
def test_custom_validator_passes_for_correct_value(self):
- mtv = ModelToValidate(number=10, name='Some Name', f_with_custom_validator=42,
- f_with_iterable_of_validators=42)
+ mtv = ModelToValidate(
+ number=10,
+ name="Some Name",
+ f_with_custom_validator=42,
+ f_with_iterable_of_validators=42,
+ )
self.assertIsNone(mtv.full_clean())
def test_custom_validator_raises_error_for_incorrect_value(self):
- mtv = ModelToValidate(number=10, name='Some Name', f_with_custom_validator=12,
- f_with_iterable_of_validators=42)
- self.assertFailsValidation(mtv.full_clean, ['f_with_custom_validator'])
+ mtv = ModelToValidate(
+ number=10,
+ name="Some Name",
+ f_with_custom_validator=12,
+ f_with_iterable_of_validators=42,
+ )
+ self.assertFailsValidation(mtv.full_clean, ["f_with_custom_validator"])
self.assertFieldFailsValidationWithMessage(
mtv.full_clean,
- 'f_with_custom_validator',
- ['This is not the answer to life, universe and everything!']
+ "f_with_custom_validator",
+ ["This is not the answer to life, universe and everything!"],
)
def test_field_validators_can_be_any_iterable(self):
- mtv = ModelToValidate(number=10, name='Some Name', f_with_custom_validator=42,
- f_with_iterable_of_validators=12)
- self.assertFailsValidation(mtv.full_clean, ['f_with_iterable_of_validators'])
+ mtv = ModelToValidate(
+ number=10,
+ name="Some Name",
+ f_with_custom_validator=42,
+ f_with_iterable_of_validators=12,
+ )
+ self.assertFailsValidation(mtv.full_clean, ["f_with_iterable_of_validators"])
self.assertFieldFailsValidationWithMessage(
mtv.full_clean,
- 'f_with_iterable_of_validators',
- ['This is not the answer to life, universe and everything!']
+ "f_with_iterable_of_validators",
+ ["This is not the answer to life, universe and everything!"],
)
diff --git a/tests/validation/tests.py b/tests/validation/tests.py
index 5598b5ffe6..43de77a44a 100644
--- a/tests/validation/tests.py
+++ b/tests/validation/tests.py
@@ -5,101 +5,110 @@ from django.utils.functional import lazy
from . import ValidationAssertions
from .models import (
- Article, Author, GenericIPAddressTestModel, GenericIPAddrUnpackUniqueTest,
+ Article,
+ Author,
+ GenericIPAddressTestModel,
+ GenericIPAddrUnpackUniqueTest,
ModelToValidate,
)
class BaseModelValidationTests(ValidationAssertions, TestCase):
-
def test_missing_required_field_raises_error(self):
mtv = ModelToValidate(f_with_custom_validator=42)
- self.assertFailsValidation(mtv.full_clean, ['name', 'number'])
+ self.assertFailsValidation(mtv.full_clean, ["name", "number"])
def test_with_correct_value_model_validates(self):
- mtv = ModelToValidate(number=10, name='Some Name')
+ mtv = ModelToValidate(number=10, name="Some Name")
self.assertIsNone(mtv.full_clean())
def test_custom_validate_method(self):
mtv = ModelToValidate(number=11)
- self.assertFailsValidation(mtv.full_clean, [NON_FIELD_ERRORS, 'name'])
+ self.assertFailsValidation(mtv.full_clean, [NON_FIELD_ERRORS, "name"])
def test_wrong_FK_value_raises_error(self):
- mtv = ModelToValidate(number=10, name='Some Name', parent_id=3)
+ mtv = ModelToValidate(number=10, name="Some Name", parent_id=3)
self.assertFieldFailsValidationWithMessage(
- mtv.full_clean, 'parent',
- ['model to validate instance with id %r does not exist.' % mtv.parent_id]
+ mtv.full_clean,
+ "parent",
+ ["model to validate instance with id %r does not exist." % mtv.parent_id],
)
- mtv = ModelToValidate(number=10, name='Some Name', ufm_id='Some Name')
+ mtv = ModelToValidate(number=10, name="Some Name", ufm_id="Some Name")
self.assertFieldFailsValidationWithMessage(
- mtv.full_clean, 'ufm',
- ["unique fields model instance with unique_charfield %r does not exist." % mtv.name]
+ mtv.full_clean,
+ "ufm",
+ [
+ "unique fields model instance with unique_charfield %r does not exist."
+ % mtv.name
+ ],
)
def test_correct_FK_value_validates(self):
- parent = ModelToValidate.objects.create(number=10, name='Some Name')
- mtv = ModelToValidate(number=10, name='Some Name', parent_id=parent.pk)
+ parent = ModelToValidate.objects.create(number=10, name="Some Name")
+ mtv = ModelToValidate(number=10, name="Some Name", parent_id=parent.pk)
self.assertIsNone(mtv.full_clean())
def test_limited_FK_raises_error(self):
# The limit_choices_to on the parent field says that a parent object's
# number attribute must be 10, so this should fail validation.
- parent = ModelToValidate.objects.create(number=11, name='Other Name')
- mtv = ModelToValidate(number=10, name='Some Name', parent_id=parent.pk)
- self.assertFailsValidation(mtv.full_clean, ['parent'])
+ parent = ModelToValidate.objects.create(number=11, name="Other Name")
+ mtv = ModelToValidate(number=10, name="Some Name", parent_id=parent.pk)
+ self.assertFailsValidation(mtv.full_clean, ["parent"])
def test_FK_validates_using_base_manager(self):
# Archived articles are not available through the default manager, only
# the base manager.
author = Author.objects.create(name="Randy", archived=True)
- article = Article(title='My Article', author=author)
+ article = Article(title="My Article", author=author)
self.assertIsNone(article.full_clean())
def test_wrong_email_value_raises_error(self):
- mtv = ModelToValidate(number=10, name='Some Name', email='not-an-email')
- self.assertFailsValidation(mtv.full_clean, ['email'])
+ mtv = ModelToValidate(number=10, name="Some Name", email="not-an-email")
+ self.assertFailsValidation(mtv.full_clean, ["email"])
def test_correct_email_value_passes(self):
- mtv = ModelToValidate(number=10, name='Some Name', email='valid@email.com')
+ mtv = ModelToValidate(number=10, name="Some Name", email="valid@email.com")
self.assertIsNone(mtv.full_clean())
def test_wrong_url_value_raises_error(self):
- mtv = ModelToValidate(number=10, name='Some Name', url='not a url')
- self.assertFieldFailsValidationWithMessage(mtv.full_clean, 'url', ['Enter a valid URL.'])
+ mtv = ModelToValidate(number=10, name="Some Name", url="not a url")
+ self.assertFieldFailsValidationWithMessage(
+ mtv.full_clean, "url", ["Enter a valid URL."]
+ )
def test_text_greater_that_charfields_max_length_raises_errors(self):
- mtv = ModelToValidate(number=10, name='Some Name' * 100)
- self.assertFailsValidation(mtv.full_clean, ['name'])
+ mtv = ModelToValidate(number=10, name="Some Name" * 100)
+ self.assertFailsValidation(mtv.full_clean, ["name"])
def test_malformed_slug_raises_error(self):
- mtv = ModelToValidate(number=10, name='Some Name', slug='##invalid##')
- self.assertFailsValidation(mtv.full_clean, ['slug'])
+ mtv = ModelToValidate(number=10, name="Some Name", slug="##invalid##")
+ self.assertFailsValidation(mtv.full_clean, ["slug"])
def test_full_clean_does_not_mutate_exclude(self):
mtv = ModelToValidate(f_with_custom_validator=42)
- exclude = ['number']
- self.assertFailsValidation(mtv.full_clean, ['name'], exclude=exclude)
+ exclude = ["number"]
+ self.assertFailsValidation(mtv.full_clean, ["name"], exclude=exclude)
self.assertEqual(len(exclude), 1)
- self.assertEqual(exclude[0], 'number')
+ self.assertEqual(exclude[0], "number")
class ArticleForm(forms.ModelForm):
class Meta:
model = Article
- exclude = ['author']
+ exclude = ["author"]
class ModelFormsTests(TestCase):
@classmethod
def setUpTestData(cls):
- cls.author = Author.objects.create(name='Joseph Kocherhans')
+ cls.author = Author.objects.create(name="Joseph Kocherhans")
def test_partial_validation(self):
# Make sure the "commit=False and set field values later" idiom still
# works with model validation.
data = {
- 'title': 'The state of model validation',
- 'pub_date': '2010-1-10 14:49:00'
+ "title": "The state of model validation",
+ "pub_date": "2010-1-10 14:49:00",
}
form = ArticleForm(data)
self.assertEqual(list(form.errors), [])
@@ -114,7 +123,7 @@ class ModelFormsTests(TestCase):
# validation, so the form should save cleanly even though pub_date is
# not allowed to be null.
data = {
- 'title': 'The state of model validation',
+ "title": "The state of model validation",
}
article = Article(author_id=self.author.id)
form = ArticleForm(data, instance=article)
@@ -125,17 +134,13 @@ class ModelFormsTests(TestCase):
def test_validation_with_invalid_blank_field(self):
# Even though pub_date is set to blank=True, an invalid value was
# provided, so it should fail validation.
- data = {
- 'title': 'The state of model validation',
- 'pub_date': 'never'
- }
+ data = {"title": "The state of model validation", "pub_date": "never"}
article = Article(author_id=self.author.id)
form = ArticleForm(data, instance=article)
- self.assertEqual(list(form.errors), ['pub_date'])
+ self.assertEqual(list(form.errors), ["pub_date"])
class GenericIPAddressFieldTests(ValidationAssertions, TestCase):
-
def test_correct_generic_ip_passes(self):
giptm = GenericIPAddressTestModel(generic_ip="1.2.3.4")
self.assertIsNone(giptm.full_clean())
@@ -148,13 +153,13 @@ class GenericIPAddressFieldTests(ValidationAssertions, TestCase):
def test_invalid_generic_ip_raises_error(self):
giptm = GenericIPAddressTestModel(generic_ip="294.4.2.1")
- self.assertFailsValidation(giptm.full_clean, ['generic_ip'])
+ self.assertFailsValidation(giptm.full_clean, ["generic_ip"])
giptm = GenericIPAddressTestModel(generic_ip="1:2")
- self.assertFailsValidation(giptm.full_clean, ['generic_ip'])
+ self.assertFailsValidation(giptm.full_clean, ["generic_ip"])
giptm = GenericIPAddressTestModel(generic_ip=1)
- self.assertFailsValidation(giptm.full_clean, ['generic_ip'])
+ self.assertFailsValidation(giptm.full_clean, ["generic_ip"])
giptm = GenericIPAddressTestModel(generic_ip=lazy(lambda: 1, int))
- self.assertFailsValidation(giptm.full_clean, ['generic_ip'])
+ self.assertFailsValidation(giptm.full_clean, ["generic_ip"])
def test_correct_v4_ip_passes(self):
giptm = GenericIPAddressTestModel(v4_ip="1.2.3.4")
@@ -162,9 +167,9 @@ class GenericIPAddressFieldTests(ValidationAssertions, TestCase):
def test_invalid_v4_ip_raises_error(self):
giptm = GenericIPAddressTestModel(v4_ip="294.4.2.1")
- self.assertFailsValidation(giptm.full_clean, ['v4_ip'])
+ self.assertFailsValidation(giptm.full_clean, ["v4_ip"])
giptm = GenericIPAddressTestModel(v4_ip="2001::2")
- self.assertFailsValidation(giptm.full_clean, ['v4_ip'])
+ self.assertFailsValidation(giptm.full_clean, ["v4_ip"])
def test_correct_v6_ip_passes(self):
giptm = GenericIPAddressTestModel(v6_ip="2001::2")
@@ -172,16 +177,16 @@ class GenericIPAddressFieldTests(ValidationAssertions, TestCase):
def test_invalid_v6_ip_raises_error(self):
giptm = GenericIPAddressTestModel(v6_ip="1.2.3.4")
- self.assertFailsValidation(giptm.full_clean, ['v6_ip'])
+ self.assertFailsValidation(giptm.full_clean, ["v6_ip"])
giptm = GenericIPAddressTestModel(v6_ip="1:2")
- self.assertFailsValidation(giptm.full_clean, ['v6_ip'])
+ self.assertFailsValidation(giptm.full_clean, ["v6_ip"])
def test_v6_uniqueness_detection(self):
# These two addresses are the same with different syntax
giptm = GenericIPAddressTestModel(generic_ip="2001::1:0:0:0:0:2")
giptm.save()
giptm = GenericIPAddressTestModel(generic_ip="2001:0:1:2")
- self.assertFailsValidation(giptm.full_clean, ['generic_ip'])
+ self.assertFailsValidation(giptm.full_clean, ["generic_ip"])
def test_v4_unpack_uniqueness_detection(self):
# These two are different, because we are not doing IPv4 unpacking
@@ -194,7 +199,7 @@ class GenericIPAddressFieldTests(ValidationAssertions, TestCase):
giptm = GenericIPAddrUnpackUniqueTest(generic_v4unpack_ip="::ffff:18.52.18.52")
giptm.save()
giptm = GenericIPAddrUnpackUniqueTest(generic_v4unpack_ip="18.52.18.52")
- self.assertFailsValidation(giptm.full_clean, ['generic_v4unpack_ip'])
+ self.assertFailsValidation(giptm.full_clean, ["generic_v4unpack_ip"])
def test_empty_generic_ip_passes(self):
giptm = GenericIPAddressTestModel(generic_ip="")