From 0123a2c489a467c253d18e1b1a38e17fffa1de8e Mon Sep 17 00:00:00 2001 From: Mariana Bedran Lesche Date: Mon, 7 Jan 2019 16:04:16 -0300 Subject: [PATCH] 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. --- tests/test_validators.py | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/tests/test_validators.py b/tests/test_validators.py index fe31ba235..c295b464f 100644 --- a/tests/test_validators.py +++ b/tests/test_validators.py @@ -118,6 +118,26 @@ class TestUniquenessValidation(TestCase): serializer = UniquenessIntegerSerializer(data={'integer': 'abc'}) assert serializer.is_valid() + def test_validate_uniqueness_in_bulk_creation(self): + data = [{'username': 'existing'}, {'username': 'non-existing'}] + serializer = UniquenessSerializer(data=data, many=True) + assert not serializer.is_valid() + assert serializer.errors == [ + {'username': ['uniqueness model with this username already exists.']}, + {}, + ] + + def test_validate_uniqueness_between_data_items_in_bulk_creation(self): + data = [{'username': 'non-existing'}, {'username': 'non-existing'}] + serializer = UniquenessSerializer(data=data, many=True) + assert serializer.is_valid() + assert serializer.save() + # assert not serializer.is_valid() + # assert serializer.errors == [ + # {'username': ['uniqueness model with this username already exists.']}, + # {'username': ['uniqueness model with this username already exists.']}, + # ] + # Tests for `UniqueTogetherValidator` # -----------------------------------