Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Refactor attributes validation (#8905)
Iga Karbowiakcfb4b0785333
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex deae2b3e01..38fd3932c5 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -23,6 +23,9 @@ All notable, unreleased changes to this project will be documented in this file.- Add query complexity limit to GraphQL API - #8526 by rafalp- Add `quantity_limit_per_customer` field to ProductVariant #8405 by @kuchichan- Optimize products stock availability filter - #8809 by @fowczarek+- Refactor attributes validation - #8905 by @IKarbowiak+ - in create mutations: require all required attributes+ - in update mutations: do not require providing any attributes; when any attribute is given, validate provided values.- Do no allow using id for updating checkout and order metadata - #8906 by @IKarbowiak# 3.0.0 [Unreleased]diff --git a/saleor/graphql/attribute/tests/test_utils.py b/saleor/graphql/attribute/tests/test_utils.pyindex 1e18fbd285..4a09f72c2f 100644--- a/saleor/graphql/attribute/tests/test_utils.py+++ b/saleor/graphql/attribute/tests/test_utils.py@@ -8,8 +8,9 @@ from ...product.mutations.products import AttrValuesInputfrom ..utils import AttributeAssignmentMixin, validate_attributes_input[email protected]("creation", [True, False])def test_validate_attributes_input_for_product(- weight_attribute, color_attribute, product_type+ creation, weight_attribute, color_attribute, product_type):# givencolor_attribute.value_required = True@@ -46,15 +47,16 @@ def test_validate_attributes_input_for_product(input_data,product_type.product_attributes.all(),is_page_attributes=False,- variant_validation=False,+ creation=creation,)# thenassert not errors[email protected]("creation", [True, False])def test_validate_attributes_input_for_product_no_values_given(- weight_attribute, color_attribute, product_type+ creation, weight_attribute, color_attribute, product_type):# givencolor_attribute.value_required = True@@ -91,7 +93,7 @@ def test_validate_attributes_input_for_product_no_values_given(input_data,product_type.product_attributes.all(),is_page_attributes=False,- variant_validation=False,+ creation=creation,)# then@@ -104,8 +106,9 @@ def test_validate_attributes_input_for_product_no_values_given(}[email protected]("creation", [True, False])def test_validate_attributes_input_for_product_too_many_values_given(- weight_attribute, color_attribute, product_type+ creation, weight_attribute, color_attribute, product_type):# givencolor_attribute.input_type = AttributeInputType.DROPDOWN@@ -144,7 +147,7 @@ def test_validate_attributes_input_for_product_too_many_values_given(input_data,product_type.product_attributes.all(),is_page_attributes=False,- variant_validation=False,+ creation=creation,)# then@@ -156,8 +159,9 @@ def test_validate_attributes_input_for_product_too_many_values_given(][email protected]("creation", [True, False])def test_validate_attributes_input_for_product_empty_values_given(- weight_attribute, color_attribute, product_type+ creation, weight_attribute, color_attribute, product_type):# givencolor_attribute.input_type = AttributeInputType.DROPDOWN@@ -196,7 +200,7 @@ def test_validate_attributes_input_for_product_empty_values_given(input_data,product_type.product_attributes.all(),is_page_attributes=False,- variant_validation=False,+ creation=creation,)# then@@ -239,7 +243,7 @@ def test_validate_attributes_input_for_product_lack_of_required_attribute(input_data,product_attributes,is_page_attributes=False,- variant_validation=None,+ creation=True,)# then@@ -251,8 +255,9 @@ def test_validate_attributes_input_for_product_lack_of_required_attribute(}-def test_validate_attributes_input_for_product_multiple_errors(- weight_attribute, color_attribute, product_type[email protected]("creation", [True, False])+def test_validate_attributes_input_for_product_creation_multiple_errors(+ creation, weight_attribute, color_attribute, product_type):# givencolor_attribute.input_type = AttributeInputType.DROPDOWN@@ -291,7 +296,7 @@ def test_validate_attributes_input_for_product_multiple_errors(input_data,product_type.product_attributes.all(),is_page_attributes=False,- variant_validation=False,+ creation=creation,)# then@@ -306,8 +311,9 @@ def test_validate_attributes_input_for_product_multiple_errors(}[email protected]("creation", [True, False])def test_validate_attributes_input_for_page(- weight_attribute, color_attribute, page_type+ creation, weight_attribute, color_attribute, page_type):# givencolor_attribute.value_required = True@@ -344,15 +350,16 @@ def test_validate_attributes_input_for_page(input_data,page_type.page_attributes.all(),is_page_attributes=True,- variant_validation=False,+ creation=creation,)# thenassert not errors[email protected]("creation", [True, False])def test_validate_attributes_input_for_page_no_values_given(- weight_attribute, color_attribute, page_type+ creation, weight_attribute, color_attribute, page_type):# givencolor_attribute.value_required = True@@ -389,7 +396,7 @@ def test_validate_attributes_input_for_page_no_values_given(input_data,page_type.page_attributes.all(),is_page_attributes=True,- variant_validation=False,+ creation=creation,)# then@@ -402,8 +409,9 @@ def test_validate_attributes_input_for_page_no_values_given(}[email protected]("creation", [True, False])def test_validate_attributes_input_for_page_too_many_values_given(- weight_attribute, color_attribute, page_type+ creation, weight_attribute, color_attribute, page_type):# givencolor_attribute.input_type = AttributeInputType.DROPDOWN@@ -442,7 +450,7 @@ def test_validate_attributes_input_for_page_too_many_values_given(input_data,page_type.page_attributes.all(),is_page_attributes=True,- variant_validation=False,+ creation=creation,)# then@@ -454,8 +462,9 @@ def test_validate_attributes_input_for_page_too_many_values_given(][email protected]("creation", [True, False])def test_validate_attributes_input_for_page_empty_values_given(- weight_attribute, color_attribute, page_type+ creation, weight_attribute, color_attribute, page_type):# givencolor_attribute.input_type = AttributeInputType.DROPDOWN@@ -494,7 +503,7 @@ def test_validate_attributes_input_for_page_empty_values_given(input_data,page_type.page_attributes.all(),is_page_attributes=True,- variant_validation=False,+ creation=creation,)# then@@ -534,7 +543,7 @@ def test_validate_attributes_input_for_page_lack_of_required_attribute(# whenerrors = validate_attributes_input(- input_data, page_attributes, is_page_attributes=True, variant_validation=None+ input_data, page_attributes, is_page_attributes=True, creation=True)# then@@ -586,7 +595,7 @@ def test_validate_attributes_input_for_page_multiple_errors(input_data,page_type.page_attributes.all(),is_page_attributes=True,- variant_validation=False,+ creation=True,)# then@@ -601,7 +610,10 @@ def test_validate_attributes_input_for_page_multiple_errors(}-def test_validate_attributes_input(weight_attribute, color_attribute, product_type):[email protected]("creation", [True, False])+def test_validate_attributes_input(+ creation, weight_attribute, color_attribute, product_type+):# givencolor_attribute.value_required = Truecolor_attribute.save(update_fields=["value_required"])@@ -636,15 +648,16 @@ def test_validate_attributes_input(weight_attribute, color_attribute, product_ty# whenerrors = validate_attributes_input(- input_data, attributes, is_page_attributes=False, variant_validation=True+ input_data, attributes, is_page_attributes=False, creation=creation)# thenassert not errors[email protected]("creation", [True, False])def test_validate_attributes_input_no_values_given(- weight_attribute, color_attribute, product_type+ creation, weight_attribute, color_attribute, product_type):# givencolor_attribute.value_required = True@@ -680,7 +693,7 @@ def test_validate_attributes_input_no_values_given(# whenerrors = validate_attributes_input(- input_data, attributes, is_page_attributes=False, variant_validation=True+ input_data, attributes, is_page_attributes=False, creation=creation)# then@@ -693,8 +706,9 @@ def test_validate_attributes_input_no_values_given(}[email protected]("creation", [True, False])def test_validate_not_required_variant_selection_attributes_input_no_values_given(- weight_attribute, color_attribute, product_type+ creation, weight_attribute, color_attribute, product_type):# givencolor_attribute.value_required = False@@ -738,17 +752,16 @@ def test_validate_not_required_variant_selection_attributes_input_no_values_giveinput_data,attributes,is_page_attributes=False,- variant_validation=attributes.values(- "id", "attributevariant__variant_selection"- ),+ creation=creation,)# thenassert not errors[email protected]("creation", [True, False])def test_validate_attributes_input_too_many_values_given(- weight_attribute, color_attribute, product_type+ creation, weight_attribute, color_attribute, product_type):# givencolor_attribute.value_required = True@@ -787,9 +800,7 @@ def test_validate_attributes_input_too_many_values_given(input_data,attributes,is_page_attributes=False,- variant_validation=attributes.values(- "id", "attributevariant__variant_selection"- ),+ creation=creation,)# then@@ -802,8 +813,9 @@ def test_validate_attributes_input_too_many_values_given(}[email protected]("creation", [True, False])def test_validate_attributes_input_empty_values_given(- weight_attribute, color_attribute, product_type+ creation, weight_attribute, color_attribute, product_type):# givencolor_attribute.value_required = True@@ -839,7 +851,7 @@ def test_validate_attributes_input_empty_values_given(# whenerrors = validate_attributes_input(- input_data, attributes, is_page_attributes=False, variant_validation=True+ input_data, attributes, is_page_attributes=False, creation=creation)# then@@ -889,7 +901,7 @@ def test_validate_attributes_input_multiple_errors(# whenerrors = validate_attributes_input(- input_data, attributes, is_page_attributes=False, variant_validation=True+ input_data, attributes, is_page_attributes=False, creation=True)# then@@ -904,8 +916,9 @@ def test_validate_attributes_input_multiple_errors(}[email protected]("creation", [True, False])def test_validate_attributes_with_file_input_type_for_product(- weight_attribute, file_attribute, product_type+ creation, weight_attribute, file_attribute, product_type):# givenfile_attribute.value_required = True@@ -942,15 +955,16 @@ def test_validate_attributes_with_file_input_type_for_product(input_data,product_type.product_attributes.all(),is_page_attributes=False,- variant_validation=None,+ creation=creation,)# thenassert not errors[email protected]("creation", [True, False])def test_validate_attributes_with_file_input_type_for_product_no_file_given(- weight_attribute, file_attribute, product_type+ creation, weight_attribute, file_attribute, product_type):# givenfile_attribute.value_required = True@@ -987,7 +1001,7 @@ def test_validate_attributes_with_file_input_type_for_product_no_file_given(input_data,product_type.product_attributes.all(),is_page_attributes=False,- variant_validation=None,+ creation=creation,)# then@@ -999,8 +1013,9 @@ def test_validate_attributes_with_file_input_type_for_product_no_file_given(}[email protected]("creation", [True, False])def test_validate_not_required_attrs_with_file_input_type_for_product_no_file_given(- weight_attribute, file_attribute, product_type+ creation, weight_attribute, file_attribute, product_type):# givenfile_attribute.value_required = False@@ -1037,15 +1052,16 @@ def test_validate_not_required_attrs_with_file_input_type_for_product_no_file_giinput_data,product_type.product_attributes.all(),is_page_attributes=False,- variant_validation=None,+ creation=creation,)# thenassert not errors[email protected]("creation", [True, False])def test_validate_attributes_with_file_input_type_for_product_empty_file_value(- weight_attribute, file_attribute, product_type+ creation, weight_attribute, file_attribute, product_type):# givenfile_attribute.value_required = True@@ -1082,7 +1098,7 @@ def test_validate_attributes_with_file_input_type_for_product_empty_file_value(input_data,product_type.product_attributes.all(),is_page_attributes=False,- variant_validation=None,+ creation=creation,)# then@@ -1094,7 +1110,10 @@ def test_validate_attributes_with_file_input_type_for_product_empty_file_value(}-def test_validate_numeric_attributes_input_for_product(numeric_attribute, product_type):[email protected]("creation", [True, False])+def test_validate_numeric_attributes_input_for_product(+ creation, numeric_attribute, product_type+):# givennumeric_attribute.value_required = Truenumeric_attribute.save(update_fields=["value_required"])@@ -1117,7 +1136,7 @@ def test_validate_numeric_attributes_input_for_product(numeric_attribute, producinput_data,product_type.product_attributes.all(),is_page_attributes=False,- variant_validation=None,+ creation=creation,)# then@@ -1125,8 +1144,9 @@ def test_validate_numeric_attributes_input_for_product(numeric_attribute, produc@pytest.mark.parametrize("value", ["qvd", "12.se", " "])[email protected]("creation", [True, False])def test_validate_numeric_attributes_input_for_product_not_numeric_value_given(- value, numeric_attribute, product_type+ creation, value, numeric_attribute, product_type):# givennumeric_attribute.value_required = True@@ -1150,7 +1170,7 @@ def test_validate_numeric_attributes_input_for_product_not_numeric_value_given(input_data,product_type.product_attributes.all(),is_page_attributes=False,- variant_validation=None,+ creation=creation,)# then@@ -1162,8 +1182,9 @@ def test_validate_numeric_attributes_input_for_product_not_numeric_value_given(}[email protected]("creation", [True, False])def test_validate_numeric_attributes_input_for_product_blank_value(- numeric_attribute, product_type+ creation, numeric_attribute, product_type):# givennumeric_attribute.value_required = True@@ -1187,7 +1208,7 @@ def test_validate_numeric_attributes_input_for_product_blank_value(input_data,product_type.product_attributes.all(),is_page_attributes=False,- variant_validation=None,+ creation=creation,)# then@@ -1199,8 +1220,9 @@ def test_validate_numeric_attributes_input_for_product_blank_value(}[email protected]("creation", [True, False])def test_validate_numeric_attributes_input_for_product_more_than_one_value_given(- numeric_attribute, product_type+ creation, numeric_attribute, product_type):# givennumeric_attribute.value_required = True@@ -1224,7 +1246,7 @@ def test_validate_numeric_attributes_input_for_product_more_than_one_value_giveninput_data,product_type.product_attributes.all(),is_page_attributes=False,- variant_validation=None,+ creation=creation,)# thendiff --git a/saleor/graphql/attribute/utils.py b/saleor/graphql/attribute/utils.pyindex c5ed50ce4e..ee75a41d4f 100644--- a/saleor/graphql/attribute/utils.py+++ b/saleor/graphql/attribute/utils.py@@ -317,50 +317,12 @@ class AttributeAssignmentMixin:else assignment.values.filter(**{lookup_field: value}).first())- @classmethod- def _validate_attributes_input(- cls,- cleaned_input: T_INPUT_MAP,- attribute_qs: "QuerySet",- *,- is_variant: bool,- is_page_attributes: bool- ):- """Check the cleaned attribute input.-- An Attribute queryset is supplied.-- - ensure all required attributes are passed- - ensure the values are correct-- :raises ValidationError: when an invalid operation was found.- """- variant_validation = False- if is_variant:- qs = get_variant_selection_attributes(attribute_qs)- if len(cleaned_input) < qs.count():- raise ValidationError(- "All variant selection attributes must take a value.",- code=ProductErrorCode.REQUIRED.value,- )- variant_validation = True-- errors = validate_attributes_input(- cleaned_input,- attribute_qs,- is_page_attributes=is_page_attributes,- variant_validation=variant_validation,- )-- if errors:- raise ValidationError(errors)-@classmethoddef clean_input(cls,raw_input: dict,attributes_qs: "QuerySet",- is_variant: bool = False,+ creation: bool = True,is_page_attributes: bool = False,) -> T_INPUT_MAP:"""Resolve and prepare the input for further checks.@@ -369,8 +331,8 @@ class AttributeAssignmentMixin::param attributes_qs:A queryset of attributes, the attribute values must be prefetched.Prefetch is needed by ``_pre_save_values`` during save.- :param page_attributes: Whether the input is for page type or not.- :param is_variant: Whether the input is for a variant or a product.+ :param creation: Whether the input is from creation mutation.+ :param is_page_attributes: Whether the input is for page type or not.:raises ValidationError: contain the message.:return: The resolved data@@ -447,7 +409,7 @@ class AttributeAssignmentMixin:cls._validate_attributes_input(cleaned_input,attributes_qs,- is_variant=is_variant,+ creation=creation,is_page_attributes=is_page_attributes,)@@ -477,6 +439,32 @@ class AttributeAssignmentMixin:values.references = ref_instancesreturn values+ @classmethod+ def _validate_attributes_input(+ cls,+ cleaned_input: T_INPUT_MAP,+ attribute_qs: "QuerySet",+ *,+ creation: bool,+ is_page_attributes: bool+ ):+ """Check the cleaned attribute input.++ An Attribute queryset is supplied.++ - ensure all required attributes are passed+ - ensure the values are correct++ :raises ValidationError: when an invalid operation was found.+ """+ if errors := validate_attributes_input(+ cleaned_input,+ attribute_qs,+ is_page_attributes=is_page_attributes,+ creation=creation,+ ):+ raise ValidationError(errors)+@classmethoddef save(cls, instance: T_INSTANCE, cleaned_input: T_INPUT_MAP):"""Save the cleaned input into the database against the given instance.@@ -575,7 +563,7 @@ def validate_attributes_input(attribute_qs: "QuerySet",*,is_page_attributes: bool,- variant_validation: bool,+ creation: bool,):"""Validate attribute input.@@ -611,7 +599,9 @@ def validate_attributes_input(errors = prepare_error_list_from_error_attribute_mapping(attribute_errors, error_code_enum)- if not variant_validation:+ # Check if all required attributes are in input only when instance is created.+ # We should allow updating any instance attributes.+ if creation:errors = validate_required_attributes(input_data, attribute_qs, errors, error_code_enum)diff --git a/saleor/graphql/page/mutations/pages.py b/saleor/graphql/page/mutations/pages.pyindex 2ad12e45dd..e930755028 100644--- a/saleor/graphql/page/mutations/pages.py+++ b/saleor/graphql/page/mutations/pages.py@@ -127,6 +127,14 @@ class PageUpdate(PageCreate):error_type_class = PageErrorerror_type_field = "page_errors"+ @classmethod+ def clean_attributes(cls, attributes: dict, page_type: models.PageType):+ attributes_qs = page_type.page_attributes+ attributes = AttributeAssignmentMixin.clean_input(+ attributes, attributes_qs, creation=False, is_page_attributes=True+ )+ return attributes+@classmethoddef save(cls, info, instance, cleaned_input):super(PageCreate, cls).save(info, instance, cleaned_input)diff --git a/saleor/graphql/page/tests/test_page.py b/saleor/graphql/page/tests/test_page.pyindex 15f87e9996..c4e129ca16 100644--- a/saleor/graphql/page/tests/test_page.py+++ b/saleor/graphql/page/tests/test_page.py@@ -1436,6 +1436,60 @@ def test_update_page_trigger_webhook()+def test_update_page_only_title(staff_api_client, permission_manage_pages, page):+ """Ensures that updating page field without providing attributes is allowed."""+ # given+ query = UPDATE_PAGE_MUTATION++ page_type = page.page_type+ page_title = page.title+ new_slug = "new-slug"+ assert new_slug != page.slug++ page_id = graphene.Node.to_global_id("Page", page.id)++ variables = {+ "id": page_id,+ "input": {+ "slug": new_slug,+ "isPublished": True,+ },+ }++ # when+ response = staff_api_client.post_graphql(+ query, variables, permissions=[permission_manage_pages]+ )++ # then+ content = get_graphql_content(response)+ data = content["data"]["pageUpdate"]++ assert not data["errors"]+ assert data["page"]["title"] == page_title+ assert data["page"]["slug"] == new_slug++ expected_attributes = []+ page_attr = page.attributes.all()+ for attr in page_type.page_attributes.all():+ values = [+ {"slug": slug, "file": None, "name": name, "reference": None}+ for slug, name in page_attr.filter(assignment__attribute=attr).values_list(+ "values__slug", "values__name"+ )+ ]+ attr_data = {+ "attribute": {"slug": attr.slug},+ "values": values,+ }+ expected_attributes.append(attr_data)++ attributes = data["page"]["attributes"]+ assert len(attributes) == len(expected_attributes)+ for attr_data in attributes:+ assert attr_data in expected_attributes++def test_update_page_with_file_attribute_value(staff_api_client, permission_manage_pages, page, page_file_attribute):diff --git a/saleor/graphql/product/mutations/products.py b/saleor/graphql/product/mutations/products.pyindex 4c3c0d7769..a41fefda6f 100644--- a/saleor/graphql/product/mutations/products.py+++ b/saleor/graphql/product/mutations/products.py@@ -563,9 +563,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, is_variant=False- )+ attributes = AttributeAssignmentMixin.clean_input(attributes, attributes_qs)return attributes@classmethod@@ -688,6 +686,16 @@ class ProductUpdate(ProductCreate):error_type_class = ProductErrorerror_type_field = "product_errors"+ @classmethod+ def clean_attributes(+ cls, attributes: dict, product_type: models.ProductType+ ) -> T_INPUT_MAP:+ attributes_qs = product_type.product_attributes+ attributes = AttributeAssignmentMixin.clean_input(+ attributes, attributes_qs, creation=False+ )+ return attributes+@classmethod@traced_atomic_transaction()def save(cls, info, instance, cleaned_input):@@ -830,9 +838,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, is_variant=True- )+ attributes = AttributeAssignmentMixin.clean_input(attributes, attributes_qs)return attributes@classmethod@@ -921,10 +927,14 @@ class ProductVariantCreate(ModelMutation):cleaned_attributes, used_attribute_values, instance)cleaned_input["attributes"] = cleaned_attributes- elif not instance.pk and not attributes:+ # elif not instance.pk and not attributes:+ elif not instance.pk and (+ not attributes+ and product_type.variant_attributes.filter(value_required=True)+ ):# if attributes were not provided on creationraise ValidationError(- "All attributes must take a value.",+ "All required attributes must take a value.",ProductErrorCode.REQUIRED.value,)except ValidationError as exc:@@ -996,8 +1006,8 @@ class ProductVariantCreate(ModelMutation):attributes = cleaned_input.get("attributes")if attributes:AttributeAssignmentMixin.save(instance, attributes)- generate_and_set_variant_name(instance, cleaned_input.get("sku"))+ generate_and_set_variant_name(instance, cleaned_input.get("sku"))update_product_search_document(instance.product)event_to_call = (info.context.plugins.product_variant_created@@ -1037,6 +1047,16 @@ class ProductVariantUpdate(ProductVariantCreate):error_type_field = "product_errors"errors_mapping = {"price_amount": "price"}+ @classmethod+ def clean_attributes(+ cls, attributes: dict, product_type: models.ProductType+ ) -> T_INPUT_MAP:+ attributes_qs = product_type.variant_attributes+ attributes = AttributeAssignmentMixin.clean_input(+ attributes, attributes_qs, creation=False+ )+ return attributes+@classmethoddef validate_duplicated_attribute_values(cls, attributes_data, used_attribute_values, instance=Nonediff --git a/saleor/graphql/product/tests/test_product.py b/saleor/graphql/product/tests/test_product.pyindex e665654233..b319d9c8ad 100644--- a/saleor/graphql/product/tests/test_product.py+++ b/saleor/graphql/product/tests/test_product.py@@ -2655,7 +2655,7 @@ def test_products_query_with_filter_search_by_rich_text_attribute(assert products[0]["node"]["name"] == product_with_rich_text_attr.name[email protected]("search_value", ["134", "134", "134 cm"])[email protected]("search_value", ["13456", "13456 cm"])def test_products_query_with_filter_search_by_numeric_attribute_value(search_value,query_products_with_filter,@@ -2675,7 +2675,7 @@ def test_products_query_with_filter_search_by_numeric_attribute_value(numeric_attribute.save(update_fields=["unit"])numeric_attr_value = numeric_attribute.values.first()- numeric_attr_value.name = "134"+ numeric_attr_value.name = "13456"numeric_attr_value.save(update_fields=["name"])associate_attribute_values_to_instance(@@ -6558,6 +6558,61 @@ def test_update_product_with_page_reference_attribute_value(assert product_type_page_reference_attribute.values.count() == values_count + 1+def test_update_product_without_supplying_required_product_attribute(+ staff_api_client, product, permission_manage_products, color_attribute+):+ """Ensure assigning an existing value to a product doesn't create a new+ attribute value."""++ # given+ staff_api_client.user.user_permissions.add(permission_manage_products)++ product_type = product.product_type+ color_attribute_id = graphene.Node.to_global_id("Attribute", color_attribute.id)++ # Create and assign a new attribute requiring a value to be always supplied+ required_attribute = Attribute.objects.create(+ name="Required One", slug="required-one", value_required=True+ )+ product_type.product_attributes.add(required_attribute)+ required_attribute_id = graphene.Node.to_global_id(+ "Attribute", required_attribute.id+ )++ value = "Blue"+ variables = {+ "productId": graphene.Node.to_global_id("Product", product.pk),+ "input": {"attributes": [{"id": color_attribute_id, "values": [value]}]},+ }++ # when+ data = get_graphql_content(+ staff_api_client.post_graphql(MUTATION_UPDATE_PRODUCT, variables)+ )["data"]["productUpdate"]++ # then+ assert not data["errors"]+ attributes_data = data["product"]["attributes"]+ assert len(attributes_data) == 2+ assert {+ "attribute": {"id": required_attribute_id, "name": required_attribute.name},+ "values": [],+ } in attributes_data+ assert {+ "attribute": {"id": color_attribute_id, "name": color_attribute.name},+ "values": [+ {+ "id": ANY,+ "name": value,+ "slug": value.lower(),+ "file": None,+ "reference": None,+ "boolean": None,+ }+ ],+ } in attributes_data++def test_update_product_with_empty_input_collections(product, permission_manage_products, staff_api_client):@@ -7222,45 +7277,6 @@ def test_update_product_with_existing_attribute_value(), "A new attribute value shouldn't have been created"-def test_update_product_without_supplying_required_product_attribute(- staff_api_client, product, permission_manage_products, color_attribute-):- """Ensure assigning an existing value to a product doesn't create a new- attribute value."""-- staff_api_client.user.user_permissions.add(permission_manage_products)-- product_type = product.product_type- color_attribute_id = graphene.Node.to_global_id("Attribute", color_attribute.id)-- # Create and assign a new attribute requiring a value to be always supplied- required_attribute = Attribute.objects.create(- name="Required One", slug="required-one", value_required=True- )- product_type.product_attributes.add(required_attribute)- required_attribute_id = graphene.Node.to_global_id(- "Attribute", required_attribute.id- )-- # Try to assign multiple values from an attribute that does not support such things- variables = {- "productId": graphene.Node.to_global_id("Product", product.pk),- "attributes": [{"id": color_attribute_id, "values": ["Blue"]}],- }-- data = get_graphql_content(- staff_api_client.post_graphql(SET_ATTRIBUTES_TO_PRODUCT_QUERY, variables)- )["data"]["productUpdate"]- assert data["errors"] == [- {- "field": "attributes",- "code": ProductErrorCode.REQUIRED.name,- "message": ANY,- "attributes": [required_attribute_id],- }- ]--def test_update_product_with_non_existing_attribute(staff_api_client, product, permission_manage_products, color_attribute):diff --git a/saleor/graphql/product/tests/test_variant.py b/saleor/graphql/product/tests/test_variant.pyindex 125cc7f211..168a7e687a 100644--- a/saleor/graphql/product/tests/test_variant.py+++ b/saleor/graphql/product/tests/test_variant.py@@ -566,7 +566,7 @@ def test_create_variant(sku = "1"weight = 10.22variant_slug = product_type.variant_attributes.first().slug- variant_id = graphene.Node.to_global_id(+ attribute_id = graphene.Node.to_global_id("Attribute", product_type.variant_attributes.first().pk)variant_value = "test-value"@@ -582,7 +582,7 @@ def test_create_variant("sku": sku,"stocks": stocks,"weight": weight,- "attributes": [{"id": variant_id, "values": [variant_value]}],+ "attributes": [{"id": attribute_id, "values": [variant_value]}],"trackInventory": True,}response = staff_api_client.post_graphql(@@ -622,7 +622,7 @@ def test_create_variant_preorder():query = CREATE_VARIANT_MUTATIONproduct_id = graphene.Node.to_global_id("Product", product.pk)- variant_id = graphene.Node.to_global_id(+ attribute_id = graphene.Node.to_global_id("Attribute", product_type.variant_attributes.first().pk)variant_value = "test-value"@@ -638,7 +638,7 @@ def test_create_variant_preorder("productId": product_id,"sku": "1","weight": 10.22,- "attributes": [{"id": variant_id, "values": [variant_value]}],+ "attributes": [{"id": attribute_id, "values": [variant_value]}],"preorder": {"globalThreshold": global_threshold,"endDate": end_date,@@ -661,6 +661,65 @@ def test_create_variant_preorder(updated_webhook_mock.assert_not_called()+@patch("saleor.plugins.manager.PluginsManager.product_variant_created")+@patch("saleor.plugins.manager.PluginsManager.product_variant_updated")+def test_create_variant_no_required_attributes(+ updated_webhook_mock,+ created_webhook_mock,+ staff_api_client,+ product,+ product_type,+ permission_manage_products,+ warehouse,+):+ query = CREATE_VARIANT_MUTATION+ product_id = graphene.Node.to_global_id("Product", product.pk)+ sku = "1"+ weight = 10.22++ attribute = product_type.variant_attributes.first()+ attribute.value_required = False+ attribute.save(update_fields=["value_required"])++ stocks = [+ {+ "warehouse": graphene.Node.to_global_id("Warehouse", warehouse.pk),+ "quantity": 20,+ }+ ]++ variables = {+ "productId": product_id,+ "sku": sku,+ "stocks": stocks,+ "weight": weight,+ "attributes": [],+ "trackInventory": True,+ }+ response = staff_api_client.post_graphql(+ query, variables, permissions=[permission_manage_products]+ )+ content = get_graphql_content(response)["data"]["productVariantCreate"]+ flush_post_commit_hooks()++ assert not content["errors"]+ data = content["productVariant"]+ assert data["name"] == sku+ assert data["sku"] == sku+ assert not data["attributes"][0]["values"]+ assert data["weight"]["unit"] == WeightUnitsEnum.KG.name+ assert data["weight"]["value"] == weight+ assert len(data["stocks"]) == 1+ assert data["stocks"][0]["quantity"] == stocks[0]["quantity"]+ assert data["stocks"][0]["warehouse"]["slug"] == warehouse.slug+ created_webhook_mock.assert_called_once_with(product.variants.last())+ updated_webhook_mock.assert_not_called()++ product.refresh_from_db()+ assert product.search_document+ assert sku in product.search_document++@patch("saleor.plugins.manager.PluginsManager.product_variant_created")def test_create_variant_with_file_attribute(created_webhook_mock,@@ -1243,7 +1302,7 @@ def test_create_variant_with_numeric_attribute(weight = 10.22product_type.variant_attributes.set([numeric_attribute])variant_slug = numeric_attribute.slug- variant_id = graphene.Node.to_global_id("Attribute", numeric_attribute.pk)+ attribute_id = graphene.Node.to_global_id("Attribute", numeric_attribute.pk)variant_value = "22.31"stocks = [{@@ -1257,7 +1316,7 @@ def test_create_variant_with_numeric_attribute("sku": sku,"stocks": stocks,"weight": weight,- "attributes": [{"id": variant_id, "values": [variant_value]}],+ "attributes": [{"id": attribute_id, "values": [variant_value]}],"trackInventory": True,}response = staff_api_client.post_graphql(@@ -1297,7 +1356,7 @@ def test_create_variant_with_numeric_attribute_not_numeric_value_given(sku = "1"weight = 10.22product_type.variant_attributes.set([numeric_attribute])- variant_id = graphene.Node.to_global_id("Attribute", numeric_attribute.pk)+ attribute_id = graphene.Node.to_global_id("Attribute", numeric_attribute.pk)variant_value = "abd"stocks = [{@@ -1311,7 +1370,7 @@ def test_create_variant_with_numeric_attribute_not_numeric_value_given("sku": sku,"stocks": stocks,"weight": weight,- "attributes": [{"id": variant_id, "values": [variant_value]}],+ "attributes": [{"id": attribute_id, "values": [variant_value]}],"trackInventory": True,}response = staff_api_client.post_graphql(@@ -1333,7 +1392,7 @@ def test_create_product_variant_with_negative_weight(query = CREATE_VARIANT_MUTATIONproduct_id = graphene.Node.to_global_id("Product", product.pk)- variant_id = graphene.Node.to_global_id(+ attribute_id = graphene.Node.to_global_id("Attribute", product_type.variant_attributes.first().pk)variant_value = "test-value"@@ -1341,7 +1400,7 @@ def test_create_product_variant_with_negative_weight(variables = {"productId": product_id,"weight": -1,- "attributes": [{"id": variant_id, "values": [variant_value]}],+ "attributes": [{"id": attribute_id, "values": [variant_value]}],}response = staff_api_client.post_graphql(query, variables, permissions=[permission_manage_products]@@ -1353,12 +1412,17 @@ def test_create_product_variant_with_negative_weight(assert error["code"] == ProductErrorCode.INVALID.name-def test_create_product_variant_without_attributes(+def test_create_product_variant_required_without_attributes(staff_api_client, product, permission_manage_products):# givenquery = CREATE_VARIANT_MUTATIONproduct_id = graphene.Node.to_global_id("Product", product.pk)++ attribute = product.product_type.variant_attributes.first()+ attribute.value_required = True+ attribute.save(update_fields=["value_required"])+variables = {"productId": product_id,"sku": "test-sku",@@ -1380,16 +1444,20 @@ def test_create_product_variant_without_attributes(assert error["code"] == ProductErrorCode.REQUIRED.name-def test_create_product_variant_not_all_attributes(+def test_create_product_variant_missing_required_attributes(staff_api_client, product, product_type, color_attribute, permission_manage_products):query = CREATE_VARIANT_MUTATIONproduct_id = graphene.Node.to_global_id("Product", product.pk)sku = "1"- variant_id = graphene.Node.to_global_id(+ attribute_id = graphene.Node.to_global_id("Attribute", product_type.variant_attributes.first().pk)variant_value = "test-value"++ color_attribute.value_required = True+ color_attribute.save(update_fields=["value_required"])+product_type.variant_attributes.add(color_attribute, through_defaults={"variant_selection": True})@@ -1397,7 +1465,7 @@ def test_create_product_variant_not_all_attributes(variables = {"productId": product_id,"sku": sku,- "attributes": [{"id": variant_id, "values": [variant_value]}],+ "attributes": [{"id": attribute_id, "values": [variant_value]}],}response = staff_api_client.post_graphql(query, variables, permissions=[permission_manage_products]@@ -1408,7 +1476,7 @@ def test_create_product_variant_not_all_attributes("field": "attributes","code": ProductErrorCode.REQUIRED.name,"message": ANY,- "attributes": None,+ "attributes": [graphene.Node.to_global_id("Attribute", color_attribute.pk)],}assert not product.variants.filter(sku=sku).exists()@@ -1735,7 +1803,7 @@ def test_create_variant_with_empty_string_for_sku(sku = ""weight = 10.22variant_slug = product_type.variant_attributes.first().slug- variant_id = graphene.Node.to_global_id(+ attribute_id = graphene.Node.to_global_id("Attribute", product_type.variant_attributes.first().pk)variant_value = "test-value"@@ -1751,7 +1819,7 @@ def test_create_variant_with_empty_string_for_sku("sku": sku,"stocks": stocks,"weight": weight,- "attributes": [{"id": variant_id, "values": [variant_value]}],+ "attributes": [{"id": attribute_id, "values": [variant_value]}],"trackInventory": True,}response = staff_api_client.post_graphql(@@ -1790,7 +1858,7 @@ def test_create_variant_without_sku(product_id = graphene.Node.to_global_id("Product", product.pk)weight = 10.22variant_slug = product_type.variant_attributes.first().slug- variant_id = graphene.Node.to_global_id(+ attribute_id = graphene.Node.to_global_id("Attribute", product_type.variant_attributes.first().pk)variant_value = "test-value"@@ -1805,7 +1873,7 @@ def test_create_variant_without_sku("productId": product_id,"stocks": stocks,"weight": weight,- "attributes": [{"id": variant_id, "values": [variant_value]}],+ "attributes": [{"id": attribute_id, "values": [variant_value]}],"trackInventory": True,}response = staff_api_client.post_graphql(@@ -2153,7 +2221,7 @@ QUERY_UPDATE_VARIANT_ATTRIBUTES = """mutation updateVariant ($id: ID!,$sku: String,- $attributes: [AttributeValueInput!]!) {+ $attributes: [AttributeValueInput!]) {productVariantUpdate(id: $id,input: {@@ -2192,29 +2260,22 @@ QUERY_UPDATE_VARIANT_ATTRIBUTES = """"""-def test_update_product_variant_not_all_attributes(- staff_api_client, product, product_type, color_attribute, permission_manage_products+def test_update_product_variant_do_not_require_required_attributes(+ staff_api_client, product, product_type, permission_manage_products):- """Ensures updating a variant with missing attributes (all attributes must- be provided) raises an error. We expect the color attribute- to be flagged as missing."""+ """Ensures product variant can be updated without providing required attributes."""query = QUERY_UPDATE_VARIANT_ATTRIBUTESvariant = product.variants.first()variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)sku = "test sku"- attr_id = graphene.Node.to_global_id(- "Attribute", product_type.variant_attributes.first().id- )- variant_value = "test-value"- product_type.variant_attributes.add(- color_attribute, through_defaults={"variant_selection": True}- )+ attr = product_type.variant_attributes.first()+ attr.value_required = True+ attr.save(update_fields=["value_required"])variables = {"id": variant_id,"sku": sku,- "attributes": [{"id": attr_id, "values": [variant_value]}],}response = staff_api_client.post_graphql(@@ -2222,13 +2283,11 @@ def test_update_product_variant_not_all_attributes()variant.refresh_from_db()content = get_graphql_content(response)- assert len(content["data"]["productVariantUpdate"]["errors"]) == 1- assert content["data"]["productVariantUpdate"]["errors"][0] == {- "field": "attributes",- "message": "All variant selection attributes must take a value.",- "code": ProductErrorCode.REQUIRED.name,- }- assert not product.variants.filter(sku=sku).exists()+ data = content["data"]["productVariantUpdate"]+ assert not len(data["errors"])+ assert data["productVariant"]["sku"] == sku+ assert len(data["productVariant"]["attributes"]) == 1+ assert data["productVariant"]["attributes"][0]["values"]def test_update_product_variant_with_current_attribute(