Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Fix attribute mutations validation (#10699)
Iga Karbowiak760e95a0187d
diff --git a/saleor/graphql/attribute/mutations.py b/saleor/graphql/attribute/mutations.pyindex 3093dc19b5..ccd52c4444 100644--- a/saleor/graphql/attribute/mutations.py+++ b/saleor/graphql/attribute/mutations.py@@ -19,6 +19,7 @@ from ...core.permissions import (from ...core.tracing import traced_atomic_transactionfrom ...core.utils import generate_unique_slugfrom ...product import models as product_models+from ..core.descriptions import DEPRECATED_IN_3X_INPUTfrom ..core.enums import MeasurementUnitsEnumfrom ..core.fields import JSONStringfrom ..core.inputs import ReorderInput@@ -193,8 +194,18 @@ class BaseReorderAttributeValuesMutation(BaseMutation):class AttributeValueInput(graphene.InputObjectType):value = graphene.String(description=AttributeValueDescriptions.VALUE)- rich_text = JSONString(description=AttributeValueDescriptions.RICH_TEXT)- plain_text = graphene.String(description=AttributeValueDescriptions.PLAIN_TEXT)+ rich_text = JSONString(+ description=AttributeValueDescriptions.RICH_TEXT+ + DEPRECATED_IN_3X_INPUT+ + "The rich text attribute hasn't got predefined value, so can be specified "+ "only from instance that supports the given attribute."+ )+ plain_text = graphene.String(+ description=AttributeValueDescriptions.PLAIN_TEXT+ + DEPRECATED_IN_3X_INPUT+ + "The plain text attribute hasn't got predefined value, so can be specified "+ "only from instance that supports the given attribute."+ )file_url = graphene.String(required=False,description="URL of the file attribute. Every time, a new value is created.",@@ -279,6 +290,7 @@ class AttributeUpdateInput(graphene.InputObjectType):class AttributeMixin:# must be redefined by inheriting classesATTRIBUTE_VALUES_FIELD: str+ ONLY_SWATCH_FIELDS = ["file_url", "content_type", "value"]@classmethoddef clean_values(cls, cleaned_input, attribute):@@ -295,9 +307,8 @@ class AttributeMixin:returnif (- attribute_input_type- in [AttributeInputType.FILE, AttributeInputType.REFERENCE]- and values_input+ values_input+ and attribute_input_type not in AttributeInputType.TYPES_WITH_CHOICES):raise ValidationError({@@ -309,30 +320,37 @@ class AttributeMixin:})- is_numeric_attr = attribute_input_type == AttributeInputType.NUMERICis_swatch_attr = attribute_input_type == AttributeInputType.SWATCHfor value_data in values_input:- cls.validate_value(attribute, value_data, is_numeric_attr, is_swatch_attr)+ cls._validate_value(attribute, value_data, is_swatch_attr)cls.check_values_are_unique(values_input, attribute)@classmethod- def validate_value(+ def _validate_value(cls,attribute: models.Attribute,value_data: dict,- is_numeric_attr: bool,is_swatch_attr: bool,):- value = value_data["name"]- cls.clean_value_input_data(value_data, is_swatch_attr)+ """Validate the new attribute value."""+ value = value_data.get("name")+ if value is None:+ raise ValidationError(+ {+ cls.ATTRIBUTE_VALUES_FIELD: ValidationError(+ "The name field is required.",+ code=AttributeErrorCode.REQUIRED.value,+ )+ }+ )- if is_numeric_attr:- cls.validate_numeric_value(value)- elif is_swatch_attr:+ if is_swatch_attr:cls.validate_swatch_attr_value(value_data)+ else:+ cls.validate_non_swatch_attr_value(value_data)- slug_value = value if not is_numeric_attr else value.replace(".", "_")+ slug_value = valuevalue_data["slug"] = slugify(unidecode(slug_value))attribute_value = models.AttributeValue(**value_data, attribute=attribute)@@ -342,14 +360,15 @@ class AttributeMixin:for field, err in validation_errors.error_dict.items():if field == "attribute":continue- raise ValidationError({cls.ATTRIBUTE_VALUES_FIELD: err})+ errors = []+ for error in err:+ error.code = AttributeErrorCode.INVALID.value+ errors.append(error)+ raise ValidationError({cls.ATTRIBUTE_VALUES_FIELD: errors})@classmethod- def clean_value_input_data(cls, value_data: dict, is_swatch_attr: bool):- swatch_fields = ["file_url", "content_type", "value"]- if not is_swatch_attr and any(- [value_data.get(field) for field in swatch_fields]- ):+ def validate_non_swatch_attr_value(cls, value_data: dict):+ if any([value_data.get(field) for field in cls.ONLY_SWATCH_FIELDS]):raise ValidationError({cls.ATTRIBUTE_VALUES_FIELD: ValidationError(@@ -360,20 +379,6 @@ class AttributeMixin:})- @classmethod- def validate_numeric_value(cls, value):- try:- float(value)- except ValueError:- raise ValidationError(- {- cls.ATTRIBUTE_VALUES_FIELD: ValidationError(- "Value of numeric attribute must be numeric.",- code=AttributeErrorCode.INVALID.value,- )- }- )-@classmethoddef validate_swatch_attr_value(cls, value_data: dict):if value_data.get("value") and value_data.get("file_url"):@@ -667,10 +672,9 @@ class AttributeValueCreate(AttributeMixin, ModelMutation):input_type = instance.attribute.input_typeis_swatch_attr = input_type == AttributeInputType.SWATCH- only_swatch_fields = ["file_url", "content_type"]errors = {}if not is_swatch_attr:- for field in only_swatch_fields:+ for field in cls.ONLY_SWATCH_FIELDS:if cleaned_input.get(field):errors[field] = ValidationError(f"The field {field} can be defined only for swatch attributes.",@@ -682,6 +686,7 @@ class AttributeValueCreate(AttributeMixin, ModelMutation):except ValidationError as error:errors["value"] = error.error_dict[cls.ATTRIBUTE_VALUES_FIELD]errors["fileUrl"] = error.error_dict[cls.ATTRIBUTE_VALUES_FIELD]+if errors:raise ValidationError(errors)diff --git a/saleor/graphql/attribute/tests/mutations/test_attribute_create.py b/saleor/graphql/attribute/tests/mutations/test_attribute_create.pyindex eae3a01ee1..8faa2f68ac 100644--- a/saleor/graphql/attribute/tests/mutations/test_attribute_create.py+++ b/saleor/graphql/attribute/tests/mutations/test_attribute_create.py@@ -211,27 +211,10 @@ def test_create_numeric_attribute_and_attribute_values(# thencontent = get_graphql_content(response)- assert not content["data"]["attributeCreate"]["errors"]data = content["data"]["attributeCreate"]-- # Check if the attribute was correctly created- assert data["attribute"]["name"] == attribute_name- assert data["attribute"]["slug"] == slugify(- attribute_name- ), "The default slug should be the slugified name"- assert (- data["attribute"]["productTypes"]["edges"] == []- ), "The attribute should not have been assigned to a product type"-- # Check if the attribute values were correctly created- assert data["attribute"]["type"] == AttributeTypeEnum.PRODUCT_TYPE.name- assert data["attribute"]["unit"] == MeasurementUnitsEnum.M.name- assert data["attribute"]["inputType"] == AttributeInputTypeEnum.NUMERIC.name- assert data["attribute"]["filterableInStorefront"] is True- assert data["attribute"]["filterableInDashboard"] is True- assert data["attribute"]["availableInGrid"] is True- assert data["attribute"]["storefrontSearchPosition"] == 0- assert data["attribute"]["choices"]["edges"] == []+ assert len(data["errors"]) == 1+ assert data["errors"][0]["code"] == AttributeErrorCode.INVALID.name+ assert data["errors"][0]["field"] == "values"def test_create_numeric_attribute_and_attribute_values_not_numeric_value_provided(diff --git a/saleor/graphql/attribute/tests/mutations/test_attribute_update.py b/saleor/graphql/attribute/tests/mutations/test_attribute_update.pyindex 5904854319..76a90fce93 100644--- a/saleor/graphql/attribute/tests/mutations/test_attribute_update.py+++ b/saleor/graphql/attribute/tests/mutations/test_attribute_update.py@@ -203,6 +203,37 @@ def test_update_empty_attribute_and_add_values(assert attribute.values.filter(name=attribute_value_name).exists()+def test_update_empty_attribute_and_add_values_name_not_given(+ staff_api_client,+ color_attribute_without_values,+ permission_manage_product_types_and_attributes,+):+ # given+ query = UPDATE_ATTRIBUTE_MUTATION+ attribute = color_attribute_without_values+ node_id = graphene.Node.to_global_id("Attribute", attribute.id)+ variables = {+ "id": node_id,+ "input": {+ "addValues": [{"value": "abc"}],+ "removeValues": [],+ },+ }++ # when+ response = staff_api_client.post_graphql(+ query, variables, permissions=[permission_manage_product_types_and_attributes]+ )++ # then+ content = get_graphql_content(response)+ attribute.refresh_from_db()+ data = content["data"]["attributeUpdate"]+ assert len(data["errors"]) == 1+ assert data["errors"][0]["code"] == AttributeErrorCode.REQUIRED.name+ assert data["errors"][0]["field"] == "addValues"++def test_update_attribute_with_file_input_type(staff_api_client,file_attribute_with_file_input_type_without_values,@@ -347,6 +378,31 @@ def test_update_attribute_with_file_input_type_invalid_settings(assert {error["code"] for error in errors} == {AttributeErrorCode.INVALID.name}+def test_update_attribute_provide_existing_value_name(+ staff_api_client, color_attribute, permission_manage_product_types_and_attributes+):+ # given+ query = UPDATE_ATTRIBUTE_MUTATION+ attribute = color_attribute+ value = color_attribute.values.first()+ node_id = graphene.Node.to_global_id("Attribute", attribute.id)+ variables = {+ "input": {"addValues": [{"name": value.name}], "removeValues": []},+ "id": node_id,+ }++ # when+ response = staff_api_client.post_graphql(+ query, variables, permissions=[permission_manage_product_types_and_attributes]+ )++ # then+ content = get_graphql_content(response)+ attribute.refresh_from_db()+ data = content["data"]["attributeUpdate"]+ assert len(data["errors"]) == 1++UPDATE_ATTRIBUTE_SLUG_MUTATION = """mutation updateAttribute($id: ID!, $slug: String) {diff --git a/saleor/graphql/attribute/tests/mutations/test_attribute_value_update.py b/saleor/graphql/attribute/tests/mutations/test_attribute_value_update.pyindex c6f9c2f874..2bc569248c 100644--- a/saleor/graphql/attribute/tests/mutations/test_attribute_value_update.py+++ b/saleor/graphql/attribute/tests/mutations/test_attribute_value_update.py@@ -435,3 +435,29 @@ def test_update_attribute_value_invalid_input_data(assert len(data["errors"]) == 1assert data["errors"][0]["code"] == AttributeErrorCode.INVALID.nameassert data["errors"][0]["field"] == field+++def test_update_attribute_value_swatch_attr_value(+ staff_api_client,+ swatch_attribute,+ permission_manage_product_types_and_attributes,+):+ # given+ query = UPDATE_ATTRIBUTE_VALUE_MUTATION+ value = swatch_attribute.values.first()+ node_id = graphene.Node.to_global_id("AttributeValue", value.id)+ new_value = "#FFFFF"+ variables = {"input": {"value": new_value}, "id": node_id}++ # when+ response = staff_api_client.post_graphql(+ query, variables, permissions=[permission_manage_product_types_and_attributes]+ )++ # then+ content = get_graphql_content(response)+ data = content["data"]["attributeValueUpdate"]+ value.refresh_from_db()+ assert data["attributeValue"]["name"] == value.name+ assert data["attributeValue"]["slug"] == value.slug+ assert data["attributeValue"]["value"] == new_valuediff --git a/saleor/graphql/schema.graphql b/saleor/graphql/schema.graphqlindex 3b3f5996c5..566d4b4560 100644--- a/saleor/graphql/schema.graphql+++ b/saleor/graphql/schema.graphql@@ -20286,11 +20286,15 @@ input AttributeValueCreateInput {Represents the text of the attribute value, includes formatting.Rich text format. For reference see https://editorjs.io/++ DEPRECATED: this field will be removed in Saleor 4.0.The rich text attribute hasn't got predefined value, so can be specified only from instance that supports the given attribute."""richText: JSONString"""Represents the text of the attribute value, plain text without formating.++ DEPRECATED: this field will be removed in Saleor 4.0.The plain text attribute hasn't got predefined value, so can be specified only from instance that supports the given attribute."""plainText: String@@ -20376,11 +20380,15 @@ input AttributeValueUpdateInput {Represents the text of the attribute value, includes formatting.Rich text format. For reference see https://editorjs.io/++ DEPRECATED: this field will be removed in Saleor 4.0.The rich text attribute hasn't got predefined value, so can be specified only from instance that supports the given attribute."""richText: JSONString"""Represents the text of the attribute value, plain text without formating.++ DEPRECATED: this field will be removed in Saleor 4.0.The plain text attribute hasn't got predefined value, so can be specified only from instance that supports the given attribute."""plainText: String