Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Made changes from review
NyanKiyoshi74c4c342f34c
diff --git a/saleor/graphql/core/mutations.py b/saleor/graphql/core/mutations.pyindex 6780f38c6c..4238eb543a 100644--- a/saleor/graphql/core/mutations.py+++ b/saleor/graphql/core/mutations.py@@ -106,18 +106,18 @@ class BaseMutation(graphene.Mutation):cls._meta.fields.update(fields)@classmethod- def get_node_by_id(- cls, info, graphene_type: ObjectType, node_id: Union[int, str], qs=None+ def get_node_by_pk(+ cls, info, graphene_type: ObjectType, pk: Union[int, str], qs=None):"""Attempt to resolve a node from the given internal ID.Whether by using the provided query set object or by calling type's get_node()."""if qs is not None:- return qs.filter(pk=node_id).first()+ return qs.filter(pk=pk).first()get_node = getattr(graphene_type, "get_node", None)if get_node:- return get_node(info, node_id)+ return get_node(info, pk)return None@classmethod@@ -127,19 +127,15 @@ class BaseMutation(graphene.Mutation):try:if only_type is not None:- internal_id = from_global_id_strict_type(- node_id, only_type, field=field- )+ pk = from_global_id_strict_type(node_id, only_type, field=field)else:# FIXME: warn when supplied only_type is None?- only_type, internal_id = graphene.Node.from_global_id(node_id)+ only_type, pk = graphene.Node.from_global_id(node_id)if isinstance(only_type, str):only_type = info.schema.get_type(only_type).graphene_type- node = cls.get_node_by_id(- info, graphene_type=only_type, node_id=internal_id, qs=qs- )+ node = cls.get_node_by_pk(info, graphene_type=only_type, pk=pk, qs=qs)except (AssertionError, GraphQLError) as e:raise ValidationError({field: str(e)})else:diff --git a/saleor/graphql/core/utils/__init__.py b/saleor/graphql/core/utils/__init__.pyindex ea47bb3c80..82dc9d5057 100644--- a/saleor/graphql/core/utils/__init__.py+++ b/saleor/graphql/core/utils/__init__.py@@ -41,10 +41,10 @@ def from_global_id_strict_type(try:_type, _id = graphene.Node.from_global_id(global_id)except (binascii.Error, UnicodeDecodeError) as exc:- raise ValidationError({field: f"Invalid base64 global ID"}) from exc+ raise ValidationError({field: f"Couldn't resolve to a node"}) from excif str(_type) != str(only_type):- raise ValidationError({field: f"Must receive a {only_type} id."})+ raise ValidationError({field: f"Must receive a {only_type} id"})return _iddiff --git a/saleor/graphql/product/mutations/products.py b/saleor/graphql/product/mutations/products.pyindex 6cb2caefc3..f3e58dfb5e 100644--- a/saleor/graphql/product/mutations/products.py+++ b/saleor/graphql/product/mutations/products.py@@ -472,10 +472,9 @@ class AttributeAssignmentMixin:"""Handles cleaning of the attribute input and creating the proper relations.1. You should first call ``clean_input``, to transform and attempt to resolve- the provided input into actual objects.- 2. You should then call ``is_valid`` with the cleaned input to perform a few+ the provided input into actual objects. It will then perform a fewchecks to validate the operations supplied by the user are possible and allowed.- 3. Once everything is ready and all your data is saved inside a transaction,+ 2. Once everything is ready and all your data is saved inside a transaction,you shall call ``save`` with the cleaned input to build all the requiredrelations. Once the ``save`` call is done, you are safe from continuing workingor to commit the transaction.@@ -578,11 +577,27 @@ class AttributeAssignmentMixin:validate_attribute_input_for_variant(attribute, values)@classmethod- def clean_input(cls, raw_input: dict, attributes_qs: QuerySet) -> T_INPUT_MAP:+ def _validate_input(+ cls, cleaned_input: T_INPUT_MAP, attribute_qs, is_variant: bool+ ):+ """Check if no invalid operations were supplied.++ :raises ValidationError: when an invalid operation was found.+ """+ if is_variant:+ return cls._check_input_for_variant(cleaned_input, attribute_qs)+ else:+ return cls._check_input_for_product(cleaned_input, attribute_qs)++ @classmethod+ def clean_input(+ cls, raw_input: dict, attributes_qs: QuerySet, is_variant: bool+ ) -> T_INPUT_MAP:"""Resolve and prepare the input for further checks.:param raw_input: The user's attributes input.:param attributes_qs: A queryset of attributes, must prefetch attribute values.+ :param is_variant: Whether the input is for a variant or a product.:raises ValidationError: contain the message.:return: The resolved data@@ -620,19 +635,9 @@ class AttributeAssignmentMixin:key = slugs[attribute.slug]cleaned_input.append((attribute, key))+ cls._validate_input(cleaned_input, attributes_qs, is_variant)return cleaned_input- @classmethod- def validate_input(cls, cleaned_input: T_INPUT_MAP, attribute_qs, is_variant: bool):- """Check if no invalid operations were supplied.-- :raises ValidationError: when an invalid operation was found.- """- if is_variant:- return cls._check_input_for_variant(cleaned_input, attribute_qs)- else:- return cls._check_input_for_product(cleaned_input, attribute_qs)-@classmethoddef save(cls, instance: T_INSTANCE, cleaned_input: T_INPUT_MAP):"""Save the cleaned input into the database against the given instance.@@ -663,8 +668,7 @@ class ProductCreate(ModelMutation):cls, attributes: dict, product_type: models.ProductType) -> T_INPUT_MAP:attributes_qs = product_type.product_attributes- attributes = AttributeAssignmentMixin.clean_input(attributes, attributes_qs)- AttributeAssignmentMixin.validate_input(+ attributes = AttributeAssignmentMixin.clean_input(attributes, attributes_qs, is_variant=False)return attributes@@ -908,8 +912,7 @@ class ProductVariantCreate(ModelMutation):cls, attributes: dict, product_type: models.ProductType) -> T_INPUT_MAP:attributes_qs = product_type.variant_attributes- attributes = AttributeAssignmentMixin.clean_input(attributes, attributes_qs)- AttributeAssignmentMixin.validate_input(+ attributes = AttributeAssignmentMixin.clean_input(attributes, attributes_qs, is_variant=True)return attributesdiff --git a/tests/api/test_base_mutation.py b/tests/api/test_base_mutation.pyindex 790d4dda27..8fa31c23b7 100644--- a/tests/api/test_base_mutation.py+++ b/tests/api/test_base_mutation.py@@ -81,7 +81,7 @@ def test_user_error_nonexistent_id(schema_context):user_errors = result.data["test"]["errors"]assert user_errorsassert user_errors[0]["field"] == "productId"- assert "Invalid base64 global ID" in user_errors[0]["message"]+ assert user_errors[0]["message"] == "Couldn't resolve to a node"def test_user_error_id_of_different_type(product, schema_context):@@ -109,7 +109,7 @@ def test_user_error_id_of_different_type(product, schema_context):user_errors = result.data["test"]["errors"]assert user_errorsassert user_errors[0]["field"] == "productId"- assert user_errors[0]["message"] == "Must receive a Product id."+ assert user_errors[0]["message"] == "Must receive a Product id"def test_get_node_or_error_returns_null_for_empty_id():diff --git a/tests/api/test_checkout.py b/tests/api/test_checkout.pyindex 2e5bda34c4..13c8f398cc 100644--- a/tests/api/test_checkout.py+++ b/tests/api/test_checkout.py@@ -1131,7 +1131,7 @@ def test_checkout_complete_invalid_checkout_id(user_api_client):response = user_api_client.post_graphql(MUTATION_CHECKOUT_COMPLETE, variables)content = get_graphql_content(response)data = content["data"]["checkoutComplete"]- assert data["errors"][0]["message"] == "Invalid base64 global ID"+ assert data["errors"][0]["message"] == "Couldn't resolve to a node"assert data["errors"][0]["field"] == "checkoutId"assert orders_count == Order.objects.count()