Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Add manual validation for unique values
Marcin Gębalabe75216f009a
diff --git a/saleor/graphql/product/mutations/attributes.py b/saleor/graphql/product/mutations/attributes.pyindex d252a1fec1..b7934d1f9d 100644--- a/saleor/graphql/product/mutations/attributes.py+++ b/saleor/graphql/product/mutations/attributes.py@@ -24,7 +24,10 @@ from ..types import Attribute, AttributeValueclass AttributeValueCreateInput(graphene.InputObjectType):name = graphene.String(required=True, description=AttributeValueDescriptions.NAME)- value = graphene.String(description=AttributeValueDescriptions.VALUE)+ value = graphene.String(+ description=AttributeValueDescriptions.VALUE,+ deprecation_reason="This field is depracated",+ )class AttributeCreateInput(graphene.InputObjectType):@@ -494,6 +497,13 @@ class AttributeClearPrivateMeta(ClearMetaBaseMutation):public = False+def validate_value_is_unique(attribute: models.Attribute, value: models.AttributeValue):+ """Check if the attribute value is unique within the attribute it belongs to."""+ duplicated_values = attribute.values.exclude(pk=value.pk).filter(slug=value.slug)+ if duplicated_values.exists():+ raise ValidationError({"name": f"Value with slug {value.slug} already exists."})++class AttributeValueCreate(ModelMutation):attribute = graphene.Field(Attribute, description="The updated attribute.")@@ -518,6 +528,11 @@ class AttributeValueCreate(ModelMutation):cleaned_input["slug"] = slugify(cleaned_input["name"])return cleaned_input+ @classmethod+ def clean_instance(cls, instance):+ validate_value_is_unique(instance.attribute, instance)+ super().clean_instance(instance)+@classmethoddef perform_mutation(cls, _root, info, attribute_id, input):attribute = cls.get_node_or_error(info, attribute_id, only_type=Attribute)@@ -555,6 +570,11 @@ class AttributeValueUpdate(ModelMutation):cleaned_input["slug"] = slugify(cleaned_input["name"])return cleaned_input+ @classmethod+ def clean_instance(cls, instance):+ validate_value_is_unique(instance.attribute, instance)+ super().clean_instance(instance)+@classmethoddef success_response(cls, instance):response = super().success_response(instance)diff --git a/tests/api/test_attributes.py b/tests/api/test_attributes.pyindex cbccde6837..eb7621de98 100644--- a/tests/api/test_attributes.py+++ b/tests/api/test_attributes.py@@ -2,12 +2,14 @@ from typing import Unionimport grapheneimport pytest+from django.core.exceptions import ValidationErrorfrom django.db.models import Qfrom django.template.defaultfilters import slugifyfrom graphene.utils.str_converters import to_camel_casefrom saleor.graphql.core.utils import snake_to_camel_casefrom saleor.graphql.product.enums import AttributeTypeEnum, AttributeValueType+from saleor.graphql.product.mutations.attributes import validate_value_is_uniquefrom saleor.graphql.product.types.attributes import resolve_attribute_value_typefrom saleor.graphql.product.types.products import resolve_attribute_listfrom saleor.graphql.product.utils import attributes_to_json@@ -23,6 +25,22 @@ from saleor.product.models import (from tests.api.utils import get_graphql_content+def test_validate_value_is_unique(color_attribute):+ value = color_attribute.values.first()++ # a new value but with existing slug should raise an error+ with pytest.raises(ValidationError):+ validate_value_is_unique(color_attribute, AttributeValue(slug=value.slug))++ # a new value with a new slug should pass+ validate_value_is_unique(+ color_attribute, AttributeValue(slug="spanish-inquisition")+ )++ # value that already belongs to the attribute shouldn't be taken into account+ validate_value_is_unique(color_attribute, value)++def test_attributes_to_json(product, color_attribute, size_attribute):attribute_values_count = AttributeValue.objects.count()@@ -807,7 +825,7 @@ def test_create_attribute_value_not_unique_name(data = content["data"]["attributeValueCreate"]assert data["errors"]assert data["errors"][0]["message"]- assert not data["errors"][0]["field"]+ assert data["errors"][0]["field"] == "name"UPDATE_ATTRIBUTE_VALUE_QUERY = """@@ -869,7 +887,7 @@ def test_update_attribute_value_name_not_unique(data = content["data"]["attributeValueUpdate"]assert data["errors"]assert data["errors"][0]["message"]- assert not data["errors"][0]["field"]+ assert data["errors"][0]["field"] == "name"def test_update_same_attribute_value(