Skip to content

Commit 0123a2c

Browse files
maribedranmari
authored and
mari
committed
Add tests for unique validation for bulk creation in model serializers
The unique validation in model serializers only check for existing entries on the database. If the serializer is instanced with many=True and receives more than one item in the data argument having the same value for a unique field, the .is_valid() method returns True, but calling .save() will raise an IntegrityError.
1 parent ac0f0a1 commit 0123a2c

File tree

1 file changed

+20
-0
lines changed

1 file changed

+20
-0
lines changed

tests/test_validators.py

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -118,6 +118,26 @@ def test_value_error_treated_as_not_unique(self):
118118
serializer = UniquenessIntegerSerializer(data={'integer': 'abc'})
119119
assert serializer.is_valid()
120120

121+
def test_validate_uniqueness_in_bulk_creation(self):
122+
data = [{'username': 'existing'}, {'username': 'non-existing'}]
123+
serializer = UniquenessSerializer(data=data, many=True)
124+
assert not serializer.is_valid()
125+
assert serializer.errors == [
126+
{'username': ['uniqueness model with this username already exists.']},
127+
{},
128+
]
129+
130+
def test_validate_uniqueness_between_data_items_in_bulk_creation(self):
131+
data = [{'username': 'non-existing'}, {'username': 'non-existing'}]
132+
serializer = UniquenessSerializer(data=data, many=True)
133+
assert serializer.is_valid()
134+
assert serializer.save()
135+
# assert not serializer.is_valid()
136+
# assert serializer.errors == [
137+
# {'username': ['uniqueness model with this username already exists.']},
138+
# {'username': ['uniqueness model with this username already exists.']},
139+
# ]
140+
121141

122142
# Tests for `UniqueTogetherValidator`
123143
# -----------------------------------

0 commit comments

Comments
 (0)