Skip to content

Saleor Core: the high performance, composable, headless commerce API.

Fix slug validation and generation for Attribute create (#12476)

Jakub17c8d807b3d1
diff --git a/saleor/graphql/attribute/mutations/mixins.py b/saleor/graphql/attribute/mutations/mixins.py
index 63529406df..1bb28c3191 100644
--- a/saleor/graphql/attribute/mutations/mixins.py
+++ b/saleor/graphql/attribute/mutations/mixins.py
@@ -5,6 +5,7 @@ from text_unidecode import unidecode
from ....attribute import ATTRIBUTE_PROPERTIES_CONFIGURATION, AttributeInputType
from ....attribute import models as models
from ....attribute.error_codes import AttributeErrorCode
+from ....core.utils import prepare_unique_slug
from ...core import ResolveInfo
from ...core.validators import validate_slug_and_generate_if_needed
@@ -43,8 +44,11 @@ class AttributeMixin:
)
is_swatch_attr = attribute_input_type == AttributeInputType.SWATCH
+
+ slug_list = list(attribute.values.values_list("slug", flat=True))
+
for value_data in values_input:
- cls._validate_value(attribute, value_data, is_swatch_attr)
+ cls._validate_value(attribute, value_data, is_swatch_attr, slug_list)
cls.check_values_are_unique(values_input, attribute)
@@ -54,6 +58,7 @@ class AttributeMixin:
attribute: models.Attribute,
value_data: dict,
is_swatch_attr: bool,
+ slug_list: list,
):
"""Validate the new attribute value."""
value = value_data.get("name")
@@ -72,8 +77,9 @@ class AttributeMixin:
else:
cls.validate_non_swatch_attr_value(value_data)
- slug_value = value
- value_data["slug"] = slugify(unidecode(slug_value))
+ slug_value = prepare_unique_slug(slugify(unidecode(value)), slug_list)
+ value_data["slug"] = slug_value
+ slug_list.append(slug_value)
attribute_value = models.AttributeValue(**value_data, attribute=attribute)
try:
@@ -116,10 +122,11 @@ class AttributeMixin:
@classmethod
def check_values_are_unique(cls, values_input: dict, attribute: models.Attribute):
# Check values uniqueness in case of creating new attribute.
- existing_values = attribute.values.values_list("slug", flat=True)
+ existing_names = attribute.values.values_list("name", flat=True)
+ existing_names = [name.lower().strip() for name in existing_names]
for value_data in values_input:
- slug = slugify(unidecode(value_data["name"]))
- if slug in existing_values:
+ name = unidecode(value_data["name"]).lower().strip()
+ if name in existing_names:
msg = (
f'Value {value_data["name"]} already exists within this attribute.'
)
@@ -131,10 +138,8 @@ class AttributeMixin:
}
)
- new_slugs = [
- slugify(unidecode(value_data["name"])) for value_data in values_input
- ]
- if len(set(new_slugs)) != len(new_slugs):
+ new_names = [value_data["name"].lower().strip() for value_data in values_input]
+ if len(set(new_names)) != len(new_names):
raise ValidationError(
{
cls.ATTRIBUTE_VALUES_FIELD: ValidationError(
diff --git a/saleor/graphql/attribute/tests/mutations/test_attribute_create.py b/saleor/graphql/attribute/tests/mutations/test_attribute_create.py
index e0226389a6..48b2e5ab9e 100644
--- a/saleor/graphql/attribute/tests/mutations/test_attribute_create.py
+++ b/saleor/graphql/attribute/tests/mutations/test_attribute_create.py
@@ -1298,3 +1298,43 @@ def test_create_attribute_with_non_unique_external_reference(
assert error["field"] == "externalReference"
assert error["code"] == AttributeErrorCode.UNIQUE.name
assert error["message"] == "Attribute with this External reference already exists."
+
+
+def test_create_attribute_similar_names(
+ staff_api_client,
+ permission_manage_product_types_and_attributes,
+ permission_manage_products,
+ product_type,
+):
+ # given
+ name_1 = "15"
+ name_2 = "1.5"
+
+ query = CREATE_ATTRIBUTE_MUTATION
+ variables = {
+ "input": {
+ "name": "Example name",
+ "type": AttributeTypeEnum.PRODUCT_TYPE.name,
+ "values": [{"name": name_1}, {"name": name_2}],
+ }
+ }
+
+ # when
+ response = staff_api_client.post_graphql(
+ query,
+ variables,
+ permissions=[
+ permission_manage_product_types_and_attributes,
+ permission_manage_products,
+ ],
+ )
+
+ # then
+ assert slugify(name_1) == slugify(name_2)
+ content = get_graphql_content(response)
+ errors = content["data"]["attributeCreate"]["errors"]
+ assert len(errors) == 0
+ values_edges = content["data"]["attributeCreate"]["attribute"]["choices"]["edges"]
+ assert len(values_edges) == 2
+ slugs = [node["node"]["slug"] for node in values_edges]
+ assert set(slugs) == {"15", "15-2"}
diff --git a/saleor/graphql/attribute/tests/mutations/test_attribute_update.py b/saleor/graphql/attribute/tests/mutations/test_attribute_update.py
index 089b08567c..221cd839c3 100644
--- a/saleor/graphql/attribute/tests/mutations/test_attribute_update.py
+++ b/saleor/graphql/attribute/tests/mutations/test_attribute_update.py
@@ -7,7 +7,7 @@ from django.utils.functional import SimpleLazyObject
from freezegun import freeze_time
from .....attribute.error_codes import AttributeErrorCode
-from .....attribute.models import Attribute
+from .....attribute.models import Attribute, AttributeValue
from .....core.utils.json_serializer import CustomJsonEncoder
from .....webhook.event_types import WebhookEventAsyncType
from .....webhook.payloads import generate_meta, generate_requestor
@@ -609,6 +609,12 @@ def test_update_attribute_slug_and_name(
"Provided values are not unique.",
AttributeErrorCode.UNIQUE,
),
+ (
+ "Red color ",
+ "Red color",
+ "Provided values are not unique.",
+ AttributeErrorCode.UNIQUE,
+ ),
),
)
def test_update_attribute_and_add_attribute_values_errors(
@@ -811,3 +817,35 @@ def test_update_attribute_with_non_unique_external_reference(
assert error["field"] == "externalReference"
assert error["code"] == AttributeErrorCode.UNIQUE.name
assert error["message"] == "Attribute with this External reference already exists."
+
+
+def test_update_attribute_name_similar_value(
+ staff_api_client,
+ attribute_without_values,
+ permission_manage_product_types_and_attributes,
+):
+ # given
+ query = UPDATE_ATTRIBUTE_MUTATION
+ attribute = attribute_without_values
+ AttributeValue.objects.create(attribute=attribute, name="15", slug="15")
+ name = "1.5"
+ node_id = graphene.Node.to_global_id("Attribute", attribute.id)
+ variables = {
+ "input": {"addValues": [{"name": 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"]) == 0
+ values_edges = data["attribute"]["choices"]["edges"]
+ assert len(values_edges) == 2
+ slugs = [node["node"]["slug"] for node in values_edges]
+ assert set(slugs) == {"15", "15-2"}
diff --git a/saleor/graphql/product/tests/queries/test_product_query.py b/saleor/graphql/product/tests/queries/test_product_query.py
index f29b98f852..8f5a59f1d3 100644
--- a/saleor/graphql/product/tests/queries/test_product_query.py
+++ b/saleor/graphql/product/tests/queries/test_product_query.py
@@ -2198,7 +2198,7 @@ def test_query_product_media_sorting_asc(
media = content["data"]["product"]["media"]
_, media1 = graphene.Node.from_global_id(media[0]["id"])
_, media2 = graphene.Node.from_global_id(media[1]["id"])
- assert media1 < media2
+ assert int(media1) < int(media2)
def test_query_product_media_sorting_desc(
@@ -2223,7 +2223,7 @@ def test_query_product_media_sorting_desc(
media = content["data"]["product"]["media"]
_, media1 = graphene.Node.from_global_id(media[0]["id"])
_, media2 = graphene.Node.from_global_id(media[1]["id"])
- assert media1 > media2
+ assert int(media1) > int(media2)
def test_query_product_media_sorting_default(