Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Properly resolve IDs when adding attributes to products
NyanKiyoshib2fb9b31f935
diff --git a/saleor/graphql/product/interfaces.py b/saleor/graphql/product/interfaces.pynew file mode 100644index 0000000000..61db2c2105--- /dev/null+++ b/saleor/graphql/product/interfaces.py@@ -0,0 +1,10 @@+from dataclasses import dataclass+from typing import List++from ...product import models+++@dataclass(frozen=True)+class ResolvedAttributeInput:+ instance: models.Attribute+ values: List[str]diff --git a/saleor/graphql/product/mutations/products.py b/saleor/graphql/product/mutations/products.pyindex 864962b2ae..67192f398c 100644--- a/saleor/graphql/product/mutations/products.py+++ b/saleor/graphql/product/mutations/products.py@@ -401,7 +401,12 @@ class AttributeValueInput(InputObjectType):)slug = graphene.String(description="Slug of an attribute.")values = graphene.List(- graphene.String, required=True, description="Value of an attribute."+ graphene.String,+ required=True,+ description=(+ "The value or slug of an attribute to resolve. "+ "If the passed value is non-existent, it will be created."+ ),)diff --git a/saleor/graphql/product/utils.py b/saleor/graphql/product/utils.pyindex bcef424d9d..7ccbfa58ce 100644--- a/saleor/graphql/product/utils.py+++ b/saleor/graphql/product/utils.py@@ -1,9 +1,14 @@from collections import defaultdict-from typing import List+from typing import Dict, List+import graphenefrom django.utils.text import slugifyfrom ...product import AttributeInputType, models+from .interfaces import ResolvedAttributeInput++attribute_input_type = List[ResolvedAttributeInput]+attribute_map_type = Dict[str, models.Attribute]def validate_attribute_input(instance: models.Attribute, values: List[str]):@@ -16,56 +21,84 @@ def validate_attribute_input(instance: models.Attribute, values: List[str]):raise ValueError(f"A {instance.input_type} attribute must take only one value")-def attributes_to_json(attribute_value_input: List[dict], attributes_queryset):+def _resolve_attributes_input(+ attribute_input: List[dict],+ attributes_map_by_slug: attribute_map_type,+ attributes_map_by_id: attribute_map_type,+) -> attribute_input_type:+ """This resolves a raw GraphQL input to proper attribute. Its job is to ensure+ a backward compatibility with passing attributes by slug."""++ resolved_input = [] # type: List[ResolvedAttributeInput]++ for attribute_input in attribute_input:+ if "slug" in attribute_input:+ attribute = attributes_map_by_slug.get(attribute_input["slug"])+ elif "id" in attribute_input:+ type_, attribute_id = graphene.Node.from_global_id(attribute_input["id"])+ if type_ != "Attribute":+ raise ValueError(f"Couldn't resolve to a node: {attribute_input['id']}")+ attribute = attributes_map_by_id.get(attribute_id)+ else:+ raise ValueError("The value ID or slug was not provided")++ if not attribute:+ raise ValueError(+ "The given attribute doesn't belong to given product type."+ )++ values = attribute_input.get("values")+ validate_attribute_input(attribute, values)++ resolved_input.append(ResolvedAttributeInput(instance=attribute, values=values))++ return resolved_input+++def attributes_to_json(+ raw_input: List[dict], attributes_queryset+) -> Dict[str, List[str]]:"""Transform attributes to the HStore representation.Attributes configuration per product is stored in a HStore field asa dict of IDs. This function transforms the list of `AttributeValueInput`objects to this format."""- attributes_map_by_slug = {}- attributes_map_by_id = {}++ attributes_json = defaultdict(list)+ passed_slugs = set()++ attributes_map_by_slug = {} # type: attribute_map_type+ attributes_map_by_id = {} # type: attribute_map_typefor attr in attributes_queryset:attributes_map_by_slug[attr.slug] = attr- attributes_map_by_id[attr.id] = attr+ attributes_map_by_id[str(attr.id)] = attr- attributes_json = defaultdict(list)- passed_slugs = set()+ resolved_input = _resolve_attributes_input(+ raw_input, attributes_map_by_slug, attributes_map_by_id+ )values_map = {}for attr in attributes_queryset:for value in attr.values.all():values_map[value.slug] = value.id- for attribute_input in attribute_value_input:- if "slug" in attribute_input:- attribute = attributes_map_by_slug.get(attribute_input["slug"])- elif "id" in attribute_input:- attribute = attributes_map_by_id.get(attribute_input["id"])- else:- raise ValueError("The value ID or slug was not provided")-- if not attribute:- raise ValueError(- "The given attribute doesn't belong to given product type."- )-- passed_slugs.add(attribute.slug)-- values = attribute_input.get("values")- validate_attribute_input(attribute, values)+ for item in resolved_input:+ passed_slugs.add(item.instance.slug)- for value in values:+ for value in item.values:value_id = values_map.get(value)if value_id is None:# `value_id` was not found; create a new AttributeValue# instance from the provided `value`.- obj = attribute.values.get_or_create(name=value, slug=slugify(value))[0]+ obj = item.instance.values.get_or_create(+ name=value, slug=slugify(value)+ )[0]value_id = obj.pk- attributes_json[str(attribute.pk)].append(str(value_id))+ attributes_json[str(item.instance.pk)].append(str(value_id))# Check that all required attributes were passedfor missing_slug in attributes_map_by_slug.keys() ^ passed_slugs:diff --git a/tests/api/test_attributes.py b/tests/api/test_attributes.pyindex a170dda556..e3ddc82567 100644--- a/tests/api/test_attributes.py+++ b/tests/api/test_attributes.py@@ -13,31 +13,36 @@ from saleor.product.models import Attribute, AttributeValue, Category, ProductTyfrom tests.api.utils import get_graphql_content-def test_attributes_to_json(product, color_attribute):+def test_attributes_to_json(product, color_attribute, size_attribute):+ attribute_values_count = AttributeValue.objects.count()++ attribute_id = graphene.Node.to_global_id("Attribute", color_attribute.id)color_value = color_attribute.values.first()# test transforming slugs of existing attributes to IDs- input_data = [{"id": color_attribute.id, "values": [color_value.slug]}]+ input_data = [{"id": attribute_id, "values": [color_value.slug]}]attrs_qs = product.product_type.product_attributes.all()ids = attributes_to_json(input_data, attrs_qs)assert str(color_attribute.pk) in idsassert ids[str(color_attribute.pk)] == [str(color_value.pk)]+ assert (+ AttributeValue.objects.count() == attribute_values_count+ ), "No new values should been created"# test creating a new attribute value- input_data = [{"id": color_attribute.id, "values": ["Space Grey"]}]+ input_data = [{"id": attribute_id, "values": ["Space Grey"]}]ids = attributes_to_json(input_data, attrs_qs)new_value = AttributeValue.objects.get(slug="space-grey")+ attribute_values_count += 1assert str(color_attribute.pk) in idsassert ids[str(color_attribute.pk)] == [str(new_value.pk)]- # test passing an attribute that doesn't belong to this product raises- # an error- input_data = [{"id": -1, "values": ["not-a-value"]}]- with pytest.raises(ValueError) as exc:- attributes_to_json(input_data, attrs_qs)- assert exc.value.args == (- "The given attribute doesn't belong to given product type.",- )+ # test passing the newly created value by slug+ input_data = [{"id": attribute_id, "values": ["space-grey"]}]+ attributes_to_json(input_data, attrs_qs)+ assert (+ AttributeValue.objects.count() == attribute_values_count+ ), "Only one new value should have been created"# WARNING: Passing by slug will be dropped in a future release@@ -83,8 +88,37 @@ def test_attributes_to_json_missing_required_value(product, color_attribute, inpassert exc.value.args == ("color expects a value but none were given",)+def test_attributes_to_json_id_not_in_product_type(product, size_attribute):+ attrs_qs = product.product_type.product_attributes.all()++ # Pass an id not belonging to the product type+ input_data = [+ {+ "id": graphene.Node.to_global_id("Attribute", size_attribute.pk),+ "values": ["a-value"],+ }+ ]+ with pytest.raises(ValueError) as exc:+ attributes_to_json(input_data, attrs_qs)+ assert exc.value.args == (+ "The given attribute doesn't belong to given product type.",+ )+++def test_attributes_to_json_invalid_id_type(product):+ attrs_qs = product.product_type.product_attributes.all()+ invalid_id = graphene.Node.to_global_id("Invalid", 1)++ # Pass an id of invalid type+ input_data = [{"id": invalid_id, "values": ["a-value"]}]+ with pytest.raises(ValueError) as exc:+ attributes_to_json(input_data, attrs_qs)+ assert exc.value.args == (f"Couldn't resolve to a node: {invalid_id}",)++def test_attributes_to_json_without_values(product, color_attribute):- input_data = [{"id": color_attribute.id, "values": []}]+ attribute_id = graphene.Node.to_global_id("Attribute", color_attribute.id)+ input_data = [{"id": attribute_id, "values": []}]attrs_qs = product.product_type.product_attributes.all()# The attribute should be ignored and raise no error as the value is not required@@ -95,6 +129,7 @@ def test_attributes_to_json_duplicated_slug(product, color_attribute, size_attri# It's possible to have a value with the same slug but for a different attribute.# Ensure that `attributes_to_json` works in that case.+ attribute_id = graphene.Node.to_global_id("Attribute", color_attribute.id)color_value = color_attribute.values.first()# Create a fake duplicated value.@@ -102,7 +137,7 @@ def test_attributes_to_json_duplicated_slug(product, color_attribute, size_attrislug=color_value.slug, name="Duplicated value", attribute=size_attribute)- input_data = [{"id": color_attribute.id, "values": [color_value.slug]}]+ input_data = [{"id": attribute_id, "values": [color_value.slug]}]attrs_qs = product.product_type.product_attributes.all()ids = attributes_to_json(input_data, attrs_qs)assert str(color_attribute.pk) in idsdiff --git a/tests/api/test_product.py b/tests/api/test_product.pyindex 9c3c3d87c8..492ee44f66 100644--- a/tests/api/test_product.py+++ b/tests/api/test_product.py@@ -740,11 +740,11 @@ def test_create_product(# Default attribute defined in product_type fixturecolor_attr = product_type.product_attributes.get(name="Color")color_value_slug = color_attr.values.first().slug- color_attr_slug = color_attr.slug+ color_attr_id = graphene.Node.to_global_id("Attribute", color_attr.id)# Add second attributeproduct_type.product_attributes.add(size_attribute)- size_attr_slug = product_type.product_attributes.get(name="Size").slug+ size_attr_id = graphene.Node.to_global_id("Attribute", size_attribute.id)non_existent_attr_value = "The cake is a lie"# test creating root product@@ -758,8 +758,8 @@ def test_create_product("taxCode": product_tax_rate,"basePrice": product_price,"attributes": [- {"slug": color_attr_slug, "values": [color_value_slug]},- {"slug": size_attr_slug, "values": [non_existent_attr_value]},+ {"id": color_attr_id, "values": [color_value_slug]},+ {"id": size_attr_id, "values": [non_existent_attr_value]},],}@@ -1106,11 +1106,14 @@ def test_update_product_can_only_assign_multiple_values_to_valid_input_types(name="multi", slug="multi-vals", input_type=AttributeInputType.MULTISELECT)multi_values_attr.product_types.add(product.product_type)+ multi_values_attr_id = graphene.Node.to_global_id("Attribute", multi_values_attr.id)++ color_attribute_id = graphene.Node.to_global_id("Attribute", color_attribute.id)# Try to assign multiple values from an attribute that does not support such thingsvariables = {"productId": graphene.Node.to_global_id("Product", product.pk),- "attributes": [{"slug": color_attribute.slug, "values": ["red", "blue"]}],+ "attributes": [{"id": color_attribute_id, "values": ["red", "blue"]}],}data = get_graphql_content(staff_api_client.post_graphql(SET_ATTRIBUTES_TO_PRODUCT_QUERY, variables)@@ -1123,11 +1126,11 @@ def test_update_product_can_only_assign_multiple_values_to_valid_input_types(]# Try to assign multiple values from a valid attribute- variables["attributes"] = [{"slug": multi_values_attr.slug, "values": ["a", "b"]}]+ variables["attributes"] = [{"id": multi_values_attr_id, "values": ["a", "b"]}]data = get_graphql_content(staff_api_client.post_graphql(SET_ATTRIBUTES_TO_PRODUCT_QUERY, variables))["data"]["productUpdate"]- assert data["errors"] == []+ assert not data["errors"]def test_update_product_without_variants(